From e8f91c93de3599309d8fe11fd94318bfdc51d36c Mon Sep 17 00:00:00 2001 From: Kim Motoyoshi Kalland Date: Thu, 12 Feb 2009 15:59:43 +0100 Subject: Merge branch 'gl2text' of ..\qt-main --- src/opengl/gl2paintengineex/qglshader.cpp | 16 ++- src/opengl/gl2paintengineex/qglshader_p.h | 1 + .../gl2paintengineex/qpaintengineex_opengl2.cpp | 6 ++ src/opengl/opengl.pro | 12 +-- src/opengl/qgl.cpp | 25 ++++- src/opengl/qglextensions.cpp | 21 +++- src/opengl/qglextensions_p.h | 111 ++++++++++++++++++++- src/opengl/qglframebufferobject.cpp | 8 +- src/opengl/qglpixelbuffer.cpp | 10 +- src/opengl/qglpixmapfilter.cpp | 20 ++-- src/opengl/qwindowsurface_gl.cpp | 8 +- 11 files changed, 207 insertions(+), 31 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglshader.cpp b/src/opengl/gl2paintengineex/qglshader.cpp index 634be84..4ac6e61 100644 --- a/src/opengl/gl2paintengineex/qglshader.cpp +++ b/src/opengl/gl2paintengineex/qglshader.cpp @@ -49,7 +49,11 @@ return false; \ ctx->makeCurrent(); \ - +#if !defined(QT_OPENGL_ES_2) +static const char *qglslDefines = "#define lowp\n#define mediump\n#define highp\n"; +#else +static const char *qglslDefines = ""; +#endif class QGLShaderPrivate @@ -131,9 +135,13 @@ bool QGLShader::compile() return false; const QByteArray src_ba = d->source.toAscii(); - const char* src = src_ba.constData(); + const char* src[2]; + src[0] = qglslDefines; + src[1] = src_ba.constData(); + - glShaderSource(d->shaderId, 1, &src, 0); + QGLContext *ctx = d->ctx; + glShaderSource(d->shaderId, 2, src, 0); glCompileShader(d->shaderId); @@ -160,6 +168,7 @@ QString QGLShader::log() GLint logSize; GLint logLength; + QGLContext *ctx = d->ctx; glGetShaderiv(d->shaderId, GL_INFO_LOG_LENGTH, &logSize); if (!logSize) @@ -377,6 +386,7 @@ void QGLShaderProgram::use() if (!d->valid) return; + QGLContext *ctx = d->ctx; glUseProgram(d->programId); } diff --git a/src/opengl/gl2paintengineex/qglshader_p.h b/src/opengl/gl2paintengineex/qglshader_p.h index 1625b84..4cbf3f6 100644 --- a/src/opengl/gl2paintengineex/qglshader_p.h +++ b/src/opengl/gl2paintengineex/qglshader_p.h @@ -81,6 +81,7 @@ SAMPLER_2D_SHADOW. #include +#include typedef struct { GLfloat a; diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index a74f044..2948e62 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -845,6 +845,7 @@ void QGL2PaintEngineEx::transformChanged() void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src) { Q_D(QGL2PaintEngineEx); + QGLContext *ctx = d->ctx; glActiveTexture(QT_BRUSH_TEXTURE_UNIT); d->ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, true); @@ -862,6 +863,7 @@ void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const Qt::ImageConversionFlags) { Q_D(QGL2PaintEngineEx); + QGLContext *ctx = d->ctx; glActiveTexture(QT_BRUSH_TEXTURE_UNIT); d->ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); @@ -926,6 +928,7 @@ void QGL2PaintEngineEx::drawCachedGlyphs(const QPointF &p, const QTextItemInt &t const QImage &image = cache->image(); int margin = cache->glyphMargin(); + QGLContext *ctx = d->ctx; glActiveTexture(QT_BRUSH_TEXTURE_UNIT); d->ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); @@ -1000,6 +1003,9 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) d->width = widget->width(); d->height = widget->height(); + qt_resolve_version_1_3_functions(d->ctx); + qt_resolve_glsl_extensions(d->ctx); + if (!d->shaderManager) d->shaderManager = new QGLPEXShaderManager(d->ctx); diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro index 48d7caf..af16312 100644 --- a/src/opengl/opengl.pro +++ b/src/opengl/opengl.pro @@ -34,12 +34,12 @@ SOURCES += qgl.cpp \ qglextensions.cpp \ qglpixmapfilter.cpp -!contains(QT_CONFIG, opengles2) { - HEADERS += qpaintengine_opengl_p.h - SOURCES += qpaintengine_opengl.cpp -} +#!contains(QT_CONFIG, opengles2) { +# HEADERS += qpaintengine_opengl_p.h +# SOURCES += qpaintengine_opengl.cpp +#} -contains(QT_CONFIG, opengles2) { +#contains(QT_CONFIG, opengles2) { SOURCES += gl2paintengineex/qglgradientcache.cpp \ gl2paintengineex/qglpexshadermanager.cpp \ gl2paintengineex/qglshader.cpp \ @@ -51,7 +51,7 @@ contains(QT_CONFIG, opengles2) { gl2paintengineex/qglshader_p.h \ gl2paintengineex/qgl2pexvertexarray_p.h \ gl2paintengineex/qpaintengineex_opengl2_p.h -} +#} x11 { diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 4c152e2..386e9b8 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -65,7 +65,7 @@ #include "qimage.h" #include "qgl_p.h" -#if defined(QT_OPENGL_ES_2) +#if 1 || defined(QT_OPENGL_ES_2) #include "gl2paintengineex/qpaintengineex_opengl2_p.h" #else #include @@ -2041,7 +2041,24 @@ void QGLContext::deleteTexture(QMacCompatGLuint id) // qpaintengine_opengl.cpp #if !defined(QT_OPENGL_ES_2) -extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); +//extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); +void qt_add_rect_to_array(const QRectF &r, q_vertexType *array) +{ + qreal left = r.left(); + qreal right = r.right(); + qreal top = r.top(); + qreal bottom = r.bottom(); + + array[0] = f2vt(left); + array[1] = f2vt(top); + array[2] = f2vt(right); + array[3] = f2vt(top); + array[4] = f2vt(right); + array[5] = f2vt(bottom); + array[6] = f2vt(left); + array[7] = f2vt(bottom); +} + #else void qt_add_rect_to_array(const QRectF &r, q_vertexType *array) {}; #endif @@ -4039,14 +4056,14 @@ void QGLWidget::drawTexture(const QPointF &point, QMacCompatGLuint textureId, QM } #endif -#if defined(QT_OPENGL_ES_2) +#if 1 || defined(QT_OPENGL_ES_2) Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_engine) #else Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_engine) #endif #ifdef Q_WS_QWS -Q_OPENGL_EXPORT QOpenGLPaintEngine* qt_qgl_paint_engine() +Q_OPENGL_EXPORT QPaintEngine* qt_qgl_paint_engine() { #if !defined(QT_OPENGL_ES_2) return qt_gl_engine(); diff --git a/src/opengl/qglextensions.cpp b/src/opengl/qglextensions.cpp index 8357cf9..b054fe8 100644 --- a/src/opengl/qglextensions.cpp +++ b/src/opengl/qglextensions.cpp @@ -176,10 +176,29 @@ bool qt_resolve_glsl_extensions(QGLContext *ctx) glUniform1fv = (_glUniform1fv) ctx->getProcAddress(QLatin1String("glUniform1fv")); glUniform1i = (_glUniform1i) ctx->getProcAddress(QLatin1String("glUniform1i")); + glGetActiveAttrib = (_glGetActiveAttrib) ctx->getProcAddress(QLatin1String("glGetActiveAttrib")); + glGetAttribLocation = (_glGetAttribLocation) ctx->getProcAddress(QLatin1String("glGetAttribLocation")); + glGetActiveUniform = (_glGetActiveUniform) ctx->getProcAddress(QLatin1String("glGetActiveUniform")); + glGetProgramInfoLog = (_glGetProgramInfoLog) ctx->getProcAddress(QLatin1String("glGetProgramInfoLog")); + glUniform1f = (_glUniform1f) ctx->getProcAddress(QLatin1String("glUniform1f")); + glUniform2f = (_glUniform2f) ctx->getProcAddress(QLatin1String("glUniform2f")); + glUniform4f = (_glUniform4f) ctx->getProcAddress(QLatin1String("glUniform4f")); + glUniformMatrix2fv = (_glUniformMatrix2fv) ctx->getProcAddress(QLatin1String("glUniformMatrix2fv")); + glUniformMatrix3fv = (_glUniformMatrix3fv) ctx->getProcAddress(QLatin1String("glUniformMatrix3fv")); + glUniformMatrix4fv = (_glUniformMatrix4fv) ctx->getProcAddress(QLatin1String("glUniformMatrix4fv")); + glEnableVertexAttribArray = (_glEnableVertexAttribArray) ctx->getProcAddress(QLatin1String("glEnableVertexAttribArray")); + glDisableVertexAttribArray = (_glDisableVertexAttribArray) ctx->getProcAddress(QLatin1String("glDisableVertexAttribArray")); + glVertexAttribPointer = (_glVertexAttribPointer) ctx->getProcAddress(QLatin1String("glVertexAttribPointer")); + glStencilOpSeparate = (_glStencilOpSeparate) ctx->getProcAddress(QLatin1String("glStencilOpSeparate")); + return glCreateShader && glShaderSource && glCompileShader && glDeleteProgram && glCreateProgram && glAttachShader && glDetachShader && glLinkProgram && glUseProgram && glDeleteProgram && glGetShaderInfoLog && glGetShaderiv && glGetProgramiv && glGetUniformLocation && - glUniform1i && glUniform1fv && glUniform2fv && glUniform3fv && glUniform4fv; + glUniform1i && glUniform1fv && glUniform2fv && glUniform3fv && glUniform4fv && + glGetActiveAttrib && glGetAttribLocation && glGetActiveUniform && glGetProgramInfoLog && + glUniform1f && glUniform2f && glUniform4f && + glUniformMatrix2fv && glUniformMatrix3fv && glUniformMatrix4fv && + glEnableVertexAttribArray && glDisableVertexAttribArray && glVertexAttribPointer && glStencilOpSeparate; } QT_END_NAMESPACE diff --git a/src/opengl/qglextensions_p.h b/src/opengl/qglextensions_p.h index a0517f5..fdf0bba 100644 --- a/src/opengl/qglextensions_p.h +++ b/src/opengl/qglextensions_p.h @@ -74,6 +74,10 @@ typedef ptrdiff_t GLsizeiptrARB; #endif +#ifndef GL_VERSION_2_0 +typedef char GLchar; +#endif + // ARB_pixel_buffer_object typedef void (APIENTRY *_glBindBufferARB) (GLenum, GLuint); typedef void (APIENTRY *_glDeleteBuffersARB) (GLsizei, const GLuint *); @@ -107,10 +111,10 @@ typedef void (APIENTRY *_glGetShaderiv) (GLuint, GLenum, GLint *); typedef void (APIENTRY *_glGetProgramiv) (GLuint, GLenum, GLint *); typedef GLuint (APIENTRY *_glGetUniformLocation) (GLuint, const char*); -typedef void (APIENTRY *_glUniform4fv) (GLint, GLsizei, GLfloat *); -typedef void (APIENTRY *_glUniform3fv) (GLint, GLsizei, GLfloat *); -typedef void (APIENTRY *_glUniform2fv) (GLint, GLsizei, GLfloat *); -typedef void (APIENTRY *_glUniform1fv) (GLint, GLsizei, GLfloat *); +typedef void (APIENTRY *_glUniform4fv) (GLint, GLsizei, const GLfloat *); +typedef void (APIENTRY *_glUniform3fv) (GLint, GLsizei, const GLfloat *); +typedef void (APIENTRY *_glUniform2fv) (GLint, GLsizei, const GLfloat *); +typedef void (APIENTRY *_glUniform1fv) (GLint, GLsizei, const GLfloat *); typedef void (APIENTRY *_glUniform1i) (GLint, GLint); typedef void (APIENTRY *_glActiveStencilFaceEXT) (GLenum ); @@ -118,6 +122,22 @@ typedef void (APIENTRY *_glActiveStencilFaceEXT) (GLenum ); typedef void (APIENTRY *_glMultiTexCoord4f) (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); typedef void (APIENTRY *_glActiveTexture) (GLenum); +typedef void (APIENTRY *_glGetActiveAttrib) (GLuint program, GLuint index, GLsizei maxLength, GLsizei* length, GLint* size, GLenum* type, GLchar* name); +typedef GLint (APIENTRY *_glGetAttribLocation) (GLuint program, const GLchar* name); +typedef void (APIENTRY *_glGetActiveUniform) (GLuint program, GLuint index, GLsizei maxLength, GLsizei* length, GLint* size, GLenum* type, GLchar* name); +typedef void (APIENTRY *_glGetProgramInfoLog) (GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog); +typedef void (APIENTRY *_glUniform1f) (GLint location, GLfloat v0); +typedef void (APIENTRY *_glUniform2f) (GLint location, GLfloat v0, GLfloat v1); +typedef void (APIENTRY *_glUniform4f) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); +typedef void (APIENTRY *_glUniformMatrix2fv) (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +typedef void (APIENTRY *_glUniformMatrix3fv) (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +typedef void (APIENTRY *_glUniformMatrix4fv) (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); +typedef void (APIENTRY *_glEnableVertexAttribArray) (GLuint); +typedef void (APIENTRY *_glDisableVertexAttribArray) (GLuint); +typedef void (APIENTRY *_glVertexAttribPointer) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer); +typedef void (APIENTRY *_glStencilOpSeparate) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); + + // EXT_GL_framebuffer_object typedef GLboolean (APIENTRY *_glIsRenderbufferEXT) (GLuint renderbuffer); typedef void (APIENTRY *_glBindRenderbufferEXT) (GLenum target, GLuint renderbuffer); @@ -207,6 +227,21 @@ struct QGLExtensionFuncs qt_glBufferDataARB = 0; qt_glMapBufferARB = 0; qt_glUnmapBufferARB = 0; + + qt_glGetActiveAttrib = 0; + qt_glGetAttribLocation = 0; + qt_glGetActiveUniform = 0; + qt_glGetProgramInfoLog = 0; + qt_glUniform1f = 0; + qt_glUniform2f = 0; + qt_glUniform4f = 0; + qt_glUniformMatrix2fv = 0; + qt_glUniformMatrix3fv = 0; + qt_glUniformMatrix4fv = 0; + qt_glEnableVertexAttribArray = 0; + qt_glDisableVertexAttribArray = 0; + qt_glVertexAttribPointer = 0; + qt_glStencilOpSeparate = 0; } _glProgramStringARB qt_glProgramStringARB; @@ -270,6 +305,21 @@ struct QGLExtensionFuncs _glBufferDataARB qt_glBufferDataARB; _glMapBufferARB qt_glMapBufferARB; _glUnmapBufferARB qt_glUnmapBufferARB; + + _glGetActiveAttrib qt_glGetActiveAttrib; + _glGetAttribLocation qt_glGetAttribLocation; + _glGetActiveUniform qt_glGetActiveUniform; + _glGetProgramInfoLog qt_glGetProgramInfoLog; + _glUniform1f qt_glUniform1f; + _glUniform2f qt_glUniform2f; + _glUniform4f qt_glUniform4f; + _glUniformMatrix2fv qt_glUniformMatrix2fv; + _glUniformMatrix3fv qt_glUniformMatrix3fv; + _glUniformMatrix4fv qt_glUniformMatrix4fv; + _glEnableVertexAttribArray qt_glEnableVertexAttribArray; + _glDisableVertexAttribArray qt_glDisableVertexAttribArray; + _glVertexAttribPointer qt_glVertexAttribPointer; + _glStencilOpSeparate qt_glStencilOpSeparate; }; @@ -416,6 +466,40 @@ struct QGLExtensionFuncs #define GL_UNPACK_IMAGE_HEIGHT 0x806E #endif +#ifndef GL_VERSION_1_4 +#define GL_INCR_WRAP 0x8507 +#define GL_DECR_WRAP 0x8508 +#endif + +#ifndef GL_VERSION_2_0 +#define GL_FRAGMENT_SHADER 0x8B30 +#define GL_VERTEX_SHADER 0x8B31 +#define GL_FLOAT_VEC2 0x8B50 +#define GL_FLOAT_VEC3 0x8B51 +#define GL_FLOAT_VEC4 0x8B52 +#define GL_INT_VEC2 0x8B53 +#define GL_INT_VEC3 0x8B54 +#define GL_INT_VEC4 0x8B55 +#define GL_BOOL 0x8B56 +#define GL_BOOL_VEC2 0x8B57 +#define GL_BOOL_VEC3 0x8B58 +#define GL_BOOL_VEC4 0x8B59 +#define GL_FLOAT_MAT2 0x8B5A +#define GL_FLOAT_MAT3 0x8B5B +#define GL_FLOAT_MAT4 0x8B5C +#define GL_SAMPLER_1D 0x8B5D +#define GL_SAMPLER_2D 0x8B5E +#define GL_SAMPLER_3D 0x8B5F +#define GL_SAMPLER_CUBE 0x8B60 +#define GL_COMPILE_STATUS 0x8B81 +#define GL_LINK_STATUS 0x8B82 +#define GL_INFO_LOG_LENGTH 0x8B84 +#define GL_ACTIVE_UNIFORMS 0x8B86 +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#endif + #define glProgramStringARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glProgramStringARB #define glBindProgramARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindProgramARB #define glDeleteProgramsARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteProgramsARB @@ -502,6 +586,25 @@ struct QGLExtensionFuncs #define glUniform1fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform1fv #define glUniform1i QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform1i +#define glGetActiveAttrib QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetActiveAttrib +#define glGetAttribLocation QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetAttribLocation +#define glGetActiveUniform QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetActiveUniform +#define glGetProgramInfoLog QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetProgramInfoLog +#define glUniform1f QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform1f +#define glUniform2f QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform2f +#define glUniform4f QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform4f +#define glUniformMatrix2fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix2fv +#define glUniformMatrix3fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix3fv +#define glUniformMatrix4fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix4fv +#define glEnableVertexAttribArray QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glEnableVertexAttribArray +#define glDisableVertexAttribArray QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDisableVertexAttribArray +#define glVertexAttribPointer QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glVertexAttribPointer +#define glStencilOpSeparate QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glStencilOpSeparate + +#if !defined(QT_OPENGL_ES_2) +#define glClearDepthf(x) glClearDepth(GLdouble(x)) +#endif + extern bool qt_resolve_framebufferobject_extensions(QGLContext *ctx); bool qt_resolve_buffer_extensions(QGLContext *ctx); diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 8524dfa..9134fc6 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -43,7 +43,11 @@ #include #include +#if 1 || defined(QT_OPENGL_ES_2) +#include +#else #include +#endif #include #include #include @@ -573,7 +577,9 @@ QImage QGLFramebufferObject::toImage() const return image; } -#if !defined(QT_OPENGL_ES_2) +#if 1 || defined(QT_OPENGL_ES_2) +Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_paintengine) +#else Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_paintengine) #endif diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp index 5f74f26..6a207c8 100644 --- a/src/opengl/qglpixelbuffer.cpp +++ b/src/opengl/qglpixelbuffer.cpp @@ -81,13 +81,15 @@ #include #include -#if !defined(QT_OPENGL_ES_2) +#if 1 || defined(QT_OPENGL_ES_2) +#include +#else #include #endif QT_BEGIN_NAMESPACE -#if !defined(QT_OPENGL_ES_2) +#if 0 && !defined(QT_OPENGL_ES_2) extern void qgl_cleanup_glyph_cache(QGLContext *); #else void qgl_cleanup_glyph_cache(QGLContext *) {} @@ -363,7 +365,9 @@ bool QGLPixelBuffer::isValid() const return !d->invalid; } -#if !defined(QT_OPENGL_ES_2) +#if 1 || defined(QT_OPENGL_ES_2) +Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_paintengine) +#else Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_paintengine) #endif diff --git a/src/opengl/qglpixmapfilter.cpp b/src/opengl/qglpixmapfilter.cpp index ff23948..8a64515 100644 --- a/src/opengl/qglpixmapfilter.cpp +++ b/src/opengl/qglpixmapfilter.cpp @@ -138,13 +138,6 @@ void QGLSLProgram::disable() glUseProgram(0); } -typedef GLuint (APIENTRY *_glGetUniformLocation) (GLuint, const char*); -typedef void (APIENTRY *_glUniform4fv) (GLint, GLsizei, GLfloat *); -typedef void (APIENTRY *_glUniform3fv) (GLint, GLsizei, GLfloat *); -typedef void (APIENTRY *_glUniform2fv) (GLint, GLsizei, GLfloat *); -typedef void (APIENTRY *_glUniform1fv) (GLint, GLsizei, GLfloat *); -typedef void (APIENTRY *_glUniform1i) (GLint, GLint); - int QGLSLProgram::getUniformLocation(const QString &name) { return glGetUniformLocation(m_program, name.toAscii().constData()); @@ -244,7 +237,18 @@ QPixmapFilter *QGLContextPrivate::createPixmapFilter(int type) const #if !defined(QT_OPENGL_ES_2) extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); -extern void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array); +//extern void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array); +void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array) +{ + array[0] = f2vt(x1); + array[1] = f2vt(y1); + array[2] = f2vt(x2); + array[3] = f2vt(y1); + array[4] = f2vt(x2); + array[5] = f2vt(y2); + array[6] = f2vt(x1); + array[7] = f2vt(y2); +} #endif static void qgl_drawTexture(const QRectF &rect, int tx_width, int tx_height, const QRectF & src) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 3dd3064..bb4ffc5 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -69,7 +69,11 @@ #include #include +#if 1 || defined(QT_OPENGL_ES_2) +#include +#else #include +#endif #ifndef GLX_ARB_multisample #define GLX_SAMPLE_BUFFERS_ARB 100000 @@ -283,7 +287,9 @@ void QGLWindowSurface::hijackWindow(QWidget *widget) qDebug() << "hijackWindow() context created for" << widget << d_ptr->contexts.size(); } -#if !defined(QT_OPENGL_ES_2) +#if 1 || defined(QT_OPENGL_ES_2) +Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_window_surface_paintengine) +#else Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_window_surface_paintengine) #endif -- cgit v0.12 From afdd536c50ba14ece1db63f5efab0328730f2e26 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 17 Feb 2009 14:10:06 +0100 Subject: Fixes: Move QGLDrawable into qgl_p.h so that we can use it in the GL 2 paint engine. RevBy: Tom Details: Now we can use the GL 2 paint engine on non-widget paint devices like pixel buffers, framebuffer objects, and GL window surfaces. Using -graphicssystem opengl works now. --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 19 +-- src/opengl/qgl.cpp | 150 ++++++++++++++++++ src/opengl/qgl_p.h | 33 ++++ src/opengl/qpaintengine_opengl.cpp | 176 --------------------- 4 files changed, 193 insertions(+), 185 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 2948e62..1cc2233 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -133,10 +133,9 @@ public: inline QColor premultiplyColor(QColor c, GLfloat opacity); QGL2PaintEngineEx* q; - - //### Move into QGLDrawable + QGLDrawable drawable; + QGLContext *ctx; int width, height; - QGLContext* ctx; // Dirty flags bool matrixDirty; // Implies matrix uniforms are also dirty @@ -997,11 +996,12 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) // qDebug("QGL2PaintEngineEx::begin()"); - QGLWidget* widget = static_cast(pdev); - d->ctx = const_cast(widget->context()); - d->ctx->makeCurrent(); - d->width = widget->width(); - d->height = widget->height(); + d->drawable.setDevice(pdev); + d->drawable.makeCurrent(); + d->ctx = d->drawable.context(); + QSize sz = d->drawable.size(); + d->width = sz.width(); + d->height = sz.height(); qt_resolve_version_1_3_functions(d->ctx); qt_resolve_glsl_extensions(d->ctx); @@ -1033,7 +1033,8 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) bool QGL2PaintEngineEx::end() { Q_D(QGL2PaintEngineEx); - d->ctx->swapBuffers(); + d->drawable.swapBuffers(); + d->drawable.doneCurrent(); return false; } diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 386e9b8..7c42039 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -71,9 +71,14 @@ #include #endif +#include +#include + #include #include #include +#include +#include #include "qcolormap.h" #include "qcache.h" #include "qfile.h" @@ -4219,4 +4224,149 @@ Q_OPENGL_EXPORT const QString qt_gl_library_name() } #endif +void QGLDrawable::setDevice(QPaintDevice *pdev) +{ + wasBound = false; + widget = 0; + buffer = 0; + fbo = 0; +#ifdef Q_WS_QWS + wsurf = 0; +#endif + if (pdev->devType() == QInternal::Widget) + widget = static_cast(pdev); + else if (pdev->devType() == QInternal::Pbuffer) + buffer = static_cast(pdev); + else if (pdev->devType() == QInternal::FramebufferObject) + fbo = static_cast(pdev); + else if (pdev->devType() == QInternal::UnknownDevice) +#ifdef Q_WS_QWS + wsurf = static_cast(pdev)->windowSurface(); +#else + wsurf = static_cast(pdev); +#endif +} + +void QGLDrawable::swapBuffers() +{ + if (widget) { + if (widget->autoBufferSwap()) + widget->swapBuffers(); + } else { + glFlush(); + } +} + +void QGLDrawable::makeCurrent() +{ + if (widget) + widget->makeCurrent(); + else if (buffer) + buffer->makeCurrent(); + else if (wsurf) + wsurf->context()->makeCurrent(); + else if (fbo) { + wasBound = fbo->isBound(); + if (!wasBound) + fbo->bind(); + } +} + +void QGLDrawable::doneCurrent() +{ + if (fbo && !wasBound) + fbo->release(); +} + +QSize QGLDrawable::size() const +{ + if (widget) { + return QSize(widget->d_func()->glcx->device()->width(), + widget->d_func()->glcx->device()->height()); + } else if (buffer) { + return buffer->size(); + } else if (fbo) { + return fbo->size(); + } else if (wsurf) { +#ifdef Q_WS_QWS + return wsurf->window()->frameSize(); +#else + return QSize(wsurf->width(), wsurf->height()); +#endif + } + return QSize(); +} + +QGLFormat QGLDrawable::format() const +{ + if (widget) + return widget->format(); + else if (buffer) + return buffer->format(); + else if (wsurf) + return wsurf->context()->format(); + else if (fbo && QGLContext::currentContext()) { + QGLFormat fmt = QGLContext::currentContext()->format(); + fmt.setStencil(fbo->attachment() == QGLFramebufferObject::CombinedDepthStencil); + fmt.setDepth(fbo->attachment() != QGLFramebufferObject::NoAttachment); + return fmt; + } + + return QGLFormat(); +} + +GLuint QGLDrawable::bindTexture(const QImage &image, GLenum target, GLint format) +{ + if (widget) + return widget->d_func()->glcx->d_func()->bindTexture(image, target, format, true); + else if (buffer) + return buffer->d_func()->qctx->d_func()->bindTexture(image, target, format, true); + else if (fbo && QGLContext::currentContext()) + return const_cast(QGLContext::currentContext())->d_func()->bindTexture(image, target, format, true); + else if (wsurf) + return wsurf->context()->d_func()->bindTexture(image, target, format, true); + return 0; +} + +GLuint QGLDrawable::bindTexture(const QPixmap &pixmap, GLenum target, GLint format) +{ + if (widget) + return widget->d_func()->glcx->d_func()->bindTexture(pixmap, target, format, true); + else if (buffer) + return buffer->d_func()->qctx->d_func()->bindTexture(pixmap, target, format, true); + else if (fbo && QGLContext::currentContext()) + return const_cast(QGLContext::currentContext())->d_func()->bindTexture(pixmap, target, format, true); + else if (wsurf) + return wsurf->context()->d_func()->bindTexture(pixmap, target, format, true); + return 0; +} + +QColor QGLDrawable::backgroundColor() const +{ + if (widget) + return widget->palette().brush(widget->backgroundRole()).color(); + return QApplication::palette().brush(QPalette::Background).color(); +} + +QGLContext *QGLDrawable::context() const +{ + if (widget) + return widget->d_func()->glcx; + else if (buffer) + return buffer->d_func()->qctx; + else if (fbo) + return const_cast(QGLContext::currentContext()); + else if (wsurf) + return wsurf->context(); + return 0; +} + +bool QGLDrawable::autoFillBackground() const +{ + if (widget) + return widget->autoFillBackground(); + else + return false; +} + QT_END_NAMESPACE diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index b15eebc..2eccc23 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -282,6 +282,39 @@ Q_SIGNALS: void aboutToDestroyContext(const QGLContext *context); }; +class QGLPixelBuffer; +class QGLFramebufferObject; +class QWSGLWindowSurface; +class QGLWindowSurface; +class QGLDrawable { +public: + QGLDrawable() : widget(0), buffer(0), fbo(0) + , wsurf(0) + {} + void setDevice(QPaintDevice *pdev); + void swapBuffers(); + void makeCurrent(); + void doneCurrent(); + QSize size() const; + QGLFormat format() const; + GLuint bindTexture(const QImage &image, GLenum target = GL_TEXTURE_2D, GLint format = GL_RGBA); + GLuint bindTexture(const QPixmap &pixmap, GLenum target = GL_TEXTURE_2D, GLint format = GL_RGBA); + QColor backgroundColor() const; + QGLContext *context() const; + bool autoFillBackground() const; + +private: + bool wasBound; + QGLWidget *widget; + QGLPixelBuffer *buffer; + QGLFramebufferObject *fbo; +#ifdef Q_WS_QWS + QWSGLWindowSurface *wsurf; +#else + QGLWindowSurface *wsurf; +#endif +}; + // GL extension definitions class QGLExtensions { public: diff --git a/src/opengl/qpaintengine_opengl.cpp b/src/opengl/qpaintengine_opengl.cpp index 976a021..998492c 100644 --- a/src/opengl/qpaintengine_opengl.cpp +++ b/src/opengl/qpaintengine_opengl.cpp @@ -57,13 +57,11 @@ #include "qpen.h" #include "qvarlengtharray.h" #include -#include #include #include #include #include "private/qtessellator_p.h" -#include "private/qwindowsurface_gl_p.h" #include "util/fragmentprograms_p.h" @@ -190,180 +188,6 @@ const QGLTrapezoid QGLTrapezoid::translated(const QPointF &delta) const return trap; } -class QGLDrawable { -public: - QGLDrawable() : widget(0), buffer(0), fbo(0) - , wsurf(0) - {} - inline void setDevice(QPaintDevice *pdev); - inline void swapBuffers(); - inline void makeCurrent(); - inline void doneCurrent(); - inline QSize size() const; - inline QGLFormat format() const; - inline GLuint bindTexture(const QImage &image, GLenum target = GL_TEXTURE_2D, GLint format = GL_RGBA); - inline GLuint bindTexture(const QPixmap &pixmap, GLenum target = GL_TEXTURE_2D, GLint format = GL_RGBA); - inline QColor backgroundColor() const; - inline QGLContext *context() const; - inline bool autoFillBackground() const; - -private: - bool wasBound; - QGLWidget *widget; - QGLPixelBuffer *buffer; - QGLFramebufferObject *fbo; -#ifdef Q_WS_QWS - QWSGLWindowSurface *wsurf; -#else - QGLWindowSurface *wsurf; -#endif -}; - -void QGLDrawable::setDevice(QPaintDevice *pdev) -{ - wasBound = false; - widget = 0; - buffer = 0; - fbo = 0; -#ifdef Q_WS_QWS - wsurf = 0; -#endif - if (pdev->devType() == QInternal::Widget) - widget = static_cast(pdev); - else if (pdev->devType() == QInternal::Pbuffer) - buffer = static_cast(pdev); - else if (pdev->devType() == QInternal::FramebufferObject) - fbo = static_cast(pdev); - else if (pdev->devType() == QInternal::UnknownDevice) -#ifdef Q_WS_QWS - wsurf = static_cast(pdev)->windowSurface(); -#else - wsurf = static_cast(pdev); -#endif -} - -inline void QGLDrawable::swapBuffers() -{ - if (widget) { - if (widget->autoBufferSwap()) - widget->swapBuffers(); - } else { - glFlush(); - } -} - -inline void QGLDrawable::makeCurrent() -{ - if (widget) - widget->makeCurrent(); - else if (buffer) - buffer->makeCurrent(); - else if (wsurf) - wsurf->context()->makeCurrent(); - else if (fbo) { - wasBound = fbo->isBound(); - if (!wasBound) - fbo->bind(); - } -} - -inline void QGLDrawable::doneCurrent() -{ - if (fbo && !wasBound) - fbo->release(); -} - -inline QSize QGLDrawable::size() const -{ - if (widget) { - return QSize(widget->d_func()->glcx->device()->width(), - widget->d_func()->glcx->device()->height()); - } else if (buffer) { - return buffer->size(); - } else if (fbo) { - return fbo->size(); - } else if (wsurf) { -#ifdef Q_WS_QWS - return wsurf->window()->frameSize(); -#else - return QSize(wsurf->width(), wsurf->height()); -#endif - } - return QSize(); -} - -inline QGLFormat QGLDrawable::format() const -{ - if (widget) - return widget->format(); - else if (buffer) - return buffer->format(); - else if (wsurf) - return wsurf->context()->format(); - else if (fbo && QGLContext::currentContext()) { - QGLFormat fmt = QGLContext::currentContext()->format(); - fmt.setStencil(fbo->attachment() == QGLFramebufferObject::CombinedDepthStencil); - fmt.setDepth(fbo->attachment() != QGLFramebufferObject::NoAttachment); - return fmt; - } - - return QGLFormat(); -} - -inline GLuint QGLDrawable::bindTexture(const QImage &image, GLenum target, GLint format) -{ - if (widget) - return widget->d_func()->glcx->d_func()->bindTexture(image, target, format, true); - else if (buffer) - return buffer->d_func()->qctx->d_func()->bindTexture(image, target, format, true); - else if (fbo && QGLContext::currentContext()) - return const_cast(QGLContext::currentContext())->d_func()->bindTexture(image, target, format, true); - else if (wsurf) - return wsurf->context()->d_func()->bindTexture(image, target, format, true); - return 0; -} - -inline GLuint QGLDrawable::bindTexture(const QPixmap &pixmap, GLenum target, GLint format) -{ - if (widget) - return widget->d_func()->glcx->d_func()->bindTexture(pixmap, target, format, true); - else if (buffer) - return buffer->d_func()->qctx->d_func()->bindTexture(pixmap, target, format, true); - else if (fbo && QGLContext::currentContext()) - return const_cast(QGLContext::currentContext())->d_func()->bindTexture(pixmap, target, format, true); - else if (wsurf) - return wsurf->context()->d_func()->bindTexture(pixmap, target, format, true); - return 0; -} - -inline QColor QGLDrawable::backgroundColor() const -{ - if (widget) - return widget->palette().brush(widget->backgroundRole()).color(); - return QApplication::palette().brush(QPalette::Background).color(); -} - -inline QGLContext *QGLDrawable::context() const -{ - if (widget) - return widget->d_func()->glcx; - else if (buffer) - return buffer->d_func()->qctx; - else if (fbo) - return const_cast(QGLContext::currentContext()); - else if (wsurf) - return wsurf->context(); - return 0; -} - -inline bool QGLDrawable::autoFillBackground() const -{ - if (widget) - return widget->autoFillBackground(); - else - return false; -} - class QOpenGLImmediateModeTessellator; class QGLMaskGenerator; -- cgit v0.12 From 842d514edd0ef6fa8d6e863dfe6ba696b95ba790 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 17 Feb 2009 15:43:05 +0100 Subject: Get rid of warning introduced in the last commit. --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 1cc2233..e211f10 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -134,8 +134,8 @@ public: QGL2PaintEngineEx* q; QGLDrawable drawable; - QGLContext *ctx; int width, height; + QGLContext *ctx; // Dirty flags bool matrixDirty; // Implies matrix uniforms are also dirty -- cgit v0.12 From a49ec03834b14063b4130c410d59df6e8c4db8ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 17 Feb 2009 16:11:41 +0100 Subject: Fixes: Improve text rendering in GL 2 paint engine. Details: Avoid adding 0.5 to dx() / dy() which caused images / glyphs to get slight antialiasing and edge artifacts. --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index e211f10..0e41602 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -399,8 +399,8 @@ void QGL2PaintEngineExPrivate::updateMatrix() // Use the (3x3) transform for the Model~View matrix: const QTransform& transform = q->state()->matrix; GLfloat MV[4][4] = { - {transform.m11(), transform.m21(), 0.0, transform.dx() + 0.5}, - {transform.m12(), transform.m22(), 0.0, transform.dy() + 0.5}, + {transform.m11(), transform.m21(), 0.0, transform.dx()}, + {transform.m12(), transform.m22(), 0.0, transform.dy()}, {0.0, 0.0, 1.0, 0.0}, {transform.m13(), transform.m23(), 0.0, transform.m33()} }; -- cgit v0.12 From 6513e4b9513dfc591c53744517f05aa3c522ace3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 18 Feb 2009 09:42:04 +0100 Subject: Fixes: GL 2 paint engine text rendering optimization. RevBy: Tom Details: Buffer vertex and texture coordinates so that we get away with just a single glDrawArrays call per text item. Also move drawCachedGlyphs() into the private class. --- src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp | 6 ++ src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h | 1 + .../gl2paintengineex/qpaintengineex_opengl2.cpp | 101 +++++++++------------ .../gl2paintengineex/qpaintengineex_opengl2_p.h | 1 - 4 files changed, 52 insertions(+), 57 deletions(-) diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp b/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp index 0352d39..f237847 100644 --- a/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp +++ b/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp @@ -59,6 +59,12 @@ QGLRect QGL2PEXVertexArray::boundingRect() const return QGLRect(minX, minY, maxX, maxY); } +void QGL2PEXVertexArray::addRect(const QRectF &rect) +{ + vertexArray << rect.topLeft() << rect.topRight() << rect.bottomRight() + << rect.bottomRight() << rect.bottomLeft() << rect.topLeft(); +} + void QGL2PEXVertexArray::addPath(const QVectorPath &path, GLfloat curveInverseScale) { const QPointF* const points = reinterpret_cast(path.points()); diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h index c205022..65f6d42 100644 --- a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h +++ b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h @@ -98,6 +98,7 @@ public: maxX(-2e10), maxY(-2e10), minX(2e10), minY(2e10), boundingRectDirty(true) {} + void addRect(const QRectF &rect); void addPath(const QVectorPath &path, GLfloat curveInverseScale); void clear(); diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 0e41602..ea0d7b1 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -115,6 +115,7 @@ public: void setBrush(const QBrush* brush); void drawTexture(const QGLRect& dest, const QGLRect& src, int txtWidth, int txtHeight); + void drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti); void fill(const QVectorPath &path); void drawOutline(const QVectorPath& path); @@ -152,7 +153,8 @@ public: GLfloat inverseScale; - QGL2PEXVertexArray pathVertexArray; + QGL2PEXVertexArray vertexCoordinateArray; + QGL2PEXVertexArray textureCoordinateArray; GLfloat pmvMatrix[4][4]; @@ -548,17 +550,17 @@ void QGL2PaintEngineExPrivate::drawOutline(const QVectorPath& path) if (matrixDirty) updateMatrix(); - pathVertexArray.clear(); - pathVertexArray.addPath(path, inverseScale); + vertexCoordinateArray.clear(); + vertexCoordinateArray.addPath(path, inverseScale); if (path.hasImplicitClose()) { // Close the path's outline - pathVertexArray.lineToArray(path.points()[0], path.points()[1]); - pathVertexArray.stops().last() += 1; + vertexCoordinateArray.lineToArray(path.points()[0], path.points()[1]); + vertexCoordinateArray.stops().last() += 1; } prepareForDraw(); - drawVertexArrays(pathVertexArray, GL_LINE_STRIP); + drawVertexArrays(vertexCoordinateArray, GL_LINE_STRIP); } @@ -578,26 +580,26 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) composite(rect); } else if (path.shape() == QVectorPath::EllipseHint) { - pathVertexArray.clear(); - pathVertexArray.addPath(path, inverseScale); + vertexCoordinateArray.clear(); + vertexCoordinateArray.addPath(path, inverseScale); prepareForDraw(); - drawVertexArrays(pathVertexArray, GL_TRIANGLE_FAN); + drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN); } else { // The path is too complicated & needs the stencil technique - pathVertexArray.clear(); - pathVertexArray.addPath(path, inverseScale); + vertexCoordinateArray.clear(); + vertexCoordinateArray.addPath(path, inverseScale); - fillStencilWithVertexArray(pathVertexArray, path.hasWindingFill()); + fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill()); // Stencil the brush onto the dest buffer glStencilFunc(GL_NOTEQUAL, 0, 0xFFFF); // Pass if stencil buff value != 0 glEnable(GL_STENCIL_TEST); prepareForDraw(); - composite(pathVertexArray.boundingRect()); + composite(vertexCoordinateArray.boundingRect()); glDisable(GL_STENCIL_TEST); - cleanStencilBuffer(pathVertexArray.boundingRect()); + cleanStencilBuffer(vertexCoordinateArray.boundingRect()); } } @@ -876,6 +878,7 @@ void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem) { + Q_D(QGL2PaintEngineEx); QOpenGLPaintEngineState *s = state(); const QTextItemInt &ti = static_cast(textItem); @@ -893,17 +896,17 @@ void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem drawCached = false; if (drawCached) { - drawCachedGlyphs(p, ti); + d->drawCachedGlyphs(p, ti); return; } QPaintEngineEx::drawTextItem(p, ti); } -void QGL2PaintEngineEx::drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti) +void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti) { - Q_D(QGL2PaintEngineEx); - QOpenGLPaintEngineState *s = state(); + Q_Q(QGL2PaintEngineEx); + QOpenGLPaintEngineState *s = q->state(); QVarLengthArray positions; QVarLengthArray glyphs; @@ -927,65 +930,51 @@ void QGL2PaintEngineEx::drawCachedGlyphs(const QPointF &p, const QTextItemInt &t const QImage &image = cache->image(); int margin = cache->glyphMargin(); - QGLContext *ctx = d->ctx; glActiveTexture(QT_BRUSH_TEXTURE_UNIT); - d->ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); + ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); glEnable(GL_BLEND); - d->shaderManager->textShader()->use(); - d->updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); + shaderManager->textShader()->use(); + updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); - if (d->compositionModeDirty) - d->updateCompositionMode(); + if (compositionModeDirty) + updateCompositionMode(); - if (d->matrixDirty) - d->updateMatrix(); + if (matrixDirty) + updateMatrix(); - if (d->textShaderMatrixUniformDirty) { - d->shaderManager->textShader()->uniforms()[QLatin1String("pmvMatrix")] = d->pmvMatrix; - d->textShaderMatrixUniformDirty = false; + if (textShaderMatrixUniformDirty) { + shaderManager->textShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; + textShaderMatrixUniformDirty = false; } - d->shaderManager->textShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; - QColor col = d->premultiplyColor(state()->pen.color(), (GLfloat)state()->opacity); - d->shaderManager->textShader()->uniforms()[QLatin1String("fragmentColor")] = col; + shaderManager->textShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; + QColor col = premultiplyColor(s->pen.color(), (GLfloat)s->opacity); + shaderManager->textShader()->uniforms()[QLatin1String("fragmentColor")] = col; GLfloat dx = 1.0 / image.width(); GLfloat dy = 1.0 / image.height(); - glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); - glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); + vertexCoordinateArray.clear(); + textureCoordinateArray.clear(); + for (int i=0; icoords.value(glyphs[i]); int x = positions[i].x.toInt() + c.baseLineX - margin; int y = positions[i].y.toInt() - c.baseLineY - margin; - QGLRect dest = QRectF(x, y, c.w, c.h); - QGLRect src = QRectF(c.x, c.y, c.w, c.h); - - GLfloat vertexCoords[] = { - dest.left, dest.top, - dest.left, dest.bottom, - dest.right, dest.bottom, - dest.right, dest.top - }; - - glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoords); - - QGLRect srcTextureRect(src.left*dx, 1.0 - src.top*dy, src.right*dx, 1.0 - src.bottom*dy); + vertexCoordinateArray.addRect(QRectF(x, y, c.w, c.h)); + textureCoordinateArray.addRect(QRectF(c.x*dx, 1 - c.y*dy, c.w * dx, -c.h * dy)); + } - GLfloat textureCoords[] = { - srcTextureRect.left, srcTextureRect.top, - srcTextureRect.left, srcTextureRect.bottom, - srcTextureRect.right, srcTextureRect.bottom, - srcTextureRect.right, srcTextureRect.top - }; + glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); + glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); - glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoords); + glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray.data()); + glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray.data()); + glDrawArrays(GL_TRIANGLES, 0, 6 * glyphs.size()); - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - } glDisableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); glDisableVertexAttribArray(QT_VERTEX_COORDS_ATTR); } diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index ce66e4b..9f84a25 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -100,7 +100,6 @@ public: virtual void drawImage(const QRectF &r, const QImage &pm, const QRectF &sr, Qt::ImageConversionFlags flags = Qt::AutoColor); virtual void drawTextItem(const QPointF &p, const QTextItem &textItem); - void drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti); Type type() const { return OpenGL; } -- cgit v0.12 From d903f379470fb9f9159fbf37f2cfc02638cd05f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 18 Feb 2009 14:54:51 +0100 Subject: Fixes: Enable use of the GL pixmap backend in the GL 2 paint engine. --- src/opengl/qgl.cpp | 10 +++++----- src/opengl/qgl_p.h | 4 ++++ src/opengl/qpixmapdata_gl.cpp | 13 ++++++++++--- src/opengl/qpixmapdata_gl_p.h | 1 + 4 files changed, 20 insertions(+), 8 deletions(-) diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 7c42039..558897d 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -1888,14 +1888,14 @@ GLuint QGLContextPrivate::bindTexture(const QImage &image, GLenum target, GLint /*! \internal */ GLuint QGLContextPrivate::bindTexture(const QPixmap &pixmap, GLenum target, GLint format, bool clean) { -#if !defined(QT_OPENGL_ES_2) - if (target == qt_gl_preferredTextureTarget() && pixmap.pixmapData()->classId() == QPixmapData::OpenGLClass) { - const QGLPixmapData *data = static_cast(pixmap.pixmapData()); + Q_Q(QGLContext); + QPixmapData *pd = pixmap.pixmapData(); + if (target == qt_gl_preferredTextureTarget() && pd->classId() == QPixmapData::OpenGLClass) { + const QGLPixmapData *data = static_cast(pd); - if (data->isValidContext(QGLContext::currentContext())) + if (data->isValidContext(q)) return data->bind(); } -#endif const qint64 key = pixmap.cacheKey(); GLuint id; diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index 2eccc23..76f3812 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -418,9 +418,13 @@ inline GLenum qt_gl_preferredTextureFormat() inline GLenum qt_gl_preferredTextureTarget() { +#if 1 || defined(QT_OPENGL_ES_2) + return GL_TEXTURE_2D; +#else return (QGLExtensions::glExtensions & QGLExtensions::TextureRectangle) ? GL_TEXTURE_RECTANGLE_NV : GL_TEXTURE_2D; +#endif } diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index b079557..ec71fa6 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -57,12 +57,14 @@ class QGLShareContextScope public: QGLShareContextScope(const QGLContext *ctx) : m_oldContext(0) - , m_ctx(const_cast(ctx)) { - const QGLContext *currentContext = QGLContext::currentContext(); + QGLContext *currentContext = const_cast(QGLContext::currentContext()); if (currentContext != ctx && !qgl_share_reg()->checkSharing(ctx, currentContext)) { - m_oldContext = const_cast(currentContext); + m_oldContext = currentContext; + m_ctx = const_cast(ctx); m_ctx->makeCurrent(); + } else { + m_ctx = currentContext; } } @@ -127,6 +129,7 @@ QGLPixmapData::QGLPixmapData(PixelType type) : QPixmapData(type, OpenGLClass) , m_width(0) , m_height(0) + , m_ctx(0) , m_texture(0) , m_dirty(false) { @@ -148,6 +151,9 @@ bool QGLPixmapData::isValid() const bool QGLPixmapData::isValidContext(const QGLContext *ctx) const { + if (ctx == m_ctx) + return true; + const QGLContext *share_ctx = qt_gl_share_widget()->context(); return ctx == share_ctx || qgl_share_reg()->checkSharing(ctx, share_ctx); } @@ -173,6 +179,7 @@ void QGLPixmapData::ensureCreated() const m_dirty = false; QGLShareContextScope ctx(qt_gl_share_widget()->context()); + m_ctx = ctx; const GLenum format = qt_gl_preferredTextureFormat(); const GLenum target = qt_gl_preferredTextureTarget(); diff --git a/src/opengl/qpixmapdata_gl_p.h b/src/opengl/qpixmapdata_gl_p.h index e450f01..97f4959 100644 --- a/src/opengl/qpixmapdata_gl_p.h +++ b/src/opengl/qpixmapdata_gl_p.h @@ -97,6 +97,7 @@ private: int m_width; int m_height; + mutable QGLContext *m_ctx; mutable GLuint m_texture; mutable bool m_dirty; mutable QImage m_source; -- cgit v0.12 From a3c964db2bee664b0e71e9ec1c5d8b2830659ff9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 18 Feb 2009 14:56:16 +0100 Subject: Fixes: Introduce mode transfer functions in the GL 2 paint engine. RevBy: Tom Details: Mode transfer lets us optimize the case where the same operation is done a lot of times in a row, for example image or text drawing, by being able to assume that most of the state has already been set up properly. --- src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h | 4 +- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 143 +++++++++++++-------- 2 files changed, 94 insertions(+), 53 deletions(-) diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h index 65f6d42..a83f13e 100644 --- a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h +++ b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h @@ -62,7 +62,7 @@ public: QGLPoint(GLfloat new_x, GLfloat new_y) : x(new_x), y(new_y) {}; - QGLPoint(QPointF p) : + QGLPoint(const QPointF &p) : x(p.x()), y(p.y()) {}; QGLPoint(const QPointF* p) : @@ -77,7 +77,7 @@ public: struct QGLRect { - QGLRect(QRectF r) + QGLRect(const QRectF &r) : left(r.left()), top(r.top()), right(r.right()), bottom(r.bottom()) {} QGLRect(GLfloat l, GLfloat t, GLfloat r, GLfloat b) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index ea0d7b1..88c33d4 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -86,6 +86,11 @@ extern QImage qt_imageForBrush(int brushStyle, bool invert); //in qbrush.cpp #include +enum EngineMode { + ImageDrawingMode, + TextDrawingMode, + DefaultMode +}; static const GLuint QT_VERTEX_COORDS_ATTR = 0; static const GLuint QT_TEXTURE_COORDS_ATTR = 1; @@ -114,7 +119,9 @@ public: void setBrush(const QBrush* brush); - void drawTexture(const QGLRect& dest, const QGLRect& src, int txtWidth, int txtHeight); + void transferMode(EngineMode newMode); + + void drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize); void drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti); void fill(const QVectorPath &path); @@ -138,6 +145,8 @@ public: int width, height; QGLContext *ctx; + EngineMode mode; + // Dirty flags bool matrixDirty; // Implies matrix uniforms are also dirty bool compositionModeDirty; @@ -156,6 +165,9 @@ public: QGL2PEXVertexArray vertexCoordinateArray; QGL2PEXVertexArray textureCoordinateArray; + GLfloat staticVertexCoordinateArray[8]; + GLfloat staticTextureCoordinateArray[8]; + GLfloat pmvMatrix[4][4]; QGLPEXShaderManager* shaderManager; @@ -486,14 +498,21 @@ void QGL2PaintEngineExPrivate::updateCompositionMode() compositionModeDirty = false; } +static inline void setCoords(GLfloat *coords, const QGLRect &rect) +{ + coords[0] = rect.left; + coords[1] = rect.top; + coords[2] = rect.right; + coords[3] = rect.top; + coords[4] = rect.right; + coords[5] = rect.bottom; + coords[6] = rect.left; + coords[7] = rect.bottom; +} -void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, int txtWidth, int txtHeight) +void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize) { // qDebug("QGL2PaintEngineExPrivate::drawImage()"); - - // We have a shader specifically for drawPixmap/drawImage... - shaderManager->imageShader()->use(); - updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); if (compositionModeDirty) @@ -507,45 +526,66 @@ void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& s imageShaderMatrixUniformDirty = false; } - shaderManager->imageShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; - -// if (q->state()->opacity < 0.99f) + if (q->state()->opacity < 0.99f) shaderManager->imageShader()->uniforms()[QLatin1String("opacity")] = (GLfloat)q->state()->opacity; - GLfloat vertexCoords[] = { - dest.left, dest.top, - dest.left, dest.bottom, - dest.right, dest.bottom, - dest.right, dest.top - }; + GLfloat dx = 1.0 / textureSize.width(); + GLfloat dy = 1.0 / textureSize.height(); - glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); - glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoords); + QGLRect srcTextureRect(src.left*dx, 1.0 - src.top*dy, src.right*dx, 1.0 - src.bottom*dy); - GLfloat dx = 1.0 / txtWidth; - GLfloat dy = 1.0 / txtHeight; + setCoords(staticVertexCoordinateArray, dest); + setCoords(staticTextureCoordinateArray, srcTextureRect); - QGLRect srcTextureRect(src.left*dx, 1.0 - src.top*dy, src.right*dx, 1.0 - src.bottom*dy); + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); +} - GLfloat textureCoords[] = { - srcTextureRect.left, srcTextureRect.top, - srcTextureRect.left, srcTextureRect.bottom, - srcTextureRect.right, srcTextureRect.bottom, - srcTextureRect.right, srcTextureRect.top - }; +void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) +{ + if (newMode == mode) + return; - glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); - glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoords); + if (mode == TextDrawingMode || mode == ImageDrawingMode) { + glDisableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); + glDisableVertexAttribArray(QT_VERTEX_COORDS_ATTR); + } - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + if (newMode == TextDrawingMode) { + glEnable(GL_BLEND); + glActiveTexture(QT_BRUSH_TEXTURE_UNIT); - glDisableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); - glDisableVertexAttribArray(QT_VERTEX_COORDS_ATTR); -} + glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); + glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); + glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray.data()); + glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray.data()); + + shaderManager->textShader()->use(); + shaderManager->textShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; + } + + if (newMode == ImageDrawingMode) { + // We have a shader specifically for drawPixmap/drawImage... + shaderManager->imageShader()->use(); + shaderManager->imageShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; + shaderManager->imageShader()->uniforms()[QLatin1String("opacity")] = (GLfloat)1.0; + + glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); + glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); + + glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, staticVertexCoordinateArray); + glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, staticTextureCoordinateArray); + + glActiveTexture(QT_BRUSH_TEXTURE_UNIT); + } + + mode = newMode; +} void QGL2PaintEngineExPrivate::drawOutline(const QVectorPath& path) { + transferMode(DefaultMode); + // qDebug("QGL2PaintEngineExPrivate::drawOutline()"); if (matrixDirty) updateMatrix(); @@ -567,6 +607,8 @@ void QGL2PaintEngineExPrivate::drawOutline(const QVectorPath& path) // Assumes everything is configured for the brush you want to use void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) { + transferMode(DefaultMode); + if (matrixDirty) updateMatrix(); @@ -846,10 +888,10 @@ void QGL2PaintEngineEx::transformChanged() void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src) { Q_D(QGL2PaintEngineEx); - QGLContext *ctx = d->ctx; - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); + d->transferMode(ImageDrawingMode); - d->ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, true); + QGLContext *ctx = d->ctx; + ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, true); //FIXME: we should use hasAlpha() instead, but that's SLOW at the moment if ((state()->opacity < 0.99f) || pixmap.hasAlphaChannel()) @@ -857,23 +899,24 @@ void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, c else glDisable(GL_BLEND); - d->drawTexture(dest, src, pixmap.width(), pixmap.height()); + d->drawTexture(dest, src, pixmap.size()); } void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src, Qt::ImageConversionFlags) { Q_D(QGL2PaintEngineEx); + d->transferMode(ImageDrawingMode); + QGLContext *ctx = d->ctx; - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); - d->ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); + ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); if ((state()->opacity < 0.99f) || image.hasAlphaChannel()) glEnable(GL_BLEND); else glDisable(GL_BLEND); - d->drawTexture(dest, src, image.width(), image.height()); + d->drawTexture(dest, src, image.size()); } void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem) @@ -908,6 +951,8 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte Q_Q(QGL2PaintEngineEx); QOpenGLPaintEngineState *s = q->state(); + transferMode(TextDrawingMode); + QVarLengthArray positions; QVarLengthArray glyphs; QTransform matrix; @@ -930,12 +975,8 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte const QImage &image = cache->image(); int margin = cache->glyphMargin(); - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); - glEnable(GL_BLEND); - - shaderManager->textShader()->use(); updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); if (compositionModeDirty) @@ -949,13 +990,15 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte textShaderMatrixUniformDirty = false; } - shaderManager->textShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; QColor col = premultiplyColor(s->pen.color(), (GLfloat)s->opacity); shaderManager->textShader()->uniforms()[QLatin1String("fragmentColor")] = col; GLfloat dx = 1.0 / image.width(); GLfloat dy = 1.0 / image.height(); + QGLPoint *oldVertexCoordinateDataPtr = vertexCoordinateArray.data(); + QGLPoint *oldTextureCoordinateDataPtr = textureCoordinateArray.data(); + vertexCoordinateArray.clear(); textureCoordinateArray.clear(); @@ -968,15 +1011,12 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte textureCoordinateArray.addRect(QRectF(c.x*dx, 1 - c.y*dy, c.w * dx, -c.h * dy)); } - glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); - glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); + if (vertexCoordinateArray.data() != oldVertexCoordinateDataPtr) + glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray.data()); + if (textureCoordinateArray.data() != oldTextureCoordinateDataPtr) + glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray.data()); - glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray.data()); - glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray.data()); glDrawArrays(GL_TRIANGLES, 0, 6 * glyphs.size()); - - glDisableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); - glDisableVertexAttribArray(QT_VERTEX_COORDS_ATTR); } bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) @@ -991,6 +1031,7 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) QSize sz = d->drawable.size(); d->width = sz.width(); d->height = sz.height(); + d->mode = DefaultMode; qt_resolve_version_1_3_functions(d->ctx); qt_resolve_glsl_extensions(d->ctx); -- cgit v0.12 From 7cee2659388388754d741ba4b46647c57d03c498 Mon Sep 17 00:00:00 2001 From: Gunnar Sletta Date: Mon, 23 Feb 2009 13:54:07 +0100 Subject: Fixes: Make raster engine perform better on 0-opacity drawing RevBy: sroedal Task: came in from brisbane --- src/gui/painting/qdrawhelper_p.h | 3 ++- src/gui/painting/qpaintengine_raster.cpp | 23 +++++++++++++++++------ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/gui/painting/qdrawhelper_p.h b/src/gui/painting/qdrawhelper_p.h index de97683..586ffe3 100644 --- a/src/gui/painting/qdrawhelper_p.h +++ b/src/gui/painting/qdrawhelper_p.h @@ -110,6 +110,7 @@ struct QSpanData; class QGradient; class QRasterBuffer; class QClipData; +class QRasterPaintEngineState; typedef QT_FT_SpanFunc ProcessSpans; typedef void (*BitmapBlitFunc)(QRasterBuffer *rasterBuffer, @@ -293,7 +294,7 @@ struct QSpanData }; void init(QRasterBuffer *rb, const QRasterPaintEngine *pe); - void setup(const QBrush &brush, int alpha); + void setup(const QBrush &brush, int alpha, const QRasterPaintEngineState *s); void setupMatrix(const QTransform &matrix, int bilinear); void initTexture(const QImage *image, int alpha, QTextureData::Type = QTextureData::Plain, const QRect &sourceRect = QRect()); void adjustSpanMethods(); diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index ba79b5b..92a196c 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -483,12 +483,12 @@ bool QRasterPaintEngine::begin(QPaintDevice *device) d->rasterizer->setClipRect(d->deviceRect); s->penData.init(d->rasterBuffer, this); - s->penData.setup(s->pen.brush(), s->intOpacity); + s->penData.setup(s->pen.brush(), s->intOpacity, s); s->stroker = &d->basicStroker; d->basicStroker.setClipRect(d->deviceRect); s->brushData.init(d->rasterBuffer, this); - s->brushData.setup(s->brush, s->intOpacity); + s->brushData.setup(s->brush, s->intOpacity, s); d->rasterBuffer->compositionMode = QPainter::CompositionMode_SourceOver; @@ -769,7 +769,7 @@ void QRasterPaintEngine::updatePen(const QPen &pen) s->strokeFlags = 0; s->penData.clip = d->clip(); - s->penData.setup(pen_style == Qt::NoPen ? QBrush() : pen.brush(), s->intOpacity); + s->penData.setup(pen_style == Qt::NoPen ? QBrush() : pen.brush(), s->intOpacity, s); if (s->strokeFlags & QRasterPaintEngine::DirtyTransform || pen.brush().transform().type() >= QTransform::TxNone) { @@ -869,7 +869,7 @@ void QRasterPaintEngine::updateBrush(const QBrush &brush) QRasterPaintEngineState *s = state(); // must set clip prior to setup, as setup uses it... s->brushData.clip = d->clip(); - s->brushData.setup(brush, s->intOpacity); + s->brushData.setup(brush, s->intOpacity, s); if (s->fillFlags & DirtyTransform || brush.transform().type() >= QTransform::TxNone) d_func()->updateMatrixData(&s->brushData, brush, d->brushMatrix()); @@ -1024,6 +1024,10 @@ void QRasterPaintEnginePrivate::drawImage(const QPointF &pt, { if (!clip.isValid()) return; + + if (alpha ==0) + return; + Q_ASSERT(img.depth() >= 8); int srcBPL = img.bytesPerLine(); @@ -1867,9 +1871,12 @@ void QRasterPaintEngine::fillRect(const QRectF &r, const QColor &color) QRasterPaintEngineState *s = state(); d->solid_color_filler.solid.color = PREMUL(ARGB_COMBINE_ALPHA(color.rgba(), s->intOpacity)); + if ((d->solid_color_filler.solid.color & 0xff000000) == 0 + && s->composition_mode == QPainter::CompositionMode_SourceOver) { + return; + } d->solid_color_filler.clip = d->clip(); d->solid_color_filler.adjustSpanMethods(); - fillRect(r, &d->solid_color_filler); } @@ -4906,7 +4913,7 @@ void QSpanData::init(QRasterBuffer *rb, const QRasterPaintEngine *pe) extern QImage qt_imageForBrush(int brushStyle, bool invert); -void QSpanData::setup(const QBrush &brush, int alpha) +void QSpanData::setup(const QBrush &brush, int alpha, const QRasterPaintEngineState *s) { Qt::BrushStyle brushStyle = qbrush_style(brush); switch (brushStyle) { @@ -4914,6 +4921,10 @@ void QSpanData::setup(const QBrush &brush, int alpha) type = Solid; QColor c = qbrush_color(brush); solid.color = PREMUL(ARGB_COMBINE_ALPHA(c.rgba(), alpha)); + if ((solid.color & 0xff000000) == 0 + && s->composition_mode == QPainter::CompositionMode_SourceOver) { + type = None; + } break; } -- cgit v0.12 From 6ab74831766cdd5cf4e94eee8a60099436e61202 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Mon, 9 Mar 2009 13:07:18 +0100 Subject: Fixes: Extreme amount of pixel buffers created in embeddeddialogs demo. Details: As a window surface is created even for embedded widgets, don't create the GL resources required by the surface until they are actually needed. RevBy: Tom --- src/opengl/qwindowsurface_gl.cpp | 14 +++++++++++--- src/opengl/qwindowsurface_gl_p.h | 1 + 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index bb4ffc5..08c2aab 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -315,6 +315,8 @@ QGLContext *QGLWindowSurface::context() const QPaintDevice *QGLWindowSurface::paintDevice() { + updateGeometry(); + if (d_ptr->pb) return d_ptr->pb; @@ -330,6 +332,7 @@ static void drawTexture(const QRectF &rect, GLuint tex_id, const QSize &texSize, void QGLWindowSurface::beginPaint(const QRegion &) { + updateGeometry(); } void QGLWindowSurface::endPaint(const QRegion &rgn) @@ -460,9 +463,9 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & d_ptr->fbo->bind(); } -void QGLWindowSurface::setGeometry(const QRect &rect) +void QGLWindowSurface::updateGeometry() { - QWindowSurface::setGeometry(rect); + QRect rect = QWindowSurface::geometry(); const GLenum target = qt_gl_preferredTextureTarget(); @@ -496,7 +499,7 @@ void QGLWindowSurface::setGeometry(const QRect &rect) qt_gl_share_widget()); if (d_ptr->pb->isValid()) { - qDebug() << "PB Sample buffers:" << d_ptr->pb->format().sampleBuffers(); + qDebug() << "Created Window Surface Pixelbuffer, Sample buffers:" << d_ptr->pb->format().sampleBuffers(); d_ptr->pb->makeCurrent(); glGenTextures(1, &d_ptr->pb_tex_id); @@ -561,6 +564,11 @@ void QGLWindowSurface::setGeometry(const QRect &rect) d_ptr->ctx->d_ptr->internal_context = true; } +void QGLWindowSurface::setGeometry(const QRect &rect) +{ + QWindowSurface::setGeometry(rect); +} + bool QGLWindowSurface::scroll(const QRegion &area, int dx, int dy) { // this code randomly fails currently for unknown reasons diff --git a/src/opengl/qwindowsurface_gl_p.h b/src/opengl/qwindowsurface_gl_p.h index 0194378..d47e3e3 100644 --- a/src/opengl/qwindowsurface_gl_p.h +++ b/src/opengl/qwindowsurface_gl_p.h @@ -74,6 +74,7 @@ public: QPaintDevice *paintDevice(); void flush(QWidget *widget, const QRegion ®ion, const QPoint &offset); void setGeometry(const QRect &rect); + void updateGeometry(); bool scroll(const QRegion &area, int dx, int dy); void beginPaint(const QRegion ®ion); -- cgit v0.12 From 570ef6dbc4526d39ef8d2b7e29ddedcfa67b061f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Mon, 9 Mar 2009 15:01:48 +0100 Subject: Fixes: Clipping bug in GL 2 paint engine (embeddeddialogs demo). RevBy: Tom --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 88c33d4..9eeef1b 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1057,6 +1057,7 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) glDisable(GL_DEPTH_TEST); + updateClipRegion(QRegion(), Qt::NoClip); return true; } -- cgit v0.12 From 0f95b04c91e559ca62698234dcd82445c5ee8ceb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Mon, 9 Mar 2009 15:01:16 +0100 Subject: Fixes: Small optimizations in GL 2 paint engine... RevBy: Tom --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 9eeef1b..ce9f976 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -424,7 +424,9 @@ void QGL2PaintEngineExPrivate::updateMatrix() for (int row = 0; row < 4; ++row) { for (int col = 0; col < 4; ++col) { pmvMatrix[col][row] = 0.0; - for (int n = 0; n < 4; ++n) + + // P[row][n] is 0.0 for n < row + for (int n = row; n < 4; ++n) pmvMatrix[col][row] += P[row][n] * MV[n][col]; } } @@ -804,8 +806,6 @@ void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush) { Q_D(QGL2PaintEngineEx); - QTime startTime = QTime::currentTime(); - d->setBrush(&brush); d->fill(path); d->setBrush(&(state()->brush)); // reset back to the state's brush -- cgit v0.12 From 4feeae36f1dc18795646e648f9987795706d21f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Mon, 9 Mar 2009 13:09:25 +0100 Subject: Fixes: Get rid of GL 2 paint engine debug message... RevBy: Tom --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index ce9f976..6e24bdc 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -794,8 +794,6 @@ void QGL2PaintEngineExPrivate::drawVertexArrays(QGL2PEXVertexArray& vertexArray, QGL2PaintEngineEx::QGL2PaintEngineEx() : QPaintEngineEx(*(new QGL2PaintEngineExPrivate(this))) { - qDebug("QGL2PaintEngineEx::QGL2PaintEngineEx()"); - } QGL2PaintEngineEx::~QGL2PaintEngineEx() -- cgit v0.12 From 56fc9b853f8d19999c81ed13a9f2fcd0e95241e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 11 Mar 2009 09:16:37 +0100 Subject: Fixes: Respect the SmoothPixmapTransform render hint in the GL2 paint engine. RevBy: Tom --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 6e24bdc..dbf18b1 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -515,7 +515,7 @@ static inline void setCoords(GLfloat *coords, const QGLRect &rect) void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize) { // qDebug("QGL2PaintEngineExPrivate::drawImage()"); - updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); + updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform); if (compositionModeDirty) updateCompositionMode(); -- cgit v0.12 From 4d4580b5f43adb22b6ba95f49698efcd5dbdfeae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 11 Mar 2009 10:37:13 +0100 Subject: Fixes: Make FBO window surface work with GL 2 paint engine. RevBy: Trond Details: Need to make sure clipping/scissoring etc is turned off and that we are in a good state. --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 3 +++ src/opengl/qwindowsurface_gl.cpp | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index dbf18b1..89ed1f7 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1062,6 +1062,9 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) bool QGL2PaintEngineEx::end() { Q_D(QGL2PaintEngineEx); + QGLContext *ctx = d->ctx; + glUseProgram(0); + d->transferMode(DefaultMode); d->drawable.swapBuffers(); d->drawable.doneCurrent(); return false; diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 08c2aab..5cd4366 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -439,6 +439,9 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & if (d_ptr->fbo) d_ptr->fbo->release(); + glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + glMatrixMode(GL_MODELVIEW); glLoadIdentity(); @@ -539,6 +542,7 @@ void QGLWindowSurface::updateGeometry() d_ptr->fbo->bind(); if (d_ptr->fbo->isValid()) { + qDebug() << "Created Window Surface FBO" << rect.size(); return; } else { qDebug() << "QGLWindowSurface: Failed to create valid FBO, falling back"; -- cgit v0.12 From 1ada6800efbbca276441b3b170b1ccfa0c09c20a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 12 Mar 2009 09:00:34 +0100 Subject: Fixes: Add blitting and multisample API to QGLFramebufferObject. RevBy: Trond Details: Support GL_EXT_framebuffer_multisample and GL_EXT_framebuffer_blit in the QGLFramebufferObject API. --- src/opengl/qgl.cpp | 2 + src/opengl/qgl_p.h | 3 +- src/opengl/qglextensions.cpp | 3 + src/opengl/qglextensions_p.h | 37 +++ src/opengl/qglframebufferobject.cpp | 456 +++++++++++++++++++++++++++++++++--- src/opengl/qglframebufferobject.h | 49 ++++ 6 files changed, 520 insertions(+), 30 deletions(-) diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 558897d..fc11d90 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -4175,6 +4175,8 @@ void QGLExtensions::init_extensions() glExtensions |= FramebufferObject; glExtensions |= GenerateMipmap; #endif + if (extensions.contains(QLatin1String("EXT_framebuffer_blit"))) + glExtensions |= FramebufferBlit; QGLContext cx(QGLFormat::defaultFormat()); if (glExtensions & TextureCompression) { diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index 76f3812..8ab73d8 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -330,7 +330,8 @@ public: StencilWrap = 0x00000100, PackedDepthStencil = 0x00000200, NVFloatBuffer = 0x00000400, - PixelBufferObject = 0x00000800 + PixelBufferObject = 0x00000800, + FramebufferBlit = 0x00001000 }; Q_DECLARE_FLAGS(Extensions, Extension) diff --git a/src/opengl/qglextensions.cpp b/src/opengl/qglextensions.cpp index b054fe8..e6ac043 100644 --- a/src/opengl/qglextensions.cpp +++ b/src/opengl/qglextensions.cpp @@ -74,6 +74,9 @@ bool qt_resolve_framebufferobject_extensions(QGLContext *ctx) glGetFramebufferAttachmentParameterivEXT = (_glGetFramebufferAttachmentParameterivEXT) ctx->getProcAddress(QLatin1String("glGetFramebufferAttachmentParameterivEXT")); glGenerateMipmapEXT = (_glGenerateMipmapEXT) ctx->getProcAddress(QLatin1String("glGenerateMipmapEXT")); + glBlitFramebufferEXT = (_glBlitFramebufferEXT) ctx->getProcAddress(QLatin1String("glBlitFramebufferEXT")); + glRenderbufferStorageMultisampleEXT = + (_glRenderbufferStorageMultisampleEXT) ctx->getProcAddress(QLatin1String("glRenderbufferStorageMultisampleEXT")); return glIsRenderbufferEXT; #else Q_UNUSED(ctx); diff --git a/src/opengl/qglextensions_p.h b/src/opengl/qglextensions_p.h index fdf0bba..cd35eb0 100644 --- a/src/opengl/qglextensions_p.h +++ b/src/opengl/qglextensions_p.h @@ -162,6 +162,15 @@ typedef void (APIENTRY *_glGetFramebufferAttachmentParameterivEXT) (GLenum targe GLint *params); typedef void (APIENTRY *_glGenerateMipmapEXT) (GLenum target); +// EXT_GL_framebuffer_blit +typedef void (APIENTRY *_glBlitFramebufferEXT) (int srcX0, int srcY0, int srcX1, int srcY1, + int dstX0, int dstY0, int dstX1, int dstY1, + GLbitfield mask, GLenum filter); + +// EXT_GL_framebuffer_multisample +typedef void (APIENTRY *_glRenderbufferStorageMultisampleEXT) (GLenum target, GLsizei samples, + GLenum internalformat, GLsizei width, GLsizei height); + QT_BEGIN_NAMESPACE struct QGLExtensionFuncs @@ -220,6 +229,8 @@ struct QGLExtensionFuncs qt_glGetFramebufferAttachmentParameterivEXT = 0; qt_glGenerateMipmapEXT = 0; #endif + qt_glBlitFramebufferEXT = 0; + qt_glRenderbufferStorageMultisampleEXT = 0; qt_glBindBufferARB = 0; qt_glDeleteBuffersARB = 0; @@ -298,6 +309,8 @@ struct QGLExtensionFuncs _glGetFramebufferAttachmentParameterivEXT qt_glGetFramebufferAttachmentParameterivEXT; _glGenerateMipmapEXT qt_glGenerateMipmapEXT; #endif + _glBlitFramebufferEXT qt_glBlitFramebufferEXT; + _glRenderbufferStorageMultisampleEXT qt_glRenderbufferStorageMultisampleEXT; _glBindBufferARB qt_glBindBufferARB; _glDeleteBuffersARB qt_glDeleteBuffersARB; @@ -447,6 +460,28 @@ struct QGLExtensionFuncs #define GL_RENDERBUFFER_STENCIL_SIZE_EXT 0x8D55 #endif +// GL_EXT_framebuffer_blit +#ifndef GL_READ_FRAMEBUFFER_EXT +#define GL_READ_FRAMEBUFFER_EXT 0x8CA8 +#endif + +// GL_EXT_framebuffer_multisample +#ifndef GL_RENDERBUFFER_SAMPLES_EXT +#define GL_RENDERBUFFER_SAMPLES_EXT 0x8CAB +#endif + +#ifndef GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT +#define GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT 0x8D56 +#endif + +#ifndef GL_MAX_SAMPLES_EXT +#define GL_MAX_SAMPLES_EXT 0x8D5 +#endif + +#ifndef GL_DRAW_FRAMEBUFFER_EXT +#define GL_DRAW_FRAMEBUFFER_EXT 0x8CA9 +#endif + #ifndef GL_EXT_packed_depth_stencil #define GL_DEPTH_STENCIL_EXT 0x84F9 #define GL_UNSIGNED_INT_24_8_EXT 0x84FA @@ -533,6 +568,8 @@ struct QGLExtensionFuncs #define glFramebufferRenderbufferEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glFramebufferRenderbufferEXT #define glGetFramebufferAttachmentParameterivEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetFramebufferAttachmentParameterivEXT #define glGenerateMipmapEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenerateMipmapEXT +#define glBlitFramebufferEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBlitFramebufferEXT +#define glRenderbufferStorageMultisampleEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glRenderbufferStorageMultisampleEXT #else // QT_OPENGL_ES_2 diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 9134fc6..297ef84 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -67,6 +67,216 @@ extern QImage qt_gl_read_framebuffer(const QSize&, bool, bool); } \ } +class QGLFramebufferObjectFormatPrivate +{ +public: + int samples; + QGLFramebufferObject::Attachment attachment; + GLenum target; + GLenum internal_format; +}; + +/*! + \class QGLFramebufferObjectFormat + \brief The QGLFramebufferObjectFormat class specifies the format of an OpenGL + framebuffer object. + + \since 4.6 + + \ingroup multimedia + + A framebuffer object has several characteristics: + \list + \i \link setSamples() Number of samples per pixels.\endlink + \i \link setAttachment() Depth and/or stencil attachments.\endlink + \i \link setTextureTarget() Texture target.\endlink + \i \link setInternalFormat() Internal format.\endlink + \endlist + + Note that the desired attachments or number of samples per pixels might not + be supported by the hardware driver. Call QGLFramebufferObject::format() + after creating a QGLFramebufferObject to find the exact format that was + used to create the frame buffer object. + + \sa QGLFramebufferObject +*/ + +/*! + \since 4.6 + + Creates a QGLFramebufferObjectFormat object with properties specifying + the format of an OpenGL framebuffer object. + + A multisample framebuffer object is specified by setting \a samples + to a value different from zero. If the desired amount of samples per pixel is + not supported by the hardware then the maximum number of samples per pixel + will be used. Note that multisample framebuffer objects can not be bound as + textures. Also, the \c{GL_EXT_framebuffer_multisample} extension is required + to create a framebuffer with more than one sample per pixel. + + For multisample framebuffer objects a color render buffer is created, + otherwise a texture with the texture target \a target is created. + The color render buffer or texture will have the internal format + \a internalFormat, and will be bound to the \c GL_COLOR_ATTACHMENT0 + attachment in the framebuffer object. + + The \a attachment parameter describes the depth/stencil buffer + configuration. + + \sa samples(), attachment(), target(), internalFormat() +*/ + +QGLFramebufferObjectFormat::QGLFramebufferObjectFormat(int samples, + QGLFramebufferObject::Attachment attachment, + GLenum target, + GLenum internalFormat) +{ + d = new QGLFramebufferObjectFormatPrivate; + d->samples = samples; + d->attachment = attachment; + d->target = target; + d->internal_format = internalFormat; +} + +/*! + \since 4.6 + + Constructs a copy of \a other. +*/ + +QGLFramebufferObjectFormat::QGLFramebufferObjectFormat(const QGLFramebufferObjectFormat &other) +{ + d = new QGLFramebufferObjectFormatPrivate; + *d = *other.d; +} + +/*! + \since 4.6 + + Assigns \a other to this object. +*/ + +QGLFramebufferObjectFormat::QGLFramebufferObjectFormat & +QGLFramebufferObjectFormat::operator=(const QGLFramebufferObjectFormat &other) +{ + *d = *other.d; + return *this; +} + +/*! + \since 4.6 + + Destroys the QGLFramebufferObjectFormat. +*/ +QGLFramebufferObjectFormat::~QGLFramebufferObjectFormat() +{ + delete d; +} + +/*! + \since 4.6 + + Sets the number of samples per pixel for a multisample framebuffer object + to \a samples. + A sample count of 0 represents a regular non-multisample framebuffer object. + + \sa samples() +*/ +void QGLFramebufferObjectFormat::setSamples(int samples) +{ + d->samples = samples; +} + +/*! + \since 4.6 + + Returns the number of samples per pixel if a framebuffer object + is a multisample framebuffer object. Otherwise, returns 0. + + \sa setSamples() +*/ +int QGLFramebufferObjectFormat::samples() const +{ + return d->samples; +} + +/*! + \since 4.6 + + Sets the attachments a framebuffer object should have to \a attachment. + + \sa attachment() +*/ +void QGLFramebufferObjectFormat::setAttachment(QGLFramebufferObject::Attachment attachment) +{ + d->attachment = attachment; +} + +/*! + \since 4.6 + + Returns the status of the depth and stencil buffers attached to + a framebuffer object. + + \sa setAttachment() +*/ +QGLFramebufferObject::Attachment QGLFramebufferObjectFormat::attachment() const +{ + return d->attachment; +} + +/*! + \since 4.6 + + Sets the texture target of the texture attached to a framebuffer object to + \a target. Ignored for multisample framebuffer objects. + + \sa textureTarget(), samples() +*/ +void QGLFramebufferObjectFormat::setTextureTarget(GLenum target) +{ + d->target = target; +} + +/*! + \since 4.6 + + Returns the texture target of the texture attached to a framebuffer object. + Ignored for multisample framebuffer objects. + + \sa setTextureTarget(), samples() +*/ +GLenum QGLFramebufferObjectFormat::textureTarget() const +{ + return d->target; +} + +/*! + \since 4.6 + + Sets the internal format of a framebuffer object's texture or multisample + framebuffer object's color buffer to \a internalFormat. + + \sa internalFormat() +*/ +void QGLFramebufferObjectFormat::setInternalFormat(GLenum internalFormat) +{ + d->internal_format = internalFormat; +} + +/*! + \since 4.6 + + Returns the internal format of a framebuffer object's texture or + multisample framebuffer object's color buffer. + + \sa setInternalFormat() +*/ +GLenum QGLFramebufferObjectFormat::internalFormat() const +{ + return d->internal_format; +} + class QGLFramebufferObjectPrivate { public: @@ -74,13 +284,16 @@ public: ~QGLFramebufferObjectPrivate() {} void init(const QSize& sz, QGLFramebufferObject::Attachment attachment, - GLenum internal_format, GLenum texture_target); + GLenum internal_format, GLenum texture_target, int samples = 0); bool checkFramebufferStatus() const; GLuint texture; GLuint fbo; GLuint depth_stencil_buffer; + GLuint color_buffer; GLenum target; QSize size; + QGLFramebufferObjectFormat format; + int samples; uint valid : 1; uint bound : 1; QGLFramebufferObject::Attachment fbo_attachment; @@ -122,6 +335,9 @@ bool QGLFramebufferObjectPrivate::checkFramebufferStatus() const case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: qDebug("QGLFramebufferObject: Framebuffer incomplete, missing read buffer."); break; + case GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT: + qDebug("QGLFramebufferObject: Framebuffer incomplete, attachments must have same number of samples per pixel."); + break; default: qDebug() <<"QGLFramebufferObject: An undefined error has occurred: "<< status; break; @@ -130,7 +346,7 @@ bool QGLFramebufferObjectPrivate::checkFramebufferStatus() const } void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::Attachment attachment, - GLenum texture_target, GLenum internal_format) + GLenum texture_target, GLenum internal_format, int samples) { ctx = const_cast(QGLContext::currentContext()); bool ext_detected = (QGLExtensions::glExtensions & QGLExtensions::FramebufferObject); @@ -147,26 +363,56 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At QT_CHECK_GLERROR(); // init texture - glGenTextures(1, &texture); - glBindTexture(target, texture); - glTexImage2D(target, 0, internal_format, size.width(), size.height(), 0, - GL_RGBA, GL_UNSIGNED_BYTE, NULL); + if (samples == 0) { + glGenTextures(1, &texture); + glBindTexture(target, texture); + glTexImage2D(target, 0, internal_format, size.width(), size.height(), 0, + GL_RGBA, GL_UNSIGNED_BYTE, NULL); #ifndef QT_OPENGL_ES - glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameteri(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameteri(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #else - glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); + glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); + glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #endif - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, - target, texture, 0); + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + target, texture, 0); - QT_CHECK_GLERROR(); - valid = checkFramebufferStatus(); + QT_CHECK_GLERROR(); + valid = checkFramebufferStatus(); + + color_buffer = 0; + samples = 0; + } else { + GLint maxSamples; + glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); + + samples = qBound(1, samples, int(maxSamples)); + + glGenRenderbuffersEXT(1, &color_buffer); + glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, color_buffer); + if (glRenderbufferStorageMultisampleEXT) { + glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, + internal_format, size.width(), size.height()); + } else { + samples = 0; + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internal_format, + size.width(), size.height()); + } + + glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + GL_RENDERBUFFER_EXT, color_buffer); + + QT_CHECK_GLERROR(); + valid = checkFramebufferStatus(); + + if (valid) + glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &samples); + } if (attachment == QGLFramebufferObject::CombinedDepthStencil && (QGLExtensions::glExtensions & QGLExtensions::PackedDepthStencil)) { @@ -175,7 +421,13 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At Q_ASSERT(!glIsRenderbufferEXT(depth_stencil_buffer)); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_stencil_buffer); Q_ASSERT(glIsRenderbufferEXT(depth_stencil_buffer)); - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); + if (samples != 0 && glRenderbufferStorageMultisampleEXT) + glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, + GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); + else + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, + GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); + GLint i = 0; glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &i); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, @@ -183,6 +435,7 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_buffer); fbo_attachment = QGLFramebufferObject::CombinedDepthStencil; + valid = checkFramebufferStatus(); if (!valid) glDeleteRenderbuffersEXT(1, &depth_stencil_buffer); @@ -193,12 +446,23 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At Q_ASSERT(!glIsRenderbufferEXT(depth_stencil_buffer)); glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_stencil_buffer); Q_ASSERT(glIsRenderbufferEXT(depth_stencil_buffer)); + if (samples != 0 && glRenderbufferStorageMultisampleEXT) { #ifdef QT_OPENGL_ES #define GL_DEPTH_COMPONENT16 0x81A5 - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, size.width(), size.height()); + glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, + GL_DEPTH_COMPONENT16, size.width(), size.height()); #else - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, size.width(), size.height()); + glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, + GL_DEPTH_COMPONENT, size.width(), size.height()); #endif + } else { +#ifdef QT_OPENGL_ES +#define GL_DEPTH_COMPONENT16 0x81A5 + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, size.width(), size.height()); +#else + glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, size.width(), size.height()); +#endif + } GLint i = 0; glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &i); glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, @@ -213,10 +477,18 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); if (!valid) { - glDeleteTextures(1, &texture); + if (color_buffer) + glDeleteRenderbuffersEXT(1, &color_buffer); + else + glDeleteTextures(1, &texture); glDeleteFramebuffersEXT(1, &fbo); } QT_CHECK_GLERROR(); + + format.setTextureTarget(target); + format.setSamples(samples); + format.setAttachment(fbo_attachment); + format.setInternalFormat(internal_format); } /*! @@ -264,13 +536,18 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At framebuffer objects more portable. \endlist - Note that primitives drawn to a QGLFramebufferObject with QPainter - will only be antialiased if the QPainter::HighQualityAntialiasing - render hint is set. This is because there is currently no support - for the \c{GL_EXT_framebuffer_multisample} extension, which is - required to do multisample based antialiasing. Also note that the - QPainter::HighQualityAntialiasing render hint requires the - \c{GL_ARB_fragment_program} extension to work in OpenGL. + Note that you need to create a QGLFramebufferObject with more than one + sample per pixel for primitives to be antialiased when drawing using a + QPainter, unless if the QPainter::HighQualityAntialiasing render hint is + set. The QPainter::HighQualityAntialiasing render hint will enable + antialiasing as long as the \c{GL_ARB_fragment_program} extension is + present. To create a multisample framebuffer object you should use one of + the constructors that take a QGLFramebufferObject parameter, and set the + QGLFramebufferObject::samples() property to a non-zero value. + + If you want to use a framebuffer object with multisampling enabled + as a texture, you first need to copy from it to a regular framebuffer + object using QGLContext::blitFramebuffer(). \sa {Framebuffer Object Example} */ @@ -358,6 +635,32 @@ QGLFramebufferObject::QGLFramebufferObject(int width, int height, GLenum target) d->init(QSize(width, height), NoAttachment, target, DEFAULT_FORMAT); } +/*! \overload + + Constructs an OpenGL framebuffer object of the given \a size based on the + supplied \a format. +*/ + +QGLFramebufferObject::QGLFramebufferObject(const QSize &size, const QGLFramebufferObjectFormat &format) + : d_ptr(new QGLFramebufferObjectPrivate) +{ + Q_D(QGLFramebufferObject); + d->init(size, format.attachment(), format.textureTarget(), format.internalFormat(), format.samples()); +} + +/*! \overload + + Constructs an OpenGL framebuffer object of the given \a width and \a height + based on the supplied \a format. +*/ + +QGLFramebufferObject::QGLFramebufferObject(int width, int height, const QGLFramebufferObjectFormat &format) + : d_ptr(new QGLFramebufferObjectPrivate) +{ + Q_D(QGLFramebufferObject); + d->init(QSize(width, height), format.attachment(), format.textureTarget(), format.internalFormat(), format.samples()); +} + #ifdef Q_MAC_COMPAT_GL_FUNCTIONS /*! \internal */ QGLFramebufferObject::QGLFramebufferObject(int width, int height, QMacCompatGLenum target) @@ -445,6 +748,8 @@ QGLFramebufferObject::~QGLFramebufferObject() || qgl_share_reg()->checkSharing(d->ctx, QGLContext::currentContext()))) { glDeleteTextures(1, &d->texture); + if (d->color_buffer) + glDeleteRenderbuffersEXT(1, &d->color_buffer); if (d->depth_stencil_buffer) glDeleteRenderbuffersEXT(1, &d->depth_stencil_buffer); glDeleteFramebuffersEXT(1, &d->fbo); @@ -540,6 +845,9 @@ bool QGLFramebufferObject::release() Returns the texture id for the texture attached as the default rendering target in this framebuffer object. This texture id can be bound as a normal texture in your own GL code. + + If a multisample framebuffer object is used then the value returned + from this function will be invalid. */ GLuint QGLFramebufferObject::texture() const { @@ -560,6 +868,15 @@ QSize QGLFramebufferObject::size() const } /*! + Returns the format of this framebuffer object. +*/ +const QGLFramebufferObjectFormat &QGLFramebufferObject::format() const +{ + Q_D(const QGLFramebufferObject); + return d->format; +} + +/*! \fn QImage QGLFramebufferObject::toImage() const Returns the contents of this framebuffer object as a QImage. @@ -752,4 +1069,85 @@ bool QGLFramebufferObject::isBound() const return d->bound; } +/*! + \fn bool QGLFramebufferObject::hasOpenGLFramebufferBlit() + + \since 4.6 + + Returns true if the OpenGL \c{GL_EXT_framebuffer_blit} extension + is present on this system; otherwise returns false. +*/ +bool QGLFramebufferObject::hasOpenGLFramebufferBlit() +{ + QGLWidget dmy; // needed to detect and init the QGLExtensions object + return (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit); +} + +/*! + \since 4.6 + + Blits from the \a sourceRect rectangle in the \a source framebuffer + object to the \a targetRect rectangle in the \a target framebuffer object. + + If \a source or \a target is 0, the default framebuffer will be used + instead of a framebuffer object as source or target respectively. + + The \a buffers parameter should be a mask consisting of any combination of + COLOR_BUFFER_BIT, DEPTH_BUFFER_BIT, and STENCIL_BUFFER_BIT. Any buffer type + that is not present both in the source and target buffers is ignored. + + The \a sourceRect and \a targetRect rectangles may have different sizes; + in this case \a buffers should not contain DEPTH_BUFFER_BIT or + STENCIL_BUFFER_BIT. The \a filter parameter should be set to GL_LINEAR or + GL_NEAREST, and specifies whether linear or nearest interpolation should + be used when scaling is performed. + + If \a source equals \a target a copy is performed within the same buffer. + Results are undefined if the source and target rectangles overlap and + have different sizes. The sizes must also be the same if any of the + framebuffer objects are multisample framebuffers. + + Note that the scissor test will restrict the blit area if enabled. + + This function will have no effect unless hasOpenGLFramebufferBlit() returns + true. +*/ +void QGLFramebufferObject::blitFramebuffer(QGLFramebufferObject *target, const QRect &targetRect, + QGLFramebufferObject *source, const QRect &sourceRect, + GLbitfield buffers, + GLenum filter) +{ + if (!(QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit)) + return; + + const QGLContext *ctx = QGLContext::currentContext(); + if (!ctx) + return; + + const int height = ctx->device()->height(); + + const int sh = source ? source->height() : height; + const int th = target ? target->height() : height; + + const int sx0 = sourceRect.left(); + const int sx1 = sourceRect.right(); + const int sy0 = sh - sourceRect.bottom() - 1; + const int sy1 = sh - sourceRect.top() - 1; + + const int tx0 = targetRect.left(); + const int tx1 = targetRect.right(); + const int ty0 = th - targetRect.bottom() - 1; + const int ty1 = th - targetRect.top() - 1; + + glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, source ? source->handle() : 0); + glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, target ? target->handle() : 0); + + glBlitFramebufferEXT(sx0, sy0, sx1, sy1, + tx0, ty0, tx1, ty1, + buffers, filter); + + glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); + glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0); +} + QT_END_NAMESPACE diff --git a/src/opengl/qglframebufferobject.h b/src/opengl/qglframebufferobject.h index a9e1b2f..0a2a9d2 100644 --- a/src/opengl/qglframebufferobject.h +++ b/src/opengl/qglframebufferobject.h @@ -52,6 +52,7 @@ QT_BEGIN_NAMESPACE QT_MODULE(OpenGL) class QGLFramebufferObjectPrivate; +class QGLFramebufferObjectFormat; class Q_OPENGL_EXPORT QGLFramebufferObject : public QPaintDevice { @@ -77,6 +78,9 @@ public: GLenum target = GL_TEXTURE_2D, GLenum internal_format = GL_RGBA); #endif + QGLFramebufferObject(const QSize &size, const QGLFramebufferObjectFormat &format); + QGLFramebufferObject(int width, int height, const QGLFramebufferObjectFormat &format); + #ifdef Q_MAC_COMPAT_GL_FUNCTIONS QGLFramebufferObject(const QSize &size, QMacCompatGLenum target = GL_TEXTURE_2D); QGLFramebufferObject(int width, int height, QMacCompatGLenum target = GL_TEXTURE_2D); @@ -89,10 +93,13 @@ public: virtual ~QGLFramebufferObject(); + const QGLFramebufferObjectFormat &format() const; + bool isValid() const; bool isBound() const; bool bind(); bool release(); + GLuint texture() const; QSize size() const; QImage toImage() const; @@ -110,6 +117,12 @@ public: void drawTexture(const QPointF &point, QMacCompatGLuint textureId, QMacCompatGLenum textureTarget = GL_TEXTURE_2D); #endif + static bool hasOpenGLFramebufferBlit(); + static void blitFramebuffer(QGLFramebufferObject *target, const QRect &targetRect, + QGLFramebufferObject *source, const QRect &sourceRect, + GLbitfield buffers = GL_COLOR_BUFFER_BIT, + GLenum filter = GL_NEAREST); + protected: int metric(PaintDeviceMetric metric) const; int devType() const { return QInternal::FramebufferObject; } @@ -120,6 +133,42 @@ private: friend class QGLDrawable; }; +class QGLFramebufferObjectFormatPrivate; +class Q_OPENGL_EXPORT QGLFramebufferObjectFormat +{ +public: +#if !defined(QT_OPENGL_ES) || defined(Q_QDOC) + QGLFramebufferObjectFormat(int samples = 0, + QGLFramebufferObject::Attachment attachment = QGLFramebufferObject::NoAttachment, + GLenum target = GL_TEXTURE_2D, + GLenum internalFormat = GL_RGBA8); +#else + QGLFramebufferObjectFormat(int samples = 0, + QGLFramebufferObject::Attachment attachment = QGLFramebufferObject::NoAttachment, + GLenum target = GL_TEXTURE_2D, + GLenum internalFormat = GL_RGBA); +#endif + + QGLFramebufferObjectFormat(const QGLFramebufferObjectFormat &other); + QGLFramebufferObjectFormat &operator=(const QGLFramebufferObjectFormat &other); + ~QGLFramebufferObjectFormat(); + + void setSamples(int samples); + int samples() const; + + void setAttachment(QGLFramebufferObject::Attachment attachment); + QGLFramebufferObject::Attachment attachment() const; + + void setTextureTarget(GLenum target); + GLenum textureTarget() const; + + void setInternalFormat(GLenum internalFormat); + GLenum internalFormat() const; + +private: + QGLFramebufferObjectFormatPrivate *d; +}; + QT_END_NAMESPACE QT_END_HEADER -- cgit v0.12 From ee8949183917ae7494cbf0121922d0b68384f90f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 11 Mar 2009 12:23:51 +0100 Subject: Fixes: Use the new framebuffer blit/multisample API in the window surface. RevBy: Trond --- src/opengl/qwindowsurface_gl.cpp | 49 +++++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 18 deletions(-) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 5cd4366..b4a4565 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -436,34 +436,39 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & #ifdef Q_WS_MAC ctx->updatePaintDevice(); #endif - if (d_ptr->fbo) - d_ptr->fbo->release(); - glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); + if (d_ptr->fbo && QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit) { + QGLFramebufferObject::blitFramebuffer(0, rect, d_ptr->fbo, rect); + d_ptr->fbo->bind(); + } else { + if (d_ptr->fbo) + d_ptr->fbo->release(); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); #ifndef QT_OPENGL_ES - glOrtho(0, size.width(), size.height(), 0, -999999, 999999); + glOrtho(0, size.width(), size.height(), 0, -999999, 999999); #else - glOrthof(0, size.width(), size.height(), 0, -999999, 999999); + glOrthof(0, size.width(), size.height(), 0, -999999, 999999); #endif - glViewport(0, 0, size.width(), size.height()); + glViewport(0, 0, size.width(), size.height()); + + glColor4f(1, 1, 1, 1); + drawTexture(rect, texture, window()->size(), br); - glColor4f(1, 1, 1, 1); - drawTexture(rect, texture, window()->size(), br); + if (d_ptr->fbo) + d_ptr->fbo->bind(); + } if (ctx->format().doubleBuffer()) ctx->swapBuffers(); else glFlush(); - - if (d_ptr->fbo) - d_ptr->fbo->bind(); } void QGLWindowSurface::updateGeometry() @@ -537,12 +542,20 @@ void QGLWindowSurface::updateGeometry() ctx->d_ptr->internal_context = true; ctx->makeCurrent(); delete d_ptr->fbo; - d_ptr->fbo = new QGLFramebufferObject(rect.size(), QGLFramebufferObject::CombinedDepthStencil, - GLenum(target), GLenum(GL_RGBA)); + QGLFramebufferObjectFormat format; + format.setAttachment(QGLFramebufferObject::CombinedDepthStencil); + format.setInternalFormat(GL_RGBA); + format.setTextureTarget(target); + + if (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit) + format.setSamples(8); + + d_ptr->fbo = new QGLFramebufferObject(rect.size(), format); d_ptr->fbo->bind(); if (d_ptr->fbo->isValid()) { - qDebug() << "Created Window Surface FBO" << rect.size(); + qDebug() << "Created Window Surface FBO" << rect.size() + << "with samples" << d_ptr->fbo->format().samples(); return; } else { qDebug() << "QGLWindowSurface: Failed to create valid FBO, falling back"; -- cgit v0.12 From b469889f6f9b49f2e52948e3419958b0d8bfc994 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 11 Mar 2009 18:46:13 +0100 Subject: Fixes: Prevent QGLFramebufferObject from resetting the current context. RevBy: Trond Details: If there is already an active context we don't need a dummy widget. --- src/opengl/qglframebufferobject.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 297ef84..45d4788 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -918,7 +918,8 @@ QPaintEngine *QGLFramebufferObject::paintEngine() const */ bool QGLFramebufferObject::hasOpenGLFramebufferObjects() { - QGLWidget dmy; // needed to detect and init the QGLExtensions object + if (!QGLContext::currentContext()) + QGLWidget dmy; // needed to detect and init the QGLExtensions object return (QGLExtensions::glExtensions & QGLExtensions::FramebufferObject); } @@ -1079,7 +1080,8 @@ bool QGLFramebufferObject::isBound() const */ bool QGLFramebufferObject::hasOpenGLFramebufferBlit() { - QGLWidget dmy; // needed to detect and init the QGLExtensions object + if (!QGLContext::currentContext()) + QGLWidget dmy; // needed to detect and init the QGLExtensions object return (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit); } -- cgit v0.12 From 860498a1e63bff2b5a52accda92256c36ba5c23d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 11 Mar 2009 18:47:47 +0100 Subject: Fixes: Use the blit/multisample FBO API in the framebuffer object example. RevBy: Trond --- examples/opengl/framebufferobject/glwidget.cpp | 28 ++++++++++++++++++++++---- examples/opengl/framebufferobject/glwidget.h | 3 ++- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/examples/opengl/framebufferobject/glwidget.cpp b/examples/opengl/framebufferobject/glwidget.cpp index d3591d6..3cb3929 100644 --- a/examples/opengl/framebufferobject/glwidget.cpp +++ b/examples/opengl/framebufferobject/glwidget.cpp @@ -53,7 +53,18 @@ GLWidget::GLWidget(QWidget *parent) { setWindowTitle(tr("OpenGL framebuffer objects")); makeCurrent(); - fbo = new QGLFramebufferObject(1024, 1024); + + if (QGLFramebufferObject::hasOpenGLFramebufferBlit()) { + QGLFramebufferObjectFormat format; + format.setSamples(4); + + render_fbo = new QGLFramebufferObject(512, 512, format); + texture_fbo = new QGLFramebufferObject(512, 512); + } else { + render_fbo = new QGLFramebufferObject(1024, 1024); + texture_fbo = render_fbo; + } + rot_x = rot_y = rot_z = 0.0f; scale = 0.1f; anim = new QTimeLine(750, this); @@ -113,7 +124,9 @@ GLWidget::~GLWidget() { delete[] wave; glDeleteLists(tile_list, 1); - delete fbo; + delete texture_fbo; + if (render_fbo != texture_fbo) + delete render_fbo; } void GLWidget::paintEvent(QPaintEvent *) @@ -129,10 +142,16 @@ void GLWidget::draw() saveGLState(); // render the 'bubbles.svg' file into our framebuffer object - QPainter fbo_painter(fbo); + QPainter fbo_painter(render_fbo); svg_renderer->render(&fbo_painter); fbo_painter.end(); + if (render_fbo != texture_fbo) { + QRect rect(0, 0, render_fbo->width(), render_fbo->height()); + QGLFramebufferObject::blitFramebuffer(texture_fbo, rect, + render_fbo, rect); + } + // draw into the GL widget glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_PROJECTION); @@ -145,8 +164,9 @@ void GLWidget::draw() glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glBindTexture(GL_TEXTURE_2D, fbo->texture()); + glBindTexture(GL_TEXTURE_2D, texture_fbo->texture()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); + glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glEnable(GL_TEXTURE_2D); glEnable(GL_MULTISAMPLE); glEnable(GL_CULL_FACE); diff --git a/examples/opengl/framebufferobject/glwidget.h b/examples/opengl/framebufferobject/glwidget.h index b64cfa8..d97ef78 100644 --- a/examples/opengl/framebufferobject/glwidget.h +++ b/examples/opengl/framebufferobject/glwidget.h @@ -77,6 +77,7 @@ private: QImage logo; QTimeLine *anim; QSvgRenderer *svg_renderer; - QGLFramebufferObject *fbo; + QGLFramebufferObject *render_fbo; + QGLFramebufferObject *texture_fbo; }; -- cgit v0.12 From 855aa89e0ba99f8a0f75d7b31930bab2cefb93f8 Mon Sep 17 00:00:00 2001 From: Gunnar Sletta Date: Wed, 4 Mar 2009 14:43:58 +0100 Subject: Fixes: make the toNormalizedFillRect function slightly faster RevBy: sroedal --- src/gui/painting/qpaintengine_raster.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 92a196c..3cf618c 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -1706,12 +1706,17 @@ void QRasterPaintEngine::stroke(const QVectorPath &path, const QPen &pen) static inline QRect toNormalizedFillRect(const QRectF &rect) { - const int x1 = qRound(rect.x() + aliasedCoordinateDelta); - const int y1 = qRound(rect.y() + aliasedCoordinateDelta); - const int x2 = qRound(rect.right() + aliasedCoordinateDelta); - const int y2 = qRound(rect.bottom() + aliasedCoordinateDelta); + int x1 = int(rect.x() + aliasedCoordinateDelta); + int y1 = int(rect.y() + aliasedCoordinateDelta); + int x2 = int(rect.right() + aliasedCoordinateDelta); + int y2 = int(rect.bottom() + aliasedCoordinateDelta); - return QRect(x1, y1, x2 - x1, y2 - y1).normalized(); + if (x2 < x1) + qSwap(x1, x2); + if (y2 < y1) + qSwap(y1, y2); + + return QRect(x1, y1, x2 - x1, y2 - y1); } /*! -- cgit v0.12 From 2cb3823e440116f331c0287b29667f7c448e3ed0 Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 24 Mar 2009 08:58:57 +1000 Subject: Import shader implementation from before the history cut. --- demos/boxes/boxes.pro | 2 - demos/boxes/glextensions.cpp | 37 - demos/boxes/glextensions.h | 85 - demos/boxes/glshaders.cpp | 266 --- demos/boxes/glshaders.h | 108 -- demos/boxes/scene.cpp | 102 +- demos/boxes/scene.h | 11 +- examples/opengl/hellogl_es2/glwidget.cpp | 391 ++-- examples/opengl/hellogl_es2/glwidget.h | 31 +- src/opengl/gl2paintengineex/qglshader_p.h | 3 +- src/opengl/opengl.pro | 6 +- src/opengl/qglextensions.cpp | 214 ++- src/opengl/qglextensions_p.h | 126 ++ src/opengl/qglpixmapfilter.cpp | 165 +- src/opengl/qglpixmapfilter_p.h | 29 - src/opengl/qglshaderprogram.cpp | 2828 +++++++++++++++++++++++++++++ src/opengl/qglshaderprogram.h | 285 +++ 17 files changed, 3619 insertions(+), 1070 deletions(-) delete mode 100644 demos/boxes/glshaders.cpp delete mode 100644 demos/boxes/glshaders.h create mode 100644 src/opengl/qglshaderprogram.cpp create mode 100644 src/opengl/qglshaderprogram.h diff --git a/demos/boxes/boxes.pro b/demos/boxes/boxes.pro index 6c1a331..a7b19a3 100644 --- a/demos/boxes/boxes.pro +++ b/demos/boxes/boxes.pro @@ -11,7 +11,6 @@ INCLUDEPATH += . HEADERS += 3rdparty/fbm.h \ glbuffers.h \ glextensions.h \ - glshaders.h \ gltrianglemesh.h \ qtbox.h \ roundedbox.h \ @@ -21,7 +20,6 @@ HEADERS += 3rdparty/fbm.h \ SOURCES += 3rdparty/fbm.c \ glbuffers.cpp \ glextensions.cpp \ - glshaders.cpp \ main.cpp \ qtbox.cpp \ roundedbox.cpp \ diff --git a/demos/boxes/glextensions.cpp b/demos/boxes/glextensions.cpp index 59256a8..5f168b6 100644 --- a/demos/boxes/glextensions.cpp +++ b/demos/boxes/glextensions.cpp @@ -47,23 +47,6 @@ bool GLExtensionFunctions::resolve(const QGLContext *context) { bool ok = true; - RESOLVE_GL_FUNC(CreateShaderObjectARB) - RESOLVE_GL_FUNC(ShaderSourceARB) - RESOLVE_GL_FUNC(CompileShaderARB) - RESOLVE_GL_FUNC(GetObjectParameterivARB) - RESOLVE_GL_FUNC(DeleteObjectARB) - RESOLVE_GL_FUNC(GetInfoLogARB) - RESOLVE_GL_FUNC(CreateProgramObjectARB) - RESOLVE_GL_FUNC(AttachObjectARB) - RESOLVE_GL_FUNC(DetachObjectARB) - RESOLVE_GL_FUNC(LinkProgramARB) - RESOLVE_GL_FUNC(UseProgramObjectARB) - RESOLVE_GL_FUNC(GetUniformLocationARB) - RESOLVE_GL_FUNC(Uniform1iARB) - RESOLVE_GL_FUNC(Uniform1fARB) - RESOLVE_GL_FUNC(Uniform4fARB) - RESOLVE_GL_FUNC(UniformMatrix4fvARB) - RESOLVE_GL_FUNC(GenFramebuffersEXT) RESOLVE_GL_FUNC(GenRenderbuffersEXT) RESOLVE_GL_FUNC(BindRenderbufferEXT) @@ -88,26 +71,6 @@ bool GLExtensionFunctions::resolve(const QGLContext *context) return ok; } -bool GLExtensionFunctions::glslSupported() { - return CreateShaderObjectARB - && CreateShaderObjectARB - && ShaderSourceARB - && CompileShaderARB - && GetObjectParameterivARB - && DeleteObjectARB - && GetInfoLogARB - && CreateProgramObjectARB - && AttachObjectARB - && DetachObjectARB - && LinkProgramARB - && UseProgramObjectARB - && GetUniformLocationARB - && Uniform1iARB - && Uniform1fARB - && Uniform4fARB - && UniformMatrix4fvARB; -} - bool GLExtensionFunctions::fboSupported() { return GenFramebuffersEXT && GenRenderbuffersEXT diff --git a/demos/boxes/glextensions.h b/demos/boxes/glextensions.h index 74617d6..4755532 100644 --- a/demos/boxes/glextensions.h +++ b/demos/boxes/glextensions.h @@ -47,23 +47,6 @@ /* Functions resolved: -glCreateShaderObjectARB -glShaderSourceARB -glCompileShaderARB -glGetObjectParameterivARB -glDeleteObjectARB -glGetInfoLogARB -glCreateProgramObjectARB -glAttachObjectARB -glDetachObjectARB -glLinkProgramARB -glUseProgramObjectARB -glGetUniformLocationARB -glUniform1iARB -glUniform1fARB -glUniform4fARB -glUniformMatrix4fvARB - glGenFramebuffersEXT glGenRenderbuffersEXT glBindRenderbufferEXT @@ -136,39 +119,6 @@ typedef ptrdiff_t GLsizeiptr; #define GL_DEPTH_ATTACHMENT_EXT 0x8D00 #endif -#ifndef GL_ARB_vertex_shader -#define GL_VERTEX_SHADER_ARB 0x8B31 -#endif - -#ifndef GL_ARB_fragment_shader -#define GL_FRAGMENT_SHADER_ARB 0x8B30 -#endif - -#ifndef GL_ARB_shader_objects -typedef char GLcharARB; -typedef unsigned int GLhandleARB; -#define GL_OBJECT_COMPILE_STATUS_ARB 0x8B81 -#define GL_OBJECT_LINK_STATUS_ARB 0x8B82 -#define GL_OBJECT_INFO_LOG_LENGTH_ARB 0x8B84 -#endif - -typedef GLhandleARB (APIENTRY *_glCreateShaderObjectARB) (GLenum); -typedef void (APIENTRY *_glShaderSourceARB) (GLhandleARB, GLuint, const GLcharARB**, GLint *); -typedef void (APIENTRY *_glCompileShaderARB) (GLhandleARB); -typedef void (APIENTRY *_glGetObjectParameterivARB) (GLhandleARB, GLenum, int *); -typedef void (APIENTRY *_glDeleteObjectARB) (GLhandleARB); -typedef void (APIENTRY *_glGetInfoLogARB) (GLhandleARB, GLsizei, GLsizei *, GLcharARB *); -typedef GLhandleARB (APIENTRY *_glCreateProgramObjectARB) (); -typedef void (APIENTRY *_glAttachObjectARB) (GLhandleARB, GLhandleARB); -typedef void (APIENTRY *_glDetachObjectARB) (GLhandleARB, GLhandleARB); -typedef void (APIENTRY *_glLinkProgramARB) (GLhandleARB); -typedef void (APIENTRY *_glUseProgramObjectARB) (GLhandleARB); -typedef GLint (APIENTRY *_glGetUniformLocationARB) (GLhandleARB, const GLcharARB *); -typedef void (APIENTRY *_glUniform1iARB) (GLint, GLint); -typedef void (APIENTRY *_glUniform1fARB) (GLint, GLfloat); -typedef void (APIENTRY *_glUniform4fARB) (GLint, GLfloat, GLfloat, GLfloat, GLfloat); -typedef void (APIENTRY *_glUniformMatrix4fvARB) (GLint, GLuint, GLboolean, const GLfloat *); - typedef void (APIENTRY *_glGenFramebuffersEXT) (GLsizei, GLuint *); typedef void (APIENTRY *_glGenRenderbuffersEXT) (GLsizei, GLuint *); typedef void (APIENTRY *_glBindRenderbufferEXT) (GLenum, GLuint); @@ -194,27 +144,9 @@ struct GLExtensionFunctions { bool resolve(const QGLContext *context); - bool glslSupported(); bool fboSupported(); bool openGL15Supported(); // the rest: multi-texture, 3D-texture, vertex buffer objects - _glCreateShaderObjectARB CreateShaderObjectARB; - _glShaderSourceARB ShaderSourceARB; - _glCompileShaderARB CompileShaderARB; - _glGetObjectParameterivARB GetObjectParameterivARB; - _glDeleteObjectARB DeleteObjectARB; - _glGetInfoLogARB GetInfoLogARB; - _glCreateProgramObjectARB CreateProgramObjectARB; - _glAttachObjectARB AttachObjectARB; - _glDetachObjectARB DetachObjectARB; - _glLinkProgramARB LinkProgramARB; - _glUseProgramObjectARB UseProgramObjectARB; - _glGetUniformLocationARB GetUniformLocationARB; - _glUniform1iARB Uniform1iARB; - _glUniform1fARB Uniform1fARB; - _glUniform4fARB Uniform4fARB; - _glUniformMatrix4fvARB UniformMatrix4fvARB; - _glGenFramebuffersEXT GenFramebuffersEXT; _glGenRenderbuffersEXT GenRenderbuffersEXT; _glBindRenderbufferEXT BindRenderbufferEXT; @@ -243,23 +175,6 @@ inline GLExtensionFunctions &getGLExtensionFunctions() return funcs; } -#define glCreateShaderObjectARB getGLExtensionFunctions().CreateShaderObjectARB -#define glShaderSourceARB getGLExtensionFunctions().ShaderSourceARB -#define glCompileShaderARB getGLExtensionFunctions().CompileShaderARB -#define glGetObjectParameterivARB getGLExtensionFunctions().GetObjectParameterivARB -#define glDeleteObjectARB getGLExtensionFunctions().DeleteObjectARB -#define glGetInfoLogARB getGLExtensionFunctions().GetInfoLogARB -#define glCreateProgramObjectARB getGLExtensionFunctions().CreateProgramObjectARB -#define glAttachObjectARB getGLExtensionFunctions().AttachObjectARB -#define glDetachObjectARB getGLExtensionFunctions().DetachObjectARB -#define glLinkProgramARB getGLExtensionFunctions().LinkProgramARB -#define glUseProgramObjectARB getGLExtensionFunctions().UseProgramObjectARB -#define glGetUniformLocationARB getGLExtensionFunctions().GetUniformLocationARB -#define glUniform1iARB getGLExtensionFunctions().Uniform1iARB -#define glUniform1fARB getGLExtensionFunctions().Uniform1fARB -#define glUniform4fARB getGLExtensionFunctions().Uniform4fARB -#define glUniformMatrix4fvARB getGLExtensionFunctions().UniformMatrix4fvARB - #define glGenFramebuffersEXT getGLExtensionFunctions().GenFramebuffersEXT #define glGenRenderbuffersEXT getGLExtensionFunctions().GenRenderbuffersEXT #define glBindRenderbufferEXT getGLExtensionFunctions().BindRenderbufferEXT diff --git a/demos/boxes/glshaders.cpp b/demos/boxes/glshaders.cpp deleted file mode 100644 index b6999a8..0000000 --- a/demos/boxes/glshaders.cpp +++ /dev/null @@ -1,266 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "glshaders.h" - -#define GLSHADERS_ASSERT_OPENGL(prefix, assertion, returnStatement) \ -if (m_failed || !(assertion)) { \ - if (!m_failed) qCritical(prefix ": The necessary OpenGL functions are not available."); \ - m_failed = true; \ - returnStatement; \ -} - - -GLShader::GLShader(const char *data, int size, GLenum shaderType) -: m_compileError(false), m_failed(false) -{ - GLSHADERS_ASSERT_OPENGL("GLShader::GLShader", - glCreateShaderObjectARB && glShaderSourceARB && glCompileShaderARB && glGetObjectParameterivARB, return) - - m_shader = glCreateShaderObjectARB(shaderType); - - GLint glSize = size; - glShaderSourceARB(m_shader, 1, &data, &glSize); - glCompileShaderARB(m_shader); - int status; - glGetObjectParameterivARB(m_shader, GL_OBJECT_COMPILE_STATUS_ARB, &status); - m_compileError = (status != 1); -} - -GLShader::GLShader(const QString& fileName, GLenum shaderType) - : m_compileError(false), m_failed(false) -{ - GLSHADERS_ASSERT_OPENGL("GLShader::GLShader", - glCreateShaderObjectARB && glShaderSourceARB && glCompileShaderARB && glGetObjectParameterivARB, return) - - m_shader = glCreateShaderObjectARB(shaderType); - - QFile file(fileName); - if (file.open(QIODevice::ReadOnly)) { - QByteArray bytes = file.readAll(); - GLint size = file.size(); - const char *p = bytes.data(); - file.close(); - glShaderSourceARB(m_shader, 1, &p, &size); - glCompileShaderARB(m_shader); - int status; - glGetObjectParameterivARB(m_shader, GL_OBJECT_COMPILE_STATUS_ARB, &status); - m_compileError = (status != 1); - } else { - m_compileError = true; - } -} - -GLShader::~GLShader() -{ - GLSHADERS_ASSERT_OPENGL("GLShader::~GLShader", glDeleteObjectARB, return) - - glDeleteObjectARB(m_shader); -} - -QString GLShader::log() -{ - GLSHADERS_ASSERT_OPENGL("GLShader::log", glGetObjectParameterivARB - && glGetInfoLogARB, return QLatin1String("GLSL not supported.")) - - int length; - glGetObjectParameterivARB(m_shader, GL_OBJECT_INFO_LOG_LENGTH_ARB, &length); - char *log = new char[length + 1]; - GLsizei glLength = length; - glGetInfoLogARB(m_shader, glLength, &glLength, log); - log[glLength] = '\0'; - QString result(log); - delete log; - return result; -} - -GLVertexShader::GLVertexShader(const char *data, int size) : GLShader(data, size, GL_VERTEX_SHADER_ARB) -{ -} - -GLVertexShader::GLVertexShader(const QString& fileName) : GLShader(fileName, GL_VERTEX_SHADER_ARB) -{ -} - -GLFragmentShader::GLFragmentShader(const char *data, int size) : GLShader(data, size, GL_FRAGMENT_SHADER_ARB) -{ -} - -GLFragmentShader::GLFragmentShader(const QString& fileName) : GLShader(fileName, GL_FRAGMENT_SHADER_ARB) -{ -} - -GLProgram::GLProgram() : m_linked(false), m_linkError(false), m_failed(false) -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::GLProgram", glCreateProgramObjectARB, return) - - m_program = glCreateProgramObjectARB(); -} - -GLProgram::~GLProgram() -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::~GLProgram", glDeleteObjectARB, return) - - glDeleteObjectARB(m_program); -} - -void GLProgram::attach(const GLShader &shader) -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::attach", glAttachObjectARB, return) - - glAttachObjectARB(m_program, shader.m_shader); - m_linked = m_linkError = false; -} - -void GLProgram::detach(const GLShader &shader) -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::detach", glDetachObjectARB, return) - - glDetachObjectARB(m_program, shader.m_shader); - m_linked = m_linkError = false; -} - -bool GLProgram::failed() -{ - if (m_failed || m_linkError) - return true; - - if (m_linked) - return false; - - GLSHADERS_ASSERT_OPENGL("GLProgram::failed", glLinkProgramARB && glGetObjectParameterivARB, return true) - - glLinkProgramARB(m_program); - int status; - glGetObjectParameterivARB(m_program, GL_OBJECT_LINK_STATUS_ARB, &status); - m_linkError = !(m_linked = (status == 1)); - return m_linkError; -} - -QString GLProgram::log() -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::log", glGetObjectParameterivARB && glGetInfoLogARB, - return QLatin1String("Failed.")) - - int length; - glGetObjectParameterivARB(m_program, GL_OBJECT_INFO_LOG_LENGTH_ARB, &length); - char *log = new char[length + 1]; - GLsizei glLength = length; - glGetInfoLogARB(m_program, glLength, &glLength, log); - log[glLength] = '\0'; - QString result(log); - delete log; - return result; -} - -void GLProgram::bind() -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::bind", glUseProgramObjectARB, return) - - if (!failed()) - glUseProgramObjectARB(m_program); -} - -void GLProgram::unbind() -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::bind", glUseProgramObjectARB, return) - - glUseProgramObjectARB(0); -} - -bool GLProgram::hasParameter(const QString& name) -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::hasParameter", glGetUniformLocationARB, return false) - - if (!failed()) { - QByteArray asciiName = name.toAscii(); - return -1 != glGetUniformLocationARB(m_program, asciiName.data()); - } - return false; -} - -void GLProgram::setInt(const QString& name, int value) -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::setInt", glGetUniformLocationARB && glUniform1iARB, return) - - if (!failed()) { - QByteArray asciiName = name.toAscii(); - int loc = glGetUniformLocationARB(m_program, asciiName.data()); - glUniform1iARB(loc, value); - } -} - -void GLProgram::setFloat(const QString& name, float value) -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::setFloat", glGetUniformLocationARB && glUniform1fARB, return) - - if (!failed()) { - QByteArray asciiName = name.toAscii(); - int loc = glGetUniformLocationARB(m_program, asciiName.data()); - glUniform1fARB(loc, value); - } -} - -void GLProgram::setColor(const QString& name, QRgb value) -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::setColor", glGetUniformLocationARB && glUniform4fARB, return) - - //qDebug() << "Setting color" << name; - if (!failed()) { - QByteArray asciiName = name.toAscii(); - int loc = glGetUniformLocationARB(m_program, asciiName.data()); - //qDebug() << "Location of" << name << "is" << loc; - QColor color(value); - glUniform4fARB(loc, color.redF(), color.greenF(), color.blueF(), color.alphaF()); - } -} - -void GLProgram::setMatrix(const QString& name, const gfx::Matrix4x4f &mat) -{ - GLSHADERS_ASSERT_OPENGL("GLProgram::setMatrix", glGetUniformLocationARB && glUniformMatrix4fvARB, return) - - if (!failed()) { - QByteArray asciiName = name.toAscii(); - int loc = glGetUniformLocationARB(m_program, asciiName.data()); - //qDebug() << "Location of" << name << "is" << loc; - glUniformMatrix4fvARB(loc, 1, GL_FALSE, mat.bits()); - } -} \ No newline at end of file diff --git a/demos/boxes/glshaders.h b/demos/boxes/glshaders.h deleted file mode 100644 index 2b6209a..0000000 --- a/demos/boxes/glshaders.h +++ /dev/null @@ -1,108 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the demonstration applications of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GLSHADERS_H -#define GLSHADERS_H - -//#include -#include "glextensions.h" - -#include -#include - -#include "vector.h" - -class GLShader -{ -public: - friend class GLProgram; - virtual ~GLShader(); - bool failed() const {return m_failed;} - QString log(); -protected: - GLShader(const char *data, int size, GLenum shaderType); - GLShader(const QString& fileName, GLenum shaderType); - - GLhandleARB m_shader; - bool m_compileError; - bool m_failed; -}; - -class GLVertexShader : public GLShader -{ -public: - GLVertexShader(const char *data, int size); - GLVertexShader(const QString& fileName); -}; - -class GLFragmentShader : public GLShader -{ -public: - GLFragmentShader(const char *data, int size); - GLFragmentShader(const QString& fileName); -}; - -class GLProgram -{ -public: - GLProgram(); - ~GLProgram(); - void attach(const GLShader &shader); - void detach(const GLShader &shader); - void bind(); - void unbind(); - bool failed(); - QString log(); - bool hasParameter(const QString& name); - // use program before setting values - void setInt(const QString& name, int value); - void setFloat(const QString& name, float value); - void setColor(const QString& name, QRgb value); - void setMatrix(const QString& name, const gfx::Matrix4x4f &mat); - // TODO: add a bunch of set-functions for different types. -private: - GLhandleARB m_program; - bool m_linked; - bool m_linkError; - bool m_failed; -}; - -#endif diff --git a/demos/boxes/scene.cpp b/demos/boxes/scene.cpp index 1040e17..e5aab75 100644 --- a/demos/boxes/scene.cpp +++ b/demos/boxes/scene.cpp @@ -531,11 +531,11 @@ Scene::~Scene() if (texture) delete texture; if (m_mainCubemap) delete m_mainCubemap; - foreach (GLProgram *program, m_programs) + foreach (QGLShaderProgram *program, m_programs) if (program) delete program; if (m_vertexShader) delete m_vertexShader; - foreach (GLFragmentShader *shader, m_fragmentShaders) + foreach (QGLShader *shader, m_fragmentShaders) if (shader) delete shader; foreach (GLRenderTargetCube *rt, m_cubemaps) if (rt) delete rt; @@ -549,16 +549,18 @@ void Scene::initGL() { m_box = new GLRoundedBox(0.25f, 1.0f, 10); - m_vertexShader = new GLVertexShader(":/res/boxes/basic.vsh"); + m_vertexShader = new QGLShader(":/res/boxes/basic.vsh", QGLShader::VertexShader); QStringList list; list << ":/res/boxes/cubemap_posx.jpg" << ":/res/boxes/cubemap_negx.jpg" << ":/res/boxes/cubemap_posy.jpg" << ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg"; m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize)); - m_environmentShader = new GLFragmentShader(environmentShaderText, strlen(environmentShaderText)); - m_environmentProgram = new GLProgram; - m_environmentProgram->attach(*m_vertexShader); - m_environmentProgram->attach(*m_environmentShader); + m_environmentShader = new QGLShader(QGLShader::FragmentShader); + m_environmentShader->setSourceCode(environmentShaderText); + m_environmentProgram = new QGLShaderProgram; + m_environmentProgram->addShader(m_vertexShader); + m_environmentProgram->addShader(m_environmentShader); + m_environmentProgram->link(); const int NOISE_SIZE = 128; // for a different size, B and BM in fbm.c must also be changed m_noise = new GLTexture3D(NOISE_SIZE, NOISE_SIZE, NOISE_SIZE); @@ -610,19 +612,19 @@ void Scene::initGL() filter = QStringList("*.fsh"); files = QDir(":/res/boxes/").entryInfoList(filter, QDir::Files | QDir::Readable); foreach (QFileInfo file, files) { - GLProgram *program = new GLProgram; - GLFragmentShader* shader = new GLFragmentShader(file.absoluteFilePath()); + QGLShaderProgram *program = new QGLShaderProgram; + QGLShader* shader = new QGLShader(file.absoluteFilePath(), QGLShader::FragmentShader); // The program does not take ownership over the shaders, so store them in a vector so they can be deleted afterwards. - program->attach(*m_vertexShader); - program->attach(*shader); - if (program->failed()) { + program->addShader(m_vertexShader); + program->addShader(shader); + if (!program->link()) { qWarning("Failed to compile and link shader program"); qWarning("Vertex shader log:"); - qWarning() << m_vertexShader->log(); + qWarning() << m_vertexShader->errors(); qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):"; - qWarning() << shader->log(); + qWarning() << shader->errors(); qWarning("Shader program log:"); - qWarning() << program->log(); + qWarning() << program->errors(); delete shader; delete program; @@ -633,13 +635,13 @@ void Scene::initGL() m_programs << program; m_renderOptions->addShader(file.baseName()); - program->bind(); - m_cubemaps << (program->hasParameter("env") ? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : 0); - program->unbind(); + program->enable(); + m_cubemaps << ((program->uniformLocation("env") != -1) ? new GLRenderTargetCube(qMin(256, m_maxTextureSize)) : 0); + program->disable(); } if (m_programs.size() == 0) - m_programs << new GLProgram; + m_programs << new QGLShaderProgram; m_renderOptions->emitParameterChanged(); } @@ -674,12 +676,12 @@ void Scene::renderBoxes(const gfx::Matrix4x4f &view, int excludeBox) // Don't render the environment if the environment texture can't be set for the correct sampler. if (glActiveTexture) { m_environment->bind(); - m_environmentProgram->bind(); - m_environmentProgram->setInt("tex", 0); - m_environmentProgram->setInt("env", 1); - m_environmentProgram->setInt("noise", 2); + m_environmentProgram->enable(); + m_environmentProgram->setUniformValue("tex", 0); + m_environmentProgram->setUniformValue("env", 1); + m_environmentProgram->setUniformValue("noise", 2); m_box->draw(); - m_environmentProgram->unbind(); + m_environmentProgram->disable(); m_environment->unbind(); } @@ -707,14 +709,18 @@ void Scene::renderBoxes(const gfx::Matrix4x4f &view, int excludeBox) else m_environment->bind(); } - m_programs[i]->bind(); - m_programs[i]->setInt("tex", 0); - m_programs[i]->setInt("env", 1); - m_programs[i]->setInt("noise", 2); - m_programs[i]->setMatrix("view", view); - m_programs[i]->setMatrix("invView", invView); + m_programs[i]->enable(); + m_programs[i]->setUniformValue("tex", 0); + m_programs[i]->setUniformValue("env", 1); + m_programs[i]->setUniformValue("noise", 2); + QMatrix4x4 mview; + QMatrix4x4 minvview; + memcpy(mview.data(), view.bits(), sizeof(float) * 16); + memcpy(minvview.data(), invView.bits(), sizeof(float) * 16); + m_programs[i]->setUniformValue("view", mview); + m_programs[i]->setUniformValue("invView", minvview); m_box->draw(); - m_programs[i]->unbind(); + m_programs[i]->disable(); if (glActiveTexture) { if (m_dynamicCubemap && m_cubemaps[i]) @@ -737,14 +743,18 @@ void Scene::renderBoxes(const gfx::Matrix4x4f &view, int excludeBox) m_environment->bind(); } - m_programs[m_currentShader]->bind(); - m_programs[m_currentShader]->setInt("tex", 0); - m_programs[m_currentShader]->setInt("env", 1); - m_programs[m_currentShader]->setInt("noise", 2); - m_programs[m_currentShader]->setMatrix("view", view); - m_programs[m_currentShader]->setMatrix("invView", invView); + m_programs[m_currentShader]->enable(); + m_programs[m_currentShader]->setUniformValue("tex", 0); + m_programs[m_currentShader]->setUniformValue("env", 1); + m_programs[m_currentShader]->setUniformValue("noise", 2); + QMatrix4x4 mview; + QMatrix4x4 minvview; + memcpy(mview.data(), view.bits(), sizeof(float) * 16); + memcpy(minvview.data(), invView.bits(), sizeof(float) * 16); + m_programs[m_currentShader]->setUniformValue("view", mview); + m_programs[m_currentShader]->setUniformValue("invView", minvview); m_box->draw(); - m_programs[m_currentShader]->unbind(); + m_programs[m_currentShader]->disable(); if (glActiveTexture) { if (m_dynamicCubemap) @@ -1021,20 +1031,20 @@ void Scene::toggleDynamicCubemap(int state) void Scene::setColorParameter(const QString &name, QRgb color) { // set the color in all programs - foreach (GLProgram *program, m_programs) { - program->bind(); - program->setColor(name, color); - program->unbind(); + foreach (QGLShaderProgram *program, m_programs) { + program->enable(); + program->setUniformValue(program->uniformLocation(name), QColor(color)); + program->disable(); } } void Scene::setFloatParameter(const QString &name, float value) { // set the color in all programs - foreach (GLProgram *program, m_programs) { - program->bind(); - program->setFloat(name, value); - program->unbind(); + foreach (QGLShaderProgram *program, m_programs) { + program->enable(); + program->setUniformValue(program->uniformLocation(name), value); + program->disable(); } } diff --git a/demos/boxes/scene.h b/demos/boxes/scene.h index 2db9317..c056739 100644 --- a/demos/boxes/scene.h +++ b/demos/boxes/scene.h @@ -53,7 +53,6 @@ #include "vector.h" #include "trackball.h" #include "glbuffers.h" -#include "glshaders.h" #include "qtbox.h" #define PI 3.14159265358979 @@ -231,11 +230,11 @@ private: GLTexture3D *m_noise; GLRenderTargetCube *m_mainCubemap; QVector m_cubemaps; - QVector m_programs; - GLVertexShader *m_vertexShader; - QVector m_fragmentShaders; - GLFragmentShader *m_environmentShader; - GLProgram *m_environmentProgram; + QVector m_programs; + QGLShader *m_vertexShader; + QVector m_fragmentShaders; + QGLShader *m_environmentShader; + QGLShaderProgram *m_environmentProgram; }; diff --git a/examples/opengl/hellogl_es2/glwidget.cpp b/examples/opengl/hellogl_es2/glwidget.cpp index 213c5b2..ee50670 100644 --- a/examples/opengl/hellogl_es2/glwidget.cpp +++ b/examples/opengl/hellogl_es2/glwidget.cpp @@ -48,124 +48,10 @@ const int bubbleNum = 8; -inline void CrossProduct(qreal &xOut, qreal &yOut, qreal &zOut, qreal x1, qreal y1, qreal z1, qreal x2, qreal y2, qreal z2) -{ - xOut = y1 * z2 - z1 * y2; - yOut = z1 * x2 - x1 * z2; - zOut = x1 * y2 - y1 * x2; -} - -inline void Normalize(qreal &x, qreal &y, qreal &z) -{ - qreal l = sqrt(x*x + y*y + z*z); - x = x / l; - y = y / l; - z = z / l; -} - -inline void IdentityMatrix(GLfloat *m) -{ - m[0 * 4 + 0] = 1.0f; - m[1 * 4 + 0] = 0.0f; - m[2 * 4 + 0] = 0.0f; - m[3 * 4 + 0] = 0.0f; - m[0 * 4 + 1] = 0.0f; - m[1 * 4 + 1] = 1.0f; - m[2 * 4 + 1] = 0.0f; - m[3 * 4 + 1] = 0.0f; - m[0 * 4 + 2] = 0.0f; - m[1 * 4 + 2] = 0.0f; - m[2 * 4 + 2] = 1.0f; - m[3 * 4 + 2] = 0.0f; - m[0 * 4 + 3] = 0.0f; - m[1 * 4 + 3] = 0.0f; - m[2 * 4 + 3] = 0.0f; - m[3 * 4 + 3] = 1.0f; -} - -// Adjust a 4x4 matrix to apply a scale. -inline void ScaleMatrix(GLfloat *m, GLfloat scalex, GLfloat scaley, GLfloat scalez) -{ - m[0 * 4 + 0] *= scalex; - m[0 * 4 + 1] *= scalex; - m[0 * 4 + 2] *= scalex; - m[0 * 4 + 3] *= scalex; - m[1 * 4 + 0] *= scaley; - m[1 * 4 + 1] *= scaley; - m[1 * 4 + 2] *= scaley; - m[1 * 4 + 3] *= scaley; - m[2 * 4 + 0] *= scalez; - m[2 * 4 + 1] *= scalez; - m[2 * 4 + 2] *= scalez; - m[2 * 4 + 3] *= scalez; -} - -// Adjust a 4x4 matrix to apply a translation. -inline void TranslateMatrix(GLfloat *m, GLfloat translatex, GLfloat translatey, GLfloat translatez) -{ - m[3 * 4 + 0] += m[0 * 4 + 0] * translatex + m[1 * 4 + 0] * translatey + m[2 * 4 + 0] * translatez; - m[3 * 4 + 1] += m[0 * 4 + 1] * translatex + m[1 * 4 + 1] * translatey + m[2 * 4 + 1] * translatez; - m[3 * 4 + 2] += m[0 * 4 + 2] * translatex + m[1 * 4 + 2] * translatey + m[2 * 4 + 2] * translatez; - m[3 * 4 + 3] += m[0 * 4 + 3] * translatex + m[1 * 4 + 3] * translatey + m[2 * 4 + 3] * translatez; -} - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -// Adjust a 4x4 matrix to apply a rotation. -inline void RotateMatrix(GLfloat *m, GLfloat angle, GLfloat vx, GLfloat vy, GLfloat vz) -{ - GLfloat len = sqrt(vx * vx + vy * vy + vz * vz); - if (len != 0) { - vx /= len; - vy /= len; - vz /= len; - } - - GLfloat c, s, ic; - c = cos(angle * M_PI / 180.0); - s = sin(angle * M_PI / 180.0); - ic = 1.0f - c; - - GLfloat rot[16]; - rot[0 * 4 + 0] = vx * vx * ic + c; - rot[1 * 4 + 0] = vx * vy * ic - vz * s; - rot[2 * 4 + 0] = vx * vz * ic + vy * s; - rot[3 * 4 + 0] = 0.0f; - rot[0 * 4 + 1] = vy * vx * ic + vz * s; - rot[1 * 4 + 1] = vy * vy * ic + c; - rot[2 * 4 + 1] = vy * vz * ic - vx * s; - rot[3 * 4 + 1] = 0.0f; - rot[0 * 4 + 2] = vx * vz * ic - vy * s; - rot[1 * 4 + 2] = vy * vz * ic + vx * s; - rot[2 * 4 + 2] = vz * vz * ic + c; - rot[3 * 4 + 2] = 0.0f; - rot[0 * 4 + 3] = 0.0f; - rot[1 * 4 + 3] = 0.0f; - rot[2 * 4 + 3] = 0.0f; - rot[3 * 4 + 3] = 1.0f; - - GLfloat temp[16]; - for (int i = 0; i < 4; ++i) { - for (int j = 0; j < 4; ++j) { - temp[j * 4 + i] = 0.0f; - for (int k = 0; k < 4; ++k) { - temp[j * 4 + i] += m[k * 4 + i] * rot[j * 4 + k]; - } - } - } - - qMemCopy(m, temp, sizeof(temp)); -} - GLWidget::GLWidget(QWidget *parent) : QGLWidget(parent) { qtLogo = true; - createdVertices = 0; - createdNormals = 0; - m_vertexNumber = 0; frames = 0; setAttribute(Qt::WA_PaintOnScreen); setAttribute(Qt::WA_NoSystemBackground); @@ -178,10 +64,6 @@ GLWidget::GLWidget(QWidget *parent) GLWidget::~GLWidget() { - if (createdVertices) - delete[] createdVertices; - if (createdNormals) - delete[] createdNormals; } void GLWidget::setScaling(int scale) { @@ -210,13 +92,11 @@ void GLWidget::showBubbles(bool bubbles) void GLWidget::paintQtLogo() { glDisable(GL_TEXTURE_2D); - glVertexAttribPointer(vertexAttr1, 3, GL_FLOAT, GL_FALSE, 0, createdVertices); - glEnableVertexAttribArray(vertexAttr1); - glVertexAttribPointer(normalAttr1, 3, GL_FLOAT, GL_FALSE, 0, createdNormals); - glEnableVertexAttribArray(normalAttr1); - glDrawArrays(GL_TRIANGLES, 0, m_vertexNumber / 3); - glDisableVertexAttribArray(normalAttr1); - glDisableVertexAttribArray(vertexAttr1); + program1.setAttributeArray(vertexAttr1, vertices.constData()); + program1.setAttributeArray(normalAttr1, normals.constData()); + glDrawArrays(GL_TRIANGLES, 0, vertices.size()); + program1.disableAttributeArray(normalAttr1); + program1.disableAttributeArray(vertexAttr1); } void GLWidget::paintTexturedCube() @@ -239,8 +119,7 @@ void GLWidget::paintTexturedCube() -0.5, -0.5, -0.5, -0.5, -0.5, 0.5, 0.5, -0.5, -0.5, 0.5, -0.5, 0.5, 0.5, -0.5, -0.5, -0.5, -0.5, 0.5 }; - glVertexAttribPointer(vertexAttr2, 3, GL_FLOAT, GL_FALSE, 0, afVertices); - glEnableVertexAttribArray(vertexAttr2); + program2.setAttributeArray(vertexAttr2, afVertices, 3); GLfloat afTexCoord[] = { 0.0f,0.0f, 1.0f,1.0f, 1.0f,0.0f, @@ -258,8 +137,7 @@ void GLWidget::paintTexturedCube() 1.0f,0.0f, 1.0f,1.0f, 0.0f,0.0f, 0.0f,1.0f, 0.0f,0.0f, 1.0f,1.0f }; - glVertexAttribPointer(texCoordAttr2, 2, GL_FLOAT, GL_FALSE, 0, afTexCoord); - glEnableVertexAttribArray(texCoordAttr2); + program2.setAttributeArray(texCoordAttr2, afTexCoord, 2); GLfloat afNormals[] = { @@ -278,50 +156,15 @@ void GLWidget::paintTexturedCube() 0,1,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0, 0,1,0 }; - glVertexAttribPointer(normalAttr2, 3, GL_FLOAT, GL_FALSE, 0, afNormals); - glEnableVertexAttribArray(normalAttr2); + program2.setAttributeArray(normalAttr2, afNormals, 3); - glUniform1i(textureUniform2, 0); // use texture unit 0 + program2.setUniformValue(textureUniform2, 0); // use texture unit 0 glDrawArrays(GL_TRIANGLES, 0, 36); - glDisableVertexAttribArray(vertexAttr2); - glDisableVertexAttribArray(normalAttr2); - glDisableVertexAttribArray(texCoordAttr2); -} - -static void reportCompileErrors(GLuint shader, const char *src) -{ - GLint value = 0; - glGetShaderiv(shader, GL_COMPILE_STATUS, &value); - bool compiled = (value != 0); - value = 0; - glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &value); - if (!compiled && value > 1) { - char *log = new char [value]; - GLint len; - glGetShaderInfoLog(shader, value, &len, log); - qWarning("%s\n", log); - qWarning("when compiling:\n%s\n", src); - delete [] log; - } -} - -static void reportLinkErrors(GLuint program, const char *vsrc, const char *fsrc) -{ - GLint value = 0; - glGetProgramiv(program, GL_LINK_STATUS, &value); - bool linked = (value != 0); - value = 0; - glGetProgramiv(program, GL_INFO_LOG_LENGTH, &value); - if (!linked && value > 1) { - char *log = new char [value]; - GLint len; - glGetProgramInfoLog(program, value, &len, log); - qWarning("%s\n", log); - qWarning("when linking:\n%s\nwith:\n%s\n", vsrc, fsrc); - delete [] log; - } + program2.disableAttributeArray(vertexAttr2); + program2.disableAttributeArray(normalAttr2); + program2.disableAttributeArray(texCoordAttr2); } void GLWidget::initializeGL () @@ -332,8 +175,8 @@ void GLWidget::initializeGL () glGenTextures(1, &m_uiTexture); m_uiTexture = bindTexture(QImage(":/qt.png")); - GLuint vshader1 = glCreateShader(GL_VERTEX_SHADER); - const char *vsrc1[1] = { + QGLShader *vshader1 = new QGLShader(QGLShader::VertexShader, this); + const char *vsrc1 = "attribute highp vec4 vertex;\n" "attribute mediump vec3 normal;\n" "uniform mediump mat4 matrix;\n" @@ -346,36 +189,28 @@ void GLWidget::initializeGL () " color = vec4(col * 0.2 + col * 0.8 * angle, 1.0);\n" " color = clamp(color, 0.0, 1.0);\n" " gl_Position = matrix * vertex;\n" - "}\n" - }; - glShaderSource(vshader1, 1, vsrc1, 0); - glCompileShader(vshader1); - reportCompileErrors(vshader1, vsrc1[0]); + "}\n"; + vshader1->setSourceCode(vsrc1); - GLuint fshader1 = glCreateShader(GL_FRAGMENT_SHADER); - const char *fsrc1[1] = { + QGLShader *fshader1 = new QGLShader(QGLShader::FragmentShader, this); + const char *fsrc1 = "varying mediump vec4 color;\n" "void main(void)\n" "{\n" " gl_FragColor = color;\n" - "}\n" - }; - glShaderSource(fshader1, 1, fsrc1, 0); - glCompileShader(fshader1); - reportCompileErrors(fshader1, fsrc1[0]); - - program1 = glCreateProgram(); - glAttachShader(program1, vshader1); - glAttachShader(program1, fshader1); - glLinkProgram(program1); - reportLinkErrors(program1, vsrc1[0], fsrc1[0]); - - vertexAttr1 = glGetAttribLocation(program1, "vertex"); - normalAttr1 = glGetAttribLocation(program1, "normal"); - matrixUniform1 = glGetUniformLocation(program1, "matrix"); - - GLuint vshader2 = glCreateShader(GL_VERTEX_SHADER); - const char *vsrc2[1] = { + "}\n"; + fshader1->setSourceCode(fsrc1); + + program1.addShader(vshader1); + program1.addShader(fshader1); + program1.link(); + + vertexAttr1 = program1.attributeLocation("vertex"); + normalAttr1 = program1.attributeLocation("normal"); + matrixUniform1 = program1.uniformLocation("matrix"); + + QGLShader *vshader2 = new QGLShader(QGLShader::VertexShader); + const char *vsrc2 = "attribute highp vec4 vertex;\n" "attribute highp vec4 texCoord;\n" "attribute mediump vec3 normal;\n" @@ -388,14 +223,11 @@ void GLWidget::initializeGL () " angle = max(dot(normal, toLight), 0.0);\n" " gl_Position = matrix * vertex;\n" " texc = texCoord;\n" - "}\n" - }; - glShaderSource(vshader2, 1, vsrc2, 0); - glCompileShader(vshader2); - reportCompileErrors(vshader2, vsrc2[0]); + "}\n"; + vshader2->setSourceCode(vsrc2); - GLuint fshader2 = glCreateShader(GL_FRAGMENT_SHADER); - const char *fsrc2[1] = { + QGLShader *fshader2 = new QGLShader(QGLShader::FragmentShader); + const char *fsrc2 = "varying highp vec4 texc;\n" "uniform sampler2D tex;\n" "varying mediump float angle;\n" @@ -404,23 +236,18 @@ void GLWidget::initializeGL () " highp vec3 color = texture2D(tex, texc.st).rgb;\n" " color = color * 0.2 + color * 0.8 * angle;\n" " gl_FragColor = vec4(clamp(color, 0.0, 1.0), 1.0);\n" - "}\n" - }; - glShaderSource(fshader2, 1, fsrc2, 0); - glCompileShader(fshader2); - reportCompileErrors(fshader2, fsrc2[0]); - - program2 = glCreateProgram(); - glAttachShader(program2, vshader2); - glAttachShader(program2, fshader2); - glLinkProgram(program2); - reportLinkErrors(program2, vsrc2[0], fsrc2[0]); - - vertexAttr2 = glGetAttribLocation(program2, "vertex"); - normalAttr2 = glGetAttribLocation(program2, "normal"); - texCoordAttr2 = glGetAttribLocation(program2, "texCoord"); - matrixUniform2 = glGetUniformLocation(program2, "matrix"); - textureUniform2 = glGetUniformLocation(program2, "tex"); + "}\n"; + fshader2->setSourceCode(fsrc2); + + program2.addShader(vshader2); + program2.addShader(fshader2); + program2.link(); + + vertexAttr2 = program2.attributeLocation("vertex"); + normalAttr2 = program2.attributeLocation("normal"); + texCoordAttr2 = program2.attributeLocation("texCoord"); + matrixUniform2 = program2.uniformLocation("matrix"); + textureUniform2 = program2.uniformLocation("tex"); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); @@ -450,24 +277,23 @@ void GLWidget::paintGL() glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); - GLfloat modelview[16]; - IdentityMatrix(modelview); - RotateMatrix(modelview, m_fAngle, 0.0, 1.0, 0.0); - RotateMatrix(modelview, m_fAngle, 1.0, 0.0, 0.0); - RotateMatrix(modelview, m_fAngle, 0.0, 0.0, 1.0); - ScaleMatrix(modelview, m_fScale, m_fScale, m_fScale); - TranslateMatrix(modelview, 0, -0.2, 0); + QMatrix4x4 modelview; + modelview.rotate(m_fAngle, 0.0f, 1.0f, 0.0f); + modelview.rotate(m_fAngle, 1.0f, 0.0f, 0.0f); + modelview.rotate(m_fAngle, 0.0f, 0.0f, 1.0f); + modelview.scale(m_fScale); + modelview.translate(0.0f, -0.2f, 0.0f); if (qtLogo) { - glUseProgram(program1); - glUniformMatrix4fv(matrixUniform1, 1, GL_FALSE, modelview); + program1.enable(); + program1.setUniformValue(matrixUniform1, modelview); paintQtLogo(); - glUseProgram(0); + program1.disable(); } else { - glUseProgram(program2); - glUniformMatrix4fv(matrixUniform2, 1, GL_FALSE, modelview); + program2.enable(); + program1.setUniformValue(matrixUniform2, modelview); paintTexturedCube(); - glUseProgram(0); + program2.disable(); } glDisable(GL_DEPTH_TEST); @@ -563,80 +389,69 @@ void GLWidget::createGeometry() extrude(x8, y8, x5, y5); } - m_vertexNumber = vertices.size(); - createdVertices = new GLfloat[m_vertexNumber]; - createdNormals = new GLfloat[m_vertexNumber]; - for (int i = 0;i < m_vertexNumber;i++) { - createdVertices[i] = vertices.at(i) * 2; - createdNormals[i] = normals.at(i); - } - vertices.clear(); - normals.clear(); + for (int i = 0;i < vertices.size();i++) + vertices[i] *= 2.0f; } void GLWidget::quad(qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal x4, qreal y4) { - qreal nx, ny, nz; + vertices << QVector3D(x1, y1, -0.05f); + vertices << QVector3D(x2, y2, -0.05f); + vertices << QVector3D(x4, y4, -0.05f); - vertices << x1 << y1 << -0.05f; - vertices << x2 << y2 << -0.05f; - vertices << x4 << y4 << -0.05f; + vertices << QVector3D(x3, y3, -0.05f); + vertices << QVector3D(x4, y4, -0.05f); + vertices << QVector3D(x2, y2, -0.05f); - vertices << x3 << y3 << -0.05f; - vertices << x4 << y4 << -0.05f; - vertices << x2 << y2 << -0.05f; + QVector3D n = QVector3D::normal + (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(x4 - x1, y4 - y1, 0.0f)); - CrossProduct(nx, ny, nz, x2 - x1, y2 - y1, 0, x4 - x1, y4 - y1, 0); - Normalize(nx, ny, nz); + normals << n; + normals << n; + normals << n; - normals << nx << ny << nz; - normals << nx << ny << nz; - normals << nx << ny << nz; + normals << n; + normals << n; + normals << n; - normals << nx << ny << nz; - normals << nx << ny << nz; - normals << nx << ny << nz; + vertices << QVector3D(x4, y4, 0.05f); + vertices << QVector3D(x2, y2, 0.05f); + vertices << QVector3D(x1, y1, 0.05f); - vertices << x4 << y4 << 0.05f; - vertices << x2 << y2 << 0.05f; - vertices << x1 << y1 << 0.05f; + vertices << QVector3D(x2, y2, 0.05f); + vertices << QVector3D(x4, y4, 0.05f); + vertices << QVector3D(x3, y3, 0.05f); - vertices << x2 << y2 << 0.05f; - vertices << x4 << y4 << 0.05f; - vertices << x3 << y3 << 0.05f; + n = QVector3D::normal + (QVector3D(x2 - x4, y2 - y4, 0.0f), QVector3D(x1 - x4, y1 - y4, 0.0f)); - CrossProduct(nx, ny, nz, x2 - x4, y2 - y4, 0, x1 - x4, y1 - y4, 0); - Normalize(nx, ny, nz); + normals << n; + normals << n; + normals << n; - normals << nx << ny << nz; - normals << nx << ny << nz; - normals << nx << ny << nz; - - normals << nx << ny << nz; - normals << nx << ny << nz; - normals << nx << ny << nz; + normals << n; + normals << n; + normals << n; } void GLWidget::extrude(qreal x1, qreal y1, qreal x2, qreal y2) { - qreal nx, ny, nz; - - vertices << x1 << y1 << +0.05f; - vertices << x2 << y2 << +0.05f; - vertices << x1 << y1 << -0.05f; + vertices << QVector3D(x1, y1, +0.05f); + vertices << QVector3D(x2, y2, +0.05f); + vertices << QVector3D(x1, y1, -0.05f); - vertices << x2 << y2 << -0.05f; - vertices << x1 << y1 << -0.05f; - vertices << x2 << y2 << +0.05f; + vertices << QVector3D(x2, y2, -0.05f); + vertices << QVector3D(x1, y1, -0.05f); + vertices << QVector3D(x2, y2, +0.05f); - CrossProduct(nx, ny, nz, x2 - x1, y2 - y1, 0.0f, 0.0f, 0.0f, -0.1f); - Normalize(nx, ny, nz); + QVector3D n = QVector3D::normal + (QVector3D(x2 - x1, y2 - y1, 0.0f), QVector3D(0.0f, 0.0f, -0.1f)); - normals << nx << ny << nz; - normals << nx << ny << nz; - normals << nx << ny << nz; + normals << n; + normals << n; + normals << n; - normals << nx << ny << nz; - normals << nx << ny << nz; - normals << nx << ny << nz; + normals << n; + normals << n; + normals << n; } diff --git a/examples/opengl/hellogl_es2/glwidget.h b/examples/opengl/hellogl_es2/glwidget.h index 9a7823a..596e1cc 100644 --- a/examples/opengl/hellogl_es2/glwidget.h +++ b/examples/opengl/hellogl_es2/glwidget.h @@ -43,7 +43,11 @@ #define GLWIDGET_H #include +#include +#include +#include #include +#include class Bubble; class GLWidget : public QGLWidget { @@ -71,24 +75,21 @@ private: void createBubbles(int number); void quad(qreal x1, qreal y1, qreal x2, qreal y2, qreal x3, qreal y3, qreal x4, qreal y4); void extrude(qreal x1, qreal y1, qreal x2, qreal y2); - QList vertices; - QList normals; - GLfloat *createdVertices; - GLfloat *createdNormals; - int m_vertexNumber; + QVector vertices; + QVector normals; bool qtLogo; QList bubbles; int frames; QTime time; - GLuint program1; - GLuint program2; - GLuint vertexAttr1; - GLuint normalAttr1; - GLuint matrixUniform1; - GLuint vertexAttr2; - GLuint normalAttr2; - GLuint texCoordAttr2; - GLuint matrixUniform2; - GLuint textureUniform2; + QGLShaderProgram program1; + QGLShaderProgram program2; + int vertexAttr1; + int normalAttr1; + int matrixUniform1; + int vertexAttr2; + int normalAttr2; + int texCoordAttr2; + int matrixUniform2; + int textureUniform2; }; #endif diff --git a/src/opengl/gl2paintengineex/qglshader_p.h b/src/opengl/gl2paintengineex/qglshader_p.h index 4cbf3f6..64c9a42 100644 --- a/src/opengl/gl2paintengineex/qglshader_p.h +++ b/src/opengl/gl2paintengineex/qglshader_p.h @@ -81,7 +81,8 @@ SAMPLER_2D_SHADOW. #include -#include +#define QGLShader QGLEngineShader +#define QGLShaderProgram QGLEngineShaderProgram typedef struct { GLfloat a; diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro index af16312..3b8bfa1 100644 --- a/src/opengl/opengl.pro +++ b/src/opengl/opengl.pro @@ -25,14 +25,16 @@ HEADERS += qgl.h \ qglcolormap.h \ qglpixelbuffer.h \ qglframebufferobject.h \ - qglpixmapfilter_p.h + qglpixmapfilter_p.h \ + qglshaderprogram.h SOURCES += qgl.cpp \ qglcolormap.cpp \ qglpixelbuffer.cpp \ qglframebufferobject.cpp \ qglextensions.cpp \ - qglpixmapfilter.cpp + qglpixmapfilter.cpp \ + qglshaderprogram.cpp #!contains(QT_CONFIG, opengles2) { # HEADERS += qpaintengine_opengl_p.h diff --git a/src/opengl/qglextensions.cpp b/src/opengl/qglextensions.cpp index e6ac043..5fda346 100644 --- a/src/opengl/qglextensions.cpp +++ b/src/opengl/qglextensions.cpp @@ -153,55 +153,179 @@ bool qt_resolve_buffer_extensions(QGLContext *ctx) bool qt_resolve_glsl_extensions(QGLContext *ctx) { +#if defined(QT_OPENGL_ES_2) + // The GLSL shader functions are always present in OpenGL/ES 2.0. + // The only exceptions are glGetProgramBinaryOES and glProgramBinaryOES. + if (!QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glslResolved) { + glGetProgramBinaryOES = (_glGetProgramBinaryOES) ctx->getProcAddress(QLatin1String("glGetProgramBinaryOES")); + glProgramBinaryOES = (_glProgramBinaryOES) ctx->getProcAddress(QLatin1String("glProgramBinaryOES")); + QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glslResolved = true; + } + return true; +#else if (glCreateShader) return true; glCreateShader = (_glCreateShader) ctx->getProcAddress(QLatin1String("glCreateShader")); - glShaderSource = (_glShaderSource) ctx->getProcAddress(QLatin1String("glShaderSource")); - glCompileShader = (_glCompileShader) ctx->getProcAddress(QLatin1String("glCompileShader")); - glDeleteShader = (_glDeleteShader) ctx->getProcAddress(QLatin1String("glDeleteShader")); - - glCreateProgram = (_glCreateProgram) ctx->getProcAddress(QLatin1String("glCreateProgram")); - glAttachShader = (_glAttachShader) ctx->getProcAddress(QLatin1String("glAttachShader")); - glDetachShader = (_glDetachShader) ctx->getProcAddress(QLatin1String("glDetachShader")); - glLinkProgram = (_glLinkProgram) ctx->getProcAddress(QLatin1String("glLinkProgram")); - glUseProgram = (_glUseProgram) ctx->getProcAddress(QLatin1String("glUseProgram")); - glDeleteProgram = (_glDeleteProgram) ctx->getProcAddress(QLatin1String("glDeleteProgram")); - - glGetShaderInfoLog = (_glGetShaderInfoLog) ctx->getProcAddress(QLatin1String("glGetShaderInfoLog")); - glGetShaderiv = (_glGetShaderiv) ctx->getProcAddress(QLatin1String("glGetShaderiv")); - glGetProgramiv = (_glGetProgramiv) ctx->getProcAddress(QLatin1String("glGetProgramiv")); - - glGetUniformLocation = (_glGetUniformLocation) ctx->getProcAddress(QLatin1String("glGetUniformLocation")); - glUniform4fv = (_glUniform4fv) ctx->getProcAddress(QLatin1String("glUniform4fv")); - glUniform3fv = (_glUniform3fv) ctx->getProcAddress(QLatin1String("glUniform3fv")); - glUniform2fv = (_glUniform2fv) ctx->getProcAddress(QLatin1String("glUniform2fv")); - glUniform1fv = (_glUniform1fv) ctx->getProcAddress(QLatin1String("glUniform1fv")); - glUniform1i = (_glUniform1i) ctx->getProcAddress(QLatin1String("glUniform1i")); - - glGetActiveAttrib = (_glGetActiveAttrib) ctx->getProcAddress(QLatin1String("glGetActiveAttrib")); - glGetAttribLocation = (_glGetAttribLocation) ctx->getProcAddress(QLatin1String("glGetAttribLocation")); - glGetActiveUniform = (_glGetActiveUniform) ctx->getProcAddress(QLatin1String("glGetActiveUniform")); - glGetProgramInfoLog = (_glGetProgramInfoLog) ctx->getProcAddress(QLatin1String("glGetProgramInfoLog")); - glUniform1f = (_glUniform1f) ctx->getProcAddress(QLatin1String("glUniform1f")); - glUniform2f = (_glUniform2f) ctx->getProcAddress(QLatin1String("glUniform2f")); - glUniform4f = (_glUniform4f) ctx->getProcAddress(QLatin1String("glUniform4f")); - glUniformMatrix2fv = (_glUniformMatrix2fv) ctx->getProcAddress(QLatin1String("glUniformMatrix2fv")); - glUniformMatrix3fv = (_glUniformMatrix3fv) ctx->getProcAddress(QLatin1String("glUniformMatrix3fv")); - glUniformMatrix4fv = (_glUniformMatrix4fv) ctx->getProcAddress(QLatin1String("glUniformMatrix4fv")); - glEnableVertexAttribArray = (_glEnableVertexAttribArray) ctx->getProcAddress(QLatin1String("glEnableVertexAttribArray")); - glDisableVertexAttribArray = (_glDisableVertexAttribArray) ctx->getProcAddress(QLatin1String("glDisableVertexAttribArray")); - glVertexAttribPointer = (_glVertexAttribPointer) ctx->getProcAddress(QLatin1String("glVertexAttribPointer")); - glStencilOpSeparate = (_glStencilOpSeparate) ctx->getProcAddress(QLatin1String("glStencilOpSeparate")); - - return glCreateShader && glShaderSource && glCompileShader && glDeleteProgram && - glCreateProgram && glAttachShader && glDetachShader && glLinkProgram && glUseProgram && - glDeleteProgram && glGetShaderInfoLog && glGetShaderiv && glGetProgramiv && glGetUniformLocation && - glUniform1i && glUniform1fv && glUniform2fv && glUniform3fv && glUniform4fv && - glGetActiveAttrib && glGetAttribLocation && glGetActiveUniform && glGetProgramInfoLog && - glUniform1f && glUniform2f && glUniform4f && - glUniformMatrix2fv && glUniformMatrix3fv && glUniformMatrix4fv && - glEnableVertexAttribArray && glDisableVertexAttribArray && glVertexAttribPointer && glStencilOpSeparate; + if (glCreateShader) { + glShaderSource = (_glShaderSource) ctx->getProcAddress(QLatin1String("glShaderSource")); + glShaderBinary = (_glShaderBinary) ctx->getProcAddress(QLatin1String("glShaderBinary")); + glCompileShader = (_glCompileShader) ctx->getProcAddress(QLatin1String("glCompileShader")); + glDeleteShader = (_glDeleteShader) ctx->getProcAddress(QLatin1String("glDeleteShader")); + glIsShader = (_glIsShader) ctx->getProcAddress(QLatin1String("glIsShader")); + + glCreateProgram = (_glCreateProgram) ctx->getProcAddress(QLatin1String("glCreateProgram")); + glAttachShader = (_glAttachShader) ctx->getProcAddress(QLatin1String("glAttachShader")); + glDetachShader = (_glDetachShader) ctx->getProcAddress(QLatin1String("glDetachShader")); + glLinkProgram = (_glLinkProgram) ctx->getProcAddress(QLatin1String("glLinkProgram")); + glUseProgram = (_glUseProgram) ctx->getProcAddress(QLatin1String("glUseProgram")); + glDeleteProgram = (_glDeleteProgram) ctx->getProcAddress(QLatin1String("glDeleteProgram")); + glIsProgram = (_glIsProgram) ctx->getProcAddress(QLatin1String("glIsProgram")); + + glGetShaderInfoLog = (_glGetShaderInfoLog) ctx->getProcAddress(QLatin1String("glGetShaderInfoLog")); + glGetShaderiv = (_glGetShaderiv) ctx->getProcAddress(QLatin1String("glGetShaderiv")); + glGetShaderSource = (_glGetShaderSource) ctx->getProcAddress(QLatin1String("glGetShaderSource")); + glGetProgramiv = (_glGetProgramiv) ctx->getProcAddress(QLatin1String("glGetProgramiv")); + glGetProgramInfoLog = (_glGetProgramInfoLog) ctx->getProcAddress(QLatin1String("glGetProgramInfoLog")); + + glGetActiveUniform = (_glGetActiveUniform) ctx->getProcAddress(QLatin1String("glGetActiveUniform"));//### REMOVE + glGetUniformLocation = (_glGetUniformLocation) ctx->getProcAddress(QLatin1String("glGetUniformLocation")); + glUniform4f = (_glUniform4f) ctx->getProcAddress(QLatin1String("glUniform4f")); //### REMOVE + glUniform4fv = (_glUniform4fv) ctx->getProcAddress(QLatin1String("glUniform4fv")); + glUniform3fv = (_glUniform3fv) ctx->getProcAddress(QLatin1String("glUniform3fv")); + glUniform2f = (_glUniform2f) ctx->getProcAddress(QLatin1String("glUniform2f")); //### REMOVE + glUniform2fv = (_glUniform2fv) ctx->getProcAddress(QLatin1String("glUniform2fv")); + glUniform1f = (_glUniform1f) ctx->getProcAddress(QLatin1String("glUniform1f")); //### REMOVE + glUniform1fv = (_glUniform1fv) ctx->getProcAddress(QLatin1String("glUniform1fv")); + glUniform1i = (_glUniform1i) ctx->getProcAddress(QLatin1String("glUniform1i")); + glUniform1iv = (_glUniform1iv) ctx->getProcAddress(QLatin1String("glUniform1iv")); + glUniformMatrix2fv = (_glUniformMatrix2fv) ctx->getProcAddress(QLatin1String("glUniformMatrix2fv")); + glUniformMatrix3fv = (_glUniformMatrix3fv) ctx->getProcAddress(QLatin1String("glUniformMatrix3fv")); + glUniformMatrix4fv = (_glUniformMatrix4fv) ctx->getProcAddress(QLatin1String("glUniformMatrix4fv")); + glUniformMatrix2x3fv = (_glUniformMatrix2x3fv) ctx->getProcAddress(QLatin1String("glUniformMatrix2x3fv")); + glUniformMatrix2x4fv = (_glUniformMatrix2x4fv) ctx->getProcAddress(QLatin1String("glUniformMatrix2x4fv")); + glUniformMatrix3x2fv = (_glUniformMatrix3x2fv) ctx->getProcAddress(QLatin1String("glUniformMatrix3x2fv")); + glUniformMatrix3x4fv = (_glUniformMatrix3x4fv) ctx->getProcAddress(QLatin1String("glUniformMatrix3x4fv")); + glUniformMatrix4x2fv = (_glUniformMatrix4x2fv) ctx->getProcAddress(QLatin1String("glUniformMatrix4x2fv")); + glUniformMatrix4x3fv = (_glUniformMatrix4x3fv) ctx->getProcAddress(QLatin1String("glUniformMatrix4x3fv")); + + glGetActiveAttrib = (_glGetActiveAttrib) ctx->getProcAddress(QLatin1String("glGetActiveAttrib")); //### REMOVE + glBindAttribLocation = (_glBindAttribLocation) ctx->getProcAddress(QLatin1String("glBindAttribLocation")); + glGetAttribLocation = (_glGetAttribLocation) ctx->getProcAddress(QLatin1String("glGetAttribLocation")); + glVertexAttrib1fv = (_glVertexAttrib1fv) ctx->getProcAddress(QLatin1String("glVertexAttrib1fv")); + glVertexAttrib2fv = (_glVertexAttrib2fv) ctx->getProcAddress(QLatin1String("glVertexAttrib2fv")); + glVertexAttrib3fv = (_glVertexAttrib3fv) ctx->getProcAddress(QLatin1String("glVertexAttrib3fv")); + glVertexAttrib4fv = (_glVertexAttrib4fv) ctx->getProcAddress(QLatin1String("glVertexAttrib4fv")); + glVertexAttribPointer = (_glVertexAttribPointer) ctx->getProcAddress(QLatin1String("glVertexAttribPointer")); + glDisableVertexAttribArray = (_glDisableVertexAttribArray) ctx->getProcAddress(QLatin1String("glDisableVertexAttribArray")); + glEnableVertexAttribArray = (_glEnableVertexAttribArray) ctx->getProcAddress(QLatin1String("glEnableVertexAttribArray")); + + glStencilOpSeparate = (_glStencilOpSeparate) ctx->getProcAddress(QLatin1String("glStencilOpSeparate")); //### Not really a glsl extension, but needed for gl2 + + } else { + // We may not have the standard shader functions, but we might + // have the older ARB functions instead. + glCreateShader = (_glCreateShader) ctx->getProcAddress(QLatin1String("glCreateShaderObjectARB")); + glShaderSource = (_glShaderSource) ctx->getProcAddress(QLatin1String("glShaderSourceARB")); + glShaderBinary = (_glShaderBinary) ctx->getProcAddress(QLatin1String("glShaderBinaryARB")); + glCompileShader = (_glCompileShader) ctx->getProcAddress(QLatin1String("glCompileShaderARB")); + glDeleteShader = (_glDeleteShader) ctx->getProcAddress(QLatin1String("glDeleteObjectARB")); + glIsShader = 0; + + glCreateProgram = (_glCreateProgram) ctx->getProcAddress(QLatin1String("glCreateProgramObjectARB")); + glAttachShader = (_glAttachShader) ctx->getProcAddress(QLatin1String("glAttachObjectARB")); + glDetachShader = (_glDetachShader) ctx->getProcAddress(QLatin1String("glDetachObjectARB")); + glLinkProgram = (_glLinkProgram) ctx->getProcAddress(QLatin1String("glLinkProgramARB")); + glUseProgram = (_glUseProgram) ctx->getProcAddress(QLatin1String("glUseProgramObjectARB")); + glDeleteProgram = (_glDeleteProgram) ctx->getProcAddress(QLatin1String("glDeleteObjectARB")); + glIsProgram = 0; + + glGetShaderInfoLog = (_glGetShaderInfoLog) ctx->getProcAddress(QLatin1String("glGetInfoLogARB")); + glGetShaderiv = (_glGetShaderiv) ctx->getProcAddress(QLatin1String("glGetObjectParameterivARB")); + glGetShaderSource = (_glGetShaderSource) ctx->getProcAddress(QLatin1String("glGetShaderSourceARB")); + glGetProgramiv = (_glGetProgramiv) ctx->getProcAddress(QLatin1String("glGetObjectParameterivARB")); + glGetProgramInfoLog = (_glGetProgramInfoLog) ctx->getProcAddress(QLatin1String("glGetInfoLogARB")); + + glGetActiveUniform = (_glGetActiveUniform) ctx->getProcAddress(QLatin1String("glGetActiveUniformARB"));//### REMOVE + glGetUniformLocation = (_glGetUniformLocation) ctx->getProcAddress(QLatin1String("glGetUniformLocationARB")); + glUniform4f = (_glUniform4f) ctx->getProcAddress(QLatin1String("glUniform4fARB")); //### REMOVE + glUniform4fv = (_glUniform4fv) ctx->getProcAddress(QLatin1String("glUniform4fvARB")); + glUniform3fv = (_glUniform3fv) ctx->getProcAddress(QLatin1String("glUniform3fvARB")); + glUniform2f = (_glUniform2f) ctx->getProcAddress(QLatin1String("glUniform2fARB")); //### REMOVE + glUniform2fv = (_glUniform2fv) ctx->getProcAddress(QLatin1String("glUniform2fvARB")); + glUniform1f = (_glUniform1f) ctx->getProcAddress(QLatin1String("glUniform1fARB")); //### REMOVE + glUniform1fv = (_glUniform1fv) ctx->getProcAddress(QLatin1String("glUniform1fvARB")); + glUniform1i = (_glUniform1i) ctx->getProcAddress(QLatin1String("glUniform1iARB")); + glUniform1iv = (_glUniform1iv) ctx->getProcAddress(QLatin1String("glUniform1ivARB")); + glUniformMatrix2fv = (_glUniformMatrix2fv) ctx->getProcAddress(QLatin1String("glUniformMatrix2fvARB")); + glUniformMatrix3fv = (_glUniformMatrix3fv) ctx->getProcAddress(QLatin1String("glUniformMatrix3fvARB")); + glUniformMatrix4fv = (_glUniformMatrix4fv) ctx->getProcAddress(QLatin1String("glUniformMatrix4fvARB")); + glUniformMatrix2x3fv = (_glUniformMatrix2x3fv) ctx->getProcAddress(QLatin1String("glUniformMatrix2x3fvARB")); + glUniformMatrix2x4fv = (_glUniformMatrix2x4fv) ctx->getProcAddress(QLatin1String("glUniformMatrix2x4fvARB")); + glUniformMatrix3x2fv = (_glUniformMatrix3x2fv) ctx->getProcAddress(QLatin1String("glUniformMatrix3x2fvARB")); + glUniformMatrix3x4fv = (_glUniformMatrix3x4fv) ctx->getProcAddress(QLatin1String("glUniformMatrix3x4fvARB")); + glUniformMatrix4x2fv = (_glUniformMatrix4x2fv) ctx->getProcAddress(QLatin1String("glUniformMatrix4x2fvARB")); + glUniformMatrix4x3fv = (_glUniformMatrix4x3fv) ctx->getProcAddress(QLatin1String("glUniformMatrix4x3fvARB")); + + glGetActiveAttrib = (_glGetActiveAttrib) ctx->getProcAddress(QLatin1String("glGetActiveAttribARB")); //### REMOVE + glBindAttribLocation = (_glBindAttribLocation) ctx->getProcAddress(QLatin1String("glBindAttribLocationARB")); + glGetAttribLocation = (_glGetAttribLocation) ctx->getProcAddress(QLatin1String("glGetAttribLocationARB")); + glVertexAttrib1fv = (_glVertexAttrib1fv) ctx->getProcAddress(QLatin1String("glVertexAttrib1fvARB")); + glVertexAttrib2fv = (_glVertexAttrib2fv) ctx->getProcAddress(QLatin1String("glVertexAttrib2fvARB")); + glVertexAttrib3fv = (_glVertexAttrib3fv) ctx->getProcAddress(QLatin1String("glVertexAttrib3fvARB")); + glVertexAttrib4fv = (_glVertexAttrib4fv) ctx->getProcAddress(QLatin1String("glVertexAttrib4fvARB")); + glVertexAttribPointer = (_glVertexAttribPointer) ctx->getProcAddress(QLatin1String("glVertexAttribPointerARB")); + glDisableVertexAttribArray = (_glDisableVertexAttribArray) ctx->getProcAddress(QLatin1String("glDisableVertexAttribArrayARB")); + glEnableVertexAttribArray = (_glEnableVertexAttribArray) ctx->getProcAddress(QLatin1String("glEnableVertexAttribArrayARB")); + + glStencilOpSeparate = 0; //### Was never an ARB extension but went strait into OpenGL 2.0 + } + + // Note: glShaderBinary(), glIsShader(), glIsProgram(), and + // glUniformMatrixNxMfv() are optional, but all other functions + // are required. + + return glCreateShader && + glShaderSource && + glCompileShader && + glDeleteProgram && + glCreateProgram && + glAttachShader && + glDetachShader && + glLinkProgram && + glUseProgram && + glDeleteProgram && + glGetShaderInfoLog && + glGetShaderiv && + glGetShaderSource && + glGetProgramiv && + glGetProgramInfoLog && + glGetActiveUniform && //### REMOVE + glGetUniformLocation && + glUniform1f && //### REMOVE + glUniform1fv && + glUniform2f && //### REMOVE + glUniform2fv && + glUniform3fv && + glUniform4f && //### REMOVE + glUniform4fv && + glUniform1i && + glUniform1iv && + glUniformMatrix2fv && + glUniformMatrix3fv && + glUniformMatrix4fv && + glGetActiveAttrib && //### REMOVE + glBindAttribLocation && + glGetAttribLocation && + glVertexAttrib1fv && + glVertexAttrib2fv && + glVertexAttrib3fv && + glVertexAttrib4fv && + glVertexAttribPointer && + glDisableVertexAttribArray && + glEnableVertexAttribArray && + glStencilOpSeparate; +#endif } QT_END_NAMESPACE diff --git a/src/opengl/qglextensions_p.h b/src/opengl/qglextensions_p.h index cd35eb0..69632e7 100644 --- a/src/opengl/qglextensions_p.h +++ b/src/opengl/qglextensions_p.h @@ -96,8 +96,10 @@ typedef void (APIENTRY *_glProgramLocalParameter4fvARB) (GLenum, GLuint, const G // GLSL typedef GLuint (APIENTRY *_glCreateShader) (GLenum); typedef void (APIENTRY *_glShaderSource) (GLuint, GLsizei, const char **, const GLint *); +typedef void (APIENTRY *_glShaderBinary) (GLint, const GLuint*, GLenum, const void*, GLint); typedef void (APIENTRY *_glCompileShader) (GLuint); typedef void (APIENTRY *_glDeleteShader) (GLuint); +typedef GLboolean (APIENTRY *_glIsShader) (GLuint); typedef GLuint (APIENTRY *_glCreateProgram) (); typedef void (APIENTRY *_glAttachShader) (GLuint, GLuint); @@ -105,10 +107,13 @@ typedef void (APIENTRY *_glDetachShader) (GLuint, GLuint); typedef void (APIENTRY *_glLinkProgram) (GLuint); typedef void (APIENTRY *_glUseProgram) (GLuint); typedef void (APIENTRY *_glDeleteProgram) (GLuint); +typedef GLboolean (APIENTRY *_glIsProgram) (GLuint); typedef void (APIENTRY *_glGetShaderInfoLog) (GLuint, GLsizei, GLsizei *, char *); typedef void (APIENTRY *_glGetShaderiv) (GLuint, GLenum, GLint *); +typedef void (APIENTRY *_glGetShaderSource) (GLuint, GLsizei, GLsizei *, char *); typedef void (APIENTRY *_glGetProgramiv) (GLuint, GLenum, GLint *); +typedef void (APIENTRY *_glGetProgramInfoLog) (GLuint, GLsizei, GLsizei *, char *); typedef GLuint (APIENTRY *_glGetUniformLocation) (GLuint, const char*); typedef void (APIENTRY *_glUniform4fv) (GLint, GLsizei, const GLfloat *); @@ -116,6 +121,29 @@ typedef void (APIENTRY *_glUniform3fv) (GLint, GLsizei, const GLfloat *); typedef void (APIENTRY *_glUniform2fv) (GLint, GLsizei, const GLfloat *); typedef void (APIENTRY *_glUniform1fv) (GLint, GLsizei, const GLfloat *); typedef void (APIENTRY *_glUniform1i) (GLint, GLint); +typedef void (APIENTRY *_glUniform1iv) (GLint, GLsizei, const GLint *); +typedef void (APIENTRY *_glUniformMatrix2fv) (GLint, GLsizei, GLboolean, const GLfloat *); +typedef void (APIENTRY *_glUniformMatrix3fv) (GLint, GLsizei, GLboolean, const GLfloat *); +typedef void (APIENTRY *_glUniformMatrix4fv) (GLint, GLsizei, GLboolean, const GLfloat *); +typedef void (APIENTRY *_glUniformMatrix2x3fv) (GLint, GLsizei, GLboolean, const GLfloat *); +typedef void (APIENTRY *_glUniformMatrix2x4fv) (GLint, GLsizei, GLboolean, const GLfloat *); +typedef void (APIENTRY *_glUniformMatrix3x2fv) (GLint, GLsizei, GLboolean, const GLfloat *); +typedef void (APIENTRY *_glUniformMatrix3x4fv) (GLint, GLsizei, GLboolean, const GLfloat *); +typedef void (APIENTRY *_glUniformMatrix4x2fv) (GLint, GLsizei, GLboolean, const GLfloat *); +typedef void (APIENTRY *_glUniformMatrix4x3fv) (GLint, GLsizei, GLboolean, const GLfloat *); + +typedef void (APIENTRY *_glBindAttribLocation) (GLuint, GLuint, const char *); +typedef GLint (APIENTRY *_glGetAttribLocation) (GLuint, const char *); +typedef void (APIENTRY *_glVertexAttrib1fv) (GLuint, const GLfloat *); +typedef void (APIENTRY *_glVertexAttrib2fv) (GLuint, const GLfloat *); +typedef void (APIENTRY *_glVertexAttrib3fv) (GLuint, const GLfloat *); +typedef void (APIENTRY *_glVertexAttrib4fv) (GLuint, const GLfloat *); +typedef void (APIENTRY *_glVertexAttribPointer) (GLuint, GLint, GLenum, GLboolean, GLsizei, const GLvoid *); +typedef void (APIENTRY *_glDisableVertexAttribArray) (GLuint); +typedef void (APIENTRY *_glEnableVertexAttribArray) (GLuint); + +typedef void (APIENTRY *_glGetProgramBinaryOES) (GLuint, GLsizei, GLsizei *, GLenum *, void *); +typedef void (APIENTRY *_glProgramBinaryOES) (GLuint, GLenum, const void *, GLint); typedef void (APIENTRY *_glActiveStencilFaceEXT) (GLenum ); @@ -182,10 +210,13 @@ struct QGLExtensionFuncs qt_glGenProgramsARB = 0; qt_glProgramLocalParameter4fvARB = 0; +#if !defined(QT_OPENGL_ES_2) qt_glCreateShader = 0; qt_glShaderSource = 0; + qt_glShaderBinary = 0; qt_glCompileShader = 0; qt_glDeleteShader = 0; + qt_glIsShader = 0; qt_glCreateProgram = 0; qt_glAttachShader = 0; @@ -193,10 +224,13 @@ struct QGLExtensionFuncs qt_glLinkProgram = 0; qt_glUseProgram = 0; qt_glDeleteProgram = 0; + qt_glIsProgram = 0; qt_glGetShaderInfoLog = 0; qt_glGetShaderiv = 0; + qt_glGetShaderSource = 0; qt_glGetProgramiv = 0; + qt_glGetProgramInfoLog = 0; qt_glGetUniformLocation = 0; qt_glUniform4fv = 0; @@ -204,6 +238,32 @@ struct QGLExtensionFuncs qt_glUniform2fv = 0; qt_glUniform1fv = 0; qt_glUniform1i = 0; + qt_glUniform1iv = 0; + qt_glUniformMatrix2fv = 0; + qt_glUniformMatrix3fv = 0; + qt_glUniformMatrix4fv = 0; + qt_glUniformMatrix2x3fv = 0; + qt_glUniformMatrix2x4fv = 0; + qt_glUniformMatrix3x2fv = 0; + qt_glUniformMatrix3x4fv = 0; + qt_glUniformMatrix4x2fv = 0; + qt_glUniformMatrix4x3fv = 0; + + qt_glBindAttribLocation = 0; + qt_glGetAttribLocation = 0; + qt_glVertexAttrib1fv = 0; + qt_glVertexAttrib2fv = 0; + qt_glVertexAttrib3fv = 0; + qt_glVertexAttrib4fv = 0; + qt_glVertexAttribPointer = 0; + qt_glDisableVertexAttribArray = 0; + qt_glEnableVertexAttribArray = 0; +#else + qt_glslResolved = false; + + qt_glGetProgramBinaryOES = 0; + qt_glProgramBinaryOES = 0; +#endif qt_glActiveStencilFaceEXT = 0; @@ -261,11 +321,14 @@ struct QGLExtensionFuncs _glGenProgramsARB qt_glGenProgramsARB; _glProgramLocalParameter4fvARB qt_glProgramLocalParameter4fvARB; +#if !defined(QT_OPENGL_ES_2) // GLSL definitions _glCreateShader qt_glCreateShader; _glShaderSource qt_glShaderSource; + _glShaderBinary qt_glShaderBinary; _glCompileShader qt_glCompileShader; _glDeleteShader qt_glDeleteShader; + _glIsShader qt_glIsShader; _glCreateProgram qt_glCreateProgram; _glAttachShader qt_glAttachShader; @@ -273,10 +336,13 @@ struct QGLExtensionFuncs _glLinkProgram qt_glLinkProgram; _glUseProgram qt_glUseProgram; _glDeleteProgram qt_glDeleteProgram; + _glIsProgram qt_glIsProgram; _glGetShaderInfoLog qt_glGetShaderInfoLog; _glGetShaderiv qt_glGetShaderiv; + _glGetShaderSource qt_glGetShaderSource; _glGetProgramiv qt_glGetProgramiv; + _glGetProgramInfoLog qt_glGetProgramInfoLog; _glGetUniformLocation qt_glGetUniformLocation; _glUniform4fv qt_glUniform4fv; @@ -284,6 +350,32 @@ struct QGLExtensionFuncs _glUniform2fv qt_glUniform2fv; _glUniform1fv qt_glUniform1fv; _glUniform1i qt_glUniform1i; + _glUniform1iv qt_glUniform1iv; + _glUniformMatrix2fv qt_glUniformMatrix2fv; + _glUniformMatrix3fv qt_glUniformMatrix3fv; + _glUniformMatrix4fv qt_glUniformMatrix4fv; + _glUniformMatrix2x3fv qt_glUniformMatrix2x3fv; + _glUniformMatrix2x4fv qt_glUniformMatrix2x4fv; + _glUniformMatrix3x2fv qt_glUniformMatrix3x2fv; + _glUniformMatrix3x4fv qt_glUniformMatrix3x4fv; + _glUniformMatrix4x2fv qt_glUniformMatrix4x2fv; + _glUniformMatrix4x3fv qt_glUniformMatrix4x3fv; + + _glBindAttribLocation qt_glBindAttribLocation; + _glGetAttribLocation qt_glGetAttribLocation; + _glVertexAttrib1fv qt_glVertexAttrib1fv; + _glVertexAttrib2fv qt_glVertexAttrib2fv; + _glVertexAttrib3fv qt_glVertexAttrib3fv; + _glVertexAttrib4fv qt_glVertexAttrib4fv; + _glVertexAttribPointer qt_glVertexAttribPointer; + _glDisableVertexAttribArray qt_glDisableVertexAttribArray; + _glEnableVertexAttribArray qt_glEnableVertexAttribArray; +#else + bool qt_glslResolved; + + _glGetProgramBinaryOES qt_glGetProgramBinaryOES; + _glProgramBinaryOES qt_glProgramBinaryOES; +#endif _glActiveStencilFaceEXT qt_glActiveStencilFaceEXT; @@ -600,10 +692,14 @@ struct QGLExtensionFuncs #define glMapBufferARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glMapBufferARB #define glUnmapBufferARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUnmapBufferARB +#if !defined(QT_OPENGL_ES_2) + #define glCreateShader QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glCreateShader #define glShaderSource QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glShaderSource +#define glShaderBinary QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glShaderBinary #define glCompileShader QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glCompileShader #define glDeleteShader QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteShader +#define glIsShader QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glIsShader #define glCreateProgram QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glCreateProgram #define glAttachShader QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glAttachShader @@ -611,10 +707,13 @@ struct QGLExtensionFuncs #define glLinkProgram QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glLinkProgram #define glUseProgram QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUseProgram #define glDeleteProgram QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteProgram +#define glIsProgram QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glIsProgram #define glGetShaderInfoLog QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetShaderInfoLog #define glGetShaderiv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetShaderiv +#define glGetShaderSource QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetShaderSource #define glGetProgramiv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetProgramiv +#define glGetProgramInfoLog QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetProgramInfoLog #define glGetUniformLocation QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetUniformLocation #define glUniform4fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform4fv @@ -622,6 +721,33 @@ struct QGLExtensionFuncs #define glUniform2fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform2fv #define glUniform1fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform1fv #define glUniform1i QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform1i +#define glUniform1iv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniform1iv +#define glUniformMatrix2fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix2fv +#define glUniformMatrix3fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix3fv +#define glUniformMatrix4fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix4fv +#define glUniformMatrix2x3fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix2x3fv +#define glUniformMatrix2x4fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix2x4fv +#define glUniformMatrix3x2fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix3x2fv +#define glUniformMatrix3x4fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix3x4fv +#define glUniformMatrix4x2fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix4x2fv +#define glUniformMatrix4x3fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUniformMatrix4x3fv + +#define glBindAttribLocation QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindAttribLocation +#define glGetAttribLocation QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetAttribLocation +#define glVertexAttrib1fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glVertexAttrib1fv +#define glVertexAttrib2fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glVertexAttrib2fv +#define glVertexAttrib3fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glVertexAttrib3fv +#define glVertexAttrib4fv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glVertexAttrib4fv +#define glVertexAttribPointer QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glVertexAttribPointer +#define glDisableVertexAttribArray QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDisableVertexAttribArray +#define glEnableVertexAttribArray QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glEnableVertexAttribArray + +#else // QT_OPENGL_ES_2 + +#define glGetProgramBinaryOES QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetProgramBinaryOES +#define glProgramBinaryOES QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glProgramBinaryOES + +#endif // QT_OPENGL_ES_2 #define glGetActiveAttrib QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetActiveAttrib #define glGetAttribLocation QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetAttribLocation diff --git a/src/opengl/qglpixmapfilter.cpp b/src/opengl/qglpixmapfilter.cpp index 8a64515..87abf60 100644 --- a/src/opengl/qglpixmapfilter.cpp +++ b/src/opengl/qglpixmapfilter.cpp @@ -45,27 +45,12 @@ #include "qpaintengine_opengl_p.h" #include "qglpixelbuffer.h" -#include "qglextensions_p.h" +#include "qglshaderprogram.h" #include "qgl_p.h" #include "private/qapplication_p.h" -#ifndef GL_FRAGMENT_SHADER -#define GL_FRAGMENT_SHADER 0x8B30 -#endif - -#ifndef GL_COMPILE_STATUS -#define GL_COMPILE_STATUS 0x8B81 -#endif - -#ifndef GL_LINK_STATUS -#define GL_LINK_STATUS 0x8B82 -#endif - - - - QT_BEGIN_NAMESPACE @@ -79,110 +64,6 @@ void QGLPixmapFilterBase::drawImpl(QPainter *painter, const QPointF &pos, const processGL(painter, pos, src, source); } -QGLSLProgram::QGLSLProgram(const QString &src) - : ctx(QGLContext::currentContext()) -{ - if (!qt_resolve_glsl_extensions(const_cast(ctx))) { - qWarning("Failed to resolve GLSL functions"); - m_valid = false; - return; - } - - m_shader = glCreateShader(GL_FRAGMENT_SHADER); - - const QByteArray src_ba = src.toAscii(); - const char *src_cstr = src_ba.constData(); - - glShaderSource(m_shader, 1, &src_cstr, 0); - glCompileShader(m_shader); - glGetShaderiv(m_shader, GL_COMPILE_STATUS, &m_valid); - if (!m_valid) { - char data[4096]; - GLsizei len; - glGetShaderInfoLog(m_shader, 4096, &len, data); - qWarning("Failed to compile GLSL shader:\n%s\nCODE:\n%s\n", data, src_cstr); - return; - } - - m_program = glCreateProgram(); - glAttachShader(m_program, m_shader); - glLinkProgram(m_program); - glGetProgramiv(m_program, GL_LINK_STATUS, &m_valid); - if (!m_valid) { - char data[4096]; - GLsizei len; - glGetShaderInfoLog(m_shader, 4096, &len, data); - qWarning("Failed to link GLSL program:\n%s\nCODE:\n%s\n", data, src_cstr); - return; - } -} - -QGLSLProgram::~QGLSLProgram() -{ - glDeleteProgram(m_program); - glDeleteShader(m_shader); -} - -bool QGLSLProgram::success() const -{ - return m_valid; -} - -void QGLSLProgram::enable() -{ - glUseProgram(m_program); -} - -void QGLSLProgram::disable() -{ - glUseProgram(0); -} - -int QGLSLProgram::getUniformLocation(const QString &name) -{ - return glGetUniformLocation(m_program, name.toAscii().constData()); -} - -void QGLSLProgram::setUniform(int uniform, int value) -{ - enable(); - glUniform1i(uniform, value); -} - -void QGLSLProgram::setUniform(int uniform, qreal value) -{ - enable(); - GLfloat v[] = { value }; - glUniform1fv(uniform, 1, v); -} - -void QGLSLProgram::setUniform(int uniform, qreal v1, qreal v2) -{ - enable(); - GLfloat v[] = { v1, v2 }; - glUniform2fv(uniform, 1, v); -} - -void QGLSLProgram::setUniform(int uniform, qreal v1, qreal v2, qreal v3) -{ - enable(); - GLfloat v[] = { v1, v2, v3 }; - glUniform3fv(uniform, 1, v); -} - -void QGLSLProgram::setUniform(int uniform, qreal v1, qreal v2, qreal v3, qreal v4) -{ - enable(); - GLfloat v[] = { v1, v2, v3, v4 }; - glUniform4fv(uniform, 1, v); -} - -void QGLSLProgram::setUniform(int uniform, int count, float *v) -{ - enable(); - glUniform1fv(uniform, count, v); -} - class QGLPixmapColorizeFilter: public QGLPixmapFilter { public: @@ -192,8 +73,8 @@ protected: bool processGL(QPainter *painter, const QPointF &pos, const QPixmap &pixmap, const QRectF &srcRect) const; private: - mutable QGLSLProgram m_program; - uint m_colorUniform; + mutable QGLShaderProgram m_program; + int m_colorUniform; }; class QGLPixmapConvolutionFilter: public QGLPixmapFilter @@ -206,11 +87,11 @@ protected: bool processGL(QPainter *painter, const QPointF &pos, const QPixmap &src, const QRectF &srcRect) const; private: - QString generateConvolutionShader() const; + QByteArray generateConvolutionShader() const; - mutable QGLSLProgram *m_program; - mutable uint m_scaleUniform; - mutable uint m_matrixUniform; + mutable QGLShaderProgram *m_program; + mutable int m_scaleUniform; + mutable int m_matrixUniform; mutable int m_kernelWidth; mutable int m_kernelHeight; @@ -298,10 +179,12 @@ static const char *qt_gl_colorize_filter = "}"; QGLPixmapColorizeFilter::QGLPixmapColorizeFilter() - : m_program(QLatin1String(qt_gl_colorize_filter)) { - m_program.setUniform(m_program.getUniformLocation(QLatin1String("texture")), 0); // GL_TEXTURE_0 - m_colorUniform = m_program.getUniformLocation(QLatin1String("color")); + m_program.addShader(QGLShader::FragmentShader, qt_gl_colorize_filter); + m_program.link(); + m_program.enable(); + m_program.setUniformValue(m_program.uniformLocation("texture"), 0); // GL_TEXTURE_0 + m_colorUniform = m_program.uniformLocation("color"); } bool QGLPixmapColorizeFilter::processGL(QPainter *, const QPointF &pos, const QPixmap &src, const QRectF &srcRect) const @@ -309,10 +192,10 @@ bool QGLPixmapColorizeFilter::processGL(QPainter *, const QPointF &pos, const QP bindTexture(src); QColor col = color(); - m_program.setUniform(m_colorUniform, col.redF(), col.greenF(), col.blueF()); + m_program.enable(); + m_program.setUniformValue(m_colorUniform, col.redF(), col.greenF(), col.blueF()); QRectF target = (srcRect.isNull() ? QRectF(src.rect()) : srcRect).translated(pos); - m_program.enable(); qgl_drawTexture(target, src.width(), src.height(), srcRect); m_program.disable(); @@ -320,7 +203,7 @@ bool QGLPixmapColorizeFilter::processGL(QPainter *, const QPointF &pos, const QP } // generates convolution filter code for arbitrary sized kernel -QString QGLPixmapConvolutionFilter::generateConvolutionShader() const { +QByteArray QGLPixmapConvolutionFilter::generateConvolutionShader() const { QByteArray code; code.append("uniform sampler2D texture;\n"); code.append("uniform vec2 inv_texture_size;\n"); @@ -356,7 +239,7 @@ QString QGLPixmapConvolutionFilter::generateConvolutionShader() const { code.append(" }\n"); code.append(" gl_FragColor = sum;\n"); code.append("}"); - return QLatin1String(code); + return code; } QGLPixmapConvolutionFilter::QGLPixmapConvolutionFilter() @@ -388,10 +271,12 @@ bool QGLPixmapConvolutionFilter::processGL(QPainter *, const QPointF &pos, const m_kernelWidth = columns(); m_kernelHeight = rows(); - QString code = generateConvolutionShader(); - m_program = new QGLSLProgram(code); - m_scaleUniform = m_program->getUniformLocation(QLatin1String("inv_texture_size")); - m_matrixUniform = m_program->getUniformLocation(QLatin1String("matrix")); + QByteArray code = generateConvolutionShader(); + m_program = new QGLShaderProgram(); + m_program->addShader(QGLShader::FragmentShader, code); + m_program->link(); + m_scaleUniform = m_program->uniformLocation("inv_texture_size"); + m_matrixUniform = m_program->uniformLocation("matrix"); } const qreal *kernel = convolutionKernel(); @@ -401,10 +286,10 @@ bool QGLPixmapConvolutionFilter::processGL(QPainter *, const QPointF &pos, const const qreal iw = 1.0 / src.width(); const qreal ih = 1.0 / src.height(); - m_program->setUniform(m_scaleUniform, iw, ih); - m_program->setUniform(m_matrixUniform, m_kernelWidth * m_kernelHeight, conv); - m_program->enable(); + m_program->setUniformValue(m_scaleUniform, iw, ih); + m_program->setUniformValueArray(m_matrixUniform, conv, m_kernelWidth * m_kernelHeight, 1); + qgl_drawTexture(target, src.width(), src.height(), boundingRectFor(srcRect)); m_program->disable(); return true; diff --git a/src/opengl/qglpixmapfilter_p.h b/src/opengl/qglpixmapfilter_p.h index dc2eea6..d6742fc 100644 --- a/src/opengl/qglpixmapfilter_p.h +++ b/src/opengl/qglpixmapfilter_p.h @@ -87,35 +87,6 @@ public: } }; -class Q_OPENGL_EXPORT QGLSLProgram -{ -public: - QGLSLProgram(const QString &src); - ~QGLSLProgram(); - - bool success() const; - - void enable(); - void disable(); - - int getUniformLocation(const QString &name); - - void setUniform(int uniform, int value); - void setUniform(int uniform, qreal value); - void setUniform(int uniform, qreal v1, qreal v2); - void setUniform(int uniform, qreal v1, qreal v2, qreal v3); - void setUniform(int uniform, qreal v1, qreal v2, qreal v3, qreal v4); - void setUniform(int uniform, int count, float *v); - -private: - GLuint m_shader; - GLuint m_program; - - GLint m_valid; - - const QGLContext *ctx; -}; - QT_END_NAMESPACE QT_END_HEADER diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp new file mode 100644 index 0000000..934b5a5 --- /dev/null +++ b/src/opengl/qglshaderprogram.cpp @@ -0,0 +1,2828 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtOpenGL module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qglshaderprogram.h" +#include "qglextensions_p.h" +#include "qgl_p.h" +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +#if !defined(QT_OPENGL_ES_1_CL) + +/*! + \class QGLShaderProgram + \brief The QGLShaderProgram class allows OpenGL shader programs to be linked and used. + \since 4.6 + + \section1 Introduction + + This class supports shader programs written in the OpenGL Shading + Language (GLSL) and in the OpenGL/ES Shading Language (GLSL/ES). + + QGLShader and QGLShaderProgram shelter the programmer from the details of + compiling and linking vertex and fragment shaders. + + The following example creates a vertex shader program using the + supplied source \c{code}. Once compiled and linked, the shader + program is activated in the current QGLContext by calling + QGLShaderProgram::enable(): + + \code + QGLShader shader(QGLShader::VertexShader); + shader.setSourceCode(code); + + QGLShaderProgram program(context); + program.addShader(shader); + program.link(); + + program.enable(); + \endcode + + \section1 Writing portable shaders + + Shader programs can be difficult to reuse across OpenGL implementations + because of varying levels of support for standard vertex attributes and + uniform variables. In particular, GLSL/ES lacks all of the + standard variables that are present on desktop OpenGL systems: + \c{gl_Vertex}, \c{gl_Normal}, \c{gl_Color}, and so on. Desktop OpenGL + lacks the variable qualifiers \c{highp}, \c{mediump}, and \c{lowp}. + + The QGLShaderProgram class makes the process of writing portable shaders + easier by prefixing all shader programs with the following lines on + desktop OpenGL: + + \code + #define highp + #define mediump + #define lowp + \endcode + + This makes it possible to run most GLSL/ES shader programs + on desktop systems. The programmer should restrict themselves + to just features that are present in GLSL/ES, and avoid + standard variable names that only work on the desktop. + + \section1 Simple shader example + + \code + program.addShader(QGLShader::VertexShader, + "attribute highp vec4 vertex;\n" + "attribute mediump mat4 matrix;\n" + "void main(void)\n" + "{\n" + " gl_Position = matrix * vertex;\n" + "}"); + program.addShader(QGLShader::FragmentShader, + "uniform mediump vec4 color;\n" + "void main(void)\n" + "{\n" + " gl_FragColor = color;\n" + "}"); + program.link(); + program.enable(); + + int vertexLocation = program.attributeLocation("vertex"); + int matrixLocation = program.attributeLocation("matrix"); + int colorLocation = program.uniformLocation("color"); + \endcode + + With the above shader program active, we can draw a green triangle + as follows: + + \code + static GLfloat const triangleVertices[] = { + 60.0f, 10.0f, 0.0f, + 110.0f, 110.0f, 0.0f, + 10.0f, 110.0f, 0.0f + }; + + QColor color(0, 255, 0, 255); + + QMatrix4x4 pmvMatrix; + pmvMatrix.ortho(rect()); + + program.setAttributeArray(vertexLocation, triangleVertices, 3); + program.setUniformValue(matrixLocation, pmvMatrix); + program.setUniformValue(colorLocation, color); + + glDrawArrays(GL_TRIANGLES, 0, 3); + \endcode + + \section1 Partial shaders + + Desktop GLSL can attach an arbitrary number of vertex and fragment + shaders to a shader program. Embedded GLSL/ES on the other hand + supports only a single shader of each type on a shader program. + + Multiple shaders of the same type can be useful when large libraries + of shaders are needed. Common functions can be factored out into + library shaders that can be reused in multiple shader programs. + + To support this use of shaders, the application programmer can + create shaders with the QGLShader::PartialVertexShader and + QGLShader::PartialFragmentShader types. These types direct + QGLShader and QGLShaderProgram to delay shader compilation until + link time. + + When link() is called, the sources for the partial shaders are + concatenated, and a single vertex or fragment shader is compiled + and linked into the shader program. + + It is more efficient to use the QGLShader::VertexShader and + QGLShader::FragmentShader when there is only one shader of that + type in the program. + + \sa QGLShader +*/ + +/*! + \class QGLShader + \brief The QGLShader class allows OpenGL shaders to be compiled. + \since 4.6 + + This class supports shaders written in the OpenGL Shading Language (GLSL) + and in the OpenGL/ES Shading Language (GLSL/ES). + + QGLShader and QGLShaderProgram shelter the programmer from the details of + compiling and linking vertex and fragment shaders. + + \sa QGLShaderProgram +*/ + +/*! + \enum QGLShader::ShaderType + This enum specifies the type of QGLShader that is being created. + + \value VertexShader Vertex shader written in the OpenGL Shading Language (GLSL). + \value FragmentShader Fragment shader written in the OpenGL Shading Language (GLSL). + \value PartialVertexShader Partial vertex shader that will be concatenated with all other partial vertex shaders at link time. + \value PartialFragmentShader Partial fragment shader that will be concatenated with all other partial fragment shaders at link time. +*/ + +#ifndef GL_FRAGMENT_SHADER +#define GL_FRAGMENT_SHADER 0x8B30 +#endif +#ifndef GL_VERTEX_SHADER +#define GL_VERTEX_SHADER 0x8B31 +#endif +#ifndef GL_COMPILE_STATUS +#define GL_COMPILE_STATUS 0x8B81 +#endif +#ifndef GL_LINK_STATUS +#define GL_LINK_STATUS 0x8B82 +#endif +#ifndef GL_INFO_LOG_LENGTH +#define GL_INFO_LOG_LENGTH 0x8B84 +#endif +#ifndef GL_ACTIVE_UNIFORMS +#define GL_ACTIVE_UNIFORMS 0x8B86 +#endif +#ifndef GL_ACTIVE_UNIFORM_MAX_LENGTH +#define GL_ACTIVE_UNIFORM_MAX_LENGTH 0x8B87 +#endif +#ifndef GL_ACTIVE_ATTRIBUTES +#define GL_ACTIVE_ATTRIBUTES 0x8B89 +#endif +#ifndef GL_ACTIVE_ATTRIBUTE_MAX_LENGTH +#define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A +#endif +#ifndef GL_CURRENT_VERTEX_ATTRIB +#define GL_CURRENT_VERTEX_ATTRIB 0x8626 +#endif +#ifndef GL_SHADER_SOURCE_LENGTH +#define GL_SHADER_SOURCE_LENGTH 0x8B88 +#endif +#ifndef GL_SHADER_BINARY_FORMATS +#define GL_SHADER_BINARY_FORMATS 0x8DF8 +#endif +#ifndef GL_NUM_SHADER_BINARY_FORMATS +#define GL_NUM_SHADER_BINARY_FORMATS 0x8DF9 +#endif + +class QGLShaderPrivate +{ +public: + QGLShaderPrivate(QGLShader::ShaderType type, const QGLContext *ctx) + { + context = ctx; + shader = 0; + shaderType = type; + compiled = false; + isPartial = (type == QGLShader::PartialVertexShader || + type == QGLShader::PartialFragmentShader); + hasPartialSource = false; + } + + const QGLContext *context; + GLuint shader; + QGLShader::ShaderType shaderType; + bool compiled; + bool isPartial; + bool hasPartialSource; + QString errors; + QByteArray partialSource; + + bool create(); + bool compile(); +}; + +#define ctx context + +bool QGLShaderPrivate::create() +{ + if (isPartial) + return true; + if (!context) + context = QGLContext::currentContext(); + if (!context) + return false; + if (qt_resolve_glsl_extensions(const_cast(context))) { + if (shaderType == QGLShader::VertexShader) + shader = glCreateShader(GL_VERTEX_SHADER); + else + shader = glCreateShader(GL_FRAGMENT_SHADER); + if (!shader) { + qWarning() << "QGLShader: could not create shader"; + return false; + } + return true; + } else { + return false; + } +} + +bool QGLShaderPrivate::compile() +{ + // Partial shaders are compiled during QGLShaderProgram::link(). + if (isPartial && hasPartialSource) { + compiled = true; + return true; + } + if (!shader) + return false; + glCompileShader(shader); + GLint value = 0; + glGetShaderiv(shader, GL_COMPILE_STATUS, &value); + compiled = (value != 0); + value = 0; + glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &value); + if (!compiled && value > 1) { + char *log = new char [value]; + GLint len; + glGetShaderInfoLog(shader, value, &len, log); + errors = QString::fromLatin1(log); + qWarning() << "QGLShader::compile:" << errors; + delete [] log; + } + return compiled; +} + +#undef ctx +#define ctx d->context + +/*! + Constructs a new QGLShader object of the specified \a type + and attaches it to \a parent. If shader programs are not supported, + then isValid() will return false. + + This constructor is normally followed by a call to setSourceCode() + or setSourceCodeFile(). + + The shader will be associated with the current QGLContext. + + \sa setSourceCode(), setSourceCodeFile(), isValid() +*/ +QGLShader::QGLShader(QGLShader::ShaderType type, QObject *parent) + : QObject(parent) +{ + d = new QGLShaderPrivate(type, QGLContext::currentContext()); + d->create(); +} + +/*! + Constructs a new QGLShader object from the source code in \a fileName + and attaches it to \a parent. If the filename ends in \c{.fsh}, + it is assumed to be a fragment shader, otherwise it is assumed to + be a vertex shader (normally the extension is \c{.vsh} for vertex shaders). + If the shader could not be loaded, then isValid() will return false. + + The shader will be associated with the current QGLContext. + + \sa isValid() +*/ +QGLShader::QGLShader(const QString& fileName, QObject *parent) + : QObject(parent) +{ + if (fileName.endsWith(QLatin1String(".fsh"), Qt::CaseInsensitive)) + d = new QGLShaderPrivate(QGLShader::FragmentShader, QGLContext::currentContext()); + else + d = new QGLShaderPrivate(QGLShader::VertexShader, QGLContext::currentContext()); + if (d->create() && !setSourceCodeFile(fileName)) { + if (d->shader) + glDeleteShader(d->shader); + d->shader = 0; + } +} + +/*! + Constructs a new QGLShader object of the specified \a type from the + source code in \a fileName and attaches it to \a parent. + If the shader could not be loaded, then isValid() will return false. + + The shader will be associated with the current QGLContext. + + \sa isValid() +*/ +QGLShader::QGLShader + (const QString& fileName, QGLShader::ShaderType type, QObject *parent) + : QObject(parent) +{ + d = new QGLShaderPrivate(type, QGLContext::currentContext()); + if (d->create() && !setSourceCodeFile(fileName)) { + if (d->shader) + glDeleteShader(d->shader); + d->shader = 0; + } +} + +/*! + Constructs a new QGLShader object of the specified \a type + and attaches it to \a parent. If shader programs are not supported, + then isValid() will return false. + + This constructor is normally followed by a call to setSourceCode() + or setSourceCodeFile(). + + The shader will be associated with \a context. + + \sa setSourceCode(), setSourceCodeFile(), isValid() +*/ +QGLShader::QGLShader(QGLShader::ShaderType type, const QGLContext *context, QObject *parent) + : QObject(parent) +{ + d = new QGLShaderPrivate(type, context); + d->create(); +} + +/*! + Constructs a new QGLShader object from the source code in \a fileName + and attaches it to \a parent. If the filename ends in \c{.fsh}, + it is assumed to be a fragment shader, otherwise it is assumed to + be a vertex shader (normally the extension is \c{.vsh} for vertex shaders). + If the shader could not be loaded, then isValid() will return false. + + The shader will be associated with \a context. + + \sa isValid() +*/ +QGLShader::QGLShader(const QString& fileName, const QGLContext *context, QObject *parent) + : QObject(parent) +{ + if (fileName.endsWith(QLatin1String(".fsh"), Qt::CaseInsensitive)) + d = new QGLShaderPrivate(QGLShader::FragmentShader, context); + else + d = new QGLShaderPrivate(QGLShader::VertexShader, context); + if (d->create() && !setSourceCodeFile(fileName)) { + if (d->shader) + glDeleteShader(d->shader); + d->shader = 0; + } +} + +/*! + Constructs a new QGLShader object of the specified \a type from the + source code in \a fileName and attaches it to \a parent. + If the shader could not be loaded, then isValid() will return false. + + The shader will be associated with \a context. + + \sa isValid() +*/ +QGLShader::QGLShader + (const QString& fileName, QGLShader::ShaderType type, const QGLContext *context, QObject *parent) + : QObject(parent) +{ + d = new QGLShaderPrivate(type, context); + if (d->create() && !setSourceCodeFile(fileName)) { + if (d->shader) + glDeleteShader(d->shader); + d->shader = 0; + } +} + +/*! + Deletes this shader. If the shader has been attached to a + QGLShaderProgram object, then the actual shader will stay around + until the QGLShaderProgram is destroyed. +*/ +QGLShader::~QGLShader() +{ + if (d->shader) + glDeleteShader(d->shader); + delete d; +} + +/*! + Returns true if this shader is valid. Shaders become invalid + when they are destroyed and no longer attached to a QGLShaderProgram. +*/ +bool QGLShader::isValid() const +{ + if (d->isPartial && d->hasPartialSource) + return true; + if (!d->shader) + return false; +#if defined(QT_OPENGL_ES_2) + return glIsShader(d->shader); +#else + // glIsShader() may not exist on some systems. + return (!glIsShader || glIsShader(d->shader)); +#endif +} + +/*! + Returns the type of this shader. +*/ +QGLShader::ShaderType QGLShader::shaderType() const +{ + return d->shaderType; +} + +// The precision qualifiers are useful on OpenGL/ES systems, +// but usually not present on desktop systems. Define the +// keywords to empty strings on desktop systems. +#ifndef QT_OPENGL_ES +#define QGL_DEFINE_QUALIFIERS 1 +static const char qualifierDefines[] = + "#define lowp\n" + "#define mediump\n" + "#define highp\n"; +#endif + +/*! + Sets the \a source code for this shader and compiles it. + Returns true if the source was successfully compiled, false otherwise. + + If shaderType() is PartialVertexShader or PartialFragmentShader, + then this function will always return true, even if the source code + is invalid. Partial shaders are compiled when QGLShaderProgram::link() + is called. +*/ +bool QGLShader::setSourceCode(const char *source) +{ + if (d->isPartial) { + d->partialSource = QByteArray(source); + d->hasPartialSource = true; + return d->compile(); + } else if (d->shader) { + QVarLengthArray src; +#ifdef QGL_DEFINE_QUALIFIERS + src.append(qualifierDefines); +#endif + src.append(source); + glShaderSource(d->shader, src.size(), src.data(), 0); + return d->compile(); + } else { + return false; + } +} + +/*! + \overload + + Sets the \a source code for this shader and compiles it. + Returns true if the source was successfully compiled, false otherwise. + + If shaderType() is PartialVertexShader or PartialFragmentShader, + then this function will always return true, even if the source code + is invalid. Partial shaders are compiled when QGLShaderProgram::link() + is called. +*/ +bool QGLShader::setSourceCode(const QByteArray& source) +{ + return setSourceCode(source.constData()); +} + +/*! + \overload + + Sets the \a source code for this shader and compiles it. + Returns true if the source was successfully compiled, false otherwise. + + If shaderType() is PartialVertexShader or PartialFragmentShader, + then this function will always return true, even if the source code + is invalid. Partial shaders are compiled when QGLShaderProgram::link() + is called. +*/ +bool QGLShader::setSourceCode(const QString& source) +{ + return setSourceCode(source.toLatin1().constData()); +} + +/*! + Sets the source code for this shader to the contents of \a fileName + and compiles it. Returns true if the file could be opened and the + source compiled, false otherwise. + + If shaderType() is PartialVertexShader or PartialFragmentShader, + then this function will always return true, even if the source code + is invalid. Partial shaders are compiled when QGLShaderProgram::link() + is called. +*/ +bool QGLShader::setSourceCodeFile(const QString& fileName) +{ + if (!d->shader) + return false; + + QFile file(fileName); + if (!file.open(QFile::ReadOnly)) { + qWarning() << "QGLShader: Unable to open file" << fileName; + return false; + } + + QByteArray contents = file.readAll(); + return setSourceCode(contents.constData()); +} + +/*! + Sets the binary code for this shader to the \a length bytes from + the array \a binary. The \a format specifies how the binary data + should be interpreted by the OpenGL engine. Returns true if the + binary was set on the shader; false otherwise. + + This function cannot be used with PartialVertexShader or + PartialFragmentShader. + + \sa shaderBinaryFormats() +*/ +bool QGLShader::setBinaryCode(GLenum format, const void *binary, int length) +{ +#if !defined(QT_OPENGL_ES_2) + if (!glShaderBinary) + return false; +#endif + if (d->isPartial || !d->shader) + return false; + glGetError(); // Clear error state. + glShaderBinary(1, &(d->shader), format, binary, length); + return (glGetError() == GL_NO_ERROR); +} + +/*! + Sets the binary code for this shader to the \a length bytes from + the array \a binary. The \a format specifies how the binary data + should be interpreted by the OpenGL engine. Returns true if the + binary was set on the shader; false otherwise. + + The \a otherShader will also have binary code set on it. This is + for the case where \a binary contains both vertex and fragment + shader code. + + This function cannot be used with PartialVertexShader or + PartialFragmentShader. + + \sa shaderBinaryFormats() +*/ +bool QGLShader::setBinaryCode + (QGLShader& otherShader, GLenum format, const void *binary, int length) +{ +#if !defined(QT_OPENGL_ES_2) + if (!glShaderBinary) + return false; +#endif + if (d->isPartial || !d->shader) + return false; + if (otherShader.d->isPartial || !otherShader.d->shader) + return false; + glGetError(); // Clear error state. + GLuint shaders[2]; + shaders[0] = d->shader; + shaders[1] = otherShader.d->shader; + glShaderBinary(2, shaders, format, binary, length); + return (glGetError() == GL_NO_ERROR); +} + +/*! + Returns a list of all binary formats that are supported by + setBinaryCode() on this system. + + \sa setBinaryCode() +*/ +QList QGLShader::shaderBinaryFormats() +{ + GLint num; + QList list; + glGetError(); // Clear error state. + glGetIntegerv(GL_NUM_SHADER_BINARY_FORMATS, &num); + if (glGetError() != GL_NO_ERROR || num <= 0) + return list; + QVarLengthArray formats(num); + glGetIntegerv(GL_SHADER_BINARY_FORMATS, formats.data()); + for (GLint i = 0; i < num; ++i) + list += (GLenum)(formats[i]); + return list; +} + +/*! + Returns the source code for this shader. + + \sa setSourceCode() +*/ +QByteArray QGLShader::sourceCode() const +{ + if (d->isPartial) + return d->partialSource; + if (!d->shader) + return QByteArray(); + GLint size = 0; + glGetShaderiv(d->shader, GL_SHADER_SOURCE_LENGTH, &size); + if (size <= 0) + return QByteArray(); + GLint len = 0; + char *source = new char [size]; + glGetShaderSource(d->shader, size, &len, source); + QByteArray src(source); + delete [] source; + return src; +} + +/*! + Returns true if this shader has been compiled; false otherwise. + + \sa setSourceCode() +*/ +bool QGLShader::isCompiled() const +{ + return d->compiled; +} + +/*! + Returns the errors that occurred during the last compile. + + \sa setSourceCode() +*/ +QString QGLShader::errors() const +{ + return d->errors; +} + +/*! + Returns the OpenGL identifier associated with this shader. + + If shaderType() is PartialVertexShader or PartialFragmentShader, + this function will always return zero. Partial shaders are + created and compiled when QGLShaderProgram::link() is called. + + \sa QGLShaderProgram::programId() +*/ +GLuint QGLShader::shaderId() const +{ + return d->shader; +} + +#undef ctx +#define ctx context + +class QGLShaderProgramPrivate +{ +public: + QGLShaderProgramPrivate(const QGLContext *ctx) + { + context = ctx; + program = 0; + linked = false; + inited = false; + hasPartialShaders = false; + vertexShader = 0; + fragmentShader = 0; + } + ~QGLShaderProgramPrivate() + { + if (program) + glDeleteProgram(program); + } + + const QGLContext *context; + GLuint program; + bool linked; + bool inited; + bool hasPartialShaders; + QString errors; + QList shaders; + QList anonShaders; + QGLShader *vertexShader; + QGLShader *fragmentShader; +}; + +#undef ctx +#define ctx d->context + +/*! + Constructs a new shader program and attaches it to \a parent. + The program will be invalid until addShader() is called. + + The shader program will be associated with the current QGLContext. + + \sa isValid(), addShader() +*/ +QGLShaderProgram::QGLShaderProgram(QObject *parent) + : QObject(parent) +{ + d = new QGLShaderProgramPrivate(QGLContext::currentContext()); +} + +/*! + Constructs a new shader program and attaches it to \a parent. + The program will be invalid until addShader() is called. + + The shader program will be associated with \a context. + + \sa isValid(), addShader() +*/ +QGLShaderProgram::QGLShaderProgram(const QGLContext *context, QObject *parent) + : QObject(parent) +{ + d = new QGLShaderProgramPrivate(context); +} + +/*! + Deletes this shader program. +*/ +QGLShaderProgram::~QGLShaderProgram() +{ + delete d; +} + +bool QGLShaderProgram::init() +{ + if (d->program || d->inited) + return true; + d->inited = true; + if (!d->context) + d->context = QGLContext::currentContext(); + if (!d->context) + return false; + if (qt_resolve_glsl_extensions(const_cast(d->context))) { + d->program = glCreateProgram(); + if (!(d->program)) { + qWarning() << "QGLShaderProgram: could not create shader program"; + return false; + } + return true; + } else { + qWarning() << "QGLShaderProgram: shader programs are not supported"; + return false; + } +} + +/*! + Returns true if this shader program object is valid, false otherwise. +*/ +bool QGLShaderProgram::isValid() const +{ + if (!d->program) + return false; +#if defined(QT_OPENGL_ES_2) + return glIsProgram(d->program); +#else + // glIsProgram() may not exist on some systems. + return (!glIsProgram || glIsProgram(d->program)); +#endif +} + +/*! + Adds a compiled \a shader to this shader program. Returns true + if the shader could be added, or false otherwise. + + Ownership of the \a shader object remains with the caller. + It will not be deleted when this QGLShaderProgram instance + is deleted. This allows the caller to add the same shader + to multiple shader programs. + + \sa removeShader(), link(), removeAllShaders() +*/ +bool QGLShaderProgram::addShader(QGLShader *shader) +{ + if (!init()) + return false; + if (d->shaders.contains(shader)) + return true; // Already added to this shader program. + if (d->program && shader && shader->d->shader) { + if (!shader->d->compiled) + return false; + if (!shader->d->isPartial) + glAttachShader(d->program, shader->d->shader); + else + d->hasPartialShaders = true; + d->linked = false; // Program needs to be relinked. + d->shaders.append(shader); + return true; + } else { + return false; + } +} + +/*! + Compiles \a source as a shader of the specified \a type and + adds it to this shader program. Returns true if compilation + was successful, false otherwise. The compilation errors + will be made available via errors(). + + This function is intended to be a short-cut for quickly + adding vertex and fragment shaders to a shader program without + creating an instance of QGLShader first. + + \sa removeShader(), link(), errors(), removeAllShaders() +*/ +bool QGLShaderProgram::addShader(QGLShader::ShaderType type, const char *source) +{ + if (!init()) + return false; + QGLShader *shader = new QGLShader(type, this); + if (!shader->setSourceCode(source)) { + d->errors = shader->errors(); + delete shader; + return false; + } + d->anonShaders.append(shader); + return addShader(shader); +} + +/*! + \overload + + Compiles \a source as a shader of the specified \a type and + adds it to this shader program. Returns true if compilation + was successful, false otherwise. The compilation errors + will be made available via errors(). + + This function is intended to be a short-cut for quickly + adding vertex and fragment shaders to a shader program without + creating an instance of QGLShader first. + + \sa removeShader(), link(), errors(), removeAllShaders() +*/ +bool QGLShaderProgram::addShader(QGLShader::ShaderType type, const QByteArray& source) +{ + return addShader(type, source.constData()); +} + +/*! + \overload + + Compiles \a source as a shader of the specified \a type and + adds it to this shader program. Returns true if compilation + was successful, false otherwise. The compilation errors + will be made available via errors(). + + This function is intended to be a short-cut for quickly + adding vertex and fragment shaders to a shader program without + creating an instance of QGLShader first. + + \sa removeShader(), link(), errors(), removeAllShaders() +*/ +bool QGLShaderProgram::addShader(QGLShader::ShaderType type, const QString& source) +{ + return addShader(type, source.toLatin1().constData()); +} + +/*! + Removes \a shader from this shader program. The object is not deleted. + + \sa addShader(), link(), removeAllShaders() +*/ +void QGLShaderProgram::removeShader(QGLShader *shader) +{ + if (d->program && shader && shader->d->shader) { + glDetachShader(d->program, shader->d->shader); + d->linked = false; // Program needs to be relinked. + } + d->shaders.removeAll(shader); + d->anonShaders.removeAll(shader); +} + +/*! + Returns a list of all shaders that have been added to this shader + program using addShader(). + + \sa addShader(), removeShader() +*/ +QList QGLShaderProgram::shaders() const +{ + return d->shaders; +} + +/*! + Removes all of the shaders that were added to this program previously. + The QGLShader objects for the shaders will not be deleted if they + were constructed externally. QGLShader objects that are constructed + internally by QGLShaderProgram will be deleted. + + \sa addShader(), removeShader() +*/ +void QGLShaderProgram::removeAllShaders() +{ + foreach (QGLShader *shader, d->shaders) { + if (d->program && shader && shader->d->shader) + glDetachShader(d->program, shader->d->shader); + } + foreach (QGLShader *shader, d->anonShaders) { + // Delete shader objects that were created anonymously. + delete shader; + } + d->shaders.clear(); + d->anonShaders.clear(); + d->linked = false; // Program needs to be relinked. +} + +#if defined(QT_OPENGL_ES_2) + +#ifndef GL_PROGRAM_BINARY_LENGTH_OES +#define GL_PROGRAM_BINARY_LENGTH_OES 0x8741 +#endif +#ifndef GL_NUM_PROGRAM_BINARY_FORMATS_OES +#define GL_NUM_PROGRAM_BINARY_FORMATS_OES 0x87FE +#endif +#ifndef GL_PROGRAM_BINARY_FORMATS_OES +#define GL_PROGRAM_BINARY_FORMATS_OES 0x87FF +#endif + +#endif + +/*! + Returns the program binary associated with this shader program. + The numeric identifier of the program binary format is returned + in \a format. The \c OES_get_program_binary extension will need + to be supported by the system for binary retrieval to succeed. + + Returns an empty QByteArray if the program binary cannot be + retrieved on this system, or the shader program has not yet + been linked. + + The returned binary can be supplied to setProgramBinary() on the + same machine at some future point to reload the program. It contains + the compiled code of all of the shaders that were attached to the + program at the time programBinary() is called. + + \sa setProgramBinary(), programBinaryFormats() +*/ +QByteArray QGLShaderProgram::programBinary(int *format) const +{ +#if defined(QT_OPENGL_ES_2) + if (!isLinked()) + return QByteArray(); + + // Get the length of the binary data, bailing out if there is none. + GLint length = 0; + glGetProgramiv(d->program, GL_PROGRAM_BINARY_LENGTH_OES, &length); + if (length <= 0) + return QByteArray(); + + // Retrieve the binary data. + QByteArray binary(length, 0); + GLenum binaryFormat; + glGetProgramBinaryOES(d->program, length, 0, &binaryFormat, binary.data()); + if (format) + *format = (int)binaryFormat; + return binary; +#else + Q_UNUSED(format); + return QByteArray(); +#endif +} + +/*! + Sets the \a binary for this shader program according to \a format. + Returns true if the binary was set, or false if the binary format + is not supported or this system does not support program binaries. + The program will be linked if the load succeeds. + + \sa programBinary(), programBinaryFormats(), isLinked() +*/ +bool QGLShaderProgram::setProgramBinary(int format, const QByteArray& binary) +{ +#if defined(QT_OPENGL_ES_2) + // Load the binary and check that it was linked correctly. + glProgramBinaryOES(d->program, (GLenum)format, + binary.constData(), binary.size()); + GLint value = 0; + glGetProgramiv(d->program, GL_LINK_STATUS, &value); + d->linked = (value != 0); + value = 0; + glGetProgramiv(d->program, GL_INFO_LOG_LENGTH, &value); + d->errors = QString(); + if (value > 1) { + char *log = new char [value]; + GLint len; + glGetProgramInfoLog(d->program, value, &len, log); + d->errors = QString::fromLatin1(log); + qWarning() << "QGLShaderProgram::setProgramBinary:" << d->errors; + delete [] log; + } + return d->linked; +#else + Q_UNUSED(format); + Q_UNUSED(binary); + return false; +#endif +} + +/*! + Returns the list of program binary formats that are accepted by + this system for use with setProgramBinary(). + + \sa programBinary, setProgramBinary() +*/ +QList QGLShaderProgram::programBinaryFormats() +{ +#if defined(QT_OPENGL_ES_2) + GLint count = 0; + glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS_OES, &count); + if (count <= 0) + return QList(); + QVector list; + list.resize(count); + glGetIntegerv(GL_PROGRAM_BINARY_FORMATS_OES, list.data()); + return list.toList(); +#else + return QList(); +#endif +} + +/*! + Links together the shaders that were added to this program with + addShader(). Returns true if the link was successful or + false otherwise. If the link failed, the error messages can + be retrieved with errors(). + + Subclasses can override this function to initialize attributes + and uniform variables for use in specific shader programs. + + If the shader program was already linked, calling this + function again will force it to be re-linked. + + \sa addShader(), errors() +*/ +bool QGLShaderProgram::link() +{ + if (!d->program) + return false; + if (d->hasPartialShaders) { + // Compile the partial vertex and fragment shaders. + QByteArray vertexSource; + QByteArray fragmentSource; + foreach (QGLShader *shader, d->shaders) { + if (shader->shaderType() == QGLShader::PartialVertexShader) + vertexSource += shader->sourceCode(); + else if (shader->shaderType() == QGLShader::PartialFragmentShader) + fragmentSource += shader->sourceCode(); + } + if (vertexSource.isEmpty()) { + if (d->vertexShader) { + glDetachShader(d->program, d->vertexShader->d->shader); + delete d->vertexShader; + d->vertexShader = 0; + } + } else { + if (!d->vertexShader) { + d->vertexShader = + new QGLShader(QGLShader::VertexShader, this); + } + if (!d->vertexShader->setSourceCode(vertexSource)) { + d->errors = d->vertexShader->errors(); + return false; + } + glAttachShader(d->program, d->vertexShader->d->shader); + } + if (fragmentSource.isEmpty()) { + if (d->fragmentShader) { + glDetachShader(d->program, d->fragmentShader->d->shader); + delete d->fragmentShader; + d->fragmentShader = 0; + } + } else { + if (!d->fragmentShader) { + d->fragmentShader = + new QGLShader(QGLShader::FragmentShader, this); + } + if (!d->fragmentShader->setSourceCode(fragmentSource)) { + d->errors = d->fragmentShader->errors(); + return false; + } + glAttachShader(d->program, d->fragmentShader->d->shader); + } + } + glLinkProgram(d->program); + GLint value = 0; + glGetProgramiv(d->program, GL_LINK_STATUS, &value); + d->linked = (value != 0); + value = 0; + glGetProgramiv(d->program, GL_INFO_LOG_LENGTH, &value); + d->errors = QString(); + if (value > 1) { + char *log = new char [value]; + GLint len; + glGetProgramInfoLog(d->program, value, &len, log); + d->errors = QString::fromLatin1(log); + qWarning() << "QGLShaderProgram::link:" << d->errors; + delete [] log; + } + return d->linked; +} + +/*! + Returns true if this shader program has been linked; false otherwise. + + \sa link() +*/ +bool QGLShaderProgram::isLinked() const +{ + return d->linked; +} + +/*! + Returns the errors that occurred during the last link() + or addShader() with explicitly specified source code. + + \sa link() +*/ +QString QGLShaderProgram::errors() const +{ + return d->errors; +} + +/*! + Enable use of this shader program in the currently active QGLContext. + Returns true if the program was successfully enabled; false + otherwise. If the shader program has not yet been linked, + or it needs to be re-linked, this function will call link(). + + \sa link(), disable() +*/ +bool QGLShaderProgram::enable() +{ + if (!d->program) + return false; + if (!d->linked && !link()) + return false; + glUseProgram(d->program); + return true; +} + +/*! + Disables this shader program in the currently active QGLContext. + This is equivalent to calling \c{glUseProgram(0)}. + + \sa enable() +*/ +void QGLShaderProgram::disable() +{ +#if defined(QT_OPENGL_ES_2) + glUseProgram(0); +#else + if (glUseProgram) + glUseProgram(0); +#endif +} + +/*! + Returns the OpenGL identifier associated with this shader program. + + \sa QGLShader::shaderId() +*/ +GLuint QGLShaderProgram::programId() const +{ + return d->program; +} + +/*! + Binds the attribute \a name to the specified \a location. This + function can be called before or after the program has been linked. + Any attributes that have not been explicitly bound when the program + is linked will be assigned locations automatically. + + \sa attributeLocation() +*/ +void QGLShaderProgram::bindAttributeLocation(const char *name, int location) +{ + glBindAttribLocation(d->program, location, name); +} + +/*! + \overload + + Binds the attribute \a name to the specified \a location. This + function can be called before or after the program has been linked. + Any attributes that have not been explicitly bound when the program + is linked will be assigned locations automatically. + + \sa attributeLocation() +*/ +void QGLShaderProgram::bindAttributeLocation(const QByteArray& name, int location) +{ + glBindAttribLocation(d->program, location, name.constData()); +} + +/*! + \overload + + Binds the attribute \a name to the specified \a location. This + function can be called before or after the program has been linked. + Any attributes that have not been explicitly bound when the program + is linked will be assigned locations automatically. + + \sa attributeLocation() +*/ +void QGLShaderProgram::bindAttributeLocation(const QString& name, int location) +{ + glBindAttribLocation(d->program, location, name.toLatin1().constData()); +} + +/*! + Returns the location of the attribute \a name within this shader + program's parameter list. Returns -1 if \a name is not a valid + attribute for this shader program. + + \sa uniformLocation(), bindAttributeLocation() +*/ +int QGLShaderProgram::attributeLocation(const char *name) const +{ + if (d->linked) { + return glGetAttribLocation(d->program, name); + } else { + qWarning() << "QGLShaderProgram::attributeLocation(" << name + << "): shader program is not linked"; + return -1; + } +} + +/*! + \overload + + Returns the location of the attribute \a name within this shader + program's parameter list. Returns -1 if \a name is not a valid + attribute for this shader program. + + \sa uniformLocation(), bindAttributeLocation() +*/ +int QGLShaderProgram::attributeLocation(const QByteArray& name) const +{ + return attributeLocation(name.constData()); +} + +/*! + \overload + + Returns the location of the attribute \a name within this shader + program's parameter list. Returns -1 if \a name is not a valid + attribute for this shader program. + + \sa uniformLocation(), bindAttributeLocation() +*/ +int QGLShaderProgram::attributeLocation(const QString& name) const +{ + return attributeLocation(name.toLatin1().constData()); +} + +/*! + Sets the attribute at \a location in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(int location, GLfloat value) +{ + if (location != -1) + glVertexAttrib1fv(location, &value); +} + +/*! + \overload + + Sets the attribute called \a name in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(const char *name, GLfloat value) +{ + setAttributeValue(attributeLocation(name), value); +} + +/*! + Sets the attribute at \a location in the current context to + the 2D vector (\a x, \a y). + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(int location, GLfloat x, GLfloat y) +{ + if (location != -1) { + GLfloat values[2] = {x, y}; + glVertexAttrib2fv(location, values); + } +} + +/*! + \overload + + Sets the attribute called \a name in the current context to + the 2D vector (\a x, \a y). + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(const char *name, GLfloat x, GLfloat y) +{ + setAttributeValue(attributeLocation(name), x, y); +} + +/*! + Sets the attribute at \a location in the current context to + the 3D vector (\a x, \a y, \a z). + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue + (int location, GLfloat x, GLfloat y, GLfloat z) +{ + if (location != -1) { + GLfloat values[3] = {x, y, z}; + glVertexAttrib3fv(location, values); + } +} + +/*! + \overload + + Sets the attribute called \a name in the current context to + the 3D vector (\a x, \a y, \a z). + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue + (const char *name, GLfloat x, GLfloat y, GLfloat z) +{ + setAttributeValue(attributeLocation(name), x, y, z); +} + +/*! + Sets the attribute at \a location in the current context to + the 4D vector (\a x, \a y, \a z, \a w). + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue + (int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w) +{ + if (location != -1) { + GLfloat values[4] = {x, y, z, w}; + glVertexAttrib4fv(location, values); + } +} + +/*! + \overload + + Sets the attribute called \a name in the current context to + the 4D vector (\a x, \a y, \a z, \a w). + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue + (const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w) +{ + setAttributeValue(attributeLocation(name), x, y, z, w); +} + +/*! + Sets the attribute at \a location in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(int location, const QVector2D& value) +{ + if (location != -1) + glVertexAttrib2fv(location, reinterpret_cast(&value)); +} + +/*! + \overload + + Sets the attribute called \a name in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(const char *name, const QVector2D& value) +{ + setAttributeValue(attributeLocation(name), value); +} + +/*! + Sets the attribute at \a location in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(int location, const QVector3D& value) +{ + if (location != -1) + glVertexAttrib3fv(location, reinterpret_cast(&value)); +} + +/*! + \overload + + Sets the attribute called \a name in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(const char *name, const QVector3D& value) +{ + setAttributeValue(attributeLocation(name), value); +} + +/*! + Sets the attribute at \a location in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(int location, const QVector4D& value) +{ + if (location != -1) + glVertexAttrib4fv(location, reinterpret_cast(&value)); +} + +/*! + \overload + + Sets the attribute called \a name in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(const char *name, const QVector4D& value) +{ + setAttributeValue(attributeLocation(name), value); +} + +/*! + Sets the attribute at \a location in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(int location, const QColor& value) +{ + if (location != -1) { + GLfloat values[4] = {value.redF(), value.greenF(), value.blueF(), value.alphaF()}; + glVertexAttrib4fv(location, values); + } +} + +/*! + \overload + + Sets the attribute called \a name in the current context to \a value. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue(const char *name, const QColor& value) +{ + setAttributeValue(attributeLocation(name), value); +} + +/*! + Sets the attribute at \a location in the current context to the + contents of \a values, which contains \a columns elements, each + consisting of \a rows elements. The \a rows value should be + 1, 2, 3, or 4. This function is typically used to set matrix + values and column vectors. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue + (int location, const GLfloat *values, int columns, int rows) +{ + if (rows < 1 || rows > 4) { + qWarning() << "QGLShaderProgram::setAttributeValue: rows" << rows << "not supported"; + return; + } + if (location != -1) { + while (columns-- > 0) { + if (rows == 1) + glVertexAttrib1fv(location, values); + else if (rows == 2) + glVertexAttrib2fv(location, values); + else if (rows == 3) + glVertexAttrib3fv(location, values); + else + glVertexAttrib4fv(location, values); + values += rows; + ++location; + } + } +} + +/*! + \overload + + Sets the attribute called \a name in the current context to the + contents of \a values, which contains \a columns elements, each + consisting of \a rows elements. The \a rows value should be + 1, 2, 3, or 4. This function is typically used to set matrix + values and column vectors. + + \sa setUniformValue() +*/ +void QGLShaderProgram::setAttributeValue + (const char *name, const GLfloat *values, int columns, int rows) +{ + setAttributeValue(attributeLocation(name), values, columns, rows); +} + +/*! + Sets an array of vertex \a values on the attribute at \a location + in this shader program. The \a size indicates the number of + components per vertex (1, 2, 3, or 4), and the \a stride indicates + the number of bytes between vertices. A default \a stride value + of zero indicates that the vertices are densely packed in \a values. + + \sa setAttributeValue(), setUniformValue(), disableAttributeArray() +*/ +void QGLShaderProgram::setAttributeArray + (int location, const GLfloat *values, int size, int stride) +{ + if (location != -1) { + glVertexAttribPointer(location, size, GL_FLOAT, GL_FALSE, + stride, values); + glEnableVertexAttribArray(location); + } +} + +/*! + Sets an array of 2D vertex \a values on the attribute at \a location + in this shader program. The \a stride indicates the number of bytes + between vertices. A default \a stride value of zero indicates that + the vertices are densely packed in \a values. + + \sa setAttributeValue(), setUniformValue(), disableAttributeArray() +*/ +void QGLShaderProgram::setAttributeArray + (int location, const QVector2D *values, int stride) +{ + if (location != -1) { + glVertexAttribPointer(location, 2, GL_FLOAT, GL_FALSE, + stride, values); + glEnableVertexAttribArray(location); + } +} + +/*! + Sets an array of 3D vertex \a values on the attribute at \a location + in this shader program. The \a stride indicates the number of bytes + between vertices. A default \a stride value of zero indicates that + the vertices are densely packed in \a values. + + \sa setAttributeValue(), setUniformValue(), disableAttributeArray() +*/ +void QGLShaderProgram::setAttributeArray + (int location, const QVector3D *values, int stride) +{ + if (location != -1) { + glVertexAttribPointer(location, 3, GL_FLOAT, GL_FALSE, + stride, values); + glEnableVertexAttribArray(location); + } +} + +/*! + Sets an array of 4D vertex \a values on the attribute at \a location + in this shader program. The \a stride indicates the number of bytes + between vertices. A default \a stride value of zero indicates that + the vertices are densely packed in \a values. + + \sa setAttributeValue(), setUniformValue(), disableAttributeArray() +*/ +void QGLShaderProgram::setAttributeArray + (int location, const QVector4D *values, int stride) +{ + if (location != -1) { + glVertexAttribPointer(location, 4, GL_FLOAT, GL_FALSE, + stride, values); + glEnableVertexAttribArray(location); + } +} + +/*! + \overload + + Sets an array of vertex \a values on the attribute called \a name + in this shader program. The \a size indicates the number of + components per vertex (1, 2, 3, or 4), and the \a stride indicates + the number of bytes between vertices. A default \a stride value + of zero indicates that the vertices are densely packed in \a values. + + \sa setAttributeValue(), setUniformValue(), disableAttributeArray() +*/ +void QGLShaderProgram::setAttributeArray + (const char *name, const GLfloat *values, int size, int stride) +{ + setAttributeArray(attributeLocation(name), values, size, stride); +} + +/*! + \overload + + Sets an array of 2D vertex \a values on the attribute called \a name + in this shader program. The \a stride indicates the number of bytes + between vertices. A default \a stride value of zero indicates that + the vertices are densely packed in \a values. + + \sa setAttributeValue(), setUniformValue(), disableAttributeArray() +*/ +void QGLShaderProgram::setAttributeArray + (const char *name, const QVector2D *values, int stride) +{ + setAttributeArray(attributeLocation(name), values, stride); +} + +/*! + \overload + + Sets an array of 3D vertex \a values on the attribute called \a name + in this shader program. The \a stride indicates the number of bytes + between vertices. A default \a stride value of zero indicates that + the vertices are densely packed in \a values. + + \sa setAttributeValue(), setUniformValue(), disableAttributeArray() +*/ +void QGLShaderProgram::setAttributeArray + (const char *name, const QVector3D *values, int stride) +{ + setAttributeArray(attributeLocation(name), values, stride); +} + +/*! + \overload + + Sets an array of 4D vertex \a values on the attribute called \a name + in this shader program. The \a stride indicates the number of bytes + between vertices. A default \a stride value of zero indicates that + the vertices are densely packed in \a values. + + \sa setAttributeValue(), setUniformValue(), disableAttributeArray() +*/ +void QGLShaderProgram::setAttributeArray + (const char *name, const QVector4D *values, int stride) +{ + setAttributeArray(attributeLocation(name), values, stride); +} + +/*! + Disables the vertex array at \a location in this shader program + that was enabled by a previous call to setAttributeArray(). + + \sa setAttributeArray(), setAttributeValue(), setUniformValue() +*/ +void QGLShaderProgram::disableAttributeArray(int location) +{ + if (location != -1) + glDisableVertexAttribArray(location); +} + +/*! + \overload + + Disables the vertex array called \a name in this shader program + that was enabled by a previous call to setAttributeArray(). + + \sa setAttributeArray(), setAttributeValue(), setUniformValue() +*/ +void QGLShaderProgram::disableAttributeArray(const char *name) +{ + disableAttributeArray(attributeLocation(name)); +} + +/*! + Returns the location of the uniform variable \a name within this shader + program's parameter list. Returns -1 if \a name is not a valid + uniform variable for this shader program. + + \sa attributeLocation() +*/ +int QGLShaderProgram::uniformLocation(const char *name) const +{ + if (d->linked) { + return glGetUniformLocation(d->program, name); + } else { + qWarning() << "QGLShaderProgram::uniformLocation(" << name + << "): shader program is not linked"; + return -1; + } +} + +/*! + \overload + + Returns the location of the uniform variable \a name within this shader + program's parameter list. Returns -1 if \a name is not a valid + uniform variable for this shader program. + + \sa attributeLocation() +*/ +int QGLShaderProgram::uniformLocation(const QByteArray& name) const +{ + return uniformLocation(name.constData()); +} + +/*! + \overload + + Returns the location of the uniform variable \a name within this shader + program's parameter list. Returns -1 if \a name is not a valid + uniform variable for this shader program. + + \sa attributeLocation() +*/ +int QGLShaderProgram::uniformLocation(const QString& name) const +{ + return uniformLocation(name.toLatin1().constData()); +} + +/*! + Sets the uniform variable at \a location in the current context to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, GLfloat value) +{ + if (location != -1) + glUniform1fv(location, 1, &value); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, GLfloat value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context to \a value. + This function must be used when setting sampler values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, GLint value) +{ + if (location != -1) + glUniform1i(location, value); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to \a value. This function must be used when setting sampler values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, GLint value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context to + the 2D vector (\a x, \a y). + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, GLfloat x, GLfloat y) +{ + if (location != -1) { + GLfloat values[2] = {x, y}; + glUniform2fv(location, 1, values); + } +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context to + the 2D vector (\a x, \a y). + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, GLfloat x, GLfloat y) +{ + setUniformValue(uniformLocation(name), x, y); +} + +/*! + Sets the uniform variable at \a location in the current context to + the 3D vector (\a x, \a y, \a z). + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue + (int location, GLfloat x, GLfloat y, GLfloat z) +{ + if (location != -1) { + GLfloat values[3] = {x, y, z}; + glUniform3fv(location, 1, values); + } +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context to + the 3D vector (\a x, \a y, \a z). + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue + (const char *name, GLfloat x, GLfloat y, GLfloat z) +{ + setUniformValue(uniformLocation(name), x, y, z); +} + +/*! + Sets the uniform variable at \a location in the current context to + the 4D vector (\a x, \a y, \a z, \a w). + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue + (int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w) +{ + if (location != -1) { + GLfloat values[4] = {x, y, z, w}; + glUniform4fv(location, 1, values); + } +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context to + the 4D vector (\a x, \a y, \a z, \a w). + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue + (const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w) +{ + setUniformValue(uniformLocation(name), x, y, z, w); +} + +/*! + Sets the uniform variable at \a location in the current context to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QVector2D& value) +{ + if (location != -1) + glUniform2fv(location, 1, reinterpret_cast(&value)); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QVector2D& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QVector3D& value) +{ + if (location != -1) + glUniform3fv(location, 1, reinterpret_cast(&value)); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QVector3D& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QVector4D& value) +{ + if (location != -1) + glUniform4fv(location, 1, reinterpret_cast(&value)); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QVector4D& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context to + the red, green, blue, and alpha components of \a color. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QColor& color) +{ + if (location != -1) { + GLfloat values[4] = {color.redF(), color.greenF(), color.blueF(), color.alphaF()}; + glUniform4fv(location, 1, values); + } +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context to + the red, green, blue, and alpha components of \a color. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QColor& color) +{ + setUniformValue(uniformLocation(name), color); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 2x2 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix2x2& value) +{ + if (location != -1) + glUniformMatrix2fv(location, 1, GL_FALSE, value.data()); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 2x2 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix2x2& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 2x3 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix2x3& value) +{ +#if !defined(QT_OPENGL_ES_2) + if (location != -1) { + if (glUniformMatrix2x3fv) { + // OpenGL 2.1+: pass the matrix directly. + glUniformMatrix2x3fv(location, 1, GL_FALSE, value.data()); + } else { + // OpenGL 2.0: pass the matrix columns as a vector. + glUniform3fv(location, 2, value.data()); + } + } +#else + if (location != -1) + glUniform3fv(location, 2, value.data()); +#endif +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 2x3 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix2x3& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 2x4 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix2x4& value) +{ +#if !defined(QT_OPENGL_ES_2) + if (location != -1) { + if (glUniformMatrix2x4fv) { + // OpenGL 2.1+: pass the matrix directly. + glUniformMatrix2x4fv(location, 1, GL_FALSE, value.data()); + } else { + // OpenGL 2.0: pass the matrix columns as a vector. + glUniform4fv(location, 2, value.data()); + } + } +#else + if (location != -1) + glUniform4fv(location, 2, value.data()); +#endif +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 2x4 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix2x4& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 3x2 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix3x2& value) +{ +#if !defined(QT_OPENGL_ES_2) + if (location != -1) { + if (glUniformMatrix3x2fv) { + // OpenGL 2.1+: pass the matrix directly. + glUniformMatrix3x2fv(location, 1, GL_FALSE, value.data()); + } else { + // OpenGL 2.0: pass the matrix columns as a vector. + glUniform2fv(location, 3, value.data()); + } + } +#else + if (location != -1) + glUniform2fv(location, 3, value.data()); +#endif +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 3x2 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix3x2& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 3x3 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix3x3& value) +{ + if (location != -1) + glUniformMatrix3fv(location, 1, GL_FALSE, value.data()); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 3x3 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix3x3& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 3x4 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix3x4& value) +{ +#if !defined(QT_OPENGL_ES_2) + if (location != -1) { + if (glUniformMatrix3x4fv) { + // OpenGL 2.1+: pass the matrix directly. + glUniformMatrix3x4fv(location, 1, GL_FALSE, value.data()); + } else { + // OpenGL 2.0: pass the matrix columns as a vector. + glUniform4fv(location, 3, value.data()); + } + } +#else + if (location != -1) + glUniform4fv(location, 3, value.data()); +#endif +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 3x4 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix3x4& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 4x2 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix4x2& value) +{ +#if !defined(QT_OPENGL_ES_2) + if (location != -1) { + if (glUniformMatrix4x2fv) { + // OpenGL 2.1+: pass the matrix directly. + glUniformMatrix4x2fv(location, 1, GL_FALSE, value.data()); + } else { + // OpenGL 2.0: pass the matrix columns as a vector. + glUniform2fv(location, 4, value.data()); + } + } +#else + if (location != -1) + glUniform2fv(location, 4, value.data()); +#endif +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 4x2 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix4x2& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 4x3 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix4x3& value) +{ +#if !defined(QT_OPENGL_ES_2) + if (location != -1) { + if (glUniformMatrix4x3fv) { + // OpenGL 2.1+: pass the matrix directly. + glUniformMatrix4x3fv(location, 1, GL_FALSE, value.data()); + } else { + // OpenGL 2.0: pass the matrix columns as a vector. + glUniform3fv(location, 4, value.data()); + } + } +#else + if (location != -1) + glUniform3fv(location, 4, value.data()); +#endif +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 4x3 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix4x3& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context + to a 4x4 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QMatrix4x4& value) +{ + if (location != -1) + glUniformMatrix4fv(location, 1, GL_FALSE, value.data()); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 4x4 matrix \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QMatrix4x4& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + \overload + + Sets the uniform variable at \a location in the current context + to a 4x4 matrix \a value. The matrix elements must be specified + in column-major order. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const GLfloat value[4][4]) +{ + if (location != -1) + glUniformMatrix4fv(location, 1, GL_FALSE, value[0]); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to a 4x4 matrix \a value. The matrix elements must be specified + in column-major order. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const GLfloat value[4][4]) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable at \a location in the current context to a + 3x3 transformation matrix \a value that is specified as a QTransform value. + + To set a QTransform value as a 4x4 matrix in a shader, use + \c{setUniformValue(location, QMatrix4x4(value))}. +*/ +void QGLShaderProgram::setUniformValue(int location, const QTransform& value) +{ + if (location != -1) { + GLfloat mat[3][3] = { + {value.m11(), value.m12(), value.m13()}, + {value.m21(), value.m22(), value.m23()}, + {value.m31(), value.m32(), value.m33()} + }; + glUniformMatrix3fv(location, 1, GL_FALSE, mat[0]); + } +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context to a + 3x3 transformation matrix \a value that is specified as a QTransform value. + + To set a QTransform value as a 4x4 matrix in a shader, use + \c{setUniformValue(name, QMatrix4x4(value))}. +*/ +void QGLShaderProgram::setUniformValue + (const char *name, const QTransform& value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count elements of \a values. This overload + must be used when setting an array of sampler values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const GLint *values, int count) +{ + if (location != -1) + glUniform1iv(location, count, values); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count elements of \a values. This overload + must be used when setting an array of sampler values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray + (const char *name, const GLint *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count elements of \a values. Each element + has \a size components. The \a size must be 1, 2, 3, or 4. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const GLfloat *values, int count, int size) +{ + if (location != -1) { + if (size == 1) + glUniform1fv(location, count, values); + else if (size == 2) + glUniform2fv(location, count, values); + else if (size == 3) + glUniform3fv(location, count, values); + else if (size == 4) + glUniform4fv(location, count, values); + else + qWarning() << "QGLShaderProgram::setUniformValue: size" << size << "not supported"; + } +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count elements of \a values. Each element + has \a size components. The \a size must be 1, 2, 3, or 4. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray + (const char *name, const GLfloat *values, int count, int size) +{ + setUniformValueArray(uniformLocation(name), values, count, size); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 2D vector elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QVector2D *values, int count) +{ + if (location != -1) + glUniform2fv(location, count, reinterpret_cast(values)); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 2D vector elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QVector2D *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 3D vector elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QVector3D *values, int count) +{ + if (location != -1) + glUniform3fv(location, count, reinterpret_cast(values)); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 3D vector elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QVector3D *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 4D vector elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QVector4D *values, int count) +{ + if (location != -1) + glUniform4fv(location, count, reinterpret_cast(values)); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 4D vector elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QVector4D *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +// We may have to repack matrix arrays if the matrix types +// contain additional flag bits. Especially QMatrix4x4. +#define setUniformMatrixArray(func,location,values,count,type,cols,rows) \ + if (location == -1 || count <= 0) \ + return; \ + if (count == 1 || sizeof(type) == cols * rows * sizeof(GLfloat)) { \ + func(location, count, GL_FALSE, values->constData()); \ + } else { \ + QVarLengthArray temp(cols * rows * count); \ + for (int index = 0; index < count; ++index) { \ + qMemCopy(temp.data() + cols * rows * index, \ + values[index].constData(), cols * rows * sizeof(GLfloat)); \ + } \ + func(location, count, GL_FALSE, temp.constData()); \ + } +#if !defined(QT_OPENGL_ES_2) +#define setUniformGenericMatrixArray(func,colfunc,location,values,count,type,cols,rows) \ + if (location == -1 || count <= 0) \ + return; \ + if (count == 1 || sizeof(type) == cols * rows * sizeof(GLfloat)) { \ + if (func) \ + func(location, count, GL_FALSE, values->constData()); \ + else \ + colfunc(location, cols * count, values->constData()); \ + } else { \ + QVarLengthArray temp(cols * rows * count); \ + for (int index = 0; index < count; ++index) { \ + qMemCopy(temp.data() + cols * rows * index, \ + values[index].constData(), cols * rows * sizeof(GLfloat)); \ + } \ + if (func) \ + func(location, count, GL_FALSE, temp.constData()); \ + else \ + colfunc(location, count * cols, temp.constData()); \ + } +#else +#define setUniformGenericMatrixArray(func,colfunc,location,values,count,type,cols,rows) \ + if (location == -1 || count <= 0) \ + return; \ + if (count == 1 || sizeof(type) == cols * rows * sizeof(GLfloat)) { \ + colfunc(location, cols * count, values->constData()); \ + } else { \ + QVarLengthArray temp(cols * rows * count); \ + for (int index = 0; index < count; ++index) { \ + qMemCopy(temp.data() + cols * rows * index, \ + values[index].constData(), cols * rows * sizeof(GLfloat)); \ + } \ + colfunc(location, count * cols, temp.constData()); \ + } +#endif + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 2x2 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix2x2 *values, int count) +{ + setUniformMatrixArray + (glUniformMatrix2fv, location, values, count, QMatrix2x2, 2, 2); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 2x2 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix2x2 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 2x3 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix2x3 *values, int count) +{ + setUniformGenericMatrixArray + (glUniformMatrix2x3fv, glUniform3fv, location, values, count, + QMatrix2x3, 2, 3); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 2x3 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix2x3 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 2x4 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix2x4 *values, int count) +{ + setUniformGenericMatrixArray + (glUniformMatrix2x4fv, glUniform4fv, location, values, count, + QMatrix2x4, 2, 4); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 2x4 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix2x4 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 3x2 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix3x2 *values, int count) +{ + setUniformGenericMatrixArray + (glUniformMatrix3x2fv, glUniform2fv, location, values, count, + QMatrix3x2, 3, 2); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 3x2 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix3x2 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 3x3 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix3x3 *values, int count) +{ + setUniformMatrixArray + (glUniformMatrix3fv, location, values, count, QMatrix3x3, 3, 3); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 3x3 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix3x3 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 3x4 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix3x4 *values, int count) +{ + setUniformGenericMatrixArray + (glUniformMatrix3x4fv, glUniform4fv, location, values, count, + QMatrix3x4, 3, 4); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 3x4 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix3x4 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 4x2 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix4x2 *values, int count) +{ + setUniformGenericMatrixArray + (glUniformMatrix4x2fv, glUniform2fv, location, values, count, + QMatrix4x2, 4, 2); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 4x2 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix4x2 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 4x3 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix4x3 *values, int count) +{ + setUniformGenericMatrixArray + (glUniformMatrix4x3fv, glUniform3fv, location, values, count, + QMatrix4x3, 4, 3); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 4x3 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix4x3 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Sets the uniform variable array at \a location in the current + context to the \a count 4x4 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(int location, const QMatrix4x4 *values, int count) +{ + setUniformMatrixArray + (glUniformMatrix4fv, location, values, count, QMatrix4x4, 4, 4); +} + +/*! + \overload + + Sets the uniform variable array called \a name in the current + context to the \a count 4x4 matrix elements of \a values. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValueArray(const char *name, const QMatrix4x4 *values, int count) +{ + setUniformValueArray(uniformLocation(name), values, count); +} + +/*! + Returns true if shader programs written in the OpenGL Shading + Language (GLSL) are supported on this system; false otherwise. + + The \a context is used to resolve the GLSL extensions. + If \a context is null, then QGLContext::currentContext() is used. +*/ +bool QGLShaderProgram::hasShaderPrograms(const QGLContext *context) +{ +#if !defined(QT_OPENGL_ES_2) + if (!context) + context = QGLContext::currentContext(); + if (!context) + return false; + return qt_resolve_glsl_extensions(const_cast(context)); +#else + Q_UNUSED(context); + return true; +#endif +} + +#endif + +QT_END_NAMESPACE diff --git a/src/opengl/qglshaderprogram.h b/src/opengl/qglshaderprogram.h new file mode 100644 index 0000000..ec6faaf --- /dev/null +++ b/src/opengl/qglshaderprogram.h @@ -0,0 +1,285 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtOpenGL module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QGLSHADERPROGRAM_H +#define QGLSHADERPROGRAM_H + +#include +#include +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(OpenGL) + +#if !defined(QT_OPENGL_ES_1_CL) && !defined(QT_GL_FIXED_PREFERRED) + +class QGLShaderProgram; +class QGLShaderPrivate; + +class Q_OPENGL_EXPORT QGLShader : public QObject +{ + Q_OBJECT +public: + enum ShaderType + { + VertexShader, + FragmentShader, + PartialVertexShader, + PartialFragmentShader + }; + + explicit QGLShader(QGLShader::ShaderType type, QObject *parent = 0); + explicit QGLShader(const QString& fileName, QObject *parent = 0); + QGLShader(const QString& fileName, QGLShader::ShaderType type, QObject *parent = 0); + QGLShader(QGLShader::ShaderType type, const QGLContext *context, QObject *parent = 0); + QGLShader(const QString& fileName, const QGLContext *context, QObject *parent = 0); + QGLShader(const QString& fileName, QGLShader::ShaderType type, const QGLContext *context, QObject *parent = 0); + virtual ~QGLShader(); + + bool isValid() const; + + QGLShader::ShaderType shaderType() const; + + bool setSourceCode(const char *source); + bool setSourceCode(const QByteArray& source); + bool setSourceCode(const QString& source); + bool setSourceCodeFile(const QString& fileName); + + bool setBinaryCode(GLenum format, const void *binary, int length); + bool setBinaryCode(QGLShader& otherShader, GLenum format, const void *binary, int length); + + static QList shaderBinaryFormats(); + + QByteArray sourceCode() const; + + bool isCompiled() const; + QString errors() const; + + GLuint shaderId() const; + +private: + QGLShaderPrivate *d; + + friend class QGLShaderProgram; + + Q_DISABLE_COPY(QGLShader); +}; + +class QGLShaderProgramPrivate; + +class Q_OPENGL_EXPORT QGLShaderProgram : public QObject +{ + Q_OBJECT +public: + explicit QGLShaderProgram(QObject *parent = 0); + explicit QGLShaderProgram(const QGLContext *context, QObject *parent = 0); + virtual ~QGLShaderProgram(); + + bool isValid() const; + + bool addShader(QGLShader *shader); + void removeShader(QGLShader *shader); + QList shaders() const; + + bool addShader(QGLShader::ShaderType type, const char *source); + bool addShader(QGLShader::ShaderType type, const QByteArray& source); + bool addShader(QGLShader::ShaderType type, const QString& source); + + void removeAllShaders(); + + QByteArray programBinary(int *format) const; + bool setProgramBinary(int format, const QByteArray& binary); + static QList programBinaryFormats(); + + virtual bool link(); + bool isLinked() const; + QString errors() const; + + bool enable(); + void disable(); + + GLuint programId() const; + + void bindAttributeLocation(const char *name, int location); + void bindAttributeLocation(const QByteArray& name, int location); + void bindAttributeLocation(const QString& name, int location); + + int attributeLocation(const char *name) const; + int attributeLocation(const QByteArray& name) const; + int attributeLocation(const QString& name) const; + + void setAttributeValue(int location, GLfloat value); + void setAttributeValue(int location, GLfloat x, GLfloat y); + void setAttributeValue(int location, GLfloat x, GLfloat y, GLfloat z); + void setAttributeValue(int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void setAttributeValue(int location, const QVector2D& value); + void setAttributeValue(int location, const QVector3D& value); + void setAttributeValue(int location, const QVector4D& value); + void setAttributeValue(int location, const QColor& value); + void setAttributeValue(int location, const GLfloat *values, int columns, int rows); + + void setAttributeValue(const char *name, GLfloat value); + void setAttributeValue(const char *name, GLfloat x, GLfloat y); + void setAttributeValue(const char *name, GLfloat x, GLfloat y, GLfloat z); + void setAttributeValue(const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void setAttributeValue(const char *name, const QVector2D& value); + void setAttributeValue(const char *name, const QVector3D& value); + void setAttributeValue(const char *name, const QVector4D& value); + void setAttributeValue(const char *name, const QColor& value); + void setAttributeValue(const char *name, const GLfloat *values, int columns, int rows); + + void setAttributeArray + (int location, const GLfloat *values, int size, int stride = 0); + void setAttributeArray + (int location, const QVector2D *values, int stride = 0); + void setAttributeArray + (int location, const QVector3D *values, int stride = 0); + void setAttributeArray + (int location, const QVector4D *values, int stride = 0); + void setAttributeArray + (const char *name, const GLfloat *values, int size, int stride = 0); + void setAttributeArray + (const char *name, const QVector2D *values, int stride = 0); + void setAttributeArray + (const char *name, const QVector3D *values, int stride = 0); + void setAttributeArray + (const char *name, const QVector4D *values, int stride = 0); + void disableAttributeArray(int location); + void disableAttributeArray(const char *name); + + int uniformLocation(const char *name) const; + int uniformLocation(const QByteArray& name) const; + int uniformLocation(const QString& name) const; + + void setUniformValue(int location, GLfloat value); + void setUniformValue(int location, GLint value); + void setUniformValue(int location, GLfloat x, GLfloat y); + void setUniformValue(int location, GLfloat x, GLfloat y, GLfloat z); + void setUniformValue(int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void setUniformValue(int location, const QVector2D& value); + void setUniformValue(int location, const QVector3D& value); + void setUniformValue(int location, const QVector4D& value); + void setUniformValue(int location, const QColor& color); + void setUniformValue(int location, const QMatrix2x2& value); + void setUniformValue(int location, const QMatrix2x3& value); + void setUniformValue(int location, const QMatrix2x4& value); + void setUniformValue(int location, const QMatrix3x2& value); + void setUniformValue(int location, const QMatrix3x3& value); + void setUniformValue(int location, const QMatrix3x4& value); + void setUniformValue(int location, const QMatrix4x2& value); + void setUniformValue(int location, const QMatrix4x3& value); + void setUniformValue(int location, const QMatrix4x4& value); + void setUniformValue(int location, const GLfloat value[4][4]); + void setUniformValue(int location, const QTransform& value); + + void setUniformValue(const char *name, GLfloat value); + void setUniformValue(const char *name, GLint value); + void setUniformValue(const char *name, GLfloat x, GLfloat y); + void setUniformValue(const char *name, GLfloat x, GLfloat y, GLfloat z); + void setUniformValue(const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); + void setUniformValue(const char *name, const QVector2D& value); + void setUniformValue(const char *name, const QVector3D& value); + void setUniformValue(const char *name, const QVector4D& value); + void setUniformValue(const char *name, const QColor& color); + void setUniformValue(const char *name, const QMatrix2x2& value); + void setUniformValue(const char *name, const QMatrix2x3& value); + void setUniformValue(const char *name, const QMatrix2x4& value); + void setUniformValue(const char *name, const QMatrix3x2& value); + void setUniformValue(const char *name, const QMatrix3x3& value); + void setUniformValue(const char *name, const QMatrix3x4& value); + void setUniformValue(const char *name, const QMatrix4x2& value); + void setUniformValue(const char *name, const QMatrix4x3& value); + void setUniformValue(const char *name, const QMatrix4x4& value); + void setUniformValue(const char *name, const GLfloat value[4][4]); + void setUniformValue(const char *name, const QTransform& value); + + void setUniformValueArray(int location, const GLfloat *values, int count, int size); + void setUniformValueArray(int location, const GLint *values, int count); + void setUniformValueArray(int location, const QVector2D *values, int count); + void setUniformValueArray(int location, const QVector3D *values, int count); + void setUniformValueArray(int location, const QVector4D *values, int count); + void setUniformValueArray(int location, const QMatrix2x2 *values, int count); + void setUniformValueArray(int location, const QMatrix2x3 *values, int count); + void setUniformValueArray(int location, const QMatrix2x4 *values, int count); + void setUniformValueArray(int location, const QMatrix3x2 *values, int count); + void setUniformValueArray(int location, const QMatrix3x3 *values, int count); + void setUniformValueArray(int location, const QMatrix3x4 *values, int count); + void setUniformValueArray(int location, const QMatrix4x2 *values, int count); + void setUniformValueArray(int location, const QMatrix4x3 *values, int count); + void setUniformValueArray(int location, const QMatrix4x4 *values, int count); + + void setUniformValueArray(const char *name, const GLfloat *values, int count, int size); + void setUniformValueArray(const char *name, const GLint *values, int count); + void setUniformValueArray(const char *name, const QVector2D *values, int count); + void setUniformValueArray(const char *name, const QVector3D *values, int count); + void setUniformValueArray(const char *name, const QVector4D *values, int count); + void setUniformValueArray(const char *name, const QMatrix2x2 *values, int count); + void setUniformValueArray(const char *name, const QMatrix2x3 *values, int count); + void setUniformValueArray(const char *name, const QMatrix2x4 *values, int count); + void setUniformValueArray(const char *name, const QMatrix3x2 *values, int count); + void setUniformValueArray(const char *name, const QMatrix3x3 *values, int count); + void setUniformValueArray(const char *name, const QMatrix3x4 *values, int count); + void setUniformValueArray(const char *name, const QMatrix4x2 *values, int count); + void setUniformValueArray(const char *name, const QMatrix4x3 *values, int count); + void setUniformValueArray(const char *name, const QMatrix4x4 *values, int count); + + static bool hasShaderPrograms(const QGLContext *context = 0); + +private: + QGLShaderProgramPrivate *d; + + Q_DISABLE_COPY(QGLShaderProgram); + + bool init(); +}; + +#endif + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif -- cgit v0.12 From 0b97a00eae721304a31642fcb8892b66fb670f9e Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Fri, 27 Mar 2009 12:22:04 +1000 Subject: Bug in QGLShaderProgram::addShader() that stopped partial shaders working. --- src/opengl/qglshaderprogram.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp index 934b5a5..3c19434 100644 --- a/src/opengl/qglshaderprogram.cpp +++ b/src/opengl/qglshaderprogram.cpp @@ -849,13 +849,16 @@ bool QGLShaderProgram::addShader(QGLShader *shader) return false; if (d->shaders.contains(shader)) return true; // Already added to this shader program. - if (d->program && shader && shader->d->shader) { + if (d->program && shader) { if (!shader->d->compiled) return false; - if (!shader->d->isPartial) + if (!shader->d->isPartial) { + if (!shader->d->shader) + return false; glAttachShader(d->program, shader->d->shader); - else + } else { d->hasPartialShaders = true; + } d->linked = false; // Program needs to be relinked. d->shaders.append(shader); return true; -- cgit v0.12 From 0cbe2a23966116e642fee4ccc34aeac73a5c57cd Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Fri, 27 Mar 2009 12:34:48 +1000 Subject: Fix loading of partial shaders from files. --- src/opengl/qglshaderprogram.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp index 3c19434..5738acd 100644 --- a/src/opengl/qglshaderprogram.cpp +++ b/src/opengl/qglshaderprogram.cpp @@ -573,9 +573,6 @@ bool QGLShader::setSourceCode(const QString& source) */ bool QGLShader::setSourceCodeFile(const QString& fileName) { - if (!d->shader) - return false; - QFile file(fileName); if (!file.open(QFile::ReadOnly)) { qWarning() << "QGLShader: Unable to open file" << fileName; -- cgit v0.12 From 8559f2d8db6f99292fc8a26623e166f64f9d4a8f Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 3 Apr 2009 12:59:10 +0200 Subject: Fix build breakage after rebasing on graphics-main Reviewed-by: Trustme --- src/opengl/gl2paintengineex/qglshader.cpp | 1 + src/opengl/qglextensions_p.h | 8 -------- 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglshader.cpp b/src/opengl/gl2paintengineex/qglshader.cpp index 4ac6e61..ea4cae9 100644 --- a/src/opengl/gl2paintengineex/qglshader.cpp +++ b/src/opengl/gl2paintengineex/qglshader.cpp @@ -51,6 +51,7 @@ #if !defined(QT_OPENGL_ES_2) static const char *qglslDefines = "#define lowp\n#define mediump\n#define highp\n"; +#include "private/qgl_p.h" #else static const char *qglslDefines = ""; #endif diff --git a/src/opengl/qglextensions_p.h b/src/opengl/qglextensions_p.h index 69632e7..9249730 100644 --- a/src/opengl/qglextensions_p.h +++ b/src/opengl/qglextensions_p.h @@ -412,18 +412,10 @@ struct QGLExtensionFuncs _glUnmapBufferARB qt_glUnmapBufferARB; _glGetActiveAttrib qt_glGetActiveAttrib; - _glGetAttribLocation qt_glGetAttribLocation; _glGetActiveUniform qt_glGetActiveUniform; - _glGetProgramInfoLog qt_glGetProgramInfoLog; _glUniform1f qt_glUniform1f; _glUniform2f qt_glUniform2f; _glUniform4f qt_glUniform4f; - _glUniformMatrix2fv qt_glUniformMatrix2fv; - _glUniformMatrix3fv qt_glUniformMatrix3fv; - _glUniformMatrix4fv qt_glUniformMatrix4fv; - _glEnableVertexAttribArray qt_glEnableVertexAttribArray; - _glDisableVertexAttribArray qt_glDisableVertexAttribArray; - _glVertexAttribPointer qt_glVertexAttribPointer; _glStencilOpSeparate qt_glStencilOpSeparate; }; -- cgit v0.12 From 2485575f1883fe990d0072eed2231a5bd06948af Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 3 Apr 2009 14:30:25 +0200 Subject: Add (big) comment explaining shader pipeline in GL2 engine Reviewed-by: TrustMe --- src/opengl/gl2paintengineex/glgc_shader_source.h | 138 +++++++++++++++++++++++ 1 file changed, 138 insertions(+) diff --git a/src/opengl/gl2paintengineex/glgc_shader_source.h b/src/opengl/gl2paintengineex/glgc_shader_source.h index 5b9d28b..47a1cbb 100644 --- a/src/opengl/gl2paintengineex/glgc_shader_source.h +++ b/src/opengl/gl2paintengineex/glgc_shader_source.h @@ -48,6 +48,144 @@ QT_BEGIN_NAMESPACE QT_MODULE(OpenGL) + +/* + VERTEX SHADERS + ============== + + Vertex shaders are specified as multiple (partial) shaders. On desktop, + this works fine. On ES, QGLShader & QGLShaderProgram will make partial + shaders work by concatenating the source in each QGLShader and compiling + it as a single shader. This is abstracted nicely by QGLShaderProgram and + the GL2 engine doesn't need to worry about it. + + Generally, there's two vertex shader objects. The position shaders are + the ones which set gl_Position. There's also two "main" vertex shaders, + one which just calls the position shader and another which also passes + through some texture coordinates from a vertex attribute array to a + varying. These texture coordinates are used for mask position in text + rendering and for the source coordinates in drawImage/drawPixmap. There's + also a "Simple" vertex shader for rendering a solid colour (used to render + into the stencil buffer where the actual colour value is discarded). + + The position shaders for brushes look scary. This is because many of the + calculations which logically belong in the fragment shader have been moved + into the vertex shader to improve performance. This is why the position + calculation is in a seperate shader. Not only does it calculate the + position, but it also calculates some data to be passed to the fragment + shader as a varying. It is optimal to move as much of the calculation as + possible into the vertex shader as this is executed less often. + + The varyings passed to the fragment shaders are interpolated (which is + cheap). Unfortunately, GL will apply perspective correction to the + interpolation calusing errors. To get around this, the vertex shader must + apply perspective correction itself and set the w-value of gl_Position to + zero. That way, GL will be tricked into thinking it doesn't need to apply a + perspective correction and use linear interpolation instead (which is what + we want). Of course, if the brush transform is affeine, no perspective + correction is needed and a simpler vertex shader can be used instead. + + So there are the following "main" vertex shaders: + qglslSimpleVertexShader + qglslMainVertexShader + qglslMainWithTexCoordsVertexShader + + And the the following position vertex shaders: + qglslPositionOnlyVertexShader + qglslPositionWithTextureBrushVertexShader + qglslPositionWithPatternBrushVertexShader + qglslPositionWithLinearGradientBrushVertexShader + qglslPositionWithRadialGradientBrushVertexShader + qglslPositionWithConicalGradientBrushVertexShader + qglslAffinePositionWithTextureBrushVertexShader + qglslAffinePositionWithPatternBrushVertexShader + qglslAffinePositionWithLinearGradientBrushVertexShader + qglslAffinePositionWithRadialGradientBrushVertexShader + qglslAffinePositionWithConicalGradientBrushVertexShader + + Leading to 23 possible vertex shaders + + + FRAGMENT SHADERS + ================ + + Fragment shaders are also specified as multiple (partial) shaders. The + different fragment shaders represent the different stages in Qt's fragment + pipeline. There are 1-3 stages in this pipeline: First stage is to get the + fragment's colour value. The next stage is to get the fragment's mask value + (coverage value for anti-aliasing) and the final stage is to blend the + incoming fragment with the background (for composition modes not supported + by GL). + + Of these, the first stage will always be present. If Qt doesn't need to + apply anti-aliasing (because it's off or handled by multisampling) then + the coverage value doesn't need to be applied. (Note: There are two types + of mask, one for regular anti-aliasing and one for sub-pixel anti- + aliasing.) If the composition mode is one which GL supports natively then + the blending stage doesn't need to be applied. + + As eash stage can have multiple implementations, they are abstracted as + GLSL function calls, with the following signatures: + + Brushes & image drawing are implementations of "mediump vec4 srcPixel()": + qglslImageFragmentShader + qglslNonPremultipliedImageFragmentShader + qglslSolidBrushFragmentShader + qglslTextureBrushFragmentShader + qglslPatternBrushFragmentShader + qglslLinearGradientBrushFragmentShader + qglslRadialGradientBrushFragmentShader + qglslConicalGradientBrushFragmentShader + + NOTE: It is assumed the colour returned by srcPixel() is pre-multiplied + + The two masks are have these signature and are called: + qglslMaskFragmentShader: "mediump float mask()" + qglslRgbMaskFragmentShader: "mediump vec3 rgbMask()" + + Composition modes are "mediump vec4 composite(mediump vec4 src, mediump vec4 dest)": + qglslColorBurnCompositionModeFragmentShader + qglslColorDodgeCompositionModeFragmentShader + qglslDarkenCompositionModeFragmentShader + qglslDifferenceCompositionModeFragmentShader + qglslExclusionCompositionModeFragmentShader + qglslHardLightCompositionModeFragmentShader + qglslLightenCompositionModeFragmentShader + qglslMultiplyCompositionModeFragmentShader + qglslOverlayCompositionModeFragmentShader + qglslScreenCompositionModeFragmentShader + qglslSoftLightCompositionModeFragmentShader + + + So there are differnt frament shader main functions, depending on the + number & type of pipelines the fragment needs to go through. + + The choice of which main() fragment shader string to use depends on: + - Use of global opacity + - Brush style (some brushes apply opacity themselves) + - Use & type of mask (TODO: Need to support high quality anti-aliasing & text) + - Use of gamma-correction + - Use of non-GL Composition mode + + + CUSTOM SHADER CODE (idea) + ================== + + The use of custom shader code is supported by the engine for drawImage and + drawPixmap calls. This is implemented via hooks in the fragment pipeline. + The custom shader is passed to the engine as a partial fragment shader + (QGLCustomizedShader). The shader will implement a pre-defined method name + which Qt's fragment pipeline will call. There are two different hooks which + can be implemented as custom shader code: + + mediump vec4 customShader(sampler2d src, vec2 srcCoords) + mediump vec4 customShaderWithDest(sampler2d dest, sampler2d src, vec2 srcCoords) + +*/ + +///////////////////////////////////////////////////////////////////// + + static const char* qglslImageVertexShader = "\ attribute highp vec4 inputVertex; \ attribute lowp vec2 textureCoord; \ -- cgit v0.12 From fbce782f1d566c318737bf7e5ab55d0a66fb2a2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 16 Apr 2009 10:37:08 +0200 Subject: Fix off-by-one bugs in the framebuffer blits. The bottom-right coordinates are exclusive, not inclusive. --- src/opengl/qglframebufferobject.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 45d4788..61d0f85 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -1132,14 +1132,14 @@ void QGLFramebufferObject::blitFramebuffer(QGLFramebufferObject *target, const Q const int th = target ? target->height() : height; const int sx0 = sourceRect.left(); - const int sx1 = sourceRect.right(); - const int sy0 = sh - sourceRect.bottom() - 1; - const int sy1 = sh - sourceRect.top() - 1; + const int sx1 = sourceRect.left() + sourceRect.width(); + const int sy0 = sh - (sourceRect.top() + sourceRect.height()); + const int sy1 = sh - sourceRect.top(); const int tx0 = targetRect.left(); - const int tx1 = targetRect.right(); - const int ty0 = th - targetRect.bottom() - 1; - const int ty1 = th - targetRect.top() - 1; + const int tx1 = targetRect.left() + targetRect.width(); + const int ty0 = th - (targetRect.top() + targetRect.height()); + const int ty1 = th - targetRect.top(); glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, source ? source->handle() : 0); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, target ? target->handle() : 0); -- cgit v0.12 From d4eb0a29e73eb1f6c7e2909e6ae0302605927e02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 24 Mar 2009 15:10:01 +0100 Subject: GL2: Avoid expensive updateDepthClip() every time setState() is called Only call updateDepthClip() if the clip has actually changed. --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 30 ++++++++++------------ .../gl2paintengineex/qpaintengineex_opengl2_p.h | 1 - 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 89ed1f7..e166b54 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1200,11 +1200,6 @@ void QGL2PaintEngineEx::updateClipRegion(const QRegion &clipRegion, Qt::ClipOper state()->hasClipping = op != Qt::NoClip || d->use_system_clip; } - if (state()->hasClipping && state()->clipRegion.rects().size() == 1) - state()->fastClip = state()->clipRegion.rects().at(0); - else - state()->fastClip = QRect(); - d->updateDepthClip(); } @@ -1221,14 +1216,10 @@ void QGL2PaintEngineExPrivate::updateDepthClip() if (!q->state()->hasClipping) return; - QRect fastClip; - if (q->state()->clipEnabled) { - fastClip = q->state()->fastClip; - } else if (use_system_clip && q->systemClip().rects().count() == 1) { - fastClip = q->systemClip().rects().at(0); - } + const QVector rects = q->state()->clipEnabled ? q->state()->clipRegion.rects() : q->systemClip().rects(); + if (rects.size() == 1) { + QRect fastClip = rects.at(0); - if (!fastClip.isEmpty()) { glEnable(GL_SCISSOR_TEST); const int left = fastClip.left(); @@ -1245,7 +1236,6 @@ void QGL2PaintEngineExPrivate::updateDepthClip() glClear(GL_DEPTH_BUFFER_BIT); glClearDepthf(0x1); - const QVector rects = q->state()->clipEnabled ? q->state()->clipRegion.rects() : q->systemClip().rects(); glEnable(GL_SCISSOR_TEST); for (int i = 0; i < rects.size(); ++i) { QRect rect = rects.at(i); @@ -1268,14 +1258,23 @@ void QGL2PaintEngineExPrivate::updateDepthClip() -void QGL2PaintEngineEx::setState(QPainterState *s) +void QGL2PaintEngineEx::setState(QPainterState *new_state) { // qDebug("QGL2PaintEngineEx::setState()"); Q_D(QGL2PaintEngineEx); + + QOpenGLPaintEngineState *s = static_cast(new_state); + + QOpenGLPaintEngineState *old_state = state(); + const bool needsDepthClipUpdate = !old_state + || s->clipEnabled != old_state->clipEnabled + || s->clipEnabled && s->clipRegion != old_state->clipRegion; + QPaintEngineEx::setState(s); - d->updateDepthClip(); + if (needsDepthClipUpdate) + d->updateDepthClip(); d->matrixDirty = true; d->compositionModeDirty = true; @@ -1303,7 +1302,6 @@ QOpenGLPaintEngineState::QOpenGLPaintEngineState(QOpenGLPaintEngineState &other) { clipRegion = other.clipRegion; hasClipping = other.hasClipping; - fastClip = other.fastClip; } QOpenGLPaintEngineState::QOpenGLPaintEngineState() diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index 9f84a25..10e5337 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -67,7 +67,6 @@ public: QRegion clipRegion; bool hasClipping; - QRect fastClip; }; -- cgit v0.12 From b1c0c0bf169d4ab83ce6e9b1b333e99610aa6f6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 26 Mar 2009 10:14:07 +0100 Subject: Ensure we don't access the GL share widget when it's being destroyed. Zero the pointer before destroying the widget, as QGLWidget's destructor may indirectly trigger access to the share widget. --- src/opengl/qwindowsurface_gl.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index b4a4565..bed08cf 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -187,9 +187,10 @@ public: } void cleanup() { - delete widget; - widget = 0; + QGLWidget *w = widget; cleanedUp = true; + widget = 0; + delete w; } static bool cleanedUp; -- cgit v0.12 From 1e1371e19ae62a5bf57dcad8d53ac70dcd2ad0cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 19 Mar 2009 10:07:26 +0100 Subject: Make FBO the default instead of pixel buffers in GL window surface. Fall back to using pbuffers only if the FBO fails. --- src/opengl/qwindowsurface_gl.cpp | 57 ++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 28 deletions(-) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index bed08cf..c9d23d1 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -493,6 +493,35 @@ void QGLWindowSurface::updateGeometry() return; } + if ((QGLExtensions::glExtensions & QGLExtensions::FramebufferObject) && (d_ptr->fbo || !d_ptr->tried_fbo)) { + d_ptr->tried_fbo = true; + hijackWindow(window()); + QGLContext *ctx = reinterpret_cast(window()->d_func()->extraData()->glContext); + ctx->d_ptr->internal_context = true; + ctx->makeCurrent(); + delete d_ptr->fbo; + + QGLFramebufferObjectFormat format; + format.setAttachment(QGLFramebufferObject::CombinedDepthStencil); + format.setInternalFormat(GL_RGBA); + format.setTextureTarget(target); + + if (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit) + format.setSamples(8); + + d_ptr->fbo = new QGLFramebufferObject(rect.size(), format); + d_ptr->fbo->bind(); + if (d_ptr->fbo->isValid()) { + qDebug() << "Created Window Surface FBO" << rect.size() + << "with samples" << d_ptr->fbo->format().samples(); + return; + } else { + qDebug() << "QGLWindowSurface: Failed to create valid FBO, falling back"; + delete d_ptr->fbo; + d_ptr->fbo = 0; + } + } + if (d_ptr->pb || !d_ptr->tried_pb) { d_ptr->tried_pb = true; @@ -536,34 +565,6 @@ void QGLWindowSurface::updateGeometry() } } - if ((QGLExtensions::glExtensions & QGLExtensions::FramebufferObject) && (d_ptr->fbo || !d_ptr->tried_fbo)) { - d_ptr->tried_fbo = true; - hijackWindow(window()); - QGLContext *ctx = reinterpret_cast(window()->d_func()->extraData()->glContext); - ctx->d_ptr->internal_context = true; - ctx->makeCurrent(); - delete d_ptr->fbo; - - QGLFramebufferObjectFormat format; - format.setAttachment(QGLFramebufferObject::CombinedDepthStencil); - format.setInternalFormat(GL_RGBA); - format.setTextureTarget(target); - - if (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit) - format.setSamples(8); - - d_ptr->fbo = new QGLFramebufferObject(rect.size(), format); - d_ptr->fbo->bind(); - if (d_ptr->fbo->isValid()) { - qDebug() << "Created Window Surface FBO" << rect.size() - << "with samples" << d_ptr->fbo->format().samples(); - return; - } else { - qDebug() << "QGLWindowSurface: Failed to create valid FBO, falling back"; - delete d_ptr->fbo; - d_ptr->fbo = 0; - } - } hijackWindow(window()); QGLContext *ctx = reinterpret_cast(window()->d_func()->extraData()->glContext); -- cgit v0.12 From 99a790fe26f8217783edd1ee05937100dc7536cc Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 15 Apr 2009 14:48:11 +0200 Subject: Add uniform setters for Qt data types to QGLShaderProgram Reviewed-by: Rhys Weatherley --- src/opengl/qglshaderprogram.cpp | 132 ++++++++++++++++++++++++++++++++++++++++ src/opengl/qglshaderprogram.h | 10 +++ 2 files changed, 142 insertions(+) diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp index 5738acd..c2be1be 100644 --- a/src/opengl/qglshaderprogram.cpp +++ b/src/opengl/qglshaderprogram.cpp @@ -1836,6 +1836,30 @@ void QGLShaderProgram::setUniformValue(const char *name, GLint value) } /*! + Sets the uniform variable at \a location in the current context to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, GLuint value) +{ + if (location != -1) + glUniform1i(location, value); +} + +/*! + \overload + + Sets the uniform variable called \a name in the current context + to \a value. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, GLuint value) +{ + setUniformValue(uniformLocation(name), value); +} + +/*! Sets the uniform variable at \a location in the current context to the 2D vector (\a x, \a y). @@ -2020,6 +2044,114 @@ void QGLShaderProgram::setUniformValue(const char *name, const QColor& color) } /*! + Sets the uniform variable at \a location in the current context to + the x() & y() coordinates of \a point. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QPoint& point) +{ + if (location != -1) { + GLfloat values[4] = {point.x(), point.y()}; + glUniform2fv(location, 1, values); + } +} + +/*! + \overload + + Sets the uniform variable at \a location in the current context to + the x() & y() coordinates of \a point. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QPoint& point) +{ + setUniformValue(uniformLocation(name), point); +} + +/*! + Sets the uniform variable at \a location in the current context to + the x() & y() coordinates of \a point. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QPointF& point) +{ + if (location != -1) { + GLfloat values[4] = {point.x(), point.y()}; + glUniform2fv(location, 1, values); + } +} + +/*! + \overload + + Sets the uniform variable at \a location in the current context to + the x() & y() coordinates of \a point. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QPointF& point) +{ + setUniformValue(uniformLocation(name), point); +} + +/*! + Sets the uniform variable at \a location in the current context to + the width() & height() of the given \a size. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QSize& size) +{ + if (location != -1) { + GLfloat values[4] = {size.width(), size.width()}; + glUniform2fv(location, 1, values); + } +} + +/*! + \overload + + Sets the uniform variable at \a location in the current context to + the width() & height() of the given \a size. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QSize& size) +{ + setUniformValue(uniformLocation(name), size); +} + +/*! + Sets the uniform variable at \a location in the current context to + the width() & height() of the given \a size. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(int location, const QSizeF& size) +{ + if (location != -1) { + GLfloat values[4] = {size.width(), size.height()}; + glUniform2fv(location, 1, values); + } +} + +/*! + \overload + + Sets the uniform variable at \a location in the current context to + the width() & height() of the given \a size. + + \sa setAttributeValue() +*/ +void QGLShaderProgram::setUniformValue(const char *name, const QSizeF& size) +{ + setUniformValue(uniformLocation(name), size); +} + +/*! Sets the uniform variable at \a location in the current context to a 2x2 matrix \a value. diff --git a/src/opengl/qglshaderprogram.h b/src/opengl/qglshaderprogram.h index ec6faaf..508fd96 100644 --- a/src/opengl/qglshaderprogram.h +++ b/src/opengl/qglshaderprogram.h @@ -196,6 +196,7 @@ public: void setUniformValue(int location, GLfloat value); void setUniformValue(int location, GLint value); + void setUniformValue(int location, GLuint value); void setUniformValue(int location, GLfloat x, GLfloat y); void setUniformValue(int location, GLfloat x, GLfloat y, GLfloat z); void setUniformValue(int location, GLfloat x, GLfloat y, GLfloat z, GLfloat w); @@ -203,6 +204,10 @@ public: void setUniformValue(int location, const QVector3D& value); void setUniformValue(int location, const QVector4D& value); void setUniformValue(int location, const QColor& color); + void setUniformValue(int location, const QPoint& point); + void setUniformValue(int location, const QPointF& point); + void setUniformValue(int location, const QSize& size); + void setUniformValue(int location, const QSizeF& size); void setUniformValue(int location, const QMatrix2x2& value); void setUniformValue(int location, const QMatrix2x3& value); void setUniformValue(int location, const QMatrix2x4& value); @@ -217,6 +222,7 @@ public: void setUniformValue(const char *name, GLfloat value); void setUniformValue(const char *name, GLint value); + void setUniformValue(const char *name, GLuint value); void setUniformValue(const char *name, GLfloat x, GLfloat y); void setUniformValue(const char *name, GLfloat x, GLfloat y, GLfloat z); void setUniformValue(const char *name, GLfloat x, GLfloat y, GLfloat z, GLfloat w); @@ -224,6 +230,10 @@ public: void setUniformValue(const char *name, const QVector3D& value); void setUniformValue(const char *name, const QVector4D& value); void setUniformValue(const char *name, const QColor& color); + void setUniformValue(const char *name, const QPoint& point); + void setUniformValue(const char *name, const QPointF& point); + void setUniformValue(const char *name, const QSize& size); + void setUniformValue(const char *name, const QSizeF& size); void setUniformValue(const char *name, const QMatrix2x2& value); void setUniformValue(const char *name, const QMatrix2x3& value); void setUniformValue(const char *name, const QMatrix2x4& value); -- cgit v0.12 From adf67f5ab53758f9661b65a940ec34b4d4db6390 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 15 Apr 2009 13:33:25 +0200 Subject: Re-write the shader manager & completely break everything ;-) --- src/opengl/gl2paintengineex/glgc_shader_source.h | 137 ------- .../gl2paintengineex/qglengineshadermanager.cpp | 367 +++++++++++++++++ .../gl2paintengineex/qglengineshadermanager_p.h | 385 ++++++++++++++++++ .../gl2paintengineex/qglpexshadermanager.cpp | 450 --------------------- .../gl2paintengineex/qglpexshadermanager_p.h | 156 ------- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 4 +- src/opengl/opengl.pro | 9 +- 7 files changed, 758 insertions(+), 750 deletions(-) create mode 100644 src/opengl/gl2paintengineex/qglengineshadermanager.cpp create mode 100644 src/opengl/gl2paintengineex/qglengineshadermanager_p.h delete mode 100644 src/opengl/gl2paintengineex/qglpexshadermanager.cpp delete mode 100644 src/opengl/gl2paintengineex/qglpexshadermanager_p.h diff --git a/src/opengl/gl2paintengineex/glgc_shader_source.h b/src/opengl/gl2paintengineex/glgc_shader_source.h index 47a1cbb..5184c78 100644 --- a/src/opengl/gl2paintengineex/glgc_shader_source.h +++ b/src/opengl/gl2paintengineex/glgc_shader_source.h @@ -49,143 +49,6 @@ QT_BEGIN_NAMESPACE QT_MODULE(OpenGL) -/* - VERTEX SHADERS - ============== - - Vertex shaders are specified as multiple (partial) shaders. On desktop, - this works fine. On ES, QGLShader & QGLShaderProgram will make partial - shaders work by concatenating the source in each QGLShader and compiling - it as a single shader. This is abstracted nicely by QGLShaderProgram and - the GL2 engine doesn't need to worry about it. - - Generally, there's two vertex shader objects. The position shaders are - the ones which set gl_Position. There's also two "main" vertex shaders, - one which just calls the position shader and another which also passes - through some texture coordinates from a vertex attribute array to a - varying. These texture coordinates are used for mask position in text - rendering and for the source coordinates in drawImage/drawPixmap. There's - also a "Simple" vertex shader for rendering a solid colour (used to render - into the stencil buffer where the actual colour value is discarded). - - The position shaders for brushes look scary. This is because many of the - calculations which logically belong in the fragment shader have been moved - into the vertex shader to improve performance. This is why the position - calculation is in a seperate shader. Not only does it calculate the - position, but it also calculates some data to be passed to the fragment - shader as a varying. It is optimal to move as much of the calculation as - possible into the vertex shader as this is executed less often. - - The varyings passed to the fragment shaders are interpolated (which is - cheap). Unfortunately, GL will apply perspective correction to the - interpolation calusing errors. To get around this, the vertex shader must - apply perspective correction itself and set the w-value of gl_Position to - zero. That way, GL will be tricked into thinking it doesn't need to apply a - perspective correction and use linear interpolation instead (which is what - we want). Of course, if the brush transform is affeine, no perspective - correction is needed and a simpler vertex shader can be used instead. - - So there are the following "main" vertex shaders: - qglslSimpleVertexShader - qglslMainVertexShader - qglslMainWithTexCoordsVertexShader - - And the the following position vertex shaders: - qglslPositionOnlyVertexShader - qglslPositionWithTextureBrushVertexShader - qglslPositionWithPatternBrushVertexShader - qglslPositionWithLinearGradientBrushVertexShader - qglslPositionWithRadialGradientBrushVertexShader - qglslPositionWithConicalGradientBrushVertexShader - qglslAffinePositionWithTextureBrushVertexShader - qglslAffinePositionWithPatternBrushVertexShader - qglslAffinePositionWithLinearGradientBrushVertexShader - qglslAffinePositionWithRadialGradientBrushVertexShader - qglslAffinePositionWithConicalGradientBrushVertexShader - - Leading to 23 possible vertex shaders - - - FRAGMENT SHADERS - ================ - - Fragment shaders are also specified as multiple (partial) shaders. The - different fragment shaders represent the different stages in Qt's fragment - pipeline. There are 1-3 stages in this pipeline: First stage is to get the - fragment's colour value. The next stage is to get the fragment's mask value - (coverage value for anti-aliasing) and the final stage is to blend the - incoming fragment with the background (for composition modes not supported - by GL). - - Of these, the first stage will always be present. If Qt doesn't need to - apply anti-aliasing (because it's off or handled by multisampling) then - the coverage value doesn't need to be applied. (Note: There are two types - of mask, one for regular anti-aliasing and one for sub-pixel anti- - aliasing.) If the composition mode is one which GL supports natively then - the blending stage doesn't need to be applied. - - As eash stage can have multiple implementations, they are abstracted as - GLSL function calls, with the following signatures: - - Brushes & image drawing are implementations of "mediump vec4 srcPixel()": - qglslImageFragmentShader - qglslNonPremultipliedImageFragmentShader - qglslSolidBrushFragmentShader - qglslTextureBrushFragmentShader - qglslPatternBrushFragmentShader - qglslLinearGradientBrushFragmentShader - qglslRadialGradientBrushFragmentShader - qglslConicalGradientBrushFragmentShader - - NOTE: It is assumed the colour returned by srcPixel() is pre-multiplied - - The two masks are have these signature and are called: - qglslMaskFragmentShader: "mediump float mask()" - qglslRgbMaskFragmentShader: "mediump vec3 rgbMask()" - - Composition modes are "mediump vec4 composite(mediump vec4 src, mediump vec4 dest)": - qglslColorBurnCompositionModeFragmentShader - qglslColorDodgeCompositionModeFragmentShader - qglslDarkenCompositionModeFragmentShader - qglslDifferenceCompositionModeFragmentShader - qglslExclusionCompositionModeFragmentShader - qglslHardLightCompositionModeFragmentShader - qglslLightenCompositionModeFragmentShader - qglslMultiplyCompositionModeFragmentShader - qglslOverlayCompositionModeFragmentShader - qglslScreenCompositionModeFragmentShader - qglslSoftLightCompositionModeFragmentShader - - - So there are differnt frament shader main functions, depending on the - number & type of pipelines the fragment needs to go through. - - The choice of which main() fragment shader string to use depends on: - - Use of global opacity - - Brush style (some brushes apply opacity themselves) - - Use & type of mask (TODO: Need to support high quality anti-aliasing & text) - - Use of gamma-correction - - Use of non-GL Composition mode - - - CUSTOM SHADER CODE (idea) - ================== - - The use of custom shader code is supported by the engine for drawImage and - drawPixmap calls. This is implemented via hooks in the fragment pipeline. - The custom shader is passed to the engine as a partial fragment shader - (QGLCustomizedShader). The shader will implement a pre-defined method name - which Qt's fragment pipeline will call. There are two different hooks which - can be implemented as custom shader code: - - mediump vec4 customShader(sampler2d src, vec2 srcCoords) - mediump vec4 customShaderWithDest(sampler2d dest, sampler2d src, vec2 srcCoords) - -*/ - -///////////////////////////////////////////////////////////////////// - - static const char* qglslImageVertexShader = "\ attribute highp vec4 inputVertex; \ attribute lowp vec2 textureCoord; \ diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp new file mode 100644 index 0000000..1086430 --- /dev/null +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -0,0 +1,367 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtOpenGL module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qglengineshadermanager_p.h" + +#if defined(QT_DEBUG) +#include +#endif + + +QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) + : ctx(context), + shaderProgNeedsChanging(true), + srcPixelType(Qt::NoBrush), + useGlobalOpacity(false), + maskType(NoMask), + useTextureCoords(false), + compositionMode(QPainter::CompositionMode_SourceOver), + simpleShaderProg(0), + currentShaderProg(0) +{ + memset(compiledShaders, 0, sizeof(compiledShaders)); +} + +QGLEngineShaderManager::~QGLEngineShaderManager() +{ + //### +} + + + + + +void QGLEngineShaderManager::optimiseForBrushTransform(const QTransform transform) +{ + Q_UNUSED(transform); // Currently ignored +} + +void QGLEngineShaderManager::setSrcPixelType(Qt::BrushStyle style) +{ + srcPixelType = style; + shaderProgNeedsChanging = true; //### +} + +void QGLEngineShaderManager::setSrcPixelType(PixelSrcType type) +{ + srcPixelType = type; + shaderProgNeedsChanging = true; //### +} + +void QGLEngineShaderManager::setTextureCoordsEnabled(bool enabled) +{ + useTextureCoords = enabled; + shaderProgNeedsChanging = true; //### +} + +void QGLEngineShaderManager::setUseGlobalOpacity(bool useOpacity) +{ + useGlobalOpacity = useOpacity; + shaderProgNeedsChanging = true; //### +} + +void QGLEngineShaderManager::setMaskType(MaskType type) +{ + maskType = type; + shaderProgNeedsChanging = true; //### +} + +void QGLEngineShaderManager::setCompositionMode(QPainter::CompositionMode mode) +{ + compositionMode = mode; + shaderProgNeedsChanging = true; //### +} + +bool QGLEngineShaderManager::shaderProgramDirty() +{ + return shaderProgNeedsChanging; +} + +QGLShaderProgram* QGLEngineShaderManager::currentProgram() +{ + return currentShaderProg; +} + +QGLShaderProgram* QGLEngineShaderManager::simpleProgram() +{ + return simpleShaderProg; +} + + + + +// Select & use the correct shader program using the current state +void QGLEngineShaderManager::useCorrectShaderProg() +{ + QGLEngineShaderProg requiredProgram; + + // Choose vertex shader main function + QGLEngineShaderManager::ShaderName mainVertexShaderName = InvalidShaderName; + if (useTextureCoords) + mainVertexShaderName = MainWithTexCoordsVertexShader; + else + mainVertexShaderName = MainVertexShader; + compileNamedShader(mainVertexShaderName, QGLShader::PartialVertexShader); + requiredProgram.mainVertexShader = compiledShaders[mainVertexShaderName]; + + // Choose vertex shader shader position function (which typically also sets + // varyings) and the source pixel (srcPixel) fragment shader function: + QGLEngineShaderManager::ShaderName positionVertexShaderName = InvalidShaderName; + QGLEngineShaderManager::ShaderName srcPixelFragShaderName = InvalidShaderName; + bool isAffine = transform.isAffine(); + if ( (srcPixelType >= Qt::Dense1Pattern) && (srcPixelType <= Qt::DiagCrossPattern) ) { + if (isAffine) + positionVertexShaderName = AffinePositionWithPatternBrushVertexShader; + else + positionVertexShaderName = PositionWithPatternBrushVertexShader; + + srcPixelFragShaderName = PatternBrushSrcFragmentShader; + } + else switch (srcPixelType) { + default: + case Qt::NoBrush: + qCritical("QGLEngineShaderManager::useCorrectShaderProg() - I'm scared, Qt::NoBrush style is set"); + break; + case QGLEngineShaderManager::ImageSrc: + srcPixelFragShaderName = ImageSrcFragmentShader; + positionVertexShaderName = PositionOnlyVertexShader; + break; + case QGLEngineShaderManager::NonPremultipliedImageSrc: + srcPixelFragShaderName = NonPremultipliedImageSrcFragmentShader; + positionVertexShaderName = PositionOnlyVertexShader; + break; + case Qt::SolidPattern: + srcPixelFragShaderName = SolidBrushSrcFragmentShader; + positionVertexShaderName = PositionOnlyVertexShader; + break; + case Qt::LinearGradientPattern: + srcPixelFragShaderName = LinearGradientBrushSrcFragmentShader; + positionVertexShaderName = isAffine ? AffinePositionWithLinearGradientBrushVertexShader + : PositionWithLinearGradientBrushVertexShader; + break; + case Qt::ConicalGradientPattern: + srcPixelFragShaderName = ConicalGradientBrushSrcFragmentShader; + positionVertexShaderName = isAffine ? AffinePositionWithConicalGradientBrushVertexShader + : PositionWithConicalGradientBrushVertexShader; + break; + case Qt::RadialGradientPattern: + srcPixelFragShaderName = RadialGradientBrushSrcFragmentShader; + positionVertexShaderName = isAffine ? AffinePositionWithRadialGradientBrushVertexShader + : PositionWithRadialGradientBrushVertexShader; + break; + case Qt::TexturePattern: + srcPixelFragShaderName = TextureBrushSrcFragmentShader; + positionVertexShaderName = isAffine ? AffinePositionWithTextureBrushVertexShader + : PositionWithTextureBrushVertexShader; + break; + }; + compileNamedShader(positionVertexShaderName, QGLShader::PartialVertexShader); + compileNamedShader(srcPixelFragShaderName, QGLShader::PartialFragmentShader); + requiredProgram.positionVertexShader = compiledShaders[positionVertexShaderName]; + requiredProgram.srcPixelFragShader = compiledShaders[srcPixelFragShaderName]; + + + const bool hasCompose = compositionMode > QPainter::CompositionMode_Plus; + const bool hasMask = maskType != QGLEngineShaderManager::NoMask; + + // Choose fragment shader main function: + QGLEngineShaderManager::ShaderName mainFragShaderName; + + if (hasCompose && hasMask && useGlobalOpacity) + mainFragShaderName = MainFragmentShader_CMO; + if (hasCompose && hasMask && !useGlobalOpacity) + mainFragShaderName = MainFragmentShader_CM; + if (!hasCompose && hasMask && useGlobalOpacity) + mainFragShaderName = MainFragmentShader_MO; + if (!hasCompose && hasMask && !useGlobalOpacity) + mainFragShaderName = MainFragmentShader_M; + if (hasCompose && !hasMask && useGlobalOpacity) + mainFragShaderName = MainFragmentShader_CO; + if (hasCompose && !hasMask && !useGlobalOpacity) + mainFragShaderName = MainFragmentShader_C; + if (!hasCompose && !hasMask && useGlobalOpacity) + mainFragShaderName = MainFragmentShader_O; + if (!hasCompose && !hasMask && !useGlobalOpacity) + mainFragShaderName = MainFragmentShader; + + compileNamedShader(mainFragShaderName, QGLShader::PartialFragmentShader); + requiredProgram.mainFragShader = compiledShaders[mainFragShaderName]; + + if (hasMask) { + QGLEngineShaderManager::ShaderName maskShaderName = QGLEngineShaderManager::InvalidShaderName; + if (maskType == PixelMask) + maskShaderName = MaskFragmentShader; + else if (maskType == SubPixelMask) + maskShaderName = RgbMaskFragmentShader; + else if (maskType == SubPixelWithGammaMask) + maskShaderName = RgbMaskWithGammaFragmentShader; + else + qCritical("QGLEngineShaderManager::useCorrectShaderProg() - Unknown mask type"); + + compileNamedShader(maskShaderName, QGLShader::PartialFragmentShader); + requiredProgram.maskFragShader = compiledShaders[maskShaderName]; + } + else + requiredProgram.maskFragShader = 0; + + if (hasCompose) { + QGLEngineShaderManager::ShaderName compositionShaderName = QGLEngineShaderManager::InvalidShaderName; + switch (compositionMode) { + case QPainter::CompositionMode_Multiply: + compositionShaderName = MultiplyCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_Screen: + compositionShaderName = ScreenCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_Overlay: + compositionShaderName = OverlayCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_Darken: + compositionShaderName = DarkenCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_Lighten: + compositionShaderName = LightenCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_ColorDodge: + compositionShaderName = ColorDodgeCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_ColorBurn: + compositionShaderName = ColorBurnCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_HardLight: + compositionShaderName = HardLightCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_SoftLight: + compositionShaderName = SoftLightCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_Difference: + compositionShaderName = DifferenceCompositionModeFragmentShader; + break; + case QPainter::CompositionMode_Exclusion: + compositionShaderName = ExclusionCompositionModeFragmentShader; + break; + default: + qWarning("QGLEngineShaderManager::useCorrectShaderProg() - Unsupported composition mode"); + } + compileNamedShader(compositionShaderName, QGLShader::PartialFragmentShader); + requiredProgram.compositionFragShader = compiledShaders[compositionShaderName]; + } + else + requiredProgram.compositionFragShader = 0; + + + // At this point, requiredProgram is fully populated so try to find the program in the cache + foreach (const QGLEngineShaderProg &prog, cachedPrograms) { + if ( (prog.mainVertexShader == requiredProgram.mainVertexShader) + && (prog.positionVertexShader == requiredProgram.positionVertexShader) + && (prog.mainFragShader == requiredProgram.mainFragShader) + && (prog.srcPixelFragShader == requiredProgram.srcPixelFragShader) + && (prog.compositionFragShader == requiredProgram.compositionFragShader) ) + { + currentShaderProg = requiredProgram.program; + currentShaderProg->enable(); + shaderProgNeedsChanging = false; + return; + } + } + +/* + QGLShader* mainVertexShader; + QGLShader* positionVertexShader; + QGLShader* mainFragShader; + QGLShader* srcPixelFragShader; + QGLShader* maskFragShader; // Can be null for no mask + QGLShader* compositionFragShader; // Can be null for GL-handled mode + QGLShaderProgram* program; +*/ + // Shader program not found in cache, create it now. + requiredProgram.program = new QGLShaderProgram(ctx, this); + requiredProgram.program->addShader(requiredProgram.mainVertexShader); + requiredProgram.program->addShader(requiredProgram.positionVertexShader); + requiredProgram.program->addShader(requiredProgram.mainFragShader); + requiredProgram.program->addShader(requiredProgram.srcPixelFragShader); + requiredProgram.program->addShader(requiredProgram.maskFragShader); + requiredProgram.program->addShader(requiredProgram.compositionFragShader); + requiredProgram.program->link(); + if (!requiredProgram.program->isValid()) { + QString error; + qWarning() << "Shader program failed to link," +#if defined(QT_DEBUG) + << '\n' + << " Shaders Used:" << '\n' + << " mainVertexShader = " << requiredProgram.mainVertexShader->objectName() << '\n' + << " positionVertexShader = " << requiredProgram.positionVertexShader->objectName() << '\n' + << " mainFragShader = " << requiredProgram.mainFragShader->objectName() << '\n' + << " srcPixelFragShader = " << requiredProgram.srcPixelFragShader->objectName() << '\n' + << " maskFragShader = " << requiredProgram.maskFragShader->objectName() << '\n' + << " compositionFragShader = "<< requiredProgram.compositionFragShader->objectName() << '\n' +#endif + << " Error Log:" << '\n' + << " " << requiredProgram.program->errors(); + qWarning() << error; + } + else { + cachedPrograms.append(requiredProgram); + currentShaderProg = requiredProgram.program; + currentShaderProg->enable(); + } + shaderProgNeedsChanging = false; +} + +void QGLEngineShaderManager::compileNamedShader(QGLEngineShaderManager::ShaderName name, QGLShader::ShaderType type) +{ + if (compiledShaders[name]) + return; + + QGLShader *newShader = new QGLShader(type, ctx, this); + newShader->setSourceCode(qglEngineShaderSourceCode[name]); + // newShader->compile(); ### does not exist? + +#if defined(QT_DEBUG) + // Name the shader for easier debugging + QMetaEnum m = staticMetaObject.enumerator(staticMetaObject.indexOfEnumerator("ShaderName")); + newShader->setObjectName(QLatin1String(m.valueToKey(name))); +#endif + + compiledShaders[name] = newShader; +} + + diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h new file mode 100644 index 0000000..fe30a70 --- /dev/null +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -0,0 +1,385 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtOpenGL module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +/* + VERTEX SHADERS + ============== + + Vertex shaders are specified as multiple (partial) shaders. On desktop, + this works fine. On ES, QGLShader & QGLShaderProgram will make partial + shaders work by concatenating the source in each QGLShader and compiling + it as a single shader. This is abstracted nicely by QGLShaderProgram and + the GL2 engine doesn't need to worry about it. + + Generally, there's two vertex shader objects. The position shaders are + the ones which set gl_Position. There's also two "main" vertex shaders, + one which just calls the position shader and another which also passes + through some texture coordinates from a vertex attribute array to a + varying. These texture coordinates are used for mask position in text + rendering and for the source coordinates in drawImage/drawPixmap. There's + also a "Simple" vertex shader for rendering a solid colour (used to render + into the stencil buffer where the actual colour value is discarded). + + The position shaders for brushes look scary. This is because many of the + calculations which logically belong in the fragment shader have been moved + into the vertex shader to improve performance. This is why the position + calculation is in a seperate shader. Not only does it calculate the + position, but it also calculates some data to be passed to the fragment + shader as a varying. It is optimal to move as much of the calculation as + possible into the vertex shader as this is executed less often. + + The varyings passed to the fragment shaders are interpolated (which is + cheap). Unfortunately, GL will apply perspective correction to the + interpolation calusing errors. To get around this, the vertex shader must + apply perspective correction itself and set the w-value of gl_Position to + zero. That way, GL will be tricked into thinking it doesn't need to apply a + perspective correction and use linear interpolation instead (which is what + we want). Of course, if the brush transform is affeine, no perspective + correction is needed and a simpler vertex shader can be used instead. + + So there are the following "main" vertex shaders: + qglslSimpleVertexShader + qglslMainVertexShader + qglslMainWithTexCoordsVertexShader + + And the the following position vertex shaders: + qglslPositionOnlyVertexShader + qglslPositionWithTextureBrushVertexShader + qglslPositionWithPatternBrushVertexShader + qglslPositionWithLinearGradientBrushVertexShader + qglslPositionWithRadialGradientBrushVertexShader + qglslPositionWithConicalGradientBrushVertexShader + qglslAffinePositionWithTextureBrushVertexShader + qglslAffinePositionWithPatternBrushVertexShader + qglslAffinePositionWithLinearGradientBrushVertexShader + qglslAffinePositionWithRadialGradientBrushVertexShader + qglslAffinePositionWithConicalGradientBrushVertexShader + + Leading to 23 possible vertex shaders + + + FRAGMENT SHADERS + ================ + + Fragment shaders are also specified as multiple (partial) shaders. The + different fragment shaders represent the different stages in Qt's fragment + pipeline. There are 1-3 stages in this pipeline: First stage is to get the + fragment's colour value. The next stage is to get the fragment's mask value + (coverage value for anti-aliasing) and the final stage is to blend the + incoming fragment with the background (for composition modes not supported + by GL). + + Of these, the first stage will always be present. If Qt doesn't need to + apply anti-aliasing (because it's off or handled by multisampling) then + the coverage value doesn't need to be applied. (Note: There are two types + of mask, one for regular anti-aliasing and one for sub-pixel anti- + aliasing.) If the composition mode is one which GL supports natively then + the blending stage doesn't need to be applied. + + As eash stage can have multiple implementations, they are abstracted as + GLSL function calls with the following signatures: + + Brushes & image drawing are implementations of "qcolorp vec4 srcPixel()": + qglslImageSrcFragShader + qglslNonPremultipliedImageSrcFragShader + qglslSolidBrushSrcFragShader + qglslTextureBrushSrcFragShader + qglslPatternBrushSrcFragShader + qglslLinearGradientBrushSrcFragShader + qglslRadialGradientBrushSrcFragShader + qglslConicalGradientBrushSrcFragShader + NOTE: It is assumed the colour returned by srcPixel() is pre-multiplied + + Masks are implementations of "qcolorp vec4 applyMask(qcolorp vec4 src)": + qglslMaskFragmentShader + qglslRgbMaskFragmentShader + qglslRgbMaskWithGammaFragmentShader + + Composition modes are "qcolorp vec4 compose(qcolorp vec4 src)": + qglslColorBurnCompositionModeFragmentShader + qglslColorDodgeCompositionModeFragmentShader + qglslDarkenCompositionModeFragmentShader + qglslDifferenceCompositionModeFragmentShader + qglslExclusionCompositionModeFragmentShader + qglslHardLightCompositionModeFragmentShader + qglslLightenCompositionModeFragmentShader + qglslMultiplyCompositionModeFragmentShader + qglslOverlayCompositionModeFragmentShader + qglslScreenCompositionModeFragmentShader + qglslSoftLightCompositionModeFragmentShader + + + Note: In the future, some GLSL compilers will support an extension allowing + a new 'color' precision specifier. To support this, qcolorp is used for + all color components so it can be defined to colorp or lowp depending upon + the implementation. + + So there are differnt frament shader main functions, depending on the + number & type of pipelines the fragment needs to go through. + + The choice of which main() fragment shader string to use depends on: + - Use of global opacity + - Brush style (some brushes apply opacity themselves) + - Use & type of mask (TODO: Need to support high quality anti-aliasing & text) + - Use of non-GL Composition mode + + Leading to the following fragment shader main functions: + gl_FragColor = compose(applyMask(srcPixel()*globalOpacity)); + gl_FragColor = compose(applyMask(srcPixel())); + gl_FragColor = applyMask(srcPixel()*globalOpacity); + gl_FragColor = applyMask(srcPixel()); + gl_FragColor = compose(srcPixel()*globalOpacity); + gl_FragColor = compose(srcPixel()); + gl_FragColor = srcPixel()*globalOpacity; + gl_FragColor = srcPixel(); + + Called: + qglslMainFragmentShader_CMO + qglslMainFragmentShader_CM + qglslMainFragmentShader_MO + qglslMainFragmentShader_M + qglslMainFragmentShader_CO + qglslMainFragmentShader_C + qglslMainFragmentShader_O + qglslMainFragmentShader + + Where: + M = Mask + C = Composition + O = Global Opacity + + + CUSTOM SHADER CODE (idea, depricated) + ================== + + The use of custom shader code is supported by the engine for drawImage and + drawPixmap calls. This is implemented via hooks in the fragment pipeline. + The custom shader is passed to the engine as a partial fragment shader + (QGLCustomizedShader). The shader will implement a pre-defined method name + which Qt's fragment pipeline will call. There are two different hooks which + can be implemented as custom shader code: + + mediump vec4 customShader(sampler2d src, vec2 srcCoords) + mediump vec4 customShaderWithDest(sampler2d dest, sampler2d src, vec2 srcCoords) + +*/ + +#ifndef QGLENGINE_SHADER_MANAGER_H +#define QGLENGINE_SHADER_MANAGER_H + +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(OpenGL) + + +struct QGLEngineShaderProg +{ + QGLShader* mainVertexShader; + QGLShader* positionVertexShader; + QGLShader* mainFragShader; + QGLShader* srcPixelFragShader; + QGLShader* maskFragShader; // Can be null for no mask + QGLShader* compositionFragShader; // Can be null for GL-handled mode + QGLShaderProgram* program; +}; + +/* +struct QGLEngineCachedShaderProg +{ + QGLEngineCachedShaderProg(QGLEngineShaderManager::ShaderName vertexMain, + QGLEngineShaderManager::ShaderName vertexPosition, + QGLEngineShaderManager::ShaderName fragMain, + QGLEngineShaderManager::ShaderName pixelSrc, + QGLEngineShaderManager::ShaderName mask, + QGLEngineShaderManager::ShaderName composition); + + int cacheKey; + QGLShaderProgram* program; +} +*/ + +class QGLEngineShaderManager : public QObject +{ + Q_OBJECT; +public: + QGLEngineShaderManager(QGLContext* context); + ~QGLEngineShaderManager(); + + enum MaskType {NoMask, PixelMask, SubPixelMask, SubPixelWithGammaMask}; + enum PixelSrcType { + ImageSrc = Qt::TexturePattern+1, + NonPremultipliedImageSrc = Qt::TexturePattern+2 + }; + + // There are optimisations we can do, depending on the transform: + // 1) May not have to apply perspective-correction + // 2) Can use lower precision for vertecies + void optimiseForBrushTransform(const QTransform transform); + void setSrcPixelType(Qt::BrushStyle); + void setSrcPixelType(PixelSrcType); // For non-brush sources, like pixmaps & images + void setTextureCoordsEnabled(bool); // For images & text glyphs + void setUseGlobalOpacity(bool); + void setMaskType(MaskType); + void setCompositionMode(QPainter::CompositionMode); + + bool shaderProgramDirty(); // returns true if the shader program needs to be changed + void useCorrectShaderProg(); + + QGLShaderProgram* currentProgram(); // Returns pointer to the shader the manager has chosen + QGLShaderProgram* simpleProgram(); // Used to draw into e.g. stencil buffers + + enum ShaderName { + SimpleVertexShader, + MainVertexShader, + MainWithTexCoordsVertexShader, + + PositionOnlyVertexShader, + PositionWithPatternBrushVertexShader, + PositionWithLinearGradientBrushVertexShader, + PositionWithConicalGradientBrushVertexShader, + PositionWithRadialGradientBrushVertexShader, + PositionWithTextureBrushVertexShader, + AffinePositionWithPatternBrushVertexShader, + AffinePositionWithLinearGradientBrushVertexShader, + AffinePositionWithConicalGradientBrushVertexShader, + AffinePositionWithRadialGradientBrushVertexShader, + AffinePositionWithTextureBrushVertexShader, + + MainFragmentShader_CMO, + MainFragmentShader_CM, + MainFragmentShader_MO, + MainFragmentShader_M, + MainFragmentShader_CO, + MainFragmentShader_C, + MainFragmentShader_O, + MainFragmentShader, + + ImageSrcFragmentShader, + NonPremultipliedImageSrcFragmentShader, + SolidBrushSrcFragmentShader, + TextureBrushSrcFragmentShader, + PatternBrushSrcFragmentShader, + LinearGradientBrushSrcFragmentShader, + RadialGradientBrushSrcFragmentShader, + ConicalGradientBrushSrcFragmentShader, + + MaskFragmentShader, + RgbMaskFragmentShader, + RgbMaskWithGammaFragmentShader, + + MultiplyCompositionModeFragmentShader, + ScreenCompositionModeFragmentShader, + OverlayCompositionModeFragmentShader, + DarkenCompositionModeFragmentShader, + LightenCompositionModeFragmentShader, + ColorDodgeCompositionModeFragmentShader, + ColorBurnCompositionModeFragmentShader, + HardLightCompositionModeFragmentShader, + SoftLightCompositionModeFragmentShader, + DifferenceCompositionModeFragmentShader, + ExclusionCompositionModeFragmentShader, + + TotalShaderCount, InvalidShaderName + }; + +/* + // These allow the ShaderName enum to be used as a cache key + const int mainVertexOffset = 0; + const int positionVertexOffset = (1<<2) - PositionOnlyVertexShader; + const int mainFragOffset = (1<<6) - MainFragmentShader_CMO; + const int srcPixelOffset = (1<<10) - ImageSrcFragmentShader; + const int maskOffset = (1<<14) - NoMaskShader; + const int compositionOffset = (1 << 16) - MultiplyCompositionModeFragmentShader; +*/ + +#if defined (QT_DEBUG) + Q_ENUMS(ShaderName); +#else +#error Release build not supported yet +#endif + + +private: + QGLContext* ctx; + bool shaderProgNeedsChanging; + + // Current state variables which influence the choice of shader: + QTransform transform; + int srcPixelType; + bool useGlobalOpacity; + MaskType maskType; + bool useTextureCoords; + QPainter::CompositionMode compositionMode; + + QGLShaderProgram* simpleShaderProg; + QGLShaderProgram* currentShaderProg; + + // TODO: Possibly convert to a LUT + QList cachedPrograms; + + QGLShader* compiledShaders[TotalShaderCount]; + + void compileNamedShader(QGLEngineShaderManager::ShaderName name, QGLShader::ShaderType type); +}; + + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif //QGLENGINE_SHADER_MANAGER_H diff --git a/src/opengl/gl2paintengineex/qglpexshadermanager.cpp b/src/opengl/gl2paintengineex/qglpexshadermanager.cpp deleted file mode 100644 index e460e08..0000000 --- a/src/opengl/gl2paintengineex/qglpexshadermanager.cpp +++ /dev/null @@ -1,450 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtOpenGL module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qglpexshadermanager_p.h" - -#include "glgc_shader_source.h" - -QGLPEXShaderManager::QGLPEXShaderManager(const QGLContext* context) -{ - ctx = const_cast(context); - - defaultVertexShader= new QGLShader(QGLShader::VertexShader, context); - defaultVertexShader->addSource(QLatin1String(qglslDefaultVertexShader)); - if (!defaultVertexShader->compile()) - qWarning() << "Default vertex shader failed to compile: " << defaultVertexShader->log(); - - noBrushShader = new QGLShader(QGLShader::FragmentShader, context); - noBrushShader->addSource(QLatin1String(qglslFragmentShaderMain)); - noBrushShader->addSource(QLatin1String(qglslNoBrushFragmentShader)); - if (!noBrushShader->compile()) - qWarning() << "No brush shader failed to compile:" << noBrushShader->log(); - - - // Create a program for noBrush: - QGLShaderProgram* noBrushProg = new QGLShaderProgram(ctx); - noBrushProg->addShader(defaultVertexShader); - noBrushProg->addShader(noBrushShader); - if (!noBrushProg->link()) - qWarning() << "NoBrush shader program failed to link:" << noBrushProg->log(); - - // Add noBrush Program to cache: - QGLCachedShaderProg cachedProg; - cachedProg.vertexShader = defaultVertexShader; - cachedProg.brushShader = noBrushShader; - cachedProg.compositionShader = 0; - cachedProg.shader = noBrushProg; - cachedPrograms.append(cachedProg); - - - // Set state - useGlobalOpacity = true; - currentBrushStyle = Qt::NoBrush; - currentTransformType = FullTransform; - shaderProgNeedsChanging = false; - activeProgram = noBrushProg; - - solidBrushShader = 0; - - conicalBrushVertexShader = 0; - conicalBrushFragmentShader = 0; - - radialBrushVertexShader = 0; - radialBrushFragmentShader = 0; - - linearBrushVertexShader = 0; - linearBrushFragmentShader = 0; - - patternBrushVertexShader = 0; - patternBrushFragmentShader = 0; - - textureBrushFragmentShader = 0; - textureBrushVertexShader = 0; - - simpleFragmentShader = 0; - simpleShaderProgram = 0; - - imageVertexShader = 0; - imageFragmentShader = 0; - imageShaderProgram = 0; - - textVertexShader = 0; - textFragmentShader = 0; - textShaderProgram = 0; -} - -QGLPEXShaderManager::~QGLPEXShaderManager() -{ - delete defaultVertexShader; - delete imageVertexShader; - delete imageFragmentShader; - delete imageShaderProgram; - delete textVertexShader; - delete textFragmentShader; - delete textShaderProgram; - delete noBrushShader; - delete solidBrushShader; - - delete conicalBrushVertexShader; - delete conicalBrushFragmentShader; - - delete radialBrushVertexShader; - delete radialBrushFragmentShader; - - delete linearBrushFragmentShader; - delete linearBrushVertexShader; - - delete patternBrushFragmentShader; - delete patternBrushVertexShader; - - delete textureBrushFragmentShader; - delete textureBrushVertexShader; - - delete simpleFragmentShader; - delete simpleShaderProgram; -} - -void QGLPEXShaderManager::setUseGlobalOpacity(bool value) -{ - if (value != useGlobalOpacity) - shaderProgNeedsChanging = true; - - useGlobalOpacity = value; -} - -void QGLPEXShaderManager::setBrushStyle(Qt::BrushStyle style) -{ - if (currentBrushStyle != style) - shaderProgNeedsChanging = true; - - currentBrushStyle = style; -} - -void QGLPEXShaderManager::setAffineOnlyBrushTransform(bool value) -{ - Q_UNUSED(value); - // TODO -} - -bool QGLPEXShaderManager::useCorrectShaderProg() -{ - if (!shaderProgNeedsChanging) { - activeProgram->use(); - return false; - } - - const char* fragmentShaderMainSrc = qglslFragmentShaderMain; - QGLShader* vertexShader = defaultVertexShader; - QGLShader* fragmentShader = noBrushShader; - - // Make sure we compile up the correct brush shader - switch (currentBrushStyle) { - case Qt::NoBrush: - break; - case Qt::SolidPattern: - if (!solidBrushShader) { - qDebug("Compiling qglslSolidBrushFragmentShader"); - solidBrushShader = new QGLShader(QGLShader::FragmentShader, ctx); - solidBrushShader->addSource(QLatin1String(qglslNoOpacityFragmentShaderMain)); - solidBrushShader->addSource(QLatin1String(qglslSolidBrushFragmentShader)); - if (!solidBrushShader->compile()) - qWarning() << "qglslSolidBrush failed to compile:" << solidBrushShader->log(); - } - fragmentShader = solidBrushShader; - break; - case Qt::TexturePattern: - if (!textureBrushVertexShader) { - qDebug("Compiling qglslTextureBrushVertexShader"); - textureBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx); - textureBrushVertexShader->addSource(QLatin1String(qglslTextureBrushVertexShader)); - if (!textureBrushVertexShader->compile()) { - qWarning() << "qglslTextureBrushVertexShader failed to compile: " - << textureBrushVertexShader->log(); - } - } - vertexShader = textureBrushVertexShader; - - if (!textureBrushFragmentShader) { - qDebug("Compiling qglslTextureBrushFragmentShader"); - textureBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx); - textureBrushFragmentShader->addSource(QLatin1String(fragmentShaderMainSrc)); - textureBrushFragmentShader->addSource(QLatin1String(qglslTextureBrushFragmentShader)); - if (!textureBrushFragmentShader->compile()) { - qWarning() << "qglslTextureBrushFragmentShader failed to compile:" - << textureBrushFragmentShader->log(); - } - } - fragmentShader = textureBrushFragmentShader; - break; - case Qt::LinearGradientPattern: - if (!linearBrushVertexShader) { - qDebug("Compiling qglslLinearGradientBrushVertexShader"); - linearBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx); - linearBrushVertexShader->addSource(QLatin1String(qglslLinearGradientBrushVertexShader)); - if (!linearBrushVertexShader->compile()) { - qWarning() << "qglslLinearGradientBrushVertexShader failed to compile: " - << linearBrushVertexShader->log(); - } - } - vertexShader = linearBrushVertexShader; - - if (!linearBrushFragmentShader) { - qDebug("Compiling qglslLinearGradientBrushFragmentShader"); - linearBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx); - linearBrushFragmentShader->addSource(QLatin1String(fragmentShaderMainSrc)); - linearBrushFragmentShader->addSource(QLatin1String(qglslLinearGradientBrushFragmentShader)); - if (!linearBrushFragmentShader->compile()) { - qWarning() << "qglslLinearGradientBrushFragmentShader failed to compile:" - << linearBrushFragmentShader->log(); - } - } - fragmentShader = linearBrushFragmentShader; - break; - case Qt::RadialGradientPattern: - if (!radialBrushVertexShader) { - qDebug("Compiling qglslRadialGradientBrushVertexShader"); - radialBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx); - radialBrushVertexShader->addSource(QLatin1String(qglslRadialGradientBrushVertexShader)); - if (!radialBrushVertexShader->compile()) { - qWarning() << "qglslRadialGradientBrushVertexShader failed to compile: " - << radialBrushVertexShader->log(); - } - } - vertexShader = radialBrushVertexShader; - - if (!radialBrushFragmentShader) { - qDebug("Compiling qglslRadialGradientBrushFragmentShader"); - radialBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx); - radialBrushFragmentShader->addSource(QLatin1String(fragmentShaderMainSrc)); - radialBrushFragmentShader->addSource(QLatin1String(qglslRadialGradientBrushFragmentShader)); - if (!radialBrushFragmentShader->compile()) { - qWarning() << "qglslRadialGradientBrushFragmentShader failed to compile:" - << radialBrushFragmentShader->log(); - } - } - fragmentShader = radialBrushFragmentShader; - break; - case Qt::ConicalGradientPattern: - // FIXME: We currently use the same vertex shader as radial brush - if (!conicalBrushVertexShader) { - qDebug("Compiling qglslConicalGradientBrushVertexShader"); - conicalBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx); - conicalBrushVertexShader->addSource(QLatin1String(qglslConicalGradientBrushVertexShader)); - if (!conicalBrushVertexShader->compile()) { - qWarning() << "qglslConicalGradientBrushVertexShader failed to compile: " - << conicalBrushVertexShader->log(); - } - } - vertexShader = conicalBrushVertexShader; - - if (!conicalBrushFragmentShader) { - qDebug("Compiling qglslConicalGradientBrushFragmentShader"); - conicalBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx); - conicalBrushFragmentShader->addSource(QLatin1String(fragmentShaderMainSrc)); - conicalBrushFragmentShader->addSource(QLatin1String(qglslConicalGradientBrushFragmentShader)); - if (!conicalBrushFragmentShader->compile()) { - qWarning() << "qglslConicalGradientBrushFragmentShader failed to compile:" - << conicalBrushFragmentShader->log(); - } - } - fragmentShader = conicalBrushFragmentShader; - break; - case Qt::Dense1Pattern: - case Qt::Dense2Pattern: - case Qt::Dense3Pattern: - case Qt::Dense4Pattern: - case Qt::Dense5Pattern: - case Qt::Dense6Pattern: - case Qt::Dense7Pattern: - case Qt::HorPattern: - case Qt::VerPattern: - case Qt::CrossPattern: - case Qt::BDiagPattern: - case Qt::FDiagPattern: - case Qt::DiagCrossPattern: - if (!patternBrushVertexShader) { - qDebug("Compiling qglslPatternBrushVertexShader"); - patternBrushVertexShader = new QGLShader(QGLShader::VertexShader, ctx); - patternBrushVertexShader->addSource(QLatin1String(qglslPatternBrushVertexShader)); - if (!patternBrushVertexShader->compile()) { - qWarning() << "qglslPatternBrushVertexShader failed to compile: " - << patternBrushVertexShader->log(); - } - } - vertexShader = patternBrushVertexShader; - - if (!patternBrushFragmentShader) { - qDebug("Compiling qglslPatternBrushFragmentShader"); - patternBrushFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx); - patternBrushFragmentShader->addSource(QLatin1String(qglslNoOpacityFragmentShaderMain)); - patternBrushFragmentShader->addSource(QLatin1String(qglslPatternBrushFragmentShader)); - if (!patternBrushFragmentShader->compile()) { - qWarning() << "qglslPatternBrushFragmentShader failed to compile:" - << patternBrushFragmentShader->log(); - } - } - fragmentShader = patternBrushFragmentShader; - break; - default: - qWarning("Unimplemented brush style (%d)", currentBrushStyle); - } - - // Now newBrushShader is set correctly, check to see if we already have the program - // already linked and ready to go in the cache: - bool foundProgram = false; - foreach (QGLCachedShaderProg cachedProg, cachedPrograms) { - if ((cachedProg.vertexShader == vertexShader) && - (cachedProg.brushShader == fragmentShader) && - (cachedProg.compositionShader == 0) ) { - - activeProgram = cachedProg.shader; - foundProgram = true; - break; - } - } - - if (!foundProgram) { - qDebug() << "Linking shader program for " << currentBrushStyle; - // Required program not found - create it. - QGLShaderProgram* newProg = new QGLShaderProgram(ctx); - - newProg->addShader(vertexShader); - newProg->addShader(fragmentShader); - - if (!newProg->link()) - qWarning() << "Shader program for " << currentBrushStyle << "failed to link:" << newProg->log(); - - QGLCachedShaderProg cachedProg; - cachedProg.vertexShader = vertexShader; - cachedProg.brushShader = fragmentShader; - cachedProg.compositionShader = 0; - cachedProg.shader = newProg; - - cachedPrograms.append(cachedProg); - activeProgram = newProg; - } - - activeProgram->use(); - shaderProgNeedsChanging = false; - return true; -} - -QGLShaderProgram* QGLPEXShaderManager::brushShader() -{ - return activeProgram; -} - -// The only uniform the simple shader has is the PMV matrix -QGLShaderProgram* QGLPEXShaderManager::simpleShader() -{ - if (!simpleShaderProgram) { - simpleShaderProgram = new QGLShaderProgram(ctx); - - if (!simpleFragmentShader) { - simpleFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx); - simpleFragmentShader->addSource(QLatin1String(qglslSimpleFragmentShader)); - if (!simpleFragmentShader->compile()) - qWarning() << "qglslSimpleFragmentShader failed to compile:" << simpleFragmentShader->log(); - } - - simpleShaderProgram->addShader(defaultVertexShader); - simpleShaderProgram->addShader(simpleFragmentShader); - if (!simpleShaderProgram->link()) - qWarning() << "Simple shader program failed to link:" << simpleShaderProgram->log(); - } - - return simpleShaderProgram; -} - -QGLShaderProgram* QGLPEXShaderManager::imageShader() -{ - if (!imageShaderProgram) { - if (!imageVertexShader) { - imageVertexShader = new QGLShader(QGLShader::VertexShader, ctx); - imageVertexShader->addSource(QLatin1String(qglslImageVertexShader)); - if (!imageVertexShader->compile()) - qWarning() << "Image/Pixmap vertex shader failed to compile:" << imageVertexShader->log(); - } - - if (!imageFragmentShader) { - imageFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx); - imageFragmentShader->addSource(QLatin1String(qglslImageFragmentShader)); - if (!imageFragmentShader->compile()) - qWarning() << "Image/Pixmap fragment shader failed to compile:" << imageFragmentShader->log(); - } - - imageShaderProgram = new QGLShaderProgram(ctx); - imageShaderProgram->addShader(imageVertexShader); - imageShaderProgram->addShader(imageFragmentShader); - if (!imageShaderProgram->link()) - qWarning() << "Image/Pixmap shader program failed to link:" << imageShaderProgram->log(); - } - - return imageShaderProgram; -} - -QGLShaderProgram* QGLPEXShaderManager::textShader() -{ - if (!textShaderProgram) { - if (!textVertexShader) { - textVertexShader = new QGLShader(QGLShader::VertexShader, ctx); - textVertexShader->addSource(QLatin1String(qglslImageVertexShader)); - if (!textVertexShader->compile()) - qWarning() << "Text vertex shader failed to compile:" << textVertexShader->log(); - } - - if (!textFragmentShader) { - textFragmentShader = new QGLShader(QGLShader::FragmentShader, ctx); - textFragmentShader->addSource(QLatin1String(qglslTextFragmentShader)); - if (!textFragmentShader->compile()) - qWarning() << "Text fragment shader failed to compile:" << textFragmentShader->log(); - } - - textShaderProgram = new QGLShaderProgram(ctx); - textShaderProgram->addShader(textVertexShader); - textShaderProgram->addShader(textFragmentShader); - if (!textShaderProgram->link()) - qWarning() << "Text shader program failed to link:" << textShaderProgram->log(); - } - - return textShaderProgram; -} - diff --git a/src/opengl/gl2paintengineex/qglpexshadermanager_p.h b/src/opengl/gl2paintengineex/qglpexshadermanager_p.h deleted file mode 100644 index c8f47b2..0000000 --- a/src/opengl/gl2paintengineex/qglpexshadermanager_p.h +++ /dev/null @@ -1,156 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtOpenGL module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qglshader_p.h" - - -// Worstcase combo: Brush->Mask->Composition - -/* - Vertex shader source is specified with a single string. This string - contains the main function and sets the gl_Position. The choice of - which vertex shader to use depends on: - - Brush style - - Brush transform->isAffine() - - Fragment shaders are specified as multiple strings, one for the main - function, one for the brush calculation and optionally one for the - extended composition mode. Brushes are implementations of - "mediump vec4 brush()" - Composition modes are implemented as a - "mediump vec4 compose(mediump vec4 color)" - NOTE: Precision may change in future. - - The choice of which main() fragment shader string to use depends on: - - Global opacity - - Brush style (some brushes apply opacity themselves) - - Use of mask (TODO: Need to support high quality anti-aliasing & text) - - Composition mode - - The choice of which brush() fragment shader to use depends on: - - Brush style - -*/ - - -struct QGLCachedShaderProg -{ - QGLShader* vertexShader; - QGLShader* brushShader; - QGLShader* compositionShader; - QGLShaderProgram* shader; -}; - -class QGLPEXShaderManager -{ -public: - QGLPEXShaderManager(const QGLContext* context); - ~QGLPEXShaderManager(); - - enum TransformType {IdentityTransform, ScaleTransform, TranslateTransform, FullTransform}; - - void optimiseForBrushTransform(const QTransform& transform); - void setBrushStyle(Qt::BrushStyle style); - void setUseGlobalOpacity(bool value); - void setAffineOnlyBrushTransform(bool value); // I.e. Do we need to apply perspective-correction? - // Not doing so saves some vertex shader calculations. - - bool useCorrectShaderProg(); // returns true if the shader program has changed - - QGLShaderProgram* brushShader(); - QGLShaderProgram* simpleShader(); // Used to draw into e.g. stencil buffers - QGLShaderProgram* imageShader(); - QGLShaderProgram* textShader(); - -private: - QGLShader* defaultVertexShader; - - QGLShader* imageVertexShader; - QGLShader* imageFragmentShader; - QGLShaderProgram* imageShaderProgram; - - QGLShader* textVertexShader; - QGLShader* textFragmentShader; - QGLShaderProgram* textShaderProgram; - - QGLShader* noBrushShader; - QGLShader* solidBrushShader; - - QGLShader* conicalBrushVertexShader; - QGLShader* conicalBrushFragmentShader; - - QGLShader* radialBrushVertexShader; - QGLShader* radialBrushFragmentShader; - - QGLShader* linearBrushVertexShader; - QGLShader* linearBrushFragmentShader; - - QGLShader* patternBrushVertexShader; - QGLShader* patternBrushFragmentShader; - - QGLShader* textureBrushFragmentShader; - QGLShader* textureBrushVertexShader; - - QGLShader* simpleFragmentShader; - QGLShaderProgram* simpleShaderProgram; - - QGLShaderProgram* activeProgram; - - Qt::BrushStyle currentBrushStyle; - bool useGlobalOpacity; - TransformType currentTransformType; - bool shaderProgNeedsChanging; - - QList cachedPrograms; - - QGLContext* ctx; -}; diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 89ed1f7..53ae4fb 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -77,7 +77,7 @@ #include #include "qglgradientcache_p.h" -#include "qglpexshadermanager_p.h" +#include "qglengineshadermanager_p.h" #include "qgl2pexvertexarray_p.h" @@ -170,7 +170,7 @@ public: GLfloat pmvMatrix[4][4]; - QGLPEXShaderManager* shaderManager; + QGLEngineShaderManager* shaderManager; // Clipping & state stuff stolen from QOpenGLPaintEngine: void updateDepthClip(); diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro index 3b8bfa1..1527f2d 100644 --- a/src/opengl/opengl.pro +++ b/src/opengl/opengl.pro @@ -43,16 +43,15 @@ SOURCES += qgl.cpp \ #contains(QT_CONFIG, opengles2) { SOURCES += gl2paintengineex/qglgradientcache.cpp \ - gl2paintengineex/qglpexshadermanager.cpp \ - gl2paintengineex/qglshader.cpp \ + gl2paintengineex/qglengineshadermanager.cpp \ gl2paintengineex/qgl2pexvertexarray.cpp \ gl2paintengineex/qpaintengineex_opengl2.cpp HEADERS += gl2paintengineex/qglgradientcache_p.h \ - gl2paintengineex/qglpexshadermanager_p.h \ - gl2paintengineex/qglshader_p.h \ + gl2paintengineex/qglengineshadermanager_p.h \ gl2paintengineex/qgl2pexvertexarray_p.h \ - gl2paintengineex/qpaintengineex_opengl2_p.h + gl2paintengineex/qpaintengineex_opengl2_p.h \ + gl2paintengineex/glgc_shader_source.h #} -- cgit v0.12 From 3cdaa8ed05a6af3dabcbc82388fc75c0e2ae8f71 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 15 Apr 2009 14:33:39 +0200 Subject: Adapt GL2 Paint Engine to new math3d, shader & shader manager APIs --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 86 +++++++++++----------- 1 file changed, 43 insertions(+), 43 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 53ae4fb..f1918c8 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -219,21 +219,21 @@ void QGL2PaintEngineExPrivate::setBrush(const QBrush* brush) currentBrush = brush; brushTextureDirty = true; brushUniformsDirty = true; - shaderManager->setBrushStyle(currentBrush->style()); - shaderManager->setAffineOnlyBrushTransform(currentBrush->transform().isAffine()); + shaderManager->setSrcPixelType(currentBrush->style()); + shaderManager->optimiseForBrushTransform(currentBrush->transform()); } // Unless this gets used elsewhere, it's probably best to merge it into fillStencilWithVertexArray void QGL2PaintEngineExPrivate::useSimpleShader() { - shaderManager->simpleShader()->use(); + shaderManager->simpleProgram()->enable(); if (matrixDirty) updateMatrix(); if (simpleShaderMatrixUniformDirty) { - shaderManager->simpleShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; + shaderManager->simpleProgram()->setUniformValue("pmvMatrix", pmvMatrix); simpleShaderMatrixUniformDirty = false; } } @@ -300,7 +300,7 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() if (style == Qt::SolidPattern) { QColor col = premultiplyColor(currentBrush->color(), opacity); - shaderManager->brushShader()->uniforms()[QLatin1String("fragmentColor")] = col; + shaderManager->currentProgram()->setUniformValue("fragmentColor", col); setOpacity = false; } else { @@ -312,11 +312,11 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() QColor col = premultiplyColor(currentBrush->color(), opacity); - shaderManager->brushShader()->uniforms()[QLatin1String("patternColor")] = col; + shaderManager->currentProgram()->setUniformValue("patternColor", col); setOpacity = false; //So code below doesn't try to set the opacity uniform - QGLVec2 halfViewportSize = { width*0.5, height*0.5 }; - shaderManager->brushShader()->uniforms()[QLatin1String("halfViewportSize")] = halfViewportSize; + QVector2D halfViewportSize(width*0.5, height*0.5); + shaderManager->currentProgram()->setUniformValue("halfViewportSize", halfViewportSize); } else if (style == Qt::LinearGradientPattern) { const QLinearGradient *g = static_cast(currentBrush->gradient()); @@ -327,17 +327,16 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() QPointF l = realFinal - realStart; - // ### - QGLVec3 linearData = { + QVector3D linearData( l.x(), l.y(), 1.0f / (l.x() * l.x() + l.y() * l.y()) - }; + ); - shaderManager->brushShader()->uniforms()[QLatin1String("linearData")] = linearData; + shaderManager->currentProgram()->setUniformValue("linearData", linearData); - QGLVec2 halfViewportSize = { width*0.5, height*0.5 }; - shaderManager->brushShader()->uniforms()[QLatin1String("halfViewportSize")] = halfViewportSize; + QVector2D halfViewportSize(width*0.5, height*0.5); + shaderManager->currentProgram()->setUniformValue("halfViewportSize", halfViewportSize); } else if (style == Qt::ConicalGradientPattern) { const QConicalGradient *g = static_cast(currentBrush->gradient()); @@ -345,10 +344,10 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() GLfloat angle = -(g->angle() * 2 * Q_PI) / 360.0; - shaderManager->brushShader()->uniforms()[QLatin1String("angle")] = angle; + shaderManager->currentProgram()->setUniformValue("angle", angle); - QGLVec2 halfViewportSize = { width*0.5, height*0.5 }; - shaderManager->brushShader()->uniforms()[QLatin1String("halfViewportSize")] = halfViewportSize; + QVector2D halfViewportSize(width*0.5, height*0.5); + shaderManager->currentProgram()->setUniformValue("halfViewportSize", halfViewportSize); } else if (style == Qt::RadialGradientPattern) { const QRadialGradient *g = static_cast(currentBrush->gradient()); @@ -358,16 +357,15 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() translationPoint = realFocal; QPointF fmp = realCenter - realFocal; - shaderManager->brushShader()->uniforms()[QLatin1String("fmp")] = fmp; + shaderManager->currentProgram()->setUniformValue("fmp", fmp); GLfloat fmp2_m_radius2 = -fmp.x() * fmp.x() - fmp.y() * fmp.y() + realRadius*realRadius; - shaderManager->brushShader()->uniforms()[QLatin1String("fmp2_m_radius2")] = fmp2_m_radius2; + shaderManager->currentProgram()->setUniformValue("fmp2_m_radius2", fmp2_m_radius2); + shaderManager->currentProgram()->setUniformValue("inverse_2_fmp2_m_radius2", + GLfloat(1.0 / (2.0*fmp2_m_radius2))); - shaderManager->brushShader()->uniforms()[QLatin1String("inverse_2_fmp2_m_radius2")] = - GLfloat(1.0 / (2.0*fmp2_m_radius2)); - - QGLVec2 halfViewportSize = { width*0.5, height*0.5 }; - shaderManager->brushShader()->uniforms()[QLatin1String("halfViewportSize")] = halfViewportSize; + QVector2D halfViewportSize(width*0.5, height*0.5); + shaderManager->currentProgram()->setUniformValue("halfViewportSize", halfViewportSize); } else if (style == Qt::TexturePattern) { translationPoint = q->state()->brushOrigin; @@ -375,10 +373,10 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() const QPixmap& texPixmap = currentBrush->texture(); QSizeF invertedTextureSize( 1.0 / texPixmap.width(), 1.0 / texPixmap.height() ); - shaderManager->brushShader()->uniforms()[QLatin1String("invertedTextureSize")] = invertedTextureSize; + shaderManager->currentProgram()->setUniformValue("invertedTextureSize", invertedTextureSize); - QGLVec2 halfViewportSize = { width*0.5, height*0.5 }; - shaderManager->brushShader()->uniforms()[QLatin1String("halfViewportSize")] = halfViewportSize; + QVector2D halfViewportSize(width*0.5, height*0.5); + shaderManager->currentProgram()->setUniformValue("halfViewportSize", halfViewportSize); } else qWarning("QGL2PaintEngineEx: Unimplemented fill style"); @@ -387,11 +385,11 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() QTransform gl_to_qt(1, 0, 0, -1, 0, height); QTransform inv_matrix = gl_to_qt * (brushQTransform * q->state()->matrix).inverted() * translate; - shaderManager->brushShader()->uniforms()[QLatin1String("brushTransform")] = inv_matrix; - shaderManager->brushShader()->uniforms()[QLatin1String("brushTexture")] = QT_BRUSH_TEXTURE_UNIT; + shaderManager->currentProgram()->setUniformValue("brushTransform", inv_matrix); + shaderManager->currentProgram()->setUniformValue("brushTexture", QT_BRUSH_TEXTURE_UNIT); if (setOpacity) - shaderManager->brushShader()->uniforms()[QLatin1String("opacity")] = opacity; + shaderManager->currentProgram()->setUniformValue("opacity", opacity); } brushUniformsDirty = false; } @@ -524,12 +522,12 @@ void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& s updateMatrix(); if (imageShaderMatrixUniformDirty) { - shaderManager->imageShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; +// shaderManager->imageShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; imageShaderMatrixUniformDirty = false; } - if (q->state()->opacity < 0.99f) - shaderManager->imageShader()->uniforms()[QLatin1String("opacity")] = (GLfloat)q->state()->opacity; +// if (q->state()->opacity < 0.99f) +// shaderManager->imageShader()->uniforms()[QLatin1String("opacity")] = (GLfloat)q->state()->opacity; GLfloat dx = 1.0 / textureSize.width(); GLfloat dy = 1.0 / textureSize.height(); @@ -562,15 +560,15 @@ void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray.data()); glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray.data()); - shaderManager->textShader()->use(); - shaderManager->textShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; +// shaderManager->textShader()->use(); +// shaderManager->textShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; } if (newMode == ImageDrawingMode) { // We have a shader specifically for drawPixmap/drawImage... - shaderManager->imageShader()->use(); - shaderManager->imageShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; - shaderManager->imageShader()->uniforms()[QLatin1String("opacity")] = (GLfloat)1.0; +// shaderManager->imageShader()->use(); +// shaderManager->imageShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; +// shaderManager->imageShader()->uniforms()[QLatin1String("opacity")] = (GLfloat)1.0; glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); @@ -727,7 +725,9 @@ void QGL2PaintEngineExPrivate::prepareForDraw() if (compositionModeDirty) updateCompositionMode(); - if (shaderManager->useCorrectShaderProg()) { + if (shaderManager->shaderProgramDirty()) { + shaderManager->useCorrectShaderProg(); + // The shader program has changed so mark all uniforms as dirty: brushUniformsDirty = true; brushShaderMatrixUniformDirty = true; @@ -737,7 +737,7 @@ void QGL2PaintEngineExPrivate::prepareForDraw() updateBrushUniforms(); if (brushShaderMatrixUniformDirty) { - shaderManager->brushShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; + shaderManager->currentProgram()->setUniformValue("pmvMatrix", pmvMatrix); brushShaderMatrixUniformDirty = false; } @@ -984,12 +984,12 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte updateMatrix(); if (textShaderMatrixUniformDirty) { - shaderManager->textShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; +// shaderManager->textShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; textShaderMatrixUniformDirty = false; } QColor col = premultiplyColor(s->pen.color(), (GLfloat)s->opacity); - shaderManager->textShader()->uniforms()[QLatin1String("fragmentColor")] = col; +// shaderManager->textShader()->uniforms()[QLatin1String("fragmentColor")] = col; GLfloat dx = 1.0 / image.width(); GLfloat dy = 1.0 / image.height(); @@ -1035,7 +1035,7 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) qt_resolve_glsl_extensions(d->ctx); if (!d->shaderManager) - d->shaderManager = new QGLPEXShaderManager(d->ctx); + d->shaderManager = new QGLEngineShaderManager(d->ctx); glViewport(0, 0, d->width, d->height); -- cgit v0.12 From 5c92012d6ee57f644f62af5732a27899f2a1f462 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 16 Apr 2009 15:31:16 +0200 Subject: Clean up existing & implement missing GLSL for new shader manager --- src/opengl/gl2paintengineex/glgc_shader_source.h | 290 ---------------- .../gl2paintengineex/qglengineshadermanager.cpp | 88 ++++- .../gl2paintengineex/qglengineshadermanager_p.h | 3 +- .../gl2paintengineex/qglengineshadersource_p.h | 385 +++++++++++++++++++++ src/opengl/opengl.pro | 2 +- 5 files changed, 467 insertions(+), 301 deletions(-) delete mode 100644 src/opengl/gl2paintengineex/glgc_shader_source.h create mode 100644 src/opengl/gl2paintengineex/qglengineshadersource_p.h diff --git a/src/opengl/gl2paintengineex/glgc_shader_source.h b/src/opengl/gl2paintengineex/glgc_shader_source.h deleted file mode 100644 index 5184c78..0000000 --- a/src/opengl/gl2paintengineex/glgc_shader_source.h +++ /dev/null @@ -1,290 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtOpenGL module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GLGC_SHADER_SOURCE_H -#define GLGC_SHADER_SOURCE_H - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(OpenGL) - - -static const char* qglslImageVertexShader = "\ - attribute highp vec4 inputVertex; \ - attribute lowp vec2 textureCoord; \ - uniform highp mat4 pmvMatrix; \ - varying lowp vec2 fragTextureCoord; \ - void main(void) \ - {\ - gl_Position = pmvMatrix * inputVertex;\ - fragTextureCoord = textureCoord; \ - }"; - -static const char* qglslImageFragmentShader = "\ - varying lowp vec2 fragTextureCoord;\ - uniform sampler2D textureSampler;\ - uniform lowp float opacity; \ - void main(void) \ - {\ - gl_FragColor = texture2D(textureSampler, fragTextureCoord) * opacity; \ - }"; - -static const char* qglslTextFragmentShader = "\ - varying lowp vec2 fragTextureCoord;\ - uniform mediump vec4 fragmentColor;\ - uniform sampler2D textureSampler;\ - void main(void) \ - {\ - highp vec4 tex = texture2D(textureSampler, fragTextureCoord); \ - tex = fragmentColor * tex.r; \ - gl_FragColor = tex; \ - }"; - -static const char* qglslDefaultVertexShader = "\ - attribute highp vec4 inputVertex;\ - uniform highp mat4 pmvMatrix;\ - void main(void)\ - {\ - gl_Position = pmvMatrix * inputVertex;\ - }"; - -static const char* qglslSimpleFragmentShader = "\ - void main (void)\ - {\ - gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);\ - }"; - - -/**** FRAGMENT SHADER MAIN FUNCTIONS ****/ -// NOTE: Currently, the engine assumes brushes return colors already in pre-multiplied -// format. However, this may change if we add support for non-premultiplied - -static const char* qglslNoOpacityFragmentShaderMain = "\n\ - mediump vec4 brush();\ - void main (void)\ - {\ - gl_FragColor = brush();\ - }\n"; - -static const char* qglslFragmentShaderMain = "\n\ - mediump vec4 brush();\ - uniform lowp float opacity; \ - void main (void)\ - {\ - gl_FragColor = brush() * opacity;\ - }\n"; - - - -/**** BRUSH SHADERS ****/ - -// This should never actually be used -static const char* qglslNoBrushFragmentShader = "\n\ - mediump vec4 brush() { \ - discard; \ - return vec4(1.0, 0.8, 0.8, 1.0);\ - }\n"; - -// Solid Fill Brush -static const char* qglslSolidBrushFragmentShader = "\n\ - uniform mediump vec4 fragmentColor; \ - mediump vec4 brush() { \ - return fragmentColor;\ - }\n"; - -// Texture Brush -static const char* qglslTextureBrushVertexShader = "\ - attribute highp vec4 inputVertex; \ - uniform highp mat4 pmvMatrix; \ - uniform mediump vec2 halfViewportSize; \ - uniform mediump vec2 invertedTextureSize; \ - uniform mediump mat3 brushTransform; \ - varying mediump vec2 texCoords; \ - void main(void) { \ - gl_Position = pmvMatrix * inputVertex;\ - gl_Position.xy = gl_Position.xy / gl_Position.w; \ - mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ - mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ - mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ - gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ - gl_Position.w = invertedHTexCoordsZ; \ - texCoords.xy = (hTexCoords.xy * invertedTextureSize) * gl_Position.w; \ - texCoords.y = -texCoords.y; \ - }"; - -static const char* qglslTextureBrushFragmentShader = "\n\ - varying mediump vec2 texCoords;\ - uniform sampler2D brushTexture;\ - mediump vec4 brush() { \ - return texture2D(brushTexture, texCoords); \ - }\n"; - - -// Pattern Brush - This assumes the texture size is 8x8 and thus, the inverted size is 0.125 -static const char* qglslPatternBrushVertexShader = "\ - attribute highp vec4 inputVertex; \ - uniform highp mat4 pmvMatrix; \ - uniform mediump vec2 halfViewportSize; \ - uniform mediump vec2 invertedTextureSize; \ - uniform mediump mat3 brushTransform; \ - varying mediump vec2 texCoords; \ - void main(void) { \ - gl_Position = pmvMatrix * inputVertex;\ - gl_Position.xy = gl_Position.xy / gl_Position.w; \ - mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ - mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ - mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ - gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ - gl_Position.w = invertedHTexCoordsZ; \ - texCoords.xy = (hTexCoords.xy * 0.125) * invertedHTexCoordsZ; \ - texCoords.y = -texCoords.y; \ - }"; - -static const char* qglslPatternBrushFragmentShader = "\n\ - uniform sampler2D brushTexture;\ - uniform lowp vec4 patternColor; \ - varying mediump vec2 texCoords;\ - mediump vec4 brush() { \ - return patternColor * texture2D(brushTexture, texCoords).r; \ - }\n"; - - -// Linear Gradient Brush -static const char* qglslLinearGradientBrushVertexShader = "\ - attribute highp vec4 inputVertex; \ - uniform highp mat4 pmvMatrix; \ - uniform mediump vec2 halfViewportSize; \ - uniform highp vec3 linearData; \ - uniform mediump mat3 brushTransform; \ - varying mediump float index ; \ - void main() { \ - gl_Position = pmvMatrix * inputVertex;\ - gl_Position.xy = gl_Position.xy / gl_Position.w; \ - mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ - mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ - mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ - gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ - gl_Position.w = invertedHTexCoordsZ; \ - index = (dot(linearData.xy, hTexCoords.xy) * linearData.z) * invertedHTexCoordsZ; \ - }"; - -static const char* qglslLinearGradientBrushFragmentShader = "\n\ - uniform sampler2D brushTexture; \ - varying mediump float index; \ - mediump vec4 brush() { \ - mediump vec2 val = vec2(index, 0.5); \ - return texture2D(brushTexture, val); \ - }\n"; - - -static const char* qglslRadialGradientBrushVertexShader = "\ - attribute highp vec4 inputVertex;\ - uniform highp mat4 pmvMatrix;\ - uniform mediump vec2 halfViewportSize; \ - uniform highp mat3 brushTransform; \ - uniform highp vec2 fmp; \ - varying highp float b; \ - varying highp vec2 A; \ - void main(void) \ - {\ - gl_Position = pmvMatrix * inputVertex;\ - gl_Position.xy = gl_Position.xy / gl_Position.w; \ - mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ - mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ - mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ - gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ - gl_Position.w = invertedHTexCoordsZ; \ - A = hTexCoords.xy * invertedHTexCoordsZ; \ - b = 2.0 * fmp * (A.x + A.y); \ -\ - }"; - -static const char* qglslRadialGradientBrushFragmentShader = "\n\ - uniform sampler2D brushTexture; \ - uniform highp float fmp2_m_radius2; \ - uniform highp float inverse_2_fmp2_m_radius2; \ - varying highp float b; \ - varying highp vec2 A; \ -\ - mediump vec4 brush() { \ - highp float c = -dot(A, A); \ - highp vec2 val = vec2((-b + sqrt(b*b - 4.0*fmp2_m_radius2*c)) * inverse_2_fmp2_m_radius2, 0.5); \ - return texture2D(brushTexture, val); \ - }\n"; - -static const char* qglslConicalGradientBrushVertexShader = "\ - attribute highp vec4 inputVertex;\ - uniform highp mat4 pmvMatrix;\ - uniform mediump vec2 halfViewportSize; \ - uniform highp mat3 brushTransform; \ - varying highp vec2 A; \ - void main(void)\ - {\ - gl_Position = pmvMatrix * inputVertex;\ - gl_Position.xy = gl_Position.xy / gl_Position.w; \ - mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ - mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ - mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ - gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ - gl_Position.w = invertedHTexCoordsZ; \ - A = hTexCoords.xy * invertedHTexCoordsZ; \ - }"; - -static const char* qglslConicalGradientBrushFragmentShader = "\n\ - #define INVERSE_2PI 0.1591549430918953358 \n\ - uniform sampler2D brushTexture; \ - uniform mediump float angle; \ - varying highp vec2 A; \ - mediump vec4 brush() { \ - if (abs(A.y) == abs(A.x)) \ - A.y += 0.002; \ - highp float t = (atan2(-A.y, A.x) + angle) * INVERSE_2PI; \ - return texture2D(brushTexture, vec2(t - floor(t), 0.5)); \ - }\n"; - - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // GLGC_SHADER_SOURCE_H diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index 1086430..ea01604 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -40,12 +40,20 @@ ****************************************************************************/ #include "qglengineshadermanager_p.h" +#include "qglengineshadersource_p.h" #if defined(QT_DEBUG) #include #endif +const char* QGLEngineShaderManager::qglEngineShaderSourceCode[] = { + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0 +}; + QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) : ctx(context), shaderProgNeedsChanging(true), @@ -58,6 +66,77 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) currentShaderProg(0) { memset(compiledShaders, 0, sizeof(compiledShaders)); + +/* + Rather than having the shader source array statically initialised, it is initialised + here instead. This is to allow new shader names to be inserted or existing names moved + around without having to change the order of the glsl strings. It is hoped this will + make future hard-to-find runtime bugs more obvious and generally give more solid code. +*/ + static bool qglEngineShaderSourceCodePopulated = false; + if (!qglEngineShaderSourceCodePopulated) { + + const char** code = qglEngineShaderSourceCode; // shortcut + + code[SimpleVertexShader] = qglslSimpleVertexShader; + code[MainVertexShader] = qglslMainVertexShader; + code[MainWithTexCoordsVertexShader] = qglslMainWithTexCoordsVertexShader; + + code[PositionOnlyVertexShader] = qglslPositionOnlyVertexShader; + code[PositionWithPatternBrushVertexShader] = qglslPositionWithPatternBrushVertexShader; + code[PositionWithLinearGradientBrushVertexShader] = qglslPositionWithLinearGradientBrushVertexShader; + code[PositionWithConicalGradientBrushVertexShader] = qglslPositionWithConicalGradientBrushVertexShader; + code[PositionWithRadialGradientBrushVertexShader] = qglslPositionWithRadialGradientBrushVertexShader; + code[PositionWithTextureBrushVertexShader] = qglslPositionWithTextureBrushVertexShader; + code[AffinePositionWithPatternBrushVertexShader] = qglslAffinePositionWithPatternBrushVertexShader; + code[AffinePositionWithLinearGradientBrushVertexShader] = qglslAffinePositionWithLinearGradientBrushVertexShader; + code[AffinePositionWithConicalGradientBrushVertexShader] = qglslAffinePositionWithConicalGradientBrushVertexShader; + code[AffinePositionWithRadialGradientBrushVertexShader] = qglslAffinePositionWithRadialGradientBrushVertexShader; + code[AffinePositionWithTextureBrushVertexShader] = qglslAffinePositionWithTextureBrushVertexShader; + + code[MainFragmentShader_CMO] = qglslMainFragmentShader_CMO; + code[MainFragmentShader_CM] = qglslMainFragmentShader_CM; + code[MainFragmentShader_MO] = qglslMainFragmentShader_MO; + code[MainFragmentShader_M] = qglslMainFragmentShader_M; + code[MainFragmentShader_CO] = qglslMainFragmentShader_CO; + code[MainFragmentShader_C] = qglslMainFragmentShader_C; + code[MainFragmentShader_O] = qglslMainFragmentShader_O; + code[MainFragmentShader] = qglslMainFragmentShader; + + code[ImageSrcFragmentShader] = qglslImageSrcFragmentShader; + code[NonPremultipliedImageSrcFragmentShader] = qglslNonPremultipliedImageSrcFragmentShader; + code[SolidBrushSrcFragmentShader] = qglslSolidBrushSrcFragmentShader; + code[TextureBrushSrcFragmentShader] = qglslTextureBrushSrcFragmentShader; + code[PatternBrushSrcFragmentShader] = qglslPatternBrushSrcFragmentShader; + code[LinearGradientBrushSrcFragmentShader] = qglslLinearGradientBrushSrcFragmentShader; + code[RadialGradientBrushSrcFragmentShader] = qglslRadialGradientBrushSrcFragmentShader; + code[ConicalGradientBrushSrcFragmentShader] = qglslConicalGradientBrushSrcFragmentShader; + + code[MaskFragmentShader] = qglslMaskFragmentShader; + code[RgbMaskFragmentShader] = ""; //### + code[RgbMaskWithGammaFragmentShader] = ""; //### + + code[MultiplyCompositionModeFragmentShader] = ""; //### + code[ScreenCompositionModeFragmentShader] = ""; //### + code[OverlayCompositionModeFragmentShader] = ""; //### + code[DarkenCompositionModeFragmentShader] = ""; //### + code[LightenCompositionModeFragmentShader] = ""; //### + code[ColorDodgeCompositionModeFragmentShader] = ""; //### + code[ColorBurnCompositionModeFragmentShader] = ""; //### + code[HardLightCompositionModeFragmentShader] = ""; //### + code[SoftLightCompositionModeFragmentShader] = ""; //### + code[DifferenceCompositionModeFragmentShader] = ""; //### + code[ExclusionCompositionModeFragmentShader] = ""; //### + +#if defined(QT_DEBUG) + // Check that all the elements have been filled: + for (int i = 0; i < TotalShaderCount; ++i) { + if (qglEngineShaderSourceCode[i] == 0) + qCritical() << "qglEngineShaderSourceCode: Missing shader in element" << i; + } +#endif + qglEngineShaderSourceCodePopulated = true; + } } QGLEngineShaderManager::~QGLEngineShaderManager() @@ -303,15 +382,6 @@ void QGLEngineShaderManager::useCorrectShaderProg() } } -/* - QGLShader* mainVertexShader; - QGLShader* positionVertexShader; - QGLShader* mainFragShader; - QGLShader* srcPixelFragShader; - QGLShader* maskFragShader; // Can be null for no mask - QGLShader* compositionFragShader; // Can be null for GL-handled mode - QGLShaderProgram* program; -*/ // Shader program not found in cache, create it now. requiredProgram.program = new QGLShaderProgram(ctx, this); requiredProgram.program->addShader(requiredProgram.mainVertexShader); diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index fe30a70..38c1cff 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -375,8 +375,9 @@ private: QGLShader* compiledShaders[TotalShaderCount]; void compileNamedShader(QGLEngineShaderManager::ShaderName name, QGLShader::ShaderType type); -}; + static const char* qglEngineShaderSourceCode[TotalShaderCount]; +}; QT_END_NAMESPACE diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h new file mode 100644 index 0000000..945c56c --- /dev/null +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -0,0 +1,385 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtOpenGL module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + + +#ifndef QGL_ENGINE_SHADER_SOURCE_H +#define QGL_ENGINE_SHADER_SOURCE_H + +#include "qglengineshadermanager_p.h" + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(OpenGL) + + +static const char* const qglslSimpleVertexShader = "\ + attribute highp vec4 inputVertex;\ + uniform highp mat4 pmvMatrix;\ + void main(void)\ + {\ + gl_Position = pmvMatrix * inputVertex;\ + }"; + +static const char* const qglslMainVertexShader = "\ + void setPosition();\ + void main(void)\ + {\ + setPosition();\ + }"; + +static const char* const qglslMainWithTexCoordsVertexShader = "\ + attribute lowp vec2 textureCoord; \ + varying lowp vec2 fragTextureCoord; \ + void setPosition();\ + void main(void) \ + {\ + setPosition();\ + fragTextureCoord = textureCoord; \ + }"; + + +static const char* const qglslPositionOnlyVertexShader = "\ + attribute highp vec4 inputVertex;\ + uniform highp mat4 pmvMatrix;\ + void setPosition(void)\ + {\ + gl_Position = pmvMatrix * inputVertex;\ + }"; + + +// Pattern Brush - This assumes the texture size is 8x8 and thus, the inverted size is 0.125 +static const char* const qglslPositionWithPatternBrushVertexShader = "\ + attribute highp vec4 inputVertex; \ + uniform highp mat4 pmvMatrix; \ + uniform mediump vec2 halfViewportSize; \ + uniform mediump vec2 invertedTextureSize; \ + uniform mediump mat3 brushTransform; \ + varying mediump vec2 patternTexCoords; \ + void setPosition(void) { \ + gl_Position = pmvMatrix * inputVertex;\ + gl_Position.xy = gl_Position.xy / gl_Position.w; \ + mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ + mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ + mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ + gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ + gl_Position.w = invertedHTexCoordsZ; \ + patternTexCoords.xy = (hTexCoords.xy * 0.125) * invertedHTexCoordsZ; \ + patternTexCoords.y = -patternTexCoords.y; \ + }"; + +static const char* const qglslAffinePositionWithPatternBrushVertexShader + = qglslPositionWithPatternBrushVertexShader; + +static const char* const qglslPatternBrushSrcFragmentShader = "\ + uniform sampler2D brushTexture;\ + uniform lowp vec4 patternColor; \ + varying mediump vec2 patternTexCoords;\ + lowp vec4 srcPixel() { \ + return patternColor * texture2D(brushTexture, patternTexCoords).r; \ + }\n"; + + +// Linear Gradient Brush +static const char* const qglslPositionWithLinearGradientBrushVertexShader = "\ + attribute highp vec4 inputVertex; \ + uniform highp mat4 pmvMatrix; \ + uniform mediump vec2 halfViewportSize; \ + uniform highp vec3 linearData; \ + uniform highp mat3 brushTransform; \ + varying mediump float index ; \ + void setPosition() { \ + gl_Position = pmvMatrix * inputVertex;\ + gl_Position.xy = gl_Position.xy / gl_Position.w; \ + mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ + mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ + mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ + gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ + gl_Position.w = invertedHTexCoordsZ; \ + index = (dot(linearData.xy, hTexCoords.xy) * linearData.z) * invertedHTexCoordsZ; \ + }"; + +static const char* const qglslAffinePositionWithLinearGradientBrushVertexShader + = qglslPositionWithLinearGradientBrushVertexShader; + +static const char* const qglslLinearGradientBrushSrcFragmentShader = "\ + uniform sampler2D brushTexture; \ + varying mediump float index; \ + lowp vec4 srcPixel() { \ + mediump vec2 val = vec2(index, 0.5); \ + return texture2D(brushTexture, val); \ + }\n"; + + +// Conical Gradient Brush +static const char* const qglslPositionWithConicalGradientBrushVertexShader = "\ + attribute highp vec4 inputVertex;\ + uniform highp mat4 pmvMatrix;\ + uniform mediump vec2 halfViewportSize; \ + uniform highp mat3 brushTransform; \ + varying highp vec2 A; \ + void setPosition(void)\ + {\ + gl_Position = pmvMatrix * inputVertex;\ + gl_Position.xy = gl_Position.xy / gl_Position.w; \ + mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ + mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ + mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ + gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ + gl_Position.w = invertedHTexCoordsZ; \ + A = hTexCoords.xy * invertedHTexCoordsZ; \ + }"; + +static const char* const qglslAffinePositionWithConicalGradientBrushVertexShader + = qglslPositionWithConicalGradientBrushVertexShader; + +static const char* const qglslConicalGradientBrushSrcFragmentShader = "\ + #define INVERSE_2PI 0.1591549430918953358 \n\ + uniform sampler2D brushTexture; \ + uniform mediump float angle; \ + varying highp vec2 A; \ + lowp vec4 srcPixel() { \ + if (abs(A.y) == abs(A.x)) \ + A.y += 0.002; \ + highp float t = (atan2(-A.y, A.x) + angle) * INVERSE_2PI; \ + return texture2D(brushTexture, vec2(t - floor(t), 0.5)); \ + }"; + + +// Radial Gradient Brush +static const char* const qglslPositionWithRadialGradientBrushVertexShader = "\ + attribute highp vec4 inputVertex;\ + uniform highp mat4 pmvMatrix;\ + uniform mediump vec2 halfViewportSize; \ + uniform highp mat3 brushTransform; \ + uniform highp vec2 fmp; \ + varying highp float b; \ + varying highp vec2 A; \ + void setPosition(void) \ + {\ + gl_Position = pmvMatrix * inputVertex;\ + gl_Position.xy = gl_Position.xy / gl_Position.w; \ + mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ + mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ + mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ + gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ + gl_Position.w = invertedHTexCoordsZ; \ + A = hTexCoords.xy * invertedHTexCoordsZ; \ + b = 2.0 * fmp * (A.x + A.y); \ + }"; + +static const char* const qglslAffinePositionWithRadialGradientBrushVertexShader + = qglslPositionWithRadialGradientBrushVertexShader; + +static const char* const qglslRadialGradientBrushSrcFragmentShader = "\ + uniform sampler2D brushTexture; \ + uniform highp float fmp2_m_radius2; \ + uniform highp float inverse_2_fmp2_m_radius2; \ + varying highp float b; \ + varying highp vec2 A; \ + lowp vec4 srcPixel() { \ + highp float c = -dot(A, A); \ + highp vec2 val = vec2((-b + sqrt(b*b - 4.0*fmp2_m_radius2*c)) * inverse_2_fmp2_m_radius2, 0.5); \ + return texture2D(brushTexture, val); \ + }"; + + +// Texture Brush +static const char* const qglslPositionWithTextureBrushVertexShader = "\ + attribute highp vec4 inputVertex; \ + uniform highp mat4 pmvMatrix; \ + uniform mediump vec2 halfViewportSize; \ + uniform mediump vec2 invertedTextureSize; \ + uniform mediump mat3 brushTransform; \ + varying mediump vec2 textureTexCoords; \ + void setPosition(void) { \ + gl_Position = pmvMatrix * inputVertex;\ + gl_Position.xy = gl_Position.xy / gl_Position.w; \ + mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ + mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ + mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ + gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ + gl_Position.w = invertedHTexCoordsZ; \ + textureTexCoords.xy = (hTexCoords.xy * invertedTextureSize) * gl_Position.w; \ + textureTexCoords.y = -textureTexCoords.y; \ + }"; + +static const char* const qglslAffinePositionWithTextureBrushVertexShader + = qglslPositionWithTextureBrushVertexShader; + +static const char* const qglslTextureBrushSrcFragmentShader = "\ + varying mediump vec2 textureTexCoords; \ + uniform sampler2D brushTexture; \ + lowp vec4 srcPixel() { \ + return texture2D(brushTexture, textureTexCoords); \ + }"; + + +// Solid Fill Brush +static const char* const qglslSolidBrushSrcFragmentShader = "\ + uniform lowp vec4 fragmentColor; \ + lowp vec4 srcPixel() { \ + return fragmentColor; \ + }"; + +static const char* const qglslImageSrcFragmentShader = "\ + varying highp vec2 texCoord; \ + uniform sampler2D textureSampler; \ + lowp vec4 srcPixel() { \ + return texture2D(textureSampler, texCoord); \ + }"; + +static const char* const qglslNonPremultipliedImageSrcFragmentShader = "\ + varying highp vec2 texCoord; \ + uniform sampler2D textureSampler; \ + lowp vec4 srcPixel() { \ + lowp vec4 sample = texture2D(textureSampler, texCoord); \ + sample.rgb = sample.rgb * sample.a; \ + return sample; \ + }"; + + +static const char* const qglslMainFragmentShader_CMO = "\ + uniform lowp float globalOpacity; \ + lowp vec4 srcPixel(); \ + lowp vec4 applyMask(lowp vec4); \ + lowp vec4 compose(lowp vec4); \ + void main() { \ + gl_FragColor = compose(applyMask(srcPixel()*globalOpacity)); \ + }"; + +static const char* const qglslMainFragmentShader_CM = "\ + lowp vec4 srcPixel(); \ + lowp vec4 applyMask(lowp vec4); \ + lowp vec4 compose(lowp vec4); \ + void main() { \ + gl_FragColor = compose(applyMask(srcPixel())); \ + }"; + +static const char* const qglslMainFragmentShader_MO = "\ + uniform lowp float globalOpacity; \ + lowp vec4 srcPixel(); \ + lowp vec4 applyMask(lowp vec4); \ + void main() { \ + gl_FragColor = applyMask(srcPixel()*globalOpacity); \ + }"; + +static const char* const qglslMainFragmentShader_M = "\ + lowp vec4 srcPixel(); \ + lowp vec4 applyMask(lowp vec4); \ + void main() { \ + gl_FragColor = applyMask(srcPixel()); \ + }"; + +static const char* const qglslMainFragmentShader_CO = "\ + uniform lowp float globalOpacity; \ + lowp vec4 srcPixel(); \ + lowp vec4 compose(lowp vec4); \ + void main() { \ + gl_FragColor = compose(srcPixel()*globalOpacity); \ + }"; + +static const char* const qglslMainFragmentShader_C = "\ + lowp vec4 srcPixel(); \ + lowp vec4 compose(lowp vec4); \ + void main() { \ + gl_FragColor = compose(srcPixel()); \ + }"; + +static const char* const qglslMainFragmentShader_O = "\ + uniform lowp float globalOpacity; \ + lowp vec4 srcPixel(); \ + void main() { \ + gl_FragColor = srcPixel()*globalOpacity; \ + }"; + +static const char* const qglslMainFragmentShader = "\ + lowp vec4 srcPixel(); \ + void main() { \ + gl_FragColor = srcPixel(); \ + }"; + + +static const char* const qglslMaskFragmentShader = "\ + varying highp vec2 texCoord;\ + uniform sampler2D maskTextureSampler;\ + lowp vec4 applyMask(lowp vec4 src) \ + {\ + lowp vec4 mask = texture2D(maskTextureSampler, texCoord); \ + return src * mask.a; \ + }"; + +/* + Left to implement: + RgbMaskFragmentShader, + RgbMaskWithGammaFragmentShader, + + MultiplyCompositionModeFragmentShader, + ScreenCompositionModeFragmentShader, + OverlayCompositionModeFragmentShader, + DarkenCompositionModeFragmentShader, + LightenCompositionModeFragmentShader, + ColorDodgeCompositionModeFragmentShader, + ColorBurnCompositionModeFragmentShader, + HardLightCompositionModeFragmentShader, + SoftLightCompositionModeFragmentShader, + DifferenceCompositionModeFragmentShader, + ExclusionCompositionModeFragmentShader, +*/ + + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // GLGC_SHADER_SOURCE_H diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro index 1527f2d..8cf0e37 100644 --- a/src/opengl/opengl.pro +++ b/src/opengl/opengl.pro @@ -51,7 +51,7 @@ SOURCES += qgl.cpp \ gl2paintengineex/qglengineshadermanager_p.h \ gl2paintengineex/qgl2pexvertexarray_p.h \ gl2paintengineex/qpaintengineex_opengl2_p.h \ - gl2paintengineex/glgc_shader_source.h + gl2paintengineex/qglengineshadersource_p.h #} -- cgit v0.12 From a241ebac49f01ba0e26a177f1aadbd18c7e9cae7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 16 Apr 2009 10:55:12 +0200 Subject: Use FBOs as pixmap backend in GL graphics system. We now use FBOs to implement render-to-pixmap for the GL pixmap backend. A multisample FBO is used for rendering, and is then blitted onto a non-multisample FBO dynamically bound to the relevant texture. Reviewed-by: Tom --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 38 +++- src/opengl/qgl.cpp | 56 ++++- src/opengl/qgl.h | 2 +- src/opengl/qgl_p.h | 8 +- src/opengl/qglframebufferobject.cpp | 16 +- src/opengl/qpixmapdata_gl.cpp | 236 +++++++++++++++------ src/opengl/qpixmapdata_gl_p.h | 19 +- src/opengl/qwindowsurface_gl.cpp | 34 ++- 8 files changed, 311 insertions(+), 98 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index e166b54..fe70020 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -175,6 +175,8 @@ public: // Clipping & state stuff stolen from QOpenGLPaintEngine: void updateDepthClip(); uint use_system_clip : 1; + + QPaintEngine *last_engine; }; @@ -616,7 +618,6 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) const QPointF* const points = reinterpret_cast(path.points()); - // Check to see if there's any hints if (path.shape() == QVectorPath::RectangleHint) { QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y()); @@ -1034,6 +1035,14 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) qt_resolve_version_1_3_functions(d->ctx); qt_resolve_glsl_extensions(d->ctx); + d->last_engine = d->ctx->d_ptr->active_engine; + d->ctx->d_ptr->active_engine = this; + + if (d->last_engine) { + QGL2PaintEngineEx *engine = static_cast(d->last_engine); + static_cast(engine->d_ptr)->transferMode(DefaultMode); + } + if (!d->shaderManager) d->shaderManager = new QGLPEXShaderManager(d->ctx); @@ -1054,6 +1063,19 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) d->use_system_clip = !systemClip().isEmpty(); glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + + QGLPixmapData *source = d->drawable.copyOnBegin(); + if (source) { + d->transferMode(ImageDrawingMode); + + source->bind(); + + glDisable(GL_BLEND); + + QRect rect(0, 0, source->width(), source->height()); + d->drawTexture(QRectF(rect), QRectF(rect), rect.size()); + } updateClipRegion(QRegion(), Qt::NoClip); return true; @@ -1067,6 +1089,20 @@ bool QGL2PaintEngineEx::end() d->transferMode(DefaultMode); d->drawable.swapBuffers(); d->drawable.doneCurrent(); + d->ctx->d_ptr->active_engine = d->last_engine; + + if (d->last_engine) { + QGL2PaintEngineEx *engine = static_cast(d->last_engine); + QGL2PaintEngineExPrivate *p = static_cast(engine->d_ptr); + + glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + + glViewport(0, 0, p->width, p->height); + engine->setState(engine->state()); + p->updateDepthClip(); + } + return false; } diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index fc11d90..32531e7 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -1295,6 +1295,7 @@ void QGLContextPrivate::init(QPaintDevice *dev, const QGLFormat &format) eglContext = 0; #endif pbo = 0; + fbo = 0; crWin = false; initDone = false; sharing = false; @@ -1303,6 +1304,7 @@ void QGLContextPrivate::init(QPaintDevice *dev, const QGLFormat &format) version_flags_cached = false; version_flags = QGLFormat::OpenGL_Version_None; current_fbo = 0; + active_engine = 0; } QGLContext* QGLContext::currentCtx = 0; @@ -1313,12 +1315,8 @@ QGLContext* QGLContext::currentCtx = 0; QGLFramebufferObject::toImage() */ -QImage qt_gl_read_framebuffer(const QSize &size, bool alpha_format, bool include_alpha) +static void convertFromGLImage(QImage &img, int w, int h, bool alpha_format, bool include_alpha) { - QImage img(size, alpha_format ? QImage::Format_ARGB32 : QImage::Format_RGB32); - int w = size.width(); - int h = size.height(); - glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { // OpenGL gives RGBA; Qt wants ARGB uint *p = (uint*)img.bits(); @@ -1341,7 +1339,27 @@ QImage qt_gl_read_framebuffer(const QSize &size, bool alpha_format, bool include // OpenGL gives ABGR (i.e. RGBA backwards); Qt wants ARGB img = img.rgbSwapped(); } - return img.mirrored(); + img = img.mirrored(); +} + +QImage qt_gl_read_framebuffer(const QSize &size, bool alpha_format, bool include_alpha) +{ + QImage img(size, alpha_format ? QImage::Format_ARGB32 : QImage::Format_RGB32); + int w = size.width(); + int h = size.height(); + glReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); + convertFromGLImage(img, w, h, alpha_format, include_alpha); + return img; +} + +QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alpha) +{ + QImage img(size, alpha_format ? QImage::Format_ARGB32 : QImage::Format_RGB32); + int w = size.width(); + int h = size.height(); + glGetTexImage(qt_gl_preferredTextureTarget(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); + convertFromGLImage(img, w, h, alpha_format, include_alpha); + return img; } // returns the highest number closest to v, which is a power of 2 @@ -4235,6 +4253,15 @@ void QGLDrawable::setDevice(QPaintDevice *pdev) #ifdef Q_WS_QWS wsurf = 0; #endif + + if (pdev->devType() == QInternal::Pixmap) { + QPixmapData *data = static_cast(pdev)->pixmapData(); + Q_ASSERT(data->classId() == QPixmapData::OpenGLClass); + pixmapData = static_cast(data); + + fbo = pixmapData->fbo(); + } + if (pdev->devType() == QInternal::Widget) widget = static_cast(pdev); else if (pdev->devType() == QInternal::Pbuffer) @@ -4261,7 +4288,9 @@ void QGLDrawable::swapBuffers() void QGLDrawable::makeCurrent() { - if (widget) + if (pixmapData) + pixmapData->beginPaint(); + else if (widget) widget->makeCurrent(); else if (buffer) buffer->makeCurrent(); @@ -4274,9 +4303,18 @@ void QGLDrawable::makeCurrent() } } +QGLPixmapData *QGLDrawable::copyOnBegin() const +{ + if (!pixmapData || pixmapData->isUninitialized()) + return 0; + return pixmapData; +} + void QGLDrawable::doneCurrent() { - if (fbo && !wasBound) + if (pixmapData) + pixmapData->endPaint(); + else if (fbo && !wasBound) fbo->release(); } @@ -4285,6 +4323,8 @@ QSize QGLDrawable::size() const if (widget) { return QSize(widget->d_func()->glcx->device()->width(), widget->d_func()->glcx->device()->height()); + } else if (pixmapData) { + return pixmapData->size(); } else if (buffer) { return buffer->size(); } else if (fbo) { diff --git a/src/opengl/qgl.h b/src/opengl/qgl.h index 32fbce2..19d779a 100644 --- a/src/opengl/qgl.h +++ b/src/opengl/qgl.h @@ -372,8 +372,8 @@ private: friend QGLContextPrivate *qt_phonon_get_dptr(const QGLContext *); #endif friend class QGLFramebufferObject; -#ifdef Q_WS_WIN friend class QGLFramebufferObjectPrivate; +#ifdef Q_WS_WIN friend bool qt_resolve_GLSL_functions(QGLContext *ctx); friend bool qt_createGLSLProgram(QGLContext *ctx, GLuint &program, const char *shader_src, GLuint &shader); #endif diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index 8ab73d8..51c07b5 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -60,6 +60,7 @@ #include "QtCore/qthreadstorage.h" #include "QtCore/qhash.h" #include "private/qwidget_p.h" +#include "private/qpixmapdata_gl_p.h" #ifndef QT_OPENGL_ES_1_CL #define q_vertexType float @@ -238,6 +239,7 @@ public: QGLFormat glFormat; QGLFormat reqFormat; GLuint pbo; + GLuint fbo; uint valid : 1; uint sharing : 1; @@ -255,6 +257,7 @@ public: GLint max_texture_size; GLuint current_fbo; + QPaintEngine *active_engine; #ifdef Q_WS_WIN static inline QGLExtensionFuncs& qt_get_extension_funcs(const QGLContext *ctx) { return ctx->d_ptr->extensionFuncs; } @@ -289,7 +292,7 @@ class QGLWindowSurface; class QGLDrawable { public: QGLDrawable() : widget(0), buffer(0), fbo(0) - , wsurf(0) + , wsurf(0), pixmapData(0) {} void setDevice(QPaintDevice *pdev); void swapBuffers(); @@ -303,6 +306,8 @@ public: QGLContext *context() const; bool autoFillBackground() const; + QGLPixmapData *copyOnBegin() const; + private: bool wasBound; QGLWidget *widget; @@ -313,6 +318,7 @@ private: #else QGLWindowSurface *wsurf; #endif + QGLPixmapData *pixmapData; }; // GL extension definitions diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 61d0f85..f86205a 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -475,7 +475,7 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At fbo_attachment = QGLFramebufferObject::NoAttachment; } - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); if (!valid) { if (color_buffer) glDeleteRenderbuffersEXT(1, &color_buffer); @@ -825,18 +825,17 @@ bool QGLFramebufferObject::release() return false; Q_D(QGLFramebufferObject); QGL_FUNC_CONTEXT; - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); - d->valid = d->checkFramebufferStatus(); d->bound = false; + const QGLContext *context = QGLContext::currentContext(); - if (d->valid && context) { + if (context) { // Restore the previous setting for stacked framebuffer objects. context->d_ptr->current_fbo = d->previous_fbo; - if (d->previous_fbo) - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, d->previous_fbo); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, d->previous_fbo); d->previous_fbo = 0; } - return d->valid; + + return true; } /*! @@ -1148,8 +1147,7 @@ void QGLFramebufferObject::blitFramebuffer(QGLFramebufferObject *target, const Q tx0, ty0, tx1, ty1, buffers, filter); - glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, 0); - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); } QT_END_NAMESPACE diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index ec71fa6..0656880 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -40,6 +40,7 @@ ****************************************************************************/ #include "qpixmap.h" +#include "qglframebufferobject.h" #include @@ -48,6 +49,12 @@ #include #include +#if 1 || defined(QT_OPENGL_ES_2) +#include +#else +#include +#endif + QT_BEGIN_NAMESPACE extern QGLWidget* qt_gl_share_widget(); @@ -89,48 +96,16 @@ private: QGLContext *m_ctx; }; -void qt_gl_convertFromGLImage(QImage *img) -{ - const int w = img->width(); - const int h = img->height(); - - if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { - uint *p = (uint*)img->bits(); - uint *end = p + w*h; - - while (p < end) { - uint a = *p << 24; - *p = (*p >> 8) | a; - p++; - } - - *img = img->mirrored(); - } else { - // mirror image - uint *data = (uint *)img->bits(); - - const int mid = h/2; - - for (int y = 0; y < mid; ++y) { - uint *p = data + y * w; - uint *end = p + w; - uint *q = data + (h - y - 1) * w; - - while (p < end) - qSwap(*p++, *q++); - } - } -} - - static int qt_gl_pixmap_serial = 0; QGLPixmapData::QGLPixmapData(PixelType type) : QPixmapData(type, OpenGLClass) , m_width(0) , m_height(0) + , m_renderFbo(0) + , m_textureId(0) + , m_engine(0) , m_ctx(0) - , m_texture(0) , m_dirty(false) { setSerialNumber(++qt_gl_pixmap_serial); @@ -138,10 +113,11 @@ QGLPixmapData::QGLPixmapData(PixelType type) QGLPixmapData::~QGLPixmapData() { - if (m_texture && qt_gl_share_widget()) { - QGLShareContextScope ctx(qt_gl_share_widget()->context()); - glDeleteTextures(1, &m_texture); - } + QGLWidget *shareWidget = qt_gl_share_widget(); + if (!shareWidget) + return; + QGLShareContextScope ctx(shareWidget->context()); + glDeleteTextures(1, &m_textureId); } bool QGLPixmapData::isValid() const @@ -166,6 +142,12 @@ void QGLPixmapData::resize(int width, int height) m_width = width; m_height = height; + if (m_textureId) { + QGLShareContextScope ctx(qt_gl_share_widget()->context()); + glDeleteTextures(1, &m_textureId); + m_textureId = 0; + } + m_source = QImage(); m_dirty = isValid(); setSerialNumber(++qt_gl_pixmap_serial); @@ -184,24 +166,30 @@ void QGLPixmapData::ensureCreated() const const GLenum format = qt_gl_preferredTextureFormat(); const GLenum target = qt_gl_preferredTextureTarget(); - if (!m_texture) - glGenTextures(1, &m_texture); - - glBindTexture(target, m_texture); + if (!m_textureId) { + glGenTextures(1, &m_textureId); + glBindTexture(target, m_textureId); + glTexImage2D(target, 0, GL_RGBA, m_width, m_height, 0, + GL_RGBA, GL_UNSIGNED_BYTE, 0); + } - if (m_source.isNull()) { - glTexImage2D(target, 0, GL_RGBA, m_width, m_height, 0, format, GL_UNSIGNED_BYTE, 0); - } else { + if (!m_source.isNull()) { const QImage tx = ctx->d_func()->convertToGLFormat(m_source, true, format); - glBindTexture(target, m_texture); - glTexImage2D(target, 0, GL_RGBA, m_width, m_height, 0, format, - GL_UNSIGNED_BYTE, tx.bits()); + glBindTexture(target, m_textureId); + glTexSubImage2D(target, 0, 0, 0, m_width, m_height, format, + GL_UNSIGNED_BYTE, tx.bits()); - m_source = QImage(); + if (useFramebufferObjects()) + m_source = QImage(); } } +QGLFramebufferObject *QGLPixmapData::fbo() const +{ + return m_renderFbo; +} + void QGLPixmapData::fromImage(const QImage &image, Qt::ImageConversionFlags) { @@ -220,6 +208,17 @@ bool QGLPixmapData::scroll(int dx, int dy, const QRect &rect) return false; } +void QGLPixmapData::copy(const QPixmapData *data, const QRect &rect) +{ + if (data->classId() != QPixmapData::OpenGLClass) { + QPixmapData::copy(data, rect); + return; + } + + // can be optimized to do a framebuffer blit or similar ... + QPixmapData::copy(data, rect); +} + void QGLPixmapData::fill(const QColor &color) { if (!isValid()) @@ -246,7 +245,9 @@ QImage QGLPixmapData::toImage() const if (!isValid()) return QImage(); - if (!m_source.isNull()) + if (m_renderFbo) + return m_renderFbo->toImage().copy(0, m_renderFbo->height() - m_height, m_width, m_height); + else if (!m_source.isNull()) return m_source; else if (m_dirty) return QImage(m_width, m_height, QImage::Format_ARGB32_Premultiplied); @@ -254,21 +255,84 @@ QImage QGLPixmapData::toImage() const ensureCreated(); QGLShareContextScope ctx(qt_gl_share_widget()->context()); - QImage img(m_width, m_height, QImage::Format_ARGB32_Premultiplied); + extern QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alpha); + glBindTexture(qt_gl_preferredTextureTarget(), m_textureId); + return qt_gl_read_texture(QSize(m_width, m_height), true, true); +} - GLenum format = qt_gl_preferredTextureFormat(); - GLenum target = qt_gl_preferredTextureTarget(); +struct TextureBuffer +{ + QGLFramebufferObject *fbo; + QGL2PaintEngineEx *engine; +}; - glBindTexture(target, m_texture); -#ifndef QT_OPENGL_ES - glGetTexImage(target, 0, format, GL_UNSIGNED_BYTE, img.bits()); -#else - // XXX - cannot download textures this way on OpenGL/ES. -#endif +static QVector textureBufferStack; +static int currentTextureBuffer = 0; - qt_gl_convertFromGLImage(&img); +void QGLPixmapData::beginPaint() +{ + if (!isValid()) + return; - return img; + m_renderFbo->bind(); +} + +void QGLPixmapData::endPaint() +{ + if (!isValid()) + return; + + const QGLContext *share_ctx = qt_gl_share_widget()->context(); + QGLShareContextScope ctx(share_ctx); + + ensureCreated(); + + if (!ctx->d_ptr->fbo) + glGenFramebuffersEXT(1, &ctx->d_ptr->fbo); + + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->d_ptr->fbo); + glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + qt_gl_preferredTextureTarget(), m_textureId, 0); + + const int x0 = 0; + const int x1 = m_width; + const int y0 = 0; + const int y1 = m_height; + + glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_renderFbo->handle()); + + glDisable(GL_SCISSOR_TEST); + + glBlitFramebufferEXT(x0, y0, x1, y1, + x0, y0, x1, y1, + GL_COLOR_BUFFER_BIT, + GL_NEAREST); + + m_renderFbo->release(); + + --currentTextureBuffer; + + m_renderFbo = 0; + m_engine = 0; +} + +static TextureBuffer createTextureBuffer(const QSize &size, QGL2PaintEngineEx *engine = 0) +{ + TextureBuffer buffer; + QGLFramebufferObjectFormat fmt; + fmt.setAttachment(QGLFramebufferObject::CombinedDepthStencil); + fmt.setSamples(4); + + buffer.fbo = new QGLFramebufferObject(size, fmt); + buffer.engine = engine ? engine : new QGL2PaintEngineEx; + + return buffer; +} + +bool QGLPixmapData::useFramebufferObjects() +{ + return QGLFramebufferObject::hasOpenGLFramebufferObjects() + && QGLFramebufferObject::hasOpenGLFramebufferBlit(); } QPaintEngine* QGLPixmapData::paintEngine() const @@ -276,23 +340,59 @@ QPaintEngine* QGLPixmapData::paintEngine() const if (!isValid()) return 0; - m_source = toImage(); - m_dirty = true; + if (m_engine) + return m_engine; + else if (!useFramebufferObjects()) { + m_dirty = true; + + if (m_source.size() != size()) + m_source = QImage(size(), QImage::Format_ARGB32_Premultiplied); + return m_source.paintEngine(); + } - return m_source.paintEngine(); + extern QGLWidget* qt_gl_share_widget(); + + if (!QGLContext::currentContext()) + qt_gl_share_widget()->makeCurrent(); + QGLShareContextScope ctx(qt_gl_share_widget()->context()); + + if (textureBufferStack.size() <= currentTextureBuffer) { + textureBufferStack << createTextureBuffer(size()); + } else { + QSize sz = textureBufferStack.at(currentTextureBuffer).fbo->size(); + if (sz.width() < m_width || sz.height() < m_height) { + if (sz.width() < m_width) + sz.setWidth(qMax(m_width, qRound(sz.width() * 1.5))); + if (sz.height() < m_height) + sz.setHeight(qMax(m_height, qRound(sz.height() * 1.5))); + delete textureBufferStack.at(currentTextureBuffer).fbo; + textureBufferStack[currentTextureBuffer] = + createTextureBuffer(sz, textureBufferStack.at(currentTextureBuffer).engine); + qDebug() << "Creating new pixmap texture buffer:" << sz; + } + } + + m_renderFbo = textureBufferStack.at(currentTextureBuffer).fbo; + m_engine = textureBufferStack.at(currentTextureBuffer).engine; + + ++currentTextureBuffer; + + return m_engine; } GLuint QGLPixmapData::bind() const { ensureCreated(); - glBindTexture(qt_gl_preferredTextureTarget(), m_texture); - return m_texture; + + GLuint id = m_textureId; + glBindTexture(qt_gl_preferredTextureTarget(), id); + return id; } GLuint QGLPixmapData::textureId() const { ensureCreated(); - return m_texture; + return m_textureId; } extern int qt_defaultDpiX(); diff --git a/src/opengl/qpixmapdata_gl_p.h b/src/opengl/qpixmapdata_gl_p.h index 97f4959..b1b31f7 100644 --- a/src/opengl/qpixmapdata_gl_p.h +++ b/src/opengl/qpixmapdata_gl_p.h @@ -60,6 +60,7 @@ QT_BEGIN_NAMESPACE class QPaintEngine; +class QGLFramebufferObject; class QGLPixmapData : public QPixmapData { @@ -72,6 +73,7 @@ public: void resize(int width, int height); void fromImage(const QImage &image, Qt::ImageConversionFlags flags); + void copy(const QPixmapData *data, const QRect &rect); bool scroll(int dx, int dy, const QRect &rect); @@ -87,6 +89,17 @@ public: void ensureCreated() const; + bool isUninitialized() const { return m_dirty && m_source.isNull(); } + + QSize size() const { return QSize(m_width, m_height); } + int width() const { return m_width; } + int height() const { return m_height; } + + QGLFramebufferObject *fbo() const; + + void beginPaint(); + void endPaint(); + protected: int metric(QPaintDevice::PaintDeviceMetric metric) const; @@ -94,11 +107,15 @@ private: QGLPixmapData(const QGLPixmapData &other); QGLPixmapData &operator=(const QGLPixmapData &other); + static bool useFramebufferObjects(); + int m_width; int m_height; + mutable QGLFramebufferObject *m_renderFbo; + mutable uint m_textureId; + mutable QPaintEngine *m_engine; mutable QGLContext *m_ctx; - mutable GLuint m_texture; mutable bool m_dirty; mutable QImage m_source; }; diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index c9d23d1..e0078bb 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -100,8 +100,8 @@ QGLGraphicsSystem::QGLGraphicsSystem() int i = 0; int spec[16]; spec[i++] = GLX_RGBA; -#if 0 spec[i++] = GLX_DOUBLEBUFFER; +#if 0 spec[i++] = GLX_DEPTH_SIZE; spec[i++] = 8; spec[i++] = GLX_STENCIL_SIZE; @@ -433,19 +433,35 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & size = parent->size(); } - ctx->makeCurrent(); -#ifdef Q_WS_MAC - ctx->updatePaintDevice(); -#endif - glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); if (d_ptr->fbo && QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit) { - QGLFramebufferObject::blitFramebuffer(0, rect, d_ptr->fbo, rect); - d_ptr->fbo->bind(); + const int h = d_ptr->fbo->height(); + + const int x0 = rect.left(); + const int x1 = rect.left() + rect.width(); + const int y0 = h - (rect.top() + rect.height()); + const int y1 = h - rect.top(); + + glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0); + + glBlitFramebufferEXT(x0, y0, x1, y1, + x0, y0, x1, y1, + GL_COLOR_BUFFER_BIT, + GL_NEAREST); + + glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, d_ptr->fbo->handle()); } else { - if (d_ptr->fbo) + glDisable(GL_DEPTH_TEST); + + if (d_ptr->fbo) { d_ptr->fbo->release(); + } else { + ctx->makeCurrent(); +#ifdef Q_WS_MAC + ctx->updatePaintDevice(); +#endif + } glMatrixMode(GL_MODELVIEW); glLoadIdentity(); -- cgit v0.12 From 33957a2fee921742769e89ce6af348d182d183b2 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 16 Apr 2009 17:57:00 +0200 Subject: Don't seg-fault when the shader prog is in the cache --- src/opengl/gl2paintengineex/qglengineshadermanager.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index ea01604..1253414 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -211,6 +211,7 @@ QGLShaderProgram* QGLEngineShaderManager::simpleProgram() void QGLEngineShaderManager::useCorrectShaderProg() { QGLEngineShaderProg requiredProgram; + requiredProgram.program = 0; // Choose vertex shader main function QGLEngineShaderManager::ShaderName mainVertexShaderName = InvalidShaderName; @@ -375,7 +376,7 @@ void QGLEngineShaderManager::useCorrectShaderProg() && (prog.srcPixelFragShader == requiredProgram.srcPixelFragShader) && (prog.compositionFragShader == requiredProgram.compositionFragShader) ) { - currentShaderProg = requiredProgram.program; + currentShaderProg = prog.program; currentShaderProg->enable(); shaderProgNeedsChanging = false; return; -- cgit v0.12 From fc1e97177f6ff9369fc6b14c66e5d0526741d3e7 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 16 Apr 2009 17:59:49 +0200 Subject: Make fillRect() with a QBrush(Qt::NoBrush) a noop --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index f1918c8..80f0b1d 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -804,6 +804,9 @@ void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush) { Q_D(QGL2PaintEngineEx); + if (brush.style() == Qt::NoBrush) + return; + d->setBrush(&brush); d->fill(path); d->setBrush(&(state()->brush)); // reset back to the state's brush -- cgit v0.12 From b3f0d6e31c6897b1701de28d51980a81fb3e778f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 17 Apr 2009 10:04:08 +0200 Subject: Correctly handle using GL pixmaps that still have an active engine. In the case where a GL pixmap is used when there it still has an active engine we need to ensure that the pixmap has been flushed from the render FBO first. The newly added QGLPixmapData::copyBackFromRenderFbo() handles this. In addition, because several GL 2 paint engines can be active on the same context at the same time, we can't make any assumptions and need to call the newly added QGL2PaintEngineEx::ensureCreated() in the beginning of any state-dependent paint engine function. QGL2PaintEngineEx::ensureCreated() correctly transfers control to the current engine if a different engine is active. Running lance with -pixmap and -graphicssystem opengl works correctly with the GL pixmap backend now. --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 47 +++++++++++++++++++++- .../gl2paintengineex/qpaintengineex_opengl2_p.h | 3 +- src/opengl/qgl.cpp | 6 ++- src/opengl/qpixmapdata_gl.cpp | 43 ++++++++++++++------ src/opengl/qpixmapdata_gl_p.h | 7 +++- 5 files changed, 86 insertions(+), 20 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index fe70020..8bf3182 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -805,6 +805,7 @@ void QGL2PaintEngineEx::fill(const QVectorPath &path, const QBrush &brush) { Q_D(QGL2PaintEngineEx); + ensureActive(); d->setBrush(&brush); d->fill(path); d->setBrush(&(state()->brush)); // reset back to the state's brush @@ -814,6 +815,7 @@ void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen) { Q_D(QGL2PaintEngineEx); + ensureActive(); if (pen.style() == Qt::NoPen) return; @@ -832,7 +834,6 @@ void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen) d->setBrush(&(state()->brush)); } else return QPaintEngineEx::stroke(path, pen); - } void QGL2PaintEngineEx::penChanged() @@ -887,6 +888,7 @@ void QGL2PaintEngineEx::transformChanged() void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, const QRectF & src) { Q_D(QGL2PaintEngineEx); + ensureActive(); d->transferMode(ImageDrawingMode); QGLContext *ctx = d->ctx; @@ -905,6 +907,7 @@ void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const Qt::ImageConversionFlags) { Q_D(QGL2PaintEngineEx); + ensureActive(); d->transferMode(ImageDrawingMode); QGLContext *ctx = d->ctx; @@ -921,6 +924,7 @@ void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem) { Q_D(QGL2PaintEngineEx); + ensureActive(); QOpenGLPaintEngineState *s = state(); const QTextItemInt &ti = static_cast(textItem); @@ -974,6 +978,9 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte const QImage &image = cache->image(); int margin = cache->glyphMargin(); + if (image.isNull()) + return; + ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); @@ -1085,6 +1092,16 @@ bool QGL2PaintEngineEx::end() { Q_D(QGL2PaintEngineEx); QGLContext *ctx = d->ctx; + if (ctx->d_ptr->active_engine != this) { + QGL2PaintEngineEx *engine = static_cast(d->last_engine); + if (engine) { + QGL2PaintEngineExPrivate *p = static_cast(engine->d_ptr); + p->transferMode(DefaultMode); + p->drawable.doneCurrent(); + } + d->drawable.makeCurrent(); + } + glUseProgram(0); d->transferMode(DefaultMode); d->drawable.swapBuffers(); @@ -1106,6 +1123,31 @@ bool QGL2PaintEngineEx::end() return false; } +void QGL2PaintEngineEx::ensureActive() +{ + Q_D(QGL2PaintEngineEx); + QGLContext *ctx = d->ctx; + + if (isActive() && ctx->d_ptr->active_engine != this) { + QGL2PaintEngineEx *engine = static_cast(ctx->d_ptr->active_engine); + if (engine) { + QGL2PaintEngineExPrivate *p = static_cast(engine->d_ptr); + p->transferMode(DefaultMode); + p->drawable.doneCurrent(); + } + d->drawable.makeCurrent(); + + ctx->d_ptr->active_engine = this; + + glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); + + glViewport(0, 0, d->width, d->height); + setState(state()); + d->updateDepthClip(); + } +} + /////////////////////////////////// State/Clipping stolen from QOpenGLPaintEngine ////////////////////////////////////////// @@ -1246,6 +1288,7 @@ void QGL2PaintEngineExPrivate::updateDepthClip() Q_Q(QGL2PaintEngineEx); + q->ensureActive(); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); @@ -1305,7 +1348,7 @@ void QGL2PaintEngineEx::setState(QPainterState *new_state) QOpenGLPaintEngineState *old_state = state(); const bool needsDepthClipUpdate = !old_state || s->clipEnabled != old_state->clipEnabled - || s->clipEnabled && s->clipRegion != old_state->clipRegion; + || (s->clipEnabled && s->clipRegion != old_state->clipRegion); QPaintEngineEx::setState(s); diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index 10e5337..b31f685 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -80,6 +80,8 @@ public: bool begin(QPaintDevice *device); bool end(); + void ensureActive(); + virtual void fill(const QVectorPath &path, const QBrush &brush); virtual void stroke(const QVectorPath &path, const QPen &pen); virtual void clip(const QVectorPath &path, Qt::ClipOperation op); @@ -102,7 +104,6 @@ public: Type type() const { return OpenGL; } - // State stuff is just for clipping and ripped off from QGLPaintEngine void setState(QPainterState *s); QPainterState *createState(QPainterState *orig) const; diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 64048f2..d1cf35d 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -4289,6 +4289,8 @@ void QGLDrawable::swapBuffers() if (widget) { if (widget->autoBufferSwap()) widget->swapBuffers(); + } else if (pixmapData) { + pixmapData->swapBuffers(); } else { glFlush(); } @@ -4297,7 +4299,7 @@ void QGLDrawable::swapBuffers() void QGLDrawable::makeCurrent() { if (pixmapData) - pixmapData->beginPaint(); + pixmapData->makeCurrent(); else if (widget) widget->makeCurrent(); else if (buffer) @@ -4321,7 +4323,7 @@ QGLPixmapData *QGLDrawable::copyOnBegin() const void QGLDrawable::doneCurrent() { if (pixmapData) - pixmapData->endPaint(); + pixmapData->doneCurrent(); else if (fbo && !wasBound) fbo->release(); } diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index 0656880..1c5056d 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -246,13 +246,13 @@ QImage QGLPixmapData::toImage() const return QImage(); if (m_renderFbo) - return m_renderFbo->toImage().copy(0, m_renderFbo->height() - m_height, m_width, m_height); + copyBackFromRenderFbo(true); else if (!m_source.isNull()) return m_source; else if (m_dirty) return QImage(m_width, m_height, QImage::Format_ARGB32_Premultiplied); - - ensureCreated(); + else + ensureCreated(); QGLShareContextScope ctx(qt_gl_share_widget()->context()); extern QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alpha); @@ -269,15 +269,7 @@ struct TextureBuffer static QVector textureBufferStack; static int currentTextureBuffer = 0; -void QGLPixmapData::beginPaint() -{ - if (!isValid()) - return; - - m_renderFbo->bind(); -} - -void QGLPixmapData::endPaint() +void QGLPixmapData::copyBackFromRenderFbo(bool keepCurrentFboBound) const { if (!isValid()) return; @@ -308,6 +300,16 @@ void QGLPixmapData::endPaint() GL_COLOR_BUFFER_BIT, GL_NEAREST); + if (keepCurrentFboBound) + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_ctx->d_ptr->current_fbo); +} + +void QGLPixmapData::swapBuffers() +{ + if (!isValid()) + return; + + copyBackFromRenderFbo(false); m_renderFbo->release(); --currentTextureBuffer; @@ -316,6 +318,18 @@ void QGLPixmapData::endPaint() m_engine = 0; } +void QGLPixmapData::makeCurrent() +{ + if (isValid() && m_renderFbo) + m_renderFbo->bind(); +} + +void QGLPixmapData::doneCurrent() +{ + if (isValid() && m_renderFbo) + m_renderFbo->release(); +} + static TextureBuffer createTextureBuffer(const QSize &size, QGL2PaintEngineEx *engine = 0) { TextureBuffer buffer; @@ -382,7 +396,10 @@ QPaintEngine* QGLPixmapData::paintEngine() const GLuint QGLPixmapData::bind() const { - ensureCreated(); + if (m_renderFbo) + copyBackFromRenderFbo(true); + else + ensureCreated(); GLuint id = m_textureId; glBindTexture(qt_gl_preferredTextureTarget(), id); diff --git a/src/opengl/qpixmapdata_gl_p.h b/src/opengl/qpixmapdata_gl_p.h index b1b31f7..7dda653 100644 --- a/src/opengl/qpixmapdata_gl_p.h +++ b/src/opengl/qpixmapdata_gl_p.h @@ -97,8 +97,9 @@ public: QGLFramebufferObject *fbo() const; - void beginPaint(); - void endPaint(); + void makeCurrent(); + void doneCurrent(); + void swapBuffers(); protected: int metric(QPaintDevice::PaintDeviceMetric metric) const; @@ -107,6 +108,8 @@ private: QGLPixmapData(const QGLPixmapData &other); QGLPixmapData &operator=(const QGLPixmapData &other); + void copyBackFromRenderFbo(bool keepCurrentFboBound) const; + static bool useFramebufferObjects(); int m_width; -- cgit v0.12 From 0b37db60b856fd146727eb621c5447aff09ffc5a Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 17 Apr 2009 11:04:21 +0200 Subject: Fix GLSL warning & possible artifacts with radial gradients MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reviewed-by: Samuel Rødal --- src/opengl/gl2paintengineex/qglengineshadersource_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index 945c56c..3aa1a36 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -215,7 +215,7 @@ static const char* const qglslPositionWithRadialGradientBrushVertexShader = "\ gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ gl_Position.w = invertedHTexCoordsZ; \ A = hTexCoords.xy * invertedHTexCoordsZ; \ - b = 2.0 * fmp * (A.x + A.y); \ + b = 2.0 * dot(A, fmp); \ }"; static const char* const qglslAffinePositionWithRadialGradientBrushVertexShader -- cgit v0.12 From 534f2575a19422cff06e27b46f65c6630da6ee7f Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 17 Apr 2009 11:18:21 +0200 Subject: Add a "shocking pink" shader for rendering into stencil buff If you see shocking pink in the rendering output, it's probably because the "simple" shader is in use but color writes have somehow been enabled. :-) --- .../gl2paintengineex/qglengineshadermanager.cpp | 26 ++++++++++++++++++++-- .../gl2paintengineex/qglengineshadermanager_p.h | 1 + .../gl2paintengineex/qglengineshadersource_p.h | 5 +++++ 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index 1253414..7c165ae 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -111,6 +111,7 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) code[LinearGradientBrushSrcFragmentShader] = qglslLinearGradientBrushSrcFragmentShader; code[RadialGradientBrushSrcFragmentShader] = qglslRadialGradientBrushSrcFragmentShader; code[ConicalGradientBrushSrcFragmentShader] = qglslConicalGradientBrushSrcFragmentShader; + code[ShockingPinkSrcFragmentShader] = qglslShockingPinkSrcFragmentShader; code[MaskFragmentShader] = qglslMaskFragmentShader; code[RgbMaskFragmentShader] = ""; //### @@ -131,12 +132,33 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) #if defined(QT_DEBUG) // Check that all the elements have been filled: for (int i = 0; i < TotalShaderCount; ++i) { - if (qglEngineShaderSourceCode[i] == 0) - qCritical() << "qglEngineShaderSourceCode: Missing shader in element" << i; + if (qglEngineShaderSourceCode[i] == 0) { + int enumIndex = staticMetaObject.indexOfEnumerator("ShaderName"); + QMetaEnum m = staticMetaObject.enumerator(enumIndex); + + qCritical() << "qglEngineShaderSourceCode: Source for" << m.valueToKey(i) + << "(shader" << i << ") missing!"; + } } #endif qglEngineShaderSourceCodePopulated = true; } + + // Compile up the simple shader: + simpleShaderProg = new QGLShaderProgram(ctx, this); + compileNamedShader(MainVertexShader, QGLShader::PartialVertexShader); + compileNamedShader(PositionOnlyVertexShader, QGLShader::PartialVertexShader); + compileNamedShader(MainFragmentShader, QGLShader::PartialFragmentShader); + compileNamedShader(ShockingPinkSrcFragmentShader, QGLShader::PartialFragmentShader); + simpleShaderProg->addShader(compiledShaders[MainVertexShader]); + simpleShaderProg->addShader(compiledShaders[PositionOnlyVertexShader]); + simpleShaderProg->addShader(compiledShaders[MainFragmentShader]); + simpleShaderProg->addShader(compiledShaders[ShockingPinkSrcFragmentShader]); + simpleShaderProg->link(); + if (!simpleShaderProg->isValid()) { + qCritical() << "Errors linking simple shader:" + << simpleShaderProg->errors(); + } } QGLEngineShaderManager::~QGLEngineShaderManager() diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index 38c1cff..61a62dc 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -317,6 +317,7 @@ public: LinearGradientBrushSrcFragmentShader, RadialGradientBrushSrcFragmentShader, ConicalGradientBrushSrcFragmentShader, + ShockingPinkSrcFragmentShader, MaskFragmentShader, RgbMaskFragmentShader, diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index 3aa1a36..d605b01 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -288,6 +288,11 @@ static const char* const qglslNonPremultipliedImageSrcFragmentShader = "\ return sample; \ }"; +static const char* const qglslShockingPinkSrcFragmentShader = "\ + lowp vec4 srcPixel() { \ + return lowp vec4(0.98, 0.06, 0.75, 1.0); \ + }"; + static const char* const qglslMainFragmentShader_CMO = "\ uniform lowp float globalOpacity; \ -- cgit v0.12 From 4701bc6fa8fe47d5038ed0a86a4e6c0490c259fe Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 17 Apr 2009 12:00:08 +0200 Subject: Fix various issues with conical grad GLSL code - atan2 is just called atan in GLSL (which supports overloads) - varyings can't be modified in fragment shaders - #defines need to be on their own line --- src/opengl/gl2paintengineex/qglengineshadersource_p.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index d605b01..7557431 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -183,15 +183,17 @@ static const char* const qglslPositionWithConicalGradientBrushVertexShader = "\ static const char* const qglslAffinePositionWithConicalGradientBrushVertexShader = qglslPositionWithConicalGradientBrushVertexShader; -static const char* const qglslConicalGradientBrushSrcFragmentShader = "\ +static const char* const qglslConicalGradientBrushSrcFragmentShader = "\n\ #define INVERSE_2PI 0.1591549430918953358 \n\ - uniform sampler2D brushTexture; \ + uniform sampler2D brushTexture; \n\ uniform mediump float angle; \ varying highp vec2 A; \ lowp vec4 srcPixel() { \ + highp float t; \ if (abs(A.y) == abs(A.x)) \ - A.y += 0.002; \ - highp float t = (atan2(-A.y, A.x) + angle) * INVERSE_2PI; \ + t = (atan(-A.y + 0.002, A.x) + angle) * INVERSE_2PI; \ + else \ + t = (atan(-A.y, A.x) + angle) * INVERSE_2PI; \ return texture2D(brushTexture, vec2(t - floor(t), 0.5)); \ }"; -- cgit v0.12 From 8027a669e31d2fc96f9ffdfc0771034571dd583e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 17 Apr 2009 12:33:52 +0200 Subject: Smudgy text in GL2 paint engine when drawing on non-integer offsets. Special-case TextDrawingMode in updateMatrix() as we know that we'll have a pure translating transform, and round the transform's dx and dy to avoid drawing on non-integer offsets. Task-number: 245806 Reviewed-by: Tom --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 60 ++++++++++++++-------- 1 file changed, 39 insertions(+), 21 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 8bf3182..19163a8 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -412,32 +412,45 @@ void QGL2PaintEngineExPrivate::updateMatrix() {0.0, 0.0, 0.0, 1.0} }; - // Use the (3x3) transform for the Model~View matrix: const QTransform& transform = q->state()->matrix; - GLfloat MV[4][4] = { - {transform.m11(), transform.m21(), 0.0, transform.dx()}, - {transform.m12(), transform.m22(), 0.0, transform.dy()}, - {0.0, 0.0, 1.0, 0.0}, - {transform.m13(), transform.m23(), 0.0, transform.m33()} - }; - // NOTE: OpenGL ES works with column-major matrices, so when we multiply the matrices, - // we also transpose them ready for GL. - for (int row = 0; row < 4; ++row) { - for (int col = 0; col < 4; ++col) { - pmvMatrix[col][row] = 0.0; + if (mode == TextDrawingMode) { + // Text drawing mode is only used for non-scaling transforms + for (int row = 0; row < 4; ++row) + for (int col = 0; col < 4; ++col) + pmvMatrix[col][row] = P[row][col]; + + pmvMatrix[3][0] += P[0][0] * qRound(transform.dx()); + pmvMatrix[3][1] += P[1][1] * qRound(transform.dy()); - // P[row][n] is 0.0 for n < row - for (int n = row; n < 4; ++n) - pmvMatrix[col][row] += P[row][n] * MV[n][col]; + inverseScale = 1; + } else { + // Use the (3x3) transform for the Model~View matrix: + GLfloat MV[4][4] = { + {transform.m11(), transform.m21(), 0.0, transform.dx()}, + {transform.m12(), transform.m22(), 0.0, transform.dy()}, + {0.0, 0.0, 1.0, 0.0}, + {transform.m13(), transform.m23(), 0.0, transform.m33()} + }; + + // NOTE: OpenGL ES works with column-major matrices, so when we multiply the matrices, + // we also transpose them ready for GL. + for (int row = 0; row < 4; ++row) { + for (int col = 0; col < 4; ++col) { + pmvMatrix[col][row] = 0.0; + + // P[row][n] is 0.0 for n < row + for (int n = row; n < 4; ++n) + pmvMatrix[col][row] += P[row][n] * MV[n][col]; + } } - } - // 1/10000 == 0.0001, so we have good enough res to cover curves - // that span the entire widget... - inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())), - qMax(qAbs(transform.m12()), qAbs(transform.m21())) ), - qreal(0.0001)); + // 1/10000 == 0.0001, so we have good enough res to cover curves + // that span the entire widget... + inverseScale = qMax(1 / qMax( qMax(qAbs(transform.m11()), qAbs(transform.m22())), + qMax(qAbs(transform.m12()), qAbs(transform.m21())) ), + qreal(0.0001)); + } matrixDirty = false; @@ -554,6 +567,9 @@ void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) glDisableVertexAttribArray(QT_VERTEX_COORDS_ATTR); } + if (mode == TextDrawingMode) + matrixDirty = true; + if (newMode == TextDrawingMode) { glEnable(GL_BLEND); glActiveTexture(QT_BRUSH_TEXTURE_UNIT); @@ -566,6 +582,8 @@ void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) shaderManager->textShader()->use(); shaderManager->textShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; + + matrixDirty = true; } if (newMode == ImageDrawingMode) { -- cgit v0.12 From 4b4d4b3d7ae4ad019963d957831c46daacba62f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Mon, 20 Apr 2009 12:23:48 +0200 Subject: Prevent copy back from FBO when initializing render FBO from texture. --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 2 +- src/opengl/qpixmapdata_gl.cpp | 6 +++--- src/opengl/qpixmapdata_gl_p.h | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 19163a8..d0f0ad6 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1094,7 +1094,7 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) if (source) { d->transferMode(ImageDrawingMode); - source->bind(); + source->bind(false); glDisable(GL_BLEND); diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index 1c5056d..1fa5b47 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -301,7 +301,7 @@ void QGLPixmapData::copyBackFromRenderFbo(bool keepCurrentFboBound) const GL_NEAREST); if (keepCurrentFboBound) - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, m_ctx->d_ptr->current_fbo); + glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); } void QGLPixmapData::swapBuffers() @@ -394,9 +394,9 @@ QPaintEngine* QGLPixmapData::paintEngine() const return m_engine; } -GLuint QGLPixmapData::bind() const +GLuint QGLPixmapData::bind(bool copyBack) const { - if (m_renderFbo) + if (m_renderFbo && copyBack) copyBackFromRenderFbo(true); else ensureCreated(); diff --git a/src/opengl/qpixmapdata_gl_p.h b/src/opengl/qpixmapdata_gl_p.h index 7dda653..536f33d 100644 --- a/src/opengl/qpixmapdata_gl_p.h +++ b/src/opengl/qpixmapdata_gl_p.h @@ -82,7 +82,7 @@ public: QImage toImage() const; QPaintEngine* paintEngine() const; - GLuint bind() const; + GLuint bind(bool copyBack = true) const; GLuint textureId() const; bool isValidContext(const QGLContext *ctx) const; -- cgit v0.12 From 0c7348cbc5fbbd06ff6752d98e5a6506b8cb5ffa Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Mon, 20 Apr 2009 13:46:42 +0200 Subject: Refactor opacity handling & make drawImage/drawPixmap work again --- .../gl2paintengineex/qglengineshadermanager.cpp | 8 +- .../gl2paintengineex/qglengineshadermanager_p.h | 9 +- .../gl2paintengineex/qglengineshadersource_p.h | 28 ++--- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 139 ++++++++++----------- 4 files changed, 96 insertions(+), 88 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index 7c165ae..15d4a9d 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -248,7 +248,7 @@ void QGLEngineShaderManager::useCorrectShaderProg() // varyings) and the source pixel (srcPixel) fragment shader function: QGLEngineShaderManager::ShaderName positionVertexShaderName = InvalidShaderName; QGLEngineShaderManager::ShaderName srcPixelFragShaderName = InvalidShaderName; - bool isAffine = transform.isAffine(); + bool isAffine = brushTransform.isAffine(); if ( (srcPixelType >= Qt::Dense1Pattern) && (srcPixelType <= Qt::DiagCrossPattern) ) { if (isAffine) positionVertexShaderName = AffinePositionWithPatternBrushVertexShader; @@ -413,6 +413,12 @@ void QGLEngineShaderManager::useCorrectShaderProg() requiredProgram.program->addShader(requiredProgram.srcPixelFragShader); requiredProgram.program->addShader(requiredProgram.maskFragShader); requiredProgram.program->addShader(requiredProgram.compositionFragShader); + + // We have to bind the vertex attribute names before the program is linked: + requiredProgram.program->bindAttributeLocation("inputVertex", QT_VERTEX_COORDS_ATTR); + if (useTextureCoords) + requiredProgram.program->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR); + requiredProgram.program->link(); if (!requiredProgram.program->isValid()) { QString error; diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index 61a62dc..8fb0d5b 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -253,6 +253,9 @@ struct QGLEngineCachedShaderProg } */ +static const GLuint QT_VERTEX_COORDS_ATTR = 0; +static const GLuint QT_TEXTURE_COORDS_ATTR = 1; + class QGLEngineShaderManager : public QObject { Q_OBJECT; @@ -266,9 +269,9 @@ public: NonPremultipliedImageSrc = Qt::TexturePattern+2 }; - // There are optimisations we can do, depending on the transform: + // There are optimisations we can do, depending on the brush transform: // 1) May not have to apply perspective-correction - // 2) Can use lower precision for vertecies + // 2) Can use lower precision for matrix void optimiseForBrushTransform(const QTransform transform); void setSrcPixelType(Qt::BrushStyle); void setSrcPixelType(PixelSrcType); // For non-brush sources, like pixmaps & images @@ -360,7 +363,7 @@ private: bool shaderProgNeedsChanging; // Current state variables which influence the choice of shader: - QTransform transform; + QTransform brushTransform; int srcPixelType; bool useGlobalOpacity; MaskType maskType; diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index 7557431..2c284cb 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -79,13 +79,13 @@ static const char* const qglslMainVertexShader = "\ }"; static const char* const qglslMainWithTexCoordsVertexShader = "\ - attribute lowp vec2 textureCoord; \ - varying lowp vec2 fragTextureCoord; \ + attribute lowp vec2 textureCoordArray; \ + varying lowp vec2 textureCoords; \ void setPosition();\ void main(void) \ {\ setPosition();\ - fragTextureCoord = textureCoord; \ + textureCoords = textureCoordArray; \ }"; @@ -243,7 +243,7 @@ static const char* const qglslPositionWithTextureBrushVertexShader = "\ uniform mediump vec2 halfViewportSize; \ uniform mediump vec2 invertedTextureSize; \ uniform mediump mat3 brushTransform; \ - varying mediump vec2 textureTexCoords; \ + varying mediump vec2 brushTextureCoords; \ void setPosition(void) { \ gl_Position = pmvMatrix * inputVertex;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ @@ -252,18 +252,18 @@ static const char* const qglslPositionWithTextureBrushVertexShader = "\ mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ gl_Position.xy = gl_Position.xy * invertedHTexCoordsZ; \ gl_Position.w = invertedHTexCoordsZ; \ - textureTexCoords.xy = (hTexCoords.xy * invertedTextureSize) * gl_Position.w; \ - textureTexCoords.y = -textureTexCoords.y; \ + brushTextureCoords.xy = (hTexCoords.xy * invertedTextureSize) * gl_Position.w; \ + brushTextureCoords.y = -brushTextureCoords.y; \ }"; static const char* const qglslAffinePositionWithTextureBrushVertexShader = qglslPositionWithTextureBrushVertexShader; static const char* const qglslTextureBrushSrcFragmentShader = "\ - varying mediump vec2 textureTexCoords; \ + varying mediump vec2 brushTextureCoords; \ uniform sampler2D brushTexture; \ lowp vec4 srcPixel() { \ - return texture2D(brushTexture, textureTexCoords); \ + return texture2D(brushTexture, brushTextureCoords); \ }"; @@ -275,17 +275,17 @@ static const char* const qglslSolidBrushSrcFragmentShader = "\ }"; static const char* const qglslImageSrcFragmentShader = "\ - varying highp vec2 texCoord; \ - uniform sampler2D textureSampler; \ + varying highp vec2 textureCoords; \ + uniform sampler2D imageTexture; \ lowp vec4 srcPixel() { \ - return texture2D(textureSampler, texCoord); \ + return texture2D(imageTexture, textureCoords); \ }"; static const char* const qglslNonPremultipliedImageSrcFragmentShader = "\ - varying highp vec2 texCoord; \ - uniform sampler2D textureSampler; \ + varying highp vec2 textureCoords; \ + uniform sampler2D imageTexture; \ lowp vec4 srcPixel() { \ - lowp vec4 sample = texture2D(textureSampler, texCoord); \ + lowp vec4 sample = texture2D(imageTexture, textureCoords); \ sample.rgb = sample.rgb * sample.a; \ return sample; \ }"; diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 80f0b1d..c5ed6cc 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -89,12 +89,13 @@ extern QImage qt_imageForBrush(int brushStyle, bool invert); //in qbrush.cpp enum EngineMode { ImageDrawingMode, TextDrawingMode, - DefaultMode + BrushDrawingMode }; -static const GLuint QT_VERTEX_COORDS_ATTR = 0; -static const GLuint QT_TEXTURE_COORDS_ATTR = 1; -static const GLuint QT_BRUSH_TEXTURE_UNIT = 0; +static const GLuint QT_BRUSH_TEXTURE_UNIT = 0; +static const GLuint QT_IMAGE_TEXTURE_UNIT = 0; //Can be the same as brush texture unit +static const GLuint QT_MASK_TEXTURE_UNIT = 1; +static const GLuint QT_BACKGROUND_TEXTURE_UNIT = 2; class QGL2PaintEngineExPrivate : public QPaintEngineExPrivate { @@ -135,7 +136,7 @@ public: // ^ Calls drawVertexArrays to render into stencil buffer void cleanStencilBuffer(const QGLRect& area); - void prepareForDraw(); + void prepareForDraw(bool srcPixelsAreOpaque); inline void useSimpleShader(); inline QColor premultiplyColor(QColor c, GLfloat opacity); @@ -153,9 +154,7 @@ public: bool brushTextureDirty; bool brushUniformsDirty; bool simpleShaderMatrixUniformDirty; - bool brushShaderMatrixUniformDirty; - bool imageShaderMatrixUniformDirty; - bool textShaderMatrixUniformDirty; + bool shaderMatrixUniformDirty; bool stencilBuferDirty; const QBrush* currentBrush; // May not be the state's brush! @@ -190,7 +189,7 @@ QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate() void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform) { - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); + glActiveTexture(QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit? if (smoothPixmapTransform) { glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -270,6 +269,7 @@ void QGL2PaintEngineExPrivate::updateBrushTexture() else updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, true); + glActiveTexture(QT_BRUSH_TEXTURE_UNIT); glBindTexture(GL_TEXTURE_2D, texId); } else if (style == Qt::TexturePattern) { @@ -291,17 +291,11 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() if (style == Qt::NoBrush) return; - GLfloat opacity = 1.0; - if (q->state()->opacity < 0.99f) - opacity = (GLfloat)q->state()->opacity; - bool setOpacity = true; - QTransform brushQTransform = currentBrush->transform(); if (style == Qt::SolidPattern) { - QColor col = premultiplyColor(currentBrush->color(), opacity); + QColor col = premultiplyColor(currentBrush->color(), (GLfloat)q->state()->opacity); shaderManager->currentProgram()->setUniformValue("fragmentColor", col); - setOpacity = false; } else { // All other brushes have a transform and thus need the translation point: @@ -310,10 +304,9 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() if (style <= Qt::DiagCrossPattern) { translationPoint = q->state()->brushOrigin; - QColor col = premultiplyColor(currentBrush->color(), opacity); + QColor col = premultiplyColor(currentBrush->color(), (GLfloat)q->state()->opacity); shaderManager->currentProgram()->setUniformValue("patternColor", col); - setOpacity = false; //So code below doesn't try to set the opacity uniform QVector2D halfViewportSize(width*0.5, height*0.5); shaderManager->currentProgram()->setUniformValue("halfViewportSize", halfViewportSize); @@ -387,9 +380,6 @@ void QGL2PaintEngineExPrivate::updateBrushUniforms() shaderManager->currentProgram()->setUniformValue("brushTransform", inv_matrix); shaderManager->currentProgram()->setUniformValue("brushTexture", QT_BRUSH_TEXTURE_UNIT); - - if (setOpacity) - shaderManager->currentProgram()->setUniformValue("opacity", opacity); } brushUniformsDirty = false; } @@ -439,9 +429,7 @@ void QGL2PaintEngineExPrivate::updateMatrix() // The actual data has been updated so both shader program's uniforms need updating simpleShaderMatrixUniformDirty = true; - brushShaderMatrixUniformDirty = true; - imageShaderMatrixUniformDirty = true; - textShaderMatrixUniformDirty = true; + shaderMatrixUniformDirty = true; } @@ -515,19 +503,13 @@ void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& s // qDebug("QGL2PaintEngineExPrivate::drawImage()"); updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform); - if (compositionModeDirty) - updateCompositionMode(); + // Setup for texture drawing + shaderManager->setSrcPixelType(QGLEngineShaderManager::ImageSrc); + shaderManager->setTextureCoordsEnabled(true); + prepareForDraw(false); // ### + transferMode(ImageDrawingMode); - if (matrixDirty) - updateMatrix(); - - if (imageShaderMatrixUniformDirty) { -// shaderManager->imageShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; - imageShaderMatrixUniformDirty = false; - } - -// if (q->state()->opacity < 0.99f) -// shaderManager->imageShader()->uniforms()[QLatin1String("opacity")] = (GLfloat)q->state()->opacity; + shaderManager->currentProgram()->setUniformValue("imageTexture", QT_IMAGE_TEXTURE_UNIT); GLfloat dx = 1.0 / textureSize.width(); GLfloat dy = 1.0 / textureSize.height(); @@ -552,7 +534,7 @@ void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) if (newMode == TextDrawingMode) { glEnable(GL_BLEND); - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); +// glActiveTexture(QT_BRUSH_TEXTURE_UNIT); glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); @@ -565,28 +547,27 @@ void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) } if (newMode == ImageDrawingMode) { - // We have a shader specifically for drawPixmap/drawImage... -// shaderManager->imageShader()->use(); -// shaderManager->imageShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; -// shaderManager->imageShader()->uniforms()[QLatin1String("opacity")] = (GLfloat)1.0; - glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, staticVertexCoordinateArray); glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, staticTextureCoordinateArray); - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); +// glActiveTexture(QT_BRUSH_TEXTURE_UNIT); } + // If we're switching to BrushDrawingMode, set the source pixel type to match the brush style: + if (newMode == BrushDrawingMode) + shaderManager->setSrcPixelType(currentBrush->style()); + mode = newMode; } void QGL2PaintEngineExPrivate::drawOutline(const QVectorPath& path) { - transferMode(DefaultMode); + transferMode(BrushDrawingMode); -// qDebug("QGL2PaintEngineExPrivate::drawOutline()"); + // Might need to call updateMatrix to re-calculate inverseScale if (matrixDirty) updateMatrix(); @@ -599,7 +580,7 @@ void QGL2PaintEngineExPrivate::drawOutline(const QVectorPath& path) vertexCoordinateArray.stops().last() += 1; } - prepareForDraw(); + prepareForDraw(currentBrush->isOpaque()); drawVertexArrays(vertexCoordinateArray, GL_LINE_STRIP); } @@ -607,24 +588,24 @@ void QGL2PaintEngineExPrivate::drawOutline(const QVectorPath& path) // Assumes everything is configured for the brush you want to use void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) { - transferMode(DefaultMode); + transferMode(BrushDrawingMode); + // Might need to call updateMatrix to re-calculate inverseScale if (matrixDirty) updateMatrix(); const QPointF* const points = reinterpret_cast(path.points()); - // Check to see if there's any hints if (path.shape() == QVectorPath::RectangleHint) { QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y()); - prepareForDraw(); + prepareForDraw(currentBrush->isOpaque()); composite(rect); } else if (path.shape() == QVectorPath::EllipseHint) { vertexCoordinateArray.clear(); vertexCoordinateArray.addPath(path, inverseScale); - prepareForDraw(); + prepareForDraw(currentBrush->isOpaque()); drawVertexArrays(vertexCoordinateArray, GL_TRIANGLE_FAN); } else { @@ -637,7 +618,7 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) // Stencil the brush onto the dest buffer glStencilFunc(GL_NOTEQUAL, 0, 0xFFFF); // Pass if stencil buff value != 0 glEnable(GL_STENCIL_TEST); - prepareForDraw(); + prepareForDraw(currentBrush->isOpaque()); composite(vertexCoordinateArray.boundingRect()); glDisable(GL_STENCIL_TEST); @@ -717,34 +698,55 @@ void QGL2PaintEngineExPrivate::cleanStencilBuffer(const QGLRect& area) glDisable(GL_STENCIL_TEST); } -void QGL2PaintEngineExPrivate::prepareForDraw() +void QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque) { - if (brushTextureDirty) + if (brushTextureDirty && mode != ImageDrawingMode) updateBrushTexture(); if (compositionModeDirty) updateCompositionMode(); + if (matrixDirty) + updateMatrix(); + + const bool stateHasOpacity = q->state()->opacity < 0.99f; + if ( (!srcPixelsAreOpaque || stateHasOpacity) && + q->state()->compositionMode() != QPainter::CompositionMode_Source) + glEnable(GL_BLEND); + else + glDisable(GL_BLEND); + + bool useGlobalOpacityUniform = stateHasOpacity; + if (stateHasOpacity && (mode != ImageDrawingMode)) { + // Using a brush + bool brushIsPattern = (currentBrush->style() >= Qt::Dense1Pattern) && + (currentBrush->style() <= Qt::DiagCrossPattern); + + if ((currentBrush->style() == Qt::SolidPattern) || brushIsPattern) + useGlobalOpacityUniform = false; // Global opacity handled by srcPixel shader + } + shaderManager->setUseGlobalOpacity(useGlobalOpacityUniform); + + + // If the shader program needs changing, we change it and mark all uniforms as dirty if (shaderManager->shaderProgramDirty()) { shaderManager->useCorrectShaderProg(); // The shader program has changed so mark all uniforms as dirty: brushUniformsDirty = true; - brushShaderMatrixUniformDirty = true; + shaderMatrixUniformDirty = true; } - if (brushUniformsDirty) + if (brushUniformsDirty && mode != ImageDrawingMode) updateBrushUniforms(); - if (brushShaderMatrixUniformDirty) { + if (shaderMatrixUniformDirty) { shaderManager->currentProgram()->setUniformValue("pmvMatrix", pmvMatrix); - brushShaderMatrixUniformDirty = false; + shaderMatrixUniformDirty = false; } - if ((q->state()->opacity < 0.99f) || !currentBrush->isOpaque()) - glEnable(GL_BLEND); - else - glDisable(GL_BLEND); + if (useGlobalOpacityUniform) + shaderManager->currentProgram()->setUniformValue("globalOpacity", (GLfloat)q->state()->opacity); } void QGL2PaintEngineExPrivate::composite(const QGLRect& boundingRect) @@ -863,7 +865,6 @@ void QGL2PaintEngineEx::opacityChanged() Q_D(QGL2PaintEngineEx); Q_ASSERT(d->shaderManager); - d->shaderManager->setUseGlobalOpacity(state()->opacity > 0.999); d->brushUniformsDirty = true; } @@ -986,10 +987,10 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte if (matrixDirty) updateMatrix(); - if (textShaderMatrixUniformDirty) { +// if (textShaderMatrixUniformDirty) { // shaderManager->textShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; - textShaderMatrixUniformDirty = false; - } +// textShaderMatrixUniformDirty = false; +// } QColor col = premultiplyColor(s->pen.color(), (GLfloat)s->opacity); // shaderManager->textShader()->uniforms()[QLatin1String("fragmentColor")] = col; @@ -1032,7 +1033,7 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) QSize sz = d->drawable.size(); d->width = sz.width(); d->height = sz.height(); - d->mode = DefaultMode; + d->mode = BrushDrawingMode; qt_resolve_version_1_3_functions(d->ctx); qt_resolve_glsl_extensions(d->ctx); @@ -1067,7 +1068,7 @@ bool QGL2PaintEngineEx::end() Q_D(QGL2PaintEngineEx); QGLContext *ctx = d->ctx; glUseProgram(0); - d->transferMode(DefaultMode); + d->transferMode(BrushDrawingMode); d->drawable.swapBuffers(); d->drawable.doneCurrent(); return false; @@ -1285,9 +1286,7 @@ void QGL2PaintEngineEx::setState(QPainterState *s) d->brushTextureDirty = true; d->brushUniformsDirty = true; d->simpleShaderMatrixUniformDirty = true; - d->brushShaderMatrixUniformDirty = true; - d->imageShaderMatrixUniformDirty = true; - d->textShaderMatrixUniformDirty = true; + d->shaderMatrixUniformDirty = true; } QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const -- cgit v0.12 From b2f319ccdd2b4fda28e3fdb2128be75c97da75ee Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Mon, 20 Apr 2009 13:57:42 +0200 Subject: Kill unused SimpleVertexShader & rename vertex coords array Rename inputVertex -> vertexCoordsArray to be more consistent with other vertex attribute array naming conventions. SimpleVertexShader has also been replaced with a combination of MainVertexShader & PositionOnlyVertexShader, so can be killed. --- .../gl2paintengineex/qglengineshadermanager.cpp | 1 - .../gl2paintengineex/qglengineshadermanager_p.h | 2 -- .../gl2paintengineex/qglengineshadersource_p.h | 32 ++++++++-------------- 3 files changed, 12 insertions(+), 23 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index 15d4a9d..a4d8b77 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -78,7 +78,6 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) const char** code = qglEngineShaderSourceCode; // shortcut - code[SimpleVertexShader] = qglslSimpleVertexShader; code[MainVertexShader] = qglslMainVertexShader; code[MainWithTexCoordsVertexShader] = qglslMainWithTexCoordsVertexShader; diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index 8fb0d5b..dec8f56 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -87,7 +87,6 @@ correction is needed and a simpler vertex shader can be used instead. So there are the following "main" vertex shaders: - qglslSimpleVertexShader qglslMainVertexShader qglslMainWithTexCoordsVertexShader @@ -287,7 +286,6 @@ public: QGLShaderProgram* simpleProgram(); // Used to draw into e.g. stencil buffers enum ShaderName { - SimpleVertexShader, MainVertexShader, MainWithTexCoordsVertexShader, diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index 2c284cb..2da993a 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -63,14 +63,6 @@ QT_BEGIN_NAMESPACE QT_MODULE(OpenGL) -static const char* const qglslSimpleVertexShader = "\ - attribute highp vec4 inputVertex;\ - uniform highp mat4 pmvMatrix;\ - void main(void)\ - {\ - gl_Position = pmvMatrix * inputVertex;\ - }"; - static const char* const qglslMainVertexShader = "\ void setPosition();\ void main(void)\ @@ -90,24 +82,24 @@ static const char* const qglslMainWithTexCoordsVertexShader = "\ static const char* const qglslPositionOnlyVertexShader = "\ - attribute highp vec4 inputVertex;\ + attribute highp vec4 vertexCoordsArray;\ uniform highp mat4 pmvMatrix;\ void setPosition(void)\ {\ - gl_Position = pmvMatrix * inputVertex;\ + gl_Position = pmvMatrix * vertexCoordsArray;\ }"; // Pattern Brush - This assumes the texture size is 8x8 and thus, the inverted size is 0.125 static const char* const qglslPositionWithPatternBrushVertexShader = "\ - attribute highp vec4 inputVertex; \ + attribute highp vec4 vertexCoordsArray; \ uniform highp mat4 pmvMatrix; \ uniform mediump vec2 halfViewportSize; \ uniform mediump vec2 invertedTextureSize; \ uniform mediump mat3 brushTransform; \ varying mediump vec2 patternTexCoords; \ void setPosition(void) { \ - gl_Position = pmvMatrix * inputVertex;\ + gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ @@ -132,14 +124,14 @@ static const char* const qglslPatternBrushSrcFragmentShader = "\ // Linear Gradient Brush static const char* const qglslPositionWithLinearGradientBrushVertexShader = "\ - attribute highp vec4 inputVertex; \ + attribute highp vec4 vertexCoordsArray; \ uniform highp mat4 pmvMatrix; \ uniform mediump vec2 halfViewportSize; \ uniform highp vec3 linearData; \ uniform highp mat3 brushTransform; \ varying mediump float index ; \ void setPosition() { \ - gl_Position = pmvMatrix * inputVertex;\ + gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ @@ -163,14 +155,14 @@ static const char* const qglslLinearGradientBrushSrcFragmentShader = "\ // Conical Gradient Brush static const char* const qglslPositionWithConicalGradientBrushVertexShader = "\ - attribute highp vec4 inputVertex;\ + attribute highp vec4 vertexCoordsArray;\ uniform highp mat4 pmvMatrix;\ uniform mediump vec2 halfViewportSize; \ uniform highp mat3 brushTransform; \ varying highp vec2 A; \ void setPosition(void)\ {\ - gl_Position = pmvMatrix * inputVertex;\ + gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ @@ -200,7 +192,7 @@ static const char* const qglslConicalGradientBrushSrcFragmentShader = "\n\ // Radial Gradient Brush static const char* const qglslPositionWithRadialGradientBrushVertexShader = "\ - attribute highp vec4 inputVertex;\ + attribute highp vec4 vertexCoordsArray;\ uniform highp mat4 pmvMatrix;\ uniform mediump vec2 halfViewportSize; \ uniform highp mat3 brushTransform; \ @@ -209,7 +201,7 @@ static const char* const qglslPositionWithRadialGradientBrushVertexShader = "\ varying highp vec2 A; \ void setPosition(void) \ {\ - gl_Position = pmvMatrix * inputVertex;\ + gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ @@ -238,14 +230,14 @@ static const char* const qglslRadialGradientBrushSrcFragmentShader = "\ // Texture Brush static const char* const qglslPositionWithTextureBrushVertexShader = "\ - attribute highp vec4 inputVertex; \ + attribute highp vec4 vertexCoordsArray; \ uniform highp mat4 pmvMatrix; \ uniform mediump vec2 halfViewportSize; \ uniform mediump vec2 invertedTextureSize; \ uniform mediump mat3 brushTransform; \ varying mediump vec2 brushTextureCoords; \ void setPosition(void) { \ - gl_Position = pmvMatrix * inputVertex;\ + gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ -- cgit v0.12 From 756d1f3f3b3f1c6c42e0e1afa4f090a6b2e18199 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 21 Apr 2009 15:37:47 +0200 Subject: Make text rendering work again on the GL2 engine - But now it can handle non-solid-color pens, the whole reason for the refactor in the first place. --- .../gl2paintengineex/qglengineshadersource_p.h | 9 +-- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 85 +++++++++++----------- 2 files changed, 48 insertions(+), 46 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index 2da993a..f2facac 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -348,14 +348,13 @@ static const char* const qglslMainFragmentShader = "\ gl_FragColor = srcPixel(); \ }"; - static const char* const qglslMaskFragmentShader = "\ - varying highp vec2 texCoord;\ - uniform sampler2D maskTextureSampler;\ + varying highp vec2 textureCoords;\ + uniform sampler2D maskTexture;\ lowp vec4 applyMask(lowp vec4 src) \ {\ - lowp vec4 mask = texture2D(maskTextureSampler, texCoord); \ - return src * mask.a; \ + lowp vec4 mask = texture2D(maskTexture, textureCoords); \ + return src * mask.r; \ }"; /* diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index c5ed6cc..63cdd87 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -122,11 +122,11 @@ public: void transferMode(EngineMode newMode); - void drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize); - void drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti); - + // fill, drawOutline, drawTexture & drawCachedGlyphs are the rendering entry points: void fill(const QVectorPath &path); void drawOutline(const QVectorPath& path); + void drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize); + void drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti); void drawVertexArrays(QGL2PEXVertexArray& vertexArray, GLenum primitive); // ^ draws whatever is in the vertex array @@ -189,7 +189,7 @@ QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate() void QGL2PaintEngineExPrivate::updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform) { - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit? +// glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); //### Is it always this texture unit? if (smoothPixmapTransform) { glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_LINEAR); @@ -249,7 +249,7 @@ void QGL2PaintEngineExPrivate::updateBrushTexture() // Get the image data for the pattern QImage texImage = qt_imageForBrush(style, true); - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); + glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); ctx->d_func()->bindTexture(texImage, GL_TEXTURE_2D, GL_RGBA, true); updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, true); } @@ -269,13 +269,13 @@ void QGL2PaintEngineExPrivate::updateBrushTexture() else updateTextureFilter(GL_TEXTURE_2D, GL_CLAMP_TO_EDGE, true); - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); + glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); glBindTexture(GL_TEXTURE_2D, texId); } else if (style == Qt::TexturePattern) { const QPixmap& texPixmap = currentBrush->texture(); - glActiveTexture(QT_BRUSH_TEXTURE_UNIT); + glActiveTexture(GL_TEXTURE0 + QT_BRUSH_TEXTURE_UNIT); ctx->d_func()->bindTexture(texPixmap, GL_TEXTURE_2D, GL_RGBA, true); updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, true); } @@ -500,14 +500,14 @@ static inline void setCoords(GLfloat *coords, const QGLRect &rect) void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize) { -// qDebug("QGL2PaintEngineExPrivate::drawImage()"); + transferMode(ImageDrawingMode); + updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, q->state()->renderHints & QPainter::SmoothPixmapTransform); // Setup for texture drawing shaderManager->setSrcPixelType(QGLEngineShaderManager::ImageSrc); shaderManager->setTextureCoordsEnabled(true); prepareForDraw(false); // ### - transferMode(ImageDrawingMode); shaderManager->currentProgram()->setUniformValue("imageTexture", QT_IMAGE_TEXTURE_UNIT); @@ -533,17 +533,11 @@ void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) } if (newMode == TextDrawingMode) { - glEnable(GL_BLEND); -// glActiveTexture(QT_BRUSH_TEXTURE_UNIT); - glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray.data()); glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray.data()); - -// shaderManager->textShader()->use(); -// shaderManager->textShader()->uniforms()[QLatin1String("textureSampler")] = QT_BRUSH_TEXTURE_UNIT; } if (newMode == ImageDrawingMode) { @@ -552,14 +546,16 @@ void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, staticVertexCoordinateArray); glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, staticTextureCoordinateArray); - -// glActiveTexture(QT_BRUSH_TEXTURE_UNIT); } // If we're switching to BrushDrawingMode, set the source pixel type to match the brush style: - if (newMode == BrushDrawingMode) + if (newMode == BrushDrawingMode || newMode == TextDrawingMode) shaderManager->setSrcPixelType(currentBrush->style()); + // This needs to change when we implement high-quality anti-aliasing... + if (newMode != TextDrawingMode) + shaderManager->setMaskType(QGLEngineShaderManager::NoMask); + mode = newMode; } @@ -893,6 +889,7 @@ void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, c d->transferMode(ImageDrawingMode); QGLContext *ctx = d->ctx; + glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT); ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, true); //FIXME: we should use hasAlpha() instead, but that's SLOW at the moment @@ -911,6 +908,7 @@ void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const d->transferMode(ImageDrawingMode); QGLContext *ctx = d->ctx; + glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT); ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); if ((state()->opacity < 0.99f) || image.hasAlphaChannel()) @@ -930,9 +928,6 @@ void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem bool drawCached = true; - if (state()->pen.brush().style() != Qt::SolidPattern) - drawCached = false; - if (s->matrix.type() > QTransform::TxTranslate) drawCached = false; @@ -950,21 +945,33 @@ void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti) { + transferMode(TextDrawingMode); + Q_Q(QGL2PaintEngineEx); QOpenGLPaintEngineState *s = q->state(); - transferMode(TextDrawingMode); - QVarLengthArray positions; QVarLengthArray glyphs; QTransform matrix; matrix.translate(p.x(), p.y()); ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions); + QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat) : QFontEngineGlyphCache::Raster_A8; + GLenum maskFormat = GL_RGBA; + if (glyphType == QFontEngineGlyphCache::Raster_A8) { + shaderManager->setMaskType(QGLEngineShaderManager::PixelMask); +// maskFormat = GL_ALPHA; + } + else if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) + shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMask); + //### TODO: Gamma correction + shaderManager->setTextureCoordsEnabled(true); + + QImageTextureGlyphCache *cache = (QImageTextureGlyphCache *) ti.fontEngine->glyphCache(glyphType, s->matrix); if (!cache) { @@ -977,23 +984,6 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte const QImage &image = cache->image(); int margin = cache->glyphMargin(); - ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); - - updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); - - if (compositionModeDirty) - updateCompositionMode(); - - if (matrixDirty) - updateMatrix(); - -// if (textShaderMatrixUniformDirty) { -// shaderManager->textShader()->uniforms()[QLatin1String("pmvMatrix")] = pmvMatrix; -// textShaderMatrixUniformDirty = false; -// } - - QColor col = premultiplyColor(s->pen.color(), (GLfloat)s->opacity); -// shaderManager->textShader()->uniforms()[QLatin1String("fragmentColor")] = col; GLfloat dx = 1.0 / image.width(); GLfloat dy = 1.0 / image.height(); @@ -1013,12 +1003,26 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte textureCoordinateArray.addRect(QRectF(c.x*dx, 1 - c.y*dy, c.w * dx, -c.h * dy)); } + + glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT); + ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); + updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); + + QBrush pensBrush = q->state()->pen.brush(); + setBrush(&pensBrush); + + prepareForDraw(false); // Text always causes src pixels to be transparent + + shaderManager->currentProgram()->setUniformValue("maskTexture", QT_MASK_TEXTURE_UNIT); + if (vertexCoordinateArray.data() != oldVertexCoordinateDataPtr) glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray.data()); if (textureCoordinateArray.data() != oldTextureCoordinateDataPtr) glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray.data()); glDrawArrays(GL_TRIANGLES, 0, 6 * glyphs.size()); + + setBrush(&(q->state()->brush)); //### } bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) @@ -1068,7 +1072,6 @@ bool QGL2PaintEngineEx::end() Q_D(QGL2PaintEngineEx); QGLContext *ctx = d->ctx; glUseProgram(0); - d->transferMode(BrushDrawingMode); d->drawable.swapBuffers(); d->drawable.doneCurrent(); return false; -- cgit v0.12 From aa295fbfdae1a687bc7bd9f7f364721a35566828 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 22 Apr 2009 17:25:36 +0200 Subject: Change fragment shaders to apply the mask as the final step I.e. After composition, not before. --- src/opengl/gl2paintengineex/qglengineshadersource_p.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index f2facac..bf896b1 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -294,7 +294,7 @@ static const char* const qglslMainFragmentShader_CMO = "\ lowp vec4 applyMask(lowp vec4); \ lowp vec4 compose(lowp vec4); \ void main() { \ - gl_FragColor = compose(applyMask(srcPixel()*globalOpacity)); \ + gl_FragColor = applyMask(compose(srcPixel()*globalOpacity))); \ }"; static const char* const qglslMainFragmentShader_CM = "\ @@ -302,7 +302,7 @@ static const char* const qglslMainFragmentShader_CM = "\ lowp vec4 applyMask(lowp vec4); \ lowp vec4 compose(lowp vec4); \ void main() { \ - gl_FragColor = compose(applyMask(srcPixel())); \ + gl_FragColor = applyMask(compose(srcPixel())); \ }"; static const char* const qglslMainFragmentShader_MO = "\ -- cgit v0.12 From 0df382c78aeaf74c161d753f04ae9a13e951c0a1 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 22 Apr 2009 17:35:26 +0200 Subject: Make optimiseForBrushTransform take a QTransform reference --- src/opengl/gl2paintengineex/qglengineshadermanager.cpp | 2 +- src/opengl/gl2paintengineex/qglengineshadermanager_p.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index a4d8b77..6e702e5 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -169,7 +169,7 @@ QGLEngineShaderManager::~QGLEngineShaderManager() -void QGLEngineShaderManager::optimiseForBrushTransform(const QTransform transform) +void QGLEngineShaderManager::optimiseForBrushTransform(const QTransform &transform) { Q_UNUSED(transform); // Currently ignored } diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index dec8f56..d3856fe 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -271,7 +271,7 @@ public: // There are optimisations we can do, depending on the brush transform: // 1) May not have to apply perspective-correction // 2) Can use lower precision for matrix - void optimiseForBrushTransform(const QTransform transform); + void optimiseForBrushTransform(const QTransform &transform); void setSrcPixelType(Qt::BrushStyle); void setSrcPixelType(PixelSrcType); // For non-brush sources, like pixmaps & images void setTextureCoordsEnabled(bool); // For images & text glyphs -- cgit v0.12 From 873aa5cb7542497dd4e98bcc145b479f32343b5e Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 22 Apr 2009 17:38:02 +0200 Subject: Make useCorrectShaderProg() return a bool again Returns true if it had to change the shader program so the engine knows it needs to clean the uniforms. --- src/opengl/gl2paintengineex/qglengineshadermanager.cpp | 16 ++++++++-------- src/opengl/gl2paintengineex/qglengineshadermanager_p.h | 3 +-- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 4 +--- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index 6e702e5..3d8d34b 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -210,11 +210,6 @@ void QGLEngineShaderManager::setCompositionMode(QPainter::CompositionMode mode) shaderProgNeedsChanging = true; //### } -bool QGLEngineShaderManager::shaderProgramDirty() -{ - return shaderProgNeedsChanging; -} - QGLShaderProgram* QGLEngineShaderManager::currentProgram() { return currentShaderProg; @@ -228,9 +223,13 @@ QGLShaderProgram* QGLEngineShaderManager::simpleProgram() -// Select & use the correct shader program using the current state -void QGLEngineShaderManager::useCorrectShaderProg() +// Select & use the correct shader program using the current state. +// Returns true if program needed changing. +bool QGLEngineShaderManager::useCorrectShaderProg() { + if (!shaderProgNeedsChanging) + return false; + QGLEngineShaderProg requiredProgram; requiredProgram.program = 0; @@ -400,7 +399,7 @@ void QGLEngineShaderManager::useCorrectShaderProg() currentShaderProg = prog.program; currentShaderProg->enable(); shaderProgNeedsChanging = false; - return; + return true; } } @@ -442,6 +441,7 @@ void QGLEngineShaderManager::useCorrectShaderProg() currentShaderProg->enable(); } shaderProgNeedsChanging = false; + return true; } void QGLEngineShaderManager::compileNamedShader(QGLEngineShaderManager::ShaderName name, QGLShader::ShaderType type) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index d3856fe..e9e261f 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -279,8 +279,7 @@ public: void setMaskType(MaskType); void setCompositionMode(QPainter::CompositionMode); - bool shaderProgramDirty(); // returns true if the shader program needs to be changed - void useCorrectShaderProg(); + bool useCorrectShaderProg(); // returns true if the shader program needed to be changed QGLShaderProgram* currentProgram(); // Returns pointer to the shader the manager has chosen QGLShaderProgram* simpleProgram(); // Used to draw into e.g. stencil buffers diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 5a701aa..7dbdc32 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -741,9 +741,7 @@ void QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque) // If the shader program needs changing, we change it and mark all uniforms as dirty - if (shaderManager->shaderProgramDirty()) { - shaderManager->useCorrectShaderProg(); - + if (shaderManager->useCorrectShaderProg()) { // The shader program has changed so mark all uniforms as dirty: brushUniformsDirty = true; shaderMatrixUniformDirty = true; -- cgit v0.12 From 6e0e3c7312bbceef69e61b745d88076224745a33 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 22 Apr 2009 17:39:55 +0200 Subject: Allow release builds again The list of shaders shouldn't change too much now. --- src/opengl/gl2paintengineex/qglengineshadermanager_p.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index e9e261f..b8b2745 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -350,8 +350,6 @@ public: #if defined (QT_DEBUG) Q_ENUMS(ShaderName); -#else -#error Release build not supported yet #endif -- cgit v0.12 From 89aa644baabd8a118a59cb367aca2adf1363564e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 23 Apr 2009 14:06:07 +0200 Subject: Remove old qglshader files from gl2paintengineex. --- src/opengl/gl2paintengineex/qglshader.cpp | 616 ------------------------------ src/opengl/gl2paintengineex/qglshader_p.h | 262 ------------- 2 files changed, 878 deletions(-) delete mode 100644 src/opengl/gl2paintengineex/qglshader.cpp delete mode 100644 src/opengl/gl2paintengineex/qglshader_p.h diff --git a/src/opengl/gl2paintengineex/qglshader.cpp b/src/opengl/gl2paintengineex/qglshader.cpp deleted file mode 100644 index ea4cae9..0000000 --- a/src/opengl/gl2paintengineex/qglshader.cpp +++ /dev/null @@ -1,616 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtOpenGL module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qglshader_p.h" - - -// Windows needs to resolve OpenGL 2.0 function pointers for each context. The -// QGL OpenGL 2.0 functions are actually macros, which take a "ctx" parameter. -#define Q_CTX QGLContext* ctx = d->ctx; \ - if (!ctx) \ - return false; \ - ctx->makeCurrent(); \ - -#if !defined(QT_OPENGL_ES_2) -static const char *qglslDefines = "#define lowp\n#define mediump\n#define highp\n"; -#include "private/qgl_p.h" -#else -static const char *qglslDefines = ""; -#endif - - -class QGLShaderPrivate -{ -public: - QGLShaderPrivate() : shaderId(0), valid(false), ctx(0) {} - - GLuint shaderId; - QString source; - bool valid; - QGLShader::ShaderType type; - QGLContext* ctx; -}; - - -QGLShader::QGLShader(QGLShader::ShaderType type, const QGLContext* ctx) - : d_ptr(new QGLShaderPrivate) -{ - Q_D(QGLShader); - - if (!ctx) - ctx = QGLContext::currentContext(); - - if (!ctx) { - qWarning("QGLShader being created without a context"); - return; - } - - d->ctx = const_cast(ctx); - d->ctx->makeCurrent(); - - if (type == QGLShader::FragmentShader) - d->shaderId = glCreateShader(GL_FRAGMENT_SHADER); - else - d->shaderId = glCreateShader(GL_VERTEX_SHADER); - - if (d->shaderId == 0) { - qWarning("Error creating shader object"); - return; - } - - d->type = type; -} - -GLuint QGLShader::id() -{ - Q_D(QGLShader); - return d->shaderId; -} - -const QGLContext* QGLShader::context() -{ - Q_D(QGLShader); - return d->ctx; -} - -void QGLShader::clearSource() -{ - Q_D(QGLShader); - d->source.clear(); - d->valid = false; -} - -void QGLShader::addSource(const QLatin1String& newSource) -{ - Q_D(QGLShader); - d->source += newSource; - d->valid = false; -} - - -bool QGLShader::compile() -{ - Q_D(QGLShader); - - d->valid = false; - - if (d->source.size() == 0) - return false; - - const QByteArray src_ba = d->source.toAscii(); - const char* src[2]; - src[0] = qglslDefines; - src[1] = src_ba.constData(); - - - QGLContext *ctx = d->ctx; - glShaderSource(d->shaderId, 2, src, 0); - - glCompileShader(d->shaderId); - - GLint shaderCompiled; - glGetShaderiv(d->shaderId, GL_COMPILE_STATUS, &shaderCompiled); - if (!shaderCompiled) - return false; - - d->valid = true; - return true; -} - -bool QGLShader::isValid() -{ - Q_D(QGLShader); - return d->valid; -} - -QString QGLShader::log() -{ - Q_D(QGLShader); - - char* logData; - GLint logSize; - GLint logLength; - - QGLContext *ctx = d->ctx; - glGetShaderiv(d->shaderId, GL_INFO_LOG_LENGTH, &logSize); - - if (!logSize) - return QString(); - - logData = new char[logSize]; - glGetShaderInfoLog(d->shaderId, logSize, &logLength, logData); - QString result = QString::fromAscii(logData); - delete [] logData; - - return result; -} - - - - - - - - - - - - -class QGLShaderProgramPrivate -{ -public: - QGLShaderProgramPrivate() : valid(false), programId(0), ctx(0) {} - void populateVariableLists(); - - QVector shaders; - QGLUniformList uniforms; - QGLVertexAttributeList attributeArrays; - bool valid; - GLuint programId; - QGLContext* ctx; -}; - - - -void QGLShaderProgramPrivate::populateVariableLists() -{ - attributeArrays.clear(); - uniforms.clear(); - - int count; - int sizeOfNameBuff; - char* name; - GLint nameLength; - GLenum type; - GLint size; - GLint location; - - glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTES, &count); - glGetProgramiv(programId, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &sizeOfNameBuff); - name = new char[sizeOfNameBuff]; - - for (int i = 0; i < count; ++i) { - nameLength = -1; - glGetActiveAttrib(programId, i, sizeOfNameBuff, &nameLength, &size, &type, name); - if (nameLength == -1) - continue; - - location = glGetAttribLocation(programId, name); - attributeArrays.insert(QString::fromAscii(name), QGLVertexAttribute(type, location, ctx)); - } - - delete [] name; - - - glGetProgramiv(programId, GL_ACTIVE_UNIFORMS, &count); - glGetProgramiv(programId, GL_ACTIVE_UNIFORM_MAX_LENGTH, &sizeOfNameBuff); - - name = new char[sizeOfNameBuff]; - - for (int i = 0; i < count; ++i) { - nameLength = -1; - glGetActiveUniform(programId, i, sizeOfNameBuff, &nameLength, &size, &type, name); - if (nameLength == -1) - continue; - - location = glGetUniformLocation(programId, name); - uniforms.insert(QString::fromAscii(name), QGLUniform(type, location, ctx)); - } -} - - -QGLShaderProgram::QGLShaderProgram(const QGLContext* ctx) - : d_ptr(new QGLShaderProgramPrivate) -{ - Q_D(QGLShaderProgram); - if (!ctx) - ctx = QGLContext::currentContext(); - - if (!ctx) { - qWarning("QGLShaderProgram being created without a context"); - return; - } - - d->ctx = const_cast(ctx); - d->ctx->makeCurrent(); - - d->programId = glCreateProgram(); - - d->valid = false; -} - - -const QGLUniformList & QGLShaderProgram::uniforms() -{ - Q_D(QGLShaderProgram); - return const_cast(d->uniforms); -} - - -const QGLVertexAttributeList& QGLShaderProgram::vertexAttributes() -{ - Q_D(QGLShaderProgram); - return const_cast(d->attributeArrays); -} - - -bool QGLShaderProgram::addShader(QGLShader* newShader) -{ - Q_D(QGLShaderProgram); - if (!newShader || !d->ctx) - return false; - - if (newShader->context() != d->ctx) { - qWarning("Shader object's context does not match program's context"); - return false; - } - - if (!newShader->isValid()) - return false; - - QGLContext* ctx = d->ctx; - if (!ctx) - return false; - ctx->makeCurrent(); - - glAttachShader(d->programId, newShader->id()); - - d->shaders.append(newShader); - return true; -} - - -bool QGLShaderProgram::removeShader(QGLShader* oldShader) -{ - Q_D(QGLShaderProgram); - - int idx = d->shaders.indexOf(oldShader); - - if (idx == -1) - return false; - - d->shaders.remove(idx); - - QGLContext* ctx = d->ctx; - if (!ctx) - return false; - ctx->makeCurrent(); - - glDetachShader(d->programId, oldShader->id()); - return true; -} - - -bool QGLShaderProgram::removeAllShaders() -{ - Q_D(QGLShaderProgram); - - QGLContext* ctx = d->ctx; - if (!ctx) - return false; - ctx->makeCurrent(); - - foreach (QGLShader* shader, d->shaders) - glDetachShader(d->programId, shader->id()); - - d->shaders.clear(); - return true; -} - -#include - -bool QGLShaderProgram::link() -{ - Q_D(QGLShaderProgram); - - QGLContext* ctx = d->ctx; - if (!ctx) - return false; - ctx->makeCurrent(); - - glLinkProgram(d->programId); - - - GLint linked; - glGetProgramiv(d->programId, GL_LINK_STATUS, &linked); - - if (!linked) - return false; - - d->populateVariableLists(); - - d->valid = true; - return true; -} - -void QGLShaderProgram::use() -{ - Q_D(QGLShaderProgram); - if (!d->valid) - return; - - QGLContext *ctx = d->ctx; - glUseProgram(d->programId); -} - - -QString QGLShaderProgram::log() -{ - Q_D(QGLShaderProgram); - - QGLContext* ctx = d->ctx; - if (!ctx) - return QString(); - ctx->makeCurrent(); - - GLint logSize = -666; - glGetProgramiv(d->programId, GL_INFO_LOG_LENGTH, &logSize); - - char* logData = new char[logSize]; - GLint logLength; - - glGetProgramInfoLog(d->programId, logSize, &logLength, logData); - - QString result = QString::fromAscii(logData); - delete [] logData; - - return result; -} - -GLuint QGLShaderProgram::id() -{ - Q_D(QGLShaderProgram); - return d->programId; -} - -///////////////////////////////////////////////////////////////////////// - - - - -QGLUniform::QGLUniform() - : m_id(0), m_type(QGLInvalidType), ctx(0) -{ - qWarning("Unknown uniform! Either the uniform doesn't exist or it was removed at shader link"); -} - -const QGLUniform& QGLUniform::operator=(const GLfloat& rhs) const -{ - if (m_type != QGLFloatType) - return *this; - - glUniform1f(m_id, rhs); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const QGLVec2& rhs) const -{ - if (m_type != QGLVec2Type) - return *this; - - glUniform2fv(m_id, 1, (const GLfloat*)&rhs); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const QSizeF& rhs) const -{ - if (m_type != QGLVec2Type) - return *this; - - glUniform2f(m_id, rhs.width(), rhs.height()); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const QPointF& rhs) const -{ - if (m_type != QGLVec2Type) - return *this; - - glUniform2f(m_id, rhs.x(), rhs.y()); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const QGLVec3& rhs) const -{ - if (m_type != QGLVec3Type) - return *this; - - glUniform3fv(m_id, 1, (const GLfloat*)&rhs); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const QGLVec4& rhs) const -{ - if (m_type != QGLVec4Type) - return *this; - - glUniform4fv(m_id, 1, (const GLfloat*)&rhs); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const QColor& rhs) const -{ - if (m_type != QGLVec4Type) - return *this; - - glUniform4f(m_id, rhs.redF(), rhs.greenF(), rhs.blueF(), rhs.alphaF()); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const GLfloat rhs[2][2]) const -{ - if (m_type != QGLMat2Type) - return *this; - - glUniformMatrix2fv(m_id, 1, GL_FALSE, (GLfloat*)rhs); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const GLfloat rhs[3][3]) const -{ - if (m_type != QGLMat3Type) - return *this; - - glUniformMatrix3fv(m_id, 1, GL_FALSE, (GLfloat*)rhs); - - return *this; -} - -// Transposes ready for GL -const QGLUniform& QGLUniform::operator=(const QTransform& rhs) const -{ - if (m_type != QGLMat3Type) - return *this; - - GLfloat mat3[3][3] = { - {rhs.m11(), rhs.m12(), rhs.m13()}, - {rhs.m21(), rhs.m22(), rhs.m23()}, - {rhs.m31(), rhs.m32(), rhs.m33()} - }; - - glUniformMatrix3fv(m_id, 1, GL_FALSE, (GLfloat*)mat3); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const GLfloat rhs[4][4]) const -{ - if (m_type != QGLMat4Type) - return *this; - - glUniformMatrix4fv(m_id, 1, GL_FALSE, (GLfloat*)rhs); - - return *this; -} - -const QGLUniform& QGLUniform::operator=(const GLuint& rhs) const -{ - if ((m_type != QGLSampler2DType) || (m_type != QGLSamplerCubeType)) - return *this; - - glUniform1i(m_id, rhs); - - return *this; -} - - - - -///////////////////////////////////////////////////////////////////////// - -QGLVertexAttribute::QGLVertexAttribute() - : m_id(0), m_type(QGLInvalidType), ctx(0) -{ - qWarning("Unknown vertex attribute!"); -} - -void QGLVertexAttribute::enable() const -{ - glEnableVertexAttribArray(m_id); -} - -void QGLVertexAttribute::disable() const -{ - glDisableVertexAttribArray(m_id); -} - -// NOTE: Under PC emulation, QGLVec4Type is _always_ returned as the type, so this -// method isn't very useful. I.e. The datatypes are needed to distinguish the different -// sizes for the function signatures. -const QGLVertexAttribute& QGLVertexAttribute::operator=(const GLfloat* rhs) const -{ - int size = -1; - if (m_type == QGLFloatType) - size = 1; - else if (m_type == QGLVec2Type) - size = 2; - else if (m_type == QGLVec3Type) - size = 3; - else if (m_type == QGLVec4Type) - size = 4; - else if (m_type == QGLMat2Type) //### Not sure if this is right for matrix attributes... - size = 4; - else if (m_type == QGLMat3Type) //### Not sure if this is right for matrix attributes... - size = 9; - else if (m_type == QGLMat4Type) //### Not sure if this is right for matrix attributes... - size = 16; - else - return *this; - - glVertexAttribPointer(m_id, size, GL_FLOAT, GL_FALSE, 0, rhs); - - return *this; -} - -const QGLVertexAttribute& QGLVertexAttribute::operator=(const QGLVec3* rhs) const -{ - glVertexAttribPointer(m_id, 3, GL_FLOAT, GL_FALSE, 0, (GLfloat*)rhs); - - return *this; -} diff --git a/src/opengl/gl2paintengineex/qglshader_p.h b/src/opengl/gl2paintengineex/qglshader_p.h deleted file mode 100644 index 64c9a42..0000000 --- a/src/opengl/gl2paintengineex/qglshader_p.h +++ /dev/null @@ -1,262 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtOpenGL module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -/* -Uniform Types in OpenGL ES 2.0 -============================== -GL_FLOAT GLfloat GLfloat -GL_FLOAT_VEC2 QGLVec2 GLfloat[2] -GL_FLOAT_VEC3 QGLVec3 GLfloat[3] -GL_FLOAT_VEC4 QGLVec4 GLfloat[4] -GL_INT GLint GLint -GL_INT_VEC2 QGLIVec2 GLint[2] -GL_INT_VEC3 QGLIVec3 GLint[3] -GL_INT_VEC4 QGLIVec4 GLint[4] -GL_BOOL GLbool GLbool -GL_BOOL_VEC2 QGLBVec2 GLbool[2] -GL_BOOL_VEC3 QGLBVec3 GLbool[3] -GL_BOOL_VEC4 QGLBVec4 GLbool[4] -GL_FLOAT_MAT2 QGLMat2 GLfloat[2][2] -GL_FLOAT_MAT3 QGLMat3 GLfloat[3][3] -GL_FLOAT_MAT4 QGLMat4 GLfloat[4][4] -GL_SAMPLER_2D QGLSampler2D GLuint -GL_SAMPLER_CUBE QGLSamplerCube GLuint - -Additional Types in Desktop OpenGL 2.0 -====================================== -SAMPLER_1D, -SAMPLER_3D, -SAMPLER_1D_SHADOW, -SAMPLER_2D_SHADOW. -*/ - -#include - -#define QGLShader QGLEngineShader -#define QGLShaderProgram QGLEngineShaderProgram - -typedef struct { - GLfloat a; - GLfloat b; -} QGLVec2; - -typedef struct { - GLfloat a; - GLfloat b; - GLfloat c; -} QGLVec3; - -typedef struct { - GLfloat a; - GLfloat b; - GLfloat c; - GLfloat d; -} QGLVec4; - - -class QGLShaderProgram; - -class QGLShaderPrivate; - -class QGLShader : QObject -{ - Q_OBJECT -public: - enum ShaderType {VertexShader, FragmentShader}; - - QGLShader(ShaderType type, const QGLContext* ctx = 0); - - GLuint id(); - void clearSource(); - void addSource(const QLatin1String& newSource); - bool compile(); - bool isValid(); - QString log(); - const QGLContext* context(); //maybe make private with prog a friend? - -private: - QGLShaderPrivate* d_ptr; - Q_DECLARE_PRIVATE(QGLShader); - -/* -public slots: - void cleanupGLContextRefs(const QGLContext *context); -*/ -}; - - -enum QGLType { - QGLInvalidType = 0, - QGLFloatType = GL_FLOAT, - QGLVec2Type = GL_FLOAT_VEC2, - QGLVec3Type = GL_FLOAT_VEC3, - QGLVec4Type = GL_FLOAT_VEC4, - QGLIntType = GL_INT, - QGLIVec2Type = GL_INT_VEC2, - QGLIVec3Type = GL_INT_VEC3, - QGLIVec4Type = GL_INT_VEC4, - QGLBoolType = GL_BOOL, - QGLBVec2Type = GL_BOOL_VEC2, - QGLBVec3Type = GL_BOOL_VEC3, - QGLBVec4Type = GL_BOOL_VEC4, - QGLMat2Type = GL_FLOAT_MAT2, - QGLMat3Type = GL_FLOAT_MAT3, - QGLMat4Type = GL_FLOAT_MAT4, - QGLSampler2DType = GL_SAMPLER_2D, - QGLSamplerCubeType = GL_SAMPLER_CUBE -}; - -class QGLUniform -{ -public: - - QGLUniform(GLenum glType, GLint location, QGLContext* context) - : m_id(location), m_type(QGLType(glType)), ctx(context) {} - - QGLUniform(); // Called by QMap when there's no match on the name - - QGLType type() const {return m_type;} - GLuint id() const {return m_id;} - - // Seems odd to be const, but it doesn't actually modify any of the - // class members, only the GL state! - const QGLUniform& operator=(const GLfloat&) const; - - const QGLUniform& operator=(const QGLVec2&) const; - const QGLUniform& operator=(const QSizeF&) const; - const QGLUniform& operator=(const QPointF&) const; - - const QGLUniform& operator=(const QGLVec3&) const; - - const QGLUniform& operator=(const QGLVec4&) const; - const QGLUniform& operator=(const QColor&) const; - - const QGLUniform& operator=(const GLfloat[2][2]) const; - - const QGLUniform& operator=(const GLfloat[3][3]) const; - const QGLUniform& operator=(const QTransform&) const; - - const QGLUniform& operator=(const GLfloat[4][4]) const; - - const QGLUniform& operator=(const GLuint&) const; // sampler2d, specifying a texture unit - - -protected: - GLuint m_id; - QGLType m_type; - QGLContext* ctx; -}; - -typedef QMap QGLUniformList; -typedef QMapIterator QGLUniformListIterator; - - -class QGLVertexAttribute -{ -public: - QGLVertexAttribute(GLenum glType, GLuint location, QGLContext* context) - : m_id(location), m_type(QGLType(glType)), ctx(context) {} - - QGLVertexAttribute(); // Called by QMap when there's no match on the name - - QGLType type() const {return m_type;} - GLuint id() const {return m_id;} - void enable() const; - void disable() const; - - const QGLVertexAttribute& operator=(const GLfloat* rhs) const; - const QGLVertexAttribute& operator=(const QGLVec3* rhs) const; - -protected: - GLuint m_id; - QGLType m_type; - QGLContext* ctx; -}; - -//TODO: Convert into setter overloads on QGLShaderProgram -typedef QMap QGLVertexAttributeList; -typedef QMapIterator QGLVertexAttributeListIterator; - - - -class QGLShaderProgramPrivate; - -class QGLShaderProgram : QObject -{ - Q_OBJECT -public: - QGLShaderProgram(const QGLContext* ctx = 0); - - const QGLUniformList & uniforms(); - const QGLVertexAttributeList& vertexAttributes(); - - bool addShader(QGLShader* newShader); - bool removeShader(QGLShader* oldShader); - bool removeAllShaders(); - - bool link(); - QString log(); - bool isValid(); - void use(); - - GLuint id(); - -private: - QGLShaderProgramPrivate* d_ptr; - Q_DECLARE_PRIVATE(QGLShaderProgram); - -/* -public slots: - void cleanupGLContextRefs(const QGLContext *context); -*/ -}; - -- cgit v0.12 From 861651c67a5f627f615ac1542f945e3c11593406 Mon Sep 17 00:00:00 2001 From: Gunnar Sletta Date: Thu, 23 Apr 2009 09:16:53 +0200 Subject: Implement QRasterPaintEngine::clip(QRegion) to do something sensible... Since we now store QRegion's in the clipdata is possible for us to detect that we should go back to a rect-clip mode when we get to clip(region) or clip(rect) It turns out that the qt_span_fill_clipRegion is very slow, even for smaller regions, testcase was 3 rects, its 10% worse than span based clipping. For a fullscreen ellipse it was more in the range of 100x worse, so I removed the clip function entirely. --- src/gui/painting/qpaintengine_raster.cpp | 146 ++++++++++++++++++------------- src/gui/painting/qpaintengine_raster_p.h | 1 - 2 files changed, 86 insertions(+), 61 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 358dcea..c44763d 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -139,7 +139,6 @@ extern bool qt_cleartype_enabled; * Span functions */ static void qt_span_fill_clipRect(int count, const QSpan *spans, void *userData); -static void qt_span_fill_clipRegion(int count, const QSpan *spans, void *userData); static void qt_span_fill_clipped(int count, const QSpan *spans, void *userData); static void qt_span_clip(int count, const QSpan *spans, void *userData); static void qt_merge_clip(const QClipData *c1, const QClipData *c2, QClipData *result); @@ -1149,6 +1148,25 @@ void QRasterPaintEnginePrivate::updateMatrixData(QSpanData *spanData, const QBru } +static void qrasterpaintengine_state_setNoClip(QRasterPaintEngineState *s) +{ + if (s->flags.has_clip_ownership) + delete s->clip; + s->clip = 0; + s->flags.has_clip_ownership = false; +} + +static void qrasterpaintengine_dirty_clip(QRasterPaintEnginePrivate *d, QRasterPaintEngineState *s) +{ + s->fillFlags |= QPaintEngine::DirtyClipPath; + s->strokeFlags |= QPaintEngine::DirtyClipPath; + s->pixmapFlags |= QPaintEngine::DirtyClipPath; + + d->solid_color_filler.clip = d->clip(); + d->solid_color_filler.adjustSpanMethods(); +} + + /*! \internal */ @@ -1197,10 +1215,7 @@ void QRasterPaintEngine::clip(const QVectorPath &path, Qt::ClipOperation op) } if (op == Qt::NoClip) { - if (s->flags.has_clip_ownership) - delete s->clip; - s->clip = 0; - s->flags.has_clip_ownership = false; + qrasterpaintengine_state_setNoClip(s); } else { QClipData *base = d->baseClip; @@ -1242,13 +1257,7 @@ void QRasterPaintEngine::clip(const QVectorPath &path, Qt::ClipOperation op) s->clip = newClip; s->flags.has_clip_ownership = true; } - - s->fillFlags |= DirtyClipPath; - s->strokeFlags |= DirtyClipPath; - s->pixmapFlags |= DirtyClipPath; - - d->solid_color_filler.clip = d->clip(); - d->solid_color_filler.adjustSpanMethods(); + qrasterpaintengine_dirty_clip(d, s); } @@ -1266,10 +1275,7 @@ void QRasterPaintEngine::clip(const QRect &rect, Qt::ClipOperation op) QRasterPaintEngineState *s = state(); if (op == Qt::NoClip) { - if (s->flags.has_clip_ownership) - delete s->clip; - s->clip = d->baseClip; - s->flags.has_clip_ownership = false; + qrasterpaintengine_state_setNoClip(s); } else if (op == Qt::UniteClip || s->matrix.type() > QTransform::TxScale) { QPaintEngineEx::clip(rect, op); @@ -1313,32 +1319,63 @@ void QRasterPaintEngine::clip(const QRect &rect, Qt::ClipOperation op) return; } } - - s->brushData.clip = d->clip(); - s->penData.clip = d->clip(); - - s->fillFlags |= DirtyClipPath; - s->strokeFlags |= DirtyClipPath; - s->pixmapFlags |= DirtyClipPath; - - d->solid_color_filler.clip = d->clip(); - d->solid_color_filler.adjustSpanMethods(); + qrasterpaintengine_dirty_clip(d, s); } + /*! \internal */ void QRasterPaintEngine::clip(const QRegion ®ion, Qt::ClipOperation op) { - QPaintEngineEx::clip(region, op); -} +#ifdef QT_DEBUG_DRAW + qDebug() << "QRasterPaintEngine::clip(): " << region << op; +#endif -/*! - \internal -*/ -void QRasterPaintEngine::clip(const QPainterPath &path, Qt::ClipOperation op) -{ - QPaintEngineEx::clip(path, op); + Q_D(QRasterPaintEngine); + + if (region.numRects() == 1) { + clip(region.boundingRect(), op); + return; + } + + QRasterPaintEngineState *s = state(); + const QClipData *clip = d->clip(); + const QClipData *baseClip = d->baseClip; + + if (op == Qt::NoClip) { + qrasterpaintengine_state_setNoClip(s); + } else if (s->matrix.type() > QTransform::TxScale + || op == Qt::UniteClip + || (op == Qt::IntersectClip && !clip->hasRectClip && !clip->hasRegionClip) + || (op == Qt::ReplaceClip && !baseClip->hasRectClip && !baseClip->hasRegionClip)) { + QPaintEngineEx::clip(region, op); + } else { + const QClipData *curClip; + QClipData *newClip; + + if (op == Qt::IntersectClip) + curClip = clip; + else + curClip = baseClip; + + if (s->flags.has_clip_ownership) { + newClip = s->clip; + Q_ASSERT(newClip); + } else { + newClip = new QClipData(d->rasterBuffer->height()); + s->clip = newClip; + s->flags.has_clip_ownership = true; + } + + QRegion r = s->matrix.map(region); + if (curClip->hasRectClip) + newClip->setClipRegion(r & curClip->clipRect); + else if (curClip->hasRegionClip) + newClip->setClipRegion(r & clip->clipRegion); + + qrasterpaintengine_dirty_clip(d, s); + } } /*! @@ -4387,6 +4424,7 @@ void QClipData::setClipRect(const QRect &rect) { // qDebug() << "setClipRect" << clipSpanHeight << count << allocated << rect; hasRectClip = true; + hasRegionClip = false; clipRect = rect; xmin = rect.x(); @@ -4394,6 +4432,12 @@ void QClipData::setClipRect(const QRect &rect) ymin = qMin(rect.y(), clipSpanHeight); ymax = qMin(rect.y() + rect.height(), clipSpanHeight); + if (m_spans) { + delete m_spans; + m_spans = 0; + } + + // qDebug() << xmin << xmax << ymin << ymax; } @@ -4408,6 +4452,7 @@ void QClipData::setClipRegion(const QRegion ®ion) } hasRegionClip = true; + hasRectClip = false; clipRegion = region; { // set bounding rect @@ -4417,6 +4462,12 @@ void QClipData::setClipRegion(const QRegion ®ion) ymin = rect.y(); ymax = rect.y() + rect.height(); } + + if (m_spans) { + delete m_spans; + m_spans = 0; + } + } /*! @@ -4661,29 +4712,6 @@ static void qt_span_fill_clipRect(int count, const QSpan *spans, fillData->unclipped_blend(count, spans, fillData); } -static void qt_span_fill_clipRegion(int count, const QSpan *spans, - void *userData) -{ - QSpanData *fillData = reinterpret_cast(userData); - Q_ASSERT(fillData->blend && fillData->unclipped_blend); - - Q_ASSERT(fillData->clip); - Q_ASSERT(!fillData->clip->clipRegion.isEmpty()); - - const int NSPANS = 256; - QSpan cspans[NSPANS]; - int currentClip = 0; - while (currentClip < count) { - const int unclipped = qt_intersect_spans(const_cast(spans), - count, ¤tClip, - &cspans[0], NSPANS, - fillData->clip->clipRegion); - if (unclipped > 0) - fillData->unclipped_blend(unclipped, cspans, fillData); - } - -} - static void qt_span_clip(int count, const QSpan *spans, void *userData) { ClipData *clipData = reinterpret_cast(userData); @@ -5108,8 +5136,6 @@ void QSpanData::adjustSpanMethods() blend = unclipped_blend; } else if (clip->hasRectClip) { blend = clip->clipRect.isEmpty() ? 0 : qt_span_fill_clipRect; - } else if (clip->hasRegionClip) { - blend = clip->clipRegion.isEmpty() ? 0 : qt_span_fill_clipRegion; } else { blend = qt_span_fill_clipped; } @@ -6086,7 +6112,7 @@ void dumpClip(int width, int height, QClipData *clip) int y1 = 0; for (int i = 0; i < clip->count; ++i) { - QSpan *span = clip->spans + i; + QSpan *span = clip->spans() + i; for (int j = 0; j < span->len; ++j) clipImg.setPixel(span->x + j, span->y, 0xffffff00); x0 = qMin(x0, int(span->x)); diff --git a/src/gui/painting/qpaintengine_raster_p.h b/src/gui/painting/qpaintengine_raster_p.h index 26a2b3f..1f3f006 100644 --- a/src/gui/painting/qpaintengine_raster_p.h +++ b/src/gui/painting/qpaintengine_raster_p.h @@ -202,7 +202,6 @@ public: void clip(const QVectorPath &path, Qt::ClipOperation op); void clip(const QRect &rect, Qt::ClipOperation op); void clip(const QRegion ®ion, Qt::ClipOperation op); - void clip(const QPainterPath &path, Qt::ClipOperation op); enum ClipType { RectClip, -- cgit v0.12 From 9f1f048cb8c29f8c169afa0d5595acfa4eac606b Mon Sep 17 00:00:00 2001 From: Gunnar Sletta Date: Fri, 24 Apr 2009 09:29:06 +0200 Subject: Optimize intersected rect clipping in raster engine.. If we have span based clipping (complex) and we manage to intersect down to a plain rectangle, we switch back to rectangle mode which speeds up filling significantly... Reviewed-by: Samuel --- src/gui/painting/qpaintengine_raster.cpp | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index c44763d..bf84aa7 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -4401,20 +4401,39 @@ void QClipData::fixup() ymax = m_spans[count-1].y + 1; xmin = INT_MAX; xmax = 0; + + bool isRect = true; + int left = m_spans[0].x; + int right = m_spans[0].x + m_spans[0].len; + for (int i = 0; i < count; ++i) { -// qDebug() << " " << spans[i].x << spans[i].y << spans[i].len << spans[i].coverage; if (m_spans[i].y != y) { + if (m_spans[i].y != y + 1 && y != -1) { + isRect = false; + } y = m_spans[i].y; m_clipLines[y].spans = m_spans+i; m_clipLines[y].count = 0; // qDebug() << " new line: y=" << y; } ++m_clipLines[y].count; + int sl = (int) m_spans[i].x; + int sr = sl + m_spans[i].len; + xmin = qMin(xmin, (int)m_spans[i].x); xmax = qMax(xmax, (int)m_spans[i].x + m_spans[i].len); + + if (sl != left || sr != right) + isRect = false; } ++xmax; -// qDebug("xmin=%d,xmax=%d,ymin=%d,ymax=%d", xmin, xmax, ymin, ymax); +// qDebug("xmin=%d,xmax=%d,ymin=%d,ymax=%d %s", xmin, xmax, ymin, ymax, isRect ? "rectangular" : ""); + + if (isRect) { + hasRectClip = true; + clipRect.setRect(xmin, ymin, xmax - xmin, ymax - ymin); + } + } /* -- cgit v0.12 From a90c924918f5705f900e2f55cfc5ca44ba3f8c3b Mon Sep 17 00:00:00 2001 From: Gunnar Sletta Date: Fri, 24 Apr 2009 10:45:01 +0200 Subject: Two buglets with clipping in raster engine In fillRect_normalized(), if we don't have user-clip we always have rectclip, so the initial value of the bool was false, and would cause the code to run through the slower code path. In unclipped_normalized(), the hasRegionClip must have been a typo left over from the falcon port. Reviewed-by: Samuel --- src/gui/painting/qpaintengine_raster.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index bf84aa7..20cea08 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -1417,7 +1417,7 @@ static void fillRect_normalized(const QRect &r, QSpanData *data, { int x1, x2, y1, y2; - bool rectClipped = false; + bool rectClipped = true; if (data->clip) { x1 = qMax(r.x(), data->clip->xmin); @@ -3066,7 +3066,7 @@ bool QRasterPaintEnginePrivate::isUnclipped_normalized(const QRect &r) const if (cl->clipRect == deviceRect) return true; - if (cl->hasRegionClip) { + if (cl->hasRectClip) { // inline contains() for performance (we know the rects are normalized) const QRect &r1 = cl->clipRect; return (r.left() >= r1.left() && r.right() <= r1.right() -- cgit v0.12 From 8d93fb9149d20eb6110649c9fab2d0ef25960ccf Mon Sep 17 00:00:00 2001 From: Gunnar Sletta Date: Fri, 24 Apr 2009 10:48:10 +0200 Subject: compile... --- src/opengl/qglframebufferobject.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index b210285..b5d0088 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -160,8 +160,7 @@ QGLFramebufferObjectFormat::QGLFramebufferObjectFormat(const QGLFramebufferObjec Assigns \a other to this object. */ -QGLFramebufferObjectFormat::QGLFramebufferObjectFormat & -QGLFramebufferObjectFormat::operator=(const QGLFramebufferObjectFormat &other) +QGLFramebufferObjectFormat &QGLFramebufferObjectFormat::operator=(const QGLFramebufferObjectFormat &other) { *d = *other.d; return *this; -- cgit v0.12 From ae3c71bcc588f4b11158cb943c7dd453f066efc6 Mon Sep 17 00:00:00 2001 From: Gunnar Sletta Date: Fri, 24 Apr 2009 13:37:25 +0200 Subject: Fix crash caused by clip(QRegion) in raster now depending on baseclip This was introduced by my recent implementation... --- src/gui/painting/qpaintengine_raster.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 20cea08..f950bad 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -362,7 +362,8 @@ void QRasterPaintEngine::init() d->basicStroker.setCubicToHook(qt_ft_outline_cubic_to); d->dashStroker = 0; - d->baseClip = 0; + d->baseClip = new QClipData(d->device->height()); + d->baseClip->setClipRect(QRect(0, 0, d->device->width(), d->device->height())); d->image_filler.init(d->rasterBuffer, this); d->image_filler.type = QSpanData::Texture; @@ -446,6 +447,8 @@ QRasterPaintEngine::~QRasterPaintEngine() delete d->outlineMapper; delete d->rasterizer; delete d->dashStroker; + + delete d->baseClip; } /*! @@ -541,11 +544,6 @@ bool QRasterPaintEngine::end() } #endif - if (d->baseClip) { - delete d->baseClip; - d->baseClip = 0; - } - return true; } @@ -1099,11 +1097,10 @@ void QRasterPaintEnginePrivate::systemStateChanged() if (!systemClip.isEmpty()) { QRegion clippedDeviceRgn = systemClip & clipRect; deviceRect = clippedDeviceRgn.boundingRect(); - delete baseClip; - baseClip = new QClipData(device->height()); baseClip->setClipRegion(clippedDeviceRgn); } else { deviceRect = clipRect; + baseClip->setClipRect(deviceRect); } #ifdef QT_DEBUG_DRAW qDebug() << "systemStateChanged" << this << "deviceRect" << deviceRect << clipRect << systemClip; -- cgit v0.12 From c429978d1a547e19c95db72f89755076b3b5bf1b Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Fri, 1 May 2009 11:22:10 +1000 Subject: Rename uses of QGLShaderProgram::errors() to log() Reviewed-by: trustme --- demos/boxes/scene.cpp | 6 +++--- src/opengl/gl2paintengineex/qglengineshadermanager.cpp | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/demos/boxes/scene.cpp b/demos/boxes/scene.cpp index e5aab75..cd9671e 100644 --- a/demos/boxes/scene.cpp +++ b/demos/boxes/scene.cpp @@ -620,11 +620,11 @@ void Scene::initGL() if (!program->link()) { qWarning("Failed to compile and link shader program"); qWarning("Vertex shader log:"); - qWarning() << m_vertexShader->errors(); + qWarning() << m_vertexShader->log(); qWarning() << "Fragment shader log ( file =" << file.absoluteFilePath() << "):"; - qWarning() << shader->errors(); + qWarning() << shader->log(); qWarning("Shader program log:"); - qWarning() << program->errors(); + qWarning() << program->log(); delete shader; delete program; diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index 3d8d34b..d238830 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -156,7 +156,7 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) simpleShaderProg->link(); if (!simpleShaderProg->isValid()) { qCritical() << "Errors linking simple shader:" - << simpleShaderProg->errors(); + << simpleShaderProg->log(); } } @@ -432,7 +432,7 @@ bool QGLEngineShaderManager::useCorrectShaderProg() << " compositionFragShader = "<< requiredProgram.compositionFragShader->objectName() << '\n' #endif << " Error Log:" << '\n' - << " " << requiredProgram.program->errors(); + << " " << requiredProgram.program->log(); qWarning() << error; } else { -- cgit v0.12 From 8baf1a4dfb2b1a1bb7ecb5ada93ed9972f0e7762 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 5 May 2009 20:49:53 +0200 Subject: Fix OpenGL ES 2.0 breakages Enable GL graphics system on ES 2.0 builds - it wont work, but now QGLDrawable is being used it's just easier to build the graphics system. --- src/opengl/opengl.pro | 4 ++-- src/opengl/qgl.cpp | 2 ++ src/opengl/qwindowsurface_gl.cpp | 11 ++++++++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro index 88af516..7cb8a71 100644 --- a/src/opengl/opengl.pro +++ b/src/opengl/opengl.pro @@ -15,10 +15,10 @@ contains(QT_CONFIG, opengl):CONFIG += opengl contains(QT_CONFIG, opengles1):CONFIG += opengles1 contains(QT_CONFIG, opengles2):CONFIG += opengles2 -!contains(QT_CONFIG, opengles2) { +#!contains(QT_CONFIG, opengles2) { HEADERS += qgraphicssystem_gl_p.h qwindowsurface_gl_p.h qpixmapdata_gl_p.h SOURCES += qgraphicssystem_gl.cpp qwindowsurface_gl.cpp qpixmapdata_gl.cpp -} +#} HEADERS += qgl.h \ qgl_p.h \ diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index d74ed95..907bc51 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -1365,7 +1365,9 @@ QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alp QImage img(size, alpha_format ? QImage::Format_ARGB32 : QImage::Format_RGB32); int w = size.width(); int h = size.height(); +#if !defined(QT_OPENGL_ES_2) //### glGetTexImage not in GL ES 2.0, need to do something else here! glGetTexImage(qt_gl_preferredTextureTarget(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); +#endif convertFromGLImage(img, w, h, alpha_format, include_alpha); return img; } diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index d92241d..4c2748c 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -382,6 +382,7 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & QRegion dirtyRegion = QRegion(window()->rect()) - d_ptr->paintedRegion; +#if !defined(QT_OPENGL_ES_2) if (!dirtyRegion.isEmpty()) { context()->makeCurrent(); @@ -407,6 +408,7 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & drawTexture(rect, d_ptr->tex_id, window()->size(), rect); } } +#endif d_ptr->paintedRegion = QRegion(); context()->swapBuffers(); @@ -455,7 +457,9 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & GL_NEAREST); glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, d_ptr->fbo->handle()); - } else { + } +#if !defined(QT_OPENGL_ES_2) + else { glDisable(GL_DEPTH_TEST); if (d_ptr->fbo) { @@ -485,6 +489,7 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & if (d_ptr->fbo) d_ptr->fbo->bind(); } +#endif if (ctx->format().doubleBuffer()) ctx->swapBuffers(); @@ -568,6 +573,7 @@ void QGLWindowSurface::updateGeometry() glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(target, 0); +#if !defined(QT_OPENGL_ES_2) glMatrixMode(GL_PROJECTION); glLoadIdentity(); #ifndef QT_OPENGL_ES @@ -575,6 +581,7 @@ void QGLWindowSurface::updateGeometry() #else glOrthof(0, d_ptr->pb->width(), d_ptr->pb->height(), 0, -999999, 999999); #endif +#endif // !defined(QT_OPENGL_ES_2) d_ptr->pb->d_ptr->qctx->d_func()->internal_context = true; return; @@ -672,6 +679,7 @@ static void drawTexture(const QRectF &rect, GLuint tex_id, const QSize &texSize, extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); // qpaintengine_opengl.cpp qt_add_rect_to_array(rect, vertexArray); +#if !defined(QT_OPENGL_ES_2) glVertexPointer(2, q_vertexTypeEnum, 0, vertexArray); glTexCoordPointer(2, q_vertexTypeEnum, 0, texCoordArray); @@ -683,6 +691,7 @@ static void drawTexture(const QRectF &rect, GLuint tex_id, const QSize &texSize, glDrawArrays(GL_TRIANGLE_FAN, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); +#endif glDisable(target); glBindTexture(target, 0); -- cgit v0.12 From 7d6281973f8b0a5b53e63952f0d03624e6020454 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 5 May 2009 21:29:40 +0200 Subject: Big GL Extension Cleanup Clean up the extension naming and make things build on OpenGL ES 2.0 again. All the extensions which made it into OpenGL 2.0 spec have have the EXT postfix removed. This also eliminates defines on ES 2.0 as the code now refers to the in-spec names. Reviewed-by: sroedal --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 5 +- src/opengl/opengl.pro | 3 +- src/opengl/qgl.cpp | 10 +- src/opengl/qglextensions.cpp | 125 ++++++---- src/opengl/qglextensions_p.h | 272 +++++++++------------ src/opengl/qglframebufferobject.cpp | 76 +++--- src/opengl/qpixmapdata_gl.cpp | 10 +- src/opengl/qwindowsurface_gl.cpp | 4 +- 8 files changed, 253 insertions(+), 252 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 7dbdc32..1c0d7e0 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1059,8 +1059,9 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) d->height = sz.height(); d->mode = BrushDrawingMode; - qt_resolve_version_1_3_functions(d->ctx); - qt_resolve_glsl_extensions(d->ctx); +#if !defined(QT_OPENGL_ES_2) + qt_resolve_version_2_0_functions(d->ctx); +#endif d->last_engine = d->ctx->d_ptr->active_engine; d->ctx->d_ptr->active_engine = this; diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro index 7cb8a71..cfa9e4f 100644 --- a/src/opengl/opengl.pro +++ b/src/opengl/opengl.pro @@ -26,7 +26,8 @@ HEADERS += qgl.h \ qglpixelbuffer.h \ qglframebufferobject.h \ qglpixmapfilter_p.h \ - qglshaderprogram.h + qglshaderprogram.h \ + qglextensions_p.h SOURCES += qgl.cpp \ qglcolormap.cpp \ diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 907bc51..ccb6080 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -1573,7 +1573,7 @@ void QGLContextPrivate::cleanup() Q_Q(QGLContext); if (pbo) { QGLContext *ctx = q; - glDeleteBuffersARB(1, &pbo); + glDeleteBuffers(1, &pbo); pbo = 0; } } @@ -1838,7 +1838,7 @@ GLuint QGLContextPrivate::bindTexture(const QImage &image, GLenum target, GLint use_pbo = qt_resolve_buffer_extensions(ctx); if (use_pbo && pbo == 0) - glGenBuffersARB(1, &pbo); + glGenBuffers(1, &pbo); } // the GL_BGRA format is only present in GL version >= 1.2 @@ -1889,8 +1889,8 @@ GLuint QGLContextPrivate::bindTexture(const QImage &image, GLenum target, GLint uchar *ptr = 0; if (use_pbo) { - glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, pbo); - glBufferDataARB(GL_PIXEL_UNPACK_BUFFER_ARB, img.width() * img.height() * 4, 0, GL_STREAM_DRAW_ARB); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, pbo); + glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, img.width() * img.height() * 4, 0, GL_STREAM_DRAW_ARB); ptr = reinterpret_cast(glMapBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, GL_WRITE_ONLY_ARB)); } @@ -1917,7 +1917,7 @@ GLuint QGLContextPrivate::bindTexture(const QImage &image, GLenum target, GLint } if (use_pbo) - glBindBufferARB(GL_PIXEL_UNPACK_BUFFER_ARB, 0); + glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0); // this assumes the size of a texture is always smaller than the max cache size int cost = img.width()*img.height()*4/1024; diff --git a/src/opengl/qglextensions.cpp b/src/opengl/qglextensions.cpp index 9ec76cb..3c198fb 100644 --- a/src/opengl/qglextensions.cpp +++ b/src/opengl/qglextensions.cpp @@ -45,9 +45,15 @@ QT_BEGIN_NAMESPACE bool qt_resolve_framebufferobject_extensions(QGLContext *ctx) { -#if !defined(QT_OPENGL_ES_2) - if (glIsRenderbufferEXT != 0) +#if defined(QT_OPENGL_ES_2) + static bool have_resolved = false; + if (have_resolved) return true; + have_resolved = true; +#else + if (glIsRenderbuffer != 0) + return true; +#endif if (ctx == 0) { qWarning("QGLFramebufferObject: Unable to resolve framebuffer object extensions -" @@ -55,35 +61,37 @@ bool qt_resolve_framebufferobject_extensions(QGLContext *ctx) return false; } - glIsRenderbufferEXT = (_glIsRenderbufferEXT) ctx->getProcAddress(QLatin1String("glIsRenderbufferEXT")); - glBindRenderbufferEXT = (_glBindRenderbufferEXT) ctx->getProcAddress(QLatin1String("glBindRenderbufferEXT")); - glDeleteRenderbuffersEXT = (_glDeleteRenderbuffersEXT) ctx->getProcAddress(QLatin1String("glDeleteRenderbuffersEXT")); - glGenRenderbuffersEXT = (_glGenRenderbuffersEXT) ctx->getProcAddress(QLatin1String("glGenRenderbuffersEXT")); - glRenderbufferStorageEXT = (_glRenderbufferStorageEXT) ctx->getProcAddress(QLatin1String("glRenderbufferStorageEXT")); - glGetRenderbufferParameterivEXT = - (_glGetRenderbufferParameterivEXT) ctx->getProcAddress(QLatin1String("glGetRenderbufferParameterivEXT")); - glIsFramebufferEXT = (_glIsFramebufferEXT) ctx->getProcAddress(QLatin1String("glIsFramebufferEXT")); - glBindFramebufferEXT = (_glBindFramebufferEXT) ctx->getProcAddress(QLatin1String("glBindFramebufferEXT")); - glDeleteFramebuffersEXT = (_glDeleteFramebuffersEXT) ctx->getProcAddress(QLatin1String("glDeleteFramebuffersEXT")); - glGenFramebuffersEXT = (_glGenFramebuffersEXT) ctx->getProcAddress(QLatin1String("glGenFramebuffersEXT")); - glCheckFramebufferStatusEXT = (_glCheckFramebufferStatusEXT) ctx->getProcAddress(QLatin1String("glCheckFramebufferStatusEXT")); - glFramebufferTexture1DEXT = (_glFramebufferTexture1DEXT) ctx->getProcAddress(QLatin1String("glFramebufferTexture1DEXT")); - glFramebufferTexture2DEXT = (_glFramebufferTexture2DEXT) ctx->getProcAddress(QLatin1String("glFramebufferTexture2DEXT")); - glFramebufferTexture3DEXT = (_glFramebufferTexture3DEXT) ctx->getProcAddress(QLatin1String("glFramebufferTexture3DEXT")); - glFramebufferRenderbufferEXT = (_glFramebufferRenderbufferEXT) ctx->getProcAddress(QLatin1String("glFramebufferRenderbufferEXT")); - glGetFramebufferAttachmentParameterivEXT = - (_glGetFramebufferAttachmentParameterivEXT) ctx->getProcAddress(QLatin1String("glGetFramebufferAttachmentParameterivEXT")); - glGenerateMipmapEXT = (_glGenerateMipmapEXT) ctx->getProcAddress(QLatin1String("glGenerateMipmapEXT")); + glBlitFramebufferEXT = (_glBlitFramebufferEXT) ctx->getProcAddress(QLatin1String("glBlitFramebufferEXT")); glRenderbufferStorageMultisampleEXT = (_glRenderbufferStorageMultisampleEXT) ctx->getProcAddress(QLatin1String("glRenderbufferStorageMultisampleEXT")); - return glIsRenderbufferEXT; + +#if !defined(QT_OPENGL_ES_2) + glIsRenderbuffer = (_glIsRenderbuffer) ctx->getProcAddress(QLatin1String("glIsRenderbufferEXT")); + glBindRenderbuffer = (_glBindRenderbuffer) ctx->getProcAddress(QLatin1String("glBindRenderbufferEXT")); + glDeleteRenderbuffers = (_glDeleteRenderbuffers) ctx->getProcAddress(QLatin1String("glDeleteRenderbuffersEXT")); + glGenRenderbuffers = (_glGenRenderbuffers) ctx->getProcAddress(QLatin1String("glGenRenderbuffersEXT")); + glRenderbufferStorage = (_glRenderbufferStorage) ctx->getProcAddress(QLatin1String("glRenderbufferStorageEXT")); + glGetRenderbufferParameteriv = + (_glGetRenderbufferParameteriv) ctx->getProcAddress(QLatin1String("glGetRenderbufferParameterivEXT")); + glIsFramebuffer = (_glIsFramebuffer) ctx->getProcAddress(QLatin1String("glIsFramebufferEXT")); + glBindFramebuffer = (_glBindFramebuffer) ctx->getProcAddress(QLatin1String("glBindFramebufferEXT")); + glDeleteFramebuffers = (_glDeleteFramebuffers) ctx->getProcAddress(QLatin1String("glDeleteFramebuffersEXT")); + glGenFramebuffers = (_glGenFramebuffers) ctx->getProcAddress(QLatin1String("glGenFramebuffersEXT")); + glCheckFramebufferStatus = (_glCheckFramebufferStatus) ctx->getProcAddress(QLatin1String("glCheckFramebufferStatusEXT")); + glFramebufferTexture2D = (_glFramebufferTexture2D) ctx->getProcAddress(QLatin1String("glFramebufferTexture2DEXT")); + glFramebufferRenderbuffer = (_glFramebufferRenderbuffer) ctx->getProcAddress(QLatin1String("glFramebufferRenderbufferEXT")); + glGetFramebufferAttachmentParameteriv = + (_glGetFramebufferAttachmentParameteriv) ctx->getProcAddress(QLatin1String("glGetFramebufferAttachmentParameterivEXT")); + glGenerateMipmap = (_glGenerateMipmap) ctx->getProcAddress(QLatin1String("glGenerateMipmapEXT")); + + return glIsRenderbuffer; #else - Q_UNUSED(ctx); return true; #endif } +#if !defined(QT_OPENGL_ES_2) bool qt_resolve_version_1_3_functions(QGLContext *ctx) { if (glMultiTexCoord4f != 0) @@ -92,14 +100,12 @@ bool qt_resolve_version_1_3_functions(QGLContext *ctx) QGLContext cx(QGLFormat::defaultFormat()); glMultiTexCoord4f = (_glMultiTexCoord4f) ctx->getProcAddress(QLatin1String("glMultiTexCoord4f")); -#if defined(QT_OPENGL_ES_2) - return glMultiTexCoord4f; -#else glActiveTexture = (_glActiveTexture) ctx->getProcAddress(QLatin1String("glActiveTexture")); return glMultiTexCoord4f && glActiveTexture; -#endif } +#endif +#if !defined(QT_OPENGL_ES_2) bool qt_resolve_stencil_face_extension(QGLContext *ctx) { if (glActiveStencilFaceEXT != 0) @@ -110,7 +116,10 @@ bool qt_resolve_stencil_face_extension(QGLContext *ctx) return glActiveStencilFaceEXT; } +#endif + +#if !defined(QT_OPENGL_ES_2) bool qt_resolve_frag_program_extensions(QGLContext *ctx) { if (glProgramStringARB != 0) @@ -129,26 +138,36 @@ bool qt_resolve_frag_program_extensions(QGLContext *ctx) && glGenProgramsARB && glProgramLocalParameter4fvARB; } +#endif + bool qt_resolve_buffer_extensions(QGLContext *ctx) { - if (glBindBufferARB && glDeleteBuffersARB && glGenBuffersARB && glBufferDataARB - && glMapBufferARB && glUnmapBufferARB) + if (glMapBufferARB && glUnmapBufferARB +#if !defined(QT_OPENGL_ES_2) + && glBindBuffer && glDeleteBuffers && glGenBuffers && glBufferData +#endif + ) return true; - glBindBufferARB = (_glBindBufferARB) ctx->getProcAddress(QLatin1String("glBindBufferARB")); - glDeleteBuffersARB = (_glDeleteBuffersARB) ctx->getProcAddress(QLatin1String("glDeleteBuffersARB")); - glGenBuffersARB = (_glGenBuffersARB) ctx->getProcAddress(QLatin1String("glGenBuffersARB")); - glBufferDataARB = (_glBufferDataARB) ctx->getProcAddress(QLatin1String("glBufferDataARB")); +#if !defined(QT_OPENGL_ES_2) + glBindBuffer = (_glBindBuffer) ctx->getProcAddress(QLatin1String("glBindBufferARB")); + glDeleteBuffers = (_glDeleteBuffers) ctx->getProcAddress(QLatin1String("glDeleteBuffersARB")); + glGenBuffers = (_glGenBuffers) ctx->getProcAddress(QLatin1String("glGenBuffersARB")); + glBufferData = (_glBufferData) ctx->getProcAddress(QLatin1String("glBufferDataARB")); +#endif glMapBufferARB = (_glMapBufferARB) ctx->getProcAddress(QLatin1String("glMapBufferARB")); glUnmapBufferARB = (_glUnmapBufferARB) ctx->getProcAddress(QLatin1String("glUnmapBufferARB")); - return glBindBufferARB - && glDeleteBuffersARB - && glGenBuffersARB - && glBufferDataARB - && glMapBufferARB - && glUnmapBufferARB; + return glMapBufferARB + && glUnmapBufferARB +#if !defined(QT_OPENGL_ES_2) + && glBindBuffer + && glDeleteBuffers + && glGenBuffers + && glBufferData +#endif + ; } bool qt_resolve_glsl_extensions(QGLContext *ctx) @@ -215,7 +234,6 @@ bool qt_resolve_glsl_extensions(QGLContext *ctx) glDisableVertexAttribArray = (_glDisableVertexAttribArray) ctx->getProcAddress(QLatin1String("glDisableVertexAttribArray")); glEnableVertexAttribArray = (_glEnableVertexAttribArray) ctx->getProcAddress(QLatin1String("glEnableVertexAttribArray")); - glStencilOpSeparate = (_glStencilOpSeparate) ctx->getProcAddress(QLatin1String("glStencilOpSeparate")); //### Not really a glsl extension, but needed for gl2 } else { // We may not have the standard shader functions, but we might // have the older ARB functions instead. @@ -266,8 +284,6 @@ bool qt_resolve_glsl_extensions(QGLContext *ctx) glVertexAttribPointer = (_glVertexAttribPointer) ctx->getProcAddress(QLatin1String("glVertexAttribPointerARB")); glDisableVertexAttribArray = (_glDisableVertexAttribArray) ctx->getProcAddress(QLatin1String("glDisableVertexAttribArrayARB")); glEnableVertexAttribArray = (_glEnableVertexAttribArray) ctx->getProcAddress(QLatin1String("glEnableVertexAttribArrayARB")); - - glStencilOpSeparate = 0; //### Was never an ARB extension but went strait into OpenGL 2.0 } // Note: glShaderBinary(), glIsShader(), glIsProgram(), and @@ -307,9 +323,30 @@ bool qt_resolve_glsl_extensions(QGLContext *ctx) glVertexAttrib4fv && glVertexAttribPointer && glDisableVertexAttribArray && - glEnableVertexAttribArray && - glStencilOpSeparate; + glEnableVertexAttribArray; #endif } +#if !defined(QT_OPENGL_ES_2) +bool qt_resolve_version_2_0_functions(QGLContext *ctx) +{ + bool gl2supported = true; + if (!qt_resolve_glsl_extensions(ctx)) + gl2supported = false; + + if (!qt_resolve_version_1_3_functions(ctx)) + gl2supported = false; + + if (glStencilOpSeparate) + return gl2supported; + + glStencilOpSeparate = (_glStencilOpSeparate) ctx->getProcAddress(QLatin1String("glStencilOpSeparate")); + if (!glStencilOpSeparate) + gl2supported = false; + + return gl2supported; +} +#endif + + QT_END_NAMESPACE diff --git a/src/opengl/qglextensions_p.h b/src/opengl/qglextensions_p.h index 793400a..46047ef 100644 --- a/src/opengl/qglextensions_p.h +++ b/src/opengl/qglextensions_p.h @@ -79,10 +79,10 @@ typedef char GLchar; #endif // ARB_pixel_buffer_object -typedef void (APIENTRY *_glBindBufferARB) (GLenum, GLuint); -typedef void (APIENTRY *_glDeleteBuffersARB) (GLsizei, const GLuint *); -typedef void (APIENTRY *_glGenBuffersARB) (GLsizei, GLuint *); -typedef void (APIENTRY *_glBufferDataARB) (GLenum, GLsizeiptrARB, const GLvoid *, GLenum); +typedef void (APIENTRY *_glBindBuffer) (GLenum, GLuint); +typedef void (APIENTRY *_glDeleteBuffers) (GLsizei, const GLuint *); +typedef void (APIENTRY *_glGenBuffers) (GLsizei, GLuint *); +typedef void (APIENTRY *_glBufferData) (GLenum, GLsizeiptrARB, const GLvoid *, GLenum); typedef GLvoid* (APIENTRY *_glMapBufferARB) (GLenum, GLenum); typedef GLboolean (APIENTRY *_glUnmapBufferARB) (GLenum); @@ -145,50 +145,34 @@ typedef void (APIENTRY *_glEnableVertexAttribArray) (GLuint); typedef void (APIENTRY *_glGetProgramBinaryOES) (GLuint, GLsizei, GLsizei *, GLenum *, void *); typedef void (APIENTRY *_glProgramBinaryOES) (GLuint, GLenum, const void *, GLint); -typedef void (APIENTRY *_glActiveStencilFaceEXT) (GLenum ); typedef void (APIENTRY *_glMultiTexCoord4f) (GLenum, GLfloat, GLfloat, GLfloat, GLfloat); -typedef void (APIENTRY *_glActiveTexture) (GLenum); +typedef void (APIENTRY *_glActiveStencilFaceEXT) (GLenum ); -typedef void (APIENTRY *_glGetActiveAttrib) (GLuint program, GLuint index, GLsizei maxLength, GLsizei* length, GLint* size, GLenum* type, GLchar* name); -typedef GLint (APIENTRY *_glGetAttribLocation) (GLuint program, const GLchar* name); -typedef void (APIENTRY *_glGetActiveUniform) (GLuint program, GLuint index, GLsizei maxLength, GLsizei* length, GLint* size, GLenum* type, GLchar* name); -typedef void (APIENTRY *_glGetProgramInfoLog) (GLuint program, GLsizei bufSize, GLsizei* length, GLchar* infoLog); -typedef void (APIENTRY *_glUniform1f) (GLint location, GLfloat v0); -typedef void (APIENTRY *_glUniform2f) (GLint location, GLfloat v0, GLfloat v1); -typedef void (APIENTRY *_glUniform4f) (GLint location, GLfloat v0, GLfloat v1, GLfloat v2, GLfloat v3); -typedef void (APIENTRY *_glUniformMatrix2fv) (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); -typedef void (APIENTRY *_glUniformMatrix3fv) (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); -typedef void (APIENTRY *_glUniformMatrix4fv) (GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); -typedef void (APIENTRY *_glEnableVertexAttribArray) (GLuint); -typedef void (APIENTRY *_glDisableVertexAttribArray) (GLuint); -typedef void (APIENTRY *_glVertexAttribPointer) (GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const GLvoid* pointer); +// Needed for GL2 engine: typedef void (APIENTRY *_glStencilOpSeparate) (GLenum face, GLenum sfail, GLenum dpfail, GLenum dppass); +typedef void (APIENTRY *_glActiveTexture) (GLenum); // EXT_GL_framebuffer_object -typedef GLboolean (APIENTRY *_glIsRenderbufferEXT) (GLuint renderbuffer); -typedef void (APIENTRY *_glBindRenderbufferEXT) (GLenum target, GLuint renderbuffer); -typedef void (APIENTRY *_glDeleteRenderbuffersEXT) (GLsizei n, const GLuint *renderbuffers); -typedef void (APIENTRY *_glGenRenderbuffersEXT) (GLsizei n, GLuint *renderbuffers); -typedef void (APIENTRY *_glRenderbufferStorageEXT) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); -typedef void (APIENTRY *_glGetRenderbufferParameterivEXT) (GLenum target, GLenum pname, GLint *params); -typedef GLboolean (APIENTRY *_glIsFramebufferEXT) (GLuint framebuffer); -typedef void (APIENTRY *_glBindFramebufferEXT) (GLenum target, GLuint framebuffer); -typedef void (APIENTRY *_glDeleteFramebuffersEXT) (GLsizei n, const GLuint *framebuffers); -typedef void (APIENTRY *_glGenFramebuffersEXT) (GLsizei n, GLuint *framebuffers); -typedef GLenum (APIENTRY *_glCheckFramebufferStatusEXT) (GLenum target); -typedef void (APIENTRY *_glFramebufferTexture1DEXT) (GLenum target, GLenum attachment, GLenum textarget, +typedef GLboolean (APIENTRY *_glIsRenderbuffer) (GLuint renderbuffer); +typedef void (APIENTRY *_glBindRenderbuffer) (GLenum target, GLuint renderbuffer); +typedef void (APIENTRY *_glDeleteRenderbuffers) (GLsizei n, const GLuint *renderbuffers); +typedef void (APIENTRY *_glGenRenderbuffers) (GLsizei n, GLuint *renderbuffers); +typedef void (APIENTRY *_glRenderbufferStorage) (GLenum target, GLenum internalformat, GLsizei width, GLsizei height); +typedef void (APIENTRY *_glGetRenderbufferParameteriv) (GLenum target, GLenum pname, GLint *params); +typedef GLboolean (APIENTRY *_glIsFramebuffer) (GLuint framebuffer); +typedef void (APIENTRY *_glBindFramebuffer) (GLenum target, GLuint framebuffer); +typedef void (APIENTRY *_glDeleteFramebuffers) (GLsizei n, const GLuint *framebuffers); +typedef void (APIENTRY *_glGenFramebuffers) (GLsizei n, GLuint *framebuffers); +typedef GLenum (APIENTRY *_glCheckFramebufferStatus) (GLenum target); +typedef void (APIENTRY *_glFramebufferTexture2D) (GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); -typedef void (APIENTRY *_glFramebufferTexture2DEXT) (GLenum target, GLenum attachment, GLenum textarget, - GLuint texture, GLint level); -typedef void (APIENTRY *_glFramebufferTexture3DEXT) (GLenum target, GLenum attachment, GLenum textarget, - GLuint texture, GLint level, GLint zoffset); -typedef void (APIENTRY *_glFramebufferRenderbufferEXT) (GLenum target, GLenum attachment, GLenum renderbuffertarget, +typedef void (APIENTRY *_glFramebufferRenderbuffer) (GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); -typedef void (APIENTRY *_glGetFramebufferAttachmentParameterivEXT) (GLenum target, GLenum attachment, GLenum pname, +typedef void (APIENTRY *_glGetFramebufferAttachmentParameteriv) (GLenum target, GLenum attachment, GLenum pname, GLint *params); -typedef void (APIENTRY *_glGenerateMipmapEXT) (GLenum target); +typedef void (APIENTRY *_glGenerateMipmap) (GLenum target); // EXT_GL_framebuffer_blit typedef void (APIENTRY *_glBlitFramebufferEXT) (int srcX0, int srcY0, int srcX1, int srcY1, @@ -204,13 +188,14 @@ QT_BEGIN_NAMESPACE struct QGLExtensionFuncs { QGLExtensionFuncs() { +#if !defined(QT_OPENGL_ES_2) qt_glProgramStringARB = 0; qt_glBindProgramARB = 0; qt_glDeleteProgramsARB = 0; qt_glGenProgramsARB = 0; qt_glProgramLocalParameter4fvARB = 0; -#if !defined(QT_OPENGL_ES_2) + // GLSL qt_glCreateShader = 0; qt_glShaderSource = 0; qt_glShaderBinary = 0; @@ -258,6 +243,13 @@ struct QGLExtensionFuncs qt_glVertexAttribPointer = 0; qt_glDisableVertexAttribArray = 0; qt_glEnableVertexAttribArray = 0; + + // Extras for GL2 engine: + qt_glActiveTexture = 0; + qt_glStencilOpSeparate = 0; + + qt_glActiveStencilFaceEXT = 0; + qt_glMultiTexCoord4f = 0; #else qt_glslResolved = false; @@ -265,63 +257,46 @@ struct QGLExtensionFuncs qt_glProgramBinaryOES = 0; #endif - qt_glActiveStencilFaceEXT = 0; - - qt_glMultiTexCoord4f = 0; - qt_glActiveTexture = 0; - + // FBOs #if !defined(QT_OPENGL_ES_2) - qt_glIsRenderbufferEXT = 0; - qt_glBindRenderbufferEXT = 0; - qt_glDeleteRenderbuffersEXT = 0; - qt_glGenRenderbuffersEXT = 0; - qt_glRenderbufferStorageEXT = 0; - qt_glGetRenderbufferParameterivEXT = 0; - qt_glIsFramebufferEXT = 0; - qt_glBindFramebufferEXT = 0; - qt_glDeleteFramebuffersEXT = 0; - qt_glGenFramebuffersEXT = 0; - qt_glCheckFramebufferStatusEXT = 0; - qt_glFramebufferTexture1DEXT = 0; - qt_glFramebufferTexture2DEXT = 0; - qt_glFramebufferTexture3DEXT = 0; - qt_glFramebufferRenderbufferEXT = 0; - qt_glGetFramebufferAttachmentParameterivEXT = 0; - qt_glGenerateMipmapEXT = 0; + qt_glIsRenderbuffer = 0; + qt_glBindRenderbuffer = 0; + qt_glDeleteRenderbuffers = 0; + qt_glGenRenderbuffers = 0; + qt_glRenderbufferStorage = 0; + qt_glGetRenderbufferParameteriv = 0; + qt_glIsFramebuffer = 0; + qt_glBindFramebuffer = 0; + qt_glDeleteFramebuffers = 0; + qt_glGenFramebuffers = 0; + qt_glCheckFramebufferStatus = 0; + qt_glFramebufferTexture2D = 0; + qt_glFramebufferRenderbuffer = 0; + qt_glGetFramebufferAttachmentParameteriv = 0; + qt_glGenerateMipmap = 0; #endif qt_glBlitFramebufferEXT = 0; qt_glRenderbufferStorageMultisampleEXT = 0; - qt_glBindBufferARB = 0; - qt_glDeleteBuffersARB = 0; - qt_glGenBuffersARB = 0; - qt_glBufferDataARB = 0; + // Buffer objects: +#if !defined(QT_OPENGL_ES_2) + qt_glBindBuffer = 0; + qt_glDeleteBuffers = 0; + qt_glGenBuffers = 0; + qt_glBufferData = 0; +#endif qt_glMapBufferARB = 0; qt_glUnmapBufferARB = 0; - - qt_glGetActiveAttrib = 0; - qt_glGetAttribLocation = 0; - qt_glGetActiveUniform = 0; - qt_glGetProgramInfoLog = 0; - qt_glUniform1f = 0; - qt_glUniform2f = 0; - qt_glUniform4f = 0; - qt_glUniformMatrix2fv = 0; - qt_glUniformMatrix3fv = 0; - qt_glUniformMatrix4fv = 0; - qt_glEnableVertexAttribArray = 0; - qt_glDisableVertexAttribArray = 0; - qt_glVertexAttribPointer = 0; - qt_glStencilOpSeparate = 0; } + +#if !defined(QT_OPENGL_ES_2) _glProgramStringARB qt_glProgramStringARB; _glBindProgramARB qt_glBindProgramARB; _glDeleteProgramsARB qt_glDeleteProgramsARB; _glGenProgramsARB qt_glGenProgramsARB; _glProgramLocalParameter4fvARB qt_glProgramLocalParameter4fvARB; -#if !defined(QT_OPENGL_ES_2) // GLSL definitions _glCreateShader qt_glCreateShader; _glShaderSource qt_glShaderSource; @@ -370,6 +345,7 @@ struct QGLExtensionFuncs _glVertexAttribPointer qt_glVertexAttribPointer; _glDisableVertexAttribArray qt_glDisableVertexAttribArray; _glEnableVertexAttribArray qt_glEnableVertexAttribArray; + #else bool qt_glslResolved; @@ -378,45 +354,45 @@ struct QGLExtensionFuncs #endif _glActiveStencilFaceEXT qt_glActiveStencilFaceEXT; - _glMultiTexCoord4f qt_glMultiTexCoord4f; + +#if !defined(QT_OPENGL_ES_2) + // Extras needed for GL2 engine: _glActiveTexture qt_glActiveTexture; + _glStencilOpSeparate qt_glStencilOpSeparate; +#endif + // FBOs #if !defined(QT_OPENGL_ES_2) - _glIsRenderbufferEXT qt_glIsRenderbufferEXT; - _glBindRenderbufferEXT qt_glBindRenderbufferEXT; - _glDeleteRenderbuffersEXT qt_glDeleteRenderbuffersEXT; - _glGenRenderbuffersEXT qt_glGenRenderbuffersEXT; - _glRenderbufferStorageEXT qt_glRenderbufferStorageEXT; - _glGetRenderbufferParameterivEXT qt_glGetRenderbufferParameterivEXT; - _glIsFramebufferEXT qt_glIsFramebufferEXT; - _glBindFramebufferEXT qt_glBindFramebufferEXT; - _glDeleteFramebuffersEXT qt_glDeleteFramebuffersEXT; - _glGenFramebuffersEXT qt_glGenFramebuffersEXT; - _glCheckFramebufferStatusEXT qt_glCheckFramebufferStatusEXT; - _glFramebufferTexture1DEXT qt_glFramebufferTexture1DEXT; - _glFramebufferTexture2DEXT qt_glFramebufferTexture2DEXT; - _glFramebufferTexture3DEXT qt_glFramebufferTexture3DEXT; - _glFramebufferRenderbufferEXT qt_glFramebufferRenderbufferEXT; - _glGetFramebufferAttachmentParameterivEXT qt_glGetFramebufferAttachmentParameterivEXT; - _glGenerateMipmapEXT qt_glGenerateMipmapEXT; + _glIsRenderbuffer qt_glIsRenderbuffer; + _glBindRenderbuffer qt_glBindRenderbuffer; + _glDeleteRenderbuffers qt_glDeleteRenderbuffers; + _glGenRenderbuffers qt_glGenRenderbuffers; + _glRenderbufferStorage qt_glRenderbufferStorage; + _glGetRenderbufferParameteriv qt_glGetRenderbufferParameteriv; + _glIsFramebuffer qt_glIsFramebuffer; + _glBindFramebuffer qt_glBindFramebuffer; + _glDeleteFramebuffers qt_glDeleteFramebuffers; + _glGenFramebuffers qt_glGenFramebuffers; + _glCheckFramebufferStatus qt_glCheckFramebufferStatus; + _glFramebufferTexture2D qt_glFramebufferTexture2D; + _glFramebufferRenderbuffer qt_glFramebufferRenderbuffer; + _glGetFramebufferAttachmentParameteriv qt_glGetFramebufferAttachmentParameteriv; + _glGenerateMipmap qt_glGenerateMipmap; #endif _glBlitFramebufferEXT qt_glBlitFramebufferEXT; _glRenderbufferStorageMultisampleEXT qt_glRenderbufferStorageMultisampleEXT; - _glBindBufferARB qt_glBindBufferARB; - _glDeleteBuffersARB qt_glDeleteBuffersARB; - _glGenBuffersARB qt_glGenBuffersARB; - _glBufferDataARB qt_glBufferDataARB; + // Buffer objects +#if !defined(QT_OPENGL_ES_2) + _glBindBuffer qt_glBindBuffer; + _glDeleteBuffers qt_glDeleteBuffers; + _glGenBuffers qt_glGenBuffers; + _glBufferData qt_glBufferData; +#endif _glMapBufferARB qt_glMapBufferARB; _glUnmapBufferARB qt_glUnmapBufferARB; - _glGetActiveAttrib qt_glGetActiveAttrib; - _glGetActiveUniform qt_glGetActiveUniform; - _glUniform1f qt_glUniform1f; - _glUniform2f qt_glUniform2f; - _glUniform4f qt_glUniform4f; - _glStencilOpSeparate qt_glStencilOpSeparate; }; @@ -619,6 +595,8 @@ struct QGLExtensionFuncs #define GL_ACTIVE_ATTRIBUTE_MAX_LENGTH 0x8B8A #endif + +#if !defined(QT_OPENGL_ES_2) #define glProgramStringARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glProgramStringARB #define glBindProgramARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindProgramARB #define glDeleteProgramsARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteProgramsARB @@ -629,61 +607,44 @@ struct QGLExtensionFuncs #define glMultiTexCoord4f QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glMultiTexCoord4f -#if !defined(QT_OPENGL_ES_2) #define glActiveTexture QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glActiveTexture -#endif +#endif // !defined(QT_OPENGL_ES_2) -#if !defined(QT_OPENGL_ES_2) -#define glIsRenderbufferEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glIsRenderbufferEXT -#define glBindRenderbufferEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindRenderbufferEXT -#define glDeleteRenderbuffersEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteRenderbuffersEXT -#define glGenRenderbuffersEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenRenderbuffersEXT -#define glRenderbufferStorageEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glRenderbufferStorageEXT -#define glGetRenderbufferParameterivEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetRenderbufferParameterivEXT -#define glIsFramebufferEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glIsFramebufferEXT -#define glBindFramebufferEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindFramebufferEXT -#define glDeleteFramebuffersEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteFramebuffersEXT -#define glGenFramebuffersEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenFramebuffersEXT -#define glCheckFramebufferStatusEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glCheckFramebufferStatusEXT -#define glFramebufferTexture1DEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glFramebufferTexture1DEXT -#define glFramebufferTexture2DEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glFramebufferTexture2DEXT -#define glFramebufferTexture3DEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glFramebufferTexture3DEXT -#define glFramebufferRenderbufferEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glFramebufferRenderbufferEXT -#define glGetFramebufferAttachmentParameterivEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetFramebufferAttachmentParameterivEXT -#define glGenerateMipmapEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenerateMipmapEXT +// FBOs +#if !defined(QT_OPENGL_ES_2) +#define glIsRenderbuffer QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glIsRenderbuffer +#define glBindRenderbuffer QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindRenderbuffer +#define glDeleteRenderbuffers QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteRenderbuffers +#define glGenRenderbuffers QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenRenderbuffers +#define glRenderbufferStorage QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glRenderbufferStorage +#define glGetRenderbufferParameteriv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetRenderbufferParameteriv +#define glIsFramebuffer QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glIsFramebuffer +#define glBindFramebuffer QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindFramebuffer +#define glDeleteFramebuffers QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteFramebuffers +#define glGenFramebuffers QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenFramebuffers +#define glCheckFramebufferStatus QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glCheckFramebufferStatus +#define glFramebufferTexture2D QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glFramebufferTexture2D +#define glFramebufferRenderbuffer QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glFramebufferRenderbuffer +#define glGetFramebufferAttachmentParameteriv QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGetFramebufferAttachmentParameteriv +#define glGenerateMipmap QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenerateMipmap +#endif // QT_OPENGL_ES_2 #define glBlitFramebufferEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBlitFramebufferEXT #define glRenderbufferStorageMultisampleEXT QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glRenderbufferStorageMultisampleEXT -#else // QT_OPENGL_ES_2 - -#define glIsRenderbufferEXT glIsRenderbuffer -#define glBindRenderbufferEXT glBindRenderbuffer -#define glDeleteRenderbuffersEXT glDeleteRenderbuffers -#define glGenRenderbuffersEXT glGenRenderbuffers -#define glRenderbufferStorageEXT glRenderbufferStorage -#define glGetRenderbufferParameterivEXT glGetRenderbufferParameteriv -#define glIsFramebufferEXT glIsFramebuffer -#define glBindFramebufferEXT glBindFramebuffer -#define glDeleteFramebuffersEXT glDeleteFramebuffers -#define glGenFramebuffersEXT glGenFramebuffers -#define glCheckFramebufferStatusEXT glCheckFramebufferStatus -#define glFramebufferTexture1DEXT glFramebufferTexture1D -#define glFramebufferTexture2DEXT glFramebufferTexture2D -#define glFramebufferTexture3DEXT glFramebufferTexture3D -#define glFramebufferRenderbufferEXT glFramebufferRenderbuffer -#define glGetFramebufferAttachmentParameterivEXT glGetFramebufferAttachmentParameteriv -#define glGenerateMipmapEXT glGenerateMipmap -#endif // QT_OPENGL_ES_2 - -#define glBindBufferARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindBufferARB -#define glDeleteBuffersARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteBuffersARB -#define glGenBuffersARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenBuffersARB -#define glBufferDataARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBufferDataARB +// Buffer objects +#if !defined(QT_OPENGL_ES_2) +#define glBindBuffer QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBindBuffer +#define glDeleteBuffers QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glDeleteBuffers +#define glGenBuffers QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glGenBuffers +#define glBufferData QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glBufferData +#endif #define glMapBufferARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glMapBufferARB #define glUnmapBufferARB QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glUnmapBufferARB + +// GLSL #if !defined(QT_OPENGL_ES_2) #define glCreateShader QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glCreateShader @@ -741,9 +702,9 @@ struct QGLExtensionFuncs #endif // QT_OPENGL_ES_2 -#define glStencilOpSeparate QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glStencilOpSeparate #if !defined(QT_OPENGL_ES_2) +#define glStencilOpSeparate QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glStencilOpSeparate #define glClearDepthf(x) glClearDepth(GLdouble(x)) #endif @@ -751,6 +712,7 @@ extern bool qt_resolve_framebufferobject_extensions(QGLContext *ctx); bool qt_resolve_buffer_extensions(QGLContext *ctx); bool qt_resolve_version_1_3_functions(QGLContext *ctx); +bool qt_resolve_version_2_0_functions(QGLContext *ctx); bool qt_resolve_stencil_face_extension(QGLContext *ctx); bool qt_resolve_frag_program_extensions(QGLContext *ctx); diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index b210285..4546f00 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -307,7 +307,7 @@ public: bool QGLFramebufferObjectPrivate::checkFramebufferStatus() const { - GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT); + GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER_EXT); switch(status) { case GL_NO_ERROR: case GL_FRAMEBUFFER_COMPLETE_EXT: @@ -362,8 +362,8 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At // texture dimensions while (glGetError() != GL_NO_ERROR) {} // reset error state - glGenFramebuffersEXT(1, &fbo); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); + glGenFramebuffers(1, &fbo); + glBindFramebuffer(GL_FRAMEBUFFER_EXT, fbo); QT_CHECK_GLERROR(); // init texture @@ -383,7 +383,7 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); #endif - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, target, texture, 0); QT_CHECK_GLERROR(); @@ -397,59 +397,59 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At samples = qBound(1, samples, int(maxSamples)); - glGenRenderbuffersEXT(1, &color_buffer); - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, color_buffer); + glGenRenderbuffers(1, &color_buffer); + glBindRenderbuffer(GL_RENDERBUFFER_EXT, color_buffer); if (glRenderbufferStorageMultisampleEXT) { glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, internal_format, size.width(), size.height()); } else { samples = 0; - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, internal_format, + glRenderbufferStorage(GL_RENDERBUFFER_EXT, internal_format, size.width(), size.height()); } - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_RENDERBUFFER_EXT, color_buffer); QT_CHECK_GLERROR(); valid = checkFramebufferStatus(); if (valid) - glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &samples); + glGetRenderbufferParameteriv(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_SAMPLES_EXT, &samples); } if (attachment == QGLFramebufferObject::CombinedDepthStencil && (QGLExtensions::glExtensions & QGLExtensions::PackedDepthStencil)) { // depth and stencil buffer needs another extension - glGenRenderbuffersEXT(1, &depth_stencil_buffer); - Q_ASSERT(!glIsRenderbufferEXT(depth_stencil_buffer)); - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_stencil_buffer); - Q_ASSERT(glIsRenderbufferEXT(depth_stencil_buffer)); + glGenRenderbuffers(1, &depth_stencil_buffer); + Q_ASSERT(!glIsRenderbuffer(depth_stencil_buffer)); + glBindRenderbuffer(GL_RENDERBUFFER_EXT, depth_stencil_buffer); + Q_ASSERT(glIsRenderbuffer(depth_stencil_buffer)); if (samples != 0 && glRenderbufferStorageMultisampleEXT) glRenderbufferStorageMultisampleEXT(GL_RENDERBUFFER_EXT, samples, GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); else - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, + glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH24_STENCIL8_EXT, size.width(), size.height()); GLint i = 0; - glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &i); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, + glGetRenderbufferParameteriv(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &i); + glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_buffer); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, + glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_STENCIL_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_buffer); fbo_attachment = QGLFramebufferObject::CombinedDepthStencil; valid = checkFramebufferStatus(); if (!valid) - glDeleteRenderbuffersEXT(1, &depth_stencil_buffer); + glDeleteRenderbuffers(1, &depth_stencil_buffer); } else if (attachment == QGLFramebufferObject::Depth || attachment == QGLFramebufferObject::CombinedDepthStencil) { - glGenRenderbuffersEXT(1, &depth_stencil_buffer); - Q_ASSERT(!glIsRenderbufferEXT(depth_stencil_buffer)); - glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, depth_stencil_buffer); - Q_ASSERT(glIsRenderbufferEXT(depth_stencil_buffer)); + glGenRenderbuffers(1, &depth_stencil_buffer); + Q_ASSERT(!glIsRenderbuffer(depth_stencil_buffer)); + glBindRenderbuffer(GL_RENDERBUFFER_EXT, depth_stencil_buffer); + Q_ASSERT(glIsRenderbuffer(depth_stencil_buffer)); if (samples != 0 && glRenderbufferStorageMultisampleEXT) { #ifdef QT_OPENGL_ES #define GL_DEPTH_COMPONENT16 0x81A5 @@ -462,30 +462,30 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At } else { #ifdef QT_OPENGL_ES #define GL_DEPTH_COMPONENT16 0x81A5 - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, size.width(), size.height()); + glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT16, size.width(), size.height()); #else - glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, size.width(), size.height()); + glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT, size.width(), size.height()); #endif } GLint i = 0; - glGetRenderbufferParameterivEXT(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &i); - glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, + glGetRenderbufferParameteriv(GL_RENDERBUFFER_EXT, GL_RENDERBUFFER_DEPTH_SIZE_EXT, &i); + glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, depth_stencil_buffer); fbo_attachment = QGLFramebufferObject::Depth; valid = checkFramebufferStatus(); if (!valid) - glDeleteRenderbuffersEXT(1, &depth_stencil_buffer); + glDeleteRenderbuffers(1, &depth_stencil_buffer); } else { fbo_attachment = QGLFramebufferObject::NoAttachment; } - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); + glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); if (!valid) { if (color_buffer) - glDeleteRenderbuffersEXT(1, &color_buffer); + glDeleteRenderbuffers(1, &color_buffer); else glDeleteTextures(1, &texture); - glDeleteFramebuffersEXT(1, &fbo); + glDeleteFramebuffers(1, &fbo); } QT_CHECK_GLERROR(); @@ -753,10 +753,10 @@ QGLFramebufferObject::~QGLFramebufferObject() { glDeleteTextures(1, &d->texture); if (d->color_buffer) - glDeleteRenderbuffersEXT(1, &d->color_buffer); + glDeleteRenderbuffers(1, &d->color_buffer); if (d->depth_stencil_buffer) - glDeleteRenderbuffersEXT(1, &d->depth_stencil_buffer); - glDeleteFramebuffersEXT(1, &d->fbo); + glDeleteRenderbuffers(1, &d->depth_stencil_buffer); + glDeleteFramebuffers(1, &d->fbo); } delete d_ptr; } @@ -799,7 +799,7 @@ bool QGLFramebufferObject::bind() return false; Q_D(QGLFramebufferObject); QGL_FUNC_CONTEXT; - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, d->fbo); + glBindFramebuffer(GL_FRAMEBUFFER_EXT, d->fbo); d->bound = d->valid = d->checkFramebufferStatus(); const QGLContext *context = QGLContext::currentContext(); if (d->valid && context) { @@ -835,7 +835,7 @@ bool QGLFramebufferObject::release() if (context) { // Restore the previous setting for stacked framebuffer objects. context->d_ptr->current_fbo = d->previous_fbo; - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, d->previous_fbo); + glBindFramebuffer(GL_FRAMEBUFFER_EXT, d->previous_fbo); d->previous_fbo = 0; } @@ -1144,14 +1144,14 @@ void QGLFramebufferObject::blitFramebuffer(QGLFramebufferObject *target, const Q const int ty0 = th - (targetRect.top() + targetRect.height()); const int ty1 = th - targetRect.top(); - glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, source ? source->handle() : 0); - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, target ? target->handle() : 0); + glBindFramebuffer(GL_READ_FRAMEBUFFER_EXT, source ? source->handle() : 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, target ? target->handle() : 0); glBlitFramebufferEXT(sx0, sy0, sx1, sy1, tx0, ty0, tx1, ty1, buffers, filter); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); + glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); } QT_END_NAMESPACE diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index 1fa5b47..cb0b4d1 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -280,10 +280,10 @@ void QGLPixmapData::copyBackFromRenderFbo(bool keepCurrentFboBound) const ensureCreated(); if (!ctx->d_ptr->fbo) - glGenFramebuffersEXT(1, &ctx->d_ptr->fbo); + glGenFramebuffers(1, &ctx->d_ptr->fbo); - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->d_ptr->fbo); - glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->fbo); + glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, qt_gl_preferredTextureTarget(), m_textureId, 0); const int x0 = 0; @@ -291,7 +291,7 @@ void QGLPixmapData::copyBackFromRenderFbo(bool keepCurrentFboBound) const const int y0 = 0; const int y1 = m_height; - glBindFramebufferEXT(GL_READ_FRAMEBUFFER_EXT, m_renderFbo->handle()); + glBindFramebuffer(GL_READ_FRAMEBUFFER_EXT, m_renderFbo->handle()); glDisable(GL_SCISSOR_TEST); @@ -301,7 +301,7 @@ void QGLPixmapData::copyBackFromRenderFbo(bool keepCurrentFboBound) const GL_NEAREST); if (keepCurrentFboBound) - glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); + glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); } void QGLPixmapData::swapBuffers() diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 4c2748c..576da12 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -449,14 +449,14 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & const int y0 = h - (rect.top() + rect.height()); const int y1 = h - rect.top(); - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, 0); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, 0); glBlitFramebufferEXT(x0, y0, x1, y1, x0, y0, x1, y1, GL_COLOR_BUFFER_BIT, GL_NEAREST); - glBindFramebufferEXT(GL_DRAW_FRAMEBUFFER_EXT, d_ptr->fbo->handle()); + glBindFramebuffer(GL_DRAW_FRAMEBUFFER_EXT, d_ptr->fbo->handle()); } #if !defined(QT_OPENGL_ES_2) else { -- cgit v0.12 From 3822cd597fc481acb2a4de324c005c23ce8e78cd Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Mon, 11 May 2009 09:21:54 +0200 Subject: Fix QWS build breakage QScreen uses QSpanData::setup, so broke because of API change. Reviewed-by: sroedal --- src/gui/embedded/qscreen_qws.cpp | 5 +++-- src/gui/painting/qdrawhelper_p.h | 2 +- src/gui/painting/qpaintengine_raster.cpp | 12 ++++++------ 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/gui/embedded/qscreen_qws.cpp b/src/gui/embedded/qscreen_qws.cpp index ff48403..a82edbb 100644 --- a/src/gui/embedded/qscreen_qws.cpp +++ b/src/gui/embedded/qscreen_qws.cpp @@ -49,6 +49,7 @@ #include "qpixmap.h" #include "qvarlengtharray.h" #include "qwsdisplay_qws.h" +#include "qpainter.h" #include #include #include @@ -2710,7 +2711,7 @@ void QScreen::compose(int level, const QRegion &exposed, QRegion &blend, default: break; } - spanData.setup(qwsServer->backgroundBrush(), 256); + spanData.setup(qwsServer->backgroundBrush(), 256, QPainter::CompositionMode_SourceOver); spanData.dx = off.x(); spanData.dy = off.y(); } else if (!surface->isBuffered()) { @@ -2775,7 +2776,7 @@ void QScreen::paintBackground(const QRegion &r) rb.prepare(&img); QSpanData spanData; spanData.init(&rb, 0); - spanData.setup(bg, 256); + spanData.setup(bg, 256, QPainter::CompositionMode_Source); spanData.dx = off.x(); spanData.dy = off.y(); Q_ASSERT(spanData.blend); diff --git a/src/gui/painting/qdrawhelper_p.h b/src/gui/painting/qdrawhelper_p.h index 586ffe3..019402a 100644 --- a/src/gui/painting/qdrawhelper_p.h +++ b/src/gui/painting/qdrawhelper_p.h @@ -294,7 +294,7 @@ struct QSpanData }; void init(QRasterBuffer *rb, const QRasterPaintEngine *pe); - void setup(const QBrush &brush, int alpha, const QRasterPaintEngineState *s); + void setup(const QBrush &brush, int alpha, QPainter::CompositionMode compositionMode); void setupMatrix(const QTransform &matrix, int bilinear); void initTexture(const QImage *image, int alpha, QTextureData::Type = QTextureData::Plain, const QRect &sourceRect = QRect()); void adjustSpanMethods(); diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 9237e11..a2ce62e 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -485,12 +485,12 @@ bool QRasterPaintEngine::begin(QPaintDevice *device) d->rasterizer->setClipRect(d->deviceRect); s->penData.init(d->rasterBuffer, this); - s->penData.setup(s->pen.brush(), s->intOpacity, s); + s->penData.setup(s->pen.brush(), s->intOpacity, s->composition_mode); s->stroker = &d->basicStroker; d->basicStroker.setClipRect(d->deviceRect); s->brushData.init(d->rasterBuffer, this); - s->brushData.setup(s->brush, s->intOpacity, s); + s->brushData.setup(s->brush, s->intOpacity, s->composition_mode); d->rasterBuffer->compositionMode = QPainter::CompositionMode_SourceOver; @@ -770,7 +770,7 @@ void QRasterPaintEngine::updatePen(const QPen &pen) s->strokeFlags = 0; s->penData.clip = d->clip(); - s->penData.setup(pen_style == Qt::NoPen ? QBrush() : pen.brush(), s->intOpacity, s); + s->penData.setup(pen_style == Qt::NoPen ? QBrush() : pen.brush(), s->intOpacity, s->composition_mode); if (s->strokeFlags & QRasterPaintEngine::DirtyTransform || pen.brush().transform().type() >= QTransform::TxNone) { @@ -870,7 +870,7 @@ void QRasterPaintEngine::updateBrush(const QBrush &brush) QRasterPaintEngineState *s = state(); // must set clip prior to setup, as setup uses it... s->brushData.clip = d->clip(); - s->brushData.setup(brush, s->intOpacity, s); + s->brushData.setup(brush, s->intOpacity, s->composition_mode); if (s->fillFlags & DirtyTransform || brush.transform().type() >= QTransform::TxNone) d_func()->updateMatrixData(&s->brushData, brush, d->brushMatrix()); @@ -5029,7 +5029,7 @@ void QSpanData::init(QRasterBuffer *rb, const QRasterPaintEngine *pe) extern QImage qt_imageForBrush(int brushStyle, bool invert); -void QSpanData::setup(const QBrush &brush, int alpha, const QRasterPaintEngineState *s) +void QSpanData::setup(const QBrush &brush, int alpha, QPainter::CompositionMode compositionMode) { Qt::BrushStyle brushStyle = qbrush_style(brush); switch (brushStyle) { @@ -5038,7 +5038,7 @@ void QSpanData::setup(const QBrush &brush, int alpha, const QRasterPaintEngineSt QColor c = qbrush_color(brush); solid.color = PREMUL(ARGB_COMBINE_ALPHA(c.rgba(), alpha)); if ((solid.color & 0xff000000) == 0 - && s->composition_mode == QPainter::CompositionMode_SourceOver) { + && compositionMode == QPainter::CompositionMode_SourceOver) { type = None; } break; -- cgit v0.12 From 98bb706b76936dfc88e8d38db39518a3cdf74b30 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 13 May 2009 10:01:40 +0200 Subject: Enabled compilation of both GL and GL2 paint engine. Compile both GL and GL2 paint engine on desktop, and choose between them at run-time based on GL version flags. Reviewed-by: Tom --- src/opengl/gl2paintengineex/qglgradientcache.cpp | 8 +++--- src/opengl/gl2paintengineex/qglgradientcache_p.h | 4 +-- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 22 +++++++-------- .../gl2paintengineex/qpaintengineex_opengl2_p.h | 16 +++++------ src/opengl/opengl.pro | 29 +++++++++---------- src/opengl/qgl.cpp | 33 ++++++++++++++-------- src/opengl/qgl_p.h | 15 ++++++++-- src/opengl/qglframebufferobject.cpp | 18 +++++++----- src/opengl/qglpixelbuffer.cpp | 19 +++++++------ src/opengl/qglpixmapfilter.cpp | 15 +--------- src/opengl/qpaintengine_opengl.cpp | 32 ++------------------- src/opengl/qpixmapdata_gl.cpp | 4 --- src/opengl/qwindowsurface_gl.cpp | 18 +++++++----- 13 files changed, 109 insertions(+), 124 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglgradientcache.cpp b/src/opengl/gl2paintengineex/qglgradientcache.cpp index b4591b2..59d4bf8 100644 --- a/src/opengl/gl2paintengineex/qglgradientcache.cpp +++ b/src/opengl/gl2paintengineex/qglgradientcache.cpp @@ -44,7 +44,7 @@ #include "qglgradientcache_p.h" -void QGLGradientCache::cleanCache() { +void QGL2GradientCache::cleanCache() { QGLGradientColorTableHash::const_iterator it = cache.constBegin(); for (; it != cache.constEnd(); ++it) { const CacheInfo &cache_info = it.value(); @@ -53,7 +53,7 @@ void QGLGradientCache::cleanCache() { cache.clear(); } -GLuint QGLGradientCache::getBuffer(const QGradient &gradient, qreal opacity, const QGLContext *ctx) +GLuint QGL2GradientCache::getBuffer(const QGradient &gradient, qreal opacity, const QGLContext *ctx) { if (buffer_ctx && !qgl_share_reg()->checkSharing(buffer_ctx, ctx)) cleanCache(); @@ -84,7 +84,7 @@ GLuint QGLGradientCache::getBuffer(const QGradient &gradient, qreal opacity, con } -GLuint QGLGradientCache::addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity) +GLuint QGL2GradientCache::addCacheElement(quint64 hash_val, const QGradient &gradient, qreal opacity) { if (cache.size() == maxCacheSize()) { int elem_to_remove = qrand() % maxCacheSize(); @@ -129,7 +129,7 @@ static inline uint qtToGlColor(uint c) } //TODO: Let GL generate the texture using an FBO -void QGLGradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, qreal opacity) const +void QGL2GradientCache::generateGradientColorTable(const QGradient& gradient, uint *colorTable, int size, qreal opacity) const { int pos = 0; QGradientStops s = gradient.stops(); diff --git a/src/opengl/gl2paintengineex/qglgradientcache_p.h b/src/opengl/gl2paintengineex/qglgradientcache_p.h index 346ea13..6acaa00 100644 --- a/src/opengl/gl2paintengineex/qglgradientcache_p.h +++ b/src/opengl/gl2paintengineex/qglgradientcache_p.h @@ -54,7 +54,7 @@ #include #include -class QGLGradientCache : public QObject +class QGL2GradientCache : public QObject { Q_OBJECT struct CacheInfo @@ -71,7 +71,7 @@ class QGLGradientCache : public QObject typedef QMultiHash QGLGradientColorTableHash; public: - QGLGradientCache() : QObject(), buffer_ctx(0) + QGL2GradientCache() : QObject(), buffer_ctx(0) { /* connect(QGLSignalProxy::instance(), diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 1c0d7e0..9f2384d 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -240,7 +240,7 @@ void QGL2PaintEngineExPrivate::useSimpleShader() } -Q_GLOBAL_STATIC(QGLGradientCache, qt_opengl_gradient_cache) +Q_GLOBAL_STATIC(QGL2GradientCache, qt_opengl_gradient_cache) void QGL2PaintEngineExPrivate::updateBrushTexture() { @@ -941,7 +941,7 @@ void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem Q_D(QGL2PaintEngineEx); ensureActive(); - QOpenGLPaintEngineState *s = state(); + QOpenGL2PaintEngineState *s = state(); const QTextItemInt &ti = static_cast(textItem); @@ -967,7 +967,7 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte transferMode(TextDrawingMode); Q_Q(QGL2PaintEngineEx); - QOpenGLPaintEngineState *s = q->state(); + QOpenGL2PaintEngineState *s = q->state(); QVarLengthArray positions; QVarLengthArray glyphs; @@ -1364,9 +1364,9 @@ void QGL2PaintEngineEx::setState(QPainterState *new_state) Q_D(QGL2PaintEngineEx); - QOpenGLPaintEngineState *s = static_cast(new_state); + QOpenGL2PaintEngineState *s = static_cast(new_state); - QOpenGLPaintEngineState *old_state = state(); + QOpenGL2PaintEngineState *old_state = state(); const bool needsDepthClipUpdate = !old_state || s->clipEnabled != old_state->clipEnabled || (s->clipEnabled && s->clipRegion != old_state->clipRegion); @@ -1386,28 +1386,28 @@ void QGL2PaintEngineEx::setState(QPainterState *new_state) QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const { - QOpenGLPaintEngineState *s; + QOpenGL2PaintEngineState *s; if (!orig) - s = new QOpenGLPaintEngineState(); + s = new QOpenGL2PaintEngineState(); else - s = new QOpenGLPaintEngineState(*static_cast(orig)); + s = new QOpenGL2PaintEngineState(*static_cast(orig)); return s; } -QOpenGLPaintEngineState::QOpenGLPaintEngineState(QOpenGLPaintEngineState &other) +QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other) : QPainterState(other) { clipRegion = other.clipRegion; hasClipping = other.hasClipping; } -QOpenGLPaintEngineState::QOpenGLPaintEngineState() +QOpenGL2PaintEngineState::QOpenGL2PaintEngineState() { hasClipping = false; } -QOpenGLPaintEngineState::~QOpenGLPaintEngineState() +QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState() { } diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index b31f685..76a4fe0 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -58,12 +58,12 @@ class QGL2PaintEngineExPrivate; -class QOpenGLPaintEngineState : public QPainterState +class QOpenGL2PaintEngineState : public QPainterState { public: - QOpenGLPaintEngineState(QOpenGLPaintEngineState &other); - QOpenGLPaintEngineState(); - ~QOpenGLPaintEngineState(); + QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other); + QOpenGL2PaintEngineState(); + ~QOpenGL2PaintEngineState(); QRegion clipRegion; bool hasClipping; @@ -107,11 +107,11 @@ public: // State stuff is just for clipping and ripped off from QGLPaintEngine void setState(QPainterState *s); QPainterState *createState(QPainterState *orig) const; - inline QOpenGLPaintEngineState *state() { - return static_cast(QPaintEngineEx::state()); + inline QOpenGL2PaintEngineState *state() { + return static_cast(QPaintEngineEx::state()); } - inline const QOpenGLPaintEngineState *state() const { - return static_cast(QPaintEngineEx::state()); + inline const QOpenGL2PaintEngineState *state() const { + return static_cast(QPaintEngineEx::state()); } void updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op); diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro index cfa9e4f..7eb2503 100644 --- a/src/opengl/opengl.pro +++ b/src/opengl/opengl.pro @@ -37,24 +37,21 @@ SOURCES += qgl.cpp \ qglpixmapfilter.cpp \ qglshaderprogram.cpp -#!contains(QT_CONFIG, opengles2) { -# HEADERS += qpaintengine_opengl_p.h -# SOURCES += qpaintengine_opengl.cpp -#} +!contains(QT_CONFIG, opengles2) { + HEADERS += qpaintengine_opengl_p.h + SOURCES += qpaintengine_opengl.cpp +} -#contains(QT_CONFIG, opengles2) { - SOURCES += gl2paintengineex/qglgradientcache.cpp \ - gl2paintengineex/qglengineshadermanager.cpp \ - gl2paintengineex/qgl2pexvertexarray.cpp \ - gl2paintengineex/qpaintengineex_opengl2.cpp - - HEADERS += gl2paintengineex/qglgradientcache_p.h \ - gl2paintengineex/qglengineshadermanager_p.h \ - gl2paintengineex/qgl2pexvertexarray_p.h \ - gl2paintengineex/qpaintengineex_opengl2_p.h \ - gl2paintengineex/qglengineshadersource_p.h -#} +SOURCES += gl2paintengineex/qglgradientcache.cpp \ + gl2paintengineex/qglengineshadermanager.cpp \ + gl2paintengineex/qgl2pexvertexarray.cpp \ + gl2paintengineex/qpaintengineex_opengl2.cpp +HEADERS += gl2paintengineex/qglgradientcache_p.h \ + gl2paintengineex/qglengineshadermanager_p.h \ + gl2paintengineex/qgl2pexvertexarray_p.h \ + gl2paintengineex/qpaintengineex_opengl2_p.h \ + gl2paintengineex/qglengineshadersource_p.h x11 { contains(QT_CONFIG, opengles1)|contains(QT_CONFIG, opengles1cl)|contains(QT_CONFIG, opengles2) { diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index ccb6080..779ed9a 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -65,9 +65,9 @@ #include "qimage.h" #include "qgl_p.h" -#if 1 || defined(QT_OPENGL_ES_2) #include "gl2paintengineex/qpaintengineex_opengl2_p.h" -#else + +#ifndef QT_OPENGL_ES_2 #include #endif @@ -2125,9 +2125,6 @@ void QGLContext::deleteTexture(QMacCompatGLuint id) } #endif -// qpaintengine_opengl.cpp -#if !defined(QT_OPENGL_ES_2) -//extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); void qt_add_rect_to_array(const QRectF &r, q_vertexType *array) { qreal left = r.left(); @@ -2145,9 +2142,17 @@ void qt_add_rect_to_array(const QRectF &r, q_vertexType *array) array[7] = f2vt(bottom); } -#else -void qt_add_rect_to_array(const QRectF &r, q_vertexType *array) {}; -#endif +void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array) +{ + array[0] = f2vt(x1); + array[1] = f2vt(y1); + array[2] = f2vt(x2); + array[3] = f2vt(y1); + array[4] = f2vt(x2); + array[5] = f2vt(y2); + array[6] = f2vt(x1); + array[7] = f2vt(y2); +} static void qDrawTextureRect(const QRectF &target, GLint textureWidth, GLint textureHeight, GLenum textureTarget) { @@ -4154,9 +4159,9 @@ void QGLWidget::drawTexture(const QPointF &point, QMacCompatGLuint textureId, QM } #endif -#if 1 || defined(QT_OPENGL_ES_2) -Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_engine) -#else +Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_2_engine) + +#ifndef QT_OPENGL_ES_2 Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_engine) #endif @@ -4179,7 +4184,11 @@ Q_OPENGL_EXPORT QPaintEngine* qt_qgl_paint_engine() */ QPaintEngine *QGLWidget::paintEngine() const { - return qt_gl_engine(); +#ifndef QT_OPENGL_ES_2 + if (!qt_gl_preferGL2Engine()) + return qt_gl_engine(); +#endif + return qt_gl_2_engine(); } #ifdef QT3_SUPPORT diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index f7b9392..1513ee8 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -419,6 +419,17 @@ extern QOpenGLPaintEngine* qt_qgl_paint_engine(); extern EGLDisplay qt_qgl_egl_display(); #endif +inline bool qt_gl_preferGL2Engine() +{ +#if defined(QT_OPENGL_ES_2) + return true; +#else + QGLFormat::OpenGLVersionFlags flags = QGLFormat::openGLVersionFlags(); + bool hasOpenGL2 = (flags & QGLFormat::OpenGL_Version_2_0); + return hasOpenGL2 && qgetenv("QT_GL_NO_OPENGL2ENGINE").isEmpty(); +#endif +} + inline GLenum qt_gl_preferredTextureFormat() { return QSysInfo::ByteOrder == QSysInfo::BigEndian ? GL_RGBA : GL_BGRA; @@ -426,16 +437,16 @@ inline GLenum qt_gl_preferredTextureFormat() inline GLenum qt_gl_preferredTextureTarget() { -#if 1 || defined(QT_OPENGL_ES_2) +#if defined(QT_OPENGL_ES_2) return GL_TEXTURE_2D; #else return (QGLExtensions::glExtensions & QGLExtensions::TextureRectangle) + && !qt_gl_preferGL2Engine() ? GL_TEXTURE_RECTANGLE_NV : GL_TEXTURE_2D; #endif } - QT_END_NAMESPACE #endif // QGL_P_H diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index aa5dfc5..87e0dda 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -43,11 +43,12 @@ #include #include -#if 1 || defined(QT_OPENGL_ES_2) #include -#else + +#ifndef QT_OPENGL_ES_2 #include #endif + #include #include #include @@ -896,17 +897,20 @@ QImage QGLFramebufferObject::toImage() const return image; } -#if 1 || defined(QT_OPENGL_ES_2) -Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_paintengine) -#else -Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_paintengine) +Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_2_engine) + +#ifndef QT_OPENGL_ES_2 +Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine) #endif /*! \reimp */ QPaintEngine *QGLFramebufferObject::paintEngine() const { #if !defined(QT_OPENGL_ES_2) - return qt_buffer_paintengine(); + if (qt_gl_preferGL2Engine()) + return qt_buffer_2_engine(); + else + return qt_buffer_engine(); #else return 0; #endif diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp index 6a207c8..cb24177 100644 --- a/src/opengl/qglpixelbuffer.cpp +++ b/src/opengl/qglpixelbuffer.cpp @@ -81,15 +81,15 @@ #include #include -#if 1 || defined(QT_OPENGL_ES_2) #include -#else + +#ifndef QT_OPENGL_ES_2 #include #endif QT_BEGIN_NAMESPACE -#if 0 && !defined(QT_OPENGL_ES_2) +#if !defined(QT_OPENGL_ES_2) extern void qgl_cleanup_glyph_cache(QGLContext *); #else void qgl_cleanup_glyph_cache(QGLContext *) {} @@ -365,17 +365,20 @@ bool QGLPixelBuffer::isValid() const return !d->invalid; } -#if 1 || defined(QT_OPENGL_ES_2) -Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_paintengine) -#else -Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_paintengine) +Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_2_engine) + +#ifndef QT_OPENGL_ES_2 +Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine) #endif /*! \reimp */ QPaintEngine *QGLPixelBuffer::paintEngine() const { #if !defined(QT_OPENGL_ES_2) - return qt_buffer_paintengine(); + if (qt_gl_preferGL2Engine()) + return qt_buffer_2_engine(); + else + return qt_buffer_engine(); #else return 0; #endif diff --git a/src/opengl/qglpixmapfilter.cpp b/src/opengl/qglpixmapfilter.cpp index 5d4d5bf..eb3298b 100644 --- a/src/opengl/qglpixmapfilter.cpp +++ b/src/opengl/qglpixmapfilter.cpp @@ -116,21 +116,8 @@ QPixmapFilter *QGLContextPrivate::createPixmapFilter(int type) const return 0; } -#if !defined(QT_OPENGL_ES_2) extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); -//extern void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array); -void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array) -{ - array[0] = f2vt(x1); - array[1] = f2vt(y1); - array[2] = f2vt(x2); - array[3] = f2vt(y1); - array[4] = f2vt(x2); - array[5] = f2vt(y2); - array[6] = f2vt(x1); - array[7] = f2vt(y2); -} -#endif +extern void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array); static void qgl_drawTexture(const QRectF &rect, int tx_width, int tx_height, const QRectF & src) { diff --git a/src/opengl/qpaintengine_opengl.cpp b/src/opengl/qpaintengine_opengl.cpp index 612168e..9197ebc 100644 --- a/src/opengl/qpaintengine_opengl.cpp +++ b/src/opengl/qpaintengine_opengl.cpp @@ -123,35 +123,6 @@ struct QT_PointF { qreal y; }; -void qt_add_rect_to_array(const QRectF &r, q_vertexType *array) -{ - qreal left = r.left(); - qreal right = r.right(); - qreal top = r.top(); - qreal bottom = r.bottom(); - - array[0] = f2vt(left); - array[1] = f2vt(top); - array[2] = f2vt(right); - array[3] = f2vt(top); - array[4] = f2vt(right); - array[5] = f2vt(bottom); - array[6] = f2vt(left); - array[7] = f2vt(bottom); -} - -void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array) -{ - array[0] = f2vt(x1); - array[1] = f2vt(y1); - array[2] = f2vt(x2); - array[3] = f2vt(y1); - array[4] = f2vt(x2); - array[5] = f2vt(y2); - array[6] = f2vt(x1); - array[7] = f2vt(y2); -} - struct QGLTrapezoid { QGLTrapezoid() @@ -3124,6 +3095,9 @@ QGLTrapezoidMaskGenerator::QGLTrapezoidMaskGenerator(const QPainterPath &path, c { } +extern void qt_add_rect_to_array(const QRectF &r, q_vertexType *array); +extern void qt_add_texcoords_to_array(qreal x1, qreal y1, qreal x2, qreal y2, q_vertexType *array); + void QGLTrapezoidMaskGenerator::drawMask(const QRect &rect) { #ifdef QT_OPENGL_ES diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index cb0b4d1..89e6749 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -49,11 +49,7 @@ #include #include -#if 1 || defined(QT_OPENGL_ES_2) #include -#else -#include -#endif QT_BEGIN_NAMESPACE diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 576da12..2f111f4 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -69,9 +69,10 @@ #include #include -#if 1 || defined(QT_OPENGL_ES_2) + #include -#else + +#ifndef QT_OPENGL_ES_2 #include #endif @@ -292,17 +293,20 @@ void QGLWindowSurface::hijackWindow(QWidget *widget) qDebug() << "hijackWindow() context created for" << widget << d_ptr->contexts.size(); } -#if 1 || defined(QT_OPENGL_ES_2) -Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_window_surface_paintengine) -#else -Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_window_surface_paintengine) +Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_window_surface_2_engine) + +#ifndef QT_OPENGL_ES_2 +Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_window_surface_engine) #endif /*! \reimp */ QPaintEngine *QGLWindowSurface::paintEngine() const { #if !defined(QT_OPENGL_ES_2) - return qt_gl_window_surface_paintengine(); + if (qt_gl_preferGL2Engine()) + return qt_gl_window_surface_2_engine(); + else + return qt_gl_window_surface_engine(); #else return 0; #endif -- cgit v0.12 From b352b0e637ca19591ee122c47ce4a6ab0a26c06b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 13 May 2009 10:56:31 +0200 Subject: Made GL graphics system work with GLES2 w/o FramebufferBlit extension. At the moment, for the GL graphics system to work properly with GLES 2 without the FramebufferBlit extension swapBuffers() needs to preserve the back buffer. --- src/opengl/qwindowsurface_gl.cpp | 21 +++++++++++---------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 2f111f4..c732174 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -303,13 +303,10 @@ Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_window_surface_engine) QPaintEngine *QGLWindowSurface::paintEngine() const { #if !defined(QT_OPENGL_ES_2) - if (qt_gl_preferGL2Engine()) - return qt_gl_window_surface_2_engine(); - else + if (!qt_gl_preferGL2Engine()) return qt_gl_window_surface_engine(); -#else - return 0; #endif + return qt_gl_window_surface_2_engine(); } int QGLWindowSurface::metric(PaintDeviceMetric m) const @@ -370,6 +367,7 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & context()->makeCurrent(); if (context()->format().doubleBuffer()) { +#if !defined(QT_OPENGL_ES_2) glBindTexture(target, d_ptr->tex_id); QVector rects = d_ptr->paintedRegion.rects(); @@ -386,7 +384,6 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & QRegion dirtyRegion = QRegion(window()->rect()) - d_ptr->paintedRegion; -#if !defined(QT_OPENGL_ES_2) if (!dirtyRegion.isEmpty()) { context()->makeCurrent(); @@ -522,7 +519,12 @@ void QGLWindowSurface::updateGeometry() return; } - if ((QGLExtensions::glExtensions & QGLExtensions::FramebufferObject) && (d_ptr->fbo || !d_ptr->tried_fbo)) { + if ((QGLExtensions::glExtensions & QGLExtensions::FramebufferObject) +#ifdef QT_OPENGL_ES_2 + && (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit) +#endif + && (d_ptr->fbo || !d_ptr->tried_fbo)) + { d_ptr->tried_fbo = true; hijackWindow(window()); QGLContext *ctx = reinterpret_cast(window()->d_func()->extraData()->glContext); @@ -551,6 +553,7 @@ void QGLWindowSurface::updateGeometry() } } +#if !defined(QT_OPENGL_ES_2) if (d_ptr->pb || !d_ptr->tried_pb) { d_ptr->tried_pb = true; @@ -577,7 +580,6 @@ void QGLWindowSurface::updateGeometry() glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindTexture(target, 0); -#if !defined(QT_OPENGL_ES_2) glMatrixMode(GL_PROJECTION); glLoadIdentity(); #ifndef QT_OPENGL_ES @@ -585,7 +587,6 @@ void QGLWindowSurface::updateGeometry() #else glOrthof(0, d_ptr->pb->width(), d_ptr->pb->height(), 0, -999999, 999999); #endif -#endif // !defined(QT_OPENGL_ES_2) d_ptr->pb->d_ptr->qctx->d_func()->internal_context = true; return; @@ -595,7 +596,7 @@ void QGLWindowSurface::updateGeometry() d_ptr->pb = 0; } } - +#endif // !defined(QT_OPENGL_ES_2) hijackWindow(window()); QGLContext *ctx = reinterpret_cast(window()->d_func()->extraData()->glContext); -- cgit v0.12 From c8c5becc81679eb8a9a0f8baa454bc43fd3cccf9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 13 May 2009 14:47:54 +0200 Subject: Reverted use of GL 2 engine as default on desktop. Using GL 2 as default engine breaks the use cases where OpenGL commands are inter-mixed with QPainter commands, such as when using raw OpenGL in graphicsview. For now we'll use the old OpenGL engine for QGLWidget, QGLPixelBuffer, and QGLFramebufferObject on desktop, and the OpenGL 2 paint engine when the OpenGL graphics system is used. Reviewed-by: Trond --- src/opengl/qgl.cpp | 4 ++-- src/opengl/qgl_p.h | 5 ++--- src/opengl/qglframebufferobject.cpp | 3 ++- src/opengl/qglpixelbuffer.cpp | 2 +- src/opengl/qpixmapdata_gl.cpp | 8 ++++---- src/opengl/qwindowsurface_gl.cpp | 20 ++++---------------- 6 files changed, 15 insertions(+), 27 deletions(-) diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 779ed9a..12f781e 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -1366,7 +1366,7 @@ QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alp int w = size.width(); int h = size.height(); #if !defined(QT_OPENGL_ES_2) //### glGetTexImage not in GL ES 2.0, need to do something else here! - glGetTexImage(qt_gl_preferredTextureTarget(), 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); + glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); #endif convertFromGLImage(img, w, h, alpha_format, include_alpha); return img; @@ -1971,7 +1971,7 @@ GLuint QGLContextPrivate::bindTexture(const QPixmap &pixmap, GLenum target, GLin { Q_Q(QGLContext); QPixmapData *pd = pixmap.pixmapData(); - if (target == qt_gl_preferredTextureTarget() && pd->classId() == QPixmapData::OpenGLClass) { + if (target == GL_TEXTURE_2D && pd->classId() == QPixmapData::OpenGLClass) { const QGLPixmapData *data = static_cast(pd); if (data->isValidContext(q)) diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index 1513ee8..a294af9 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -424,9 +424,8 @@ inline bool qt_gl_preferGL2Engine() #if defined(QT_OPENGL_ES_2) return true; #else - QGLFormat::OpenGLVersionFlags flags = QGLFormat::openGLVersionFlags(); - bool hasOpenGL2 = (flags & QGLFormat::OpenGL_Version_2_0); - return hasOpenGL2 && qgetenv("QT_GL_NO_OPENGL2ENGINE").isEmpty(); + return (QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0) + && !qgetenv("QT_GL_USE_OPENGL2ENGINE").isEmpty(); #endif } diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 87e0dda..5f106ff 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -906,8 +906,9 @@ Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine) /*! \reimp */ QPaintEngine *QGLFramebufferObject::paintEngine() const { + Q_D(const QGLFramebufferObject); #if !defined(QT_OPENGL_ES_2) - if (qt_gl_preferGL2Engine()) + if (d->ctx->d_func()->internal_context || qt_gl_preferGL2Engine()) return qt_buffer_2_engine(); else return qt_buffer_engine(); diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp index cb24177..00b58d3 100644 --- a/src/opengl/qglpixelbuffer.cpp +++ b/src/opengl/qglpixelbuffer.cpp @@ -375,7 +375,7 @@ Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine) QPaintEngine *QGLPixelBuffer::paintEngine() const { #if !defined(QT_OPENGL_ES_2) - if (qt_gl_preferGL2Engine()) + if (d_ptr->qctx->d_func()->internal_context || qt_gl_preferGL2Engine()) return qt_buffer_2_engine(); else return qt_buffer_engine(); diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index 89e6749..e3af864 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -160,7 +160,7 @@ void QGLPixmapData::ensureCreated() const m_ctx = ctx; const GLenum format = qt_gl_preferredTextureFormat(); - const GLenum target = qt_gl_preferredTextureTarget(); + const GLenum target = GL_TEXTURE_2D; if (!m_textureId) { glGenTextures(1, &m_textureId); @@ -252,7 +252,7 @@ QImage QGLPixmapData::toImage() const QGLShareContextScope ctx(qt_gl_share_widget()->context()); extern QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alpha); - glBindTexture(qt_gl_preferredTextureTarget(), m_textureId); + glBindTexture(GL_TEXTURE_2D, m_textureId); return qt_gl_read_texture(QSize(m_width, m_height), true, true); } @@ -280,7 +280,7 @@ void QGLPixmapData::copyBackFromRenderFbo(bool keepCurrentFboBound) const glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->fbo); glFramebufferTexture2D(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, - qt_gl_preferredTextureTarget(), m_textureId, 0); + GL_TEXTURE_2D, m_textureId, 0); const int x0 = 0; const int x1 = m_width; @@ -398,7 +398,7 @@ GLuint QGLPixmapData::bind(bool copyBack) const ensureCreated(); GLuint id = m_textureId; - glBindTexture(qt_gl_preferredTextureTarget(), id); + glBindTexture(GL_TEXTURE_2D, id); return id; } diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index c732174..6fce3e3 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -72,10 +72,6 @@ #include -#ifndef QT_OPENGL_ES_2 -#include -#endif - #ifndef GLX_ARB_multisample #define GLX_SAMPLE_BUFFERS_ARB 100000 #define GLX_SAMPLES_ARB 100001 @@ -295,17 +291,9 @@ void QGLWindowSurface::hijackWindow(QWidget *widget) Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_window_surface_2_engine) -#ifndef QT_OPENGL_ES_2 -Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_window_surface_engine) -#endif - /*! \reimp */ QPaintEngine *QGLWindowSurface::paintEngine() const { -#if !defined(QT_OPENGL_ES_2) - if (!qt_gl_preferGL2Engine()) - return qt_gl_window_surface_engine(); -#endif return qt_gl_window_surface_2_engine(); } @@ -361,7 +349,7 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & QPoint wOffset = qt_qwidget_data(parent)->wrect.topLeft(); QRect rect = br.translated(-offset - wOffset); - const GLenum target = qt_gl_preferredTextureTarget(); + const GLenum target = GL_TEXTURE_2D; if (context()) { context()->makeCurrent(); @@ -502,7 +490,7 @@ void QGLWindowSurface::updateGeometry() { QRect rect = QWindowSurface::geometry(); - const GLenum target = qt_gl_preferredTextureTarget(); + const GLenum target = GL_TEXTURE_2D; if (rect.width() <= 0 || rect.height() <= 0) return; @@ -643,7 +631,7 @@ bool QGLWindowSurface::scroll(const QRegion &area, int dx, int dy) return true; #endif - const GLenum target = qt_gl_preferredTextureTarget(); + const GLenum target = GL_TEXTURE_2D; glBindTexture(target, d_ptr->tex_id); glCopyTexImage2D(target, 0, GL_RGBA, br.x(), d_ptr->pb->height() - (br.y() + br.height()), br.width(), br.height(), 0); @@ -656,7 +644,7 @@ bool QGLWindowSurface::scroll(const QRegion &area, int dx, int dy) static void drawTexture(const QRectF &rect, GLuint tex_id, const QSize &texSize, const QRectF &br) { - const GLenum target = qt_gl_preferredTextureTarget(); + const GLenum target = GL_TEXTURE_2D; QRectF src = br.isEmpty() ? QRectF(QPointF(), texSize) : QRectF(QPointF(br.x(), texSize.height() - br.bottom()), br.size()); -- cgit v0.12 From 521c5cc3910bffe566e0fb653041f159ecb5b6d5 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 14 May 2009 10:51:46 +0200 Subject: Make QtOpenGL compile on OpenGL ES 1.1 again --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 4 +- src/opengl/opengl.pro | 41 ++++++++------ src/opengl/qgl.cpp | 65 +++++++++++++++++----- src/opengl/qgl_p.h | 17 +++++- src/opengl/qglextensions_p.h | 5 +- src/opengl/qglframebufferobject.cpp | 10 +++- src/opengl/qglpixelbuffer.cpp | 10 +++- src/opengl/qpaintengine_opengl.cpp | 9 ++- 8 files changed, 116 insertions(+), 45 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 9f2384d..caf744a 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1331,10 +1331,10 @@ void QGL2PaintEngineExPrivate::updateDepthClip() return; } - glClearDepthf(0x0); + glClearDepth(0x0); glDepthMask(true); glClear(GL_DEPTH_BUFFER_BIT); - glClearDepthf(0x1); + glClearDepth(0x1); glEnable(GL_SCISSOR_TEST); for (int i = 0; i < rects.size(); ++i) { diff --git a/src/opengl/opengl.pro b/src/opengl/opengl.pro index 7eb2503..73af174 100644 --- a/src/opengl/opengl.pro +++ b/src/opengl/opengl.pro @@ -13,20 +13,14 @@ include(../qbase.pri) !win32:!embedded:!mac:CONFIG += x11 contains(QT_CONFIG, opengl):CONFIG += opengl contains(QT_CONFIG, opengles1):CONFIG += opengles1 +contains(QT_CONFIG, opengles1):CONFIG += opengles1cl contains(QT_CONFIG, opengles2):CONFIG += opengles2 -#!contains(QT_CONFIG, opengles2) { - HEADERS += qgraphicssystem_gl_p.h qwindowsurface_gl_p.h qpixmapdata_gl_p.h - SOURCES += qgraphicssystem_gl.cpp qwindowsurface_gl.cpp qpixmapdata_gl.cpp -#} - HEADERS += qgl.h \ qgl_p.h \ qglcolormap.h \ qglpixelbuffer.h \ qglframebufferobject.h \ - qglpixmapfilter_p.h \ - qglshaderprogram.h \ qglextensions_p.h SOURCES += qgl.cpp \ @@ -34,24 +28,35 @@ SOURCES += qgl.cpp \ qglpixelbuffer.cpp \ qglframebufferobject.cpp \ qglextensions.cpp \ - qglpixmapfilter.cpp \ - qglshaderprogram.cpp !contains(QT_CONFIG, opengles2) { HEADERS += qpaintengine_opengl_p.h SOURCES += qpaintengine_opengl.cpp } -SOURCES += gl2paintengineex/qglgradientcache.cpp \ - gl2paintengineex/qglengineshadermanager.cpp \ - gl2paintengineex/qgl2pexvertexarray.cpp \ - gl2paintengineex/qpaintengineex_opengl2.cpp +!contains(QT_CONFIG, opengles1):!contains(QT_CONFIG, opengles1cl) { + HEADERS += qglshaderprogram.h \ + qglpixmapfilter_p.h \ + qgraphicssystem_gl_p.h \ + qwindowsurface_gl_p.h \ + qpixmapdata_gl_p.h \ + gl2paintengineex/qglgradientcache_p.h \ + gl2paintengineex/qglengineshadermanager_p.h \ + gl2paintengineex/qgl2pexvertexarray_p.h \ + gl2paintengineex/qpaintengineex_opengl2_p.h \ + gl2paintengineex/qglengineshadersource_p.h + + SOURCES += qglshaderprogram.cpp \ + qglpixmapfilter.cpp \ + qgraphicssystem_gl.cpp \ + qwindowsurface_gl.cpp \ + qpixmapdata_gl.cpp \ + gl2paintengineex/qglgradientcache.cpp \ + gl2paintengineex/qglengineshadermanager.cpp \ + gl2paintengineex/qgl2pexvertexarray.cpp \ + gl2paintengineex/qpaintengineex_opengl2.cpp -HEADERS += gl2paintengineex/qglgradientcache_p.h \ - gl2paintengineex/qglengineshadermanager_p.h \ - gl2paintengineex/qgl2pexvertexarray_p.h \ - gl2paintengineex/qpaintengineex_opengl2_p.h \ - gl2paintengineex/qglengineshadersource_p.h +} x11 { contains(QT_CONFIG, opengles1)|contains(QT_CONFIG, opengles1cl)|contains(QT_CONFIG, opengles2) { diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 12f781e..a1f81ca 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -1365,7 +1365,8 @@ QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alp QImage img(size, alpha_format ? QImage::Format_ARGB32 : QImage::Format_RGB32); int w = size.width(); int h = size.height(); -#if !defined(QT_OPENGL_ES_2) //### glGetTexImage not in GL ES 2.0, need to do something else here! +#if !defined(QT_OPENGL_ES_2) && !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) + //### glGetTexImage not in GL ES 2.0, need to do something else here! glGetTexImage(GL_TEXTURE_2D, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.bits()); #endif convertFromGLImage(img, w, h, alpha_format, include_alpha); @@ -1971,12 +1972,14 @@ GLuint QGLContextPrivate::bindTexture(const QPixmap &pixmap, GLenum target, GLin { Q_Q(QGLContext); QPixmapData *pd = pixmap.pixmapData(); +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) if (target == GL_TEXTURE_2D && pd->classId() == QPixmapData::OpenGLClass) { const QGLPixmapData *data = static_cast(pd); if (data->isValidContext(q)) return data->bind(); } +#endif const qint64 key = pixmap.cacheKey(); GLuint id; @@ -4159,7 +4162,9 @@ void QGLWidget::drawTexture(const QPointF &point, QMacCompatGLuint textureId, QM } #endif +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_gl_2_engine) +#endif #ifndef QT_OPENGL_ES_2 Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_gl_engine) @@ -4184,11 +4189,16 @@ Q_OPENGL_EXPORT QPaintEngine* qt_qgl_paint_engine() */ QPaintEngine *QGLWidget::paintEngine() const { -#ifndef QT_OPENGL_ES_2 +#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL) + return qt_gl_engine(); +#elif defined(QT_OPENGL_ES_2) + return qt_gl_2_engine(); +#else if (!qt_gl_preferGL2Engine()) return qt_gl_engine(); + else + return qt_gl_2_engine(); #endif - return qt_gl_2_engine(); } #ifdef QT3_SUPPORT @@ -4338,6 +4348,7 @@ void QGLDrawable::setDevice(QPaintDevice *pdev) wsurf = 0; #endif +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) if (pdev->devType() == QInternal::Pixmap) { QPixmapData *data = static_cast(pdev)->pixmapData(); Q_ASSERT(data->classId() == QPixmapData::OpenGLClass); @@ -4345,6 +4356,9 @@ void QGLDrawable::setDevice(QPaintDevice *pdev) fbo = pixmapData->fbo(); } +#else + Q_ASSERT(pdev->devType() != QInternal::Pixmap); +#endif if (pdev->devType() == QInternal::Widget) widget = static_cast(pdev); @@ -4352,10 +4366,11 @@ void QGLDrawable::setDevice(QPaintDevice *pdev) buffer = static_cast(pdev); else if (pdev->devType() == QInternal::FramebufferObject) fbo = static_cast(pdev); - else if (pdev->devType() == QInternal::UnknownDevice) #ifdef Q_WS_QWS + else if (pdev->devType() == QInternal::UnknownDevice) wsurf = static_cast(pdev)->windowSurface(); -#else +#elif !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) + else if (pdev->devType() == QInternal::UnknownDevice) wsurf = static_cast(pdev); #endif } @@ -4365,8 +4380,10 @@ void QGLDrawable::swapBuffers() if (widget) { if (widget->autoBufferSwap()) widget->swapBuffers(); +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) } else if (pixmapData) { pixmapData->swapBuffers(); +#endif } else { glFlush(); } @@ -4374,14 +4391,18 @@ void QGLDrawable::swapBuffers() void QGLDrawable::makeCurrent() { - if (pixmapData) - pixmapData->makeCurrent(); - else if (widget) + if (widget) widget->makeCurrent(); +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) + else if (pixmapData) + pixmapData->makeCurrent(); +#endif else if (buffer) buffer->makeCurrent(); +#if defined(Q_WS_QWS) || (!defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)) else if (wsurf) wsurf->context()->makeCurrent(); +#endif else if (fbo) { wasBound = fbo->isBound(); if (!wasBound) @@ -4389,18 +4410,25 @@ void QGLDrawable::makeCurrent() } } +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) QGLPixmapData *QGLDrawable::copyOnBegin() const { if (!pixmapData || pixmapData->isUninitialized()) return 0; return pixmapData; } +#endif void QGLDrawable::doneCurrent() { - if (pixmapData) +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) + if (pixmapData) { pixmapData->doneCurrent(); - else if (fbo && !wasBound) + return; + } +#endif + + if (fbo && !wasBound) fbo->release(); } @@ -4409,19 +4437,22 @@ QSize QGLDrawable::size() const if (widget) { return QSize(widget->d_func()->glcx->device()->width(), widget->d_func()->glcx->device()->height()); +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) } else if (pixmapData) { return pixmapData->size(); +#endif } else if (buffer) { return buffer->size(); } else if (fbo) { return fbo->size(); - } else if (wsurf) { + } #ifdef Q_WS_QWS + else if (wsurf) return wsurf->window()->frameSize(); -#else +#elif !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) + else if (wsurf) return QSize(wsurf->width(), wsurf->height()); #endif - } return QSize(); } @@ -4431,8 +4462,10 @@ QGLFormat QGLDrawable::format() const return widget->format(); else if (buffer) return buffer->format(); +#if defined(Q_WS_QWS) || (!defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)) else if (wsurf) return wsurf->context()->format(); +#endif else if (fbo && QGLContext::currentContext()) { QGLFormat fmt = QGLContext::currentContext()->format(); fmt.setStencil(fbo->attachment() == QGLFramebufferObject::CombinedDepthStencil); @@ -4451,8 +4484,10 @@ GLuint QGLDrawable::bindTexture(const QImage &image, GLenum target, GLint format return buffer->d_func()->qctx->d_func()->bindTexture(image, target, format, true); else if (fbo && QGLContext::currentContext()) return const_cast(QGLContext::currentContext())->d_func()->bindTexture(image, target, format, true); +#if defined(Q_WS_QWS) || (!defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)) else if (wsurf) return wsurf->context()->d_func()->bindTexture(image, target, format, true); +#endif return 0; } @@ -4464,8 +4499,10 @@ GLuint QGLDrawable::bindTexture(const QPixmap &pixmap, GLenum target, GLint form return buffer->d_func()->qctx->d_func()->bindTexture(pixmap, target, format, true); else if (fbo && QGLContext::currentContext()) return const_cast(QGLContext::currentContext())->d_func()->bindTexture(pixmap, target, format, true); +#if defined(Q_WS_QWS) || (!defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)) else if (wsurf) return wsurf->context()->d_func()->bindTexture(pixmap, target, format, true); +#endif return 0; } @@ -4484,8 +4521,10 @@ QGLContext *QGLDrawable::context() const return buffer->d_func()->qctx; else if (fbo) return const_cast(QGLContext::currentContext()); +#if defined(Q_WS_QWS) || (!defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)) else if (wsurf) return wsurf->context(); +#endif return 0; } diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index a294af9..b421eee 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -60,7 +60,10 @@ #include "QtCore/qthreadstorage.h" #include "QtCore/qhash.h" #include "private/qwidget_p.h" + +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) #include "private/qpixmapdata_gl_p.h" +#endif #ifndef QT_OPENGL_ES_1_CL #define q_vertexType float @@ -293,7 +296,12 @@ class QGLWindowSurface; class QGLDrawable { public: QGLDrawable() : widget(0), buffer(0), fbo(0) - , wsurf(0), pixmapData(0) +#if defined(Q_WS_QWS) || (!defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL)) + , wsurf(0) +#endif +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) + , pixmapData(0) +#endif {} void setDevice(QPaintDevice *pdev); void swapBuffers(); @@ -307,7 +315,9 @@ public: QGLContext *context() const; bool autoFillBackground() const; +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) QGLPixmapData *copyOnBegin() const; +#endif private: bool wasBound; @@ -316,10 +326,13 @@ private: QGLFramebufferObject *fbo; #ifdef Q_WS_QWS QWSGLWindowSurface *wsurf; -#else +#elif !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) QGLWindowSurface *wsurf; #endif + +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) QGLPixmapData *pixmapData; +#endif }; // GL extension definitions diff --git a/src/opengl/qglextensions_p.h b/src/opengl/qglextensions_p.h index 46047ef..d6edfb6 100644 --- a/src/opengl/qglextensions_p.h +++ b/src/opengl/qglextensions_p.h @@ -705,7 +705,10 @@ struct QGLExtensionFuncs #if !defined(QT_OPENGL_ES_2) #define glStencilOpSeparate QGLContextPrivate::qt_get_extension_funcs(ctx).qt_glStencilOpSeparate -#define glClearDepthf(x) glClearDepth(GLdouble(x)) +#endif + +#if defined(QT_OPENGL_ES_2) +#define glClearDepth glClearDepthf #endif extern bool qt_resolve_framebufferobject_extensions(QGLContext *ctx); diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 5f106ff..f6857ac 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -897,7 +897,9 @@ QImage QGLFramebufferObject::toImage() const return image; } +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_2_engine) +#endif #ifndef QT_OPENGL_ES_2 Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine) @@ -906,14 +908,16 @@ Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine) /*! \reimp */ QPaintEngine *QGLFramebufferObject::paintEngine() const { +#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL) + return qt_buffer_engine(); +#elif defined(QT_OPENGL_ES_2) + return qt_buffer_2_engine(); +#else Q_D(const QGLFramebufferObject); -#if !defined(QT_OPENGL_ES_2) if (d->ctx->d_func()->internal_context || qt_gl_preferGL2Engine()) return qt_buffer_2_engine(); else return qt_buffer_engine(); -#else - return 0; #endif } diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp index 00b58d3..ce7e9bd 100644 --- a/src/opengl/qglpixelbuffer.cpp +++ b/src/opengl/qglpixelbuffer.cpp @@ -365,7 +365,9 @@ bool QGLPixelBuffer::isValid() const return !d->invalid; } +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) Q_GLOBAL_STATIC(QGL2PaintEngineEx, qt_buffer_2_engine) +#endif #ifndef QT_OPENGL_ES_2 Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine) @@ -374,13 +376,15 @@ Q_GLOBAL_STATIC(QOpenGLPaintEngine, qt_buffer_engine) /*! \reimp */ QPaintEngine *QGLPixelBuffer::paintEngine() const { -#if !defined(QT_OPENGL_ES_2) +#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_1_CL) + return qt_buffer_engine(); +#elif defined(QT_OPENGL_ES_2) + return qt_buffer_2_engine(); +#else if (d_ptr->qctx->d_func()->internal_context || qt_gl_preferGL2Engine()) return qt_buffer_2_engine(); else return qt_buffer_engine(); -#else - return 0; #endif } diff --git a/src/opengl/qpaintengine_opengl.cpp b/src/opengl/qpaintengine_opengl.cpp index 0f447d3..d28a495 100644 --- a/src/opengl/qpaintengine_opengl.cpp +++ b/src/opengl/qpaintengine_opengl.cpp @@ -2255,11 +2255,12 @@ void QOpenGLPaintEnginePrivate::updateDepthClip() return; } -#ifndef QT_OPENGL_ES - glClearDepth(0.0f); -#else +#if defined(QT_OPENGL_ES_1) || defined(QT_OPENGL_ES_2) || defined(QT_OPENGL_ES_1_CL) glClearDepthf(0.0f); +#else + glClearDepth(0.0f); #endif + glEnable(GL_DEPTH_TEST); glDepthMask(GL_TRUE); glClear(GL_DEPTH_BUFFER_BIT); @@ -5580,9 +5581,11 @@ void QOpenGLPaintEnginePrivate::ensureDrawableTexture() QPixmapFilter *QOpenGLPaintEngine::createPixmapFilter(int type) const { +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) if (QGLContext::currentContext()) return QGLContext::currentContext()->d_func()->createPixmapFilter(type); else +#endif return 0; } -- cgit v0.12 From 889316a3f57b57160e2a08fc41def774d56e288c Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Thu, 14 May 2009 15:53:44 +0200 Subject: Start work on docs for Stickman example --- examples/animation/stickman/lifecycle.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/animation/stickman/lifecycle.cpp b/examples/animation/stickman/lifecycle.cpp index 423d7ad..6b69a26 100644 --- a/examples/animation/stickman/lifecycle.cpp +++ b/examples/animation/stickman/lifecycle.cpp @@ -141,9 +141,10 @@ LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) m_alive->setInitialState(m_idle); // Lightning strikes at random +//! [0] m_alive->addTransition(new LightningStrikesTransition(lightningBlink)); - //m_alive->addTransition(new KeyPressTransition(m_keyReceiver, Qt::Key_L, lightningBlink)); connectByAnimation(lightningBlink, m_dead, new QSignalTransition(timer, SIGNAL(timeout()))); +//! [0] m_machine->setInitialState(m_alive); } @@ -159,8 +160,8 @@ void LifeCycle::start() m_machine->start(); } -void LifeCycle::connectByAnimation(QState *s1, QAbstractState *s2, - QAbstractTransition *transition) +//! [1] +void LifeCycle::connectByAnimation(QState *s1, QAbstractState *s2, QAbstractTransition *transition) { if (transition == 0) { transition = s1->addTransition(s2); @@ -170,6 +171,7 @@ void LifeCycle::connectByAnimation(QState *s1, QAbstractState *s2, } transition->addAnimation(m_animationGroup); } +//! [1] void LifeCycle::addActivity(const QString &fileName, Qt::Key key) { -- cgit v0.12 From 9400e522d7b89025157657ec87fb1631fc6bf4de Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Thu, 14 May 2009 16:50:23 +0200 Subject: Remove the connectByAnimation() function and add some documentation for the Stickman example The connectByAnimation() function is no longer needed since we have default animations. The docs are unfinished. --- doc/src/examples/stickman.qdoc | 115 ++++++++++++++++++++++++++++++ doc/src/images/stickman-example.png | Bin 0 -> 18867 bytes doc/src/images/stickman-example1.png | Bin 0 -> 8311 bytes examples/animation/stickman/lifecycle.cpp | 48 ++++++------- examples/animation/stickman/lifecycle.h | 2 - 5 files changed, 137 insertions(+), 28 deletions(-) create mode 100644 doc/src/examples/stickman.qdoc create mode 100644 doc/src/images/stickman-example.png create mode 100644 doc/src/images/stickman-example1.png diff --git a/doc/src/examples/stickman.qdoc b/doc/src/examples/stickman.qdoc new file mode 100644 index 0000000..0313c81 --- /dev/null +++ b/doc/src/examples/stickman.qdoc @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example animation/stickman + \title Stickman Example + + The Stickman example shows how to animate transitions in a state machine to implement key frame + animations. + + \image stickman-example.png + + In this example, we will write a small application which animates the joints in a skeleton and + projects a stickman figure on top. The stickman can be either "alive" or "dead", and when in the + "alive" state, he can be performing different actions defined by key frame animations. + + Animations are implemented as composite states. Each child state of the animation state + represents a frame in the animation by setting the position of each joint in the stickman's + skeleton to the positions defined for the particular frame. The frames are then bound together + with animated transitions that trigger on the source state's polished() signal. Thus, the + machine will enter the state representing the next state in the animation immediately after it + has finished animating into the previous frame. + + \image stickman-example1.png + + The states for an animation is constructed by reading a custom animation file format and + creating states that assign values to the the "position" properties of each of the nodes in the + skeleton graph. + + \snippet examples/animation/stickman/lifecycle.cpp 1 + + The states are then bound together with signal transitions that listen to the polished() signal. + + \snippet examples/animation/stickman/lifecycle.cpp 2 + + The last frame state is given a transition to the first one, so that the animation will loop + until it is interrupted when a transition out from the animation state is taken. To get smooth + animations between the different key frames, we set a default animation on the state machine. + This is a parallel animation group which contain animations for all the "position" properties + and will be selected by default when taking any transition that leads into a state that assigns + values to these properties. + + \snippet examples/animation/stickman/lifecycle.cpp 3 + + Several such animation states are constructed, and are placed together as children of a top + level "alive" state which represents the stickman life cycle. Transitions go from the parent + state to the child state to ensure that each of the child states inherit them. + + \image stickman-example2.png + + This saves us the effort of connect every state to every state with identical transitions. The + state machine makes sure that transitions between the key frame animations are also smooth by + applying the default animation when interrupting one and starting another. + + Finally, there is a transition out from the "alive" state and into the "dead" state. This is + a custom transition type called LightningStrikesTransition which samples every second and + triggers at random (one out of fifty times on average.) + + \snippet examples/animation/stickman/lifecycle.cpp 4 + + When it triggers, the machine will first enter a "lightningStrike" state which uses a timer to + pause for a brief period of time while the background color of the scene is white. This gives us + a flash effect when the lightning strikes. + + \snippet examples/animation/stickman/lifecycle.cpp 5 + + We start and stop a QTimer object when entering and exiting the state. Then we transition into + the "dead" state when the timer times out. + + \snippet examples/animation/stickman/lifecycle.cpp 0 + + When the machine is in the "dead" state, it will be unresponsive. This is because the "dead" + state has no transitions leading out. + + \image stickman-example3.png + +*/ diff --git a/doc/src/images/stickman-example.png b/doc/src/images/stickman-example.png new file mode 100644 index 0000000..a40f37b Binary files /dev/null and b/doc/src/images/stickman-example.png differ diff --git a/doc/src/images/stickman-example1.png b/doc/src/images/stickman-example1.png new file mode 100644 index 0000000..7b9a5b8 Binary files /dev/null and b/doc/src/images/stickman-example1.png differ diff --git a/examples/animation/stickman/lifecycle.cpp b/examples/animation/stickman/lifecycle.cpp index 6b69a26..1feb31d 100644 --- a/examples/animation/stickman/lifecycle.cpp +++ b/examples/animation/stickman/lifecycle.cpp @@ -82,6 +82,7 @@ private: Qt::Key m_key; }; +//! [4] class LightningStrikesTransition: public QEventTransition { public: @@ -97,6 +98,7 @@ public: return QEventTransition::eventTest(e) && ((qrand() % 50) == 0); } }; +//! [4] LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) : m_stickMan(stickMan), m_keyReceiver(keyReceiver) @@ -110,7 +112,10 @@ LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) } // Set up intial state graph +//! [3] m_machine = new QStateMachine(); + m_machine->addDefaultAnimation(m_animationGroup); +//! [3] m_alive = new QState(m_machine->rootState()); m_alive->setObjectName("alive"); @@ -122,11 +127,13 @@ LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) lightningBlink->assignProperty(m_stickMan, "fillColor", Qt::white); lightningBlink->assignProperty(m_stickMan, "isDead", true); +//! [5] QTimer *timer = new QTimer(lightningBlink); timer->setSingleShot(true); timer->setInterval(100); QObject::connect(lightningBlink, SIGNAL(entered()), timer, SLOT(start())); QObject::connect(lightningBlink, SIGNAL(exited()), timer, SLOT(stop())); +//! [5] m_dead = new QState(m_machine->rootState()); m_dead->assignProperty(m_stickMan->scene(), "backgroundBrush", Qt::black); @@ -141,9 +148,9 @@ LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) m_alive->setInitialState(m_idle); // Lightning strikes at random -//! [0] m_alive->addTransition(new LightningStrikesTransition(lightningBlink)); - connectByAnimation(lightningBlink, m_dead, new QSignalTransition(timer, SIGNAL(timeout()))); +//! [0] + lightningBlink->addTransition(timer, SIGNAL(timeout()), m_dead); //! [0] m_machine->setInitialState(m_alive); @@ -160,23 +167,10 @@ void LifeCycle::start() m_machine->start(); } -//! [1] -void LifeCycle::connectByAnimation(QState *s1, QAbstractState *s2, QAbstractTransition *transition) -{ - if (transition == 0) { - transition = s1->addTransition(s2); - } else { - transition->setTargetState(s2); - s1->addTransition(transition); - } - transition->addAnimation(m_animationGroup); -} -//! [1] - void LifeCycle::addActivity(const QString &fileName, Qt::Key key) { QState *state = makeState(m_alive, fileName); - connectByAnimation(m_alive, state, new KeyPressTransition(m_keyReceiver, key)); + m_alive->addTransition(new KeyPressTransition(m_keyReceiver, key, state)); } QState *LifeCycle::makeState(QState *parentState, const QString &animationFileName) @@ -193,26 +187,28 @@ QState *LifeCycle::makeState(QState *parentState, const QString &animationFileNa const int frameCount = animation.totalFrames(); QState *previousState = 0; for (int i=0; isetObjectName(QString::fromLatin1("frame %0").arg(i)); - animation.setCurrentFrame(i); + +//! [1] + QState *frameState = new QState(topLevel); const int nodeCount = animation.nodeCount(); for (int j=0; jassignProperty(m_stickMan->node(j), "position", animation.nodePos(j)); +//! [1] - if (previousState == 0) { + frameState->setObjectName(QString::fromLatin1("frame %0").arg(i)); + if (previousState == 0) topLevel->setInitialState(frameState); - } else { - connectByAnimation(previousState, frameState, - new QSignalTransition(previousState, SIGNAL(polished()))); - } + else +//! [2] + previousState->addTransition(previousState, SIGNAL(polished()), frameState); +//! [2] + previousState = frameState; } // Loop - connectByAnimation(previousState, topLevel->initialState(), - new QSignalTransition(previousState, SIGNAL(polished()))); + previousState->addTransition(previousState, SIGNAL(polished()), topLevel->initialState()); return topLevel; diff --git a/examples/animation/stickman/lifecycle.h b/examples/animation/stickman/lifecycle.h index e520402..8fd0fb2 100644 --- a/examples/animation/stickman/lifecycle.h +++ b/examples/animation/stickman/lifecycle.h @@ -63,8 +63,6 @@ public: void start(); private: - void connectByAnimation(QState *s1, QAbstractState *s2, - QAbstractTransition *transition = 0); QState *makeState(QState *parentState, const QString &animationFileName); StickMan *m_stickMan; -- cgit v0.12 From 7f0b4d3b99bb767724a09234768104e18aa52b0e Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 15 May 2009 10:54:27 +0200 Subject: Fix GL2 paint engine builds on Big-endian machines Reviewed-by: Trond --- src/opengl/gl2paintengineex/qglgradientcache.cpp | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglgradientcache.cpp b/src/opengl/gl2paintengineex/qglgradientcache.cpp index 59d4bf8..2239c2f 100644 --- a/src/opengl/gl2paintengineex/qglgradientcache.cpp +++ b/src/opengl/gl2paintengineex/qglgradientcache.cpp @@ -109,21 +109,18 @@ GLuint QGL2GradientCache::addCacheElement(quint64 hash_val, const QGradient &gra } -// GL's expects pixels in RGBA, bin-endian (ABGR on x86). -// Qt stores in ARGB using whatever byte-order the mancine uses. +// GL's expects pixels in RGBA (when using GL_RGBA), bin-endian (ABGR on x86). +// Qt always stores in ARGB reguardless of the byte-order the mancine uses. static inline uint qtToGlColor(uint c) { uint o; #if Q_BYTE_ORDER == Q_LITTLE_ENDIAN - o = c & 0xFF00FF00; // alpha & green already in the right place - o |= (c >> 16) & 0x000000FF; // red - o |= (c << 16) & 0x00FF0000; // blue - + o = (c & 0xff00ff00) // alpha & green already in the right place + | ((c >> 16) & 0x000000ff) // red + | ((c << 16) & 0x00ff0000); // blue #else //Q_BIG_ENDIAN - o = c & 0x00FF00FF; // alpha & green already in the right place - o |= (c << 16) & 0xFF000000; // red - o |= (c >> 16) & 0x0000FF00; // blue -#error big endian not tested with QGLGraphicsContext + o = (c << 8) + | ((c >> 24) & 0x000000ff); #endif // Q_BYTE_ORDER return o; } @@ -136,7 +133,7 @@ void QGL2GradientCache::generateGradientColorTable(const QGradient& gradient, ui QVector colors(s.size()); for (int i = 0; i < s.size(); ++i) - colors[i] = s[i].second.rgba(); // Qt LIES! It returns ARGB + colors[i] = s[i].second.rgba(); // Qt LIES! It returns ARGB (on little-endian AND on big-endian) bool colorInterpolation = (gradient.interpolationMode() == QGradient::ColorInterpolation); -- cgit v0.12 From b8058b594534050909cf0dfc6b4be2a1b6a4dc1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 15 May 2009 13:52:55 +0200 Subject: Prevented QClipData related crashes. --- src/gui/painting/qpaintengine_raster.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 87e9283..0e8f50a 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -4344,6 +4344,7 @@ void QClipData::initialize() m_clipLines = (ClipLine *)calloc(sizeof(ClipLine), clipSpanHeight); m_spans = (QSpan *)malloc(clipSpanHeight*sizeof(QSpan)); + allocated = clipSpanHeight; if (hasRectClip) { int y = 0; @@ -4388,6 +4389,7 @@ void QClipData::initialize() int y = 0; int firstInBand = 0; + count = 0; while (firstInBand < numRects) { const int currMinY = rects.at(firstInBand).y(); const int currMaxY = currMinY + rects.at(firstInBand).height(); @@ -4502,7 +4504,7 @@ void QClipData::setClipRect(const QRect &rect) ymax = qMin(rect.y() + rect.height(), clipSpanHeight); if (m_spans) { - delete m_spans; + free(m_spans); m_spans = 0; } @@ -4532,7 +4534,7 @@ void QClipData::setClipRegion(const QRegion ®ion) } if (m_spans) { - delete m_spans; + free(m_spans); m_spans = 0; } -- cgit v0.12 From a5a842b3aa3e4033a116275c04b17d37d5595cc5 Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Fri, 15 May 2009 16:45:47 +0200 Subject: doc: Update signature of eventTest() in documentation eventTest() is now non-const. --- src/corelib/statemachine/qabstracttransition.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/statemachine/qabstracttransition.cpp b/src/corelib/statemachine/qabstracttransition.cpp index a930581..68423cb 100644 --- a/src/corelib/statemachine/qabstracttransition.cpp +++ b/src/corelib/statemachine/qabstracttransition.cpp @@ -321,7 +321,7 @@ QList QAbstractTransition::animations() const #endif /*! - \fn QAbstractTransition::eventTest(QEvent *event) const + \fn QAbstractTransition::eventTest(QEvent *event) This function is called to determine whether the given \a event should cause this transition to trigger. Reimplement this function and return true if the -- cgit v0.12 From c11b50366069b9c5a0daa74dc3511d91ceafe564 Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Fri, 15 May 2009 17:01:37 +0200 Subject: doc: New state chart diagrams for Stickman example These obviously cannot be used, since they have the "unregistered version" watermark on them. Didn't notice before now, so I might as well commit them for the time being. --- doc/src/images/stickman-example1.png | Bin 8311 -> 33216 bytes doc/src/images/stickman-example2.png | Bin 0 -> 23521 bytes doc/src/images/stickman-example3.png | Bin 0 -> 12265 bytes 3 files changed, 0 insertions(+), 0 deletions(-) create mode 100644 doc/src/images/stickman-example2.png create mode 100644 doc/src/images/stickman-example3.png diff --git a/doc/src/images/stickman-example1.png b/doc/src/images/stickman-example1.png index 7b9a5b8..8ee364b 100644 Binary files a/doc/src/images/stickman-example1.png and b/doc/src/images/stickman-example1.png differ diff --git a/doc/src/images/stickman-example2.png b/doc/src/images/stickman-example2.png new file mode 100644 index 0000000..0e4c57d Binary files /dev/null and b/doc/src/images/stickman-example2.png differ diff --git a/doc/src/images/stickman-example3.png b/doc/src/images/stickman-example3.png new file mode 100644 index 0000000..62f41eb Binary files /dev/null and b/doc/src/images/stickman-example3.png differ -- cgit v0.12 From ad17d5fcaa5984e7f11e3c8a514a24264890c827 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 18 May 2009 14:06:31 +0200 Subject: Fixed access to members of an object. Reviewed-by: David Boddie --- doc/src/animation.qdoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/src/animation.qdoc b/doc/src/animation.qdoc index f3baf71..b4e603c 100644 --- a/doc/src/animation.qdoc +++ b/doc/src/animation.qdoc @@ -271,10 +271,10 @@ \code QPushButton *bonnie = new QPushButton("Bonnie"); - bonnie.show(); + bonnie->show(); QPushButton *clyde = new QPushButton("Clyde"); - clyde.show(); + clyde->show(); QPropertyAnimation *anim1 = new QPropertyAnimation(bonnie, "geometry"); // Set up anim1 -- cgit v0.12 From 3d99537a86144b8f22ef10891ba6cc55820b987a Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Mon, 18 May 2009 14:24:58 +0200 Subject: doc: Minor fixes + update UML diagrams for stick man example Using StarUML this time, since there were "unregistered version" watermarks on the Enterprise Architect ones. Not as nice, but it's impossible to find a free UML tool which produces nice diagrams. --- doc/src/examples.qdoc | 6 ++++++ doc/src/examples/stickman.qdoc | 8 ++++---- doc/src/images/stickman-example1.png | Bin 33216 -> 64543 bytes doc/src/images/stickman-example2.png | Bin 23521 -> 37412 bytes doc/src/images/stickman-example3.png | Bin 12265 -> 23591 bytes 5 files changed, 10 insertions(+), 4 deletions(-) diff --git a/doc/src/examples.qdoc b/doc/src/examples.qdoc index 6603390..c55d29f 100644 --- a/doc/src/examples.qdoc +++ b/doc/src/examples.qdoc @@ -86,6 +86,12 @@ \o \l{activeqt/webbrowser}{Web Browser}\raisedaster \o \l{activeqt/wrapper}{Wrapper}\raisedaster \endlist + + \section1 Animation + + \list + \o \l{animation/stickman}{Stick man}\raisedaster + \endlist \section1 Concurrent Programming diff --git a/doc/src/examples/stickman.qdoc b/doc/src/examples/stickman.qdoc index 0313c81..49f4953 100644 --- a/doc/src/examples/stickman.qdoc +++ b/doc/src/examples/stickman.qdoc @@ -56,7 +56,7 @@ represents a frame in the animation by setting the position of each joint in the stickman's skeleton to the positions defined for the particular frame. The frames are then bound together with animated transitions that trigger on the source state's polished() signal. Thus, the - machine will enter the state representing the next state in the animation immediately after it + machine will enter the state representing the next frame in the animation immediately after it has finished animating into the previous frame. \image stickman-example1.png @@ -74,7 +74,7 @@ The last frame state is given a transition to the first one, so that the animation will loop until it is interrupted when a transition out from the animation state is taken. To get smooth animations between the different key frames, we set a default animation on the state machine. - This is a parallel animation group which contain animations for all the "position" properties + This is a parallel animation group which contains animations for all the "position" properties and will be selected by default when taking any transition that leads into a state that assigns values to these properties. @@ -91,12 +91,12 @@ applying the default animation when interrupting one and starting another. Finally, there is a transition out from the "alive" state and into the "dead" state. This is - a custom transition type called LightningStrikesTransition which samples every second and + a custom transition type called LightningSrikesTransition which samples every second and triggers at random (one out of fifty times on average.) \snippet examples/animation/stickman/lifecycle.cpp 4 - When it triggers, the machine will first enter a "lightningStrike" state which uses a timer to + When it triggers, the machine will first enter a "lightningBlink" state which uses a timer to pause for a brief period of time while the background color of the scene is white. This gives us a flash effect when the lightning strikes. diff --git a/doc/src/images/stickman-example1.png b/doc/src/images/stickman-example1.png index 8ee364b..1596a68 100644 Binary files a/doc/src/images/stickman-example1.png and b/doc/src/images/stickman-example1.png differ diff --git a/doc/src/images/stickman-example2.png b/doc/src/images/stickman-example2.png index 0e4c57d..980276a 100644 Binary files a/doc/src/images/stickman-example2.png and b/doc/src/images/stickman-example2.png differ diff --git a/doc/src/images/stickman-example3.png b/doc/src/images/stickman-example3.png index 62f41eb..3635ff7 100644 Binary files a/doc/src/images/stickman-example3.png and b/doc/src/images/stickman-example3.png differ -- cgit v0.12 From 7c77f60643d14864e579eeddb95ec54c8c963fd9 Mon Sep 17 00:00:00 2001 From: David Faure Date: Mon, 18 May 2009 19:06:10 +0200 Subject: remove unused line (the function is even in qtgui nowadays) --- src/corelib/kernel/qtranslator.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/corelib/kernel/qtranslator.cpp b/src/corelib/kernel/qtranslator.cpp index 77d6599..308ca24 100644 --- a/src/corelib/kernel/qtranslator.cpp +++ b/src/corelib/kernel/qtranslator.cpp @@ -206,8 +206,6 @@ static int numerusHelper(int n, const uchar *rules, int rulesSize) return -1; } -extern bool qt_detectRTLLanguage(); - class QTranslatorPrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QTranslator) -- cgit v0.12 From 8ef2feacb26eabdc6e82c4a85b6f3e30665477ba Mon Sep 17 00:00:00 2001 From: Leonardo Sobral Cunha Date: Tue, 19 May 2009 13:35:24 +0200 Subject: Whitespace cleanup in QEasingCurve --- src/corelib/tools/qeasingcurve.cpp | 89 +++++++++++++++++++------------------- 1 file changed, 44 insertions(+), 45 deletions(-) diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp index a1a0d1f..72965de5 100644 --- a/src/corelib/tools/qeasingcurve.cpp +++ b/src/corelib/tools/qeasingcurve.cpp @@ -99,7 +99,7 @@ \br Easing equation function for a simple linear tweening, with no easing. - \value InQuad \inlineimage qeasingcurve-inquad.png + \value InQuad \inlineimage qeasingcurve-inquad.png \br Easing equation function for a quadratic (t^2) easing in: accelerating from zero velocity. @@ -107,7 +107,7 @@ \br Easing equation function for a quadratic (t^2) easing out: decelerating to zero velocity. - \value InOutQuad \inlineimage qeasingcurve-inoutquad.png + \value InOutQuad \inlineimage qeasingcurve-inoutquad.png \br Easing equation function for a quadratic (t^2) easing in/out: acceleration until halfway, then deceleration. @@ -121,11 +121,11 @@ in: accelerating from zero velocity. \value OutCubic \inlineimage qeasingcurve-outcubic.png \br - Easing equation function for a cubic (t^3) easing + Easing equation function for a cubic (t^3) easing out: decelerating from zero velocity. \value InOutCubic \inlineimage qeasingcurve-inoutcubic.png \br - Easing equation function for a cubic (t^3) easing + Easing equation function for a cubic (t^3) easing in/out: acceleration until halfway, then deceleration. \value OutInCubic \inlineimage qeasingcurve-outincubic.png \br @@ -133,55 +133,55 @@ out/in: deceleration until halfway, then acceleration. \value InQuart \inlineimage qeasingcurve-inquart.png \br - Easing equation function for a quartic (t^4) easing + Easing equation function for a quartic (t^4) easing in: accelerating from zero velocity. \value OutQuart \inlineimage qeasingcurve-outquart.png \br - Easing equation function for a quartic (t^4) easing + Easing equation function for a quartic (t^4) easing out: decelerating from zero velocity. \value InOutQuart \inlineimage qeasingcurve-inoutquart.png \br - Easing equation function for a quartic (t^4) easing + Easing equation function for a quartic (t^4) easing in/out: acceleration until halfway, then deceleration. \value OutInQuart \inlineimage qeasingcurve-outinquart.png \br - Easing equation function for a quartic (t^4) easing + Easing equation function for a quartic (t^4) easing out/in: deceleration until halfway, then acceleration. \value InQuint \inlineimage qeasingcurve-inquint.png \br - Easing equation function for a quintic (t^5) easing + Easing equation function for a quintic (t^5) easing in: accelerating from zero velocity. \value OutQuint \inlineimage qeasingcurve-outquint.png \br - Easing equation function for a quintic (t^5) easing + Easing equation function for a quintic (t^5) easing out: decelerating from zero velocity. \value InOutQuint \inlineimage qeasingcurve-inoutquint.png \br - Easing equation function for a quintic (t^5) easing + Easing equation function for a quintic (t^5) easing in/out: acceleration until halfway, then deceleration. \value OutInQuint \inlineimage qeasingcurve-outinquint.png \br - Easing equation function for a quintic (t^5) easing + Easing equation function for a quintic (t^5) easing out/in: deceleration until halfway, then acceleration. \value InSine \inlineimage qeasingcurve-insine.png \br - Easing equation function for a sinusoidal (sin(t)) easing + Easing equation function for a sinusoidal (sin(t)) easing in: accelerating from zero velocity. \value OutSine \inlineimage qeasingcurve-outsine.png \br - Easing equation function for a sinusoidal (sin(t)) easing + Easing equation function for a sinusoidal (sin(t)) easing out: decelerating from zero velocity. \value InOutSine \inlineimage qeasingcurve-inoutsine.png \br - Easing equation function for a sinusoidal (sin(t)) easing + Easing equation function for a sinusoidal (sin(t)) easing in/out: acceleration until halfway, then deceleration. \value OutInSine \inlineimage qeasingcurve-outinsine.png \br - Easing equation function for a sinusoidal (sin(t)) easing + Easing equation function for a sinusoidal (sin(t)) easing out/in: deceleration until halfway, then acceleration. \value InExpo \inlineimage qeasingcurve-inexpo.png \br - Easing equation function for an exponential (2^t) easing + Easing equation function for an exponential (2^t) easing in: accelerating from zero velocity. \value OutExpo \inlineimage qeasingcurve-outexpo.png \br @@ -213,47 +213,47 @@ out/in: deceleration until halfway, then acceleration. \value InElastic \inlineimage qeasingcurve-inelastic.png \br - Easing equation function for an elastic - (exponentially decaying sine wave) easing in: + Easing equation function for an elastic + (exponentially decaying sine wave) easing in: accelerating from zero velocity. The peak amplitude can be set with the \e amplitude parameter, and the period of decay by the \e period parameter. \value OutElastic \inlineimage qeasingcurve-outelastic.png \br - Easing equation function for an elastic - (exponentially decaying sine wave) easing out: - decelerating from zero velocity. The peak amplitude - can be set with the \e amplitude parameter, and the + Easing equation function for an elastic + (exponentially decaying sine wave) easing out: + decelerating from zero velocity. The peak amplitude + can be set with the \e amplitude parameter, and the period of decay by the \e period parameter. \value InOutElastic \inlineimage qeasingcurve-inoutelastic.png \br - Easing equation function for an elastic - (exponentially decaying sine wave) easing in/out: + Easing equation function for an elastic + (exponentially decaying sine wave) easing in/out: acceleration until halfway, then deceleration. \value OutInElastic \inlineimage qeasingcurve-outinelastic.png \br - Easing equation function for an elastic - (exponentially decaying sine wave) easing out/in: + Easing equation function for an elastic + (exponentially decaying sine wave) easing out/in: deceleration until halfway, then acceleration. \value InBack \inlineimage qeasingcurve-inback.png \br - Easing equation function for a back (overshooting - cubic easing: (s+1)*t^3 - s*t^2) easing in: + Easing equation function for a back (overshooting + cubic easing: (s+1)*t^3 - s*t^2) easing in: accelerating from zero velocity. \value OutBack \inlineimage qeasingcurve-outback.png \br - Easing equation function for a back (overshooting - cubic easing: (s+1)*t^3 - s*t^2) easing out: + Easing equation function for a back (overshooting + cubic easing: (s+1)*t^3 - s*t^2) easing out: decelerating from zero velocity. \value InOutBack \inlineimage qeasingcurve-inoutback.png \br - Easing equation function for a back (overshooting - cubic easing: (s+1)*t^3 - s*t^2) easing in/out: + Easing equation function for a back (overshooting + cubic easing: (s+1)*t^3 - s*t^2) easing in/out: acceleration until halfway, then deceleration. \value OutInBack \inlineimage qeasingcurve-outinback.png \br - Easing equation function for a back (overshooting - cubic easing: (s+1)*t^3 - s*t^2) easing out/in: + Easing equation function for a back (overshooting + cubic easing: (s+1)*t^3 - s*t^2) easing out/in: deceleration until halfway, then acceleration. \value InBounce \inlineimage qeasingcurve-inbounce.png \br @@ -283,14 +283,13 @@ \omitvalue NCurveTypes */ -/*! +/*! \typedef QEasingCurve::EasingFunction This is a typedef for a pointer to a function with the following signature: \snippet doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp 0 - */ #include "qeasingcurve.h" @@ -646,10 +645,10 @@ bool QEasingCurve::operator==(const QEasingCurve &other) const \fn bool QEasingCurve::operator!=(const QEasingCurve &other) const Compare this easing curve with \a other and returns true if they are not equal. It will also compare the properties of a curve. - + \sa operator==() */ - + /*! Returns the amplitude. This is not applicable for all curve types. It is only applicable for bounce and elastic curves (curves of type() @@ -664,8 +663,8 @@ qreal QEasingCurve::amplitude() const /*! Sets the amplitude to \a amplitude. - - This will set the amplitude of the bounce or the amplitude of the + + This will set the amplitude of the bounce or the amplitude of the elastic "spring" effect. The higher the number, the higher the amplitude. \sa amplitude() */ @@ -688,7 +687,7 @@ qreal QEasingCurve::period() const /*! Sets the period to \a period. - Setting a small period value will give a high frequency of the curve. A + Setting a small period value will give a high frequency of the curve. A large period will give it a small frequency. \sa period() @@ -745,7 +744,7 @@ void QEasingCurvePrivate::setType_helper(QEasingCurve::Type newType) delete config; config = 0; } - + if (isConfigFunction(newType) || (amp != -1.0) || (period != -1.0) || (overshoot != -1.0)) { config = curveToFunctionObject(newType); if (amp != -1.0) @@ -800,7 +799,7 @@ void QEasingCurve::setCustomType(EasingFunction func) /*! Returns the function pointer to the custom easing curve. - If type() does not return QEasingCurve::Custom, this function + If type() does not return QEasingCurve::Custom, this function will return 0. */ QEasingCurve::EasingFunction QEasingCurve::customType() const @@ -830,7 +829,7 @@ qreal QEasingCurve::valueForProgress(qreal progress) const #include QDebug operator<<(QDebug debug, const QEasingCurve &item) { - debug << "type:" << item.d_ptr->type + debug << "type:" << item.d_ptr->type << "func:" << item.d_ptr->func; if (item.d_ptr->config) { debug << QString::fromAscii("period:%1").arg(item.d_ptr->config->_p, 0, 'f', 20) -- cgit v0.12 From a903f9fb54f7192795abffca0a99b54d419bdb7a Mon Sep 17 00:00:00 2001 From: Leonardo Sobral Cunha Date: Tue, 19 May 2009 13:35:58 +0200 Subject: Removed memory leak in QEasingCurvePrivate Task-number: 253898 --- src/corelib/tools/qeasingcurve.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp index 72965de5..9ef9149 100644 --- a/src/corelib/tools/qeasingcurve.cpp +++ b/src/corelib/tools/qeasingcurve.cpp @@ -354,6 +354,7 @@ public: config(0), func(&easeNone) { } + ~QEasingCurvePrivate() { delete config; } void setType_helper(QEasingCurve::Type); QEasingCurve::Type type; -- cgit v0.12 From 1c64881836a7003b20e0da97b95c94394c476525 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Tue, 19 May 2009 13:41:22 +0200 Subject: Doc: Added information about ownership of animations. Reviewed-by: Thierry Bastian --- src/corelib/animation/qanimationgroup.cpp | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/corelib/animation/qanimationgroup.cpp b/src/corelib/animation/qanimationgroup.cpp index e0be3f7..e78ce9a 100644 --- a/src/corelib/animation/qanimationgroup.cpp +++ b/src/corelib/animation/qanimationgroup.cpp @@ -159,7 +159,7 @@ int QAnimationGroup::animationCount() const Returns the index of \a animation. The returned index can be passed to the other functions that take an index as an argument. - \sa insertAnimationAt() animationAt(), takeAnimationAt() + \sa insertAnimationAt(), animationAt(), takeAnimationAt() */ int QAnimationGroup::indexOfAnimation(QAbstractAnimation *animation) const { @@ -169,7 +169,11 @@ int QAnimationGroup::indexOfAnimation(QAbstractAnimation *animation) const /*! Adds \a animation to this group. This will call insertAnimationAt with - index equals to animationCount() + index equals to animationCount(). + + \note The group takes ownership of the animation. + + \sa removeAnimation() */ void QAnimationGroup::addAnimation(QAbstractAnimation *animation) { @@ -181,7 +185,10 @@ void QAnimationGroup::addAnimation(QAbstractAnimation *animation) Inserts \a animation into this animation group at \a index. If \a index is 0 the animation is inserted at the beginning. If \a index is animationCount(), the animation is inserted at the end. - \sa takeAnimationAt(), addAnimation(), indexOfAnimation() + + \note The group takes ownership of the animation. + + \sa takeAnimationAt(), addAnimation(), indexOfAnimation(), removeAnimation() */ void QAnimationGroup::insertAnimationAt(int index, QAbstractAnimation *animation) { @@ -226,11 +233,11 @@ void QAnimationGroup::removeAnimation(QAbstractAnimation *animation) } /*! - Removes the animation at \a index from this animation group. The ownership - of the animation is transferred to the caller, and a pointer to the removed - animation is returned. + Returns the animation at \a index and removes it from the animation group. + + \note The ownership of the animation is transferred to the caller. - \sa addAnimation() + \sa removeAnimation(), addAnimation(), insertAnimation(), indexOfAnimation() */ QAbstractAnimation *QAnimationGroup::takeAnimationAt(int index) { -- cgit v0.12 From 91803020462b7e42128644bdd9ed1d3455787f79 Mon Sep 17 00:00:00 2001 From: Leonardo Sobral Cunha Date: Tue, 19 May 2009 14:17:02 +0200 Subject: Removed unused method from QVariantAnimationPrivate --- src/corelib/animation/qvariantanimation.cpp | 6 ------ src/corelib/animation/qvariantanimation_p.h | 1 - 2 files changed, 7 deletions(-) diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp index 157a321..8ac8ca1 100644 --- a/src/corelib/animation/qvariantanimation.cpp +++ b/src/corelib/animation/qvariantanimation.cpp @@ -217,12 +217,6 @@ void QVariantAnimationPrivate::recalculateCurrentInterval(bool force/*=false*/) setCurrentValueForProgress(progress); } -void QVariantAnimationPrivate::setCurrentValue() -{ - const qreal progress = easing.valueForProgress(((duration == 0) ? qreal(1) : qreal(currentTime) / qreal(duration))); - setCurrentValueForProgress(progress); -} - void QVariantAnimationPrivate::setCurrentValueForProgress(const qreal progress) { Q_Q(QVariantAnimation); diff --git a/src/corelib/animation/qvariantanimation_p.h b/src/corelib/animation/qvariantanimation_p.h index 9e81649..8b2915b 100644 --- a/src/corelib/animation/qvariantanimation_p.h +++ b/src/corelib/animation/qvariantanimation_p.h @@ -108,7 +108,6 @@ public: quint32 changedSignalMask; - void setCurrentValue(); void setCurrentValueForProgress(const qreal progress); void recalculateCurrentInterval(bool force=false); void setValueAt(qreal, const QVariant &); -- cgit v0.12 From b2302dcc101fcef3c2841e9bd47790332e1cd4c2 Mon Sep 17 00:00:00 2001 From: Leonardo Sobral Cunha Date: Tue, 19 May 2009 17:31:47 +0200 Subject: Removing QT_EXPERIMENTAL_SOLUTION from the animation api --- examples/animation/animatedtiles/main.cpp | 11 ----------- examples/animation/appchooser/main.cpp | 3 --- examples/animation/easing/animation.h | 6 +----- examples/animation/moveblocks/main.cpp | 9 --------- examples/animation/padnavigator-ng/panel.h | 4 ---- examples/animation/padnavigator-ng/roundrectitem.h | 4 ---- examples/animation/padnavigator-ng/splashitem.h | 4 ---- .../research/memberfunctions/qvalueanimation.h | 6 +----- examples/animation/states/main.cpp | 8 -------- examples/animation/stickman/lifecycle.cpp | 9 --------- examples/animation/sub-attaq/animationmanager.cpp | 6 +----- examples/animation/sub-attaq/boat.cpp | 10 ---------- examples/animation/sub-attaq/boat.h | 6 +----- examples/animation/sub-attaq/boat_p.h | 6 +----- examples/animation/sub-attaq/bomb.cpp | 8 -------- examples/animation/sub-attaq/bomb.h | 9 ++------- .../animation/sub-attaq/custompropertyanimation.h | 6 +----- examples/animation/sub-attaq/graphicsscene.cpp | 9 --------- examples/animation/sub-attaq/graphicsscene.h | 7 +------ examples/animation/sub-attaq/qanimationstate.cpp | 9 ++------- examples/animation/sub-attaq/states.cpp | 7 ------- examples/animation/sub-attaq/states.h | 9 +-------- examples/animation/sub-attaq/submarine.cpp | 8 -------- examples/animation/sub-attaq/submarine.h | 5 ----- examples/animation/sub-attaq/submarine_p.h | 4 ---- examples/animation/sub-attaq/torpedo.cpp | 6 ------ examples/animation/sub-attaq/torpedo.h | 9 ++------- src/corelib/animation/qabstractanimation.cpp | 20 -------------------- src/corelib/animation/qabstractanimation.h | 4 ---- src/corelib/animation/qabstractanimation_p.h | 9 --------- src/corelib/animation/qanimationgroup.h | 6 +----- src/corelib/animation/qparallelanimationgroup.h | 6 +----- src/corelib/animation/qpauseanimation.h | 6 +----- src/corelib/animation/qpropertyanimation.h | 6 +----- src/corelib/animation/qsequentialanimationgroup.h | 6 +----- src/corelib/animation/qvariantanimation.cpp | 5 +---- src/corelib/animation/qvariantanimation.h | 9 ++------- src/corelib/animation/qvariantanimation_p.h | 6 +----- src/corelib/tools/qeasingcurve.cpp | 6 +----- src/gui/animation/qguivariantanimation.cpp | 5 ----- 40 files changed, 24 insertions(+), 258 deletions(-) diff --git a/examples/animation/animatedtiles/main.cpp b/examples/animation/animatedtiles/main.cpp index a97eaf3..7988758 100644 --- a/examples/animation/animatedtiles/main.cpp +++ b/examples/animation/animatedtiles/main.cpp @@ -40,18 +40,7 @@ ****************************************************************************/ #include -#ifdef QT_EXPERIMENTAL_SOLUTION -# include "qgraphicswidget.h" -# include "qstate.h" -# include "qstatemachine.h" -# include "qabstracttransition.h" -# include "qgraphicswidget.h" -# include "qparallelanimationgroup.h" -# include "qpropertyanimation.h" -# include "qsignaltransition.h" -#else #include -#endif class Pixmap : public QObject, public QGraphicsPixmapItem { diff --git a/examples/animation/appchooser/main.cpp b/examples/animation/appchooser/main.cpp index 1c63aba..44457f7 100644 --- a/examples/animation/appchooser/main.cpp +++ b/examples/animation/appchooser/main.cpp @@ -41,9 +41,6 @@ #include #include -#ifdef QT_EXPERIMENTAL_SOLUTION -#include "qtgraphicswidget.h" -#endif class Pixmap : public QGraphicsWidget diff --git a/examples/animation/easing/animation.h b/examples/animation/easing/animation.h index c9472e1..d4d699d 100644 --- a/examples/animation/easing/animation.h +++ b/examples/animation/easing/animation.h @@ -44,11 +44,7 @@ #include -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qpropertyanimation.h" -#else -# include -#endif +#include class Animation : public QPropertyAnimation { public: diff --git a/examples/animation/moveblocks/main.cpp b/examples/animation/moveblocks/main.cpp index 0ce07fc..b00485e 100644 --- a/examples/animation/moveblocks/main.cpp +++ b/examples/animation/moveblocks/main.cpp @@ -41,15 +41,6 @@ #include #include -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qstatemachine.h" -#include "qstate.h" -#include "qabstracttransition.h" -#include "qpropertyanimation.h" -#include "qsequentialanimationgroup.h" -#include "qparallelanimationgroup.h" -#include "qgraphicswidget.h" -#endif #include class StateSwitchEvent: public QEvent diff --git a/examples/animation/padnavigator-ng/panel.h b/examples/animation/padnavigator-ng/panel.h index 35d0db5..8ad95d9 100644 --- a/examples/animation/padnavigator-ng/panel.h +++ b/examples/animation/padnavigator-ng/panel.h @@ -40,11 +40,7 @@ ****************************************************************************/ #include -#ifdef QT_EXPERIMENTAL_SOLUTION -#include "qtgraphicswidget.h" -#else #include -#endif QT_BEGIN_NAMESPACE class Ui_BackSide; diff --git a/examples/animation/padnavigator-ng/roundrectitem.h b/examples/animation/padnavigator-ng/roundrectitem.h index fb142c6..6a7bf4b 100644 --- a/examples/animation/padnavigator-ng/roundrectitem.h +++ b/examples/animation/padnavigator-ng/roundrectitem.h @@ -41,11 +41,7 @@ #include #include -#ifdef QT_EXPERIMENTAL_SOLUTION -#include "qtgraphicswidget.h" -#else #include -#endif QT_BEGIN_NAMESPACE class QGraphicsProxyWidget; diff --git a/examples/animation/padnavigator-ng/splashitem.h b/examples/animation/padnavigator-ng/splashitem.h index 05ff040..7b4b8a9 100644 --- a/examples/animation/padnavigator-ng/splashitem.h +++ b/examples/animation/padnavigator-ng/splashitem.h @@ -40,11 +40,7 @@ ****************************************************************************/ #include -#ifdef QT_EXPERIMENTAL_SOLUTION -#include "qtgraphicswidget.h" -#else #include -#endif class SplashItem : public QGraphicsWidget { diff --git a/examples/animation/research/memberfunctions/qvalueanimation.h b/examples/animation/research/memberfunctions/qvalueanimation.h index 55c4993..17e9817 100644 --- a/examples/animation/research/memberfunctions/qvalueanimation.h +++ b/examples/animation/research/memberfunctions/qvalueanimation.h @@ -42,11 +42,7 @@ #ifndef QVALUEANIMATION_H #define QVALUEANIMATION_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qvariantanimation.h" -#else -# include -#endif +#include QT_BEGIN_HEADER diff --git a/examples/animation/states/main.cpp b/examples/animation/states/main.cpp index 06b0667..17a7a8e 100644 --- a/examples/animation/states/main.cpp +++ b/examples/animation/states/main.cpp @@ -40,14 +40,6 @@ ****************************************************************************/ #include -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qstate.h" -# include "qstatemachine.h" -# include "qtransition.h" -# include "qparallelanimationgroup.h" -# include "qsequentialanimationgroup.h" -# include "qpropertyanimation.h" -#endif class Pixmap : public QGraphicsWidget { diff --git a/examples/animation/stickman/lifecycle.cpp b/examples/animation/stickman/lifecycle.cpp index 1feb31d..eb4ed11 100644 --- a/examples/animation/stickman/lifecycle.cpp +++ b/examples/animation/stickman/lifecycle.cpp @@ -47,15 +47,6 @@ #include #include -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qstatemachine.h" -#include "qstate.h" -#include "qeventtransition.h" -#include "qsignaltransition.h" -#include "qsignalevent.h" -#include "qpropertyanimation.h" -#include "qparallelanimationgroup.h" -#endif class KeyPressTransition: public QSignalTransition { diff --git a/examples/animation/sub-attaq/animationmanager.cpp b/examples/animation/sub-attaq/animationmanager.cpp index 5b9282a..477d3bd 100644 --- a/examples/animation/sub-attaq/animationmanager.cpp +++ b/examples/animation/sub-attaq/animationmanager.cpp @@ -43,11 +43,7 @@ #include "animationmanager.h" //Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qabstractanimation.h" -#else -# include -#endif +#include #include // the universe's only animation manager diff --git a/examples/animation/sub-attaq/boat.cpp b/examples/animation/sub-attaq/boat.cpp index 143cf94..63d12bb 100644 --- a/examples/animation/sub-attaq/boat.cpp +++ b/examples/animation/sub-attaq/boat.cpp @@ -50,22 +50,12 @@ #include "qanimationstate.h" //Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qpropertyanimation.h" -# include "qstatemachine.h" -# include "qhistorystate.h" -# include "qfinalstate.h" -# include "qstate.h" -# include "qpauseanimation.h" -#include "qsequentialanimationgroup.h" -#else #include #include #include #include #include #include -#endif static QAbstractAnimation *setupDestroyAnimation(Boat *boat) { diff --git a/examples/animation/sub-attaq/boat.h b/examples/animation/sub-attaq/boat.h index b28cf20..f16074e 100644 --- a/examples/animation/sub-attaq/boat.h +++ b/examples/animation/sub-attaq/boat.h @@ -46,11 +46,7 @@ #include #include -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qtgraphicswidget.h" -#else -# include -#endif +#include class PixmapItem; class Bomb; diff --git a/examples/animation/sub-attaq/boat_p.h b/examples/animation/sub-attaq/boat_p.h index 6f03e48..c934bc5 100644 --- a/examples/animation/sub-attaq/boat_p.h +++ b/examples/animation/sub-attaq/boat_p.h @@ -47,11 +47,7 @@ #include "graphicsscene.h" // Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qkeyeventtransition.h" -#else -# include -#endif +#include static const int MAX_BOMB = 5; diff --git a/examples/animation/sub-attaq/bomb.cpp b/examples/animation/sub-attaq/bomb.cpp index 04310aa..f1f5324 100644 --- a/examples/animation/sub-attaq/bomb.cpp +++ b/examples/animation/sub-attaq/bomb.cpp @@ -47,18 +47,10 @@ #include "qanimationstate.h" //Qt - -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qpropertyanimation.h" -#include "qsequentialanimationgroup.h" -#include "qstatemachine.h" -#include "qfinalstate.h" -#else #include #include #include #include -#endif Bomb::Bomb(QGraphicsItem * parent, Qt::WindowFlags wFlags) : QGraphicsWidget(parent,wFlags), launchAnimation(0) diff --git a/examples/animation/sub-attaq/bomb.h b/examples/animation/sub-attaq/bomb.h index 9191e6e..226d056 100644 --- a/examples/animation/sub-attaq/bomb.h +++ b/examples/animation/sub-attaq/bomb.h @@ -43,13 +43,8 @@ #define __BOMB__H__ //Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qanimationgroup.h" -# include "qgraphicswidget.h" -#else -# include -# include -#endif +#include +#include class PixmapItem; diff --git a/examples/animation/sub-attaq/custompropertyanimation.h b/examples/animation/sub-attaq/custompropertyanimation.h index 48a50c9..1dca454 100644 --- a/examples/animation/sub-attaq/custompropertyanimation.h +++ b/examples/animation/sub-attaq/custompropertyanimation.h @@ -42,11 +42,7 @@ #ifndef CUSTOMPROPERTYANIMATION_H #define CUSTOMPROPERTYANIMATION_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qvariantanimation.h" -#else -# include -#endif +#include class QGraphicsItem; diff --git a/examples/animation/sub-attaq/graphicsscene.cpp b/examples/animation/sub-attaq/graphicsscene.cpp index 2a6f83c..f2d41bc 100644 --- a/examples/animation/sub-attaq/graphicsscene.cpp +++ b/examples/animation/sub-attaq/graphicsscene.cpp @@ -53,21 +53,12 @@ #include "progressitem.h" //Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qpropertyanimation.h" -#include "qsequentialanimationgroup.h" -#include "qparallelanimationgroup.h" -#include "qstatemachine.h" -#include "qfinalstate.h" -#include "qpauseanimation.h" -#else #include #include #include #include #include #include -#endif #include #include #include diff --git a/examples/animation/sub-attaq/graphicsscene.h b/examples/animation/sub-attaq/graphicsscene.h index 0840564..70c873e 100644 --- a/examples/animation/sub-attaq/graphicsscene.h +++ b/examples/animation/sub-attaq/graphicsscene.h @@ -45,12 +45,7 @@ //Qt #include #include - -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qstate.h" -#else -# include -#endif +#include class Boat; diff --git a/examples/animation/sub-attaq/qanimationstate.cpp b/examples/animation/sub-attaq/qanimationstate.cpp index 0f30ac2..26e0ef3 100644 --- a/examples/animation/sub-attaq/qanimationstate.cpp +++ b/examples/animation/sub-attaq/qanimationstate.cpp @@ -41,13 +41,8 @@ #include "qanimationstate.h" -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qstate.h" -# include "qstate_p.h" -#else -# include -# include -#endif +#include +#include QT_BEGIN_NAMESPACE diff --git a/examples/animation/sub-attaq/states.cpp b/examples/animation/sub-attaq/states.cpp index 7650b0f..adc8bd0 100644 --- a/examples/animation/sub-attaq/states.cpp +++ b/examples/animation/sub-attaq/states.cpp @@ -51,17 +51,10 @@ //Qt #include #include -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qstatemachine.h" -#include "qkeyeventtransition.h" -#include "qsignalevent.h" -#include "qfinalstate.h" -#else #include #include #include #include -#endif PlayState::PlayState(GraphicsScene *scene, QState *parent) : QState(parent), diff --git a/examples/animation/sub-attaq/states.h b/examples/animation/sub-attaq/states.h index a1cb5ff..3203b3b 100644 --- a/examples/animation/sub-attaq/states.h +++ b/examples/animation/sub-attaq/states.h @@ -43,17 +43,10 @@ #define STATES_H //Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qstate.h" -#include "qsignaltransition.h" -#include "qpropertyanimation.h" -#include "qkeyeventtransition.h" -#else #include #include #include -# include -#endif +#include #include class GraphicsScene; diff --git a/examples/animation/sub-attaq/submarine.cpp b/examples/animation/sub-attaq/submarine.cpp index 0f03efc..d8cf1da 100644 --- a/examples/animation/sub-attaq/submarine.cpp +++ b/examples/animation/sub-attaq/submarine.cpp @@ -49,18 +49,10 @@ #include "custompropertyanimation.h" #include "qanimationstate.h" -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qpropertyanimation.h" -# include "qstatemachine.h" -# include "qfinalstate.h" -# include "qsequentialanimationgroup.h" -# include "qpauseanimation.h" -#else #include #include #include #include -#endif static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub) { diff --git a/examples/animation/sub-attaq/submarine.h b/examples/animation/sub-attaq/submarine.h index 7ee587d..4001603 100644 --- a/examples/animation/sub-attaq/submarine.h +++ b/examples/animation/sub-attaq/submarine.h @@ -43,13 +43,8 @@ #define __SUBMARINE__H__ //Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qvariantanimation.h" -#include "qgraphicswidget.h" -#else #include #include -#endif class PixmapItem; diff --git a/examples/animation/sub-attaq/submarine_p.h b/examples/animation/sub-attaq/submarine_p.h index c76d991..561af4a 100644 --- a/examples/animation/sub-attaq/submarine_p.h +++ b/examples/animation/sub-attaq/submarine_p.h @@ -48,11 +48,7 @@ #include "qanimationstate.h" //Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qpropertyanimation.h" -#else #include -#endif #include //This state is describing when the boat is moving right diff --git a/examples/animation/sub-attaq/torpedo.cpp b/examples/animation/sub-attaq/torpedo.cpp index 88f1112..02a54fc 100644 --- a/examples/animation/sub-attaq/torpedo.cpp +++ b/examples/animation/sub-attaq/torpedo.cpp @@ -47,15 +47,9 @@ #include "animationmanager.h" #include "qanimationstate.h" -#if defined(QT_EXPERIMENTAL_SOLUTION) -#include "qpropertyanimation.h" -#include "qstatemachine.h" -#include "qfinalstate.h" -#else #include #include #include -#endif Torpedo::Torpedo(QGraphicsItem * parent, Qt::WindowFlags wFlags) : QGraphicsWidget(parent,wFlags), currentSpeed(0), launchAnimation(0) diff --git a/examples/animation/sub-attaq/torpedo.h b/examples/animation/sub-attaq/torpedo.h index 2e44e41..4a0f457 100644 --- a/examples/animation/sub-attaq/torpedo.h +++ b/examples/animation/sub-attaq/torpedo.h @@ -45,13 +45,8 @@ //Qt #include -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qvariantanimation.h" -# include "qgraphicswidget.h" -#else -# include -# include -#endif +#include +#include class PixmapItem; diff --git a/src/corelib/animation/qabstractanimation.cpp b/src/corelib/animation/qabstractanimation.cpp index f5b9323..759cf18 100644 --- a/src/corelib/animation/qabstractanimation.cpp +++ b/src/corelib/animation/qabstractanimation.cpp @@ -352,42 +352,22 @@ void QAbstractAnimationPrivate::setState(QAbstractAnimation::State newState) \sa QVariantAnimation, QAnimationGroup */ -#ifdef QT_EXPERIMENTAL_SOLUTION -QAbstractAnimation::QAbstractAnimation(QObject *parent) - : d_ptr(new QAbstractAnimationPrivate) -{ - // Allow auto-add on reparent - setParent(parent); - d_ptr->q_ptr = this; -} -#else QAbstractAnimation::QAbstractAnimation(QObject *parent) : QObject(*new QAbstractAnimationPrivate, 0) { // Allow auto-add on reparent setParent(parent); } -#endif /*! \internal */ -#ifdef QT_EXPERIMENTAL_SOLUTION -QAbstractAnimation::QAbstractAnimation(QAbstractAnimationPrivate &dd, QObject *parent) - : d_ptr(&dd) -{ - // Allow auto-add on reparent - setParent(parent); - d_ptr->q_ptr = this; -} -#else QAbstractAnimation::QAbstractAnimation(QAbstractAnimationPrivate &dd, QObject *parent) : QObject(dd, 0) { // Allow auto-add on reparent setParent(parent); } -#endif /*! Stops the animation if it's running, then destroys the diff --git a/src/corelib/animation/qabstractanimation.h b/src/corelib/animation/qabstractanimation.h index a7f0082..d6d50dc 100644 --- a/src/corelib/animation/qabstractanimation.h +++ b/src/corelib/animation/qabstractanimation.h @@ -123,10 +123,6 @@ protected: virtual void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); virtual void updateDirection(QAbstractAnimation::Direction direction); -#ifdef QT_EXPERIMENTAL_SOLUTION - QAbstractAnimationPrivate *d_ptr; -#endif - private: Q_DISABLE_COPY(QAbstractAnimation) Q_DECLARE_PRIVATE(QAbstractAnimation) diff --git a/src/corelib/animation/qabstractanimation_p.h b/src/corelib/animation/qabstractanimation_p.h index 41983a5..e64554c 100644 --- a/src/corelib/animation/qabstractanimation_p.h +++ b/src/corelib/animation/qabstractanimation_p.h @@ -56,19 +56,13 @@ #include #include #include -#ifndef QT_EXPERIMENTAL_SOLUTION #include -#endif QT_BEGIN_NAMESPACE class QAnimationGroup; class QAbstractAnimation; -#ifdef QT_EXPERIMENTAL_SOLUTION -class QAbstractAnimationPrivate -#else class QAbstractAnimationPrivate : public QObjectPrivate -#endif { public: QAbstractAnimationPrivate() @@ -101,9 +95,6 @@ public: int currentLoop; QAnimationGroup *group; -#ifdef QT_EXPERIMENTAL_SOLUTION - QAbstractAnimation *q_ptr; -#endif private: Q_DECLARE_PUBLIC(QAbstractAnimation) diff --git a/src/corelib/animation/qanimationgroup.h b/src/corelib/animation/qanimationgroup.h index 7dee070..263bc38 100644 --- a/src/corelib/animation/qanimationgroup.h +++ b/src/corelib/animation/qanimationgroup.h @@ -42,11 +42,7 @@ #ifndef QANIMATIONGROUP_H #define QANIMATIONGROUP_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qabstractanimation.h" -#else -# include -#endif +#include QT_BEGIN_HEADER diff --git a/src/corelib/animation/qparallelanimationgroup.h b/src/corelib/animation/qparallelanimationgroup.h index 48d66a3..57a8146 100644 --- a/src/corelib/animation/qparallelanimationgroup.h +++ b/src/corelib/animation/qparallelanimationgroup.h @@ -42,11 +42,7 @@ #ifndef QPARALLELANIMATIONGROUP_H #define QPARALLELANIMATIONGROUP_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qanimationgroup.h" -#else -# include -#endif +#include QT_BEGIN_HEADER diff --git a/src/corelib/animation/qpauseanimation.h b/src/corelib/animation/qpauseanimation.h index 595f2d0..cb6e041 100644 --- a/src/corelib/animation/qpauseanimation.h +++ b/src/corelib/animation/qpauseanimation.h @@ -42,11 +42,7 @@ #ifndef QPAUSEANIMATION_P_H #define QPAUSEANIMATION_P_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qanimationgroup.h" -#else -# include -#endif +#include QT_BEGIN_HEADER diff --git a/src/corelib/animation/qpropertyanimation.h b/src/corelib/animation/qpropertyanimation.h index b619256..dbd118c 100644 --- a/src/corelib/animation/qpropertyanimation.h +++ b/src/corelib/animation/qpropertyanimation.h @@ -42,11 +42,7 @@ #ifndef QPROPERTYANIMATION_H #define QPROPERTYANIMATION_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qvariantanimation.h" -#else -# include -#endif +#include QT_BEGIN_HEADER diff --git a/src/corelib/animation/qsequentialanimationgroup.h b/src/corelib/animation/qsequentialanimationgroup.h index 4c52d1b..4701a76 100644 --- a/src/corelib/animation/qsequentialanimationgroup.h +++ b/src/corelib/animation/qsequentialanimationgroup.h @@ -42,11 +42,7 @@ #ifndef QSEQUENTIALANIMATIONGROUP_H #define QSEQUENTIALANIMATIONGROUP_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qanimationgroup.h" -#else -# include -#endif +#include QT_BEGIN_HEADER diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp index 8ac8ca1..864575a 100644 --- a/src/corelib/animation/qvariantanimation.cpp +++ b/src/corelib/animation/qvariantanimation.cpp @@ -230,10 +230,7 @@ void QVariantAnimationPrivate::setCurrentValueForProgress(const qreal progress) localProgress); qSwap(currentValue, ret); q->updateCurrentValue(currentValue); -#ifndef QT_EXPERIMENTAL_SOLUTION - if (connectedSignals & changedSignalMask) -#endif - if (currentValue != ret) { + if ((connectedSignals & changedSignalMask) && currentValue != ret) { //the value has changed emit q->valueChanged(currentValue); } diff --git a/src/corelib/animation/qvariantanimation.h b/src/corelib/animation/qvariantanimation.h index 69dbbf3..5b90930 100644 --- a/src/corelib/animation/qvariantanimation.h +++ b/src/corelib/animation/qvariantanimation.h @@ -42,13 +42,8 @@ #ifndef QANIMATION_H #define QANIMATION_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qabstractanimation.h" -# include "qeasingcurve.h" -#else -# include -# include -#endif +#include +#include #include #include #include diff --git a/src/corelib/animation/qvariantanimation_p.h b/src/corelib/animation/qvariantanimation_p.h index 8b2915b..e0b9c51 100644 --- a/src/corelib/animation/qvariantanimation_p.h +++ b/src/corelib/animation/qvariantanimation_p.h @@ -54,11 +54,7 @@ // #include "qvariantanimation.h" -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qeasingcurve.h" -#else -# include -#endif +#include #include #include diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp index 9ef9149..23eb2a6 100644 --- a/src/corelib/tools/qeasingcurve.cpp +++ b/src/corelib/tools/qeasingcurve.cpp @@ -340,11 +340,7 @@ bool QEasingCurveFunction::operator==(const QEasingCurveFunction& other) _o == other._o; } -#ifdef QT_EXPERIMENTAL_SOLUTION -# include "easing.cpp" -#else -# include "../3rdparty/easing/easing.cpp" -#endif +#include "../3rdparty/easing/easing.cpp" class QEasingCurvePrivate { diff --git a/src/gui/animation/qguivariantanimation.cpp b/src/gui/animation/qguivariantanimation.cpp index ed18caa..37ca6a1 100644 --- a/src/gui/animation/qguivariantanimation.cpp +++ b/src/gui/animation/qguivariantanimation.cpp @@ -41,13 +41,8 @@ #ifndef QT_NO_ANIMATION -#ifdef QT_EXPERIMENTAL_SOLUTION -# include "qvariantanimation.h" -# include "qvariantanimation_p.h" -#else #include #include -#endif #include -- cgit v0.12 From 6501f21efeb9fb327be60b8d069cfad5f19f9ff7 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 7 May 2009 14:50:47 +0200 Subject: No need to export QVariantAnimationPrivate --- src/corelib/animation/qvariantanimation_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/animation/qvariantanimation_p.h b/src/corelib/animation/qvariantanimation_p.h index e0b9c51..0d296db 100644 --- a/src/corelib/animation/qvariantanimation_p.h +++ b/src/corelib/animation/qvariantanimation_p.h @@ -62,7 +62,7 @@ QT_BEGIN_NAMESPACE -class Q_CORE_EXPORT QVariantAnimationPrivate : public QAbstractAnimationPrivate +class QVariantAnimationPrivate : public QAbstractAnimationPrivate { Q_DECLARE_PUBLIC(QVariantAnimation) public: -- cgit v0.12 From c21803201a607dabc1d5a9345004d8f5dbc02d25 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 20 May 2009 11:42:25 +0200 Subject: Fix an issue that made appear warnings when the target of a property animation was destroyed The problem was that we were not really detecting when the target was destroyed. So we weren't able to unregister it from the global internal hash we have in QPropertyAnimation. This happens if an animation is running and the target object is destroyed. --- src/corelib/animation/qpropertyanimation.cpp | 27 +++++++++++++++++++++++++++ src/corelib/animation/qpropertyanimation.h | 1 + src/corelib/animation/qpropertyanimation_p.h | 5 +++-- 3 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp index 1755aa7..10fe8a2 100644 --- a/src/corelib/animation/qpropertyanimation.cpp +++ b/src/corelib/animation/qpropertyanimation.cpp @@ -146,6 +146,14 @@ void QPropertyAnimationPrivate::updateProperty(const QVariant &newValue) } } +void QPropertyAnimationPrivate::_q_targetDestroyed() +{ + Q_Q(QPropertyAnimation); + //we stop here so that this animation is removed from the global hash + q->stop(); + target = 0; +} + /*! Construct a QPropertyAnimation object. \a parent is passed to QObject's constructor. @@ -188,12 +196,25 @@ QObject *QPropertyAnimation::targetObject() const Q_D(const QPropertyAnimation); return d->target; } + void QPropertyAnimation::setTargetObject(QObject *target) { Q_D(QPropertyAnimation); if (d->target == target) return; + if (d->state != QAbstractAnimation::Stopped) { + qWarning("QPropertyAnimation::setTargetObject: you can't change the target of a running animation"); + return; + } + + //we need to get notified when the target is destroyed + if (d->target) + disconnect(d->target, SIGNAL(destroyed()), this, SLOT(_q_targetDestroyed())); + + if (target) + connect(target, SIGNAL(destroyed()), SLOT(_q_targetDestroyed())); + d->target = target; d->hasMetaProperty = 0; d->updateMetaProperty(); @@ -211,9 +232,15 @@ QByteArray QPropertyAnimation::propertyName() const Q_D(const QPropertyAnimation); return d->propertyName; } + void QPropertyAnimation::setPropertyName(const QByteArray &propertyName) { Q_D(QPropertyAnimation); + if (d->state != QAbstractAnimation::Stopped) { + qWarning("QPropertyAnimation::setPropertyName: you can't change the property name of a running animation"); + return; + } + d->propertyName = propertyName; d->hasMetaProperty = 0; d->updateMetaProperty(); diff --git a/src/corelib/animation/qpropertyanimation.h b/src/corelib/animation/qpropertyanimation.h index dbd118c..5b06bd2 100644 --- a/src/corelib/animation/qpropertyanimation.h +++ b/src/corelib/animation/qpropertyanimation.h @@ -75,6 +75,7 @@ protected: void updateCurrentValue(const QVariant &value); void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); + Q_PRIVATE_SLOT(d_func(), void _q_targetDestroyed()); private: Q_DISABLE_COPY(QPropertyAnimation) Q_DECLARE_PRIVATE(QPropertyAnimation) diff --git a/src/corelib/animation/qpropertyanimation_p.h b/src/corelib/animation/qpropertyanimation_p.h index 9d9dd31..b51d039 100644 --- a/src/corelib/animation/qpropertyanimation_p.h +++ b/src/corelib/animation/qpropertyanimation_p.h @@ -55,7 +55,6 @@ #include "qpropertyanimation.h" #include -#include #include "qvariantanimation_p.h" @@ -70,7 +69,9 @@ public: { } - QPointer target; + void _q_targetDestroyed(); + + QObject *target; //for the QProperty QMetaProperty property; -- cgit v0.12 From 66f78ca4352aeb93586d920ad3905394b15f3c0d Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 20 May 2009 11:49:17 +0200 Subject: Remove old examples and demos for animations --- bin/snapshot | 359 ------------- examples/animation/example/example.pro | 12 - examples/animation/example/main.cpp | 53 -- examples/animation/example/mainwindow.cpp | 252 --------- examples/animation/example/mainwindow.h | 75 --- .../animation/research/memberfunctions/main.cpp | 89 ---- .../research/memberfunctions/memberfunctions.pro | 16 - .../research/memberfunctions/qvalueanimation.cpp | 101 ---- .../research/memberfunctions/qvalueanimation.h | 115 ---- .../research/memberfunctions/qvalueanimation_p.h | 77 --- examples/animation/research/photobrowser/main.cpp | 82 --- examples/animation/research/photobrowser/menu.cpp | 155 ------ examples/animation/research/photobrowser/menu.h | 80 --- .../research/photobrowser/photobrowser.pro | 17 - examples/animation/research/photobrowser/river.cpp | 591 --------------------- examples/animation/research/photobrowser/river.h | 111 ---- .../animation/research/photobrowser/riveritem.cpp | 125 ----- .../animation/research/photobrowser/riveritem.h | 66 --- examples/animation/research/piemenu/main.cpp | 56 -- examples/animation/research/piemenu/piemenu.pro | 8 - .../research/piemenu/qgraphicspiemenu.cpp | 250 --------- .../animation/research/piemenu/qgraphicspiemenu.h | 104 ---- .../research/piemenu/qgraphicspiemenu_p.h | 78 --- .../research/piemenu/qgraphicspiemenusection_p.h | 88 --- examples/animation/research/piemenu/scene.cpp | 73 --- examples/animation/research/piemenu/scene.h | 60 --- .../animation/research/propertytransform/main.cpp | 88 --- .../propertytransform/propertytransform.pro | 14 - .../propertytransform/qpropertytransform.h | 119 ----- examples/animation/research/sound/main.cpp | 104 ---- examples/animation/research/sound/media/sax.mp3 | Bin 417844 -> 0 bytes examples/animation/research/sound/sound.pro | 14 - examples/animation/research/sound/sound.qrc | 5 - 33 files changed, 3437 deletions(-) delete mode 100644 bin/snapshot delete mode 100644 examples/animation/example/example.pro delete mode 100644 examples/animation/example/main.cpp delete mode 100644 examples/animation/example/mainwindow.cpp delete mode 100644 examples/animation/example/mainwindow.h delete mode 100644 examples/animation/research/memberfunctions/main.cpp delete mode 100644 examples/animation/research/memberfunctions/memberfunctions.pro delete mode 100644 examples/animation/research/memberfunctions/qvalueanimation.cpp delete mode 100644 examples/animation/research/memberfunctions/qvalueanimation.h delete mode 100644 examples/animation/research/memberfunctions/qvalueanimation_p.h delete mode 100644 examples/animation/research/photobrowser/main.cpp delete mode 100644 examples/animation/research/photobrowser/menu.cpp delete mode 100644 examples/animation/research/photobrowser/menu.h delete mode 100644 examples/animation/research/photobrowser/photobrowser.pro delete mode 100644 examples/animation/research/photobrowser/river.cpp delete mode 100644 examples/animation/research/photobrowser/river.h delete mode 100644 examples/animation/research/photobrowser/riveritem.cpp delete mode 100644 examples/animation/research/photobrowser/riveritem.h delete mode 100644 examples/animation/research/piemenu/main.cpp delete mode 100644 examples/animation/research/piemenu/piemenu.pro delete mode 100644 examples/animation/research/piemenu/qgraphicspiemenu.cpp delete mode 100644 examples/animation/research/piemenu/qgraphicspiemenu.h delete mode 100644 examples/animation/research/piemenu/qgraphicspiemenu_p.h delete mode 100644 examples/animation/research/piemenu/qgraphicspiemenusection_p.h delete mode 100644 examples/animation/research/piemenu/scene.cpp delete mode 100644 examples/animation/research/piemenu/scene.h delete mode 100644 examples/animation/research/propertytransform/main.cpp delete mode 100644 examples/animation/research/propertytransform/propertytransform.pro delete mode 100644 examples/animation/research/propertytransform/qpropertytransform.h delete mode 100644 examples/animation/research/sound/main.cpp delete mode 100644 examples/animation/research/sound/media/sax.mp3 delete mode 100644 examples/animation/research/sound/sound.pro delete mode 100644 examples/animation/research/sound/sound.qrc diff --git a/bin/snapshot b/bin/snapshot deleted file mode 100644 index b9a64e1..0000000 --- a/bin/snapshot +++ /dev/null @@ -1,359 +0,0 @@ -#!/usr/bin/perl -w -###################################################################### -# -# -###################################################################### - -# use packages ------------------------------------------------------- -use File::Basename; -use File::Path; -use Cwd; -use Config; -use strict; - -my $targetPath = ""; -my $qtdir = $ENV{"QTDIR"}; - -my @class_renames = ( - "QAbstractAnimation", - "QAnimationGroup", - "QParallelAnimationGroup", - "QSequentialAnimationGroup", - "QEasingCurve", - "QVariantAnimation", - "QPropertyAnimation", - "QItemAnimation", - "QPauseAnimation", - "QAbstractState", - "QAbstractStateGroup", - "QAbstractTransition", - "QActionState", - "QEventTransition", - "QFinalState", - "QHistoryState", - "QParallelStateGroup", - "QSignalEvent", - "QSignalTransition", - "QState", - "QStateAction", - "QStateInvokeMethodAction", - "QStateFinishedEvent", - "QStateFinishedTransition", - "QStateMachine", - "QTransition", - "QMouseEventTransition", - "QBasicMouseEventTransition", - "QKeyEventTransition", - "QBasicKeyEventTransition", - "QGraphicsWidget", - "QBoundEvent"); - -my @files = ( - "3rdparty/easing/easing.cpp", - "corelib/tools/qeasingcurve.h", - "corelib/tools/qeasingcurve.cpp", - "corelib/animation/animation.pri", - "corelib/animation/qabstractanimation.cpp", - "corelib/animation/qabstractanimation.h", - "corelib/animation/qabstractanimation_p.h", - "corelib/animation/qvariantanimation.cpp", - "corelib/animation/qvariantanimation.h", - "corelib/animation/qanimationgroup.cpp", - "corelib/animation/qvariantanimation_p.h", - "corelib/animation/qanimationgroup.h", - "corelib/animation/qanimationgroup_p.h", - "corelib/animation/qparallelanimationgroup.cpp", - "corelib/animation/qparallelanimationgroup.h", - "corelib/animation/qparallelanimationgroup_p.h", - "corelib/animation/qpauseanimation.cpp", - "corelib/animation/qpauseanimation.h", - "corelib/animation/qpropertyanimation.cpp", - "corelib/animation/qpropertyanimation.h", - "corelib/animation/qpropertyanimation_p.h", - "corelib/animation/qsequentialanimationgroup.cpp", - "corelib/animation/qsequentialanimationgroup.h", - "corelib/animation/qsequentialanimationgroup_p.h", - "gui/animation/qguivariantanimation.cpp", - "gui/animation/animation.pri", - - "corelib/statemachine/statemachine.pri", - "corelib/statemachine/qabstractstate.cpp", - "corelib/statemachine/qabstractstate.h", - "corelib/statemachine/qabstractstate_p.h", - "corelib/statemachine/qabstracttransition.cpp", - "corelib/statemachine/qabstracttransition.h", - "corelib/statemachine/qabstracttransition_p.h", - "corelib/statemachine/qactionstate.h", - "corelib/statemachine/qactionstate_p.h", - "corelib/statemachine/qactionstate.cpp", - "corelib/statemachine/qboundevent_p.h", - "corelib/statemachine/qeventtransition.cpp", - "corelib/statemachine/qeventtransition.h", - "corelib/statemachine/qeventtransition_p.h", - "corelib/statemachine/qfinalstate.cpp", - "corelib/statemachine/qfinalstate.h", - "corelib/statemachine/qhistorystate.cpp", - "corelib/statemachine/qhistorystate.h", - "corelib/statemachine/qhistorystate_p.h", - "corelib/statemachine/qsignalevent.h", - "corelib/statemachine/qsignaleventgenerator_p.h", - "corelib/statemachine/qsignaltransition.cpp", - "corelib/statemachine/qsignaltransition.h", - "corelib/statemachine/qsignaltransition_p.h", - "corelib/statemachine/qstate.cpp", - "corelib/statemachine/qstate.h", - "corelib/statemachine/qstateaction.cpp", - "corelib/statemachine/qstateaction.h", - "corelib/statemachine/qstateaction_p.h", - "corelib/statemachine/qstatefinishedevent.h", - "corelib/statemachine/qstatefinishedtransition.cpp", - "corelib/statemachine/qstatefinishedtransition.h", - "corelib/statemachine/qstatemachine.cpp", - "corelib/statemachine/qstatemachine.h", - "corelib/statemachine/qstatemachine_p.h", - "corelib/statemachine/qstate_p.h", - "corelib/statemachine/qactiontransition.cpp", - "corelib/statemachine/qactiontransition.h", - "corelib/statemachine/qactiontransition_p.h", - "gui/statemachine/qkeyeventtransition.h", - "gui/statemachine/qkeyeventtransition.cpp", - "gui/statemachine/qbasickeyeventtransition.cpp", - "gui/statemachine/qbasickeyeventtransition_p.h", - "gui/statemachine/qbasicmouseeventtransition.cpp", - "gui/statemachine/qbasicmouseeventtransition_p.h", - "gui/statemachine/qguistatemachine.cpp", - "gui/statemachine/qkeyeventtransition.cpp", - "gui/statemachine/qkeyeventtransition.h", - "gui/statemachine/qmouseeventtransition.cpp", - "gui/statemachine/qmouseeventtransition.h", - "gui/statemachine/statemachine.pri", # needs special handling - ); - - -while ( @ARGV ) { - my $arg = shift @ARGV; - if ("$arg" eq "-to") { - $targetPath = shift @ARGV; - } -} - -if ($targetPath eq "") { - die("missing -to option"); -} - -my $projectXML = "$targetPath\\files.xml"; -open(OXML, "> " . $projectXML) || die "Could not open $projectXML for writing (no write permission?)"; - -print "COPYING SOURCES...\n"; -foreach my $files(@files) { - copyFile("$qtdir/src/$files","$targetPath/src", 1); -} -copyFile("$qtdir/doc/src/animation.qdoc","$targetPath/doc", 0); -copyFile("$qtdir/doc/src/statemachine.qdoc","$targetPath/doc", 0); -copyFile("$qtdir/src/3rdparty/easing/legal.qdoc","$targetPath/doc", 0); - -copyFile("$qtdir/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp","$targetPath/doc/src/snippets/code", 0); - - -my %animation_examples = ( - easing => [ "easing.pro", - "main.cpp", - "window.cpp", - "window.h", - "animation.h", - "form.ui", - "images/qt-logo.png", - "resources.qrc"], - moveblocks => [ "moveblocks.pro", - "main.cpp" ], - animatedtiles => [ "animatedtiles.pro", - "animatedtiles.qrc", - "main.cpp", - "images/*"], - "sub-attaq" => ["sub-attaq.pro", - "animationmanager.cpp", - "animationmanager.h", - "boat.cpp", - "boat_p.h", - "boat.h", - "bomb.cpp", - "bomb.h", - "custompropertyanimation.h", - "custompropertyanimation.cpp", - "graphicsscene.cpp", - "graphicsscene.h", - "main.cpp", - "mainwindow.cpp", - "mainwindow.h", - "pics/scalable/*", - "pics/big/*.png", - "pics/big/explosion/boat/*", - "pics/big/explosion/submarine/*", - "pics/small/*", - "pics/welcome/*", - "pixmapitem.cpp", - "pixmapitem.h", - "subattaq.qrc", - "submarine.cpp", - "submarine.h", - "submarine_p.h", - "states.cpp", - "states.h", - "qanimationstate.cpp", - "qanimationstate.h", - "torpedo.cpp", - "torpedo.h", - "data.xml"], - "stickman" => ["stickman.pro", - "main.cpp", - "animation.cpp", - "animation.h", - "graphicsview.cpp", - "graphicsview.h", - "lifecycle.cpp", - "lifecycle.h", - "node.cpp", - "node.h", - "stickman.cpp", - "stickman.h", - "editor/*", - "animations/chilling", - "animations/dancing", - "animations/dead", - "animations/jumping"] - ); - -my $exDir; -print "COPYING EXAMPLES...\n"; -for $exDir ( keys %animation_examples ) { - print " $exDir...\n"; - my $i = 0; - for $i ( 0 .. $#{ $animation_examples{$exDir} } ) { - my $ex_file = $animation_examples{$exDir}[$i]; - - my $copyTargetPath; - my $glob = 0; - if (index($ex_file,"/") > 0) { - my($basefile, $fullPath) = fileparse("$targetPath/examples/$exDir/$ex_file"); - if (index($basefile, "*") >= 0) { - $glob = 1; - } - mkpath "$fullPath", 0777 unless(-e "$fullPath"); - $copyTargetPath = "$fullPath"; - } else { - $copyTargetPath = "$targetPath/examples/$exDir"; - } - my $lastCh = substr($copyTargetPath, length($copyTargetPath) - 1, 1); - if ($lastCh eq "/" || $lastCh eq "\\") { - chop($copyTargetPath); - } - - if ($glob eq 1) { - my @globFiles = < $qtdir/examples/animation/$exDir/$ex_file >; - foreach my $globFile(@globFiles) { - copyFile("$globFile", "$copyTargetPath", 0); - } - } else { - copyFile("$qtdir/examples/animation/$exDir/$ex_file", "$copyTargetPath", 0); - } - } -} - -close OXML; -print("Finished!"); - - -###################################################################### -# Syntax: copyFile(gitfile, destinationPath) -# Params: gitfile, string, filename to create duplicate for -# destinationPath, string, destination name of duplicate -# autoRename, int, 0: Don't rename -# 1: The file should be renamed to have the "qt" prefix -# -# -# Purpose: Copies to the solutions area. -# Returns: -- -# Warning: Dies if script cannot get write access. -###################################################################### -sub copyFile -{ - my ($gitfile, $destinationPath, $autoRename) = @_; - # Bi-directional synchronization - open( I, "< " . $gitfile ) || die "Could not open $gitfile for reading"; - local $/; - binmode I; - my $filecontents = ; - my ($baseFileName, $path, $ext) = fileparse($gitfile, qr/\.[^.]*/); - if ($ext eq ".h" or $ext eq ".cpp" or $ext eq ".qdoc") { - # both public and private classes - foreach my $qtClass(@class_renames) { - my $solutionClass = $qtClass; - $solutionClass =~s/^Q/Qt/g; - $filecontents =~s/$qtClass/$solutionClass/g; - my $qtFilename = lc($qtClass); - my $solutionFilename = lc($solutionClass); - $filecontents =~s/(#\s*include\s+["])$qtFilename/${1}$solutionFilename/g; - } - - $filecontents =~s/Q_CORE_EXPORT/Q_ANIMATION_EXPORT/g; - $filecontents =~s/Q_GUI_EXPORT/Q_ANIMATION_EXPORT/g; - $filecontents =~s/class Q_GUI_EXPORT/class/g; - $filecontents =~s/class Q_AUTOTEST_EXPORT/class/g; - - # moc stuff - $filecontents =~s/(#\s*include\s+["])moc_q/${1}moc_qt/g; - - $filecontents =~s/\\since 4\.[0-9]//g; - $filecontents =~s/\\ingroup [a-z]+//g; - - if (substr($filecontents, 0, 10) eq "/*********") { - my $endOfComment = index($filecontents, "*/"); - $filecontents = substr($filecontents, $endOfComment + 2); - } - } - if ($ext eq ".pri" ) { - $filecontents =~s/\$\$PWD\/q/\$\$PWD\/qt/g; - $filecontents =~s/animation\/q/\$\$PWD\/qt/g; - - # oooh such a hack this is - if ($baseFileName eq "statemachine") { - if (index($gitfile, "corelib/statemachine") >= 0) { - $baseFileName = "corelib_statemachine"; - } - if (index($gitfile, "gui/statemachine") >= 0) { - $baseFileName = "gui_statemachine"; - } - } - if ($baseFileName eq "animation") { - if (index($gitfile, "corelib/animation") >= 0) { - $baseFileName = "corelib_animation"; - } - if (index($gitfile, "gui/animation") >= 0) { - $baseFileName = "gui_animation"; - } - } - - } - - if ($ext eq ".pro") { - $filecontents = "$filecontents\ninclude(../../src/qtanimationframework.pri)\n"; - } - close I; - - mkpath $destinationPath, 0777 unless(-e "$destinationPath"); - - if ($autoRename eq 1 and ($ext eq ".h" or $ext eq ".cpp" or $ext eq ".qdoc")) { - $baseFileName =~s/^q/qt/g; - } - my $targetFile = "$destinationPath/$baseFileName$ext"; - open(O, "> " . $targetFile) || die "Could not open $targetFile for writing (no write permission?)"; - local $/; - binmode O; - print O $filecontents; - close O; - - my $xmlEntry = substr($targetFile, length($targetPath) + 1); - print "$xmlEntry\n"; - print OXML "$xmlEntry\n"; -} - diff --git a/examples/animation/example/example.pro b/examples/animation/example/example.pro deleted file mode 100644 index bc79b82..0000000 --- a/examples/animation/example/example.pro +++ /dev/null @@ -1,12 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) Thu Sep 25 14:03:47 2008 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -# Input -HEADERS += mainwindow.h -SOURCES += main.cpp mainwindow.cpp diff --git a/examples/animation/example/main.cpp b/examples/animation/example/main.cpp deleted file mode 100644 index 1180b4f..0000000 --- a/examples/animation/example/main.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "mainwindow.h" - -int main(int argc, char *argv[]) -{ - //Q_INIT_RESOURCE(example); - QApplication app(argc, argv); - MainWindow w; - w.show(); - return app.exec(); -} - diff --git a/examples/animation/example/mainwindow.cpp b/examples/animation/example/mainwindow.cpp deleted file mode 100644 index 4aff384..0000000 --- a/examples/animation/example/mainwindow.cpp +++ /dev/null @@ -1,252 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "mainwindow.h" - -MainWindow::MainWindow() : QMainWindow(0) -{ - // Text edit and button - listWidget = new QListWidget; - new QListWidgetItem("Rachel", listWidget); - new QListWidgetItem("Andreas", listWidget); - new QListWidgetItem("David", listWidget); - new QListWidgetItem("Olivier", listWidget); - new QListWidgetItem("Andy", listWidget); - new QListWidgetItem("Martial", listWidget); - new QListWidgetItem("Kazou", listWidget); - new QListWidgetItem("Fred", listWidget); - new QListWidgetItem("Ingrid", listWidget); - QGraphicsProxyWidget *listProxy = new QGraphicsProxyWidget; - listProxy->setWidget(listWidget); - - labelWidget = new QLabel; - QGraphicsProxyWidget *labelProxy = new QGraphicsProxyWidget; - labelProxy->setWidget(labelWidget); - labelWidget->setAttribute(Qt::WA_NoSystemBackground); - - label2Widget = new QLabel; - label2Widget->setAlignment(Qt::AlignCenter); - QGraphicsProxyWidget *label2Proxy = new QGraphicsProxyWidget; - label2Proxy->setWidget(label2Widget); - label2Widget->setAttribute(Qt::WA_NoSystemBackground); - - editWidget = new QLineEdit; - QGraphicsProxyWidget *editProxy = new QGraphicsProxyWidget; - editProxy->setWidget(editWidget); - editWidget->setAttribute(Qt::WA_NoSystemBackground); - - // Parent widget - QGraphicsWidget *widget = new QGraphicsWidget; - // Parent widget - QGraphicsWidget *widget2 = new QGraphicsWidget; - - QGraphicsLinearLayout *vLayout = new QGraphicsLinearLayout(Qt::Vertical, widget); - vLayout->addItem(listProxy); - vLayout->addItem(widget2); - widget->setLayout(vLayout); - - QPushButton *button = new QPushButton; - QGraphicsProxyWidget *buttonProxy = new QGraphicsProxyWidget; - buttonProxy->setWidget(button); - - QPushButton *button2 = new QPushButton; - QGraphicsProxyWidget *buttonProxy2 = new QGraphicsProxyWidget; - buttonProxy2->setWidget(button2); - - QPushButton *button3 = new QPushButton; - QGraphicsProxyWidget *buttonProxy3 = new QGraphicsProxyWidget; - buttonProxy3->setWidget(button3); - - QPushButton *button4 = new QPushButton; - QGraphicsProxyWidget *buttonProxy4 = new QGraphicsProxyWidget; - buttonProxy4->setWidget(button4); - - QGraphicsLinearLayout *hLayout = new QGraphicsLinearLayout(Qt::Horizontal, widget2); - hLayout->addItem(buttonProxy); - hLayout->addItem(buttonProxy2); - hLayout->addItem(buttonProxy3); - widget2->setLayout(hLayout); - - scene = new QGraphicsScene(0, 0, 700, 600); - scene->setBackgroundBrush(scene->palette().window()); - scene->addItem(widget); - scene->addItem(editProxy); - scene->addItem(label2Proxy); - scene->addItem(labelProxy); - scene->addItem(buttonProxy4); - - machine = new QStateMachine(); - - group = new QState(machine->rootState()); - state1 = new QState(group); - state2 = new QState(group); - state3 = new QState(group); - group->setInitialState(state1); - - machine->setInitialState(group); - - // State 1 - state1->assignProperty(button, "text", "Edit"); - state1->assignProperty(button2, "text", "Add"); - state1->assignProperty(button3, "text", "Remove"); - state1->assignProperty(button4, "text", "Accept"); - state1->addTransition(button2, SIGNAL(clicked()), state3); - state1->assignProperty(listProxy, "geometry", QRectF(0, 0, 700, 560)); - state1->assignProperty(widget, "geometry", QRectF(0, 0, 700, 600)); - state1->assignProperty(editProxy, "opacity", double(0)); - state1->assignProperty(labelProxy, "opacity", double(0)); - state1->assignProperty(label2Proxy, "opacity", double(0)); - state1->assignProperty(buttonProxy4, "opacity", double(0)); - state1->assignProperty(labelWidget, "text", "Name : "); - state1->assignProperty(label2Widget, "text", "Edit a contact"); - state1->assignProperty(label2Proxy, "geometry", QRectF(375, -50, 300, 30)); - state1->assignProperty(labelProxy, "geometry", QRectF(350, 300, 100, 30)); - state1->assignProperty(editProxy, "geometry", QRectF(750, 300, 250, 30)); - state1->assignProperty(buttonProxy4, "geometry", QRectF(500, 350, 80, 25)); - - // State 2 - state2->assignProperty(button, "text", "Close Editing"); - state2->assignProperty(listProxy, "geometry", QRectF(0, 0, 350, 560)); - state2->addTransition(button2, SIGNAL(clicked()), state3); - state2->addTransition(button4, SIGNAL(clicked()), state1); - - state2->assignProperty(editProxy, "opacity", double(1)); - state2->assignProperty(labelProxy, "opacity", double(1)); - state2->assignProperty(label2Proxy, "opacity", double(1)); - state2->assignProperty(buttonProxy4, "opacity", double(1)); - - state2->assignProperty(label2Proxy, "geometry", QRectF(375, 250, 300, 30)); - state2->assignProperty(editProxy, "geometry", QRectF(440, 300, 260, 30)); - - // State 3 - state3->assignProperty(button4, "text", "Create New"); - state3->assignProperty(listProxy, "geometry", QRectF(0, 0, 350, 560)); - state3->addTransition(button4, SIGNAL(clicked()), state1); - state3->addTransition(button, SIGNAL(clicked()), state1); - state3->assignProperty(editProxy, "opacity", double(1)); - state3->assignProperty(labelProxy, "opacity", double(1)); - state3->assignProperty(label2Proxy, "opacity", double(1)); - state3->assignProperty(buttonProxy4, "opacity", double(1)); - - state3->assignProperty(label2Proxy, "geometry", QRectF(375, 250, 300, 30)); - state3->assignProperty(editProxy, "geometry", QRectF(440, 300, 260, 30)); - - { - QAnimationGroup *animationGroup = new QParallelAnimationGroup; - QVariantAnimation *anim = new QPropertyAnimation(labelProxy, "opacity"); - animationGroup->addAnimation(anim); - anim = new QPropertyAnimation(label2Proxy, "geometry"); - animationGroup->addAnimation(anim); - anim = new QPropertyAnimation(editProxy, "geometry"); - animationGroup->addAnimation(anim); - anim = new QPropertyAnimation(listProxy, "geometry"); - animationGroup->addAnimation(anim); - - QAbstractTransition *trans = state1->addTransition(button, SIGNAL(clicked()), state2); - trans->addAnimation(animationGroup); - } - - { - QVariantAnimation *anim; - QAnimationGroup *animationGroup = new QParallelAnimationGroup; - anim = new QPropertyAnimation(label2Proxy, "geometry"); - animationGroup->addAnimation(anim); - anim = new QPropertyAnimation(editProxy, "geometry"); - animationGroup->addAnimation(anim); - anim = new QPropertyAnimation(listProxy, "geometry"); - animationGroup->addAnimation(anim); - QAbstractTransition *trans = state2->addTransition(button, SIGNAL(clicked()), state1); - trans->addAnimation(animationGroup); - } - - currentState = state1; - - view = new QGraphicsView(scene); - - setCentralWidget(view); - - QObject::connect(state3, SIGNAL(entered()), this, SLOT(onEnterState3())); - QObject::connect(state2, SIGNAL(entered()), this, SLOT(onEnterState2())); - QObject::connect(state1, SIGNAL(entered()), this, SLOT(onEnterState1())); - - connect(listWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(onItemClicked(QListWidgetItem*))); - connect(button3, SIGNAL(clicked()), this, SLOT(onRemoveClicked())); - - machine->start(); -} - -void MainWindow::onEnterState2() -{ - currentState = state2; - if (listWidget->currentItem()) - editWidget->setText(listWidget->currentItem()->text()); -} - -void MainWindow::onEnterState1() -{ - if (currentState == state2 && listWidget->currentItem()) - listWidget->currentItem()->setText(editWidget->text()); - if (currentState == state3 && !editWidget->text().isNull()) { - new QListWidgetItem(editWidget->text(), listWidget); - editWidget->clear(); - } - currentState = state1; -} - -void MainWindow::onEnterState3() -{ - currentState = state3; -} - -void MainWindow::onItemClicked(QListWidgetItem*) -{ - if (currentState == state2) - { - editWidget->setText(listWidget->currentItem()->text()); - editWidget->clear(); - } -} - -void MainWindow::onRemoveClicked() -{ - QListWidgetItem *listItem = listWidget->takeItem(listWidget->currentRow()); - delete listItem; -} diff --git a/examples/animation/example/mainwindow.h b/examples/animation/example/mainwindow.h deleted file mode 100644 index 163eb89..0000000 --- a/examples/animation/example/mainwindow.h +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __MAINWINDOW__H__ -#define __MAINWINDOW__H__ - -#include - -class MainWindow : public QMainWindow -{ -Q_OBJECT -public: - MainWindow(); - -private slots : - void onEnterState3(); - void onEnterState2(); - void onEnterState1(); - void onItemClicked(QListWidgetItem*); - void onRemoveClicked(); -private: - QListWidget *listWidget; - QLabel *labelWidget; - QLabel *label2Widget; - QLineEdit *editWidget; - QGraphicsScene *scene; - QGraphicsView *view; - QState *state1; - QState *state2; - QState *state3; - QState *currentState; - QState *group; - QStateMachine *machine; -}; - -#endif //__MAINWINDOW__H__ - diff --git a/examples/animation/research/memberfunctions/main.cpp b/examples/animation/research/memberfunctions/main.cpp deleted file mode 100644 index 2663f9c..0000000 --- a/examples/animation/research/memberfunctions/main.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "qvalueanimation.h" - -AbstractProperty *qGraphicsItemProperty(QGraphicsItem *item, const char *property) -{ - if (qstrcmp(property, "pos") == 0) { - return new MemberFunctionProperty(item, &QGraphicsItem::pos, &QGraphicsItem::setPos); - } - return 0; -} - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - QGraphicsScene scene; - QGraphicsView view(&scene); - - QGraphicsItem *item = new QGraphicsRectItem(QRectF(0,0, 200, 100)); - scene.addItem(item); - - QValueAnimation *posAnim = new QValueAnimation; - posAnim->setStartValue(QPointF(0,0)); - posAnim->setEndValue(QPointF(400, 0)); - posAnim->setDuration(1000); - // Alternative 1 - //posAnim->setMemberFunction(item, &QGraphicsItem::pos, &QGraphicsItem::setPos); - - // Alternative 2 - //posAnim->setProperty(qMemberFunctionProperty(item, &QGraphicsItem::pos, &QGraphicsItem::setPos)); - - // Alternative 3 - posAnim->setProperty(qGraphicsItemProperty(item, "pos")); - - // Alternative 4, (by implementing the qGraphicsItemProperty QGraphicsItem::property()) - //posAnim->setProperty(item->property("pos")); - - // can also do this, which abstracts away the whole property thing. - // i.e. this interface can also be used for QObject-properties: - //posAnim->setAnimationProperty(animationProperty); - - posAnim->start(); - - view.resize(800,600); - view.show(); - return app.exec(); -} - diff --git a/examples/animation/research/memberfunctions/memberfunctions.pro b/examples/animation/research/memberfunctions/memberfunctions.pro deleted file mode 100644 index 6b67895..0000000 --- a/examples/animation/research/memberfunctions/memberfunctions.pro +++ /dev/null @@ -1,16 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) fr 26. sep 13:21:57 2008 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -# Input -SOURCES += main.cpp \ - qvalueanimation.cpp -HEADERS += qvalueanimation.h - -CONFIG += console - diff --git a/examples/animation/research/memberfunctions/qvalueanimation.cpp b/examples/animation/research/memberfunctions/qvalueanimation.cpp deleted file mode 100644 index de0b8ff..0000000 --- a/examples/animation/research/memberfunctions/qvalueanimation.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qvalueanimation.h" -#include "qvalueanimation_p.h" - -QT_BEGIN_NAMESPACE - - -void QValueAnimationPrivate::initDefaultStartValue() -{ - Q_Q(QValueAnimation); - if (animProp && !q->startValue().isValid() - && (currentTime == 0 - || (currentTime == duration && currentLoop == (loopCount - 1)))) { - setDefaultStartValue(animProp->read()); - } -} - - -QValueAnimation::QValueAnimation(QObject *parent) : QVariantAnimation(*new QValueAnimationPrivate, parent) -{ -} - -QValueAnimation::~QValueAnimation() -{ -} - -void QValueAnimation::setProperty(AbstractProperty *animProp) -{ - Q_D(QValueAnimation); - d->animProp = animProp; -} - -/*! - \reimp - */ -void QValueAnimation::updateCurrentValue(const QVariant &value) -{ - Q_D(QValueAnimation); - if (state() == QAbstractAnimation::Stopped) - return; - - d->animProp->write(value); -} - - -/*! - \reimp -*/ -void QValueAnimation::updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState) -{ - Q_D(QValueAnimation); - // Initialize start value - if (oldState == QAbstractAnimation::Stopped && newState == QAbstractAnimation::Running) - d->initDefaultStartValue(); -} - - - -#include "moc_qvalueanimation.cpp" - -QT_END_NAMESPACE diff --git a/examples/animation/research/memberfunctions/qvalueanimation.h b/examples/animation/research/memberfunctions/qvalueanimation.h deleted file mode 100644 index 17e9817..0000000 --- a/examples/animation/research/memberfunctions/qvalueanimation.h +++ /dev/null @@ -1,115 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QVALUEANIMATION_H -#define QVALUEANIMATION_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -class QGraphicsItem; -class QValueAnimationPrivate; - -QT_MODULE(Gui) - -struct AbstractProperty { - virtual void write(const QVariant &value) = 0; - virtual QVariant read() const = 0; -}; - -# define CALL_MEMBER_FN(object,ptrToMember) ((object)->*(ptrToMember)) -template -class MemberFunctionProperty : public AbstractProperty { -public: - typedef void (Target::*RefWrite)(const T &); - typedef T (Target::*ValRead)(void) const; - - MemberFunctionProperty(Target *target, ValRead readFunc, RefWrite writeFunc) - : m_target(target), m_readFn(readFunc), m_writeFn(writeFunc) {} - - virtual void write(const QVariant &value) { - CALL_MEMBER_FN(m_target, m_writeFn)(qVariantValue(value)); - } - - virtual QVariant read() const { - if (m_readFn) - return qVariantFromValue(CALL_MEMBER_FN(m_target, m_readFn)()); - return QVariant(); - } - -private: - Target *m_target; - ValRead m_readFn; - RefWrite m_writeFn; -}; - - -class QValueAnimation : public QVariantAnimation -{ - Q_OBJECT - -public: - QValueAnimation(QObject *parent = 0); - ~QValueAnimation(); - - template - void setMemberFunction(Target *target, - T (Target::*readFunc)(void) const, // ### useValRead typedef - void (Target::*writeFunc)(const T &) // ### use RefWrite typedef - ) { - // ### ownership of MemberFunctionProperty - AbstractProperty *animProp = new MemberFunctionProperty(target, readFunc, writeFunc); - setProperty(animProp); - } - - void updateCurrentValue(const QVariant &value); - void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - void setProperty(AbstractProperty *animProp); - -private: - Q_DISABLE_COPY(QValueAnimation); - Q_DECLARE_PRIVATE(QValueAnimation); -}; - -#endif // QVALUEANIMATION_H diff --git a/examples/animation/research/memberfunctions/qvalueanimation_p.h b/examples/animation/research/memberfunctions/qvalueanimation_p.h deleted file mode 100644 index 55c8ce1..0000000 --- a/examples/animation/research/memberfunctions/qvalueanimation_p.h +++ /dev/null @@ -1,77 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QVALUEANIMATION_P_H -#define QVALUEANIMATION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of QIODevice. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include //### - -QT_BEGIN_NAMESPACE - -class QValueAnimationPrivate : public QVariantAnimationPrivate -{ - Q_DECLARE_PUBLIC(QValueAnimation) -public: - QValueAnimationPrivate() : QVariantAnimationPrivate(), animProp(0) - { - } - - void initDefaultStartValue(); - - AbstractProperty *animProp; - - //###TODO -}; - -QT_END_NAMESPACE - -#endif //QVALUEANIMATION_P_H diff --git a/examples/animation/research/photobrowser/main.cpp b/examples/animation/research/photobrowser/main.cpp deleted file mode 100644 index d5ab2a3..0000000 --- a/examples/animation/research/photobrowser/main.cpp +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include "river.h" -#include "menu.h" - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - if (app.arguments().size() == 1) { - qWarning("you have to specifiy a path to look for the photos"); - return 0; - } - - - QGraphicsScene scene; - scene.setSceneRect(QRectF(QPointF(), River::fixedSize())); - - QGraphicsView view(&scene); - view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - - const int fw = view.frameWidth() * 2; - view.setFixedSize(River::fixedSize() + QSize(fw,fw)); - - River river(app.arguments()[1]); - scene.addItem(&river); - - Menu menu(&river); - menu.addAction(QLatin1String("River Mode"), &river, SLOT(setRiverMode())); - menu.addAction(QLatin1String("Grid Mode"), &river, SLOT(setGridMode())); - menu.addAction(QLatin1String("Cover Flow"), &river, SLOT(setCoverMode())); - menu.addAction(QLatin1String("Hide Menu"), &menu, SLOT(hide())); - menu.addAction(QLatin1String("Exit"), &app, SLOT(quit())); - menu.setZValue(2); - menu.setFocus(); - - river.menu = &menu; - view.show(); - - return app.exec(); -} diff --git a/examples/animation/research/photobrowser/menu.cpp b/examples/animation/research/photobrowser/menu.cpp deleted file mode 100644 index 97493ba..0000000 --- a/examples/animation/research/photobrowser/menu.cpp +++ /dev/null @@ -1,155 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "menu.h" - -Menu::Menu(QGraphicsItem *parent) : QGraphicsWidget(parent), m_selected(0) -{ - setFlag(QGraphicsItem::ItemIsFocusable); - m_selection = new QGraphicsRectItem(this); - QLinearGradient linearGrad(QPointF(0, 0), QPointF(0,50)); - linearGrad.setColorAt(0, QColor(255,255,255,128)); - linearGrad.setColorAt(1, QColor(255,255,255,16)); - m_selection->setBrush(linearGrad); - m_selection->setPen(QPen(Qt::transparent)); -} - -Menu::~Menu() -{ -} - - -MenuAction *Menu::addAction(const QString &text, QObject *receiver, const char* slot) -{ - MenuAction *action = new MenuAction(text, this); - if (!m_actions.isEmpty()) { - MenuAction *last = m_actions.last(); - action->setPos(last->pos() + last->boundingRect().bottomLeft()); - } - m_actions.append(action); - if (m_selection->boundingRect().width() < action->boundingRect().width()) - m_selection->setRect(action->boundingRect()); - - QObject::connect(action, SIGNAL(triggered()), receiver, slot); - return action; -} - -QRectF Menu::boundingRect() const -{ - QRectF res; - foreach (MenuAction *a, m_actions) - res |= a->boundingRect(); - return res; -} - -void Menu::keyPressEvent (QKeyEvent * event) -{ - switch (event->key()) { - case Qt::Key_Escape: - hide(); - break; - case Qt::Key_Up: - m_selected -= 2; - case Qt::Key_Down: - if (!m_actions.isEmpty()) { - m_selected = (m_selected + 1 + m_actions.count()) % m_actions.count(); - QItemAnimation *anim = new QItemAnimation(m_selection, QItemAnimation::Position); - anim->setEndValue(m_actions.at(m_selected)->pos()); - anim->start(QAbstractAnimation::DeleteWhenStopped); - } - break; - case Qt::Key_Enter: - case Qt::Key_Return: - if (!m_actions.isEmpty()) { - QItemAnimation *anim = new QItemAnimation(m_selection, QItemAnimation::RotationX); - anim->setEndValue(m_selection->xRotation() < 180 ? qreal(360) : qreal(0)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - m_actions.at(m_selected)->trigger(); - hide(); - } - break; - default: - QGraphicsItem::keyPressEvent(event); - } -} - -void Menu::show() -{ - QItemAnimation *anim = new QItemAnimation(this, QItemAnimation::Opacity); - anim->setEndValue(qreal(1.)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(m_selection, QItemAnimation::ScaleFactorX); - anim->setEndValue(qreal(1)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(m_selection, QItemAnimation::ScaleFactorY); - anim->setEndValue(qreal(1)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - setFocus(); -} - -void Menu::hide() -{ - QItemAnimation *anim = new QItemAnimation(m_selection, QItemAnimation::ScaleFactorX); - anim->setEndValue(qreal(.1)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(m_selection, QItemAnimation::ScaleFactorY); - anim->setEndValue(qreal(.1)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(this, QItemAnimation::Opacity); - anim->setEndValue(qreal(0)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - parentItem()->setFocus(); -} - - -MenuAction::MenuAction(const QString &text, Menu * parent) - : QGraphicsTextItem(text,parent) -{ - QFont f = font(); - f.setPointSize(18); - setFont(f); - setDefaultTextColor(Qt::white); -} - -void MenuAction::trigger() -{ - emit triggered(); -} diff --git a/examples/animation/research/photobrowser/menu.h b/examples/animation/research/photobrowser/menu.h deleted file mode 100644 index 3bdfe45..0000000 --- a/examples/animation/research/photobrowser/menu.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __MENU__H__ -#define __MENU__H__ - -#include - -class MenuAction; - -class Menu : public QGraphicsWidget -{ - Q_OBJECT -public: - Menu(QGraphicsItem *parent); - ~Menu(); - - MenuAction *addAction(const QString&, QObject *receiver = 0, const char* slot = 0 ); - - QRectF boundingRect() const; - void keyPressEvent ( QKeyEvent * event ); -public slots: - void show(); - void hide(); -private: - QList m_actions; - QGraphicsRectItem *m_selection; - int m_selected; -}; - -class MenuAction : public QGraphicsTextItem -{ - Q_OBJECT -public: - MenuAction(const QString &text, Menu * parent); - void trigger(); -signals: - void triggered(); -}; - - -#endif //__RIVERITEM__H__ diff --git a/examples/animation/research/photobrowser/photobrowser.pro b/examples/animation/research/photobrowser/photobrowser.pro deleted file mode 100644 index 21f03d6..0000000 --- a/examples/animation/research/photobrowser/photobrowser.pro +++ /dev/null @@ -1,17 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) ven. 22. août 13:09:33 2008 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -# Input -SOURCES += main.cpp \ - river.cpp \ - riveritem.cpp \ - menu.cpp -HEADERS += river.h \ - riveritem.h \ - menu.h diff --git a/examples/animation/research/photobrowser/river.cpp b/examples/animation/research/photobrowser/river.cpp deleted file mode 100644 index 6760066..0000000 --- a/examples/animation/research/photobrowser/river.cpp +++ /dev/null @@ -1,591 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "river.h" -#include "riveritem.h" - -#include "qvariantanimation.h" - -#include -#include -#include -#include - - -#define GRID_ROW_COUNT 3 -#define GRID_COLUMN_COUNT 2 -#define GRID_DIMENSIONS (GRID_ROW_COUNT * GRID_COLUMN_COUNT) -#define ITEM_COUNT 12 - -#define RIVER_MAGNIFY(ITEM) (qreal(0.50) + (ITEM)->zValue()*2 ) -#define GRID_MAGNIFY qreal(1.5) -#define GRID_CURRENT_MAGNIFY 2 - -River::River(const QString &path) : -m_images(QDir(path).entryInfoList(QStringList() << QLatin1String("*.jpg") << QLatin1String("*.png"))), -m_currentImage(0), m_mode(RiverMode), m_selectedItem(-1) , m_topLeftIndex(-1) -{ - setFocusPolicy(Qt::StrongFocus); - setGeometry(QRectF( QPointF(), fixedSize())); - - - for (int i = 0; i < ITEM_COUNT; ++i) { - RiverItem * item = new RiverItem(this); - - //here we also randomize the x position (not when looping) - const int x = qrand() % fixedSize().width(); - item->setPos(x, -1); - - m_items.insert(m_currentImage, item); - addUnusedRiverItem(item); - } - -} - -QPointF River::gridItemPosition(int row, int col) const -{ - if (col < 0) { - col += GRID_COLUMN_COUNT; - row --; - } - return QPointF(rect().width()*(col*2 + 1)/(GRID_COLUMN_COUNT*2), - rect().height()*(row*2 + 1)/(GRID_ROW_COUNT*2)); -} - -QPixmap River::pixmap(int index) const -{ - if (index < 0 || index >= m_images.size()) - return QPixmap(); - - if (m_pixmaps.size() <= index) { - m_pixmaps.resize(index+1); - } - - if (m_pixmaps.at(index).isNull()) { - m_pixmaps[index] = QPixmap(m_images.at(index).absoluteFilePath()); - } - - return m_pixmaps.at(index); -} - -void River::addUnusedRiverItem(RiverItem * item) -{ - if (m_images.isEmpty()) - return; - - QRectF realItemRect = item->mapToParent(item->boundingRect()).boundingRect(); - - int y = item->pos().y(); - int x = item->pos().x(); - if (x >= fixedSize().width() || x < -realItemRect.width() || y < 0) { - //we set the new pixmap - - m_items.remove(m_items.key(item)); - - while (m_items.contains(m_currentImage)) - m_currentImage = (m_currentImage + 1 ) % m_images.size(); - - item->setPixmap(pixmap(m_currentImage)); - - m_items.insert(m_currentImage, item); - //this manages looping as well - m_currentImage = (m_currentImage + 1 ) % m_images.size(); - - item->setZValue(qreal(qrand()%100)/200.0); - - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::ScaleFactorX, scene()); - anim->setEndValue(RIVER_MAGNIFY(item)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorY, scene()); - anim->setEndValue(RIVER_MAGNIFY(item)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - - realItemRect = item->mapToParent(item->boundingRect()).boundingRect(); - - y = -realItemRect.y() + qrand() % (fixedSize().height() - int(realItemRect.height())); - if (x >= fixedSize().width()) { - x = -realItemRect.width()/2; - } - } - - item->setPos(x, y); - - const QPointF target(QPointF(fixedSize().width() + realItemRect.width()/2, y)); - - const int distance = target.x() - x; - - const int duration = (40 - 50*item->zValue() ) * distance; - QItemAnimation *a = new QItemAnimation(item, QItemAnimation::Position, scene()); - a->setEndValue(target); - a->setDuration(duration); - a->start(QAbstractAnimation::DeleteWhenStopped); - connect(a, SIGNAL(finished()), SLOT(animationFinished())); -} - -void River::animationFinished() -{ - QItemAnimation *anim = qobject_cast(sender()); - if (!anim || anim->propertyName() != QItemAnimation::Position) - return; - - /*RiverItem *item = static_cast(anim->graphicsItem()); - if (m_mode != RiverMode) {*/ - /*int key = m_items.key(item); - if (key < m_topLeftIndex || key >= m_topLeftIndex + GRID_DIMENSIONS) { - delete item; - m_items.remove(key); - }*/ - //return; - - //} - - addUnusedRiverItem(static_cast(anim->targetItem())); -} - -void River::switchPaused() -{ - const bool paused = m_pausedAnimations.isEmpty(); - if (paused) - m_pausedAnimations = scene()->findChildren(); - - foreach(QItemAnimation *anim, m_pausedAnimations) { - if (paused) - anim->pause(); - else - anim->resume(); - } - - if (!paused) - m_pausedAnimations.clear(); -} - -void River::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) -{ - painter->fillRect(option->rect, Qt::black); -} - -void River::setMode(Mode m) -{ - if (m_mode == m) - return; - - Mode oldMode = m_mode; - m_mode = m; - switch(m) - { - case RiverMode: - m_mode = oldMode; //some animation may be stopt, and we don't want that animationFinished we were in that mode yet - foreach (RiverItem *item, m_items) { - const int x = qrand() % fixedSize().width(); - const int y = qrand() % fixedSize().width(); - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::ScaleFactorX, scene()); - anim->setEndValue(RIVER_MAGNIFY(item)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorY, scene()); - anim->setEndValue(RIVER_MAGNIFY(item)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(item, QItemAnimation::Position, scene()); - anim->setEndValue(QPointF(x, y)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - connect(anim, SIGNAL(finished()), SLOT(animationFinished())); - } - m_mode = m; - break; - - case GridMode: - - if (oldMode == GridFullScreenMode) { - currentItem()->setFullScreen(false, GRID_CURRENT_MAGNIFY); - } else { - m_topLeftIndex = -GRID_DIMENSIONS; - foreach (RiverItem *item, m_items) { - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::ScaleFactorX, scene()); - anim->setEndValue(GRID_MAGNIFY); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorY, scene()); - anim->setEndValue(GRID_MAGNIFY); - anim->start(QAbstractAnimation::DeleteWhenStopped); - } - adjustGrid(m_currentImage - GRID_DIMENSIONS + 1); - setCurrentItem(m_topLeftIndex); - } - break; - case GridFullScreenMode: - //let's put the current item fullscreen - currentItem()->setFullScreen(true, GRID_CURRENT_MAGNIFY); - break; - case CoverMode: - m_gridItem = m_items.values(); - setCurrentItem(m_gridItem.count()/2); - default: - break; - } -} - -River::Mode River::mode() const -{ - return m_mode; -} - -QSize River::fixedSize() -{ - return QSize(352, 416); -} - -//the name of this method is not that good... -void River::makeCenterAvailable(qreal size) -{ - QRectF center(QPointF(), QSizeF(size, size)); - center.moveCenter(rect().center()); - - const QList list = scene()->items(center); - - foreach(QGraphicsItem *item, m_items) { - - if (!list.contains(item)) - continue; - - QPointF pos = item->pos(); - - if (pos.y() < rect().center().y()) { - //item is above center - pos.ry() = center.top() - item->boundingRect().height() - 1; - } else { - //item is below the center - pos.ry() = center.bottom() + 1; - } - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::Position, scene()); - anim->setEndValue(pos); - anim->setDuration(150); - anim->start(QAbstractAnimation::DeleteWhenStopped); - } -} - - -//this is there just to test small interaction -void River::keyPressEvent ( QKeyEvent * keyEvent ) -{ - switch(keyEvent->key()) - { - case Qt::Key_O: - { - QItemAnimation *anim = new QItemAnimation(this, QItemAnimation::Opacity, scene()); - anim->setDuration(2000); - anim->setEndValue(qreal(.5)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - } - break; - case Qt::Key_N: - //that's a test - makeCenterAvailable(60); - break; - case Qt::Key_P: - switchPaused(); - break; - case Qt::Key_V: - setMode(GridMode); - break; - case Qt::Key_R: - setMode(RiverMode); - break; - case Qt::Key_C: - setMode(CoverMode); - break; - case Qt::Key_Return: - case Qt::Key_Enter: - if (m_mode == RiverMode) { - setMode(GridMode); - } else if (m_mode == GridMode) { - setMode(GridFullScreenMode); - } else if (m_mode == GridFullScreenMode) { - setMode(GridMode); - } - break; - case Qt::Key_Escape: - if (m_mode == GridFullScreenMode) { - setMode(GridMode); - } else if (m_mode == GridMode || m_mode == CoverMode) { - setMode(RiverMode); - } else if (m_mode == RiverMode) { - menu->show(); - } - break; - case Qt::Key_Right: - if (m_mode == GridMode) { - navigateBy(+1); - } else if (m_mode == CoverMode) { - setCurrentItem(m_selectedItem + 1); - } - break; - case Qt::Key_Left: - if (m_mode == GridMode) { - navigateBy(-1); - } else if (m_mode == CoverMode) { - setCurrentItem(m_selectedItem - 1); - } - break; - case Qt::Key_Down: - if (m_mode == GridMode) { - navigateBy(GRID_COLUMN_COUNT); - } - break; - case Qt::Key_Up: - if (m_mode == GridMode) { - navigateBy(-GRID_COLUMN_COUNT); - } - break; -// case Qt::Key_PageUp: - case Qt::Key_M: - menu->show(); - break; - case Qt::Key_Space: - if (m_mode == GridMode) { - RiverItem *item = currentItem(); - if(!item) - break; - - //stupid sequence. - QPointF pos = item->pos(); - QAnimationGroup *group = new QSequentialAnimationGroup(); - //item->animator()->beginSequence(); - - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::Position, scene()); - anim->setEndValue(pos); - group->addAnimation(anim); - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorX, scene()); - anim->setEndValue(qreal(1.)); - anim->setDuration(500); - group->addAnimation(anim); - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorY, scene()); - anim->setEndValue(qreal(1.)); - anim->setDuration(500); - group->addAnimation(anim); - anim = new QItemAnimation(item, QItemAnimation::RotationX, scene()); - anim->setEndValue(qreal(0)); - group->addAnimation(anim); - group->start(QAbstractAnimation::DeleteWhenStopped); - } - default: - break; - } - - QGraphicsItem::keyPressEvent(keyEvent); -} - - -void River::setGridMode() -{ - setMode(GridMode); -} - -void River::setRiverMode() -{ - setMode(RiverMode); -} - -void River::setCoverMode() -{ - setMode(CoverMode); -} - - -void River::adjustGrid(int newTopLeft) -{ - for (int i = newTopLeft ; i < newTopLeft + GRID_DIMENSIONS; i++) { - if (!m_items.contains(i)) { - RiverItem *item = createItem(i); - int row = (i - m_topLeftIndex) / GRID_COLUMN_COUNT; - int col = (i - m_topLeftIndex) % GRID_COLUMN_COUNT; - item->setPos(gridItemPosition(row, col)); - item->setXScale(0); - item->setYScale(0); - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::ScaleFactorX, scene()); - anim->setEndValue(GRID_MAGNIFY); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorY, scene()); - anim->setEndValue(GRID_MAGNIFY); - anim->start(QAbstractAnimation::DeleteWhenStopped); - } - } - newTopLeft = newTopLeft - newTopLeft % GRID_COLUMN_COUNT; - - QHash::iterator it = m_items.begin(); - while (it != m_items.constEnd()) { - const int imageIdx = it.key(); - RiverItem *item = *it; - QSizeF itemSize = item->boundingRect().size(); - if ((imageIdx >= newTopLeft && imageIdx < newTopLeft + GRID_DIMENSIONS) - || boundingRect().adjusted(-itemSize.width()/2, -itemSize.height()/2, itemSize.width()/2, itemSize.height()/2) - .contains(item->pos())) { - int row = (imageIdx-newTopLeft) / GRID_COLUMN_COUNT; - int col = (imageIdx-newTopLeft) % GRID_COLUMN_COUNT; - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::Position, scene()); - anim->setEndValue(gridItemPosition(row, col)); - anim->start(QAbstractAnimation::DeleteWhenStopped); - ++it; - } else { - ++it; /* ### ideally we should remove the items, but this cause the photobrowser to crash - because the QItemAnimations are not notified the item is deleted - delete item; - it = m_items.erase(it); - */ - } - } - - m_topLeftIndex = newTopLeft; -} - - -RiverItem *River::createItem(int imageIndex) -{ - Q_ASSERT(!m_items.contains(imageIndex)); - RiverItem * item = new RiverItem(this); - item->setPixmap(pixmap(imageIndex)); - m_items.insert(imageIndex,item); - return item; -} - -void River::setCurrentItem(int newCurrentItem) -{ - if (m_mode == CoverMode) - { - m_selectedItem = newCurrentItem; - for (int i = 0; i < m_gridItem.count(); i++) { - QVariantAnimation *anim; - RiverItem *item = m_gridItem.at(i); - - qreal rotation = 0; - qreal width = boundingRect().width() / 2; - qreal x = width; - qreal scale = 3; - qreal z = 1; - qreal y = boundingRect().height()/2; - - if (i < newCurrentItem - 4) { - item->setVisible(false); - item->setPos(QPointF(0, y)); - continue; - } else if(i > newCurrentItem + 4) { - item->setVisible(false); - item->setPos(QPointF(boundingRect().width(), y)); - continue; - } else if (i < newCurrentItem) { - x = (i - newCurrentItem + 4) * width/7; - rotation = -75; - scale = 2; - z = 1.+qreal(i-newCurrentItem)/10.; - } else if (i > newCurrentItem) { - x = width + (i - newCurrentItem + 3) * width/7; - rotation = 75; - scale = 2; - z = 1.-qreal(i-newCurrentItem)/8.; - } - - item->setVisible(true); - item->setZValue(z); - - anim = new QItemAnimation(item, QItemAnimation::RotationY, scene()); - anim->setEndValue(rotation); - anim->start(QAbstractAnimation::DeleteWhenStopped); - - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorX, scene()); - anim->setEndValue(scale); - anim->start(QVariantAnimation::DeleteWhenStopped); - - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorY, scene()); - anim->setEndValue(scale); - anim->start(QVariantAnimation::DeleteWhenStopped); - - anim = new QItemAnimation(item, QItemAnimation::Position, scene()); - anim->setEndValue(QPointF(x,y)); - anim->start(QVariantAnimation::DeleteWhenStopped); - } - return; - } - - - //deselect the current item - if (m_selectedItem >= 0 && m_items.contains(m_selectedItem)) { - RiverItem *item = m_items.value(m_selectedItem); - item->setZValue(qreal(qrand()%100)/200.0); - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::ScaleFactorX, scene()); - anim->setEndValue(GRID_MAGNIFY); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorY, scene()); - anim->setEndValue(GRID_MAGNIFY); - anim->start(QAbstractAnimation::DeleteWhenStopped); - } - - if (newCurrentItem < 0) { - m_selectedItem = newCurrentItem; - return; - } - - //ensure visible; - if (newCurrentItem < m_topLeftIndex) { - adjustGrid(newCurrentItem); - } else if (newCurrentItem >= m_topLeftIndex + GRID_DIMENSIONS) { - adjustGrid(newCurrentItem - GRID_DIMENSIONS + GRID_COLUMN_COUNT); - } - - //select the new one - m_selectedItem = newCurrentItem; - RiverItem *item = currentItem(); - Q_ASSERT(item); - item->setZValue(1); - - QItemAnimation *anim = new QItemAnimation(item, QItemAnimation::ScaleFactorX, scene()); - anim->setEndValue(GRID_CURRENT_MAGNIFY); - anim->start(QAbstractAnimation::DeleteWhenStopped); - anim = new QItemAnimation(item, QItemAnimation::ScaleFactorY, scene()); - anim->setEndValue(GRID_CURRENT_MAGNIFY); - anim->start(QAbstractAnimation::DeleteWhenStopped); -} - -void River::navigateBy(int offset) -{ - int newSelection = m_selectedItem + offset; - const int imageCount = m_images.size(); - while (newSelection < 0) - newSelection += imageCount; - newSelection %= imageCount; - setCurrentItem(newSelection); -} diff --git a/examples/animation/research/photobrowser/river.h b/examples/animation/research/photobrowser/river.h deleted file mode 100644 index d6bfc76..0000000 --- a/examples/animation/research/photobrowser/river.h +++ /dev/null @@ -1,111 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __RIVER__H__ -#define __RIVER__H__ - -#include -#include - -#include "menu.h" - -class RiverItem; - -class River : public QGraphicsWidget -{ - Q_OBJECT -public: - enum Mode - { - RiverMode, - GridMode, - GridFullScreenMode, - CoverMode - }; - - River(const QString &path); - void addUnusedRiverItem(RiverItem * item); - - static QSize fixedSize(); - - void switchPaused(); - - void setMode(Mode m); - Mode mode() const; - - Menu *menu; - -protected: - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - void keyPressEvent ( QKeyEvent * keyEvent ); - void makeCenterAvailable(qreal size); - QPointF gridItemPosition(int row, int col) const; - QPixmap pixmap(int index) const; - -protected slots: - void animationFinished(); -public slots: - void setRiverMode(); - void setGridMode(); - void setCoverMode(); - -private: - const QFileInfoList m_images; - int m_currentImage; - mutable QVector m_pixmaps; - QHash m_items; - QList m_gridItem; - QList m_pausedAnimations; - Mode m_mode; - - void adjustGrid(int topRight); - RiverItem *currentItem() { return m_items.value(m_selectedItem); } - RiverItem *createItem(int imageIndex); - void setCurrentItem(int currentItem); - void navigateBy(int offset); - - int m_selectedItem; - int m_topLeftIndex; - -}; - - -#endif //__RIVERITEM__H__ diff --git a/examples/animation/research/photobrowser/riveritem.cpp b/examples/animation/research/photobrowser/riveritem.cpp deleted file mode 100644 index 9692d30..0000000 --- a/examples/animation/research/photobrowser/riveritem.cpp +++ /dev/null @@ -1,125 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "riveritem.h" -#include "river.h" - -RiverItem::RiverItem(QGraphicsItem *parent) : QGraphicsPixmapItem(parent), m_fullscreen(false) -{ - setCacheMode(DeviceCoordinateCache); -} - -RiverItem::~RiverItem() -{ -} - -void RiverItem::setPixmap(const QPixmap &pix) -{ - const QSize oldSize = pixmap().size(); - const QSize newSize = pix.size(); - QGraphicsPixmapItem::setPixmap(pix); - - if (newSize != oldSize) { - setOffset(-newSize.width()/2, -newSize.height()/2); - const qreal scaleFactor = qreal(River::fixedSize().height())/(qreal(pix.height()*7)); - setTransform(QTransform().scale(scaleFactor, scaleFactor)); - prepareGeometryChange(); - } -} - - -void RiverItem::setFullScreen(bool b, qreal originScaleFactor) -{ - if (m_fullscreen == b) - return; - - m_fullscreen = b; - - QPointF newPos; - qreal rotationZ; - qreal scaleX, scaleY; - - if (b) { - const QSizeF basePixmapSize = transform().map(boundingRect()).boundingRect().size(); - - newPos = parentItem()->boundingRect().center(); - rotationZ = 90; - scaleY = qreal(River::fixedSize().width()) / basePixmapSize.height() * yScale(); - scaleX = qreal(River::fixedSize().height()) / basePixmapSize.width() * xScale(); - - if (m_nonFSPos.isNull()) { - m_nonFSPos = pos(); //let's save our current (non fullscreen) position - } - - } else { - Q_ASSERT(!m_nonFSPos.isNull()); - rotationZ = 0; - scaleX = originScaleFactor; - scaleY = originScaleFactor; - newPos = m_nonFSPos; - } - - QAnimationGroup *group = new QParallelAnimationGroup(scene()); - QItemAnimation *anim = new QItemAnimation(this, QItemAnimation::Position); - anim->setEndValue(newPos); - group->addAnimation(anim); - anim = new QItemAnimation(this, QItemAnimation::RotationZ); - anim->setEndValue(rotationZ); - group->addAnimation(anim); - anim = new QItemAnimation(this, QItemAnimation::ScaleFactorX); - anim->setEndValue(scaleX); - group->addAnimation(anim); - anim = new QItemAnimation(this, QItemAnimation::ScaleFactorY); - anim->setEndValue(scaleY); - group->addAnimation(anim); - group->start(QAbstractAnimation::DeleteWhenStopped); -} - -void RiverItem::mousePressEvent(QGraphicsSceneMouseEvent*) -{ - //just let it rotate on itself - QItemAnimation *anim = new QItemAnimation(this, QItemAnimation::RotationY); - anim->setEndValue(yRotation() < 180 ? 360 : 0); - anim->setDuration(500); - anim->start(QAbstractAnimation::DeleteWhenStopped); -} - - diff --git a/examples/animation/research/photobrowser/riveritem.h b/examples/animation/research/photobrowser/riveritem.h deleted file mode 100644 index 2023c44..0000000 --- a/examples/animation/research/photobrowser/riveritem.h +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __RIVERITEM__H__ -#define __RIVERITEM__H__ - -#include - -class RiverItemAnimator; - -class RiverItem : public QGraphicsPixmapItem -{ -public: - RiverItem(QGraphicsItem *parent); - ~RiverItem(); - - void setPixmap(const QPixmap &); - void setFullScreen(bool b, qreal originScaleFactor); - -protected: - void mousePressEvent(QGraphicsSceneMouseEvent*); - -private: - QPointF m_nonFSPos; //to save the position when not in fullscreen - bool m_fullscreen; -}; - -#endif //__RIVERITEM__H__ diff --git a/examples/animation/research/piemenu/main.cpp b/examples/animation/research/piemenu/main.cpp deleted file mode 100644 index 8076da8..0000000 --- a/examples/animation/research/piemenu/main.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "scene.h" -#include "qgraphicspiemenu.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - Scene scene; - - QGraphicsView view(&scene); - view.show(); - - return app.exec(); -} diff --git a/examples/animation/research/piemenu/piemenu.pro b/examples/animation/research/piemenu/piemenu.pro deleted file mode 100644 index 4d7a067..0000000 --- a/examples/animation/research/piemenu/piemenu.pro +++ /dev/null @@ -1,8 +0,0 @@ -SOURCES += \ - main.cpp \ - qgraphicspiemenu.cpp \ - scene.cpp -HEADERS += \ - qgraphicspiemenu.h \ - qgraphicspiemenu_p.h \ - scene.h diff --git a/examples/animation/research/piemenu/qgraphicspiemenu.cpp b/examples/animation/research/piemenu/qgraphicspiemenu.cpp deleted file mode 100644 index a199119..0000000 --- a/examples/animation/research/piemenu/qgraphicspiemenu.cpp +++ /dev/null @@ -1,250 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qgraphicspiemenu.h" -#include "qgraphicspiemenu_p.h" - -#include - -QGraphicsPieMenu::QGraphicsPieMenu(QGraphicsItem *parent) - : QGraphicsWidget(parent), d_ptr(new QGraphicsPieMenuPrivate) -{ - d_ptr->q_ptr = this; - d_ptr->machine = new QStateMachine(); - d_ptr->popupState = new QState(d_ptr->machine->rootState()); - d_ptr->machine->setInitialState(d_ptr->popupState); - d_ptr->menuAction = new QAction(this); -} - -QGraphicsPieMenu::QGraphicsPieMenu(const QString &title, QGraphicsItem *parent) - : QGraphicsWidget(parent), d_ptr(new QGraphicsPieMenuPrivate) -{ - d_ptr->q_ptr = this; - d_ptr->machine = new QStateMachine(); - d_ptr->popupState = new QState(d_ptr->machine->rootState()); - d_ptr->machine->setInitialState(d_ptr->popupState); - d_ptr->menuAction = new QAction(this); - setTitle(title); -} - -QGraphicsPieMenu::QGraphicsPieMenu(const QIcon &icon, const QString &title, QGraphicsItem *parent) - : QGraphicsWidget(parent), d_ptr(new QGraphicsPieMenuPrivate) -{ - d_ptr->q_ptr = this; - d_ptr->machine = new QStateMachine(); - d_ptr->popupState = new QState(d_ptr->machine->rootState()); - d_ptr->machine->setInitialState(d_ptr->popupState); - d_ptr->menuAction = new QAction(this); - setIcon(icon); - setTitle(title); -} - -QGraphicsPieMenu::~QGraphicsPieMenu() -{ - delete d_ptr; -} - -QAction *QGraphicsPieMenu::addAction(const QString &text) -{ - QAction *action = new QAction(text, this); - addAction(action); - return action; -} - -QAction *QGraphicsPieMenu::addAction(const QIcon &icon, const QString &text) -{ - QAction *action = new QAction(icon, text, this); - addAction(action); - return action; -} - -QAction *QGraphicsPieMenu::addAction(const QString &text, const QObject *receiver, const char *member, const QKeySequence &shortcut) -{ - QAction *action = new QAction(text, this); - action->setShortcut(shortcut); - connect(action, SIGNAL(triggered(bool)), receiver, member); - addAction(action); - return action; -} - -QAction *QGraphicsPieMenu::addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char *member, const QKeySequence &shortcut) -{ - QAction *action = new QAction(icon, text, this); - action->setShortcut(shortcut); - connect(action, SIGNAL(triggered(bool)), receiver, member); - addAction(action); - return action; -} - -QAction *QGraphicsPieMenu::addMenu(QGraphicsPieMenu *menu) -{ - QAction *action = menu->menuAction(); - addAction(action); - return action; -} - -QGraphicsPieMenu *QGraphicsPieMenu::addMenu(const QString &title) -{ - QGraphicsPieMenu *menu = new QGraphicsPieMenu(title, this); - addMenu(menu); - return menu; -} - -QGraphicsPieMenu *QGraphicsPieMenu::addMenu(const QIcon &icon, const QString &title) -{ - QGraphicsPieMenu *menu = new QGraphicsPieMenu(icon, title, this); - addMenu(menu); - return menu; -} - -QAction *QGraphicsPieMenu::addSeparator() -{ - QAction *action = new QAction(this); - action->setSeparator(true); - addAction(action); - return action; -} - -QAction *QGraphicsPieMenu::insertMenu(QAction *before, QGraphicsPieMenu *menu) -{ - QAction *action = menu->menuAction(); - insertAction(before, action); - return action; -} - -QAction *QGraphicsPieMenu::insertSeparator(QAction *before) -{ - QAction *action = new QAction(this); - action->setSeparator(true); - insertAction(before, action); - return action; -} - -QAction *QGraphicsPieMenu::menuAction() const -{ - return d_func()->menuAction; -} - -bool QGraphicsPieMenu::isEmpty() const -{ - // ### d->actions - QList actionList = actions(); - bool ret = true; - for (int i = 0; ret && i < actionList.size(); ++i) { - const QAction *action = actionList.at(i); - if (!action->isSeparator() && action->isVisible()) { - ret = false; - break; - } - } - return ret; -} - -void QGraphicsPieMenu::clear() -{ - // ### d->actions - QList actionList = actions(); - for(int i = 0; i < actionList.size(); i++) { - QAction *action = actionList.at(i); - removeAction(action); - if (action->parent() == this && action->associatedGraphicsWidgets().isEmpty()) - delete action; - } -} - -void QGraphicsPieMenu::popup(const QPointF &pos) -{ - Q_UNUSED(pos); - Q_D(QGraphicsPieMenu); - d->machine->start(); -} - -QAction *QGraphicsPieMenu::exec() -{ - return exec(pos()); -} - -QAction *QGraphicsPieMenu::exec(const QPointF &pos) -{ - Q_UNUSED(pos); - return 0; -} - -QAction *QGraphicsPieMenu::exec(QList actions, const QPointF &pos) -{ - QGraphicsPieMenu menu; - for (QList::ConstIterator it = actions.constBegin(); it != actions.constEnd(); ++it) - menu.addAction(*it); - return menu.exec(pos); -} - -QString QGraphicsPieMenu::title() const -{ - Q_D(const QGraphicsPieMenu); - return d->title; -} - -void QGraphicsPieMenu::setTitle(const QString &title) -{ - Q_D(QGraphicsPieMenu); - d->title = title; - updateGeometry(); -} - -QIcon QGraphicsPieMenu::icon() const -{ - Q_D(const QGraphicsPieMenu); - return d->icon; -} - -void QGraphicsPieMenu::setIcon(const QIcon &icon) -{ - Q_D(QGraphicsPieMenu); - d->icon = icon; - updateGeometry(); -} - -QSizeF QGraphicsPieMenu::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const -{ - Q_UNUSED(which); - Q_UNUSED(constraint); - return QSizeF(1, 1); -} diff --git a/examples/animation/research/piemenu/qgraphicspiemenu.h b/examples/animation/research/piemenu/qgraphicspiemenu.h deleted file mode 100644 index d784f93..0000000 --- a/examples/animation/research/piemenu/qgraphicspiemenu.h +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QGRAPHICSPIEMENU_H -#define QGRAPHICSPIEMENU_H - -#include - -class QGraphicsPieMenuPrivate; -class QGraphicsPieMenu : public QGraphicsWidget -{ - Q_OBJECT -public: - QGraphicsPieMenu(QGraphicsItem *parent = 0); - QGraphicsPieMenu(const QString &title, QGraphicsItem *parent = 0); - QGraphicsPieMenu(const QIcon &icon, const QString &title, QGraphicsItem *parent = 0); - ~QGraphicsPieMenu(); - -#ifdef Q_NO_USING_KEYWORD - inline void addAction(QAction *action) { QGraphicsWidget::addAction(action); } -#else - using QGraphicsWidget::addAction; -#endif - QAction *addAction(const QString &text); - QAction *addAction(const QIcon &icon, const QString &text); - QAction *addAction(const QString &text, const QObject *receiver, const char *member, const QKeySequence &shortcut = 0); - QAction *addAction(const QIcon &icon, const QString &text, const QObject *receiver, const char *member, const QKeySequence &shortcut = 0); - QAction *addMenu(QGraphicsPieMenu *menu); - QGraphicsPieMenu *addMenu(const QString &title); - QGraphicsPieMenu *addMenu(const QIcon &icon, const QString &title); - QAction *addSeparator(); - QAction *insertMenu(QAction *before, QGraphicsPieMenu *menu); - QAction *insertSeparator(QAction *before); - - QAction *menuAction() const; - - bool isEmpty() const; - void clear(); - - void popup(const QPointF &pos); - QAction *exec(); - QAction *exec(const QPointF &pos); - static QAction *exec(QList actions, const QPointF &pos); - - QString title() const; - void setTitle(const QString &title); - - QIcon icon() const; - void setIcon(const QIcon &icon); - -Q_SIGNALS: - void aboutToShow(); - void aboutToHide(); - void triggered(QAction *action); - void hovered(QAction *action); - -protected: - QSizeF sizeHint(Qt::SizeHint which, const QSizeF &constraint = QSizeF()) const; - -private: - Q_DISABLE_COPY(QGraphicsPieMenu) - Q_DECLARE_PRIVATE(QGraphicsPieMenu) - QGraphicsPieMenuPrivate *d_ptr; -}; - -#endif diff --git a/examples/animation/research/piemenu/qgraphicspiemenu_p.h b/examples/animation/research/piemenu/qgraphicspiemenu_p.h deleted file mode 100644 index 458b8f1..0000000 --- a/examples/animation/research/piemenu/qgraphicspiemenu_p.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QGRAPHICSPIEMENU_P_H -#define QGRAPHICSPIEMENU_P_H - -#include "qgraphicspiemenu.h" -#include "qgraphicspiemenusection_p.h" - -#include -#include -#include -#include - -class QAction; -class QEventLoop; -class QGraphicsPieMenuSection; - -class QGraphicsPieMenuPrivate -{ - Q_DECLARE_PUBLIC(QGraphicsPieMenu); -public: - void init(const QIcon &icon = QIcon(), const QString &title = QString()); - - QIcon icon; - QString title; - QStateMachine *machine; - QState *popupState; - //QTransition *transition; - QList sections; - - QEventLoop *eventLoop; - - QAction *menuAction; - QGraphicsPieMenu *q_ptr; - - void updatePopupState(); -}; - -#endif diff --git a/examples/animation/research/piemenu/qgraphicspiemenusection_p.h b/examples/animation/research/piemenu/qgraphicspiemenusection_p.h deleted file mode 100644 index 2d71a06..0000000 --- a/examples/animation/research/piemenu/qgraphicspiemenusection_p.h +++ /dev/null @@ -1,88 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QGRAPHICSPIEMENUSECTION_H -#define QGRAPHICSPIEMENUSECTION_H - -#include -#include - -class QGraphicsPieMenuSection : public QGraphicsWidget -{ - Q_OBJECT - Q_PROPERTY(qreal rotation READ rotation WRITE setRotation) -public: - QGraphicsPieMenuSection(QGraphicsItem *parent = 0) - : QGraphicsWidget(parent), rot(0) - { } - - qreal rotation() const - { - return rot; - } - void setRotation(qreal rotation) - { - rot = rotation; - setTransform(QTransform().rotate(rot)); - } - - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) - { - Q_UNUSED(option); - Q_UNUSED(widget); - painter->setPen(QPen(Qt::black, 1)); - painter->setBrush(QBrush(Qt::gray)); - painter->drawPie(QRectF(-100, -100, 200, 200), 0, -30 * 16); - } - -protected: - QSizeF sizeHint(Qt::SizeHint which, const QSizeF &size = QSizeF()) const - { - Q_UNUSED(which); - Q_UNUSED(size); - return QSizeF(100, 30); - } - -private: - qreal rot; -}; - -#endif diff --git a/examples/animation/research/piemenu/scene.cpp b/examples/animation/research/piemenu/scene.cpp deleted file mode 100644 index 6309975..0000000 --- a/examples/animation/research/piemenu/scene.cpp +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qgraphicspiemenu.h" -#include "scene.h" - -#include -#include - -Scene::Scene(qreal x, qreal y, qreal width, qreal height, QObject *parent) - : QGraphicsScene(x, y, width, height, parent) -{ -} - -Scene::Scene(const QRectF &sceneRect, QObject *parent) - : QGraphicsScene(sceneRect, parent) -{ -} - -Scene::Scene(QObject *parent) - : QGraphicsScene(parent) -{ -} - -Scene::~Scene() -{ -} - -void Scene::mousePressEvent(QGraphicsSceneMouseEvent *event) -{ - QGraphicsPieMenu *menu = new QGraphicsPieMenu; - for (int i = 0; i < 5; ++i) - menu->addAction(new QAction(QString("Item %1").arg(i), menu)); - menu->popup(event->scenePos()); -} diff --git a/examples/animation/research/piemenu/scene.h b/examples/animation/research/piemenu/scene.h deleted file mode 100644 index bbfe6d3..0000000 --- a/examples/animation/research/piemenu/scene.h +++ /dev/null @@ -1,60 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SCENE_H -#define SCENE_H - -#include - -class Scene : public QGraphicsScene -{ - Q_OBJECT -public: - Scene(qreal x, qreal y, qreal width, qreal height, QObject *parent = 0); - Scene(const QRectF &sceneRect, QObject *parent = 0); - Scene(QObject *parent = 0); - ~Scene(); - -protected: - void mousePressEvent(QGraphicsSceneMouseEvent *event); -}; - -#endif diff --git a/examples/animation/research/propertytransform/main.cpp b/examples/animation/research/propertytransform/main.cpp deleted file mode 100644 index 99cd769..0000000 --- a/examples/animation/research/propertytransform/main.cpp +++ /dev/null @@ -1,88 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include "qpropertytransform.h" - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - QGraphicsScene scene; - QGraphicsView view(&scene); - - QGraphicsItem *item = new QGraphicsRectItem(QRectF(0,0, 200, 100)); - scene.addItem(item); - QPropertyTransform transform; - transform.setTargetItem(item); - - QAnimationGroup *group = new QAnimationGroup(QAnimationGroup::Parallel, &scene); - QPropertyAnimation *scaleAnim = new QPropertyAnimation(&transform, "scaleX"); - scaleAnim->setStartValue(1.0); - scaleAnim->setTargetValue(2.0); - scaleAnim->setDuration(10000); - group->add(scaleAnim); - - QPropertyAnimation *scaleAnim2 = new QPropertyAnimation(&transform, "scaleY"); - scaleAnim2->setStartValue(.0); - scaleAnim2->setTargetValue(2.0); - scaleAnim2->setDuration(10000); - QEasingCurve curve(QEasingCurve::InElastic); - curve.setPeriod(2); - curve.setAmplitude(2); - - //scaleAnim2->setEasingCurve(curve); - //scaleAnim2->setEasingCurve(QEasingCurve(QEasingCurve::OutElastic , 2, 2 )); - group->add(scaleAnim2); - - QPropertyAnimation *rotAnim = new QPropertyAnimation(&transform, "rotation"); - rotAnim->setStartValue(0); - rotAnim->setTargetValue(90); - rotAnim->setDuration(10000); - group->add(rotAnim); - - group->start(); - - view.resize(800,600); - view.show(); - return app.exec(); -} diff --git a/examples/animation/research/propertytransform/propertytransform.pro b/examples/animation/research/propertytransform/propertytransform.pro deleted file mode 100644 index 94c36b8..0000000 --- a/examples/animation/research/propertytransform/propertytransform.pro +++ /dev/null @@ -1,14 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) fr 26. sep 13:21:57 2008 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -# Input -SOURCES += main.cpp -HEADERS += qpropertytransform.h -CONFIG += console - diff --git a/examples/animation/research/propertytransform/qpropertytransform.h b/examples/animation/research/propertytransform/qpropertytransform.h deleted file mode 100644 index e27987f..0000000 --- a/examples/animation/research/propertytransform/qpropertytransform.h +++ /dev/null @@ -1,119 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include - -/** - * Experimental. - * Pros: - * 1. Does not add ugly/confusing API to QGraphicsItem. - * - * Cons: - * 1. apply() /m_item->setTransform() is called too many times. (FIXED NOW?) - * - * - */ -class QPropertyTransform : public QObject { - Q_OBJECT -public: - Q_PROPERTY(QPointF center READ center WRITE setCenter); - Q_PROPERTY(qreal rotation READ rotation WRITE setRotation); - Q_PROPERTY(qreal scaleX READ scaleX WRITE setScaleX); - Q_PROPERTY(qreal scaleY READ scaleY WRITE setScaleY); -public: - QPropertyTransform() : m_item(0), m_rotationZ(0), m_scaleX(1.), m_scaleY(1.) {} - - void setTargetItem(QGraphicsItem *item) { - m_item = item; - } - - void setCenter(const QPointF ¢er) { - m_center = center; - apply(); - } - - QPointF center() const { return m_center; } - - void setRotation(qreal rotation) { - m_rotationZ = rotation; - apply(); - } - - qreal rotation() const { return m_rotationZ; } - - void setScaleX(qreal scale) { - m_scaleX = scale; - apply(); - } - - qreal scaleX() const { return m_scaleX; } - - void setScaleY(qreal scale) { - m_scaleY = scale; - apply(); - } - - qreal scaleY() const { return m_scaleY; } - -private: - QTransform transform() const { - return QTransform().translate(m_center.x(), m_center.y()) - .rotate(m_rotationZ) - .scale(m_scaleX, m_scaleY) - .translate(-m_center.x(), -m_center.y()); - } - - void apply() { - if (m_item) - m_item->setTransform(transform()); - } - - QGraphicsItem *m_item; - QPointF m_center; - qreal m_rotationZ; - qreal m_scaleX; - qreal m_scaleY; -}; - diff --git a/examples/animation/research/sound/main.cpp b/examples/animation/research/sound/main.cpp deleted file mode 100644 index ffbc44c..0000000 --- a/examples/animation/research/sound/main.cpp +++ /dev/null @@ -1,104 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//The purpose of this example is to show that it is possible to have your own -// animation with undefined duration - -#include -#include - -class SoundAnimation : public QAbstractAnimation -{ -public: - SoundAnimation(const QString &file) - { - //in an idea case we should also control the errors - Phonon::createPath(&m_media, &m_audio); - m_media.setCurrentSource(file); - connect(&m_media, SIGNAL(finished()), SLOT(stop())); - } - - int duration() const - { - return -1; - } - - void updateCurrentTime(int msecs) - { - //nothing to do here... - qDebug() << "updateCurrentTime" << msecs; - } - - void updateState(State state) - { - switch(state) - { - case Running: - m_media.play(); - break; - case Stopped: - m_media.stop(); - break; - case Paused: - m_media.pause(); - break; - } - } - - -private: - Phonon::MediaObject m_media; - Phonon::AudioOutput m_audio; - -}; - - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - Q_INIT_RESOURCE(sound); - - SoundAnimation anim(QLatin1String(":/media/sax.mp3")); - app.connect(&anim, SIGNAL(finished()), SLOT(quit())); - anim.start(); - - return app.exec(); -} diff --git a/examples/animation/research/sound/media/sax.mp3 b/examples/animation/research/sound/media/sax.mp3 deleted file mode 100644 index 0a078b1..0000000 Binary files a/examples/animation/research/sound/media/sax.mp3 and /dev/null differ diff --git a/examples/animation/research/sound/sound.pro b/examples/animation/research/sound/sound.pro deleted file mode 100644 index 0ad3050..0000000 --- a/examples/animation/research/sound/sound.pro +++ /dev/null @@ -1,14 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) mer. 21. janv. 13:53:26 2009 -###################################################################### - -TEMPLATE = app -QT += phonon -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -RESOURCES = sound.qrc - -# Input -SOURCES += main.cpp diff --git a/examples/animation/research/sound/sound.qrc b/examples/animation/research/sound/sound.qrc deleted file mode 100644 index 8919142..0000000 --- a/examples/animation/research/sound/sound.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - -media/sax.mp3 - - -- cgit v0.12 From 2f4f470faa12125d1bc8a0b1b353637c5749cce5 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 11:50:33 +0200 Subject: remove the citizenquartz example It's not done yet, so let's re-add it when it is. --- .../statemachine/citizenquartz/citizenquartz.pro | 20 -- .../statemachine/citizenquartz/citizenquartz.qrc | 6 - examples/statemachine/citizenquartz/clock.cpp | 390 --------------------- examples/statemachine/citizenquartz/clock.h | 62 ---- .../statemachine/citizenquartz/clockbutton.cpp | 39 --- examples/statemachine/citizenquartz/clockbutton.h | 25 -- .../statemachine/citizenquartz/clockdisplay.cpp | 139 -------- examples/statemachine/citizenquartz/clockdisplay.h | 89 ----- .../statemachine/citizenquartz/images/alarm.png | Bin 434 -> 0 bytes examples/statemachine/citizenquartz/main.cpp | 23 -- .../citizenquartz/propertyaddstate.cpp | 46 --- .../statemachine/citizenquartz/propertyaddstate.h | 33 -- .../statemachine/citizenquartz/sound/alarm.wav | Bin 3238264 -> 0 bytes examples/statemachine/citizenquartz/timeperiod.h | 84 ----- 14 files changed, 956 deletions(-) delete mode 100644 examples/statemachine/citizenquartz/citizenquartz.pro delete mode 100644 examples/statemachine/citizenquartz/citizenquartz.qrc delete mode 100644 examples/statemachine/citizenquartz/clock.cpp delete mode 100644 examples/statemachine/citizenquartz/clock.h delete mode 100644 examples/statemachine/citizenquartz/clockbutton.cpp delete mode 100644 examples/statemachine/citizenquartz/clockbutton.h delete mode 100644 examples/statemachine/citizenquartz/clockdisplay.cpp delete mode 100644 examples/statemachine/citizenquartz/clockdisplay.h delete mode 100644 examples/statemachine/citizenquartz/images/alarm.png delete mode 100644 examples/statemachine/citizenquartz/main.cpp delete mode 100644 examples/statemachine/citizenquartz/propertyaddstate.cpp delete mode 100644 examples/statemachine/citizenquartz/propertyaddstate.h delete mode 100644 examples/statemachine/citizenquartz/sound/alarm.wav delete mode 100644 examples/statemachine/citizenquartz/timeperiod.h diff --git a/examples/statemachine/citizenquartz/citizenquartz.pro b/examples/statemachine/citizenquartz/citizenquartz.pro deleted file mode 100644 index 58039a0..0000000 --- a/examples/statemachine/citizenquartz/citizenquartz.pro +++ /dev/null @@ -1,20 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -# Input -SOURCES += main.cpp \ - clock.cpp \ - clockbutton.cpp \ - clockdisplay.cpp \ - propertyaddstate.cpp \ - -HEADERS += clock.h \ - clockbutton.h \ - clockdisplay.h \ - propertyaddstate.h \ - timeperiod.h \ - -RESOURCES += citizenquartz.qrc -CONFIG += console diff --git a/examples/statemachine/citizenquartz/citizenquartz.qrc b/examples/statemachine/citizenquartz/citizenquartz.qrc deleted file mode 100644 index fc09ef9..0000000 --- a/examples/statemachine/citizenquartz/citizenquartz.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - sound/alarm.wav - images/alarm.png - - \ No newline at end of file diff --git a/examples/statemachine/citizenquartz/clock.cpp b/examples/statemachine/citizenquartz/clock.cpp deleted file mode 100644 index 1b2b21e..0000000 --- a/examples/statemachine/citizenquartz/clock.cpp +++ /dev/null @@ -1,390 +0,0 @@ -#include "clock.h" -#include "clockbutton.h" -#include "clockdisplay.h" -#include "propertyaddstate.h" -#include "timeperiod.h" - -#include -#include -#include - -#include -#include -#include - -Clock::Clock(QGraphicsItem *parent) - : QGraphicsItem(parent), - m_stateMachine(0), - m_clockDisplay(0), - m_buttonA(0), - m_buttonB(0), - m_buttonC(0), - m_buttonD(0), - m_alarmState(0), - m_timeState(0), - m_updateState(0), - m_regularState(0), - m_displaysHistoryState(0), - m_alarmSound(new QSound(":/sound/alarm.wav", this)) -{ -} - -void Clock::initializeUi() -{ - QPainterPath path = shape(); - QPointF pap; - qreal aap; - - m_buttonA = new ClockButton("Button A", this); - pap = path.pointAtPercent(0.05); - aap = path.angleAtPercent(0.05); - m_buttonA->translate(pap.x(), pap.y()); - m_buttonA->rotate(-aap); - connect(m_buttonA, SIGNAL(pressed()), this, SIGNAL(anyButtonPressed())); - - m_buttonB = new ClockButton("Button B", this); - pap = path.pointAtPercent(0.77); - aap = path.angleAtPercent(0.77); - m_buttonB->translate(pap.x(), pap.y()); - m_buttonB->rotate(-aap); - connect(m_buttonB, SIGNAL(pressed()), this, SIGNAL(anyButtonPressed())); - - m_buttonC = new ClockButton("Button C", this); - pap = path.pointAtPercent(0.67); - aap = path.angleAtPercent(0.67); - m_buttonC->translate(pap.x(), pap.y()); - m_buttonC->rotate(-aap); - connect(m_buttonC, SIGNAL(pressed()), this, SIGNAL(anyButtonPressed())); - - m_buttonD = new ClockButton("Button D", this); - pap = path.pointAtPercent(0.57); - aap = path.angleAtPercent(0.57); - m_buttonD->translate(pap.x(), pap.y()); - m_buttonD->rotate(-aap); - connect(m_buttonD, SIGNAL(pressed()), this, SIGNAL(anyButtonPressed())); - - QGraphicsSimpleTextItem *label = new QGraphicsSimpleTextItem(this); - label->setText("CITIZEN"); - label->setPos(0.0 - label->boundingRect().width() / 2.0, -100.0); - - m_clockDisplay = new ClockDisplay(this); - m_clockDisplay->setCurrentTime(QDateTime::currentDateTime()); - - QTimer *timer = new QTimer(this); - connect(timer, SIGNAL(timeout()), this, SLOT(updateTime())); - timer->setInterval(1); - timer->start(); - m_time.start(); -} - -void Clock::initializeStateMachine() -{ - m_stateMachine = new QStateMachine; - - QState *displays = new QState(m_stateMachine->rootState()); - displays->setObjectName("displays"); - initializeDisplaysState(displays); - - QState *alarmsBeepState = new QState(m_stateMachine->rootState()); - alarmsBeepState->setObjectName("alarmsBeep"); - alarmsBeepState->invokeMethodOnEntry(this, "playSound"); - alarmsBeepState->invokeMethodOnExit(this, "stopSound"); - - QTimer *alarmTimeOut = new QTimer(alarmsBeepState); - alarmTimeOut->setInterval(30000); - alarmsBeepState->invokeMethodOnEntry(alarmTimeOut, "start"); - alarmsBeepState->invokeMethodOnExit(alarmTimeOut, "stop"); - - displays->addTransition(m_clockDisplay, SIGNAL(alarmTriggered()), alarmsBeepState); - alarmsBeepState->addTransition(this, SIGNAL(anyButtonPressed()), m_displaysHistoryState); - alarmsBeepState->addTransition(alarmTimeOut, SIGNAL(timeout()), m_displaysHistoryState); - - m_stateMachine->setInitialState(displays); - m_stateMachine->start(); -} - -void Clock::initializeUpdateState(QState *updateState) -{ - QState *sec = new QState(updateState); - sec->setObjectName("sec"); - sec->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditSecondMode); - updateState->setInitialState(sec); - - PropertyAddState *secIncrease = new PropertyAddState(updateState); - secIncrease->setObjectName("sec ++"); - secIncrease->addToProperty(m_clockDisplay, "currentTime", TimePeriod().setSeconds(1)); - sec->addTransition(m_buttonD, SIGNAL(pressed()), secIncrease); - secIncrease->addTransition(sec); - - QState *oneMin = new QState(updateState); - oneMin->setObjectName("1 min"); - oneMin->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditMinuteMode); - sec->addTransition(m_buttonC, SIGNAL(pressed()), oneMin); - - PropertyAddState *oneMinIncrease = new PropertyAddState(updateState); - oneMinIncrease->setObjectName("1 min ++"); - oneMinIncrease->addToProperty(m_clockDisplay, "currentTime", TimePeriod().setMinutes(1)); - oneMin->addTransition(m_buttonD, SIGNAL(pressed()), oneMinIncrease); - oneMinIncrease->addTransition(oneMin); - - QState *tenMin = new QState(updateState); - tenMin->setObjectName("10 min"); - tenMin->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditMinuteMode); - oneMin->addTransition(m_buttonC, SIGNAL(pressed()), tenMin); - - PropertyAddState *tenMinIncrease = new PropertyAddState(updateState); - tenMinIncrease->setObjectName("10 min ++"); - tenMinIncrease->addToProperty(m_clockDisplay, "currentTime", TimePeriod().setMinutes(10)); - tenMin->addTransition(m_buttonD, SIGNAL(pressed()), tenMinIncrease); - tenMinIncrease->addTransition(tenMin); - - QState *hr = new QState(updateState); - hr->setObjectName("hr"); - hr->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditHourMode); - tenMin->addTransition(m_buttonC, SIGNAL(pressed()), hr); - - PropertyAddState *hrIncrease = new PropertyAddState(updateState); - hrIncrease->setObjectName("hr ++"); - hrIncrease->addToProperty(m_clockDisplay, "currentTime", TimePeriod().setHours(1)); - hr->addTransition(m_buttonD, SIGNAL(pressed()), hrIncrease); - hrIncrease->addTransition(hr); - - QState *mon = new QState(updateState); - mon->setObjectName("mon"); - mon->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditMonthMode); - hr->addTransition(m_buttonC, SIGNAL(pressed()), mon); - - PropertyAddState *monIncrease = new PropertyAddState(updateState); - monIncrease->setObjectName("mon ++"); - monIncrease->addToProperty(m_clockDisplay, "currentTime", TimePeriod().setMonths(1)); - mon->addTransition(m_buttonD, SIGNAL(pressed()), monIncrease); - monIncrease->addTransition(mon); - - QState *day = new QState(updateState); - day->setObjectName("day"); - day->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditDayMode); - mon->addTransition(m_buttonC, SIGNAL(pressed()), day); - - PropertyAddState *dayIncrease = new PropertyAddState(updateState); - dayIncrease->setObjectName("day ++"); - dayIncrease->addToProperty(m_clockDisplay, "currentTime", TimePeriod().setDays(1)); - day->addTransition(m_buttonD, SIGNAL(pressed()), dayIncrease); - dayIncrease->addTransition(day); - - QState *year = new QState(updateState); - year->setObjectName("year"); - year->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditYearMode); - day->addTransition(m_buttonC, SIGNAL(pressed()), year); - - PropertyAddState *yearIncrease = new PropertyAddState(updateState); - yearIncrease->setObjectName("year ++"); - yearIncrease->addToProperty(m_clockDisplay, "currentTime", TimePeriod().setYears(1)); - year->addTransition(m_buttonD, SIGNAL(pressed()), yearIncrease); - yearIncrease->addTransition(year); - year->addTransition(m_buttonC, SIGNAL(pressed()), m_timeState); -} - -void Clock::initializeRegularState(QState *regular) -{ - m_timeState = new QState(regular); - m_timeState->setObjectName("time"); - m_timeState->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::CurrentTimeMode); - - QState *date = new QState(regular); - date->setObjectName("date"); - date->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::CurrentDateMode); - - QState *dateTimerState = new QState(date); - dateTimerState->setObjectName("dateTimerState"); - - // Date state exits after 2 m - QTimer *dateTimer = new QTimer(dateTimerState); - dateTimer->setSingleShot(true); - dateTimer->setInterval(2*60000); - dateTimerState->invokeMethodOnEntry(dateTimer, "start"); - dateTimerState->invokeMethodOnExit(dateTimer, "stop"); - - date->setInitialState(dateTimerState); - - m_updateState = new QState(regular); - m_updateState->setObjectName("update"); - - // Update state exits after 2 m - QTimer *updateTimer = new QTimer(m_updateState); - updateTimer->setSingleShot(true); - updateTimer->setInterval(2 * 60000); - m_updateState->invokeMethodOnEntry(updateTimer, "start"); - m_updateState->invokeMethodOnExit(updateTimer, "stop"); - - initializeUpdateState(m_updateState); - - m_timeState->addTransition(m_buttonD, SIGNAL(pressed()), date); - date->addTransition(m_buttonD, SIGNAL(pressed()), m_timeState); - date->addTransition(dateTimer, SIGNAL(timeout()), m_timeState); - - m_updateState->addTransition(updateTimer, SIGNAL(timeout()), m_timeState); - m_updateState->addTransition(m_buttonB, SIGNAL(pressed()), m_timeState); - - regular->setInitialState(m_timeState); -} - -void Clock::initializeAlarmUpdateState(QState *update) -{ - QState *hr = new QState(update); - hr->setObjectName("hr"); - hr->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditAlarmHourMode); - - PropertyAddState *hrInc = new PropertyAddState(update); - hrInc->setObjectName("hr ++"); - hrInc->addToProperty(m_clockDisplay, "alarm", TimePeriod().setHours(1)); - hr->addTransition(m_buttonD, SIGNAL(pressed()), hrInc); - hrInc->addTransition(hr); - - QState *tenMin = new QState(update); - tenMin->setObjectName("10 min"); - tenMin->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditAlarmTenMinuteMode); - hr->addTransition(m_buttonC, SIGNAL(pressed()), tenMin); - - PropertyAddState *tenMinInc = new PropertyAddState(update); - tenMinInc->setObjectName("10 min ++"); - tenMinInc->addToProperty(m_clockDisplay, "alarm", TimePeriod().setMinutes(10)); - tenMin->addTransition(m_buttonD, SIGNAL(pressed()), tenMinInc); - tenMinInc->addTransition(tenMin); - - QState *oneMin = new QState(update); - oneMin->setObjectName("1 min"); - oneMin->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::EditAlarmMinuteMode); - tenMin->addTransition(m_buttonC, SIGNAL(pressed()), oneMin); - - PropertyAddState *oneMinInc = new PropertyAddState(update); - oneMinInc->setObjectName("1 min ++"); - oneMinInc->addToProperty(m_clockDisplay, "alarm", TimePeriod().setMinutes(1)); - oneMin->addTransition(m_buttonD, SIGNAL(pressed()), oneMinInc); - oneMinInc->addTransition(oneMin); - - oneMin->addTransition(m_buttonC, SIGNAL(pressed()), m_alarmState); - m_alarmState->addTransition(m_buttonC, SIGNAL(pressed()), hr); -} - -void Clock::initializeOutState(QState *out) -{ - m_alarmState = new QState(out); - m_alarmState->setObjectName("alarmState"); - m_alarmState->setPropertyOnEntry(m_clockDisplay, "displayMode", ClockDisplay::AlarmMode); - initializeAlarmState(m_alarmState); - out->setInitialState(m_alarmState); - - QState *alarmUpdate = new QState(out); - alarmUpdate->setObjectName("alarmUpdate"); - initializeAlarmUpdateState(alarmUpdate); - - alarmUpdate->addTransition(m_buttonB, SIGNAL(pressed()), m_alarmState); - m_alarmState->addTransition(m_buttonA, SIGNAL(pressed()), m_regularState); -} - -void Clock::initializeDisplaysState(QState *displays) -{ - m_regularState = new QState(displays); - m_regularState->setObjectName("regular"); - initializeRegularState(m_regularState); - displays->setInitialState(m_regularState); - - QState *out = new QState(displays); - out->setObjectName("out"); - - QTimer *outTimer = new QTimer(out); - outTimer->setSingleShot(true); - outTimer->setInterval(2 * 60000); - out->invokeMethodOnEntry(outTimer, "start"); - out->invokeMethodOnExit(outTimer, "stop"); - - initializeOutState(out); - - QState *wait = new QState(displays); - wait->setObjectName("wait"); - - QTimer *waitTimer = new QTimer(wait); - waitTimer->setSingleShot(true); - waitTimer->setInterval(2000); - wait->invokeMethodOnEntry(waitTimer, "start"); - wait->invokeMethodOnExit(waitTimer, "stop"); - - m_displaysHistoryState = displays->addHistoryState(QState::DeepHistory); - - m_timeState->addTransition(m_buttonC, SIGNAL(pressed()), wait); - wait->addTransition(waitTimer, SIGNAL(timeout()), m_updateState); - wait->addTransition(m_buttonC, SIGNAL(released()), m_timeState); - m_timeState->addTransition(m_buttonA, SIGNAL(pressed()), m_alarmState); - out->addTransition(outTimer, SIGNAL(timeout()), m_regularState); -} - -void Clock::initializeAlarmState(QState *alarmState) -{ - QState *offState = new QState(alarmState); - offState->setObjectName("alarmOff"); - offState->setPropertyOnEntry(m_clockDisplay, "alarmEnabled", false); - - QState *onState = new QState(alarmState); - onState->setObjectName("alarmOn"); - onState->setPropertyOnEntry(m_clockDisplay, "alarmEnabled", true); - - QHistoryState *history = alarmState->addHistoryState(); - history->setObjectName("alarmHistory"); - history->setDefaultState(offState); - - offState->addTransition(m_buttonD, SIGNAL(pressed()), onState); - onState->addTransition(m_buttonD, SIGNAL(pressed()), offState); - - QState *intermediate = new QState(alarmState); - intermediate->addTransition(history); - - alarmState->setInitialState(intermediate); -} - -QRectF Clock::boundingRect() const -{ - return shape().boundingRect(); -} - -QPainterPath Clock::shape() const -{ - QPainterPath path; - path.addRoundedRect(QRectF(-140.0, -100.0, 280.0, 200.0), 50.0, 50.0, Qt::RelativeSize); - - return path; -} - -void Clock::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - painter->setPen(Qt::black); - painter->setBrush(Qt::NoBrush); - - // Clock face - painter->drawPath(shape()); -} - -void Clock::updateTime() -{ - int elapsed = m_time.elapsed(); - if (elapsed > 0) { - m_time.restart(); - QDateTime currentTime = m_clockDisplay->currentTime(); - m_clockDisplay->setCurrentTime(currentTime.addMSecs(elapsed)); - - update(); - } -} - -void Clock::playSound() -{ - qDebug("playing sound"); - m_alarmSound->stop(); - m_alarmSound->play(); -} - -void Clock::stopSound() -{ - qDebug("stopping sound"); - m_alarmSound->stop(); -} - diff --git a/examples/statemachine/citizenquartz/clock.h b/examples/statemachine/citizenquartz/clock.h deleted file mode 100644 index afd6433..0000000 --- a/examples/statemachine/citizenquartz/clock.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef CLOCK_H -#define CLOCK_H - -#include -#include - -class ClockButton ; -class ClockDisplay ; -class QStateMachine ; -class QState ; -class QTimerState ; -class QSound ; -class QHistoryState ; - -class Clock: public QObject, public QGraphicsItem -{ - Q_OBJECT -public: - Clock(QGraphicsItem *parent = 0); - - void initializeUi(); - void initializeStateMachine(); - - virtual QRectF boundingRect() const; - virtual QPainterPath shape() const; - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0); - -signals: - void anyButtonPressed(); - -public slots: - void updateTime(); - void playSound(); - void stopSound(); - -private: - void initializeDisplaysState(QState *displays); - void initializeAlarmState(QState *alarmState); - void initializeRegularState(QState *regular); - void initializeUpdateState(QState *update); - void initializeOutState(QState *out); - void initializeAlarmUpdateState(QState *update); - - QStateMachine *m_stateMachine; - ClockDisplay *m_clockDisplay; - ClockButton *m_buttonA; - ClockButton *m_buttonB; - ClockButton *m_buttonC; - ClockButton *m_buttonD; - - QState *m_alarmState; - QState *m_timeState; - QState *m_updateState; - QState *m_regularState; - - QHistoryState *m_displaysHistoryState; - - QSound *m_alarmSound; - QTime m_time; -}; - -#endif // CLOCK_H diff --git a/examples/statemachine/citizenquartz/clockbutton.cpp b/examples/statemachine/citizenquartz/clockbutton.cpp deleted file mode 100644 index 7b86891..0000000 --- a/examples/statemachine/citizenquartz/clockbutton.cpp +++ /dev/null @@ -1,39 +0,0 @@ -#include "clockbutton.h" - -#include - -ClockButton::ClockButton(const QString &name, QGraphicsItem *parent) : QGraphicsItem(parent) -{ - setObjectName(name); - setToolTip(name); - setAcceptedMouseButtons(Qt::LeftButton); -} - -QRectF ClockButton::boundingRect() const -{ - return QRectF(-10.0, -10.0, 20.0, 20.0); -} - -QPainterPath ClockButton::shape() const -{ - QPainterPath path; - path.addRoundedRect(boundingRect(), 15.0, 15.0, Qt::RelativeSize); - - return path; -} - -void ClockButton::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - painter->setBrush(Qt::black); - painter->drawPath(shape()); -} - -void ClockButton::mousePressEvent(QGraphicsSceneMouseEvent *) -{ - emit pressed(); -} - -void ClockButton::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) -{ - emit released(); -} \ No newline at end of file diff --git a/examples/statemachine/citizenquartz/clockbutton.h b/examples/statemachine/citizenquartz/clockbutton.h deleted file mode 100644 index 02a7ccd..0000000 --- a/examples/statemachine/citizenquartz/clockbutton.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef CLOCKBUTTON_H -#define CLOCKBUTTON_H - -#include - -class ClockButton: public QObject, public QGraphicsItem -{ - Q_OBJECT -public: - ClockButton(const QString &name, QGraphicsItem *parent = 0); - - virtual QRectF boundingRect() const; - virtual QPainterPath shape() const; - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *); - -protected: - virtual void mousePressEvent(QGraphicsSceneMouseEvent *); - virtual void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); - -signals: - void pressed(); - void released(); -}; - -#endif //CLOCKBUTTON_H diff --git a/examples/statemachine/citizenquartz/clockdisplay.cpp b/examples/statemachine/citizenquartz/clockdisplay.cpp deleted file mode 100644 index db026f5..0000000 --- a/examples/statemachine/citizenquartz/clockdisplay.cpp +++ /dev/null @@ -1,139 +0,0 @@ -#include "clockdisplay.h" - -#include -#include - -ClockDisplay::ClockDisplay(QGraphicsItem *parent) - : QGraphicsItem(parent), - m_displayMode(CurrentTimeMode), - m_currentTime(QDate(1970, 1, 1), QTime(0, 0)), - m_alarm(0, 0), - m_alarmEnabled(false), - m_blink(false) - -{ - m_text = new QGraphicsTextItem(this); - - QTimer *timer = new QTimer(this); - connect(timer, SIGNAL(timeout()), this, SLOT(toggleBlinkFlag())); - timer->start(500); - - QFont font = m_text->font(); - font.setPointSizeF(20.0); - m_text->setFont(font); - - m_text->translate(-100.0, -20.0); - - QPixmap pm(":/images/alarm.png"); - m_alarmSymbol = new QGraphicsPixmapItem(pm, this); - m_alarmSymbol->translate(-100.0, -60.0); - m_alarmSymbol->setOffset(5.0, 5.0); - m_alarmSymbol->scale(0.5, 0.5); -} - -ClockDisplay::~ClockDisplay() -{ -} - -void ClockDisplay::toggleBlinkFlag() -{ - m_blink = !m_blink; - update(); -} - -void ClockDisplay::updateText() -{ - switch (m_displayMode) { - case EditSecondMode: - if (m_blink) { - m_text->setHtml(m_currentTime.toString("hh:mm:''ss''")); - break; - } - // fall throoough - case EditMinuteMode: - if (m_blink) { - m_text->setHtml(m_currentTime.toString("hh:''mm'':ss")); - break; - } - - // fall throoough - case EditHourMode: - if (m_blink) { - m_text->setHtml(m_currentTime.toString("''hh'':mm:ss")); - break; - } - - // fall throoough - case CurrentTimeMode: - m_text->setHtml(m_currentTime.toString("hh:mm:ss")); - break; - - case EditMonthMode: - if (m_blink) { - m_text->setHtml(m_currentTime.toString("yyyy.''MM''.dd")); - break; - } - - // fall throoough - case EditDayMode: - if (m_blink) { - m_text->setHtml(m_currentTime.toString("yyyy.MM.''dd''")); - break; - } - - // fall throoough - case EditYearMode: - if (m_blink) { - m_text->setHtml(m_currentTime.toString("''yyyy''.MM.dd")); - break; - } - - // fall throoough - case CurrentDateMode: - m_text->setHtml(m_currentTime.toString("yyyy.MM.dd")); - break; - - case EditAlarmHourMode: - if (m_blink) { - m_text->setHtml(m_alarm.toString("''hh'':mm")); - break; - } - - // fall throooough - case EditAlarmTenMinuteMode: - case EditAlarmMinuteMode: - if (m_blink) { - m_text->setHtml(m_alarm.toString("hh:''mm''")); - break; - } - - // fall throoough - case AlarmMode: - m_text->setHtml(m_alarm.toString("hh:mm")); - break; - - default: - m_text->setHtml("Not implemented"); - }; -} - -QRectF ClockDisplay::boundingRect() const -{ - return QRectF(-100.0, -60.0, 200.0, 120.0); -} - -void ClockDisplay::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - m_alarmSymbol->setVisible(m_alarmEnabled); - - updateText(); - - // Screen - painter->drawRoundedRect(boundingRect(), 15.0, 15.0, Qt::RelativeSize); - - // Button grid - painter->drawLine(QPointF(-100.0, -20.0), QPointF(100.0, -20.0)); - painter->drawLine(QPointF(-50.0, -60.0), QPointF(-50.0, -20.0)); - painter->drawLine(QPointF(0.0, -60.0), QPointF(0.0, -20.0)); - painter->drawLine(QPointF(50.0, -60.0), QPointF(50.0, -20.0)); -} diff --git a/examples/statemachine/citizenquartz/clockdisplay.h b/examples/statemachine/citizenquartz/clockdisplay.h deleted file mode 100644 index ec86509..0000000 --- a/examples/statemachine/citizenquartz/clockdisplay.h +++ /dev/null @@ -1,89 +0,0 @@ -#ifndef CLOCKDISPLAY_H -#define CLOCKDISPLAY_H - -#include -#include -#include - -class ClockDisplay: public QObject, public QGraphicsItem -{ - Q_OBJECT - Q_ENUMS(DisplayMode) - Q_PROPERTY(DisplayMode displayMode READ displayMode WRITE setDisplayMode) - Q_PROPERTY(QDateTime currentTime READ currentTime WRITE setCurrentTime) - Q_PROPERTY(QTime alarm READ alarm WRITE setAlarm) - Q_PROPERTY(bool alarmEnabled READ alarmEnabled WRITE setAlarmEnabled) -public: - enum DisplayMode { - CurrentTimeMode, - EditSecondMode, - EditMinuteMode, - EditHourMode, - - CurrentDateMode, - EditMonthMode, - EditDayMode, - EditYearMode, - - AlarmMode, - EditAlarmHourMode, - EditAlarmTenMinuteMode, - EditAlarmMinuteMode, - - ChimeMode, - StopWatchMode, - ModeCount - }; - - ClockDisplay(QGraphicsItem *parent = 0); - virtual ~ClockDisplay(); - - void setDisplayMode(DisplayMode displayMode) { m_displayMode = displayMode; update(); } - DisplayMode displayMode() const { return m_displayMode; } - - QDateTime currentTime() const { return m_currentTime; } - void setCurrentTime(const QDateTime &time) - { - if (m_alarmEnabled && !alarmMatches(m_currentTime) && alarmMatches(time)) - emit alarmTriggered(); - m_currentTime = time; - update(); - } - - QTime alarm() const { return m_alarm; } - void setAlarm(const QTime &time) { m_alarm = time; update(); } - - bool alarmEnabled() const { return m_alarmEnabled; } - void setAlarmEnabled(bool enabled) { m_alarmEnabled = enabled; update(); } - - virtual QRectF boundingRect() const; - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *); - -signals: - void alarmTriggered(); - -private slots: - void toggleBlinkFlag(); - -private: - void updateText(); - - bool alarmMatches(const QDateTime &dt) - { - return (dt.time().hour() == m_alarm.hour() && dt.time().minute() == m_alarm.minute()); - } - - DisplayMode m_displayMode; - - QDateTime m_currentTime; - QTime m_alarm; - - QGraphicsTextItem *m_text; - QGraphicsPixmapItem *m_alarmSymbol; - - uint m_alarmEnabled : 1; - uint m_blink : 1; - uint m_reserved : 30; -}; - -#endif diff --git a/examples/statemachine/citizenquartz/images/alarm.png b/examples/statemachine/citizenquartz/images/alarm.png deleted file mode 100644 index a19778d..0000000 Binary files a/examples/statemachine/citizenquartz/images/alarm.png and /dev/null differ diff --git a/examples/statemachine/citizenquartz/main.cpp b/examples/statemachine/citizenquartz/main.cpp deleted file mode 100644 index 2c6b14c..0000000 --- a/examples/statemachine/citizenquartz/main.cpp +++ /dev/null @@ -1,23 +0,0 @@ -#include -#include -#include - -#include "clock.h" - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - QGraphicsScene scene; - - Clock *clock = new Clock; - clock->initializeUi(); - clock->initializeStateMachine(); - scene.addItem(clock); - - QGraphicsView view(&scene); - view.setRenderHint(QPainter::Antialiasing); - view.show(); - - return app.exec(); -} diff --git a/examples/statemachine/citizenquartz/propertyaddstate.cpp b/examples/statemachine/citizenquartz/propertyaddstate.cpp deleted file mode 100644 index dd23948..0000000 --- a/examples/statemachine/citizenquartz/propertyaddstate.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "PropertyAddState.h" -#include "timeperiod.h" - -#include -#include - -PropertyAddState::PropertyAddState(QState *parent) - : QState(parent) -{ -} - -void PropertyAddState::addToProperty(QObject *object, const char *propertyName, - const QVariant &valueToAdd) -{ - m_propertyAdditions.append(PropertyAdder(object, propertyName, valueToAdd)); -} - -QVariant PropertyAddState::addProperties(const QVariant ¤t, const QVariant &toAdd) const -{ - QVariant result; - switch (current.type()) { - case QVariant::DateTime: - result = current.toDateTime() + qvariant_cast(toAdd); - break; - case QVariant::Time: - result = current.toTime() + qvariant_cast(toAdd); - break; - default: - qWarning("PropertyAddState::addProperties: QVariant type '%s' not supported", - current.typeName()); - }; - - return result; -} - -void PropertyAddState::onEntry() -{ - foreach (PropertyAdder propertyAdder, m_propertyAdditions) { - QObject *object = propertyAdder.object; - QByteArray propertyName = propertyAdder.propertyName; - QVariant toAdd = propertyAdder.valueToAdd; - QVariant current = object->property(propertyName); - - object->setProperty(propertyName, addProperties(current, toAdd)); - } -} diff --git a/examples/statemachine/citizenquartz/propertyaddstate.h b/examples/statemachine/citizenquartz/propertyaddstate.h deleted file mode 100644 index 4d28055..0000000 --- a/examples/statemachine/citizenquartz/propertyaddstate.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef PropertyAddState_H -#define PropertyAddState_H - -#include - -#include -#include - -class PropertyAddState: public QState -{ -public: - PropertyAddState(QState *parent = 0); - - void addToProperty(QObject *object, const char *propertyName, const QVariant &valueToAdd); - virtual void onEntry(); - -private: - QVariant addProperties(const QVariant ¤t, const QVariant &toAdd) const; - - struct PropertyAdder { - PropertyAdder(QObject *_object, const char *_propertyName, const QVariant &_valueToAdd) - : object(_object), propertyName(_propertyName), valueToAdd(_valueToAdd) - { - } - - QObject *object; - QByteArray propertyName; - QVariant valueToAdd; - }; - QList m_propertyAdditions; -}; - -#endif // PropertyAddState_H diff --git a/examples/statemachine/citizenquartz/sound/alarm.wav b/examples/statemachine/citizenquartz/sound/alarm.wav deleted file mode 100644 index 1d9486f..0000000 Binary files a/examples/statemachine/citizenquartz/sound/alarm.wav and /dev/null differ diff --git a/examples/statemachine/citizenquartz/timeperiod.h b/examples/statemachine/citizenquartz/timeperiod.h deleted file mode 100644 index c5a3a16..0000000 --- a/examples/statemachine/citizenquartz/timeperiod.h +++ /dev/null @@ -1,84 +0,0 @@ -#ifndef TIMEPERIOD_H -#define TIMEPERIOD_H - -#include -#include -#include - -class TimePeriod -{ -public: - TimePeriod() : m_seconds(0), m_minutes(0), m_hours(0), m_days(0), m_months(0), m_years(0) - { - } - - TimePeriod &setSeconds(int seconds) { m_seconds = seconds; return *this; } - int seconds() const { return m_seconds; } - - TimePeriod &setMinutes(int minutes) { m_minutes = minutes; return *this; } - int minutes() const { return m_minutes; } - - TimePeriod &setHours(int hours) { m_hours = hours; return *this; } - int hours() const { return m_hours; } - - TimePeriod &setDays(int days) { m_days = days; return *this; } - int days() const { return m_days; } - - TimePeriod &setMonths(int months) { m_months = months; return *this; } - int months() const { return m_months; } - - TimePeriod &setYears(int years) { m_years = years; return *this; } - int years() const { return m_years; } - - operator QVariant() const - { - QVariant v; - qVariantSetValue(v, *this); - return v; - } - -private: - int m_seconds; - int m_minutes; - int m_hours; - int m_days; - int m_months; - int m_years; -}; - -inline void operator+=(QDateTime &dateTime, const TimePeriod &timePeriod) -{ - dateTime = dateTime.addSecs(timePeriod.seconds()); - dateTime = dateTime.addSecs(timePeriod.minutes() * 60); - dateTime = dateTime.addSecs(timePeriod.hours() * 3600); - dateTime = dateTime.addDays(timePeriod.days()); - dateTime = dateTime.addMonths(timePeriod.months()); - dateTime = dateTime.addYears(timePeriod.years()); -} - -inline QDateTime operator+(const QDateTime &dateTime, const TimePeriod &timePeriod) -{ - QDateTime result(dateTime); - result += timePeriod; - - return result; -} - -inline void operator+=(QTime &time, const TimePeriod &timePeriod) -{ - time = time.addSecs(timePeriod.seconds()); - time = time.addSecs(timePeriod.minutes() * 60); - time = time.addSecs(timePeriod.hours() * 3600); -} - -inline QTime operator+(const QTime &time, const TimePeriod &timePeriod) -{ - QTime result(time); - result += timePeriod; - - return result; -} - -Q_DECLARE_METATYPE(TimePeriod) - -#endif \\ TIMEPERIOD_H -- cgit v0.12 From 74ca1734cd6c69e7827a7a66b0c0db5face7752f Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 12:53:59 +0200 Subject: kill experimental QtAnimation module stuff, the module doesn't exist anymore --- bin/syncqt | 2 -- mkspecs/features/qt.prf | 3 +-- 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/bin/syncqt b/bin/syncqt index 5ac8933..7a9f1d3 100755 --- a/bin/syncqt +++ b/bin/syncqt @@ -23,7 +23,6 @@ my $basedir = $ENV{"QTDIR"}; $basedir =~ s=\\=/=g; my %modules = ( # path to module name map "QtGui" => "$basedir/src/gui", - "QtAnimation" => "$basedir/src/animation", "QtOpenGL" => "$basedir/src/opengl", "QtCore" => "$basedir/src/corelib", "QtXml" => "$basedir/src/xml", @@ -681,7 +680,6 @@ foreach (@modules_to_sync) { foreach(split(/ /, "$1")) { $master_contents .= "#include \n" if("$_" eq "core"); $master_contents .= "#include \n" if("$_" eq "gui"); - $master_contents .= "#include \n" if("$_" eq "experimental-animation"); $master_contents .= "#include \n" if("$_" eq "network"); $master_contents .= "#include \n" if("$_" eq "svg"); $master_contents .= "#include \n" if("$_" eq "script"); diff --git a/mkspecs/features/qt.prf b/mkspecs/features/qt.prf index 3ef864e..0c6e09a 100644 --- a/mkspecs/features/qt.prf +++ b/mkspecs/features/qt.prf @@ -36,7 +36,7 @@ INCLUDEPATH = $$QMAKE_INCDIR_QT $$INCLUDEPATH #prepending prevents us from picki win32:INCLUDEPATH += $$QMAKE_INCDIR_QT/ActiveQt # As order does matter for static libs, we reorder the QT variable here -TMPLIBS = webkit phonon dbus testlib script scripttools svg qt3support sql xmlpatterns xml opengl experimental-animation gui network core +TMPLIBS = webkit phonon dbus testlib script scripttools svg qt3support sql xmlpatterns xml opengl gui network core for(QTLIB, $$list($$TMPLIBS)) { contains(QT, $$QTLIB): QT_ORDERED += $$QTLIB } @@ -147,7 +147,6 @@ for(QTLIB, $$list($$lower($$unique(QT)))) { else:isEqual(QTLIB, svg):qlib = QtSvg else:isEqual(QTLIB, script):qlib = QtScript else:isEqual(QTLIB, scripttools):qlib = QtScriptTools - else:isEqual(QTLIB, experimental-animation):qlib = QtAnimation else:isEqual(QTLIB, testlib):qlib = QtTest else:isEqual(QTLIB, dbus):qlib = QtDBus else:isEqual(QTLIB, phonon):qlib = phonon -- cgit v0.12 From 87f51bd2526130f1b3c79d59aec89fe078094d68 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 12:58:57 +0200 Subject: update the qdoc tags (\since 4.6, remove \preliminary) --- src/corelib/animation/qabstractanimation.cpp | 3 +-- src/corelib/animation/qanimationgroup.cpp | 3 +-- src/corelib/animation/qparallelanimationgroup.cpp | 3 +-- src/corelib/animation/qpauseanimation.cpp | 3 +-- src/corelib/animation/qpropertyanimation.cpp | 2 +- src/corelib/animation/qsequentialanimationgroup.cpp | 3 +-- src/corelib/animation/qvariantanimation.cpp | 3 +-- src/corelib/tools/qeasingcurve.cpp | 1 + 8 files changed, 8 insertions(+), 13 deletions(-) diff --git a/src/corelib/animation/qabstractanimation.cpp b/src/corelib/animation/qabstractanimation.cpp index 759cf18..94a94d1 100644 --- a/src/corelib/animation/qabstractanimation.cpp +++ b/src/corelib/animation/qabstractanimation.cpp @@ -43,8 +43,7 @@ \class QAbstractAnimation \ingroup animation \brief The QAbstractAnimation class is the base of all animations. - \since 4.5 - \preliminary + \since 4.6 The class defines the functions for the functionality shared by all animations. By inheriting this class, you can create custom diff --git a/src/corelib/animation/qanimationgroup.cpp b/src/corelib/animation/qanimationgroup.cpp index e78ce9a..ed06eff 100644 --- a/src/corelib/animation/qanimationgroup.cpp +++ b/src/corelib/animation/qanimationgroup.cpp @@ -42,9 +42,8 @@ /*! \class QAnimationGroup \brief The QAnimationGroup class is an abstract base class for groups of animations. - \since 4.5 + \since 4.6 \ingroup animation - \preliminary An animation group is a container for animations (subclasses of QAbstractAnimation). A group is usually responsible for managing diff --git a/src/corelib/animation/qparallelanimationgroup.cpp b/src/corelib/animation/qparallelanimationgroup.cpp index 48c8b3e..13f6073 100644 --- a/src/corelib/animation/qparallelanimationgroup.cpp +++ b/src/corelib/animation/qparallelanimationgroup.cpp @@ -42,9 +42,8 @@ /*! \class QParallelAnimationGroup \brief The QParallelAnimationGroup class provides a parallel group of animations. - \since 4.5 + \since 4.6 \ingroup animation - \preliminary QParallelAnimationGroup--a \l{QAnimationGroup}{container for animations}--starts all its animations when it is diff --git a/src/corelib/animation/qpauseanimation.cpp b/src/corelib/animation/qpauseanimation.cpp index c853745..b175f0c 100644 --- a/src/corelib/animation/qpauseanimation.cpp +++ b/src/corelib/animation/qpauseanimation.cpp @@ -42,9 +42,8 @@ /*! \class QPauseAnimation \brief The QPauseAnimation class provides a pause for QSequentialAnimationGroup. - \since 4.5 + \since 4.6 \ingroup animation - \preliminary If you wish to introduce a delay between animations in a QSequentialAnimationGroup, you can insert a QPauseAnimation. This diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp index 10fe8a2..9a17049 100644 --- a/src/corelib/animation/qpropertyanimation.cpp +++ b/src/corelib/animation/qpropertyanimation.cpp @@ -42,8 +42,8 @@ /*! \class QPropertyAnimation \brief The QPropertyAnimation class animates Qt properties + \since 4.6 \ingroup animation - \preliminary QPropertyAnimation interpolates over \l{Qt's Property System}{Qt properties}. As property values are stored in \l{QVariant}s, the diff --git a/src/corelib/animation/qsequentialanimationgroup.cpp b/src/corelib/animation/qsequentialanimationgroup.cpp index 38f4818..14814a7 100644 --- a/src/corelib/animation/qsequentialanimationgroup.cpp +++ b/src/corelib/animation/qsequentialanimationgroup.cpp @@ -42,9 +42,8 @@ /*! \class QSequentialAnimationGroup \brief The QSequentialAnimationGroup class provides a sequential group of animations. - \since 4.5 + \since 4.6 \ingroup animation - \preliminary QSequentialAnimationGroup is a QAnimationGroup that runs its animations in sequence, i.e., it starts one animation after diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp index 864575a..a6834bb 100644 --- a/src/corelib/animation/qvariantanimation.cpp +++ b/src/corelib/animation/qvariantanimation.cpp @@ -56,8 +56,7 @@ QT_BEGIN_NAMESPACE \class QVariantAnimation \ingroup animation \brief The QVariantAnimation class provides an abstract base class for animations. - \since 4.5 - \preliminary + \since 4.6 This class is part of \l{The Animation Framework}. It serves as a base class for property and item animations, with functions for diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp index 23eb2a6..34765c8 100644 --- a/src/corelib/tools/qeasingcurve.cpp +++ b/src/corelib/tools/qeasingcurve.cpp @@ -53,6 +53,7 @@ /*! \class QEasingCurve + \since 4.6 \ingroup animation \brief The QEasingCurve class provides easing curves for controlling animation. -- cgit v0.12 From dfdb8555afc5a7e69c25c5a0c8b98167f15f51e5 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 13:18:35 +0200 Subject: remove QT_EXPERIMENTAL stuff --- src/corelib/global/qglobal.h | 16 ---------------- src/corelib/tools/qtimeline.h | 2 -- src/gui/graphicsview/qgraphicswidget.h | 1 - src/gui/statemachine/qbasickeyeventtransition.cpp | 8 +------- src/gui/statemachine/qbasickeyeventtransition_p.h | 7 +------ src/gui/statemachine/qbasicmouseeventtransition.cpp | 7 +------ src/gui/statemachine/qbasicmouseeventtransition_p.h | 7 +------ src/gui/statemachine/qkeyeventtransition.cpp | 7 +------ src/gui/statemachine/qkeyeventtransition.h | 7 ++----- src/gui/statemachine/qmouseeventtransition.cpp | 7 +------ src/gui/statemachine/qmouseeventtransition.h | 8 ++------ 11 files changed, 10 insertions(+), 67 deletions(-) diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h index a0ea68c..36d87e2 100644 --- a/src/corelib/global/qglobal.h +++ b/src/corelib/global/qglobal.h @@ -128,22 +128,6 @@ namespace QT_NAMESPACE {} #endif /* __cplusplus */ -/** - * For animation framework to work seamlessly as a solution - */ -#if 0 -# define QT_EXPERIMENTAL_BEGIN_NAMESPACE namespace QtExperimental { -# define QT_EXPERIMENTAL_END_NAMESPACE } -# define QT_EXPERIMENTAL_USE_NAMESPACE using namespace QtExperimental; -# define QT_EXPERIMENTAL_PREPEND_NAMESPACE(name) QtExperimental::name -namespace QtExperimental {} -#else -# define QT_EXPERIMENTAL_BEGIN_NAMESPACE -# define QT_EXPERIMENTAL_END_NAMESPACE -# define QT_EXPERIMENTAL_USE_NAMESPACE -# define QT_EXPERIMENTAL_PREPEND_NAMESPACE(name) name -#endif - #if defined(Q_OS_MAC) && !defined(Q_CC_INTEL) #define QT_BEGIN_HEADER extern "C++" { #define QT_END_HEADER } diff --git a/src/corelib/tools/qtimeline.h b/src/corelib/tools/qtimeline.h index 314dd7c..48c9232 100644 --- a/src/corelib/tools/qtimeline.h +++ b/src/corelib/tools/qtimeline.h @@ -45,8 +45,6 @@ #include #include -QT_EXPERIMENTAL_USE_NAMESPACE - QT_BEGIN_HEADER QT_BEGIN_NAMESPACE diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h index 05195b6..65fd219 100644 --- a/src/gui/graphicsview/qgraphicswidget.h +++ b/src/gui/graphicsview/qgraphicswidget.h @@ -59,7 +59,6 @@ class QGraphicsLayout; class QGraphicsSceneMoveEvent; class QGraphicsWidgetPrivate; class QGraphicsSceneResizeEvent; -class QGraphicsWidgetAnimator; class QStyle; class QStyleOption; diff --git a/src/gui/statemachine/qbasickeyeventtransition.cpp b/src/gui/statemachine/qbasickeyeventtransition.cpp index 7f515cd..fe89f81 100644 --- a/src/gui/statemachine/qbasickeyeventtransition.cpp +++ b/src/gui/statemachine/qbasickeyeventtransition.cpp @@ -12,13 +12,7 @@ #include "qbasickeyeventtransition_p.h" #include #include - -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qabstracttransition_p.h" -#else -# include -#endif - +#include QT_BEGIN_NAMESPACE diff --git a/src/gui/statemachine/qbasickeyeventtransition_p.h b/src/gui/statemachine/qbasickeyeventtransition_p.h index 7506747..c4ff863 100644 --- a/src/gui/statemachine/qbasickeyeventtransition_p.h +++ b/src/gui/statemachine/qbasickeyeventtransition_p.h @@ -23,12 +23,7 @@ // We mean it. // -// Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qabstracttransition.h" -#else -# include -#endif +#include #include QT_BEGIN_NAMESPACE diff --git a/src/gui/statemachine/qbasicmouseeventtransition.cpp b/src/gui/statemachine/qbasicmouseeventtransition.cpp index 42b7580..a18d1e8 100644 --- a/src/gui/statemachine/qbasicmouseeventtransition.cpp +++ b/src/gui/statemachine/qbasicmouseeventtransition.cpp @@ -13,12 +13,7 @@ #include #include #include - -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qabstracttransition_p.h" -#else -# include -#endif +#include QT_BEGIN_NAMESPACE diff --git a/src/gui/statemachine/qbasicmouseeventtransition_p.h b/src/gui/statemachine/qbasicmouseeventtransition_p.h index 57f83c6..6a3ad1e 100644 --- a/src/gui/statemachine/qbasicmouseeventtransition_p.h +++ b/src/gui/statemachine/qbasicmouseeventtransition_p.h @@ -23,12 +23,7 @@ // We mean it. // -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qabstracttransition.h" -#else -# include -#endif - +#include #include QT_BEGIN_NAMESPACE diff --git a/src/gui/statemachine/qkeyeventtransition.cpp b/src/gui/statemachine/qkeyeventtransition.cpp index 3cf51a3..0418501 100644 --- a/src/gui/statemachine/qkeyeventtransition.cpp +++ b/src/gui/statemachine/qkeyeventtransition.cpp @@ -12,12 +12,7 @@ #include "qkeyeventtransition.h" #include "qbasickeyeventtransition_p.h" #include - -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qeventtransition_p.h" -#else -# include -#endif +#include QT_BEGIN_NAMESPACE diff --git a/src/gui/statemachine/qkeyeventtransition.h b/src/gui/statemachine/qkeyeventtransition.h index 08595e8..08c4800 100644 --- a/src/gui/statemachine/qkeyeventtransition.h +++ b/src/gui/statemachine/qkeyeventtransition.h @@ -12,11 +12,8 @@ #ifndef QKEYEVENTTRANSITION_H #define QKEYEVENTTRANSITION_H -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qeventtransition.h" -#else -# include -#endif +#include + QT_BEGIN_HEADER QT_BEGIN_NAMESPACE diff --git a/src/gui/statemachine/qmouseeventtransition.cpp b/src/gui/statemachine/qmouseeventtransition.cpp index 5ffdab0..ae3c407 100644 --- a/src/gui/statemachine/qmouseeventtransition.cpp +++ b/src/gui/statemachine/qmouseeventtransition.cpp @@ -13,12 +13,7 @@ #include "qbasicmouseeventtransition_p.h" #include #include - -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qeventtransition_p.h" -#else -# include -#endif +#include QT_BEGIN_NAMESPACE diff --git a/src/gui/statemachine/qmouseeventtransition.h b/src/gui/statemachine/qmouseeventtransition.h index e878a58..aedc5c2 100644 --- a/src/gui/statemachine/qmouseeventtransition.h +++ b/src/gui/statemachine/qmouseeventtransition.h @@ -12,12 +12,8 @@ #ifndef QMOUSEEVENTTRANSITION_H #define QMOUSEEVENTTRANSITION_H -//Qt -#if defined(QT_EXPERIMENTAL_SOLUTION) -# include "qeventtransition.h" -#else -# include -#endif +#include + QT_BEGIN_HEADER QT_BEGIN_NAMESPACE -- cgit v0.12 From ee550f157d4c9ca7816a75ac344d1c32eaf1f2b1 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 13:27:30 +0200 Subject: add README file for examples/animation --- examples/animation/README | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 examples/animation/README diff --git a/examples/animation/README b/examples/animation/README new file mode 100644 index 0000000..6a892f8 --- /dev/null +++ b/examples/animation/README @@ -0,0 +1,38 @@ +The animation framework aims to provide an easy way for creating animated and +smooth GUI's. By animating Qt properties, the framework provides great freedom +for animating widgets and other QObjects. The framework can also be used with +the Graphics View framework. + +The example launcher provided with Qt can be used to explore each of the +examples in this directory. + +Documentation for these examples can be found via the Tutorial and Examples +link in the main Qt documentation. + + +Finding the Qt Examples and Demos launcher +========================================== + +On Windows: + +The launcher can be accessed via the Windows Start menu. Select the menu +entry entitled "Qt Examples and Demos" entry in the submenu containing +the Qt tools. + +On Mac OS X: + +For the binary distribution, the qtdemo executable is installed in the +/Developer/Applications/Qt directory. For the source distribution, it is +installed alongside the other Qt tools on the path specified when Qt is +configured. + +On Unix/Linux: + +The qtdemo executable is installed alongside the other Qt tools on the path +specified when Qt is configured. + +On all platforms: + +The source code for the launcher can be found in the demos/qtdemo directory +in the Qt package. This example is built at the same time as the Qt libraries, +tools, examples, and demonstrations. -- cgit v0.12 From 5504a102e9f608fed7377332b8de7b823cf22b85 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 14:05:47 +0200 Subject: compile when using qt namespace --- src/3rdparty/easing/easing.cpp | 1 + src/corelib/tools/qeasingcurve.cpp | 9 +++++++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/src/3rdparty/easing/easing.cpp b/src/3rdparty/easing/easing.cpp index 5bd3997..81af40f 100644 --- a/src/3rdparty/easing/easing.cpp +++ b/src/3rdparty/easing/easing.cpp @@ -26,6 +26,7 @@ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND #define M_PI_2 (M_PI / 2) #endif +QT_USE_NAMESPACE /** * Easing equation function for a simple linear tweening, with no easing. diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp index 34765c8..8c37137 100644 --- a/src/corelib/tools/qeasingcurve.cpp +++ b/src/corelib/tools/qeasingcurve.cpp @@ -295,6 +295,11 @@ #include "qeasingcurve.h" +#ifndef QT_NO_DEBUG_STREAM +#include +#include +#endif + QT_BEGIN_NAMESPACE static bool isConfigFunction(QEasingCurve::Type type) @@ -341,7 +346,9 @@ bool QEasingCurveFunction::operator==(const QEasingCurveFunction& other) _o == other._o; } +QT_BEGIN_INCLUDE_NAMESPACE #include "../3rdparty/easing/easing.cpp" +QT_END_INCLUDE_NAMESPACE class QEasingCurvePrivate { @@ -823,8 +830,6 @@ qreal QEasingCurve::valueForProgress(qreal progress) const } #ifndef QT_NO_DEBUG_STREAM -#include -#include QDebug operator<<(QDebug debug, const QEasingCurve &item) { debug << "type:" << item.d_ptr->type -- cgit v0.12 From ac5fceafb00a2f007239f9b0fc89fe01a2064d62 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 15:34:11 +0200 Subject: compile with -qtnamespace, clean up the example .pro files --- examples/animation/animatedtiles/animatedtiles.pro | 10 ++++++-- examples/animation/animatedtiles/main.cpp | 2 ++ examples/animation/appchooser/appchooser.pro | 5 ++-- examples/animation/easing/easing.pro | 24 ++++++++--------- examples/animation/easing/easing.qrc | 5 ++++ examples/animation/easing/main.cpp | 1 + examples/animation/easing/resources.qrc | 5 ---- examples/animation/moveblocks/moveblocks.pro | 5 ++-- .../animation/padnavigator-ng/padnavigator.pro | 12 ++++----- examples/animation/padnavigator-ng/panel.h | 4 +-- .../animation/padnavigator-ng/roundrectitem.cpp | 4 +-- examples/animation/stickman/animation.h | 2 ++ .../animation/stickman/editor/animationdialog.h | 2 ++ examples/animation/stickman/lifecycle.h | 2 ++ examples/animation/stickman/stickman.h | 2 ++ examples/animation/stickman/stickman.pro | 27 +++++++++++-------- examples/animation/sub-attaq/animationmanager.h | 2 ++ examples/animation/sub-attaq/boat.h | 2 ++ .../sub-attaq/custompropertyanimation.cpp | 7 ----- .../animation/sub-attaq/custompropertyanimation.h | 2 ++ examples/animation/sub-attaq/graphicsscene.h | 2 ++ examples/animation/sub-attaq/mainwindow.h | 3 ++- examples/animation/sub-attaq/states.h | 2 ++ examples/animation/sub-attaq/sub-attaq.pro | 15 +++++------ .../eventtransitions/eventtransitions.pro | 12 ++++----- examples/statemachine/factorial/factorial.pro | 11 ++++---- examples/statemachine/pingpong/pingpong.pro | 13 +++++----- examples/statemachine/tankgame/gameitem.h | 2 ++ examples/statemachine/tankgame/mainwindow.h | 3 +++ examples/statemachine/tankgame/plugin.h | 4 +++ examples/statemachine/tankgame/tankgame.pro | 30 +++++++++++++--------- .../statemachine/trafficlight/trafficlight.pro | 7 +---- .../statemachine/twowaybutton/twowaybutton.pro | 12 ++++----- 33 files changed, 136 insertions(+), 105 deletions(-) create mode 100644 examples/animation/easing/easing.qrc delete mode 100644 examples/animation/easing/resources.qrc diff --git a/examples/animation/animatedtiles/animatedtiles.pro b/examples/animation/animatedtiles/animatedtiles.pro index 9e9062c..1840b17 100644 --- a/examples/animation/animatedtiles/animatedtiles.pro +++ b/examples/animation/animatedtiles/animatedtiles.pro @@ -1,2 +1,8 @@ -SOURCES += main.cpp -RESOURCES += animatedtiles.qrc +SOURCES = main.cpp +RESOURCES = animatedtiles.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/animatedtiles +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS animatedtiles.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/animatedtiles +INSTALLS += target sources diff --git a/examples/animation/animatedtiles/main.cpp b/examples/animation/animatedtiles/main.cpp index 7988758..4b1d99d 100644 --- a/examples/animation/animatedtiles/main.cpp +++ b/examples/animation/animatedtiles/main.cpp @@ -132,6 +132,8 @@ protected: int main(int argc, char **argv) { + Q_INIT_RESOURCE(animatedtiles); + QApplication app(argc, argv); QPixmap kineticPix(":/images/kinetic.png"); diff --git a/examples/animation/appchooser/appchooser.pro b/examples/animation/appchooser/appchooser.pro index 8cda19a..847b60a 100644 --- a/examples/animation/appchooser/appchooser.pro +++ b/examples/animation/appchooser/appchooser.pro @@ -1,6 +1,5 @@ -# Input -SOURCES += main.cpp -RESOURCES += appchooser.qrc +SOURCES = main.cpp +RESOURCES = appchooser.qrc # install target.path = $$[QT_INSTALL_EXAMPLES]/animation/appchooser diff --git a/examples/animation/easing/easing.pro b/examples/animation/easing/easing.pro index fa5b22d..8e8a35f 100644 --- a/examples/animation/easing/easing.pro +++ b/examples/animation/easing/easing.pro @@ -1,16 +1,14 @@ -###################################################################### -# Automatically generated by qmake (2.01a) to 2. okt 23:22:11 2008 -###################################################################### +HEADERS = window.h \ + animation.h +SOURCES = main.cpp \ + window.cpp -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . +FORMS = form.ui -# Input -HEADERS += window.h animation.h -SOURCES += main.cpp window.cpp +RESOURCES = easing.qrc -FORMS += form.ui - -RESOURCES = resources.qrc +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/easing +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS easing.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/easing +INSTALLS += target sources diff --git a/examples/animation/easing/easing.qrc b/examples/animation/easing/easing.qrc new file mode 100644 index 0000000..7e112d3 --- /dev/null +++ b/examples/animation/easing/easing.qrc @@ -0,0 +1,5 @@ + + + images/qt-logo.png + + \ No newline at end of file diff --git a/examples/animation/easing/main.cpp b/examples/animation/easing/main.cpp index 487fa86..bd10df2 100644 --- a/examples/animation/easing/main.cpp +++ b/examples/animation/easing/main.cpp @@ -44,6 +44,7 @@ int main(int argc, char **argv) { + Q_INIT_RESOURCE(easing); QApplication app(argc, argv); Window w; w.resize(400, 400); diff --git a/examples/animation/easing/resources.qrc b/examples/animation/easing/resources.qrc deleted file mode 100644 index 7e112d3..0000000 --- a/examples/animation/easing/resources.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - images/qt-logo.png - - \ No newline at end of file diff --git a/examples/animation/moveblocks/moveblocks.pro b/examples/animation/moveblocks/moveblocks.pro index 7a82ca5..b8e88b2 100644 --- a/examples/animation/moveblocks/moveblocks.pro +++ b/examples/animation/moveblocks/moveblocks.pro @@ -1,8 +1,7 @@ -# Input -SOURCES += main.cpp +SOURCES = main.cpp # install target.path = $$[QT_INSTALL_EXAMPLES]/animation/moveblocks -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS states.pro +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS moveblocks.pro sources.path = $$[QT_INSTALL_EXAMPLES]/animation/moveblocks INSTALLS += target sources diff --git a/examples/animation/padnavigator-ng/padnavigator.pro b/examples/animation/padnavigator-ng/padnavigator.pro index 0d094c6..8e53a6d 100644 --- a/examples/animation/padnavigator-ng/padnavigator.pro +++ b/examples/animation/padnavigator-ng/padnavigator.pro @@ -1,24 +1,24 @@ -HEADERS += \ +HEADERS = \ panel.h \ roundrectitem.h \ splashitem.h -SOURCES += \ +SOURCES = \ panel.cpp \ roundrectitem.cpp \ splashitem.cpp \ main.cpp -RESOURCES += \ +RESOURCES = \ padnavigator.qrc -FORMS += \ +FORMS = \ backside.ui contains(QT_CONFIG, opengl):QT += opengl # install -target.path = $$[QT_INSTALL_EXAMPLES]/graphicsview/padnavigator +target.path = $$[QT_INSTALL_EXAMPLES]/animation/padnavigator-ng sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS padnavigator.pro images -sources.path = $$[QT_INSTALL_EXAMPLES]/graphicsview/padnavigator +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/padnavigator-ng INSTALLS += target sources diff --git a/examples/animation/padnavigator-ng/panel.h b/examples/animation/padnavigator-ng/panel.h index 8ad95d9..9aca29d 100644 --- a/examples/animation/padnavigator-ng/panel.h +++ b/examples/animation/padnavigator-ng/panel.h @@ -44,11 +44,11 @@ QT_BEGIN_NAMESPACE class Ui_BackSide; +class QAnimationGroup; +class QPropertyAnimation; QT_END_NAMESPACE; class RoundRectItem; -class QAnimationGroup; -class QPropertyAnimation; class Panel : public QGraphicsView { diff --git a/examples/animation/padnavigator-ng/roundrectitem.cpp b/examples/animation/padnavigator-ng/roundrectitem.cpp index 7e7d423..2ff216c 100644 --- a/examples/animation/padnavigator-ng/roundrectitem.cpp +++ b/examples/animation/padnavigator-ng/roundrectitem.cpp @@ -45,9 +45,9 @@ RoundRectItem::RoundRectItem(const QRectF &rect, const QBrush &brush, QWidget *embeddedWidget) : QGraphicsWidget(), + m_rect(rect), brush(brush), - proxyWidget(0), - m_rect(rect) + proxyWidget(0) { if (embeddedWidget) { proxyWidget = new QGraphicsProxyWidget(this); diff --git a/examples/animation/stickman/animation.h b/examples/animation/stickman/animation.h index e6c375e..b0b39c9 100644 --- a/examples/animation/stickman/animation.h +++ b/examples/animation/stickman/animation.h @@ -47,7 +47,9 @@ #include class Frame; +QT_BEGIN_NAMESPACE class QIODevice; +QT_END_NAMESPACE class Animation { public: diff --git a/examples/animation/stickman/editor/animationdialog.h b/examples/animation/stickman/editor/animationdialog.h index 764cdaf..6025088 100644 --- a/examples/animation/stickman/editor/animationdialog.h +++ b/examples/animation/stickman/editor/animationdialog.h @@ -45,8 +45,10 @@ #include #include +QT_BEGIN_NAMESPACE class QSpinBox; class QLineEdit; +QT_END_NAMESPACE class StickMan; class Animation; class AnimationDialog: public QDialog diff --git a/examples/animation/stickman/lifecycle.h b/examples/animation/stickman/lifecycle.h index 8fd0fb2..2be4762 100644 --- a/examples/animation/stickman/lifecycle.h +++ b/examples/animation/stickman/lifecycle.h @@ -45,11 +45,13 @@ #include class StickMan; +QT_BEGIN_NAMESPACE class QStateMachine; class QAnimationGroup; class QState; class QAbstractState; class QAbstractTransition; +QT_END_NAMESPACE class GraphicsView; class LifeCycle { diff --git a/examples/animation/stickman/stickman.h b/examples/animation/stickman/stickman.h index 46863a3..6395272 100644 --- a/examples/animation/stickman/stickman.h +++ b/examples/animation/stickman/stickman.h @@ -47,7 +47,9 @@ const int LimbCount = 16; class Node; +QT_BEGIN_NAMESPACE class QTimer; +QT_END_NAMESPACE class StickMan: public QObject, public QGraphicsItem { Q_OBJECT diff --git a/examples/animation/stickman/stickman.pro b/examples/animation/stickman/stickman.pro index bfee5b0..956b49c 100644 --- a/examples/animation/stickman/stickman.pro +++ b/examples/animation/stickman/stickman.pro @@ -1,14 +1,19 @@ -###################################################################### -# Automatically generated by qmake (2.01a) ti 3. feb 19:50:14 2009 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . +HEADERS += stickman.h \ + animation.h \ + node.h \ + lifecycle.h \ + graphicsview.h +SOURCES += main.cpp \ + stickman.cpp \ + animation.cpp \ + node.cpp \ + lifecycle.cpp \ + graphicsview.cpp include(editor/editor.pri) -# Input -HEADERS += stickman.h animation.h node.h lifecycle.h graphicsview.h -SOURCES += main.cpp stickman.cpp animation.cpp node.cpp lifecycle.cpp graphicsview.cpp +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/stickman +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS stickman.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/stickman +INSTALLS += target sources diff --git a/examples/animation/sub-attaq/animationmanager.h b/examples/animation/sub-attaq/animationmanager.h index 69ec3d7..a563c96 100644 --- a/examples/animation/sub-attaq/animationmanager.h +++ b/examples/animation/sub-attaq/animationmanager.h @@ -44,7 +44,9 @@ #include +QT_BEGIN_NAMESPACE class QAbstractAnimation; +QT_END_NAMESPACE class AnimationManager : public QObject { diff --git a/examples/animation/sub-attaq/boat.h b/examples/animation/sub-attaq/boat.h index f16074e..08a9fa2 100644 --- a/examples/animation/sub-attaq/boat.h +++ b/examples/animation/sub-attaq/boat.h @@ -50,9 +50,11 @@ class PixmapItem; class Bomb; +QT_BEGIN_NAMESPACE class QVariantAnimation; class QAbstractAnimation; class QStateMachine; +QT_END_NAMESPACE class Boat : public QGraphicsWidget { diff --git a/examples/animation/sub-attaq/custompropertyanimation.cpp b/examples/animation/sub-attaq/custompropertyanimation.cpp index f7ab269..8226cca 100644 --- a/examples/animation/sub-attaq/custompropertyanimation.cpp +++ b/examples/animation/sub-attaq/custompropertyanimation.cpp @@ -44,9 +44,6 @@ // Qt #include -QT_BEGIN_NAMESPACE - - CustomPropertyAnimation::CustomPropertyAnimation(QObject *parent) : QVariantAnimation(parent), animProp(0) { @@ -108,8 +105,4 @@ void CustomPropertyAnimation::updateState(QAbstractAnimation::State oldState, QA QVariantAnimation::updateState(oldState, newState); } - - #include "moc_custompropertyanimation.cpp" - -QT_END_NAMESPACE diff --git a/examples/animation/sub-attaq/custompropertyanimation.h b/examples/animation/sub-attaq/custompropertyanimation.h index 1dca454..8654aeb 100644 --- a/examples/animation/sub-attaq/custompropertyanimation.h +++ b/examples/animation/sub-attaq/custompropertyanimation.h @@ -44,7 +44,9 @@ #include +QT_BEGIN_NAMESPACE class QGraphicsItem; +QT_END_NAMESPACE struct AbstractProperty { diff --git a/examples/animation/sub-attaq/graphicsscene.h b/examples/animation/sub-attaq/graphicsscene.h index 70c873e..8b0ea96 100644 --- a/examples/animation/sub-attaq/graphicsscene.h +++ b/examples/animation/sub-attaq/graphicsscene.h @@ -54,7 +54,9 @@ class Torpedo; class Bomb; class PixmapItem; class ProgressItem; +QT_BEGIN_NAMESPACE class QAction; +QT_END_NAMESPACE class GraphicsScene : public QGraphicsScene { diff --git a/examples/animation/sub-attaq/mainwindow.h b/examples/animation/sub-attaq/mainwindow.h index 72d1324..87f194a 100644 --- a/examples/animation/sub-attaq/mainwindow.h +++ b/examples/animation/sub-attaq/mainwindow.h @@ -44,9 +44,10 @@ //Qt #include - class GraphicsScene; +QT_BEGIN_NAMESPACE class QGraphicsView; +QT_END_NAMESPACE class MainWindow : public QMainWindow { diff --git a/examples/animation/sub-attaq/states.h b/examples/animation/sub-attaq/states.h index 3203b3b..71375e0 100644 --- a/examples/animation/sub-attaq/states.h +++ b/examples/animation/sub-attaq/states.h @@ -52,7 +52,9 @@ class GraphicsScene; class Boat; class SubMarine; +QT_BEGIN_NAMESPACE class QStateMachine; +QT_END_NAMESPACE class PlayState : public QState { diff --git a/examples/animation/sub-attaq/sub-attaq.pro b/examples/animation/sub-attaq/sub-attaq.pro index 961a9b5..d13a099 100644 --- a/examples/animation/sub-attaq/sub-attaq.pro +++ b/examples/animation/sub-attaq/sub-attaq.pro @@ -1,14 +1,5 @@ -# ##################################################################### -# Automatically generated by qmake (2.01a) Thu Oct 9 10:53:30 2008 -# ##################################################################### -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . -QT += xml contains(QT_CONFIG, opengl):QT += opengl -# Input HEADERS += boat.h \ bomb.h \ mainwindow.h \ @@ -37,3 +28,9 @@ SOURCES += boat.cpp \ qanimationstate.cpp \ progressitem.cpp RESOURCES += subattaq.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/sub-attaq +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS sub-attaq.pro pics +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/sub-attaq +INSTALLS += target sources diff --git a/examples/statemachine/eventtransitions/eventtransitions.pro b/examples/statemachine/eventtransitions/eventtransitions.pro index 6a976cb..7e92cf2 100644 --- a/examples/statemachine/eventtransitions/eventtransitions.pro +++ b/examples/statemachine/eventtransitions/eventtransitions.pro @@ -1,7 +1,7 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . +SOURCES = main.cpp -# Input -SOURCES += main.cpp +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/eventtransitions +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS eventtransitions.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/eventtransitions +INSTALLS += target sources diff --git a/examples/statemachine/factorial/factorial.pro b/examples/statemachine/factorial/factorial.pro index ac79117..14a6833 100644 --- a/examples/statemachine/factorial/factorial.pro +++ b/examples/statemachine/factorial/factorial.pro @@ -1,10 +1,11 @@ -TEMPLATE = app -TARGET = QT = core win32: CONFIG += console mac:CONFIG -= app_bundle -DEPENDPATH += . -INCLUDEPATH += . -# Input SOURCES += main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/factorial +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS factorial.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/factorial +INSTALLS += target sources diff --git a/examples/statemachine/pingpong/pingpong.pro b/examples/statemachine/pingpong/pingpong.pro index bff9cb8..42eab6c 100644 --- a/examples/statemachine/pingpong/pingpong.pro +++ b/examples/statemachine/pingpong/pingpong.pro @@ -1,10 +1,11 @@ QT = core -TEMPLATE = app -TARGET = win32: CONFIG += console mac:CONFIG -= app_bundle -DEPENDPATH += . -INCLUDEPATH += . -# Input -SOURCES += main.cpp +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/pingpong +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS pingpong.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/pingpong +INSTALLS += target sources diff --git a/examples/statemachine/tankgame/gameitem.h b/examples/statemachine/tankgame/gameitem.h index 43b8785..33caf71 100644 --- a/examples/statemachine/tankgame/gameitem.h +++ b/examples/statemachine/tankgame/gameitem.h @@ -3,7 +3,9 @@ #include +QT_BEGIN_NAMESPACE class QLineF; +QT_END_NAMESPACE class GameItem: public QObject, public QGraphicsItem { Q_OBJECT diff --git a/examples/statemachine/tankgame/mainwindow.h b/examples/statemachine/tankgame/mainwindow.h index 40e1595..391ab77 100644 --- a/examples/statemachine/tankgame/mainwindow.h +++ b/examples/statemachine/tankgame/mainwindow.h @@ -4,11 +4,14 @@ #include #include +QT_BEGIN_NAMESPACE class QGraphicsScene; class QStateMachine; class QState; +QT_END_NAMESPACE class GameOverTransition; class TankItem; + class MainWindow: public QMainWindow { Q_OBJECT diff --git a/examples/statemachine/tankgame/plugin.h b/examples/statemachine/tankgame/plugin.h index 2b48d43..006ad78 100644 --- a/examples/statemachine/tankgame/plugin.h +++ b/examples/statemachine/tankgame/plugin.h @@ -3,7 +3,9 @@ #include +QT_BEGIN_NAMESPACE class QState; +QT_END_NAMESPACE class Plugin { public: @@ -12,6 +14,8 @@ public: virtual QState *create(QState *parentState, QObject *tank) = 0; }; +QT_BEGIN_NAMESPACE Q_DECLARE_INTERFACE(Plugin, "TankPlugin") +QT_END_NAMESPACE #endif diff --git a/examples/statemachine/tankgame/tankgame.pro b/examples/statemachine/tankgame/tankgame.pro index 46cfe2e..59415be 100644 --- a/examples/statemachine/tankgame/tankgame.pro +++ b/examples/statemachine/tankgame/tankgame.pro @@ -1,13 +1,19 @@ -###################################################################### -# Automatically generated by qmake (2.01a) on 22. apr 14:11:33 2009 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += C:/dev/kinetic/examples/statemachine/tankgame/. . - -# Input -HEADERS += mainwindow.h plugin.h tankitem.h rocketitem.h gameitem.h gameovertransition.h -SOURCES += main.cpp mainwindow.cpp tankitem.cpp rocketitem.cpp gameitem.cpp gameovertransition.cpp +HEADERS += mainwindow.h \ + plugin.h \ + tankitem.h \ + rocketitem.h \ + gameitem.h \ + gameovertransition.h +SOURCES += main.cpp \ + mainwindow.cpp \ + tankitem.cpp \ + rocketitem.cpp \ + gameitem.cpp \ + gameovertransition.cpp CONFIG += console + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS tankgame.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame +INSTALLS += target sources diff --git a/examples/statemachine/trafficlight/trafficlight.pro b/examples/statemachine/trafficlight/trafficlight.pro index 730bd75..684575a 100644 --- a/examples/statemachine/trafficlight/trafficlight.pro +++ b/examples/statemachine/trafficlight/trafficlight.pro @@ -1,9 +1,4 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -SOURCES += main.cpp +SOURCES = main.cpp # install target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/trafficlight diff --git a/examples/statemachine/twowaybutton/twowaybutton.pro b/examples/statemachine/twowaybutton/twowaybutton.pro index 6a976cb..f6cbc57 100644 --- a/examples/statemachine/twowaybutton/twowaybutton.pro +++ b/examples/statemachine/twowaybutton/twowaybutton.pro @@ -1,7 +1,7 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . +SOURCES = main.cpp -# Input -SOURCES += main.cpp +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/twowaybutton +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS twowaybutton.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/twowaybutton +INSTALLS += target sources -- cgit v0.12 From 5a60fd1a0b39b9d366a524cc8c8576b417551e6d Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 16:08:54 +0200 Subject: fix two .pro file bugs --- examples/animation/animation.pro | 1 - examples/examples.pro | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/animation/animation.pro b/examples/animation/animation.pro index 0a57d3d..d51a89d 100644 --- a/examples/animation/animation.pro +++ b/examples/animation/animation.pro @@ -4,7 +4,6 @@ SUBDIRS += \ animatedtiles \ appchooser \ easing \ - example \ moveblocks \ padnavigator-ng \ states \ diff --git a/examples/examples.pro b/examples/examples.pro index 332a712..bfcf9b4 100644 --- a/examples/examples.pro +++ b/examples/examples.pro @@ -1,5 +1,6 @@ TEMPLATE = subdirs SUBDIRS = \ + animation \ desktop \ dialogs \ draganddrop \ @@ -25,7 +26,6 @@ SUBDIRS = \ contains(QT_CONFIG, phonon):!static: SUBDIRS += phonon contains(QT_CONFIG, webkit): SUBDIRS += webkit -contains(QT_CONFIG, animation): SUBDIRS += animation embedded:SUBDIRS += qws !wince*: { !contains(QT_EDITION, Console):contains(QT_BUILD_PARTS, tools):SUBDIRS += designer -- cgit v0.12 From dcdd15156595dbc317732970e48efa32d32b256a Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 16:13:00 +0200 Subject: fix compiler warnings --- examples/animation/stickman/node.cpp | 4 ++-- examples/animation/stickman/stickman.cpp | 2 +- examples/statemachine/tankgame/mainwindow.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/animation/stickman/node.cpp b/examples/animation/stickman/node.cpp index ed18108..9c485d9 100644 --- a/examples/animation/stickman/node.cpp +++ b/examples/animation/stickman/node.cpp @@ -75,7 +75,7 @@ QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) return QGraphicsItem::itemChange(change, value); } -void Node::mousePressEvent(QGraphicsSceneMouseEvent *event) +void Node::mousePressEvent(QGraphicsSceneMouseEvent *) { m_dragging = true; } @@ -86,7 +86,7 @@ void Node::mouseMoveEvent(QGraphicsSceneMouseEvent *event) setPos(mapToParent(event->pos())); } -void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) +void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *) { m_dragging = false; } diff --git a/examples/animation/stickman/stickman.cpp b/examples/animation/stickman/stickman.cpp index 5eb392f..e00ea41 100644 --- a/examples/animation/stickman/stickman.cpp +++ b/examples/animation/stickman/stickman.cpp @@ -178,7 +178,7 @@ Node *StickMan::node(int idx) const return 0; } -void StickMan::timerEvent(QTimerEvent *e) +void StickMan::timerEvent(QTimerEvent *) { update(); } diff --git a/examples/statemachine/tankgame/mainwindow.cpp b/examples/statemachine/tankgame/mainwindow.cpp index fcc0325..3437140 100644 --- a/examples/statemachine/tankgame/mainwindow.cpp +++ b/examples/statemachine/tankgame/mainwindow.cpp @@ -201,7 +201,7 @@ void MainWindow::gameOver() TankItem *lastTankStanding = 0; foreach (QGraphicsItem *item, items) { if (GameItem *gameItem = qgraphicsitem_cast(item)) { - if (lastTankStanding = qobject_cast(gameItem)) + if ((lastTankStanding = qobject_cast(gameItem)) != 0) break; } } -- cgit v0.12 From bf69207bd98603bd645ba010f572c990fdb7d82b Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 20 May 2009 16:31:58 +0200 Subject: add animation and state machine examples to qtdemo --- demos/qtdemo/xml/examples.xml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/demos/qtdemo/xml/examples.xml b/demos/qtdemo/xml/examples.xml index 96a3e80..2560848 100644 --- a/demos/qtdemo/xml/examples.xml +++ b/demos/qtdemo/xml/examples.xml @@ -19,6 +19,15 @@ + + + + + + + + + @@ -167,6 +176,12 @@ + + + + + + -- cgit v0.12 From 8769a71f56886ea4925fc460a553f53500dd0b4e Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Wed, 20 May 2009 15:59:52 +0200 Subject: Avoid memory leaks in QStateMachine tests Give some objects parents and allocate some objects on the stack to avoid leaking them. --- tests/auto/qstatemachine/tst_qstatemachine.cpp | 57 +++++++++++++------------- 1 file changed, 28 insertions(+), 29 deletions(-) diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index 7476831..d033869 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -522,8 +522,7 @@ void tst_QStateMachine::customLocalErrorStateInParentOfBrokenState() QState *parentOfBrokenState = new QState(); machine.addState(parentOfBrokenState); parentOfBrokenState->setObjectName("parentOfBrokenState"); - parentOfBrokenState->setErrorState(customErrorState); - + parentOfBrokenState->setErrorState(customErrorState); QState *brokenState = new QState(parentOfBrokenState); brokenState->setObjectName("brokenState"); @@ -891,7 +890,7 @@ void tst_QStateMachine::brokenStateIsNeverEntered() { QStateMachine machine; - QObject *entryController = new QObject(); + QObject *entryController = new QObject(&machine); entryController->setProperty("brokenStateEntered", false); entryController->setProperty("childStateEntered", false); entryController->setProperty("errorStateEntered", false); @@ -927,15 +926,15 @@ void tst_QStateMachine::transitionToStateNotInGraph() { s_countWarnings = false; - QStateMachine machine; + QStateMachine machine; QState *initialState = new QState(machine.rootState()); initialState->setObjectName("initialState"); machine.setInitialState(initialState); - QState *independentState = new QState(); - independentState->setObjectName("independentState"); - initialState->addTransition(independentState); + QState independentState; + independentState.setObjectName("independentState"); + initialState->addTransition(&independentState); machine.start(); QCoreApplication::processEvents(); @@ -950,10 +949,10 @@ void tst_QStateMachine::customErrorStateNotInGraph() QStateMachine machine; - QState *errorState = new QState(); - errorState->setObjectName("errorState"); - machine.setErrorState(errorState); - QVERIFY(errorState != machine.errorState()); + QState errorState; + errorState.setObjectName("errorState"); + machine.setErrorState(&errorState); + QVERIFY(&errorState != machine.errorState()); QState *initialBrokenState = new QState(machine.rootState()); initialBrokenState->setObjectName("initialBrokenState"); @@ -969,13 +968,13 @@ void tst_QStateMachine::customErrorStateNotInGraph() void tst_QStateMachine::restoreProperties() { - QObject *object = new QObject(); - object->setProperty("a", 1); - object->setProperty("b", 2); - QStateMachine machine; machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + QObject *object = new QObject(&machine); + object->setProperty("a", 1); + object->setProperty("b", 2); + QState *S1 = new QState(); S1->setObjectName("S1"); S1->assignProperty(object, "a", 3); @@ -2025,8 +2024,8 @@ void tst_QStateMachine::targetStateWithNoParent() QStateMachine machine; QState *s1 = new QState(machine.rootState()); s1->setObjectName("s1"); - QState *s2 = new QState(); - s1->addTransition(s2); + QState s2; + s1->addTransition(&s2); machine.setInitialState(s1); QSignalSpy startedSpy(&machine, SIGNAL(started())); QSignalSpy stoppedSpy(&machine, SIGNAL(stopped())); @@ -2058,7 +2057,7 @@ void tst_QStateMachine::defaultGlobalRestorePolicy() { QStateMachine machine; - QObject *propertyHolder = new QObject(); + QObject *propertyHolder = new QObject(&machine); propertyHolder->setProperty("a", 1); propertyHolder->setProperty("b", 2); @@ -2147,7 +2146,7 @@ void tst_QStateMachine::globalRestorePolicySetToDoNotRestore() QStateMachine machine; machine.setGlobalRestorePolicy(QStateMachine::DoNotRestoreProperties); - QObject *propertyHolder = new QObject(); + QObject *propertyHolder = new QObject(&machine); propertyHolder->setProperty("a", 1); propertyHolder->setProperty("b", 2); @@ -2308,7 +2307,7 @@ void tst_QStateMachine::globalRestorePolicySetToRestore() QStateMachine machine; machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - QObject *propertyHolder = new QObject(); + QObject *propertyHolder = new QObject(&machine); propertyHolder->setProperty("a", 1); propertyHolder->setProperty("b", 2); @@ -2428,7 +2427,7 @@ void tst_QStateMachine::simpleAnimation() { QStateMachine machine; - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("fooBar", 1.0); QState *s1 = new QState(machine.rootState()); @@ -2471,7 +2470,7 @@ void tst_QStateMachine::twoAnimations() { QStateMachine machine; - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("foo", 1.0); object->setProperty("bar", 3.0); @@ -2515,7 +2514,7 @@ void tst_QStateMachine::twoAnimatedTransitions() { QStateMachine machine; - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("foo", 1.0); QState *s1 = new QState(machine.rootState()); @@ -2559,7 +2558,7 @@ void tst_QStateMachine::playAnimationTwice() { QStateMachine machine; - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("foo", 1.0); QState *s1 = new QState(machine.rootState()); @@ -2602,7 +2601,7 @@ void tst_QStateMachine::nestedTargetStateForAnimation() { QStateMachine machine; - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("foo", 1.0); object->setProperty("bar", 3.0); @@ -2659,7 +2658,7 @@ void tst_QStateMachine::animatedGlobalRestoreProperty() QStateMachine machine; machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("foo", 1.0); SlotCalledCounter counter; @@ -2705,7 +2704,7 @@ void tst_QStateMachine::specificTargetValueOfAnimation() { QStateMachine machine; - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("foo", 1.0); QState *s1 = new QState(machine.rootState()); @@ -2769,7 +2768,7 @@ void tst_QStateMachine::addDefaultAnimationWithUnusedAnimation() { QStateMachine machine; - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("foo", 1.0); object->setProperty("bar", 2.0); @@ -2848,7 +2847,7 @@ void tst_QStateMachine::overrideDefaultAnimationWithSpecific() { QStateMachine machine; - QObject *object = new QObject(); + QObject *object = new QObject(&machine); object->setProperty("foo", 1.0); SlotCalledCounter counter; -- cgit v0.12 From b5fd79dfe69513ccf8d83e2eac45ae9b830a2d56 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 20 May 2009 08:38:32 +0200 Subject: Fix GLSL for OMAP3 and error checking --- src/opengl/gl2paintengineex/qglengineshadermanager.cpp | 4 ++-- src/opengl/gl2paintengineex/qglengineshadersource_p.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index d238830..514aac0 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -154,7 +154,7 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) simpleShaderProg->addShader(compiledShaders[MainFragmentShader]); simpleShaderProg->addShader(compiledShaders[ShockingPinkSrcFragmentShader]); simpleShaderProg->link(); - if (!simpleShaderProg->isValid()) { + if (!simpleShaderProg->isLinked()) { qCritical() << "Errors linking simple shader:" << simpleShaderProg->log(); } @@ -418,7 +418,7 @@ bool QGLEngineShaderManager::useCorrectShaderProg() requiredProgram.program->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR); requiredProgram.program->link(); - if (!requiredProgram.program->isValid()) { + if (!requiredProgram.program->isLinked()) { QString error; qWarning() << "Shader program failed to link," #if defined(QT_DEBUG) diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index bf896b1..fdbba72 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -284,7 +284,7 @@ static const char* const qglslNonPremultipliedImageSrcFragmentShader = "\ static const char* const qglslShockingPinkSrcFragmentShader = "\ lowp vec4 srcPixel() { \ - return lowp vec4(0.98, 0.06, 0.75, 1.0); \ + return vec4(0.98, 0.06, 0.75, 1.0); \ }"; -- cgit v0.12 From 27fadaa7eb2d58b47e7f0f508e3402e7a8de3894 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 20 May 2009 16:42:02 +0200 Subject: Make QEglProperties::value() return the EGL default if not set Previously it would always return EGL_DONT_CARE, which causes a bug somewhere on X11 leading to configs being requested with E.g. EGL_GREEN_SIZE == EGL_DONT_CARE == -1 == 0xFFFFFFFF when cast to a uint. This also helps debug config matching as toString() now indicates the match criteria EGL will use. --- src/opengl/qegl.cpp | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 48 insertions(+), 1 deletion(-) diff --git a/src/opengl/qegl.cpp b/src/opengl/qegl.cpp index 165a0f3..aebc3cb 100644 --- a/src/opengl/qegl.cpp +++ b/src/opengl/qegl.cpp @@ -405,7 +405,54 @@ int QEglProperties::value(int name) const if (props[index] == name) return props[index + 1]; } - return EGL_DONT_CARE; + + // If the attribute has not been explicitly set, return the EGL default + // The following defaults were taken from the EGL 1.4 spec: + switch(name) { + case EGL_BUFFER_SIZE: return 0; + case EGL_RED_SIZE: return 0; + case EGL_GREEN_SIZE: return 0; + case EGL_BLUE_SIZE: return 0; + case EGL_LUMINANCE_SIZE: return 0; + case EGL_ALPHA_SIZE: return 0; + case EGL_ALPHA_MASK_SIZE: return 0; + case EGL_BIND_TO_TEXTURE_RGB: return EGL_DONT_CARE; + case EGL_BIND_TO_TEXTURE_RGBA: return EGL_DONT_CARE; + case EGL_COLOR_BUFFER_TYPE: return EGL_RGB_BUFFER; + case EGL_CONFIG_CAVEAT: return EGL_DONT_CARE; + case EGL_CONFIG_ID: return EGL_DONT_CARE; + case EGL_DEPTH_SIZE: return 0; + case EGL_LEVEL: return 0; + case EGL_NATIVE_RENDERABLE: return EGL_DONT_CARE; + case EGL_NATIVE_VISUAL_TYPE: return EGL_DONT_CARE; + case EGL_MAX_SWAP_INTERVAL: return EGL_DONT_CARE; + case EGL_MIN_SWAP_INTERVAL: return EGL_DONT_CARE; + case EGL_RENDERABLE_TYPE: return EGL_OPENGL_ES_BIT; + case EGL_SAMPLE_BUFFERS: return 0; + case EGL_SAMPLES: return 0; + case EGL_STENCIL_SIZE: return 0; + case EGL_SURFACE_TYPE: return EGL_WINDOW_BIT; + case EGL_TRANSPARENT_TYPE: return EGL_NONE; + case EGL_TRANSPARENT_RED_VALUE: return EGL_DONT_CARE; + case EGL_TRANSPARENT_GREEN_VALUE: return EGL_DONT_CARE; + case EGL_TRANSPARENT_BLUE_VALUE: return EGL_DONT_CARE; + +#if defined(EGL_VERSION_1_3) + case EGL_CONFORMANT: return 0; + case EGL_MATCH_NATIVE_PIXMAP: return EGL_NONE; +#endif + + case EGL_MAX_PBUFFER_HEIGHT: + case EGL_MAX_PBUFFER_WIDTH: + case EGL_MAX_PBUFFER_PIXELS: + case EGL_NATIVE_VISUAL_ID: + case EGL_NONE: + qWarning("QEglProperties::value() - Attibute %d does not affect config selection", name); + return 0; + default: + qWarning("QEglProperties::value() - Attibute %d is unknown in EGL <=1.4", name); + return EGL_DONT_CARE; + } } // Set the value associated with a property, replacing an existing -- cgit v0.12 From 1cad8c56002a61a6240e6580cdbd784209821fa6 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 20 May 2009 17:16:48 +0200 Subject: update the padnavigator example and suppress the padnavigator-ng --- examples/animation/padnavigator-ng/backside.ui | 208 ----------------- .../padnavigator-ng/images/artsfftscope.png | Bin 1294 -> 0 bytes .../padnavigator-ng/images/blue_angle_swirl.jpg | Bin 11826 -> 0 bytes .../padnavigator-ng/images/kontact_contacts.png | Bin 4382 -> 0 bytes .../padnavigator-ng/images/kontact_journal.png | Bin 3261 -> 0 bytes .../padnavigator-ng/images/kontact_mail.png | Bin 3202 -> 0 bytes .../padnavigator-ng/images/kontact_notes.png | Bin 3893 -> 0 bytes .../padnavigator-ng/images/kopeteavailable.png | Bin 2380 -> 0 bytes .../padnavigator-ng/images/metacontact_online.png | Bin 2545 -> 0 bytes .../animation/padnavigator-ng/images/minitools.png | Bin 2087 -> 0 bytes examples/animation/padnavigator-ng/main.cpp | 54 ----- .../animation/padnavigator-ng/padnavigator.pro | 24 -- .../animation/padnavigator-ng/padnavigator.qrc | 14 -- examples/animation/padnavigator-ng/panel.cpp | 246 --------------------- examples/animation/padnavigator-ng/panel.h | 85 ------- .../animation/padnavigator-ng/roundrectitem.cpp | 136 ------------ examples/animation/padnavigator-ng/roundrectitem.h | 73 ------ examples/animation/padnavigator-ng/splashitem.cpp | 85 ------- examples/animation/padnavigator-ng/splashitem.h | 57 ----- .../padnavigator/images/artsfftscope.png | Bin 1291 -> 1290 bytes examples/graphicsview/padnavigator/main.cpp | 4 - examples/graphicsview/padnavigator/panel.cpp | 168 +++++++------- examples/graphicsview/padnavigator/panel.h | 29 +-- .../graphicsview/padnavigator/roundrectitem.cpp | 114 ++++------ examples/graphicsview/padnavigator/roundrectitem.h | 16 +- examples/graphicsview/padnavigator/splashitem.cpp | 25 +-- examples/graphicsview/padnavigator/splashitem.h | 6 - 27 files changed, 154 insertions(+), 1190 deletions(-) delete mode 100644 examples/animation/padnavigator-ng/backside.ui delete mode 100644 examples/animation/padnavigator-ng/images/artsfftscope.png delete mode 100644 examples/animation/padnavigator-ng/images/blue_angle_swirl.jpg delete mode 100644 examples/animation/padnavigator-ng/images/kontact_contacts.png delete mode 100644 examples/animation/padnavigator-ng/images/kontact_journal.png delete mode 100644 examples/animation/padnavigator-ng/images/kontact_mail.png delete mode 100644 examples/animation/padnavigator-ng/images/kontact_notes.png delete mode 100644 examples/animation/padnavigator-ng/images/kopeteavailable.png delete mode 100644 examples/animation/padnavigator-ng/images/metacontact_online.png delete mode 100644 examples/animation/padnavigator-ng/images/minitools.png delete mode 100644 examples/animation/padnavigator-ng/main.cpp delete mode 100644 examples/animation/padnavigator-ng/padnavigator.pro delete mode 100644 examples/animation/padnavigator-ng/padnavigator.qrc delete mode 100644 examples/animation/padnavigator-ng/panel.cpp delete mode 100644 examples/animation/padnavigator-ng/panel.h delete mode 100644 examples/animation/padnavigator-ng/roundrectitem.cpp delete mode 100644 examples/animation/padnavigator-ng/roundrectitem.h delete mode 100644 examples/animation/padnavigator-ng/splashitem.cpp delete mode 100644 examples/animation/padnavigator-ng/splashitem.h diff --git a/examples/animation/padnavigator-ng/backside.ui b/examples/animation/padnavigator-ng/backside.ui deleted file mode 100644 index afa488c..0000000 --- a/examples/animation/padnavigator-ng/backside.ui +++ /dev/null @@ -1,208 +0,0 @@ - - BackSide - - - - 0 - 0 - 378 - 385 - - - - BackSide - - - - - - Settings - - - true - - - true - - - - - - Title: - - - - - - - Pad Navigator Example - - - - - - - Modified: - - - - - - - Extent - - - - - - - - - 42 - - - Qt::Horizontal - - - - - - - 42 - - - - - - - - - - - - - - - Other input - - - true - - - true - - - - - - - Widgets On Graphics View - - - - - QGraphicsProxyWidget - - - - QGraphicsWidget - - - - QObject - - - - - QGraphicsItem - - - - - QGraphicsLayoutItem - - - - - - - QGraphicsGridLayout - - - - QGraphicsLayout - - - - QGraphicsLayoutItem - - - - - - - QGraphicsLinearLayout - - - - QGraphicsLayout - - - - QGraphicsLayoutItem - - - - - - - - - - - - - groupBox - hostName - dateTimeEdit - horizontalSlider - spinBox - groupBox_2 - treeWidget - - - - - horizontalSlider - valueChanged(int) - spinBox - setValue(int) - - - 184 - 125 - - - 275 - 127 - - - - - spinBox - valueChanged(int) - horizontalSlider - setValue(int) - - - 272 - 114 - - - 190 - 126 - - - - - diff --git a/examples/animation/padnavigator-ng/images/artsfftscope.png b/examples/animation/padnavigator-ng/images/artsfftscope.png deleted file mode 100644 index b4b8775..0000000 Binary files a/examples/animation/padnavigator-ng/images/artsfftscope.png and /dev/null differ diff --git a/examples/animation/padnavigator-ng/images/blue_angle_swirl.jpg b/examples/animation/padnavigator-ng/images/blue_angle_swirl.jpg deleted file mode 100644 index 5bf0deb..0000000 Binary files a/examples/animation/padnavigator-ng/images/blue_angle_swirl.jpg and /dev/null differ diff --git a/examples/animation/padnavigator-ng/images/kontact_contacts.png b/examples/animation/padnavigator-ng/images/kontact_contacts.png deleted file mode 100644 index 6fb4cc8..0000000 Binary files a/examples/animation/padnavigator-ng/images/kontact_contacts.png and /dev/null differ diff --git a/examples/animation/padnavigator-ng/images/kontact_journal.png b/examples/animation/padnavigator-ng/images/kontact_journal.png deleted file mode 100644 index b1fedb6..0000000 Binary files a/examples/animation/padnavigator-ng/images/kontact_journal.png and /dev/null differ diff --git a/examples/animation/padnavigator-ng/images/kontact_mail.png b/examples/animation/padnavigator-ng/images/kontact_mail.png deleted file mode 100644 index 672f8fa..0000000 Binary files a/examples/animation/padnavigator-ng/images/kontact_mail.png and /dev/null differ diff --git a/examples/animation/padnavigator-ng/images/kontact_notes.png b/examples/animation/padnavigator-ng/images/kontact_notes.png deleted file mode 100644 index 229bf73..0000000 Binary files a/examples/animation/padnavigator-ng/images/kontact_notes.png and /dev/null differ diff --git a/examples/animation/padnavigator-ng/images/kopeteavailable.png b/examples/animation/padnavigator-ng/images/kopeteavailable.png deleted file mode 100644 index 2eaf41a..0000000 Binary files a/examples/animation/padnavigator-ng/images/kopeteavailable.png and /dev/null differ diff --git a/examples/animation/padnavigator-ng/images/metacontact_online.png b/examples/animation/padnavigator-ng/images/metacontact_online.png deleted file mode 100644 index 6a398dd..0000000 Binary files a/examples/animation/padnavigator-ng/images/metacontact_online.png and /dev/null differ diff --git a/examples/animation/padnavigator-ng/images/minitools.png b/examples/animation/padnavigator-ng/images/minitools.png deleted file mode 100644 index 0248c9d..0000000 Binary files a/examples/animation/padnavigator-ng/images/minitools.png and /dev/null differ diff --git a/examples/animation/padnavigator-ng/main.cpp b/examples/animation/padnavigator-ng/main.cpp deleted file mode 100644 index f8b167f..0000000 --- a/examples/animation/padnavigator-ng/main.cpp +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "panel.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - Q_INIT_RESOURCE(padnavigator); - - Panel panel(3, 3); - panel.show(); - - return app.exec(); -} diff --git a/examples/animation/padnavigator-ng/padnavigator.pro b/examples/animation/padnavigator-ng/padnavigator.pro deleted file mode 100644 index 8e53a6d..0000000 --- a/examples/animation/padnavigator-ng/padnavigator.pro +++ /dev/null @@ -1,24 +0,0 @@ -HEADERS = \ - panel.h \ - roundrectitem.h \ - splashitem.h - -SOURCES = \ - panel.cpp \ - roundrectitem.cpp \ - splashitem.cpp \ - main.cpp - -RESOURCES = \ - padnavigator.qrc - -FORMS = \ - backside.ui - -contains(QT_CONFIG, opengl):QT += opengl - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation/padnavigator-ng -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS padnavigator.pro images -sources.path = $$[QT_INSTALL_EXAMPLES]/animation/padnavigator-ng -INSTALLS += target sources diff --git a/examples/animation/padnavigator-ng/padnavigator.qrc b/examples/animation/padnavigator-ng/padnavigator.qrc deleted file mode 100644 index 30ee8e1..0000000 --- a/examples/animation/padnavigator-ng/padnavigator.qrc +++ /dev/null @@ -1,14 +0,0 @@ - - - images/blue_angle_swirl.jpg - images/artsfftscope.png - images/kontact_contacts.png - images/kontact_journal.png - images/kontact_mail.png - images/kontact_notes.png - images/kopeteavailable.png - images/metacontact_online.png - images/minitools.png - images/blue_angle_swirl.jpg - - diff --git a/examples/animation/padnavigator-ng/panel.cpp b/examples/animation/padnavigator-ng/panel.cpp deleted file mode 100644 index e61be0e..0000000 --- a/examples/animation/padnavigator-ng/panel.cpp +++ /dev/null @@ -1,246 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "panel.h" -#include "roundrectitem.h" -#include "splashitem.h" -#include "ui_backside.h" - -#ifndef QT_NO_OPENGL -#include -#else -#endif -#include - -Panel::Panel(int width, int height) - : selectedIndex(0), - grid(width*height), - width(width), - height(height), - flipped(false), - flippingGroup(0), - rotationXanim(0), - rotationYanim(0) -{ - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setCacheMode(CacheBackground); - setViewportUpdateMode(FullViewportUpdate); - setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - setBackgroundBrush(QPixmap(":/images/blue_angle_swirl.jpg")); -#ifndef QT_NO_OPENGL - setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); -#endif - - QRectF bounds((-width / 2.0) * 150, (-height / 2.0) * 150, width * 150, height * 150); - - setScene(new QGraphicsScene(bounds, this)); - - baseItem = new RoundRectItem(bounds, QColor(226, 255, 92, 64)); - scene()->addItem(baseItem); - - QWidget *embed = new QWidget; - ui = new Ui_BackSide; - ui->setupUi(embed); - ui->hostName->setFocus(); - - backItem = new RoundRectItem(bounds, embed->palette().window(), embed); - backItem->setYRotation(180); - backItem->setParentItem(baseItem); - - selectionItem = new RoundRectItem(QRectF(-60, -60, 120, 120), Qt::gray); - selectionItem->setParentItem(baseItem); - selectionItem->setZValue(-1); - selectionItem->setPos(posForLocation(0)); - - int currentIndex = 0; - for (int y = 0; y < height; ++y) { - for (int x = 0; x < width; ++x) { - RoundRectItem *item = new RoundRectItem(QRectF(-54, -54, 108, 108), - QColor(214, 240, 110, 128)); - item->setPos(posForLocation(currentIndex)); - - item->setParentItem(baseItem); - item->setFlag(QGraphicsItem::ItemIsFocusable); - grid[currentIndex++] = item; - - switch (qrand() % 9) { - case 0: item->setPixmap(QPixmap(":/images/kontact_contacts.png")); break; - case 1: item->setPixmap(QPixmap(":/images/kontact_journal.png")); break; - case 2: item->setPixmap(QPixmap(":/images/kontact_notes.png")); break; - case 3: item->setPixmap(QPixmap(":/images/kopeteavailable.png")); break; - case 4: item->setPixmap(QPixmap(":/images/metacontact_online.png")); break; - case 5: item->setPixmap(QPixmap(":/images/minitools.png")); break; - case 6: item->setPixmap(QPixmap(":/images/kontact_journal.png")); break; - case 7: item->setPixmap(QPixmap(":/images/kontact_contacts.png")); break; - case 8: item->setPixmap(QPixmap(":/images/kopeteavailable.png")); break; - default: - break; - } - - connect(item, SIGNAL(activated()), this, SLOT(flip())); - } - } - - grid.first()->setFocus(); - - connect(backItem, SIGNAL(activated()), - this, SLOT(flip())); - - splash = new SplashItem; - splash->setZValue(5); - splash->setPos(-splash->rect().width() / 2, scene()->sceneRect().top()); - scene()->addItem(splash); - - splash->grabKeyboard(); - - //initialize the position - baseItem->setYRotation(selectionItem->x()/6.); - baseItem->setXRotation(selectionItem->y()/6.); - - setWindowTitle(tr("Pad Navigator Example")); -} - -Panel::~Panel() -{ -} - -void Panel::keyPressEvent(QKeyEvent *event) -{ - if (splash->isVisible() || event->key() == Qt::Key_Return || flipped) { - QGraphicsView::keyPressEvent(event); - return; - } - - selectedIndex = (selectedIndex + grid.count() + (event->key() == Qt::Key_Right) - (event->key() == Qt::Key_Left) - + width * ((event->key() == Qt::Key_Down) - (event->key() == Qt::Key_Up))) % grid.count(); - grid[selectedIndex]->setFocus(); - - const QPointF pos = posForLocation(selectedIndex); - - const double angleY = pos.x() / 6., - angleX = pos.y() / 6.; - - QAnimationGroup *group = new QParallelAnimationGroup(); - - QVariantAnimation *anim = new QPropertyAnimation(baseItem, "xRotation"); - anim->setEndValue(angleX); - anim->setDuration(150); - anim->setEasingCurve(QEasingCurve::OutInSine); - group->addAnimation(anim); - - anim = new QPropertyAnimation(baseItem, "yRotation"); - anim->setEndValue(angleY); - anim->setDuration(150); - anim->setEasingCurve(QEasingCurve::OutInSine); - group->addAnimation(anim); - - anim = new QPropertyAnimation(selectionItem, "pos"); - anim->setEndValue(pos); - anim->setDuration(150); - anim->setEasingCurve(QEasingCurve::Linear); - group->addAnimation(anim); - - group->start(QAbstractAnimation::DeleteWhenStopped); -} - -void Panel::resizeEvent(QResizeEvent *event) -{ - QGraphicsView::resizeEvent(event); - fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); -} - -void Panel::flip() -{ - grid[selectedIndex]->setFocus(); - - if (flippingGroup == 0) { - flippingGroup = new QParallelAnimationGroup(this); - - const qreal zoomOut = qreal(.75); - - //slight scaling down while flipping - QVariantAnimation *anim = new QPropertyAnimation(baseItem, "yScale"); - anim->setKeyValueAt(qreal(.5), zoomOut); - anim->setEndValue(1); - anim->setEasingCurve(QEasingCurve::OutInSine); - anim->setDuration(500); - flippingGroup->addAnimation(anim); - - anim = new QPropertyAnimation(baseItem, "xScale"); - anim->setKeyValueAt(qreal(.5), zoomOut); - anim->setEndValue(1); - anim->setEasingCurve(QEasingCurve::OutInSine); - anim->setDuration(500); - flippingGroup->addAnimation(anim); - - rotationXanim = new QPropertyAnimation(baseItem, "xRotation"); - rotationXanim->setEndValue(0); - rotationXanim->setDuration(500); - flippingGroup->addAnimation(rotationXanim); - - rotationYanim = new QPropertyAnimation(baseItem, "yRotation"); - rotationYanim->setEndValue(180); - rotationYanim->setDuration(500); - flippingGroup->addAnimation(rotationYanim); - } - - if (flippingGroup->currentTime() != 0 && flippingGroup->direction() == QAbstractAnimation::Forward) { - flippingGroup->setDirection(QAbstractAnimation::Backward); - } else { - flippingGroup->setDirection(QAbstractAnimation::Forward); - if (flippingGroup->currentTime() == 0) { - //we always make sure when it is at the beginning - rotationXanim->setStartValue(baseItem->xRotation()); - rotationYanim->setStartValue(baseItem->yRotation()); - } - } - flippingGroup->start(); - flipped = !flipped; -} - -QPointF Panel::posForLocation(int index) const -{ - const int x = index % width, - y = index / width; - return QPointF(x * 150, y * 150) - - QPointF((width - 1) * 75, (height - 1) * 75); -} diff --git a/examples/animation/padnavigator-ng/panel.h b/examples/animation/padnavigator-ng/panel.h deleted file mode 100644 index 9aca29d..0000000 --- a/examples/animation/padnavigator-ng/panel.h +++ /dev/null @@ -1,85 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include - -QT_BEGIN_NAMESPACE -class Ui_BackSide; -class QAnimationGroup; -class QPropertyAnimation; -QT_END_NAMESPACE; - -class RoundRectItem; - -class Panel : public QGraphicsView -{ - Q_OBJECT -public: - Panel(int width, int height); - ~Panel(); - -protected: - void keyPressEvent(QKeyEvent *event); - void resizeEvent(QResizeEvent *event); - -private Q_SLOTS: - void flip(); - -private: - QPointF posForLocation(int index) const; - - QGraphicsWidget *selectionItem; - QGraphicsWidget *baseItem; - RoundRectItem *backItem; - QGraphicsWidget *splash; - int selectedIndex; - - QVector grid; - - int width; - int height; - bool flipped; - Ui_BackSide *ui; - - QAnimationGroup *flippingGroup; - QPropertyAnimation *rotationXanim, *rotationYanim; -}; diff --git a/examples/animation/padnavigator-ng/roundrectitem.cpp b/examples/animation/padnavigator-ng/roundrectitem.cpp deleted file mode 100644 index 2ff216c..0000000 --- a/examples/animation/padnavigator-ng/roundrectitem.cpp +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "roundrectitem.h" - -#include - -RoundRectItem::RoundRectItem(const QRectF &rect, const QBrush &brush, QWidget *embeddedWidget) - : QGraphicsWidget(), - m_rect(rect), - brush(brush), - proxyWidget(0) -{ - if (embeddedWidget) { - proxyWidget = new QGraphicsProxyWidget(this); - proxyWidget->setFocusPolicy(Qt::StrongFocus); - proxyWidget->setWidget(embeddedWidget); - } -} - -void RoundRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - const bool widgetHidden = parentItem() == 0 || qAbs(static_cast(parentItem())->yRotation()) < 90; - - if (proxyWidget) { - if (widgetHidden) { - proxyWidget->hide(); - } else { - if (!proxyWidget->isVisible()) { - proxyWidget->setGeometry(boundingRect().adjusted(25, 25, -25, -25)); - proxyWidget->show(); - proxyWidget->setFocus(); - } - painter->setBrush(brush); - painter->setPen(QPen(Qt::black, 1)); - painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - painter->drawRoundRect(m_rect); - } - } else if (widgetHidden) { - painter->setPen(Qt::NoPen); - painter->setBrush(QColor(0, 0, 0, 64)); - painter->drawRoundRect(m_rect.translated(2, 2)); - - QLinearGradient gradient(m_rect.topLeft(), m_rect.bottomRight()); - const QColor col = brush.color(); - gradient.setColorAt(0, col); - gradient.setColorAt(1, col.dark(200)); - painter->setBrush(gradient); - painter->setPen(QPen(Qt::black, 1)); - painter->drawRoundRect(m_rect); - if (!pix.isNull()) { - painter->scale(qreal(1.95), qreal(1.95)); - painter->drawPixmap(-pix.width() / 2, -pix.height() / 2, pix); - } - } - -} - -QRectF RoundRectItem::boundingRect() const -{ - qreal penW = qreal(.5); - qreal shadowW = 2; - return m_rect.adjusted(-penW, -penW, penW + shadowW, penW + shadowW); -} - -void RoundRectItem::setPixmap(const QPixmap &pixmap) -{ - pix = pixmap; - if (scene() && isVisible()) - update(); -} - -void RoundRectItem::keyPressEvent(QKeyEvent *event) -{ - if (event->isAutoRepeat() || event->key() != Qt::Key_Return) { - QGraphicsWidget::keyPressEvent(event); - return; - } - - if (!proxyWidget) { - setXScale(qreal(.9)); - setYScale(qreal(.9)); - } - emit activated(); -} - -void RoundRectItem::keyReleaseEvent(QKeyEvent *event) -{ - if (event->isAutoRepeat() || event->key() != Qt::Key_Return) { - QGraphicsWidget::keyReleaseEvent(event); - return; - } - - if (!proxyWidget) { - setXScale(1); - setYScale(1); - } -} diff --git a/examples/animation/padnavigator-ng/roundrectitem.h b/examples/animation/padnavigator-ng/roundrectitem.h deleted file mode 100644 index 6a7bf4b..0000000 --- a/examples/animation/padnavigator-ng/roundrectitem.h +++ /dev/null @@ -1,73 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include - -QT_BEGIN_NAMESPACE -class QGraphicsProxyWidget; -QT_END_NAMESPACE; - -class RoundRectItem : public QGraphicsWidget -{ - Q_OBJECT -public: - RoundRectItem(const QRectF &rect, const QBrush &brush, QWidget *embeddedWidget = 0); - - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *); - QRectF boundingRect() const; - - void setPixmap(const QPixmap &pixmap); - -Q_SIGNALS: - void activated(); - -protected: - void keyPressEvent(QKeyEvent *event); - void keyReleaseEvent(QKeyEvent *event); - -private: - QRectF m_rect; - QBrush brush; - QPixmap pix; - QGraphicsProxyWidget *proxyWidget; -}; diff --git a/examples/animation/padnavigator-ng/splashitem.cpp b/examples/animation/padnavigator-ng/splashitem.cpp deleted file mode 100644 index 1264987..0000000 --- a/examples/animation/padnavigator-ng/splashitem.cpp +++ /dev/null @@ -1,85 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "splashitem.h" - -#include - -SplashItem::SplashItem(QGraphicsItem *parent) - : QGraphicsWidget(parent) -{ - - text = tr("Welcome to the Pad Navigator Example. You can use the" - " keyboard arrows to navigate the icons, and press enter" - " to activate an item. Please press any key to continue."); - resize(400, 175); -} - -void SplashItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - painter->setPen(QPen(Qt::black, 2)); - painter->setBrush(QColor(245, 245, 255, 220)); - painter->setClipRect(rect()); - painter->drawRoundRect(3, -100 + 3, 400 - 6, 250 - 6); - - QRectF textRect = rect().adjusted(10, 10, -10, -10); - int flags = Qt::AlignTop | Qt::AlignLeft | Qt::TextWordWrap; - - QFont font; - font.setPixelSize(18); - painter->setPen(Qt::black); - painter->setFont(font); - painter->drawText(textRect, flags, text); -} - -void SplashItem::keyPressEvent(QKeyEvent * /* event */) -{ - QVariantAnimation *anim = new QPropertyAnimation(this, "pos"); - anim->setEndValue(QPointF(x(), scene()->sceneRect().top() - rect().height())); - anim->setDuration(350); - anim->start(QAbstractAnimation::DeleteWhenStopped); - - anim = new QPropertyAnimation(this, "opacity"); - anim->setEndValue(0); - anim->start(QAbstractAnimation::DeleteWhenStopped); - - connect(anim, SIGNAL(finished()), SLOT(close())); -} diff --git a/examples/animation/padnavigator-ng/splashitem.h b/examples/animation/padnavigator-ng/splashitem.h deleted file mode 100644 index 7b4b8a9..0000000 --- a/examples/animation/padnavigator-ng/splashitem.h +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include - -class SplashItem : public QGraphicsWidget -{ - Q_OBJECT -public: - SplashItem(QGraphicsItem *parent = 0); - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - -protected: - void keyPressEvent(QKeyEvent *event); - -private: - QString text; -}; diff --git a/examples/graphicsview/padnavigator/images/artsfftscope.png b/examples/graphicsview/padnavigator/images/artsfftscope.png index 4db003f..756a1cf 100644 Binary files a/examples/graphicsview/padnavigator/images/artsfftscope.png and b/examples/graphicsview/padnavigator/images/artsfftscope.png differ diff --git a/examples/graphicsview/padnavigator/main.cpp b/examples/graphicsview/padnavigator/main.cpp index dc5ff0c..f7d6f90 100644 --- a/examples/graphicsview/padnavigator/main.cpp +++ b/examples/graphicsview/padnavigator/main.cpp @@ -40,10 +40,6 @@ ****************************************************************************/ #include -#ifndef QT_NO_OPENGL -# include -#endif - #include "panel.h" int main(int argc, char *argv[]) diff --git a/examples/graphicsview/padnavigator/panel.cpp b/examples/graphicsview/padnavigator/panel.cpp index 28a3cb4..c088fbc 100644 --- a/examples/graphicsview/padnavigator/panel.cpp +++ b/examples/graphicsview/padnavigator/panel.cpp @@ -50,15 +50,15 @@ #endif #include -#include - Panel::Panel(int width, int height) - : selectedX(0), - selectedY(0), + : selectedIndex(0), + grid(width*height), width(width), height(height), flipped(false), - flipLeft(true) + flippingGroup(0), + rotationXanim(0), + rotationYanim(0) { setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -72,12 +72,9 @@ Panel::Panel(int width, int height) #endif setMinimumSize(50, 50); - selectionTimeLine = new QTimeLine(150, this); - flipTimeLine = new QTimeLine(500, this); - QRectF bounds((-width / 2.0) * 150, (-height / 2.0) * 150, width * 150, height * 150); - scene = new QGraphicsScene(bounds, this); + QGraphicsScene *scene = new QGraphicsScene(bounds, this); scene->setItemIndexMethod(QGraphicsScene::NoIndex); setScene(scene); @@ -90,28 +87,24 @@ Panel::Panel(int width, int height) ui->hostName->setFocus(); backItem = new RoundRectItem(bounds, embed->palette().window(), embed); - backItem->setTransform(QTransform().rotate(180, Qt::YAxis)); + backItem->setYRotation(180); backItem->setParentItem(baseItem); selectionItem = new RoundRectItem(QRectF(-60, -60, 120, 120), Qt::gray); selectionItem->setParentItem(baseItem); selectionItem->setZValue(-1); - selectionItem->setPos(posForLocation(0, 0)); - startPos = selectionItem->pos(); + selectionItem->setPos(posForLocation(0)); - grid = new QGraphicsItem **[height]; - + int currentIndex = 0; for (int y = 0; y < height; ++y) { - grid[y] = new QGraphicsItem *[width]; - for (int x = 0; x < width; ++x) { RoundRectItem *item = new RoundRectItem(QRectF(-54, -54, 108, 108), QColor(214, 240, 110, 128)); - item->setPos(posForLocation(x, y)); + item->setPos(posForLocation(currentIndex)); item->setParentItem(baseItem); item->setFlag(QGraphicsItem::ItemIsFocusable); - grid[y][x] = item; + grid[currentIndex++] = item; switch (qrand() % 9) { case 0: item->setPixmap(QPixmap(":/images/kontact_contacts.png")); break; @@ -131,14 +124,10 @@ Panel::Panel(int width, int height) } } - grid[0][0]->setFocus(); + grid.first()->setFocus(); connect(backItem, SIGNAL(activated()), this, SLOT(flip())); - connect(selectionTimeLine, SIGNAL(valueChanged(qreal)), - this, SLOT(updateSelectionStep(qreal))); - connect(flipTimeLine, SIGNAL(valueChanged(qreal)), - this, SLOT(updateFlipStep(qreal))); splash = new SplashItem; splash->setZValue(5); @@ -147,16 +136,15 @@ Panel::Panel(int width, int height) splash->grabKeyboard(); - updateSelectionStep(0); + //initialize the position + baseItem->setYRotation(selectionItem->x()/6.); + baseItem->setXRotation(selectionItem->y()/6.); setWindowTitle(tr("Pad Navigator Example")); } Panel::~Panel() { - for (int y = 0; y < height; ++y) - delete [] grid[y]; - delete [] grid; } void Panel::keyPressEvent(QKeyEvent *event) @@ -166,73 +154,93 @@ void Panel::keyPressEvent(QKeyEvent *event) return; } - selectedX = (selectedX + width + (event->key() == Qt::Key_Right) - (event->key() == Qt::Key_Left)) % width; - selectedY = (selectedY + height + (event->key() == Qt::Key_Down) - (event->key() == Qt::Key_Up)) % height; - grid[selectedY][selectedX]->setFocus(); - - selectionTimeLine->stop(); - startPos = selectionItem->pos(); - endPos = posForLocation(selectedX, selectedY); - selectionTimeLine->start(); + selectedIndex = (selectedIndex + grid.count() + (event->key() == Qt::Key_Right) - (event->key() == Qt::Key_Left) + + width * ((event->key() == Qt::Key_Down) - (event->key() == Qt::Key_Up))) % grid.count(); + grid[selectedIndex]->setFocus(); + + const QPointF pos = posForLocation(selectedIndex); + + const double angleY = pos.x() / 6., + angleX = pos.y() / 6.; + + QAnimationGroup *group = new QParallelAnimationGroup(); + + QVariantAnimation *anim = new QPropertyAnimation(baseItem, "xRotation"); + anim->setEndValue(angleX); + anim->setDuration(150); + anim->setEasingCurve(QEasingCurve::OutInSine); + group->addAnimation(anim); + + anim = new QPropertyAnimation(baseItem, "yRotation"); + anim->setEndValue(angleY); + anim->setDuration(150); + anim->setEasingCurve(QEasingCurve::OutInSine); + group->addAnimation(anim); + + anim = new QPropertyAnimation(selectionItem, "pos"); + anim->setEndValue(pos); + anim->setDuration(150); + anim->setEasingCurve(QEasingCurve::Linear); + group->addAnimation(anim); + + group->start(QAbstractAnimation::DeleteWhenStopped); } void Panel::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); - fitInView(scene->sceneRect(), Qt::KeepAspectRatio); + fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); } -void Panel::updateSelectionStep(qreal val) +void Panel::flip() { - QPointF newPos(startPos.x() + (endPos - startPos).x() * val, - startPos.y() + (endPos - startPos).y() * val); - selectionItem->setPos(newPos); - - QTransform transform; - yrot = newPos.x() / 6.0; - xrot = newPos.y() / 6.0; - transform.rotate(newPos.x() / 6.0, Qt::YAxis); - transform.rotate(newPos.y() / 6.0, Qt::XAxis); - baseItem->setTransform(transform); -} + grid[selectedIndex]->setFocus(); + + if (flippingGroup == 0) { + flippingGroup = new QParallelAnimationGroup(this); + + const qreal zoomOut = qreal(.75); + + //slight scaling down while flipping + QVariantAnimation *anim = new QPropertyAnimation(baseItem, "yScale"); + anim->setKeyValueAt(qreal(.5), zoomOut); + anim->setEndValue(1); + anim->setEasingCurve(QEasingCurve::OutInSine); + anim->setDuration(500); + flippingGroup->addAnimation(anim); + + anim = new QPropertyAnimation(baseItem, "xScale"); + anim->setKeyValueAt(qreal(.5), zoomOut); + anim->setEndValue(1); + anim->setEasingCurve(QEasingCurve::OutInSine); + anim->setDuration(500); + flippingGroup->addAnimation(anim); + + rotationXanim = new QPropertyAnimation(baseItem, "xRotation"); + rotationXanim->setEndValue(0); + rotationXanim->setDuration(500); + flippingGroup->addAnimation(rotationXanim); + + rotationYanim = new QPropertyAnimation(baseItem, "yRotation"); + rotationYanim->setStartValue(0); + rotationYanim->setEndValue(180); + rotationYanim->setDuration(500); + flippingGroup->addAnimation(rotationYanim); + } -void Panel::updateFlipStep(qreal val) -{ - qreal finalxrot = xrot - xrot * val; - qreal finalyrot; - if (flipLeft) - finalyrot = yrot - yrot * val - 180 * val; + if (flippingGroup->currentTime() != 0 && flippingGroup->direction() == QAbstractAnimation::Forward) + flippingGroup->setDirection(QAbstractAnimation::Backward); else - finalyrot = yrot - yrot * val + 180 * val; - QTransform transform; - transform.rotate(finalyrot, Qt::YAxis); - transform.rotate(finalxrot, Qt::XAxis); - qreal scale = 1 - sin(3.14 * val) * 0.3; - transform.scale(scale, scale); - baseItem->setTransform(transform); - if (val == 0) - grid[selectedY][selectedX]->setFocus(); -} + flippingGroup->setDirection(QAbstractAnimation::Forward); -void Panel::flip() -{ - if (flipTimeLine->state() == QTimeLine::Running) - return; - - if (flipTimeLine->currentValue() == 0) { - flipTimeLine->setDirection(QTimeLine::Forward); - flipTimeLine->start(); - flipped = true; - flipLeft = selectionItem->pos().x() < 0; - } else { - flipTimeLine->setDirection(QTimeLine::Backward); - flipTimeLine->start(); - flipped = false; - } + flippingGroup->start(); + flipped = !flipped; } -QPointF Panel::posForLocation(int x, int y) const +QPointF Panel::posForLocation(int index) const { + const int x = index % width, + y = index / width; return QPointF(x * 150, y * 150) - QPointF((width - 1) * 75, (height - 1) * 75); } diff --git a/examples/graphicsview/padnavigator/panel.h b/examples/graphicsview/padnavigator/panel.h index 03876b7..cc03530 100644 --- a/examples/graphicsview/padnavigator/panel.h +++ b/examples/graphicsview/padnavigator/panel.h @@ -40,10 +40,12 @@ ****************************************************************************/ #include +#include QT_BEGIN_NAMESPACE -class QTimeLine; class Ui_BackSide; +class QAnimationGroup; +class QPropertyAnimation; QT_END_NAMESPACE; class RoundRectItem; @@ -60,33 +62,24 @@ protected: void resizeEvent(QResizeEvent *event); private Q_SLOTS: - void updateSelectionStep(qreal val); - void updateFlipStep(qreal val); void flip(); private: - QPointF posForLocation(int x, int y) const; + QPointF posForLocation(int index) const; - QGraphicsScene *scene; - RoundRectItem *selectionItem; - RoundRectItem *baseItem; + QGraphicsWidget *selectionItem; + QGraphicsWidget *baseItem; RoundRectItem *backItem; QGraphicsWidget *splash; - QTimeLine *selectionTimeLine; - QTimeLine *flipTimeLine; - int selectedX, selectedY; + int selectedIndex; - QGraphicsItem ***grid; + QVector grid; - QPointF startPos; - QPointF endPos; - qreal xrot, yrot; - qreal xrot2, yrot2; - int width; int height; bool flipped; - bool flipLeft; - Ui_BackSide *ui; + + QAnimationGroup *flippingGroup; + QPropertyAnimation *rotationXanim, *rotationYanim; }; diff --git a/examples/graphicsview/padnavigator/roundrectitem.cpp b/examples/graphicsview/padnavigator/roundrectitem.cpp index c5dc35d..ec91966 100644 --- a/examples/graphicsview/padnavigator/roundrectitem.cpp +++ b/examples/graphicsview/padnavigator/roundrectitem.cpp @@ -44,72 +44,61 @@ #include RoundRectItem::RoundRectItem(const QRectF &rect, const QBrush &brush, QWidget *embeddedWidget) - : QGraphicsRectItem(rect), + : QGraphicsWidget(), + m_rect(rect), brush(brush), - timeLine(75), - lastVal(0), - opa(1), proxyWidget(0) { - connect(&timeLine, SIGNAL(valueChanged(qreal)), - this, SLOT(updateValue(qreal))); - if (embeddedWidget) { proxyWidget = new QGraphicsProxyWidget(this); proxyWidget->setFocusPolicy(Qt::StrongFocus); proxyWidget->setWidget(embeddedWidget); - proxyWidget->setGeometry(boundingRect().adjusted(25, 25, -25, -25)); } } void RoundRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { - QTransform x = painter->worldTransform(); - - QLineF unit = x.map(QLineF(0, 0, 1, 1)); - if (unit.p1().x() > unit.p2().x() || unit.p1().y() > unit.p2().y()) { - if (proxyWidget && proxyWidget->isVisible()) { + const bool widgetHidden = parentItem() == 0 || qAbs(static_cast(parentItem())->yRotation()) < 90; + + if (proxyWidget) { + if (widgetHidden) { proxyWidget->hide(); - proxyWidget->setGeometry(rect()); + } else { + if (!proxyWidget->isVisible()) { + proxyWidget->setGeometry(boundingRect().adjusted(25, 25, -25, -25)); + proxyWidget->show(); + proxyWidget->setFocus(); + } + painter->setBrush(brush); + painter->setPen(QPen(Qt::black, 1)); + painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + painter->drawRoundRect(m_rect); } - return; - } - - if (proxyWidget && !proxyWidget->isVisible()) { - proxyWidget->show(); - proxyWidget->setFocus(); - } - if (proxyWidget && proxyWidget->pos() != QPoint()) - proxyWidget->setGeometry(boundingRect().adjusted(25, 25, -25, -25)); - - painter->setOpacity(opacity()); - painter->setPen(Qt::NoPen); - painter->setBrush(QColor(0, 0, 0, 64)); - painter->drawRoundRect(rect().translated(2, 2)); + } else if (widgetHidden) { + painter->setPen(Qt::NoPen); + painter->setBrush(QColor(0, 0, 0, 64)); + painter->drawRoundRect(m_rect.translated(2, 2)); - if (!proxyWidget) { - QLinearGradient gradient(rect().topLeft(), rect().bottomRight()); + QLinearGradient gradient(m_rect.topLeft(), m_rect.bottomRight()); const QColor col = brush.color(); gradient.setColorAt(0, col); - gradient.setColorAt(1, col.dark(int(200 + lastVal * 50))); + gradient.setColorAt(1, col.dark(200)); painter->setBrush(gradient); - } else { - painter->setBrush(brush); + painter->setPen(QPen(Qt::black, 1)); + painter->drawRoundRect(m_rect); + if (!pix.isNull()) { + painter->scale(qreal(1.95), qreal(1.95)); + painter->drawPixmap(-pix.width() / 2, -pix.height() / 2, pix); + } } - painter->setPen(QPen(Qt::black, 1)); - painter->drawRoundRect(rect()); - if (!pix.isNull()) { - painter->scale(1.95, 1.95); - painter->drawPixmap(-pix.width() / 2, -pix.height() / 2, pix);; - } } QRectF RoundRectItem::boundingRect() const { - qreal penW = 0.5; - qreal shadowW = 2.0; - return rect().adjusted(-penW, -penW, penW + shadowW, penW + shadowW); + qreal penW = qreal(.5); + qreal shadowW = 2; + return m_rect.adjusted(-penW, -penW, penW + shadowW, penW + shadowW); } void RoundRectItem::setPixmap(const QPixmap &pixmap) @@ -119,46 +108,29 @@ void RoundRectItem::setPixmap(const QPixmap &pixmap) update(); } -qreal RoundRectItem::opacity() const -{ - RoundRectItem *parent = parentItem() ? (RoundRectItem *)parentItem() : 0; - return opa + (parent ? parent->opacity() : 0); -} - -void RoundRectItem::setOpacity(qreal opacity) -{ - opa = opacity; - update(); -} - void RoundRectItem::keyPressEvent(QKeyEvent *event) { - if (event->isAutoRepeat() || event->key() != Qt::Key_Return - || (timeLine.state() == QTimeLine::Running && timeLine.direction() == QTimeLine::Forward)) { - QGraphicsRectItem::keyPressEvent(event); + if (event->isAutoRepeat() || event->key() != Qt::Key_Return) { + QGraphicsWidget::keyPressEvent(event); return; } - timeLine.stop(); - timeLine.setDirection(QTimeLine::Forward); - timeLine.start(); + if (!proxyWidget) { + setXScale(qreal(.9)); + setYScale(qreal(.9)); + } emit activated(); } void RoundRectItem::keyReleaseEvent(QKeyEvent *event) { - if (event->key() != Qt::Key_Return) { - QGraphicsRectItem::keyReleaseEvent(event); + if (event->isAutoRepeat() || event->key() != Qt::Key_Return) { + QGraphicsWidget::keyReleaseEvent(event); return; } - timeLine.stop(); - timeLine.setDirection(QTimeLine::Backward); - timeLine.start(); -} -void RoundRectItem::updateValue(qreal value) -{ - lastVal = value; - if (!proxyWidget) - setTransform(QTransform().scale(1 - value / 10.0, 1 - value / 10.0)); + if (!proxyWidget) { + setXScale(1); + setYScale(1); + } } diff --git a/examples/graphicsview/padnavigator/roundrectitem.h b/examples/graphicsview/padnavigator/roundrectitem.h index 33e33d7..b0d44dd 100644 --- a/examples/graphicsview/padnavigator/roundrectitem.h +++ b/examples/graphicsview/padnavigator/roundrectitem.h @@ -40,15 +40,14 @@ ****************************************************************************/ #include -#include -#include #include +#include QT_BEGIN_NAMESPACE class QGraphicsProxyWidget; QT_END_NAMESPACE; -class RoundRectItem : public QObject, public QGraphicsRectItem +class RoundRectItem : public QGraphicsWidget { Q_OBJECT public: @@ -59,9 +58,6 @@ public: void setPixmap(const QPixmap &pixmap); - qreal opacity() const; - void setOpacity(qreal opacity); - Q_SIGNALS: void activated(); @@ -69,15 +65,9 @@ protected: void keyPressEvent(QKeyEvent *event); void keyReleaseEvent(QKeyEvent *event); -private slots: - void updateValue(qreal value); - private: + QRectF m_rect; QBrush brush; QPixmap pix; - QTimeLine timeLine; - qreal lastVal; - qreal opa; - QGraphicsProxyWidget *proxyWidget; }; diff --git a/examples/graphicsview/padnavigator/splashitem.cpp b/examples/graphicsview/padnavigator/splashitem.cpp index 2a374bf..a83d4d5 100644 --- a/examples/graphicsview/padnavigator/splashitem.cpp +++ b/examples/graphicsview/padnavigator/splashitem.cpp @@ -46,12 +46,6 @@ SplashItem::SplashItem(QGraphicsItem *parent) : QGraphicsWidget(parent) { - opacity = 1.0; - - - timeLine = new QTimeLine(350); - timeLine->setCurveShape(QTimeLine::EaseInCurve); - connect(timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(setValue(qreal))); text = tr("Welcome to the Pad Navigator Example. You can use the" " keyboard arrows to navigate the icons, and press enter" @@ -61,7 +55,6 @@ SplashItem::SplashItem(QGraphicsItem *parent) void SplashItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { - painter->setOpacity(opacity); painter->setPen(QPen(Qt::black, 2)); painter->setBrush(QColor(245, 245, 255, 220)); painter->setClipRect(rect()); @@ -79,14 +72,14 @@ void SplashItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWid void SplashItem::keyPressEvent(QKeyEvent * /* event */) { - if (timeLine->state() == QTimeLine::NotRunning) - timeLine->start(); -} + QVariantAnimation *anim = new QPropertyAnimation(this, "pos"); + anim->setEndValue(QPointF(x(), scene()->sceneRect().top() - rect().height())); + anim->setDuration(350); + anim->start(QAbstractAnimation::DeleteWhenStopped); -void SplashItem::setValue(qreal value) -{ - opacity = 1 - value; - setPos(x(), scene()->sceneRect().top() - rect().height() * value); - if (value == 1) - hide(); + anim = new QPropertyAnimation(this, "opacity"); + anim->setEndValue(0); + anim->start(QAbstractAnimation::DeleteWhenStopped); + + connect(anim, SIGNAL(finished()), SLOT(close())); } diff --git a/examples/graphicsview/padnavigator/splashitem.h b/examples/graphicsview/padnavigator/splashitem.h index 982bbe2..e2655ec 100644 --- a/examples/graphicsview/padnavigator/splashitem.h +++ b/examples/graphicsview/padnavigator/splashitem.h @@ -40,7 +40,6 @@ ****************************************************************************/ #include -#include #include class SplashItem : public QGraphicsWidget @@ -53,11 +52,6 @@ public: protected: void keyPressEvent(QKeyEvent *event); -private Q_SLOTS: - void setValue(qreal value); - private: - QTimeLine *timeLine; QString text; - qreal opacity; }; -- cgit v0.12 From bdbe84f8a8dbb50873e26829ee8a5127e21a0161 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 20 May 2009 17:18:32 +0200 Subject: Revert "QVariant has changed to use some QAtomic API which was missing" This reverts commit 9afa9ce3c0423e773e88d5c586595353815ac341. --- src/corelib/arch/qatomic_bootstrap.h | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/corelib/arch/qatomic_bootstrap.h b/src/corelib/arch/qatomic_bootstrap.h index af76903..7584b84 100644 --- a/src/corelib/arch/qatomic_bootstrap.h +++ b/src/corelib/arch/qatomic_bootstrap.h @@ -92,20 +92,6 @@ Q_INLINE_TEMPLATE bool QBasicAtomicPointer::testAndSetOrdered(T *expectedValu return false; } -template -Q_INLINE_TEMPLATE T *QBasicAtomicPointer::fetchAndStoreRelaxed(T *newValue) -{ - T *currentValue = _q_value; - _q_value = newValue; - return currentValue; -} - -template -Q_INLINE_TEMPLATE bool QBasicAtomicPointer::testAndSetRelaxed(T *expectedValue, T *newValue) -{ - return testAndSetOrdered(expectedValue, newValue); -} - QT_END_NAMESPACE QT_END_HEADER -- cgit v0.12 From bbd7c13d0cf9d99413f2bea9a3acfba848e3520e Mon Sep 17 00:00:00 2001 From: David Boddie Date: Wed, 20 May 2009 18:22:17 +0200 Subject: Doc: Added a small example/test case for sequential animations. Reviewed-by: Trust Me --- doc/src/snippets/animation/sequential/icons.qrc | 6 +++ .../snippets/animation/sequential/icons/left.png | Bin 0 -> 413 bytes .../snippets/animation/sequential/icons/right.png | Bin 0 -> 414 bytes doc/src/snippets/animation/sequential/main.cpp | 50 +++++++++++++++++++++ .../snippets/animation/sequential/sequential.pro | 4 ++ doc/src/snippets/animation/sequential/tracer.cpp | 25 +++++++++++ doc/src/snippets/animation/sequential/tracer.h | 23 ++++++++++ 7 files changed, 108 insertions(+) create mode 100644 doc/src/snippets/animation/sequential/icons.qrc create mode 100644 doc/src/snippets/animation/sequential/icons/left.png create mode 100644 doc/src/snippets/animation/sequential/icons/right.png create mode 100644 doc/src/snippets/animation/sequential/main.cpp create mode 100644 doc/src/snippets/animation/sequential/sequential.pro create mode 100644 doc/src/snippets/animation/sequential/tracer.cpp create mode 100644 doc/src/snippets/animation/sequential/tracer.h diff --git a/doc/src/snippets/animation/sequential/icons.qrc b/doc/src/snippets/animation/sequential/icons.qrc new file mode 100644 index 0000000..d55f797 --- /dev/null +++ b/doc/src/snippets/animation/sequential/icons.qrc @@ -0,0 +1,6 @@ + + + icons/left.png + icons/right.png + + diff --git a/doc/src/snippets/animation/sequential/icons/left.png b/doc/src/snippets/animation/sequential/icons/left.png new file mode 100644 index 0000000..5dd8da0 Binary files /dev/null and b/doc/src/snippets/animation/sequential/icons/left.png differ diff --git a/doc/src/snippets/animation/sequential/icons/right.png b/doc/src/snippets/animation/sequential/icons/right.png new file mode 100644 index 0000000..ac61326 Binary files /dev/null and b/doc/src/snippets/animation/sequential/icons/right.png differ diff --git a/doc/src/snippets/animation/sequential/main.cpp b/doc/src/snippets/animation/sequential/main.cpp new file mode 100644 index 0000000..aff8f29 --- /dev/null +++ b/doc/src/snippets/animation/sequential/main.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include "tracer.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QWidget window; + window.resize(720, 96); + window.show(); + + QLabel *label1 = new QLabel(&window); + label1->setPixmap(QPixmap(":/icons/left.png")); + label1->move(16, 16); + label1->show(); + + QLabel *label2 = new QLabel(&window); + label2->setPixmap(QPixmap(":/icons/right.png")); + label2->move(320, 16); + label2->show(); + + QPropertyAnimation *anim1 = new QPropertyAnimation(label1, "pos"); + anim1->setDuration(2500); + anim1->setStartValue(QPoint(16, 16)); + anim1->setEndValue(QPoint(320, 16)); + + QPropertyAnimation *anim2 = new QPropertyAnimation(label2, "pos"); + anim2->setDuration(2500); + anim2->setStartValue(QPoint(320, 16)); + anim2->setEndValue(QPoint(640, 16)); + + QSequentialAnimationGroup group; + group.addAnimation(anim1); + group.addAnimation(anim2); + + Tracer tracer(&window); + + QObject::connect(anim1, SIGNAL(valueChanged(QVariant)), + &tracer, SLOT(recordValue(QVariant))); + QObject::connect(anim2, SIGNAL(valueChanged(QVariant)), + &tracer, SLOT(recordValue(QVariant))); + QObject::connect(anim1, SIGNAL(finished()), &tracer, SLOT(checkValue())); + QObject::connect(anim2, SIGNAL(finished()), &tracer, SLOT(checkValue())); + + group.start(); + return app.exec(); +} diff --git a/doc/src/snippets/animation/sequential/sequential.pro b/doc/src/snippets/animation/sequential/sequential.pro new file mode 100644 index 0000000..fcf017f --- /dev/null +++ b/doc/src/snippets/animation/sequential/sequential.pro @@ -0,0 +1,4 @@ +HEADERS = tracer.h +RESOURCES = icons.qrc +SOURCES = main.cpp \ + tracer.cpp diff --git a/doc/src/snippets/animation/sequential/tracer.cpp b/doc/src/snippets/animation/sequential/tracer.cpp new file mode 100644 index 0000000..49bd51e --- /dev/null +++ b/doc/src/snippets/animation/sequential/tracer.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include "tracer.h" + +Tracer::Tracer(QObject *parent) + : QObject(parent) +{ +} + +void Tracer::checkValue() +{ + QAbstractAnimation *animation = static_cast(sender()); + if (time != animation->duration()) { + qDebug() << "Animation's last recorded time" << time; + qDebug() << "Expected" << animation->duration(); + } +} + +void Tracer::recordValue(const QVariant &value) +{ + QAbstractAnimation *animation = static_cast(sender()); + this->value = value; + time = animation->currentTime(); +} diff --git a/doc/src/snippets/animation/sequential/tracer.h b/doc/src/snippets/animation/sequential/tracer.h new file mode 100644 index 0000000..1adb018 --- /dev/null +++ b/doc/src/snippets/animation/sequential/tracer.h @@ -0,0 +1,23 @@ +#ifndef TRACER_H +#define TRACER_H + +#include +#include + +class Tracer : public QObject +{ + Q_OBJECT + +public: + Tracer(QObject *parent = 0); + +public slots: + void checkValue(); + void recordValue(const QVariant &value); + +private: + QVariant value; + int time; +}; + +#endif -- cgit v0.12 From 9e5daecead75e1c7a77679a04a14cee9fd616215 Mon Sep 17 00:00:00 2001 From: Thomas Sondergaard Date: Wed, 20 May 2009 21:22:00 +0200 Subject: Danish translations --- translations/assistant_da.ts | 1134 ++++++++ translations/qt_da.ts | 6317 ++++++++++++++++++++++++++++++++++++++++++ translations/qt_help_da.ts | 354 +++ 3 files changed, 7805 insertions(+) create mode 100644 translations/assistant_da.ts create mode 100644 translations/qt_da.ts create mode 100644 translations/qt_help_da.ts diff --git a/translations/assistant_da.ts b/translations/assistant_da.ts new file mode 100644 index 0000000..d039248 --- /dev/null +++ b/translations/assistant_da.ts @@ -0,0 +1,1134 @@ + + + + + + AboutDialog + + + &Close + &Luk + + + + BookmarkDialog + + + + + + + Bookmarks + Favoritter + + + + Add Bookmark + Føj til Favoritter + + + + Bookmark: + Favorit: + + + + Add in Folder: + Føj til mappen: + + + + + + + + + + New Folder + Ny mappe + + + + Delete Folder + Slet mappe + + + + Rename Folder + Omdøb mappe + + + + BookmarkManager + + + Bookmarks + Favoritter + + + + Remove + Fjern + + + You are going to delete a Folder, this will also<br>remove it's content. Are you sure to continue? + Ved at slette denne mappe fjernes hele mappens<br>indhold. Ønsker du alligevel at slette? + + + + + New Folder + Ny mappe + + + + You are about to delete a folder which means that its content<br>will also be removed. Do you want to continue? + Ved at slette denne mappe fjernes hele mappens indhold.<br>Ønsker du alligevel at slette? + + + + BookmarkWidget + + + Remove + Fjern + + + + Delete Folder + Slet mappe + + + + Rename Folder + Omdøb mappe + + + + Show Bookmark + Vis favorit + + + + Show Bookmark in New Tab + Vis favorit pÃ¥ ny fane + + + + Delete Bookmark + Slet favorit + + + + Rename Bookmark + Omdøb favorit + + + + Search for: + Søg efter: + + + + Add + Tilføj + + + + CentralWidget + + + Add new page + Tilføj ny side + + + + Close current page + Luk nuværende side + + + + Print Document + Udskriv dokument + + + + + unknown + ukendt + + + + Add New Page + Tilføj ny side + + + + Close This Page + Luk denne side + + + + Close Other Pages + Luk de andre sider + + + + Add Bookmark for this Page... + Føj denne side til Favoritter... + + + + Search + Søg + + + + ContentWindow + + + Open Link + Ã…bn link + + + + Open Link in New Tab + Ã…bn link pÃ¥ ny fane + + + + FilterNameDialogClass + + + FilterNameDialog + FilterNavnDialog + + + + Filter Name: + Filternavn: + + + + FindWidget + + + Previous + Forrige + + + + Next + Næste + + + + Case Sensitive + Der skelnes mellem store og smÃ¥ bogstaver + + + + Whole words + Hele ord + + + + <img src="%1">&nbsp;Search wrapped + <img src=":/trolltech/assistant/images/wrap.png">&nbsp;Search wrapped + <img src="%1">&nbsp;Søgning startet forfra + + + + FontPanel + + + Font + Skrifttype + + + + &Writing system + &Skrivesystem + + + + &Family + &Familie + + + + &Style + &Stil + + + + &Point size + &Punktstørrelse + + + + HelpViewer + + + Help + Hjælp + + + + OK + + + + + <title>Error 404...</title><div align="center"><br><br><h1>The page could not be found</h1><br><h3>'%1'</h3></div> + <title>Fejl 404...</title><div align="center"><br><br><h1>Siden blev ikke fundet</h1><br><h3>'%1'</h3></div> + + + + Copy &Link Location + Kopiér &linkets placering + + + + Open Link in New Tab Ctrl+LMB + Ã…bn link pÃ¥ ny fane Ctrl+LMB + + + + Open Link in New Tab + Ã…bn link pÃ¥ ny fane + + + + <b>Page not found:<p>%1.</p></b> + <b>Kunne ikke finde siden:<p>%1.</p></b> + + + + Unable to launch external application. + + Kunne ikke starte ekstern applikation. + + + + + IndexWindow + + + &Look for: + &Søg efter: + + + + Open Link + Ã…bn link + + + + Open Link in New Tab + Ã…bn link pÃ¥ ny fane + + + + InstallDialog + + + + Install Documentation + Installér dokumentation + + + + Downloading documentation info... + Downloader dokumentationsinformation... + + + + Download canceled. + Download blev annulleret. + + + + + + Done. + Færdig. + + + + The file %1 already exists. Do you want to overwrite it? + Filen %1 findes allerede. Ønsker du at overskrive? + + + + Unable to save the file %1: %2. + Kunne ikke gemme filen %1: %2. + + + + Downloading %1... + Downloader %1... + + + + + + Download failed: %1. + Download mislykkedes: %1. + + + + Documentation info file is corrupt! + Dokumentationsinformationsfilen er ødelagt! + + + + Download failed: Downloaded file is corrupted. + Download mislykkedes: Den downloadede fil er ødelagt. + + + + Installing documentation %1... + Installerer dokumentation %1... + + + + Error while installing documentation: +%1 + Der opstod fejl under installation af dokumentation: +%1 + + + + Available Documentation: + Tilgængeligt dokumentation: + + + + Install + Installér + + + + Cancel + Annuller + + + + Close + Luk + + + + Installation Path: + Installationssti: + + + + ... + + + + + MainWindow + + + + Index + Indeks + + + + + Contents + Indhold + + + + + Bookmarks + Favoritter + + + + + Search + Søg + + + + + + Qt Assistant + + + + + + Unfiltered + Ufiltreret + + + Page Set&up... + Side&opsætning... + + + Print Preview... + Vis udskrift... + + + &Print... + &Udskriv... + + + CTRL+P + Ctrl+U + + + + New &Tab + &Ny Fane + + + CTRL+T + Ctrl+N + + + + &Close Tab + &Luk fane + + + CTRL+W + Ctrl+L + + + + &Quit + &Afslut + + + CTRL+Q + Ctrl+A + + + &Copy selected Text + &Kopiér markeret tekst + + + Ctrl+C + Ctrl+K + + + + &Find in Text... + &Find i tekst... + + + + Ctrl+F + + + + + Find &Next + Find N&æste + + + + F3 + + + + + Find &Previous + Find fo&rrige + + + + Shift+F3 + + + + + Preferences... + Indstillinger... + + + + Zoom &in + Zoom &ind + + + + Ctrl++ + + + + + Zoom &out + Zoom u&d + + + + Ctrl+- + + + + + Normal &Size + Normal &størrelse + + + + Ctrl+0 + + + + + &Home + &Hjem + + + + Ctrl+Home + + + + + &Back + &Tilbage + + + + &Forward + Fr&em + + + Sync with Table of Contents + Synkronisér med Indholdsfortegnelse + + + + Next Page + Næste side + + + + Ctrl+Alt+Right + Ctrl+Alt+Højre + + + + Previous Page + Forrige side + + + + Ctrl+Alt+Left + Ctrl+Alt+Venstre + + + + Add Bookmark... + Føj til Favoritter... + + + + About... + Om... + + + + Navigation Toolbar + Navigationsværktøjslinie + + + + Toolbars + Værktøjslinier + + + + Filter Toolbar + Filtrer værktøjslinie + + + + Filtered by: + Filtreret efter: + + + + Address Toolbar + Adresseværktøjslinie + + + + Address: + Adresse: + + + + Could not find the associated content item. + Det tilhørende indholdselement kunne ikke findes. + + + + Open Source Edition + + + + + This version of Qt Assistant is part of the Qt Open Source Edition, for use in the development of Open Source applications. Qt is a comprehensive C++ framework for cross-platform application development. + Denne version af Qt Assistant er en del af Qt Open Source Edition til brug med henblik pÃ¥ udvikling af Open Source-applikationer. Qt er et omfattende C++ framework for cross-platform applikationsudvikling. + + + + This program is licensed to you under the terms of the Qt Commercial License Agreement. For details, see the file LICENSE that came with this software distribution. + Dette program er omfattet af Qt Commercial License Agreement. Se filen LICENCE, der var vedlagt denne software-distribution, for yderligere detaljer. + + + + About %1 + Om %1 + + + + Updating search index + Opdaterer søgeindeks + + + + Looking for Qt Documentation... + Søger efter Qt-dokumentation... + + + + &Window + &Vindue + + + + Minimize + Minimér + + + + Ctrl+M + Ctrl+M + + + + Zoom + + + + + &File + &Filer + + + + &Edit + &Redigér + + + + &View + &Vis + + + + &Go + &GÃ¥ til + + + + &Bookmarks + F&avoritter + + + + &Help + &Hjælp + + + + You need a commercial Qt license for development of proprietary (closed source) applications. Please see <a href="http://trolltech.com/company/about/businessmodel">http://trolltech.com/company/about/businessmodel</a> for an overview of Qt licensing. + + + + ALT+O + Alt+F + + + CTRL+D + Ctrl+Ø + + + Ctrl+P + Ctrl+U + + + + Ctrl+T + Ctrl+N + + + + Ctrl+W + Ctrl+L + + + + Ctrl+Q + Ctrl+A + + + + Alt+C + Alt+L + + + + Alt+I + + + + + Alt+O + Alt+F + + + + Alt+S + + + + + Ctrl+D + Ctrl+Ø + + + + PreferencesDialog + + + + + Add Documentation + Tilføj dokumentation + + + + Qt Compressed Help Files (*.qch) + Qt komprimeret hjælpefil (*.qch) + + + + The specified file is not a valid Qt Help File! + Den anførte fil er ikke en gyldig Qt hjælpefil! + + + + The namespace %1 is already registered! + Navnerummet %1 er allerede registreret! + + + + Use custom settings + Benyt brugerdefineret opsætning + + + + PreferencesDialogClass + + + Preferences + Indstillinger + + + + Fonts + Skrifttyper + + + + Font settings: + Indstillinger for skrifttype: + + + + Browser + + + + + Application + Applikation + + + + Filters + Filtre + + + + Filter: + Filter: + + + + Attributes: + Attributter: + + + + 1 + + + + + Add + Tilføj + + + + + Remove + Fjern + + + + Documentation + Dokumentation + + + + Registered Documentation: + Registreret dokumentation: + + + + Add... + Tilføj... + + + + Network + Netværk + + + + Use Http Proxy + Benyt Http Proxy + + + + Http Proxy: + + + + + Port: + + + + + QObject + + + The specified collection file does not exist! + Den angivne hjælpesamling findes ikke! + + + + Missing collection file! + Hjælpesamling mangler! + + + + Invalid URL! + Ugyldig URL! + + + + Missing URL! + URL mangler! + + + + + + Unknown widget: %1 + Ukendt widget: %1 + + + + + + Missing widget! + Widget mangler! + + + + + The specified Qt help file does not exist! + Den angivne Qt-hjælpefil findes ikke! + + + + + Missing help file! + Hjælpefilen mangler! + + + + Unknown option: %1 + Ukendt parameter: %1 + + + + + Qt Assistant + + + + + Could not register documentation file +%1 + +Reason: +%2 + Kunne ikke registrere dokumentationsfil +%1 + +Ã…rsag: +%2 + + + + Documentation successfully registered. + Dokumentationen blev registreret. + + + + Could not unregister documentation file +%1 + +Reason: +%2 + Kunne ikke afregistrere dokumentationsfil +%1 + +Ã…rsag: +%2 + + + + Documentation successfully unregistered. + Dokumentationen blev afregistreret. + + + + The specified collection file could not be read! + Den angivne hjælpesamling kunne ikke læses! + + + + + Bookmark + Favorit + + + + QtDocInstaller + + + The file %1 could not be registered successfully! + +Reason: %2 + Filen %1 kunne ikke registreres! + +Ã…rsag: %2 + + + + RemoteControl + + + Debugging Remote Control + + + + + Received Command: %1 %2 + Modtaget kommando: %1 %2 + + + + SearchWidget + + + &Copy + &Kopiér + + + + Copy &Link Location + Kopiér &linkets placering + + + + + Open Link in New Tab + Ã…bn link pÃ¥ ny fane + + + + Select All + Markér alt + + + + Open Link + Ã…bn link + + + + TopicChooser + + + Choose a topic for <b>%1</b>: + Vælg et emne for <b>%1</b>: + + + + Choose Topic + Vælg emne + + + + &Topics + &Emner + + + + &Display + &Vis + + + + &Close + &Luk + + + TopicChooser + Emnevælger + + + unnamed + unavngivet + + + diff --git a/translations/qt_da.ts b/translations/qt_da.ts new file mode 100644 index 0000000..9350687 --- /dev/null +++ b/translations/qt_da.ts @@ -0,0 +1,6317 @@ + + + + + AudioOutput + + + <html>The audio playback device <b>%1</b> does not work.<br/>Falling back to <b>%2</b>.</html> + <html>Audio-playback-enheden<b>%1</b> virker ikke.<br/>Falder tilbage til <b>%2</b>.</html> + + + <html>Switching to the audio playback device <b>%1</b><br/>which just became available and has higher preference.</html> + <html>Skifter til audio-playback-enheden, <b>%1</b><br/>der lige er blevet tilgængeligt og har en højere præference.</html> + + + Revert back to device '%1' + GÃ¥ tilbage til enheden '%1' + + + + CloseButton + + + Close Tab + Luk fane + + + + Phonon:: + + + Notifications + Meddelelser + + + Music + Musik + + + Video + + + + Communication + Kommunikation + + + Games + Spil + + + Accessibility + Tilgængelighed + + + + Phonon::Gstreamer::Backend + + + Warning: You do not seem to have the package gstreamer0.10-plugins-good installed. + Some video features have been disabled. + Advarsel: Det ser ikke ud til, at gstreamer0.10-plugins-good pakken er installeret. + Nogle videofunktioner er deaktiveret. + + + Warning: You do not seem to have the base GStreamer plugins installed. + All audio and video support has been disabled + Advarsel: Det ser ikke ud til, at base GStreamer plugins er installeret. + Al audio- og videosupport er deaktiveret + + + + Phonon::Gstreamer::MediaObject + + + Cannot start playback. + +Check your Gstreamer installation and make sure you +have libgstreamer-plugins-base installed. + Kan ikke starte playback. + +Tjek Gstreamer-installationen og kontrollér, at +libgstreamer-plugins-base er installeret. + + + A required codec is missing. You need to install the following codec(s) to play this content: %0 + Der mangler et codec. Følgende codecs skal installeres for at afspille dette indhold: %0 + + + Could not open media source. + Kunne ikke Ã¥bne mediekilden. + + + Invalid source type. + Ugyldig kilde. + + + Could not locate media source. + Kunne ikke lokalisere mediekilden. + + + Could not open audio device. The device is already in use. + Kunne ikke Ã¥bne lydenheden. Enheden er allerede i brug. + + + Could not decode media source. + Kunne ikke afkode mediekilden. + + + + Phonon::VolumeSlider + + Volume: %1% + + + + Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1% + Anvend denne skyder til at indstille lydstyrken. Længst til venstre er 0% og længst til højre er %1% + + + + Q3Accel + + + %1, %2 not defined + %1, %2 ikke definerede + + + Ambiguous %1 not handled + Tvetydig %1 ikke behandlet + + + + Q3DataTable + + + True + Sandt + + + False + Falsk + + + Insert + Indsæt + + + Update + Opdater + + + Delete + Slet + + + + Q3FileDialog + + + Copy or Move a File + Kopiér eller flyt en fil + + + Read: %1 + Læs: %1 + + + Write: %1 + Skriv: %1 + + + Cancel + Annuller + + + + All Files (*) + Alle filer (*) + + + Name + Navn + + + Size + Størrelse + + + Type + + + + Date + Dato + + + Attributes + Attributter + + + &OK + &OK + + + Look &in: + Kig &i: + + + File &name: + Fil&navn: + + + File &type: + Fil&type: + + + Back + Tilbage + + + One directory up + En mappe op + + + Create New Folder + Opret ny folder + + + List View + Listevisning + + + Detail View + Detaljevisning + + + Preview File Info + Vis filinformation + + + Preview File Contents + Vis filindhold + + + Read-write + Læs-skriv + + + Read-only + Skrivebeskyttet + + + Write-only + Write-only + + + Inaccessible + Utilgængelig + + + Symlink to File + Symlink til Fil + + + Symlink to Directory + Symlink til katalog + + + Symlink to Special + Symlink til Speciel + + + File + Fil + + + Dir + Katalog + + + Special + Speciel + + + + Open + Ã…bn + + + + Save As + Gem som + + + &Open + &Ã…bn + + + &Save + &Gem + + + &Rename + &Omdøb + + + &Delete + &Slet + + + R&eload + Gen&indlæs + + + Sort by &Name + Sortér efter n&avn + + + Sort by &Size + Sortér efter s&tørrelse + + + Sort by &Date + Sortér efter &dato + + + &Unsorted + &Usorteret + + + Sort + Sortér + + + Show &hidden files + Vis s&kjulte filer + + + the file + filen + + + the directory + kataloget + + + the symlink + symlinket + + + Delete %1 + Slet %1 + + + <qt>Are you sure you wish to delete %1 "%2"?</qt> + <qt>Er du sikker pÃ¥, at du vil slette %1 "%2"?</qt> + + + &Yes + &Ja + + + &No + &Nej + + + New Folder 1 + Ny folder 1 + + + New Folder + Ny folder + + + New Folder %1 + Ny folder %1 + + + Find Directory + Find katalog + + + Directories + Kataloger + + + Directory: + Katalog: + + + Error + Fejl + + + %1 +File not found. +Check path and filename. + %1 +Filen blev ikke fundet. +Kontrollér sti og filnavn. + + + All Files (*.*) + Alle filer (*.*) + + + Open + Ã…bn + + + Select a Directory + Vælg et katalog + + + + Q3LocalFs + + Could not read directory +%1 + Kunne ikke læse katalog +%1 + + + Could not create directory +%1 + Kunne ikke oprette katalog +%1 + + + Could not remove file or directory +%1 + Kunne ikke fjerne fil eller katalog +%1 + + + Could not rename +%1 +to +%2 + Kunne ikke omdøbe +%1 +to +%2 + + + Could not open +%1 + Kunne ikke Ã¥bne +%1 + + + Could not write +%1 + Kunne ikke skrive +%1 + + + + Q3MainWindow + + + Line up + Linie op + + + Customize... + Tilpas... + + + + Q3NetworkProtocol + + + Operation stopped by the user + Brugeren stoppede handlingen + + + + Q3ProgressDialog + + Cancel + Annuller + + + + Q3TabDialog + + OK + + + + Apply + Udfør + + + Help + Hjælp + + + Defaults + Standarder + + + Cancel + Annuller + + + + Q3TextEdit + + + &Undo + &Fortryd + + + &Redo + &Gendan + + + Cu&t + &Klip + + + &Copy + K&opiér + + + &Paste + &Sæt ind + + + Clear + Ryd + + + Select All + Markér alt + + + + Q3TitleBar + + + System + + + + Restore up + Gendan op + + + Minimize + Minimer + + + Restore down + Gendan ned + + + Maximize + Maksimér + + + Close + Luk + + + Contains commands to manipulate the window + Indeholder kommandoer til indstilling af vinduet + + + Puts a minimized back to normal + Sætter et minimeret vindue til normal størrelse + + + Moves the window out of the way + Flytter vinduet væk + + + Puts a maximized window back to normal + Sætter et maksimeret vindue til normal størrelse + + + Makes the window full screen + Gør vinduet til fuld skærm + + + Closes the window + Lukker vinduet + + + Displays the name of the window and contains controls to manipulate it + Viser vinduets navn og indeholder kontroller til indstilling af vinduet + + + + Q3ToolBar + + + More... + Mere... + + + + Q3UrlOperator + + The protocol `%1' is not supported + Protokollen '%1' understøttes ikke + + + The protocol `%1' does not support listing directories + Protokollen '%1' understøtter ikke opremsning af kataloger + + + The protocol `%1' does not support creating new directories + Protokollen '%1' understøtter ikke oprettelse af nye kataloger + + + The protocol `%1' does not support removing files or directories + Protokollen '%1' understøtter ikke, at filer eller kataloger fjernes + + + The protocol `%1' does not support renaming files or directories + Protokollen '%1' understøtter ikke, at filer eller kataloger omdøbes + + + The protocol `%1' does not support getting files + Protokollen '%1' understøtter ikke hentning af filer + + + The protocol `%1' does not support putting files + Protokollen '%1' understøtter ikke upload af filer + + + The protocol `%1' does not support copying or moving files or directories + Protokollen '%1' understøtter ikke kopiering eller flytning af filer eller kataloger + + + (unknown) + (ukendt) + + + + Q3Wizard + + + &Cancel + &Annuller + + + < &Back + < &Tilbage + + + &Next > + &Næste > + + + &Finish + &Udfør + + + &Help + &Hjælp + + + + QAbstractSocket + + Host not found + Host blev ikke fundet + + + + Connection refused + Forbindelse afvist + + + Connection timed out + Forbindelsen timed out + + + Operation on socket is not supported + Socket-operation ikke understøttet + + + Socket operation timed out + Socket-operation timed out + + + Socket is not connected + Socket ikke forbundet + + + Network unreachable + Netværket er ikke tilgængeligt + + + + QAbstractSpinBox + + + &Step up + &Trin op + + + Step &down + Trin &ned + + + &Select All + &Vælg alle + + + + QApplication + + + Activate + Aktivér + + + + Executable '%1' requires Qt %2, found Qt %3. + Eksekverbar '%1' kræver Qt %2, ikke fundet Qt %3. + + + Incompatible Qt Library Error + Inkompatibel Qt Library fejl + + + + QT_LAYOUT_DIRECTION + Translate this string to the string 'LTR' in left-to-right languages or to 'RTL' in right-to-left languages (such as Hebrew and Arabic) to get proper widget layout. + + + + + Activates the program's main window + Aktiverer programmets hovedvindue + + + + QAxSelect + + Select ActiveX Control + Vælg ActiveX-kontrol + + + OK + + + + &Cancel + &Annuller + + + COM &Object: + COM &Objekt: + + + + QCheckBox + + + Uncheck + Fjern markering + + + Check + Kryds af + + + Toggle + SlÃ¥ til/fra + + + + QColorDialog + + + Hu&e: + Ton&e: + + + &Sat: + &Mæt: + + + &Val: + &Vær: + + + &Red: + &Rød: + + + &Green: + &Grøn: + + + Bl&ue: + Bl&Ã¥: + + + A&lpha channel: + Al&fa-kanal: + + + Select Color + Vælg farve + + + &Basic colors + &Basisfarver + + + &Custom colors + &Egne farver + + + &Add to Custom Colors + &Føj til egne farver + + + + QComboBox + + Open + Ã…bn + + + + False + Falsk + + + True + Sandt + + + + Close + Luk + + + + QCoreApplication + + + %1: key is empty + QSystemSemaphore + %1: nøgle er tom + + + %1: unable to make key + QSystemSemaphore + %1: kunne ikke lave nøgle + + + %1: ftok failed + QSystemSemaphore + %1: ftok mislykkedes + + + + QDB2Driver + + + Unable to connect + Kunne ikke skabe forbindelse + + + Unable to commit transaction + Kunne ikke gennemføre transaktion + + + Unable to rollback transaction + Kunne ikke tilbagetrække transaktion + + + Unable to set autocommit + Kunne ikke aktivere autocommit + + + + QDB2Result + + Unable to execute statement + Kunne ikke udføre statement + + + Unable to prepare statement + Kunne ikke forberede udsagn + + + Unable to bind variable + Kunne ikke binde variabel + + + Unable to fetch record %1 + Kunne ikke hente post %1 + + + Unable to fetch next + Kunne ikke hente næste + + + Unable to fetch first + Kunne ikke hente første + + + + QDateTimeEdit + + + AM + + + + am + + + + PM + + + + pm + + + + + QDial + + + QDial + + + + SpeedoMeter + Speedometer + + + SliderHandle + + + + + QDialog + + + What's This? + Hvad er dette? + + + Done + Udført + + + + QDialogButtonBox + + + OK + + + + + &OK + + + + &Save + &Gem + + + Save + Gem + + + Open + Ã…bn + + + &Cancel + &Annuller + + + Cancel + Annuller + + + &Close + &Luk + + + Close + Luk + + + Apply + Udfør + + + Reset + Nulstil + + + Help + Hjælp + + + Don't Save + Gem ikke + + + Discard + Kassér + + + &Yes + &Ja + + + Yes to &All + Ja til &alle + + + &No + &Nej + + + N&o to All + Ne&j til alle + + + Save All + Gem alle + + + Abort + Afbryd + + + Retry + Prøv igen + + + Ignore + Ignorer + + + Restore Defaults + Gendan standardværdier + + + Close without Saving + Luk uden at gemme + + + + QDirModel + + + Name + Navn + + + Size + Størrelse + + + Kind + Match OS X Finder + Type + + + Type + All other platforms + + + + Date Modified + Ændringsdato + + + + QDockWidget + + + Close + Luk + + + Dock + LÃ¥st + + + Float + Flydende + + + + QDoubleSpinBox + + More + Mere + + + Less + Mindre + + + + QErrorMessage + + + Debug Message: + Debug-besked: + + + Warning: + Advarsel: + + + Fatal Error: + Fatal fejl: + + + &Show this message again + &Vis denne besked igen + + + &OK + + + + + QFile + + Destination file exists + Destinationsfil findes + + + Cannot open %1 for input + Kan ikke Ã¥bne %1 til input + + + Cannot open for output + Kan ikke Ã¥bne til output + + + Failure to write block + Kunne ikke skrive blok + + + Cannot create %1 for output + Kunne ikke oprette %1 til output + + + + QFileDialog + + All Files (*) + Alle filer (*) + + + Directories + Kataloger + + + &Open + &Ã…bn + + + &Save + &Gem + + + Open + Ã…bn + + + %1 already exists. +Do you want to replace it? + %1 findes allerede. +Ønsker du at erstatte den? + + + %1 +File not found. +Please verify the correct file name was given. + %1 +Filen kunne ikke findes. +Kontrollér, at det rigtige filnavn er indtastet. + + + + My Computer + Min computer + + + &Rename + &Omdøb + + + &Delete + &Slet + + + Show &hidden files + Vis s&kjulte filer + + + Back + Tilbage + + + Parent Directory + Ovenliggende katalog + + + List View + Listevisning + + + Detail View + Detaljevisning + + + Files of type: + Filer af typen: + + + Directory: + Katalog: + + + %1 +Directory not found. +Please verify the correct directory name was given. + %1 +Katalog kunne ikke findes. +Kontrollér, at det rigtige katalognavn er indtastet. + + + '%1' is write protected. +Do you want to delete it anyway? + '%1' er skrivebeskyttet. +Ønsker du alligevel at slette? + + + Are sure you want to delete '%1'? + Er du sikker pÃ¥, at '%1' skal slettes? + + + Could not delete directory. + Kunne ikke slette kataloget. + + + Recent Places + Aktuelle steder + + + + All Files (*.*) + Alle filer (*.*) + + + Save As + Gem som + + + + Drive + Drev + + + File + Fil + + + Unknown + Ukendt + + + Find Directory + Find katalog + + + Show + Vis + + + Forward + Frem + + + + New Folder + Ny folder + + + &New Folder + &Ny folder + + + &Choose + &Vælg + + + + Remove + Fjern + + + File &name: + &Filnavn: + + + Look in: + Søg i: + + + Create New Folder + Opret ny folder + + + + QFileSystemModel + + + Invalid filename + Ugyldigt filnavn + + + <b>The name "%1" can not be used.</b><p>Try using another name, with fewer characters or no punctuations marks. + <b>Navnet, %1, kan ikke benyttes.</b><p>Brug et andet navn med færre tegn og ingen kommatering. + + + Name + Navn + + + Size + Størrelse + + + Kind + Match OS X Finder + Type + + + Type + All other platforms + + + + Date Modified + Ændringsdato + + + + My Computer + Min computer + + + Computer + + + + %1 TB + %1 TB + + + %1 GB + %1 GB + + + %1 MB + %1 MB + + + %1 KB + %1 KB' + + + %1 bytes + %1 bytes + + + + QFontDatabase + + Normal + + + + Bold + Fed + + + Demi Bold + + + + Black + Sort + + + Demi + + + + Light + Lys + + + Italic + Kursiv + + + Oblique + SkrÃ¥t + + + Any + Alle + + + Latin + + + + Greek + Græsk + + + Cyrillic + Kyrillisk + + + Armenian + Armensk + + + Hebrew + Hebræisk + + + Arabic + Arabisk + + + Syriac + Syrisk + + + Thaana + + + + Devanagari + + + + Bengali + Bengalsk + + + Gurmukhi + + + + Gujarati + + + + Oriya + + + + Tamil + + + + Telugu + + + + Kannada + + + + Malayalam + + + + Sinhala + + + + Thai + Thailandsk + + + Lao + + + + Tibetan + Tibetansk + + + Myanmar + + + + Georgian + georgisk + + + Khmer + + + + Simplified Chinese + Forenklet kinesisk + + + Traditional Chinese + Traditionelt kinesisk + + + Japanese + Japansk + + + Korean + Koreansk + + + Vietnamese + Vietnamesisk + + + Symbol + + + + Ogham + + + + Runic + + + + + QFontDialog + + + &Font + S&krifttype + + + Font st&yle + S&til + + + &Size + &Størrelse + + + Effects + Effekter + + + Stri&keout + &Overstreget + + + &Underline + &Understreg + + + Sample + Eksempel + + + Wr&iting System + Skr&ivesystem + + + Select Font + Vælg skrifttype + + + + QFtp + + + Not connected + Ingen forbindelse + + + + Host %1 not found + Vært %1 ikke fundet + + + + Connection refused to host %1 + Forbindelse til vært %1 afvist + + + Connection timed out to host %1 + Forbindelsen timed out til host %1 + + + Connected to host %1 + Tilsluttet vært %1 + + + Connection refused for data connection + Dataforbindelse afvist + + + Unknown error + Ukendt fejl + + + + Connecting to host failed: +%1 + Forbindelse til vært mislykkedes: +%1 + + + + Login failed: +%1 + Login mislykkedes: +%1 + + + + Listing directory failed: +%1 + Opremsning af katalogindhold mislykkedes: +%1 + + + + Changing directory failed: +%1 + Ændring af katalog mislykkedes: +%1 + + + + Downloading file failed: +%1 + Downloading af fil mislykkedes: +%1 + + + + Uploading file failed: +%1 + Uploading af fil mislykkedes: +%1 + + + + Removing file failed: +%1 + Det mislykkedes at fjerne fil: +%1 + + + + Creating directory failed: +%1 + Oprettelse af katalog mislykkedes: +%1 + + + + Removing directory failed: +%1 + Det mislykkedes at fjerne katalog: +%1 + + + Connection closed + Forbindelse lukket + + + Host %1 found + Vært %1 fundet + + + Connection to %1 closed + Forbindelse til %1 lukket + + + Host found + Vært fundet + + + Connected to host + Tilsluttet vært + + + + QHostInfo + + + Unknown error + Ukendt fejl + + + + QHostInfoAgent + + Host not found + Vært ikke fundet + + + Unknown address type + Ukendt adressetype + + + Unknown error + Ukendt fejl + + + + QHttp + + Unknown error + Ukendt fejl + + + Request aborted + Forespørgsel blev annulleret + + + + No server set to connect to + Ingen server at forbinde til + + + + Wrong content length + Forkert indholdslængde + + + + Server closed connection unexpectedly + Serveren afsluttede uventet forbindelsen + + + Error writing response to device + Skrivefejl mens der blev skrevet til enheden + + + + Connection refused + Forbindelse afvist + + + + Host %1 not found + Vært %1 ikke fundet + + + + HTTP request failed + HTTP anmodning mislykkedes + + + + Invalid HTTP response header + Ugyldig HTTP-svar-header + + + Invalid HTTP chunked body + Ugyldig HTTP chunked body + + + + Host %1 found + Vært %1 fundet + + + Connected to host %1 + Tilsluttet vært %1 + + + Connection to %1 closed + Forbindelse til %1 lukket + + + Host found + Vært fundet + + + Connected to host + Tilsluttet vært + + + + Connection closed + Forbindelse lukket + + + Proxy authentication required + Kræver proxy-autentificering + + + Authentication required + Autentificering pÃ¥krævet + + + Connection refused (or timed out) + Forbindelse blev afvist (eller tid udløb) + + + + Proxy requires authentication + Proxy kræver autentificering + + + Host requires authentication + Vært kræver autentificering + + + Data corrupted + Data er ødelagt + + + Unknown protocol specified + En ukendt protokol blev angivet + + + SSL handshake failed + SSL handshake mislykkedes + + + HTTPS connection requested but SSL support not compiled in + Der blevet anmodet om en HTTPS-forbindelse, men SSL understøttelse er ikke kompileret ind + + + + QHttpSocketEngine + + Did not receive HTTP response from proxy + Modtog ikke HTTP-svar fra proxy + + + Error parsing authentication request from proxy + Fejl under fortolking af autentificeringsanmodning fra proxy + + + Authentication required + Autentificering pÃ¥krævet + + + Proxy denied connection + Proxy nægtede forbindelse + + + Error communicating with HTTP proxy + Fejl under kommunikation med HTTP-proxy + + + Proxy server not found + Proxy-server kunne ikke findes + + + Proxy connection refused + Proxy-forbindelse nægtede + + + Proxy server connection timed out + Proxy-serverforbindelse timed out + + + Proxy connection closed prematurely + Proxy-forbindelse afsluttede i utide + + + + QIBaseDriver + + + Error opening database + Der opstod fejl ved Ã¥bning af database + + + Could not start transaction + Kunne ikke pÃ¥begynde transaktionen + + + Unable to commit transaction + Kunne ikke gennemføre transaktionen + + + Unable to rollback transaction + Kunne ikke tilbagetrække transaktionen + + + + QIBaseResult + + Unable to create BLOB + Kunne ikke oprette BLOB + + + Unable to write BLOB + Kunne ikke skrive BLOB + + + Unable to open BLOB + Kunne ikke Ã¥bne BLOB + + + Unable to read BLOB + Kunne ikke læse BLOB + + + Could not find array + Kunne ikke finde array + + + Could not get array data + Kunne ikke hente arraydata + + + Could not get query info + Kunne ikke hente forespørgselsinfo + + + Could not start transaction + Kunne ikke pÃ¥begynde transaktionen + + + Unable to commit transaction + Kunne ikke gennemføre transaktionen + + + Could not allocate statement + Kunne ikke allokere statement + + + Could not prepare statement + Kunne ikke forberede udsagn + + + Could not describe input statement + Kunne ikke beskrive input-statement + + + Could not describe statement + Kunne ikke beskrive statement + + + Unable to close statement + Kunne ikke lukke udsagn + + + Unable to execute query + Kunne ikke udføre forespørgsel + + + Could not fetch next item + Kunne ikke hente næste element + + + Could not get statement info + Kunne ikke hente udsagnsinformation + + + + QIODevice + + + Permission denied + Tilladelse nægtet + + + Too many open files + Der er for mange Ã¥bne filer + + + No such file or directory + Fil eller katalog findes ikke + + + No space left on device + Ingen plads tilbage pÃ¥ enheden + + + + Unknown error + Ukendt fejl + + + + QInputContext + + + XIM + + + + XIM input method + XIM input-metode + + + Windows input method + Windows input-metode + + + Mac OS X input method + Mac OS X input-metode + + + + QInputDialog + + + Enter a value: + Indtast en værdi: + + + + QLibrary + + + Could not mmap '%1': %2 + + + + Plugin verification data mismatch in '%1' + Plugin-verifikationsdata er sat forkert sammen i '%1' + + + Could not unmap '%1': %2 + Der var ikke muligt at lave unmap pÃ¥ '%1': %2 + + + The plugin '%1' uses incompatible Qt library. (%2.%3.%4) [%5] + Plugin '%1' bruger inkompatibelt Qt-bibliotek. (%2.%3.%4) [%5] + + + The plugin '%1' uses incompatible Qt library. Expected build key "%2", got "%3" + Plugin '%1' bruger inkompatibelt Qt-bibliotek. Forventet build key "%2", hentede "%3"' + + + Unknown error + Ukendt fejl' + + + + The shared library was not found. + DSO blev ikke fundet. + + + The file '%1' is not a valid Qt plugin. + Filen '%1' er ikke et gyldigt Qt-plugin. + + + The plugin '%1' uses incompatible Qt library. (Cannot mix debug and release libraries.) + Plugin '%1' bruger inkompatibelt Qt-bibliotek. (Ikke muligt at mikse debug og release-biblioteker) + + + + Cannot load library %1: %2 + Kan ikke indlæse bibliotek %1: %2 + + + + Cannot unload library %1: %2 + Kan ikke afregistrere bibliotek %1: %2 + + + + Cannot resolve symbol "%1" in %2: %3 + Kan ikke løse symbol "%1" i %2: %3 + + + + QLineEdit + + + &Undo + &Fortryd + + + &Redo + &Gendan + + + Cu&t + K&lip + + + &Copy + &Kopiér + + + &Paste + &Sæt ind + + + Delete + Slet + + + Select All + Markér alt + + + + QLocalServer + + + %1: Name error + %1: Navnefejl + + + %1: Permission denied + %1: Tilladelse nægtet + + + %1: Address in use + %1: Adresse i brug + + + + %1: Unknown error %2 + %1: Ukendt fejl %2 + + + + QLocalSocket + + + %1: Connection refused + %1: Forbindelse afvist + + + + %1: Remote closed + %1: Den anden ende lukkede + + + %1: Invalid name + %1: Ugyldigt navn + + + + %1: Socket access error + %1: Fejl i socket-adgang + + + + %1: Socket resource error + %1: Fejl i socket-ressource + + + + %1: Socket operation timed out + %1: Socket-handling timed out + + + + %1: Datagram too large + %1: Datagram er for stort + + + %1: Connection error + %1: Forbindelsesfejl + + + + %1: The socket operation is not supported + %1: Socket-handlingen understøttes ikke + + + %1: Unknown error + %1: Ukendt fejl + + + + %1: Unknown error %2 + %1: Ukendt fejl %2 + + + + QMYSQLDriver + + + Unable to open database ' + Kunne ikke Ã¥bne databasen ' + + + Unable to connect + Kunne ikke forbinde + + + Unable to begin transaction + Kunne ikke pÃ¥begynde transaktionen + + + Unable to commit transaction + Kunne ikke gennemføre transaktionen + + + Unable to rollback transaction + Kunne ikke tilbagetrække transaktionen + + + + QMYSQLResult + + Unable to fetch data + Kunne ikke hente data + + + Unable to execute query + Kunne ikke udføre forespørgsel + + + Unable to store result + Kunne ikke gemme resultatet + + + Unable to prepare statement + Kunne ikke forberede udsagn + + + Unable to reset statement + Kunne ikke nulstille udsagn + + + Unable to bind value + Kunne ikke tildele værdi + + + Unable to execute statement + Kunne ikke udføre udsagn + + + Unable to bind outvalues + Kunne ikke binde udværdier + + + Unable to store statement results + Kunne ikke gemme udsagnsresultater + + + Unable to execute next query + Kunne ikke udføre næste forespørgsel + + + Unable to store next result + Kunne ikke gemme næste resultat + + + + QMdiArea + + + (Untitled) + (Uden titel) + + + + QMdiSubWindow + + + %1 - [%2] + + + + Close + Luk + + + Minimize + Minimér + + + Restore Down + Gendan Ned + + + &Restore + &Gendan + + + &Move + &Flyt + + + &Size + &Størrelse + + + Mi&nimize + Mi&nimér + + + Ma&ximize + Ma&ksimér + + + Stay on &Top + Bliv &oppe + + + &Close + &Luk + + + - [%1] + + + + Maximize + Maksimér + + + Unshade + Fjern skygge + + + Shade + Skygge + + + Restore + Gendan + + + Help + Hjælp + + + Menu + + + + + QMenu + + Close + Luk + + + Open + Ã…bn + + + Execute + Udfør + + + + QMessageBox + + Help + Hjælp + + + OK + + + + About Qt + Om Qt + + + <p>This program uses Qt version %1.</p> + <p>Dette program bruger Qt-version %1.</p> + + + Show Details... + Vis detaljer... + + + Hide Details... + Skjul detaljer... + + + <h3>About Qt</h3>%1<p>Qt is a C++ toolkit for cross-platform application development.</p><p>Qt provides single-source portability across MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, and all major commercial Unix variants. Qt is also available for embedded devices as Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt is a Nokia product. See <a href="http://qtsoftware.com/qt/">qtsoftware.com/qt/</a> for more information.</p> + <h3>Om Qt</h3>%1<p>Qt er et C++ toolkit til cross-platform applikationsudvikling.</p><p>Qt tilbyder single-source portabilitet til MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, og alle større kommercielle Unix-varianter. Qt er ogsÃ¥ tilgængeligt til indlejrede systemer som Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt er et Nokia produkt. Se <a href="http://qtsoftware.com/qt/">qtsoftware.com/qt/</a> for yderligere information.</p> + + + <p>This program uses Qt Open Source Edition version %1.</p><p>Qt Open Source Edition is intended for the development of Open Source applications. You need a commercial Qt license for development of proprietary (closed source) applications.</p><p>Please see <a href="http://qtsoftware.com/company/model/">qtsoftware.com/company/model/</a> for an overview of Qt licensing.</p> + <p>Dette program bruger Qt Open Source Edition version %1.</p><p>Qt Open Source Edition er beregnet til udvikling af Open Source applikationer. En kommerciel Qt licens er nødvendig til udvikling af proprietære (lukket sourcekode) applikationer.</p><p>Se venligst <a href="http://qtsoftware.com/company/model/">qtsoftware.com/company/model/</a> for et overblik over Qt licensforhold.</p> + + + + QMultiInputContext + + + Select IM + Markér IM + + + + QMultiInputContextPlugin + + + Multiple input method switcher + Multiple input metode-switcher + + + Multiple input method switcher that uses the context menu of the text widgets + Multiple input metode-switcher, der benytter tekstkontrollernes kontekstmenuer + + + + QNativeSocketEngine + + + The remote host closed the connection + Fjern-hosten lukkede forbindelsen + + + Network operation timed out + Netværksoperationen timed out + + + Out of resources + Ikke flere ressourcer + + + Unsupported socket operation + Socket-operation ikke understøttet + + + Protocol type not supported + Protokoltypen understøttes ikke + + + Invalid socket descriptor + Ugyldig socket-deskriptor + + + Network unreachable + Netværket er ikke tilgængeligt + + + Permission denied + Tilladelse nægtet + + + Connection timed out + Forbindelsen timed out + + + Connection refused + Forbindelse afvist + + + The bound address is already in use + Den bundne adresse er allerede i brug + + + The address is not available + Adressen er ikke tilgængelig + + + The address is protected + Adressen er beskyttet + + + Unable to send a message + Kunne ikke sende en besked + + + Unable to receive a message + Kunne ikke modtage en besked + + + Unable to write + Kunne ikke skrive + + + Network error + Netværksfejl + + + Another socket is already listening on the same port + En anden socket lytter allerede på samme port + + + Unable to initialize non-blocking socket + Kunne ikke initialisere non-blocking socket + + + Unable to initialize broadcast socket + Kunne ikke initialisere broadcast-socket + + + Attempt to use IPv6 socket on a platform with no IPv6 support + Forsøg på at bruge IPv6-socket på en platform uden IPv6-support + + + Host unreachable + Vært er ikke tilgængelig + + + Datagram was too large to send + Datagrammet var for stort til at blive sendt + + + Operation on non-socket + Handling på non-socket + + + Unknown error + Ukendt fejl + + + The proxy type is invalid for this operation + Proxytypen er ugyldig til denne handling + + + + QNetworkAccessCacheBackend + + + Error opening %1 + Der opstod fejl i at åbne %1 + + + + QNetworkAccessFileBackend + + + Request for opening non-local file %1 + Anmodning om at åbne ikke-lokal fil %1 + + + Error opening %1: %2 + Der opstod fejl i at åbne %1: %2 + + + Write error writing to %1: %2 + Skrivefejl mens der blev skrevet til %1: %2 + + + Cannot open %1: Path is a directory + Kan ikke åbne %1: Stien er et katalog + + + Read error reading from %1: %2 + Læsefejl mens der blev læst fra %1: %2 + + + + QNetworkAccessFtpBackend + + + No suitable proxy found + Ingen passende proxy blev fundet + + + Cannot open %1: is a directory + Kan ikke åbne %1: Er et katalog + + + Logging in to %1 failed: authentication required + Der opstod fejl i at logge på %1: Autentificering kræves + + + Error while downloading %1: %2 + Der opstod fejl i at downloade %1: %2 + + + Error while uploading %1: %2 + Der opstod fejl i at uploade %1: %2 + + + + QNetworkAccessHttpBackend + + + No suitable proxy found + Ingen passende proxy blev fundet + + + + QNetworkReply + + Error downloading %1 - server replied: %2 + Der opstod fejl i at downloade %1 - serveren svarede: %2 + + + + Protocol "%1" is unknown + Protokollen "%1" er ukendt + + + + QNetworkReplyImpl + + Operation canceled + Handling blev annulleret + + + + QOCIDriver + + + Unable to logon + Kunne ikke logge på + + + Unable to initialize + QOCIDriver + Kunne ikke initialisere + + + Unable to begin transaction + Kunne ikke påbegynde transaktionen + + + Unable to commit transaction + Kunne ikke gennemføre transaktionen + + + Unable to rollback transaction + Kunne ikke tilbagetrække transaktionen + + + + QOCIResult + + Unable to bind column for batch execute + Kunne ikke tildele kolonne til batch-udførsel + + + Unable to execute batch statement + Kunne ikke udføre batch-udsagn + + + Unable to goto next + Kunne ikke gå til den næste + + + Unable to alloc statement + Kunne ikke allokere udsagn + + + Unable to prepare statement + Kunne ikke forberede udsagn + + + Unable to bind value + Kunne ikke tildele værdi + + + Unable to execute select statement + Kunne ikke udføre det valgte udsagn + + + Unable to execute statement + Kunne ikke udføre udsagn + + + + QODBCDriver + + + Unable to connect + Kunne ikke forbinde + + + Unable to connect - Driver doesn't support all needed functionality + Kunne ikke forbinde. Driveren understøtter ikke alle de nødvendige funktionaliteter + + + Unable to disable autocommit + Kunne ikke slå auto-udfør fra + + + Unable to commit transaction + Kunne ikke gennemføre transaktionen + + + Unable to rollback transaction + Kunne ikke tilbagetrække transaktionen + + + Unable to enable autocommit + Kunne ikke slå auto-udfør til + + + + QODBCResult + + QODBCResult::reset: Unable to set 'SQL_CURSOR_STATIC' as statement attribute. Please check your ODBC driver configuration + QODBCResult::reset: Kunne ikke indstille 'SQL_CURSOR_STATIC' til udsagnsattribut. Kontrollér ODBC-driver-konfigurationen + + + Unable to execute statement + Kunne ikke udføre udsagn + + + Unable to fetch next + Kunne ikke hente den næste + + + Unable to prepare statement + Kunne ikke forberede udsagn + + + Unable to bind variable + Kunne ikke tildele variabel + + + Unable to fetch last + Kunne ikke hente den sidste + + + Unable to fetch + Kunne ikke hente + + + Unable to fetch first + Kunne ikke hente den første + + + Unable to fetch previous + Kunne ikke hente den forrige + + + + QObject + + + Home + Hjem + + + + Operation not supported on %1 + Handling blev ikke understøttet på %1 + + + Invalid URI: %1 + Ugyldig URI: %1 + + + + Write error writing to %1: %2 + Skrivefejl mens der blev skrevet til %1: %2 + + + Read error reading from %1: %2 + Læsefejl mens der blev læst fra %1: %2 + + + Socket error on %1: %2 + Socket-fejl på %1: %2 + + + Remote host closed the connection prematurely on %1 + Fjern-host lukkede forbindelsen for tidligt på %1 + + + Protocol error: packet of size 0 received + Protokolfejl: Pakke på størrelsen 0 modtaget + + + No host name given + Hostnavn mangler + + + + QPPDOptionsModel + + + Name + Navn + + + Value + Værdi + + + + QPSQLDriver + + + Unable to connect + Kunne ikke skabe forbindelse + + + Could not begin transaction + Kunne ikke påbegynde transaktion + + + Could not commit transaction + Kunne ikke gennemføre transaktion + + + Could not rollback transaction + Kunne ikke tilbagetrække transaktion + + + Unable to subscribe + Kunne ikke tilmelde + + + Unable to unsubscribe + Kunne ikke afmelde + + + + QPSQLResult + + Unable to create query + Kunne ikke oprette forespørgsel + + + Unable to prepare statement + Kunne ikke forberede udsagn + + + + QPageSetupWidget + + + Centimeters (cm) + Centimeter (cm) + + + Millimeters (mm) + Millimeter (mm) + + + Inches (in) + + + + Points (pt) + Point (pt) + + + Form + + + + Paper + Papir + + + Page size: + Sidestørrelse: + + + Width: + Vidde: + + + Height: + Højde: + + + Paper source: + Papirkilde: + + + Orientation + + + + Portrait + Portræt + + + Landscape + Landskab + + + Reverse landscape + Omvendt landskab + + + Reverse portrait + Omvendt portræt + + + Margins + Margener + + + top margin + Margen - øverst + + + left margin + Margen - venstre + + + right margin + Margen - højre + + + bottom margin + Margen - bund + + + + QPluginLoader + + + Unknown error + Ukendt fejl + + + The plugin was not loaded. + Plugin blev ikke indlæst. + + + + QPrintDialog + + + locally connected + lokalt forbundet + + + Aliases: %1 + Aliasser: %1 + + + unknown + Ukendt + + + + A0 (841 x 1189 mm) + + + + A1 (594 x 841 mm) + + + + A2 (420 x 594 mm) + + + + A3 (297 x 420 mm) + + + + A4 (210 x 297 mm, 8.26 x 11.7 inches) + + + + A5 (148 x 210 mm) + + + + A6 (105 x 148 mm) + + + + A7 (74 x 105 mm) + + + + A8 (52 x 74 mm) + + + + A9 (37 x 52 mm) + + + + B0 (1000 x 1414 mm) + + + + B1 (707 x 1000 mm) + + + + B2 (500 x 707 mm) + + + + B3 (353 x 500 mm) + + + + B4 (250 x 353 mm) + + + + B5 (176 x 250 mm, 6.93 x 9.84 inches) + + + + B6 (125 x 176 mm) + + + + B7 (88 x 125 mm) + + + + B8 (62 x 88 mm) + + + + B9 (44 x 62 mm) + + + + B10 (31 x 44 mm) + + + + C5E (163 x 229 mm) + + + + DLE (110 x 220 mm) + + + + Executive (7.5 x 10 inches, 191 x 254 mm) + + + + Folio (210 x 330 mm) + + + + Ledger (432 x 279 mm) + + + + Legal (8.5 x 14 inches, 216 x 356 mm) + + + + Letter (8.5 x 11 inches, 216 x 279 mm) + + + + Tabloid (279 x 432 mm) + + + + US Common #10 Envelope (105 x 241 mm) + + + + + OK + + + + Print + Udskriv + + + Print To File ... + Udskriv til fil... + + + + Print range + Udskriftsområde + + + Print all + Udskriv alle + + + + File %1 is not writable. +Please choose a different file name. + Filen %1 kan ikke skrives. +Vælg et andet filnavn. + + + %1 already exists. +Do you want to overwrite it? + %1 findes allerede. +Ønsker du at overskrive? + + + File exists + Fil findes + + + <qt>Do you want to overwrite it?</qt> + <qt>Ønsker du at overskrive?</qt> + + + Print selection + Udskriv markerede + + + %1 is a directory. +Please choose a different file name. + %1 er et katalog. +Vælg et andet filnavn. + + + A0 + + + + A1 + + + + A2 + + + + A3 + + + + A4 + + + + A5 + + + + A6 + + + + A7 + + + + A8 + + + + A9 + + + + B0 + + + + B1 + + + + B2 + + + + B3 + + + + B4 + + + + B5 + + + + B6 + + + + B7 + + + + B8 + + + + B9 + + + + B10 + + + + C5E + + + + DLE + + + + Executive + + + + Folio + + + + Ledger + + + + Legal + + + + Letter + + + + Tabloid + + + + US Common #10 Envelope + + + + Custom + Brugerdefineret + + + &Options >> + &Indstillinger>> + + + &Print + &Udskriv + + + &Options << + &Indstillinger<< + + + Print to File (PDF) + Udskriv til fil (PDF) + + + Print to File (Postscript) + Udskriv til fil (Postscript) + + + Local file + Lokal fil + + + Write %1 file + Skriv %1 fil + + + + The 'From' value cannot be greater than the 'To' value. + 'Fra'-værdien kan ikke være større end 'til'-værdien. + + + + QPrintPreviewDialog + + Page Setup + Sideopsætning + + + + %1% + + + + Print Preview + Vis udskrift + + + Next page + Næste side + + + Previous page + Forrige side + + + First page + Første side + + + Last page + Sidste side + + + Fit width + Tilpas bredde + + + Fit page + Tilpas siden + + + Zoom in + Zoom ind + + + Zoom out + Zoom ud + + + Portrait + Portræt + + + Landscape + Landskab + + + Show single page + Vis enkelt side + + + Show facing pages + Vis sideopslag + + + Show overview of all pages + Vis oversigt af alle sider + + + Print + Udskriv + + + Page setup + Sideopsætning + + + Close + Luk + + + Export to PDF + Eksportér til PDF + + + Export to PostScript + Eksportér til PostScript + + + + QPrintPropertiesWidget + + Form + Form + + + Page + Side + + + Advanced + Avanceret + + + + QPrintSettingsOutput + + Form + + + + Copies + Kopier + + + Print range + Udskriv sider + + + Print all + Udskriv alle + + + Pages from + Sider fra + + + to + til + + + Selection + Valg + + + Output Settings + Udskriftsindstillinger + + + Copies: + Kopier: + + + Collate + Samordne + + + Reverse + Omvendt + + + Options + Valgmuligheder + + + Color Mode + Farvetilstand + + + Color + Farve + + + Grayscale + Gråskala + + + Duplex Printing + Dobbelsidet + + + None + Ingen + + + Long side + Bog + + + Short side + Tavle + + + + QPrintWidget + + Form + + + + Printer + ' + + + &Name: + &Navn: + + + P&roperties + &Egenskaber + + + Location: + Placering: + + + Preview + Vis udskrift + + + Type: + + + + Output &file: + Udskrifts&fil: + + + ... + + + + + QProcess + + + Could not open input redirection for reading + Kunne ikke åbne input redirection for læsning + + + + Could not open output redirection for writing + Kunne ikke åbne output redirection for skrivning + + + Resource error (fork failure): %1 + Ressource fejl (fork fejl): %1 + + + Process operation timed out + Proces-operation time out + + + Error reading from process + Fejl ved læsning fra proces + + + + Error writing to process + Fejl ved skrivning til proces + + + Process crashed + Proces crashede + + + Process failed to start + Processen kunne ikke starte + + + + QProgressDialog + + + Cancel + Annuller + + + + QPushButton + + Open + Åbn + + + + QRadioButton + + Check + Kontrollér + + + + QRegExp + + + no error occurred + der opstod ingen fejl + + + disabled feature used + deaktiveret funktion blev brugt + + + bad char class syntax + dårlig char class syntaks + + + bad lookahead syntax + dårlig lookahead syntaks + + + bad repetition syntax + dårlig gentagelsessyntaks + + + invalid octal value + ugyldigt oktal-tal + + + missing left delim + Manglende venstre delimiter + + + unexpected end + uventet afslutning + + + met internal limit + nåede interne grænse + + + + QSQLite2Driver + + + Error to open database + Der opstod fejl ved åbning af database + + + Unable to begin transaction + Kunne ikke påbegynde transaktionen + + + Unable to commit transaction + Kunne ikke gennemføre transaktionen + + + Unable to rollback Transaction + Kunne ikke tilbagetrække transaktion + + + + QSQLite2Result + + Unable to fetch results + Kunne ikke hente resultater + + + Unable to execute statement + Kunne ikke udføre statement + + + + QSQLiteDriver + + + Error opening database + Der opstod fejl ved åbning af database + + + Error closing database + Der opstod fejl ved lukning af database + + + Unable to begin transaction + Kunne ikke påbegynde transaktionen + + + Unable to commit transaction + Kunne ikke gennemføre transaktion + + + Unable to rollback transaction + Kunne ikke tilbagetrække transaktion + + + + QSQLiteResult + + Unable to fetch row + Kunne ikke hente række + + + Unable to execute statement + Kunne ikke udføre udsagn + + + Unable to reset statement + Kunne ikke nulstille udsagn + + + Unable to bind parameters + Unable to bind parameters + + + Parameter count mismatch + Misforhold i parametertælling + + + No query + Ingen forespørgesel + + + + QScrollBar + + + Scroll here + Scroll her + + + Left edge + Venstre kant + + + Top + Øverst + + + Right edge + Højre kant + + + Bottom + Bund + + + Page left + Side venstre + + + + Page up + Side øverst + + + Page right + Side højre + + + + Page down + Side ned + + + Scroll left + Scroll til venstre + + + Scroll up + Scroll op + + + Scroll right + Scroll til højre + + + Scroll down + Scroll ned + + + Line up + Linie op + + + Position + Placering + + + Line down + Linie ned + + + + QSharedMemory + + + %1: unable to set key on lock + %1: Kunne ikke oprette nøgle + + + %1: create size is less then 0 + %1: create size is less then 0 + + + + %1: unable to lock + %1: Kunne ikke låse + + + %1: unable to unlock + %1: Kunne ikke oprette nøgle + + + + %1: permission denied + %1: Tilladelse nægtet + + + %1: already exists + %1: Findes allerede + + + + %1: doesn't exists + %1: Findes ikke + + + + %1: out of resources + %1: Ikke flere ressourcer + + + + %1: unknown error %2 + %1: ukendt fejl %2 + + + %1: key is empty + %1: nøgle er tom + + + %1: unix key file doesn't exists + %1: Kunne ikke oprette nøgle + + + %1: ftok failed + %1: ftok mislykkedes + + + + %1: unable to make key + %1: Kunne ikke oprette nøgle + + + %1: system-imposed size restrictions + %1: System-pålagte størrelsesrestriktioner + + + %1: not attached + %1: Ikke vedhæftet + + + %1: invalid size + %1: Ugyldig størrelse + + + %1: key error + %1: Nøglefejl + + + %1: size query failed + %1: Størrelsesforespørgsel mislykkedes + + + + QShortcut + + + Space + + + + Esc + + + + Tab + + + + Backtab + Tilbage-tabulator + + + Backspace + Tilbage + + + Return + + + + Enter + + + + Ins + + + + Del + + + + Pause + + + + Print + Udskriv + + + SysReq + + + + Home + + + + End + + + + Left + Venstre + + + Up + Op + + + Right + Højre + + + Down + Ned + + + PgUp + + + + PgDown + + + + CapsLock + ' + + + NumLock + + + + ScrollLock + + + + Menu + + + + Help + Hjælp + + + Back + Tilbage + + + Forward + Frem + + + Stop + + + + Refresh + Opdater + + + Volume Down + Lydstyrke ned + + + Volume Mute + Lydstyrke mute + + + Volume Up + Lydstyrke op + + + Bass Boost + + + + Bass Up + Bass op + + + Bass Down + Bass ned + + + Treble Up + Diskant op + + + Treble Down + Diskant ned + + + Media Play + + + + Media Stop + + + + Media Previous + Media forrige + + + Media Next + Media næste + + + Media Record + + + + Favorites + + + + Search + Søg + + + Standby + + + + Open URL + Åbn URL + + + Launch Mail + Start mail + + + Launch Media + Start Media + + + Launch (0) + Start (0) + + + Launch (1) + Start (1) + + + Launch (2) + Start (2) + + + Launch (3) + Start (3) + + + Launch (4) + Start (4) + + + Launch (5) + Start (5) + + + Launch (6) + Start (6) + + + Launch (7) + Start (7) + + + Launch (8) + Start (8) + + + Launch (9) + Start (9) + + + Launch (A) + Start (A) + + + Launch (B) + Start (B) + + + Launch (C) + Start (C) + + + Launch (D) + Start (D) + + + Launch (E) + Start (E) + + + Launch (F) + Start (F) + + + Print Screen + + + + Page Up + + + + Page Down + + + + Caps Lock + + + + Num Lock + + + + Number Lock + + + + Scroll Lock + + + + Insert + + + + Delete + + + + Escape + + + + System Request + + + + Select + Væg + + + Yes + Ja + + + No + Nej + + + Context1 + Kontekst1 + + + Context2 + Kontekst2 + + + Context3 + Kontekst3 + + + Context4 + Kontekst4 + + + Call + Ring til + + + Hangup + Læg på + + + Flip + Vend + + + Ctrl + + + + Shift + + + + Alt + + + + Meta + + + + + + + + + F%1 + + + + Home Page + Startside + + + + QSlider + + + Page left + Side venstre + + + Page up + Side op + + + Position + Placering + + + Page right + Side højre + + + Page down + Side ned + + + + QSocks5SocketEngine + + Connection to proxy refused + Proxy-forbindelse nægtede + + + Connection to proxy closed prematurely + Proxy-forbindelse afsluttede i utide + + + Proxy host not found + Proxy-host kunne ikke findes + + + Connection to proxy timed out + Proxy-serverforbindelse timed out + + + Proxy authentication failed + Proxy autentificering mislykkedes + + + Proxy authentication failed: %1 + Proxy autentificering mislykkedes: %1 + + + SOCKS version 5 protocol error + SOCKS version 5 protokolfejl + + + General SOCKSv5 server failure + General SOCKSv5 serverfejl + + + Connection not allowed by SOCKSv5 server + Forbindelse ikke tilladt a SOCKSv5-server + + + TTL expired + TTL udløbet + + + SOCKSv5 command not supported + SOCKSv5-kommando ikke understøttet + + + Address type not supported + Adressetype understøttes ikke + + + Unknown SOCKSv5 proxy error code 0x%1 + Ukendt SOCKSv5 proxy fejlkode 0x%1 + + + Network operation timed out + Netværksoperationen timed out + + + + QSpinBox + + More + Mere + + + Less + Mindre + + + + QSql + + + Delete + Slet + + + Delete this record? + Slet denne post? + + + Yes + Ja + + + No + Nej + + + Insert + Indsæt + + + Update + Opdater + + + Save edits? + Gem ændringer? + + + Cancel + Annuller + + + Confirm + Bekræft + + + Cancel your edits? + Skal dine ændringer annulleres? + + + + QSslSocket + + + Unable to write data: %1 + Kunne ikke skrive data: %1 + + + Error while reading: %1 + Der opstod en fejl under læsning af: %1 + + + Error during SSL handshake: %1 + Der opstod en fejl under SSL handshake: %1 + + + Error creating SSL context (%1) + Der opstod fejl under oprettelse af SSL-kontekst (%1) + + + Invalid or empty cipher list (%1) + Ugyldig eller tom chifferliste (%1) + + + Error creating SSL session, %1 + Der opstod fejl under oprettelse af SSL-session, %1 + + + Error creating SSL session: %1 + Der opstod fejl under oprettelse af SSL-session, %1 + + + Cannot provide a certificate with no key, %1 + Kan ikke give et certifikat uden nøgle, %1 + + + Error loading local certificate, %1 + Der opstod fejl under indlæsning af lokalt certifikat, %1 + + + Error loading private key, %1 + Der opstod fejl under indlæsning af privat nøgle, %1 + + + Private key does not certificate public key, %1 + Privat-nøgle autoriserer ikke offentlig-nøgle, %1 + + + + QSystemSemaphore + + + %1: out of resources + %1: Ikke flere ressourcer + + + + %1: permission denied + %1: Tilladelse nægtet + + + %1: already exists + %1: Findes allerede + + + %1: does not exist + %1: Findes ikke + + + + %1: unknown error %2 + %1: Ukendt fejl %2 + + + + QTDSDriver + + + Unable to open connection + Kunne ikke etablere forbindelsen + + + Unable to use database + Kunne ikke bruge databasen + + + + QTabBar + + Scroll Left + Scroll til venstre + + + Scroll Right + Scroll til højre + + + + QTcpServer + + + Operation on socket is not supported + Socket-operation ikke understøttet + + + + QTextControl + + + &Undo + &Fortryd + + + &Redo + &Gendan + + + Cu&t + K&lip + + + &Copy + &Kopiér + + + Copy &Link Location + Kopiér l&ink + + + &Paste + &Sæt ind + + + Delete + Slet + + + Select All + Markér alt + + + + QToolButton + + Press + Tryk på + + + Open + Åbn + + + + QUdpSocket + + + This platform does not support IPv6 + Denne platform understøtter ikke IPv6 + + + + QUndoGroup + + + Undo + Fortryd + + + Redo + Gendan + + + + QUndoModel + + + <empty> + <tom> + + + + QUndoStack + + + Undo + Fortryd + + + Redo + Gendan + + + + QUnicodeControlCharacterMenu + + + LRM Left-to-right mark + + + + RLM Right-to-left mark + + + + ZWJ Zero width joiner + + + + ZWNJ Zero width non-joiner + + + + ZWSP Zero width space + + + + LRE Start of left-to-right embedding + + + + RLE Start of right-to-left embedding + + + + LRO Start of left-to-right override + + + + RLO Start of right-to-left override + + + + PDF Pop directional formatting + + + + Insert Unicode control character + + + + + QWebFrame + + + Request cancelled + Anmodning annulleret + + + Request blocked + Anmodning blokeret + + + Cannot show URL + Kan ikke vise URL + + + Frame load interruped by policy change + Billedindlæsning afbrudt af ændringer i retningslinier + + + Cannot show mimetype + Kan ikke vise MIME-type + + + File does not exist + Filen findes ikke + + + + QWebPage + + + Bad HTTP request + Dårlig HTTP-anmodning + + + + Submit + default label for Submit buttons in forms on web pages + Send + + + Submit + Submit (input element) alt text for <input> elements with no alt, title, or value + Send + + + Reset + default label for Reset buttons in forms on web pages + Nulstil + + + This is a searchable index. Enter search keywords: + text that appears at the start of nearly-obsolete web pages in the form of a 'searchable index' + Dette er et søgeindeks. Indtast søgeord: + + + Choose File + title for file button used in HTML forms + Vælg fil + + + No file selected + text to display in file button used in HTML forms when no file is selected + Der er ikke valgt en fil + + + Open in New Window + Open in New Window context menu item + Åbn i nyt vindue + + + Save Link... + Download Linked File context menu item + Gem link... + + + Copy Link + Copy Link context menu item + Kopiér link + + + Open Image + Open Image in New Window context menu item + Åbn billede + + + Save Image + Download Image context menu item + Gem billede + + + Copy Image + Copy Link context menu item + Kopiér billede + + + Open Frame + Open Frame in New Window context menu item + Åbn faneblad + + + Copy + Copy context menu item + Kopiér + + + Go Back + Back context menu item + Gå tilbage + + + Go Forward + Forward context menu item + Gå frem + + + Stop + Stop context menu item + Stop + + + Reload + Reload context menu item + Genindlæs + + + Cut + Cut context menu item + Klip + + + Paste + Paste context menu item + Sæt ind + + + No Guesses Found + No Guesses Found context menu item + Der er ikke fundet nogen gæt + + + Ignore + Ignore Spelling context menu item + Ignorér + + + Add To Dictionary + Learn Spelling context menu item + Tilføj til ordbog + + + Search The Web + Search The Web context menu item + Søg på nettet + + + Look Up In Dictionary + Look Up in Dictionary context menu item + Slå op i ordbog + + + Open Link + Open Link context menu item + Åbn link + + + Ignore + Ignore Grammar context menu item + Ignorér + + + Spelling + Spelling and Grammar context sub-menu item + Stavekontrol + + + Show Spelling and Grammar + menu item title + Vis stave- og grammatikkontrol + + + Hide Spelling and Grammar + menu item title + Skjul stave- og grammatikkontrol + + + Check Spelling + Check spelling context menu item + Kør stavekontrol + + + Check Spelling While Typing + Check spelling while typing context menu item + Kør stavekontrol mens der tastes + + + Check Grammar With Spelling + Check grammar with spelling context menu item + Kør grammatikkontrol sammen med stavekontrol + + + Fonts + Font context sub-menu item + Skrifttyper + + + Bold + Bold context menu item + Fed + + + Italic + Italic context menu item + Kursiv + + + Underline + Underline context menu item + Understreget + + + Outline + Outline context menu item + Kontur + + + Direction + Writing direction context sub-menu item + Retning + + + Text Direction + Text direction context sub-menu item + Tekstretning + + + Default + Default writing direction context menu item + Standard + + + LTR + Left to Right context menu item + + + + RTL + Right to Left context menu item + + + + Inspect + Inspect Element context menu item + Inspicér + + + No recent searches + Label for only item in menu that appears when clicking on the search field image, when no searches have been performed + Ingen aktuelle søgninger + + + Recent searches + label for first item in the menu that appears when clicking on the search field image, used as embedded menu title + Aktuelle søgninger + + + Clear recent searches + menu item in Recent Searches menu that empties menu's contents + Ryd aktuelle søgninger + + + Unknown + Unknown filesize FTP directory listing item + Ukendt + + + %1 (%2x%3 pixels) + Title string for images + %1 (%2x%3 pixels) + + + + Web Inspector - %2 + Web-inspektør - %2 + + + + Scroll here + Scroll her + + + Left edge + Venstre kant + + + Top + + + + Right edge + Højre kant + + + Bottom + Bund + + + Page left + Side venstre + + + Page up + Side øverst + + + Page right + Side højre + + + Page down + Side ned + + + Scroll left + Scroll til venstre + + + Scroll up + Scroll op + + + Scroll right + Scroll til højre + + + Scroll down + Scroll ned + + + + %n file(s) + number of chosen file + + %n fil + %n filer + + + + + JavaScript Alert - %1 + JavaScript alert - %1 + + + JavaScript Confirm - %1 + JavaScript Bekræft - %1 + + + JavaScript Prompt - %1 + JavaScript Prompt - %1 + + + Move the cursor to the next character + Flyt markør til næste tegn + + + Move the cursor to the previous character + Flyt markør til forrige tegn + + + Move the cursor to the next word + Flyt markør til næste ord + + + Move the cursor to the previous word + Flyt markør til forrige ord + + + Move the cursor to the next line + Flyt markør til næste linie + + + Move the cursor to the previous line + Flyt markør til forrige linie + + + Move the cursor to the start of the line + Flyt markør til starten af linien + + + Move the cursor to the end of the line + Flyt markør til slutningen af linien + + + Move the cursor to the start of the block + Flyt markør til starten af sektionen + + + Move the cursor to the end of the block + Flyt markør til slutningen af sektionen + + + Move the cursor to the start of the document + Flyt markør til starten af dokumentet + + + Move the cursor to the end of the document + Flyt markør til slutningen af dokumentet + + + Select to the next character + Vælg til næste tegn + + + Select to the previous character + Vælg til forrige tegn + + + Select to the next word + Vælg til næste ord + + + Select to the previous word + Vælg til forrige ord + + + Select to the next line + Vælg til næste linie + + + Select to the previous line + Vælg til forrige linie + + + Select to the start of the line + Vælg til starten af linien + + + Select to the end of the line + Vælg til slutningen af linien + + + Select to the start of the block + Vælg til starten af sektionen + + + Select to the end of the block + Vælg til slutningen af sektionen + + + Select to the start of the document + Vælg til starten af dokumentet + + + Select to the end of the document + Vælg til slutningen af dokumentet + + + Delete to the start of the word + Slet til starten af ordet + + + Delete to the end of the word + Slet til slutningen af ordet + + + + QWhatsThisAction + + + What's This? + Hvad er dette? + + + + QWidget + + + * + + + + + QWizard + + + Go Back + Gå tilbage + + + Continue + Fortsæt + + + Commit + Udfør + + + Done + Færdig + + + Help + Hjælp + + + < &Back + < &Tilbage + + + &Finish + &Afslut + + + Cancel + Annuller + + + &Help + &Hjælp + + + &Next + &Næste + + + &Next > + &Næste > + + + + QWorkspace + + + &Restore + &Gendan + + + &Move + &Flyt + + + &Size + &Størrelse + + + Mi&nimize + Mi&nimér + + + Ma&ximize + Ma&ksimér + + + &Close + &Luk + + + Stay on &Top + Bliv på &toppen + + + Sh&ade + Sk&ygge + + + %1 - [%2] + + + + Minimize + Minimer + + + Restore Down + Gendan ned + + + Close + Luk + + + &Unshade + &Fjern skygge + + + + QXml + + + no error occurred + der opstod ingen fejl + + + error triggered by consumer + + + + unexpected end of file + uventet afslutning på fil + + + more than one document type definition + mere end én definition på dokumenttype + + + error occurred while parsing element + der opstod fejl under fortolking af element + + + tag mismatch + + + + error occurred while parsing content + der opstod fejl under fortolking af indhold + + + unexpected character + uventet tegn + + + invalid name for processing instruction + + + + version expected while reading the XML declaration + version forventet under læsning af XML-deklaration + + + wrong value for standalone declaration + + + + encoding declaration or standalone declaration expected while reading the XML declaration + + + + standalone declaration expected while reading the XML declaration + + + + error occurred while parsing document type definition + der opstod fejl under fortolking af dokumenttypedefinition + + + letter is expected + + + + error occurred while parsing comment + der opstod fejl under fortolking af kommentar + + + error occurred while parsing reference + der opstod fejl under fortolking af reference + + + internal general entity reference not allowed in DTD + + + + external parsed general entity reference not allowed in attribute value + + + + external parsed general entity reference not allowed in DTD + + + + unparsed entity reference in wrong context + ufortolket enhedsreference i forkert kontekst + + + recursive entities + + + + error in the text declaration of an external entity + fejl i tekstdeklaration på en ekstern enhed + + + + QXmlStream + + + Extra content at end of document. + Ekstra indhold sidst i dokumentet. + + + Invalid entity value. + Ugyldig enhedsværdi. + + + Invalid XML character. + Ugyldigt XML-tegn. + + + Sequence ']]>' not allowed in content. + Sekvens ']]>' ikke tilladt i indhold. + + + Namespace prefix '%1' not declared + Navnerumspræfiks '%1' ikke deklareret + + + Attribute redefined. + + + + Unexpected character '%1' in public id literal. + + + + Invalid XML version string. + Ugyldigt XML-versionsstreng. + + + Unsupported XML version. + XML-version understøttes ikke. + + + %1 is an invalid encoding name. + + + + Encoding %1 is unsupported + + + + Standalone accepts only yes or no. + + + + Invalid attribute in XML declaration. + + + + Premature end of document. + + + + Invalid document. + Ugyldigt dokument. + + + Expected + Forventet + + + , but got ' + , men fik ' + + + Unexpected ' + Uventet ' + + + Expected character data. + Forventet tegndata. + + + Recursive entity detected. + + + + Start tag expected. + Start-tag forventet. + + + XML declaration not at start of document. + XML-deklaration ikke i starten af dokumentet. + + + NDATA in parameter entity declaration. + + + + %1 is an invalid processing instruction name. + + + + Invalid processing instruction name. + + + + Illegal namespace declaration. + Ulovligt navnerumsdeklaration. + + + + Invalid XML name. + Ugyldigt XML-navn. + + + Opening and ending tag mismatch. + Åbner og afslutter tag-mismatch. + + + Reference to unparsed entity '%1'. + Reference to ufortolket enhed '%1'. + + + Entity '%1' not declared. + Enheden '%1' ikke deklareret. + + + Reference to external entity '%1' in attribute value. + Reference til ekstern enhed '%1' i attributværdi. + + + Invalid character reference. + Ugyldig tegnreference. + + + Encountered incorrectly encoded content. + + + + The standalone pseudo attribute must appear after the encoding. + + + + + %1 is an invalid PUBLIC identifier. + + + + + QtXmlPatterns + + + An %1-attribute with value %2 has already been declared. + + + + An %1-attribute must have a valid %2 as value, which %3 isn't. + + + + + Network timeout. + + + + + Element %1 can't be serialized because it appears outside the document element. + + + + + Year %1 is invalid because it begins with %2. + + + + Day %1 is outside the range %2..%3. + + + + Month %1 is outside the range %2..%3. + + + + Overflow: Can't represent date %1. + + + + Day %1 is invalid for month %2. + + + + Time 24:%1:%2.%3 is invalid. Hour is 24, but minutes, seconds, and milliseconds are not all 0; + + + + Time %1:%2:%3.%4 is invalid. + + + + Overflow: Date can't be represented. + + + + At least one component must be present. + + + + At least one time component must appear after the %1-delimiter. + + + + + No operand in an integer division, %1, can be %2. + + + + The first operand in an integer division, %1, cannot be infinity (%2). + + + + The second operand in a division, %1, cannot be zero (%2). + + + + + %1 is not a valid value of type %2. + + + + + When casting to %1 from %2, the source value cannot be %3. + + + + + Integer division (%1) by zero (%2) is undefined. + + + + Division (%1) by zero (%2) is undefined. + + + + Modulus division (%1) by zero (%2) is undefined. + + + + Dividing a value of type %1 by %2 (not-a-number) is not allowed. + + + + Dividing a value of type %1 by %2 or %3 (plus or minus zero) is not allowed. + + + + Multiplication of a value of type %1 by %2 or %3 (plus or minus infinity) is not allowed. + + + + + A value of type %1 cannot have an Effective Boolean Value. + + + + + Effective Boolean Value cannot be calculated for a sequence containing two or more atomic values. + + + + + Value %1 of type %2 exceeds maximum (%3). + + + + Value %1 of type %2 is below minimum (%3). + + + + + A value of type %1 must contain an even number of digits. The value %2 does not. + + + + %1 is not valid as a value of type %2. + + + + + Operator %1 cannot be used on type %2. + + + + Operator %1 cannot be used on atomic values of type %2 and %3. + + + + + The namespace URI in the name for a computed attribute cannot be %1. + + + + The name for a computed attribute cannot have the namespace URI %1 with the local name %2. + + + + + Type error in cast, expected %1, received %2. + + + + When casting to %1 or types derived from it, the source value must be of the same type, or it must be a string literal. Type %2 is not allowed. + + + + + No casting is possible with %1 as the target type. + + + + It is not possible to cast from %1 to %2. + + + + Casting to %1 is not possible because it is an abstract type, and can therefore never be instantiated. + + + + It's not possible to cast the value %1 of type %2 to %3 + + + + Failure when casting from %1 to %2: %3 + + + + + A comment cannot contain %1 + + + + A comment cannot end with a %1. + + + + + No comparisons can be done involving the type %1. + + + + Operator %1 is not available between atomic values of type %2 and %3. + + + + + An attribute node cannot be a child of a document node. Therefore, the attribute %1 is out of place. + + + + + A library module cannot be evaluated directly. It must be imported from a main module. + + + + No template by name %1 exists. + + + + + A value of type %1 cannot be a predicate. A predicate must have either a numeric type or an Effective Boolean Value type. + + + + A positional predicate must evaluate to a single numeric value. + + + + + The target name in a processing instruction cannot be %1 in any combination of upper and lower case. Therefore, is %2 invalid. + + + + %1 is not a valid target name in a processing instruction. It must be a %2 value, e.g. %3. + + + + + The last step in a path must contain either nodes or atomic values. It cannot be a mixture between the two. + + + + + The data of a processing instruction cannot contain the string %1 + + + + + No namespace binding exists for the prefix %1 + + + + + No namespace binding exists for the prefix %1 in %2 + + + + + %1 is an invalid %2 + + + + + %1 takes at most %n argument(s). %2 is therefore invalid. + + + + + + + %1 requires at least %n argument(s). %2 is therefore invalid. + + + + + + + + The first argument to %1 cannot be of type %2. It must be a numeric type, xs:yearMonthDuration or xs:dayTimeDuration. + + + + The first argument to %1 cannot be of type %2. It must be of type %3, %4, or %5. + + + + The second argument to %1 cannot be of type %2. It must be of type %3, %4, or %5. + + + + + %1 is not a valid XML 1.0 character. + + + + + The first argument to %1 cannot be of type %2. + + + + + If both values have zone offsets, they must have the same zone offset. %1 and %2 are not the same. + + + + + %1 was called. + + + + + %1 must be followed by %2 or %3, not at the end of the replacement string. + + + + In the replacement string, %1 must be followed by at least one digit when not escaped. + + + + In the replacement string, %1 can only be used to escape itself or %2, not %3 + + + + + %1 matches newline characters + + + + %1 and %2 match the start and end of a line. + + + + Matches are case insensitive + + + + Whitespace characters are removed, except when they appear in character classes + + + + %1 is an invalid regular expression pattern: %2 + + + + %1 is an invalid flag for regular expressions. Valid flags are: + + + + + If the first argument is the empty sequence or a zero-length string (no namespace), a prefix cannot be specified. Prefix %1 was specified. + + + + + It will not be possible to retrieve %1. + + + + + The root node of the second argument to function %1 must be a document node. %2 is not a document node. + + + + + The default collection is undefined + + + + %1 cannot be retrieved + + + + + The normalization form %1 is unsupported. The supported forms are %2, %3, %4, and %5, and none, i.e. the empty string (no normalization). + + + + + A zone offset must be in the range %1..%2 inclusive. %3 is out of range. + + + + %1 is not a whole number of minutes. + + + + + Required cardinality is %1; got cardinality %2. + + + + + The item %1 did not match the required type %2. + + + + %1 is an unknown schema type. + + + + Only one %1 declaration can occur in the query prolog. + + + + The initialization of variable %1 depends on itself + + + + No variable by name %1 exists + + + + + The variable %1 is unused + + + + + Version %1 is not supported. The supported XQuery version is 1.0. + + + + The encoding %1 is invalid. It must contain Latin characters only, must not contain whitespace, and must match the regular expression %2. + + + + No function with signature %1 is available + + + + A default namespace declaration must occur before function, variable, and option declarations. + + + + Namespace declarations must occur before function, variable, and option declarations. + + + + Module imports must occur before function, variable, and option declarations. + + + + It is not possible to redeclare prefix %1. + + + + Prefix %1 is already declared in the prolog. + + + + The name of an option must have a prefix. There is no default namespace for options. + + + + The Schema Import feature is not supported, and therefore %1 declarations cannot occur. + + + + The target namespace of a %1 cannot be empty. + + + + The module import feature is not supported + + + + No value is available for the external variable by name %1. + + + + A construct was encountered which only is allowed in XQuery. + + + + A template by name %1 has already been declared. + + + + The keyword %1 cannot occur with any other mode name. + + + + The value of attribute %1 must of type %2, which %3 isn't. + + + + The prefix %1 can not be bound. By default, it is already bound to the namespace %2. + + + + A variable by name %1 has already been declared. + + + + A stylesheet function must have a prefixed name. + + + + The namespace for a user defined function cannot be empty (try the predefined prefix %1 which exists for cases like this) + + + + The namespace %1 is reserved; therefore user defined functions may not use it. Try the predefined prefix %2, which exists for these cases. + + + + The namespace of a user defined function in a library module must be equivalent to the module namespace. In other words, it should be %1 instead of %2 + + + + A function already exists with the signature %1. + + + + No external functions are supported. All supported functions can be used directly, without first declaring them as external + + + + An argument by name %1 has already been declared. Every argument name must be unique. + + + + When function %1 is used for matching inside a pattern, the argument must be a variable reference or a string literal. + + + + In an XSL-T pattern, the first argument to function %1 must be a string literal, when used for matching. + + + + In an XSL-T pattern, the first argument to function %1 must be a literal or a variable reference, when used for matching. + + + + In an XSL-T pattern, function %1 cannot have a third argument. + + + + In an XSL-T pattern, only function %1 and %2, not %3, can be used for matching. + + + + In an XSL-T pattern, axis %1 cannot be used, only axis %2 or %3 can. + + + + %1 is an invalid template mode name. + + + + The name of a variable bound in a for-expression must be different from the positional variable. Hence, the two variables named %1 collide. + + + + The Schema Validation Feature is not supported. Hence, %1-expressions may not be used. + + + + None of the pragma expressions are supported. Therefore, a fallback expression must be present + + + + Each name of a template parameter must be unique; %1 is duplicated. + + + + The %1-axis is unsupported in XQuery + + + + %1 is not a valid name for a processing-instruction. + + + + %1 is not a valid numeric literal. + + + + No function by name %1 is available. + + + + The namespace URI cannot be the empty string when binding to a prefix, %1. + + + + %1 is an invalid namespace URI. + + + + It is not possible to bind to the prefix %1 + + + + Namespace %1 can only be bound to %2 (and it is, in either case, pre-declared). + + + + Prefix %1 can only be bound to %2 (and it is, in either case, pre-declared). + + + + Two namespace declaration attributes have the same name: %1. + + + + The namespace URI must be a constant and cannot use enclosed expressions. + + + + An attribute by name %1 has already appeared on this element. + + + + A direct element constructor is not well-formed. %1 is ended with %2. + + + + The name %1 does not refer to any schema type. + + + + %1 is an complex type. Casting to complex types is not possible. However, casting to atomic types such as %2 works. + + + + %1 is not an atomic type. Casting is only possible to atomic types. + + + + %1 is not in the in-scope attribute declarations. Note that the schema import feature is not supported. + + + + The name of an extension expression must be in a namespace. + + + + + empty + + + + zero or one + + + + exactly one + + + + one or more + + + + zero or more + + + + + Required type is %1, but %2 was found. + + + + Promoting %1 to %2 may cause loss of precision. + + + + The focus is undefined. + + + + + It's not possible to add attributes after any other kind of node. + + + + An attribute by name %1 has already been created. + + + + + Only the Unicode Codepoint Collation is supported(%1). %2 is unsupported. + + + + + Attribute %1 can't be serialized because it appears at the top level. + + + + + %1 is an unsupported encoding. + + + + %1 contains octets which are disallowed in the requested encoding %2. + + + + The codepoint %1, occurring in %2 using encoding %3, is an invalid XML character. + + + + + Ambiguous rule match. + + + + + In a namespace constructor, the value for a namespace value cannot be an empty string. + + + + The prefix must be a valid %1, which %2 is not. + + + + The prefix %1 cannot be bound. + + + + Only the prefix %1 can be bound to %2 and vice versa. + + + + + Circularity detected + + + + + The parameter %1 is required, but no corresponding %2 is supplied. + + + + The parameter %1 is passed, but no corresponding %2 exists. + + + + + The URI cannot have a fragment + + + + + Element %1 is not allowed at this location. + + + + Text nodes are not allowed at this location. + + + + Parse error: %1 + + + + The value of the XSL-T version attribute must be a value of type %1, which %2 isn't. + + + + Running an XSL-T 1.0 stylesheet with a 2.0 processor. + + + + Unknown XSL-T attribute %1. + + + + Attribute %1 and %2 are mutually exclusive. + + + + In a simplified stylesheet module, attribute %1 must be present. + + + + If element %1 has no attribute %2, it cannot have attribute %3 or %4. + + + + Element %1 must have at least one of the attributes %2 or %3. + + + + At least one mode must be specified in the %1-attribute on element %2. + + + + + Attribute %1 cannot appear on the element %2. Only the standard attributes can appear. + + + + Attribute %1 cannot appear on the element %2. Only %3 is allowed, and the standard attributes. + + + + Attribute %1 cannot appear on the element %2. Allowed is %3, %4, and the standard attributes. + + + + Attribute %1 cannot appear on the element %2. Allowed is %3, and the standard attributes. + + + + XSL-T attributes on XSL-T elements must be in the null namespace, not in the XSL-T namespace which %1 is. + + + + The attribute %1 must appear on element %2. + + + + The element with local name %1 does not exist in XSL-T. + + + + + Element %1 must come last. + + + + At least one %1-element must occur before %2. + + + + Only one %1-element can appear. + + + + At least one %1-element must occur inside %2. + + + + When attribute %1 is present on %2, a sequence constructor cannot be used. + + + + Element %1 must have either a %2-attribute or a sequence constructor. + + + + When a parameter is required, a default value cannot be supplied through a %1-attribute or a sequence constructor. + + + + Element %1 cannot have children. + + + + Element %1 cannot have a sequence constructor. + + + + The attribute %1 cannot appear on %2, when it is a child of %3. + + + + A parameter in a function cannot be declared to be a tunnel. + + + + This processor is not Schema-aware and therefore %1 cannot be used. + + + + Top level stylesheet elements must be in a non-null namespace, which %1 isn't. + + + + The value for attribute %1 on element %2 must either be %3 or %4, not %5. + + + + Attribute %1 cannot have the value %2. + + + + The attribute %1 can only appear on the first %2 element. + + + + At least one %1 element must appear as child of %2. + + + + + VolumeSlider + + + Muted + + + + Volume: %1% + Lydstyrke: %1% + + + diff --git a/translations/qt_help_da.ts b/translations/qt_help_da.ts new file mode 100644 index 0000000..0e4a362 --- /dev/null +++ b/translations/qt_help_da.ts @@ -0,0 +1,354 @@ + + + + + QCLuceneResultWidget + + + Search Results + Søgeresultater + + + + Note: + Bemærk: + + + + The search results may not be complete since the documentation is still being indexed! + Søgeresultaterne kan være ufuldstændige, fordi dokumentationen stadig indekseres! + + + + Your search did not match any documents. + Søgningen matchede ikke nogen dokumenter. + + + + (The reason for this might be that the documentation is still being indexed.) + (Årsagen kan være, at dokumentationen stadig indekseres.) + + + + QHelpCollectionHandler + + + The collection file is not set up yet! + Hjælpesamlingen er ikke konfigureret endnu! + + + + Cannot open collection file: %1 + Kan ikke åbne hjælpesamlingen: %1 + + + + Cannot create tables in file %1! + Kan ikke oprette tabler i filen %1! + + + + The specified collection file already exists! + Den angivne hjælpesamling findes allerede! + + + + Cannot create directory: %1 + Kan ikke oprette kataloget: %1 + + + + Cannot copy collection file: %1 + Kan ikke kopiere hjælpesamling: %1 + + + + Unknown filter! + Ukendt filter! + + + + Cannot register filter %1! + Kan ikke registrere filteret %1! + + + + Cannot open documentation file %1! + Kan ikke åbne dokumentationsfilen %1! + + + + Invalid documentation file! + Ugyldig dokumentationsfil! + + + + The namespace %1 was not registered! + Navnerummet %1 blev ikke registreret! + + + + Namespace %1 already exists! + Navnerummet %1 findes allerede! + + + + Cannot register namespace! + Kan ikke registrere navnerummet! + + + + Cannot open database to optimize! + Kan ikke åbne den database, der skal optimeres! + + + + QHelpDBReader + + + Cannot open DB! + Kan ikke åbne DB! + + + + QHelpEngineCore + + + The specified namespace does not exist! + Det angivne navnerum findes ikke! + + + + QHelpEngineCorePrivate + + + Cannot open collection file %1! + Kan ikke åbne hjælpesamlingen %1! + + + + Cannot open documentation file %1! + Kan ikke åbne dokumentationsfilen %1! + + + + QHelpGenerator + + + Invalid help data! + Ugyldigt hjælpedata! + + + + No output file name specified! + Der er ikke anført et output-filnavn! + + + + The file %1 already exists! + Filen %1 findes allerede! + + + + Building up file structure... + Bygger filstruktur... + + + + Cannot open DB! + Kan ikke åbne DB! + + + + Cannot register namespace %1! + Kan ikke registrere navnerummet %1! + + + + Insert custom filters... + Indsæt brugerdefinerede filtre... + + + + Insert help data for filter section (%1 of %2)... + Indsæt hjælpedata til filtersektion (%1 af %2)... + + + + Documentation successfully generated. + Dokumentationen blev genereret. + + + + Some tables already exist! + Nogle af tabellerne findes allerede! + + + + Cannot create tables! + Kan ikke oprette tabeller! + + + + Cannot register virtual folder! + Kan ikke registrere virtuel mappe! + + + + Insert files... + Indsæt filer... + + + + The file %1 does not exist! Skipping it. + Filen %1 findes ikke, og den springes over. + + + + Cannot open file %1! Skipping it. + Kan ikke åbne filen %1, og den springes over. + + + + Cannot insert file data into database! + Kan ikke indsætte fildata i databasen! + + + + The filter %1 is already registered! + Filtret %1 er allerede registreret! + + + + Cannot register filter %1! + Kan ikke registrere filtret %1! + + + + Insert indices... + Indsæt indeks... + + + + Insert contents... + Indsæt indhold... + + + + Cannot insert contents! + Kan ikke indsætte indhold! + + + + Cannot register contents! + Kan ikke registrere indhold! + + + + QHelpSearchQueryWidget + + + Search for: + Søg efter: + + + + Search + Søg + + + + Advanced search + Avanceret søgning + + + + words <B>similar</B> to: + ord <B>tilsvarende</B>: + + + + <B>without</B> the words: + <B>uden</B> ordene: + + + + with <B>exact phrase</B>: + med den <B>eksakte sætning</B>: + + + + with <B>all</B> of the words: + med <B>alle</B> ordene: + + + + with <B>at least one</B> of the words: + med <B>mindst ét</B> af ordene: + + + + QHelpSearchResultWidget + + + 0 - 0 of 0 Hits + 0 - 0 af 0 Hits + + + + QHelpSearchResultWidgetPrivate + + + %1 - %2 of %3 Hits + %1 - %2 af %3 Hits + + + + QObject + + + Untitled + Ingen titel + + + + Unknown token at line %1. + Ukendt symbol på linie %1. + + + + Unknown token at line %1. Expected "QtHelpProject"! + Ukendt symbol på linie %1. Forventet "QtHelpProject"! + + + + A virtual folder must not contain a '/' character! + En virtuel mappe må ikke indholde tegnet '/'! + + + + A namespace must not contain a '/' character! + Et navnerum må ikke indeholde tegnet '/'! + + + + Missing namespace in QtHelpProject. + Navnerum i +++ mangler. + + + + Missing virtual folder in QtHelpProject + Virtuel mappe i QtHelpProject mangler + + + + Missing attribute in keyword at line %1. + Attribut i nøgleord på linie %1 mangler. + + + + The input file %1 could not be opened! + Input-filen %1 kunne ikke åbnes! + + + -- cgit v0.12 From d94ed47b7748826fc2b9fba774cce51a54c24880 Mon Sep 17 00:00:00 2001 From: Bill King Date: Thu, 21 May 2009 11:44:19 +1000 Subject: Fixes conditional jump on uninitialised value As found by valgrind. Also add error reporting that was missing. Reviewed-by: Justin McPherson --- src/sql/drivers/oci/qsql_oci.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/sql/drivers/oci/qsql_oci.cpp b/src/sql/drivers/oci/qsql_oci.cpp index d63c482..a7031b1 100644 --- a/src/sql/drivers/oci/qsql_oci.cpp +++ b/src/sql/drivers/oci/qsql_oci.cpp @@ -1789,7 +1789,7 @@ bool QOCIResult::prepare(const QString& query) bool QOCIResult::exec() { int r = 0; - ub2 stmtType; + ub2 stmtType=0; ub4 iters; ub4 mode; QList tmpStorage; @@ -1803,6 +1803,16 @@ bool QOCIResult::exec() OCI_ATTR_STMT_TYPE, d->err); + if (r != OCI_SUCCESS && r != OCI_SUCCESS_WITH_INFO) { + qOraWarning("QOCIResult::exec: Unable to get statement type:", d->err); + setLastError(qMakeError(QCoreApplication::translate("QOCIResult", + "Unable to get statement type"), QSqlError::StatementError, d->err)); +#ifdef QOCI_DEBUG + qDebug() << "lastQuery()" << lastQuery(); +#endif + return false; + } + if (stmtType == OCI_STMT_SELECT) { iters = 0; mode = OCI_DEFAULT; -- cgit v0.12 From 2cb36aed053147ecc91f72ed76074962a66b76f0 Mon Sep 17 00:00:00 2001 From: Jason McDonald Date: Thu, 21 May 2009 14:08:02 +1000 Subject: Fix build regression caused by ba5fb9f05c891feac8ab69006189de1aaafebc18. The previous "fix" caused the effect of the line before the change to be discarded, which breaks the mac binary package builds. When reviewing changes, please read the lines of context given in the patch - they are included for a reason. Acked-by: Lincoln Ramsay Acked-by: Rohan McGovern --- configure | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure b/configure index 20bf457..c882b29 100755 --- a/configure +++ b/configure @@ -2717,7 +2717,7 @@ if [ "$PLATFORM_MAC" = "yes" ]; then # Build commmand line arguments we can pass to the compiler during configure tests # by prefixing each arch with "-arch". CFG_MAC_ARCHS_GCC_FORMAT="${CFG_MAC_ARCHS/x86/i386}" - CFG_MAC_ARCHS_GCC_FORMAT="${CFG_MAC_ARCHS/i386_64/x86_64}" + CFG_MAC_ARCHS_GCC_FORMAT="${CFG_MAC_ARCHS_GCC_FORMAT/i386_64/x86_64}" for ARCH in $CFG_MAC_ARCHS_GCC_FORMAT; do MAC_ARCHS_COMMANDLINE="$MAC_ARCHS_COMMANDLINE -arch $ARCH" done -- cgit v0.12 From 7383e03bfd473f6e79718f3da7d504977a677541 Mon Sep 17 00:00:00 2001 From: Bill King Date: Thu, 21 May 2009 14:27:27 +1000 Subject: Fixes one of the fields of mysql bound params not initialised. Found by valgrind, value isn't set but is used, fixes this. Reviewed-by: Justin McPherson --- src/sql/drivers/mysql/qsql_mysql.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/sql/drivers/mysql/qsql_mysql.cpp b/src/sql/drivers/mysql/qsql_mysql.cpp index 51fc306..53645c9 100644 --- a/src/sql/drivers/mysql/qsql_mysql.cpp +++ b/src/sql/drivers/mysql/qsql_mysql.cpp @@ -927,6 +927,7 @@ bool QMYSQLResult::exec() nullVector[i] = static_cast(val.isNull()); currBind->is_null = &nullVector[i]; currBind->length = 0; + currBind->is_unsigned = 0; switch (val.type()) { case QVariant::ByteArray: @@ -973,7 +974,6 @@ bool QMYSQLResult::exec() currBind->buffer_type = MYSQL_TYPE_DOUBLE; currBind->buffer = data; currBind->buffer_length = sizeof(double); - currBind->is_unsigned = 0; break; case QVariant::LongLong: case QVariant::ULongLong: @@ -989,7 +989,6 @@ bool QMYSQLResult::exec() currBind->buffer_type = MYSQL_TYPE_STRING; currBind->buffer = const_cast(ba.constData()); currBind->buffer_length = ba.length(); - currBind->is_unsigned = 0; break; } } } -- cgit v0.12 From b0078f00058f8d2a9fbe4742f52386a866b2bd97 Mon Sep 17 00:00:00 2001 From: Jason McDonald Date: Thu, 21 May 2009 17:04:38 +1000 Subject: Fix missing/outdated license headers. Reviewed-by: Trust Me --- examples/animation/sub-attaq/boat_p.h | 13 +++- examples/animation/sub-attaq/submarine_p.h | 13 +++- examples/statemachine/tankgame/gameitem.cpp | 41 +++++++++++ examples/statemachine/tankgame/gameitem.h | 41 +++++++++++ .../statemachine/tankgame/gameovertransition.cpp | 45 +++++++++++- .../statemachine/tankgame/gameovertransition.h | 41 +++++++++++ examples/statemachine/tankgame/main.cpp | 41 +++++++++++ examples/statemachine/tankgame/mainwindow.cpp | 81 ++++++++++++++++------ examples/statemachine/tankgame/mainwindow.h | 45 +++++++++++- examples/statemachine/tankgame/plugin.h | 41 +++++++++++ examples/statemachine/tankgame/rocketitem.cpp | 43 +++++++++++- examples/statemachine/tankgame/rocketitem.h | 44 +++++++++++- examples/statemachine/tankgame/tankitem.cpp | 73 ++++++++++++++----- examples/statemachine/tankgame/tankitem.h | 47 ++++++++++++- .../tankgameplugins/random_ai/random_ai_plugin.cpp | 41 +++++++++++ .../tankgameplugins/random_ai/random_ai_plugin.h | 43 +++++++++++- .../tankgameplugins/seek_ai/seek_ai.cpp | 57 ++++++++++++--- .../statemachine/tankgameplugins/seek_ai/seek_ai.h | 61 +++++++++++++--- .../tankgameplugins/spin_ai/spin_ai.cpp | 51 ++++++++++++-- .../statemachine/tankgameplugins/spin_ai/spin_ai.h | 45 +++++++++++- .../spin_ai_with_error/spin_ai_with_error.cpp | 49 +++++++++++-- .../spin_ai_with_error/spin_ai_with_error.h | 45 +++++++++++- src/gui/statemachine/qbasickeyeventtransition.cpp | 34 ++++++++- src/gui/statemachine/qbasickeyeventtransition_p.h | 34 ++++++++- .../statemachine/qbasicmouseeventtransition.cpp | 34 ++++++++- .../statemachine/qbasicmouseeventtransition_p.h | 34 ++++++++- src/gui/statemachine/qguistatemachine.cpp | 36 +++++++++- src/gui/statemachine/qkeyeventtransition.cpp | 34 ++++++++- src/gui/statemachine/qkeyeventtransition.h | 34 ++++++++- src/gui/statemachine/qmouseeventtransition.cpp | 34 ++++++++- src/gui/statemachine/qmouseeventtransition.h | 34 ++++++++- 31 files changed, 1209 insertions(+), 100 deletions(-) diff --git a/examples/animation/sub-attaq/boat_p.h b/examples/animation/sub-attaq/boat_p.h index c934bc5..a8a24a6 100644 --- a/examples/animation/sub-attaq/boat_p.h +++ b/examples/animation/sub-attaq/boat_p.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the QtCore module of the Qt Toolkit. +** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage @@ -42,6 +42,17 @@ #ifndef BOAT_P_H #define BOAT_P_H +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + //Own #include "bomb.h" #include "graphicsscene.h" diff --git a/examples/animation/sub-attaq/submarine_p.h b/examples/animation/sub-attaq/submarine_p.h index 561af4a..8c31eb7 100644 --- a/examples/animation/sub-attaq/submarine_p.h +++ b/examples/animation/sub-attaq/submarine_p.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the QtCore module of the Qt Toolkit. +** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage @@ -42,6 +42,17 @@ #ifndef SUBMARINE_P_H #define SUBMARINE_P_H +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + //Own #include "animationmanager.h" #include "submarine.h" diff --git a/examples/statemachine/tankgame/gameitem.cpp b/examples/statemachine/tankgame/gameitem.cpp index 1a2af71..ad8b37c 100644 --- a/examples/statemachine/tankgame/gameitem.cpp +++ b/examples/statemachine/tankgame/gameitem.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "gameitem.h" #include diff --git a/examples/statemachine/tankgame/gameitem.h b/examples/statemachine/tankgame/gameitem.h index 33caf71..90b0a6c 100644 --- a/examples/statemachine/tankgame/gameitem.h +++ b/examples/statemachine/tankgame/gameitem.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef GAMEITEM_H #define GAMEITEM_H diff --git a/examples/statemachine/tankgame/gameovertransition.cpp b/examples/statemachine/tankgame/gameovertransition.cpp index cec786e..360e902 100644 --- a/examples/statemachine/tankgame/gameovertransition.cpp +++ b/examples/statemachine/tankgame/gameovertransition.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "gameovertransition.h" #include "tankitem.h" @@ -8,7 +49,7 @@ GameOverTransition::GameOverTransition(QAbstractState *targetState) : QSignalTransition(new QSignalMapper(), SIGNAL(mapped(QObject*))) { setTargetState(targetState); - + QSignalMapper *mapper = qobject_cast(senderObject()); mapper->setParent(this); } @@ -36,4 +77,4 @@ bool GameOverTransition::eventTest(QEvent *e) } else { return false; } -} \ No newline at end of file +} diff --git a/examples/statemachine/tankgame/gameovertransition.h b/examples/statemachine/tankgame/gameovertransition.h index 9a86b83..5e99a75 100644 --- a/examples/statemachine/tankgame/gameovertransition.h +++ b/examples/statemachine/tankgame/gameovertransition.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef GAMEOVERTRANSITION_H #define GAMEOVERTRANSITION_H diff --git a/examples/statemachine/tankgame/main.cpp b/examples/statemachine/tankgame/main.cpp index 26fc1bb..185ad68 100644 --- a/examples/statemachine/tankgame/main.cpp +++ b/examples/statemachine/tankgame/main.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include #include "mainwindow.h" diff --git a/examples/statemachine/tankgame/mainwindow.cpp b/examples/statemachine/tankgame/mainwindow.cpp index 3437140..46e0db3 100644 --- a/examples/statemachine/tankgame/mainwindow.cpp +++ b/examples/statemachine/tankgame/mainwindow.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "mainwindow.h" #include "tankitem.h" #include "rocketitem.h" @@ -97,7 +138,7 @@ void MainWindow::init() addWall(QRectF(centerOfMap - QPointF(-50.0, -60.0), centerOfMap - QPointF(50.0, -50.0))); addWall(QRectF(centerOfMap + QPointF(-50.0, -50.0), centerOfMap + QPointF(-40.0, 50.0))); addWall(QRectF(centerOfMap - QPointF(-50.0, -50.0), centerOfMap - QPointF(-40.0, 50.0))); - + addWall(QRectF(sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, -10.0), sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, 100.0))); addWall(QRectF(sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, 10.0), @@ -108,18 +149,18 @@ void MainWindow::init() sceneRect.topRight() + QPointF(-100.0, sceneRect.height() / 2.0 + 5.0))); - QAction *addTankAction = menuBar()->addAction("&Add tank"); - QAction *runGameAction = menuBar()->addAction("&Run game"); + QAction *addTankAction = menuBar()->addAction("&Add tank"); + QAction *runGameAction = menuBar()->addAction("&Run game"); runGameAction->setObjectName("runGameAction"); - QAction *stopGameAction = menuBar()->addAction("&Stop game"); + QAction *stopGameAction = menuBar()->addAction("&Stop game"); menuBar()->addSeparator(); QAction *quitAction = menuBar()->addAction("&Quit"); - + connect(addTankAction, SIGNAL(triggered()), this, SLOT(addTank())); connect(quitAction, SIGNAL(triggered()), this, SLOT(close())); - - m_machine = new QStateMachine(this); - QState *stoppedState = new QState(m_machine->rootState()); + + m_machine = new QStateMachine(this); + QState *stoppedState = new QState(m_machine->rootState()); stoppedState->setObjectName("stoppedState"); stoppedState->assignProperty(runGameAction, "enabled", true); stoppedState->assignProperty(stopGameAction, "enabled", false); @@ -127,19 +168,19 @@ void MainWindow::init() m_machine->setInitialState(stoppedState); //! [5] - QState *spawnsAvailable = new QState(stoppedState); + QState *spawnsAvailable = new QState(stoppedState); spawnsAvailable->assignProperty(addTankAction, "enabled", true); - QState *noSpawnsAvailable = new QState(stoppedState); + QState *noSpawnsAvailable = new QState(stoppedState); noSpawnsAvailable->assignProperty(addTankAction, "enabled", false); -//! [5] +//! [5] spawnsAvailable->setObjectName("spawnsAvailable"); noSpawnsAvailable->setObjectName("noSpawnsAvailable"); spawnsAvailable->addTransition(this, SIGNAL(mapFull()), noSpawnsAvailable); //! [3] - QHistoryState *hs = new QHistoryState(stoppedState); + QHistoryState *hs = new QHistoryState(stoppedState); hs->setDefaultState(spawnsAvailable); //! [3] hs->setObjectName("hs"); @@ -158,7 +199,7 @@ void MainWindow::init() gameOverState->setObjectName("gameOverState"); gameOverState->assignProperty(stopGameAction, "enabled", false); connect(gameOverState, SIGNAL(entered()), this, SLOT(gameOver())); - + stoppedState->addTransition(runGameAction, SIGNAL(triggered()), m_runningState); m_runningState->addTransition(stopGameAction, SIGNAL(triggered()), stoppedState); @@ -168,12 +209,12 @@ void MainWindow::init() QTimer *timer = new QTimer(this); timer->setInterval(100); connect(timer, SIGNAL(timeout()), this, SLOT(runStep())); - connect(m_runningState, SIGNAL(entered()), timer, SLOT(start())); + connect(m_runningState, SIGNAL(entered()), timer, SLOT(start())); connect(m_runningState, SIGNAL(exited()), timer, SLOT(stop())); m_machine->start(); m_time.start(); -} +} void MainWindow::runStep() { @@ -206,7 +247,7 @@ void MainWindow::gameOver() } } - QMessageBox::information(this, "Game over!", + QMessageBox::information(this, "Game over!", QString::fromLatin1("The tank played by '%1' has won!").arg(lastTankStanding->objectName())); } @@ -216,7 +257,7 @@ void MainWindow::addRocket() if (tankItem != 0) { RocketItem *rocketItem = new RocketItem; - QPointF s = tankItem->mapToScene(QPointF(tankItem->boundingRect().right() + 10.0, + QPointF s = tankItem->mapToScene(QPointF(tankItem->boundingRect().right() + 10.0, tankItem->boundingRect().center().y())); rocketItem->setPos(s); rocketItem->setDirection(tankItem->direction()); @@ -264,10 +305,10 @@ void MainWindow::addTank() bool ok; //! [1] - QString selectedName = QInputDialog::getItem(this, "Select a tank type", "Tank types", + QString selectedName = QInputDialog::getItem(this, "Select a tank type", "Tank types", itemNames, 0, false, &ok); //! [1] - + if (ok && !selectedName.isEmpty()) { int idx = itemNames.indexOf(selectedName); if (Plugin *plugin = idx >= 0 ? items.at(idx) : 0) { @@ -280,7 +321,7 @@ void MainWindow::addTank() emit mapFull(); m_gameOverTransition->addTankItem(tankItem); - + QState *region = new QState(m_runningState); region->setObjectName(QString::fromLatin1("region%1").arg(m_spawns.size())); //! [2] diff --git a/examples/statemachine/tankgame/mainwindow.h b/examples/statemachine/tankgame/mainwindow.h index 391ab77..4ae8f7a 100644 --- a/examples/statemachine/tankgame/mainwindow.h +++ b/examples/statemachine/tankgame/mainwindow.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef MAINWINDOW_H #define MAINWINDOW_H @@ -37,14 +78,14 @@ private: void addWall(const QRectF &wall); QGraphicsScene *m_scene; - + QStateMachine *m_machine; QState *m_runningState; GameOverTransition *m_gameOverTransition; QList m_spawns; QTime m_time; - + bool m_started : 1; }; diff --git a/examples/statemachine/tankgame/plugin.h b/examples/statemachine/tankgame/plugin.h index 006ad78..ddd10b7 100644 --- a/examples/statemachine/tankgame/plugin.h +++ b/examples/statemachine/tankgame/plugin.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef PLUGIN_H #define PLUGIN_H diff --git a/examples/statemachine/tankgame/rocketitem.cpp b/examples/statemachine/tankgame/rocketitem.cpp index c324980..3ace8e8 100644 --- a/examples/statemachine/tankgame/rocketitem.cpp +++ b/examples/statemachine/tankgame/rocketitem.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "rocketitem.h" #include "tankitem.h" @@ -53,7 +94,7 @@ void RocketItem::idle(qreal elapsed) if (tankItem != 0) tankItem->hitByRocket(); } - + scene()->removeItem(this); delete this; } diff --git a/examples/statemachine/tankgame/rocketitem.h b/examples/statemachine/tankgame/rocketitem.h index 189a1dd..31146a6 100644 --- a/examples/statemachine/tankgame/rocketitem.h +++ b/examples/statemachine/tankgame/rocketitem.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef ROCKETITEM_H #define ROCKETITEM_H @@ -12,7 +53,7 @@ public: virtual void idle(qreal elapsed); qreal speed() const { return 100.0; } void setDirection(qreal direction) { m_direction = direction; } - + protected: virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); QRectF boundingRect() const; @@ -22,5 +63,4 @@ private: qreal m_distance; }; - #endif diff --git a/examples/statemachine/tankgame/tankitem.cpp b/examples/statemachine/tankgame/tankitem.cpp index c322d21..393d65f 100644 --- a/examples/statemachine/tankgame/tankitem.cpp +++ b/examples/statemachine/tankgame/tankitem.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "tankitem.h" #include @@ -35,15 +76,15 @@ public: m_reverse = m_distance < 0.0; } - bool apply(qreal timeDelta) + bool apply(qreal timeDelta) { qreal dist = timeDelta * item()->speed() * (m_reverse ? -1.0 : 1.0); - bool done = false; - if (qAbs(m_distance) < qAbs(dist)) { + bool done = false; + if (qAbs(m_distance) < qAbs(dist)) { done = true; dist = m_distance; - } + } m_distance -= dist; qreal a = item()->direction() * M_PI / 180.0; @@ -69,14 +110,14 @@ public: m_reverse = m_distance < 0.0; } - bool apply(qreal timeDelta) + bool apply(qreal timeDelta) { qreal dist = timeDelta * item()->angularSpeed() * (m_reverse ? -1.0 : 1.0); - bool done = false; + bool done = false; if (qAbs(m_distance) < qAbs(dist)) { done = true; dist = m_distance; - } + } m_distance -= dist; item()->setDirection(item()->direction() + dist); @@ -88,7 +129,7 @@ private: bool m_reverse; }; -TankItem::TankItem(QObject *parent) +TankItem::TankItem(QObject *parent) : GameItem(parent), m_currentAction(0), m_currentDirection(0.0), m_enabled(true) { connect(this, SIGNAL(cannonFired()), this, SIGNAL(actionCompleted())); @@ -106,7 +147,7 @@ void TankItem::idle(qreal elapsed) QGraphicsItem *item = 0; qreal distance = distanceToObstacle(&item); if (TankItem *tankItem = qgraphicsitem_cast(item)) - emit tankSpotted(tankItem->direction(), distance); + emit tankSpotted(tankItem->direction(), distance); } } } @@ -119,7 +160,7 @@ void TankItem::hitByRocket() void TankItem::setAction(Action *newAction) { - if (m_currentAction != 0) + if (m_currentAction != 0) delete m_currentAction; m_currentAction = newAction; @@ -184,9 +225,9 @@ void TankItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidge QRectF cannonBase = brect.adjusted(10.0, 6.0, -12.0, -6.0); painter->drawEllipse(cannonBase); - painter->drawRect(QRectF(QPointF(cannonBase.center().x(), cannonBase.center().y() - 2.0), + painter->drawRect(QRectF(QPointF(cannonBase.center().x(), cannonBase.center().y() - 2.0), QPointF(brect.right(), cannonBase.center().y() + 2.0))); - + // left track painter->setBrush(QBrush(Qt::black, Qt::VerPattern)); QRectF leftTrackRect = QRectF(brect.topLeft(), QPointF(brect.right() - 2.0, brect.top() + 4.0)); @@ -223,7 +264,7 @@ qreal TankItem::direction() const void TankItem::setDirection(qreal newDirection) { - int fullRotations = int(newDirection) / 360; + int fullRotations = int(newDirection) / 360; newDirection -= fullRotations * 360.0; qreal diff = newDirection - m_currentDirection; @@ -245,8 +286,8 @@ qreal TankItem::distanceToObstacle(QGraphicsItem **obstacle) const QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); if (collidedItem != 0) { if (obstacle != 0) - *obstacle = collidedItem; - + *obstacle = collidedItem; + QPointF d = nextPosition - pos(); return sqrt(pow(d.x(), 2) + pow(d.y(), 2)); } else { @@ -259,5 +300,3 @@ qreal TankItem::distanceToObstacle() const return distanceToObstacle(0); } - - diff --git a/examples/statemachine/tankgame/tankitem.h b/examples/statemachine/tankgame/tankitem.h index 9475397..942fca8 100644 --- a/examples/statemachine/tankgame/tankitem.h +++ b/examples/statemachine/tankgame/tankitem.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef TANKITEM_H #define TANKITEM_H @@ -12,9 +53,9 @@ class TankItem: public GameItem Q_PROPERTY(bool enabled READ enabled WRITE setEnabled) Q_PROPERTY(qreal direction READ direction WRITE turnTo) Q_PROPERTY(qreal distanceToObstacle READ distanceToObstacle) -public: +public: TankItem(QObject *parent = 0); - + void setColor(const QColor &color) { m_color = color; } QColor color() const { return m_color; } @@ -53,7 +94,7 @@ public slots: //! [0] protected: - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); private: diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp index c196247..d360de9 100644 --- a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "random_ai_plugin.h" #include diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h index f5e3b6f..9faeeac 100644 --- a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef RANDOM_AI_PLUGIN_H #define RANDOM_AI_PLUGIN_H @@ -19,7 +60,7 @@ signals: void moveForwardsSelected(); void moveBackwardsSelected(); void turnSelected(); - + protected: void onEntry(QEvent *) { diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp index 2fb05d4..6aae015 100644 --- a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp +++ b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "seek_ai.h" QState *SeekAi::create(QState *parentState, QObject *tank) @@ -12,10 +53,10 @@ QState *SeekAi::create(QState *parentState, QObject *tank) QState *lookForNearestWall = new SearchState(tank, seek); lookForNearestWall->setObjectName("lookForNearestWall"); seek->setInitialState(lookForNearestWall); - + QState *driveToFirstObstacle = new QState(seek); driveToFirstObstacle->setObjectName("driveToFirstObstacle"); - lookForNearestWall->addTransition(lookForNearestWall, SIGNAL(nearestObstacleStraightAhead()), + lookForNearestWall->addTransition(lookForNearestWall, SIGNAL(nearestObstacleStraightAhead()), driveToFirstObstacle); QState *drive = new QState(driveToFirstObstacle); @@ -23,25 +64,25 @@ QState *SeekAi::create(QState *parentState, QObject *tank) driveToFirstObstacle->setInitialState(drive); connect(drive, SIGNAL(entered()), tank, SLOT(moveForwards())); connect(drive, SIGNAL(exited()), tank, SLOT(stop())); - + // Go in loop QState *finishedDriving = new QState(driveToFirstObstacle); finishedDriving->setObjectName("finishedDriving"); drive->addTransition(tank, SIGNAL(actionCompleted()), finishedDriving); finishedDriving->addTransition(drive); - + QState *turnTo = new QState(seek); turnTo->setObjectName("turnTo"); driveToFirstObstacle->addTransition(new CollisionTransition(tank, turnTo)); - + turnTo->addTransition(tank, SIGNAL(actionCompleted()), driveToFirstObstacle); ChaseState *chase = new ChaseState(tank, topLevel); - chase->setObjectName("chase"); - seek->addTransition(new TankSpottedTransition(tank, chase)); + chase->setObjectName("chase"); + seek->addTransition(new TankSpottedTransition(tank, chase)); chase->addTransition(chase, SIGNAL(finished()), driveToFirstObstacle); chase->addTransition(new TankSpottedTransition(tank, chase)); - + return topLevel; } diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h index 9d4aabc..e44ad07 100644 --- a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h +++ b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef SEEK_AI_H #define SEEK_AI_H @@ -15,18 +56,18 @@ class SearchState: public QState { Q_OBJECT public: - SearchState(QObject *tank, QState *parentState = 0) - : QState(parentState), - m_tank(tank), - m_distanceToTurn(360.0), + SearchState(QObject *tank, QState *parentState = 0) + : QState(parentState), + m_tank(tank), + m_distanceToTurn(360.0), m_nearestDistance(-1.0), - m_directionOfNearestObstacle(0.0) + m_directionOfNearestObstacle(0.0) { } public slots: void turnAlittle() - { + { qreal dist = m_tank->property("distanceToObstacle").toDouble(); if (m_nearestDistance < 0.0 || dist < m_nearestDistance) { @@ -72,7 +113,7 @@ private: class CollisionTransition: public QSignalTransition { public: - CollisionTransition(QObject *tank, QState *turnTo) + CollisionTransition(QObject *tank, QState *turnTo) : QSignalTransition(tank, SIGNAL(collision(QLineF))), m_tank(tank), m_turnTo(turnTo) @@ -99,7 +140,7 @@ protected: if (qrand() % 2 == 0) newDirection = angleOfWall; else - newDirection = angleOfWall - 180.0; + newDirection = angleOfWall - 180.0; m_turnTo->assignProperty(m_tank, "direction", newDirection); } @@ -115,7 +156,7 @@ class ChaseState: public QState class GoToLocationState: public QState { public: - GoToLocationState(QObject *tank, QState *parentState = 0) + GoToLocationState(QObject *tank, QState *parentState = 0) : QState(parentState), m_tank(tank), m_distance(0.0) { } @@ -123,7 +164,7 @@ class ChaseState: public QState void setDistance(qreal distance) { m_distance = distance; } protected: - void onEntry() + void onEntry() { QMetaObject::invokeMethod(m_tank, "moveForwards", Q_ARG(qreal, m_distance)); } diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp index de95f41..581a6b2 100644 --- a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp +++ b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "spin_ai.h" #include @@ -5,24 +46,24 @@ QState *SpinAi::create(QState *parentState, QObject *tank) { QState *topLevel = new QState(parentState); - QState *spinState = new SpinState(tank, topLevel); + QState *spinState = new SpinState(tank, topLevel); topLevel->setInitialState(spinState); // When tank is spotted, fire two times and go back to spin state QState *fireState = new QState(topLevel); QState *fireOnce = new QState(fireState); - fireState->setInitialState(fireOnce); + fireState->setInitialState(fireOnce); connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); QState *fireTwice = new QState(fireState); connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); - + fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); - + spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); - + return topLevel; } diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h index d8d3d73..652e8b8 100644 --- a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h +++ b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef SPIN_AI_H #define SPIN_AI_H @@ -16,7 +57,7 @@ public: } public slots: - void spin() + void spin() { m_tank->setProperty("direction", m_tank->property("direction").toDouble() + 90.0); } @@ -25,7 +66,7 @@ protected: void onEntry(QEvent *) { connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); - spin(); + spin(); } void onExit(QEvent *) diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp index 5499ba3..19137b2 100644 --- a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp +++ b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "spin_ai_with_error.h" #include @@ -5,7 +46,7 @@ QState *SpinAiWithError::create(QState *parentState, QObject *tank) { QState *topLevel = new QState(parentState); - QState *spinState = new SpinState(tank, topLevel); + QState *spinState = new SpinState(tank, topLevel); topLevel->setInitialState(spinState); // When tank is spotted, fire two times and go back to spin state @@ -17,12 +58,12 @@ QState *SpinAiWithError::create(QState *parentState, QObject *tank) QState *fireTwice = new QState(fireState); connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); - + fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); - + spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); - + return topLevel; } diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h index 456ba01..e040bf2 100644 --- a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h +++ b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef SPIN_AI_WITH_ERROR_H #define SPIN_AI_WITH_ERROR_H @@ -16,7 +57,7 @@ public: } public slots: - void spin() + void spin() { m_tank->setProperty("direction", m_tank->property("direction").toDouble() + 90.0); } @@ -25,7 +66,7 @@ protected: void onEntry(QEvent *) { connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); - spin(); + spin(); } void onExit(QEvent *) diff --git a/src/gui/statemachine/qbasickeyeventtransition.cpp b/src/gui/statemachine/qbasickeyeventtransition.cpp index fe89f81..f7f1eb6 100644 --- a/src/gui/statemachine/qbasickeyeventtransition.cpp +++ b/src/gui/statemachine/qbasickeyeventtransition.cpp @@ -3,9 +3,39 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/statemachine/qbasickeyeventtransition_p.h b/src/gui/statemachine/qbasickeyeventtransition_p.h index c4ff863..39fa6ad 100644 --- a/src/gui/statemachine/qbasickeyeventtransition_p.h +++ b/src/gui/statemachine/qbasickeyeventtransition_p.h @@ -3,9 +3,39 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/statemachine/qbasicmouseeventtransition.cpp b/src/gui/statemachine/qbasicmouseeventtransition.cpp index a18d1e8..20dd792 100644 --- a/src/gui/statemachine/qbasicmouseeventtransition.cpp +++ b/src/gui/statemachine/qbasicmouseeventtransition.cpp @@ -3,9 +3,39 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/statemachine/qbasicmouseeventtransition_p.h b/src/gui/statemachine/qbasicmouseeventtransition_p.h index 6a3ad1e..6c0afe4 100644 --- a/src/gui/statemachine/qbasicmouseeventtransition_p.h +++ b/src/gui/statemachine/qbasicmouseeventtransition_p.h @@ -3,9 +3,39 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/statemachine/qguistatemachine.cpp b/src/gui/statemachine/qguistatemachine.cpp index b7563d7..612e43e 100644 --- a/src/gui/statemachine/qguistatemachine.cpp +++ b/src/gui/statemachine/qguistatemachine.cpp @@ -1,11 +1,41 @@ - /**************************************************************************** +/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/statemachine/qkeyeventtransition.cpp b/src/gui/statemachine/qkeyeventtransition.cpp index 0418501..f803711 100644 --- a/src/gui/statemachine/qkeyeventtransition.cpp +++ b/src/gui/statemachine/qkeyeventtransition.cpp @@ -3,9 +3,39 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/statemachine/qkeyeventtransition.h b/src/gui/statemachine/qkeyeventtransition.h index 08c4800..3c8295f 100644 --- a/src/gui/statemachine/qkeyeventtransition.h +++ b/src/gui/statemachine/qkeyeventtransition.h @@ -3,9 +3,39 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/statemachine/qmouseeventtransition.cpp b/src/gui/statemachine/qmouseeventtransition.cpp index ae3c407..e4e18eb 100644 --- a/src/gui/statemachine/qmouseeventtransition.cpp +++ b/src/gui/statemachine/qmouseeventtransition.cpp @@ -3,9 +3,39 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/statemachine/qmouseeventtransition.h b/src/gui/statemachine/qmouseeventtransition.h index aedc5c2..3f5f3ac 100644 --- a/src/gui/statemachine/qmouseeventtransition.h +++ b/src/gui/statemachine/qmouseeventtransition.h @@ -3,9 +3,39 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ -- cgit v0.12 From c29b54fc517be2ddff32a1c6df3a886993b786ab Mon Sep 17 00:00:00 2001 From: Jason McDonald Date: Thu, 21 May 2009 18:35:14 +1000 Subject: Fix compile error caused by reference to non-existant example. Reviewed-by: Trust Me --- examples/animation/animation.pro | 1 - 1 file changed, 1 deletion(-) diff --git a/examples/animation/animation.pro b/examples/animation/animation.pro index d51a89d..9a2874b 100644 --- a/examples/animation/animation.pro +++ b/examples/animation/animation.pro @@ -5,7 +5,6 @@ SUBDIRS += \ appchooser \ easing \ moveblocks \ - padnavigator-ng \ states \ stickman \ sub-attaq -- cgit v0.12 From 252d48a53c11734f308e9505c6015a7c4906f75c Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Fri, 22 May 2009 08:55:15 +1000 Subject: webview test runs. --- .../visual/webview/autosize/data/opengl/image0.png | Bin 5396 -> 0 bytes .../visual/webview/autosize/data/opengl/manifest.xml | 4 ---- .../visual/webview/autosize/data/raster/image0.png | Bin 0 -> 4820 bytes .../visual/webview/autosize/data/raster/manifest.qml | 6 ++++++ 4 files changed, 6 insertions(+), 4 deletions(-) delete mode 100644 tests/auto/declarative/visual/webview/autosize/data/opengl/image0.png delete mode 100644 tests/auto/declarative/visual/webview/autosize/data/opengl/manifest.xml create mode 100644 tests/auto/declarative/visual/webview/autosize/data/raster/image0.png create mode 100644 tests/auto/declarative/visual/webview/autosize/data/raster/manifest.qml diff --git a/tests/auto/declarative/visual/webview/autosize/data/opengl/image0.png b/tests/auto/declarative/visual/webview/autosize/data/opengl/image0.png deleted file mode 100644 index 351a7b7..0000000 Binary files a/tests/auto/declarative/visual/webview/autosize/data/opengl/image0.png and /dev/null differ diff --git a/tests/auto/declarative/visual/webview/autosize/data/opengl/manifest.xml b/tests/auto/declarative/visual/webview/autosize/data/opengl/manifest.xml deleted file mode 100644 index b784f42..0000000 --- a/tests/auto/declarative/visual/webview/autosize/data/opengl/manifest.xml +++ /dev/null @@ -1,4 +0,0 @@ - - - - diff --git a/tests/auto/declarative/visual/webview/autosize/data/raster/image0.png b/tests/auto/declarative/visual/webview/autosize/data/raster/image0.png new file mode 100644 index 0000000..206952d Binary files /dev/null and b/tests/auto/declarative/visual/webview/autosize/data/raster/image0.png differ diff --git a/tests/auto/declarative/visual/webview/autosize/data/raster/manifest.qml b/tests/auto/declarative/visual/webview/autosize/data/raster/manifest.qml new file mode 100644 index 0000000..6d900f5 --- /dev/null +++ b/tests/auto/declarative/visual/webview/autosize/data/raster/manifest.qml @@ -0,0 +1,6 @@ +TestLog { + TestFullFrame { + time: 0 + frameId: 0 + } +} -- cgit v0.12 From 4ea52386e0281700e6143e0ba946314e7dd30608 Mon Sep 17 00:00:00 2001 From: Anders Bakken Date: Thu, 21 May 2009 16:03:41 -0700 Subject: Removed warning Explicitly cast to integer. Reviewed-by: Shane McLaughlin --- src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp b/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp index 989a37a..a68bc8f 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp +++ b/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp @@ -383,7 +383,7 @@ void QDirectFBPaintEngine::clip(const QVectorPath &path, Qt::ClipOperation op) { Q_D(QDirectFBPaintEngine); d->dirtyClip = true; - const QPoint bottom = d->transform.map(QPoint(0, path.controlPointRect().y2)); + const QPoint bottom = d->transform.map(QPoint(0, int(path.controlPointRect().y2))); if (bottom.y() >= d->lastLockedHeight) d->lock(); QRasterPaintEngine::clip(path, op); -- cgit v0.12 From 6b7c7d6f0b0330571a6868f53d27a30132d4b736 Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Wed, 20 May 2009 16:57:08 +0200 Subject: Use QTest::ignoreMessage() instead of custom implementation Since QTest::ignoreMessage() already exists, we should use this instead of implementing an ad hoc solution that does the same. --- tests/auto/qstatemachine/tst_qstatemachine.cpp | 66 ++++++-------------------- 1 file changed, 14 insertions(+), 52 deletions(-) diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index d033869..6b219d2 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -212,32 +212,12 @@ protected: } }; -static QtMsgType s_msgType; -static QByteArray s_msg; -static bool s_countWarnings; -static QtMsgHandler s_oldHandler; - -static void defaultErrorStateTestMessageHandler(QtMsgType type, const char *msg) -{ - s_msgType = type; - s_msg = msg; - - if (s_countWarnings) - s_oldHandler(type, msg); -} - void tst_QStateMachine::init() { - s_msg = QByteArray(); - s_msgType = QtDebugMsg; - s_countWarnings = true; - - s_oldHandler = qInstallMsgHandler(defaultErrorStateTestMessageHandler); } void tst_QStateMachine::cleanup() { - qInstallMsgHandler(s_oldHandler); } class EventTransition : public QAbstractTransition @@ -256,14 +236,13 @@ private: void tst_QStateMachine::transitionToRootState() { - s_countWarnings = false; - QStateMachine machine; QState *initialState = new QState(); machine.addState(initialState); machine.setInitialState(initialState); + QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::setTargetStates: root state cannot be target of transition"); initialState->addTransition(new EventTransition(QEvent::User, machine.rootState())); machine.start(); @@ -346,8 +325,6 @@ void tst_QStateMachine::transitionEntersParent() void tst_QStateMachine::defaultErrorState() { - s_countWarnings = false; // we expect warnings here - QStateMachine machine; QVERIFY(machine.errorState() != 0); @@ -360,14 +337,12 @@ void tst_QStateMachine::defaultErrorState() QState *childState = new QState(brokenState); childState->setObjectName("childState"); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'MyInitialState'"); + // initialState has no initial state machine.start(); QCoreApplication::processEvents(); - QCOMPARE(s_msgType, QtWarningMsg); - QCOMPARE(QString::fromLatin1(s_msg.data()), - QString::fromLatin1("Unrecoverable error detected in running state machine: Missing initial state in compound state 'MyInitialState'")); - QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'MyInitialState'")); @@ -436,8 +411,6 @@ void tst_QStateMachine::customGlobalErrorState() QCOMPARE(customErrorState->errorString, QString::fromLatin1("Missing initial state in compound state 'brokenState'")); QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'brokenState'")); - QVERIFY(s_msg.isEmpty()); - QCOMPARE(s_msgType, QtDebugMsg); } void tst_QStateMachine::customLocalErrorStateInBrokenState() @@ -453,7 +426,7 @@ void tst_QStateMachine::customLocalErrorStateInBrokenState() QState *brokenState = new QState(); brokenState->setObjectName("brokenState"); - machine.addState(brokenState); + machine.addState(brokenState); brokenState->setErrorState(customErrorState); QState *childState = new QState(brokenState); @@ -461,7 +434,7 @@ void tst_QStateMachine::customLocalErrorStateInBrokenState() initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - machine.start(); + machine.start(); QCoreApplication::processEvents(); machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); @@ -470,19 +443,17 @@ void tst_QStateMachine::customLocalErrorStateInBrokenState() QCOMPARE(machine.configuration().count(), 1); QVERIFY(machine.configuration().contains(customErrorState)); QCOMPARE(customErrorState->error, QStateMachine::NoInitialStateError); - QVERIFY(s_msg.isEmpty()); } void tst_QStateMachine::customLocalErrorStateInOtherState() { - s_countWarnings = false; - QStateMachine machine; CustomErrorState *customErrorState = new CustomErrorState(&machine); machine.addState(customErrorState); QState *initialState = new QState(); initialState->setObjectName("initialState"); + QTest::ignoreMessage(QtWarningMsg, "QState::setErrorState: error state cannot belong to a different state machine"); initialState->setErrorState(customErrorState); machine.addState(initialState); machine.setInitialState(initialState); @@ -497,6 +468,7 @@ void tst_QStateMachine::customLocalErrorStateInOtherState() initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'brokenState'"); machine.start(); QCoreApplication::processEvents(); @@ -505,7 +477,6 @@ void tst_QStateMachine::customLocalErrorStateInOtherState() QCOMPARE(machine.configuration().count(), 1); QVERIFY(machine.configuration().contains(machine.errorState())); - QCOMPARE(s_msgType, QtWarningMsg); } void tst_QStateMachine::customLocalErrorStateInParentOfBrokenState() @@ -541,7 +512,6 @@ void tst_QStateMachine::customLocalErrorStateInParentOfBrokenState() QCOMPARE(machine.configuration().count(), 1); QVERIFY(machine.configuration().contains(customErrorState)); - QVERIFY(s_msg.isEmpty()); } void tst_QStateMachine::customLocalErrorStateOverridesParent() @@ -583,7 +553,6 @@ void tst_QStateMachine::customLocalErrorStateOverridesParent() QVERIFY(machine.configuration().contains(customErrorStateForBrokenState)); QCOMPARE(customErrorStateForBrokenState->error, QStateMachine::NoInitialStateError); QCOMPARE(customErrorStateForParent->error, QStateMachine::NoError); - QVERIFY(s_msg.isEmpty()); } void tst_QStateMachine::errorStateHasChildren() @@ -622,14 +591,11 @@ void tst_QStateMachine::errorStateHasChildren() QCOMPARE(machine.configuration().count(), 2); QVERIFY(machine.configuration().contains(customErrorState)); QVERIFY(machine.configuration().contains(childOfErrorState)); - QVERIFY(s_msg.isEmpty()); } void tst_QStateMachine::errorStateHasErrors() { - s_countWarnings = false; - QStateMachine machine; CustomErrorState *customErrorState = new CustomErrorState(&machine); customErrorState->setObjectName("customErrorState"); @@ -659,21 +625,19 @@ void tst_QStateMachine::errorStateHasErrors() QCoreApplication::processEvents(); machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'customErrorState'"); QCoreApplication::processEvents(); QCOMPARE(machine.configuration().count(), 1); QVERIFY(machine.configuration().contains(oldErrorState)); // Fall back to default QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'customErrorState'")); - - QCOMPARE(s_msgType, QtWarningMsg); } void tst_QStateMachine::errorStateIsRootState() { - s_countWarnings = false; - QStateMachine machine; + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::setErrorState: root state cannot be error state"); machine.setErrorState(machine.rootState()); QState *initialState = new QState(); @@ -694,6 +658,7 @@ void tst_QStateMachine::errorStateIsRootState() QCoreApplication::processEvents(); machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'brokenState'"); QCoreApplication::processEvents(); QCOMPARE(machine.configuration().count(), 1); @@ -774,8 +739,6 @@ void tst_QStateMachine::errorStateEntersParentFirst() void tst_QStateMachine::customErrorStateIsNull() { - s_countWarnings = false; - QStateMachine machine; QAbstractState *oldErrorState = machine.errorState(); machine.rootState()->setErrorState(0); @@ -794,12 +757,12 @@ void tst_QStateMachine::customErrorStateIsNull() QCoreApplication::processEvents(); machine.postEvent(new QEvent(QEvent::User)); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state ''"); QCoreApplication::processEvents(); QCOMPARE(machine.errorState(), reinterpret_cast(0)); QCOMPARE(machine.configuration().count(), 1); QVERIFY(machine.configuration().contains(oldErrorState)); - QCOMPARE(s_msgType, QtWarningMsg); } void tst_QStateMachine::clearError() @@ -924,8 +887,6 @@ void tst_QStateMachine::brokenStateIsNeverEntered() void tst_QStateMachine::transitionToStateNotInGraph() { - s_countWarnings = false; - QStateMachine machine; QState *initialState = new QState(machine.rootState()); @@ -937,6 +898,7 @@ void tst_QStateMachine::transitionToStateNotInGraph() initialState->addTransition(&independentState); machine.start(); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: No common ancestor for targets and source of transition from state 'initialState'"); QCoreApplication::processEvents(); QCOMPARE(machine.configuration().count(), 1); @@ -945,12 +907,11 @@ void tst_QStateMachine::transitionToStateNotInGraph() void tst_QStateMachine::customErrorStateNotInGraph() { - s_countWarnings = false; - QStateMachine machine; QState errorState; errorState.setObjectName("errorState"); + QTest::ignoreMessage(QtWarningMsg, "QState::setErrorState: error state cannot belong to a different state machine"); machine.setErrorState(&errorState); QVERIFY(&errorState != machine.errorState()); @@ -960,6 +921,7 @@ void tst_QStateMachine::customErrorStateNotInGraph() new QState(initialBrokenState); machine.start(); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'initialBrokenState'"); QCoreApplication::processEvents(); QCOMPARE(machine.configuration().count(), 1); -- cgit v0.12 From c8e632f96a942590ab9936d136dcf2f7eb17fef8 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Fri, 22 May 2009 10:01:35 +0200 Subject: configure script fix, -h should display help and not just h. Reviewed-by:cduclos --- configure | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/configure b/configure index c882b29..32efd86 100755 --- a/configure +++ b/configure @@ -202,7 +202,7 @@ earlyArgParse() VAL=$1 fi ;; - h|help|--help|-help) + -h|help|--help|-help) if [ "$VAL" = "yes" ]; then OPT_HELP="$VAL" COMMERCIAL_USER="no" #doesn't matter we will display the help -- cgit v0.12 From ab1b7f137350d6eeafec2a64e3c25a4b02be65a9 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Fri, 22 May 2009 10:05:11 +0200 Subject: Enabled the use of promoted widgets in new form templates. The form builder used for preview of the templates did not implement custom widget handling (FormBuilder::createCustomWidgets()). On encountering a promoted widget, the widget factory would then create a Widget Database entry specifying QWidget inheritance (emergency fallback) which could not be overidden later on. To fix this, moved the code for handling custom widgets from QDesignerResource to QSimpleResource and create a new formbuilder class that handles it especially for the New Form Dialog preview. Task-number: 254282 --- .../components/formeditor/qdesigner_resource.cpp | 121 +------------------ tools/designer/src/lib/shared/newformwidget.cpp | 5 +- .../src/lib/shared/qdesigner_formbuilder.cpp | 14 +++ .../src/lib/shared/qdesigner_formbuilder_p.h | 17 ++- tools/designer/src/lib/shared/qsimpleresource.cpp | 133 +++++++++++++++++++++ tools/designer/src/lib/shared/qsimpleresource_p.h | 17 +++ 6 files changed, 183 insertions(+), 124 deletions(-) diff --git a/tools/designer/src/components/formeditor/qdesigner_resource.cpp b/tools/designer/src/components/formeditor/qdesigner_resource.cpp index 75a53b7..5f53ae2 100644 --- a/tools/designer/src/components/formeditor/qdesigner_resource.cpp +++ b/tools/designer/src/components/formeditor/qdesigner_resource.cpp @@ -743,26 +743,6 @@ void QDesignerResource::setSaveRelative(bool relative) m_resourceBuilder->setSaveRelative(relative); } -static bool addFakeMethods(const DomSlots *domSlots, QStringList &fakeSlots, QStringList &fakeSignals) -{ - if (!domSlots) - return false; - - bool rc = false; - foreach (const QString &fakeSlot, domSlots->elementSlot()) - if (fakeSlots.indexOf(fakeSlot) == -1) { - fakeSlots += fakeSlot; - rc = true; - } - - foreach (const QString &fakeSignal, domSlots->elementSignal()) - if (fakeSignals.indexOf(fakeSignal) == -1) { - fakeSignals += fakeSignal; - rc = true; - } - return rc; -} - QWidget *QDesignerResource::create(DomUI *ui, QWidget *parentWidget) { // Load extra info extension. This is used by Jambi for preventing @@ -1425,108 +1405,9 @@ DomLayoutItem *QDesignerResource::createDom(QLayoutItem *item, DomLayout *ui_lay return ui_item; } -static void addFakeMethodsToWidgetDataBase(const DomCustomWidget *domCustomWidget, WidgetDataBaseItem *item) -{ - const DomSlots *domSlots = domCustomWidget->elementSlots(); - if (!domSlots) - return; - - // Merge in new slots, signals - QStringList fakeSlots = item->fakeSlots(); - QStringList fakeSignals = item->fakeSignals(); - if (addFakeMethods(domSlots, fakeSlots, fakeSignals)) { - item->setFakeSlots(fakeSlots); - item->setFakeSignals(fakeSignals); - } -} - -void QDesignerResource::addCustomWidgetsToWidgetDatabase(DomCustomWidgetList& custom_widget_list) -{ - // Perform one iteration of adding the custom widgets to the database, - // looking up the base class and inheriting its data. - // Remove the succeeded custom widgets from the list. - // Classes whose base class could not be found are left in the list. - QDesignerWidgetDataBaseInterface *db = m_formWindow->core()->widgetDataBase(); - for (int i=0; i < custom_widget_list.size(); ) { - bool classInserted = false; - DomCustomWidget *custom_widget = custom_widget_list[i]; - const QString customClassName = custom_widget->elementClass(); - const QString base_class = custom_widget->elementExtends(); - QString includeFile; - IncludeType includeType = IncludeLocal; - if (const DomHeader *header = custom_widget->elementHeader()) { - includeFile = header->text(); - if (header->hasAttributeLocation() && header->attributeLocation() == QLatin1String("global")) - includeType = IncludeGlobal; - } - const bool domIsContainer = custom_widget->elementContainer(); - // Append a new item - if (base_class.isEmpty()) { - WidgetDataBaseItem *item = new WidgetDataBaseItem(customClassName); - item->setPromoted(false); - item->setGroup(QApplication::translate("Designer", "Custom Widgets")); - item->setIncludeFile(buildIncludeFile(includeFile, includeType)); - item->setContainer(domIsContainer); - item->setCustom(true); - addFakeMethodsToWidgetDataBase(custom_widget, item); - db->append(item); - custom_widget_list.removeAt(i); - classInserted = true; - } else { - // Create a new entry cloned from base class. Note that this will ignore existing - // classes, eg, plugin custom widgets. - QDesignerWidgetDataBaseItemInterface *item = - appendDerived(db, customClassName, QApplication::translate("Designer", "Promoted Widgets"), - base_class, - buildIncludeFile(includeFile, includeType), - true,true); - // Ok, base class found. - if (item) { - // Hack to accommodate for old UI-files in which "contains" is not set properly: - // Apply "contains" from DOM only if true (else, eg classes from QFrame might not accept - // dropping child widgets on them as container=false). This also allows for - // QWidget-derived stacked pages. - if (domIsContainer) - item->setContainer(domIsContainer); - - addFakeMethodsToWidgetDataBase(custom_widget, static_cast(item)); - custom_widget_list.removeAt(i); - classInserted = true; - } - } - // Skip failed item. - if (!classInserted) - i++; - } - -} void QDesignerResource::createCustomWidgets(DomCustomWidgets *dom_custom_widgets) { - if (dom_custom_widgets == 0) - return; - DomCustomWidgetList custom_widget_list = dom_custom_widgets->elementCustomWidget(); - // Attempt to insert each item derived from its base class. - // This should at most require two iterations in the event that the classes are out of order - // (derived first, max depth: promoted custom plugin = 2) - for (int iteration = 0; iteration < 2; iteration++) { - addCustomWidgetsToWidgetDatabase(custom_widget_list); - if (custom_widget_list.empty()) - return; - } - // Oops, there are classes left whose base class could not be found. - // Default them to QWidget with warnings. - const QString fallBackBaseClass = QLatin1String("QWidget"); - for (int i=0; i < custom_widget_list.size(); i++ ) { - DomCustomWidget *custom_widget = custom_widget_list[i]; - const QString customClassName = custom_widget->elementClass(); - const QString base_class = custom_widget->elementExtends(); - qDebug() << "** WARNING The base class " << base_class << " of the custom widget class " << customClassName - << " could not be found. Defaulting to " << fallBackBaseClass << '.'; - custom_widget->setElementExtends(fallBackBaseClass); - } - // One more pass. - addCustomWidgetsToWidgetDatabase(custom_widget_list); - Q_ASSERT(custom_widget_list.empty()); + QSimpleResource::handleDomCustomWidgets(core(), dom_custom_widgets); } DomTabStops *QDesignerResource::saveTabStops() diff --git a/tools/designer/src/lib/shared/newformwidget.cpp b/tools/designer/src/lib/shared/newformwidget.cpp index d79d77a..503e597 100644 --- a/tools/designer/src/lib/shared/newformwidget.cpp +++ b/tools/designer/src/lib/shared/newformwidget.cpp @@ -310,9 +310,8 @@ QImage NewFormWidget::grabForm(QDesignerFormEditorInterface *core, const QString &workingDir, const qdesigner_internal::DeviceProfile &dp) { - qdesigner_internal::QDesignerFormBuilder formBuilder(core, - qdesigner_internal::QDesignerFormBuilder::DisableScripts, - dp); + qdesigner_internal::NewFormWidgetFormBuilder + formBuilder(core, qdesigner_internal::QDesignerFormBuilder::DisableScripts, dp); if (!workingDir.isEmpty()) formBuilder.setWorkingDirectory(workingDir); diff --git a/tools/designer/src/lib/shared/qdesigner_formbuilder.cpp b/tools/designer/src/lib/shared/qdesigner_formbuilder.cpp index 6394847..b92a48d 100644 --- a/tools/designer/src/lib/shared/qdesigner_formbuilder.cpp +++ b/tools/designer/src/lib/shared/qdesigner_formbuilder.cpp @@ -473,6 +473,20 @@ QPixmap QDesignerFormBuilder::createPreviewPixmap(const QDesignerFormWindowInter return rc; } +// ---------- NewFormWidgetFormBuilder + +NewFormWidgetFormBuilder::NewFormWidgetFormBuilder(QDesignerFormEditorInterface *core, + Mode mode, + const DeviceProfile &deviceProfile) : + QDesignerFormBuilder(core, mode, deviceProfile) +{ +} + +void NewFormWidgetFormBuilder::createCustomWidgets(DomCustomWidgets *dc) +{ + QSimpleResource::handleDomCustomWidgets(core(), dc); +} + } // namespace qdesigner_internal QT_END_NAMESPACE diff --git a/tools/designer/src/lib/shared/qdesigner_formbuilder_p.h b/tools/designer/src/lib/shared/qdesigner_formbuilder_p.h index b982e1c..ee40085 100644 --- a/tools/designer/src/lib/shared/qdesigner_formbuilder_p.h +++ b/tools/designer/src/lib/shared/qdesigner_formbuilder_p.h @@ -75,7 +75,7 @@ namespace qdesigner_internal { class DesignerPixmapCache; class DesignerIconCache; -/* Form builder used for previewing forms, widget box and new form dialog. +/* Form builder used for previewing forms and widget box. * It applies the system settings to its toplevel window. */ class QDESIGNER_SHARED_EXPORT QDesignerFormBuilder: public QFormBuilder @@ -159,6 +159,21 @@ private: bool m_mainWidget; }; +// Form builder for a new form widget (preview). To allow for promoted +// widgets in the template, it implements the handling of custom widgets +// (adding of them to the widget database). + +class QDESIGNER_SHARED_EXPORT NewFormWidgetFormBuilder: public QDesignerFormBuilder { +public: + NewFormWidgetFormBuilder(QDesignerFormEditorInterface *core, + Mode mode, + const DeviceProfile &deviceProfile = DeviceProfile()); + +protected: + virtual void createCustomWidgets(DomCustomWidgets *); +}; + + } // namespace qdesigner_internal QT_END_NAMESPACE diff --git a/tools/designer/src/lib/shared/qsimpleresource.cpp b/tools/designer/src/lib/shared/qsimpleresource.cpp index 8d29002..69d48fd 100644 --- a/tools/designer/src/lib/shared/qsimpleresource.cpp +++ b/tools/designer/src/lib/shared/qsimpleresource.cpp @@ -41,6 +41,7 @@ #include "qsimpleresource_p.h" #include "widgetfactory_p.h" +#include "widgetdatabase_p.h" #include #include @@ -57,6 +58,8 @@ #include #include #include +#include + QT_BEGIN_NAMESPACE @@ -267,6 +270,136 @@ bool QSimpleResource::warningsEnabled() return m_warningsEnabled; } +// Custom widgets handling helpers + +// Add unique fake slots and signals to lists +bool QSimpleResource::addFakeMethods(const DomSlots *domSlots, QStringList &fakeSlots, QStringList &fakeSignals) +{ + if (!domSlots) + return false; + + bool rc = false; + foreach (const QString &fakeSlot, domSlots->elementSlot()) + if (fakeSlots.indexOf(fakeSlot) == -1) { + fakeSlots += fakeSlot; + rc = true; + } + + foreach (const QString &fakeSignal, domSlots->elementSignal()) + if (fakeSignals.indexOf(fakeSignal) == -1) { + fakeSignals += fakeSignal; + rc = true; + } + return rc; +} + +void QSimpleResource::addFakeMethodsToWidgetDataBase(const DomCustomWidget *domCustomWidget, WidgetDataBaseItem *item) +{ + const DomSlots *domSlots = domCustomWidget->elementSlots(); + if (!domSlots) + return; + + // Merge in new slots, signals + QStringList fakeSlots = item->fakeSlots(); + QStringList fakeSignals = item->fakeSignals(); + if (addFakeMethods(domSlots, fakeSlots, fakeSignals)) { + item->setFakeSlots(fakeSlots); + item->setFakeSignals(fakeSignals); + } +} + +// Perform one iteration of adding the custom widgets to the database, +// looking up the base class and inheriting its data. +// Remove the succeeded custom widgets from the list. +// Classes whose base class could not be found are left in the list. + +void QSimpleResource::addCustomWidgetsToWidgetDatabase(const QDesignerFormEditorInterface *core, + QList& custom_widget_list) +{ + QDesignerWidgetDataBaseInterface *db = core->widgetDataBase(); + for (int i=0; i < custom_widget_list.size(); ) { + bool classInserted = false; + DomCustomWidget *custom_widget = custom_widget_list[i]; + const QString customClassName = custom_widget->elementClass(); + const QString base_class = custom_widget->elementExtends(); + QString includeFile; + IncludeType includeType = IncludeLocal; + if (const DomHeader *header = custom_widget->elementHeader()) { + includeFile = header->text(); + if (header->hasAttributeLocation() && header->attributeLocation() == QLatin1String("global")) + includeType = IncludeGlobal; + } + const bool domIsContainer = custom_widget->elementContainer(); + // Append a new item + if (base_class.isEmpty()) { + WidgetDataBaseItem *item = new WidgetDataBaseItem(customClassName); + item->setPromoted(false); + item->setGroup(QCoreApplication::translate("Designer", "Custom Widgets")); + item->setIncludeFile(buildIncludeFile(includeFile, includeType)); + item->setContainer(domIsContainer); + item->setCustom(true); + addFakeMethodsToWidgetDataBase(custom_widget, item); + db->append(item); + custom_widget_list.removeAt(i); + classInserted = true; + } else { + // Create a new entry cloned from base class. Note that this will ignore existing + // classes, eg, plugin custom widgets. + QDesignerWidgetDataBaseItemInterface *item = + appendDerived(db, customClassName, QCoreApplication::translate("Designer", "Promoted Widgets"), + base_class, + buildIncludeFile(includeFile, includeType), + true,true); + // Ok, base class found. + if (item) { + // Hack to accommodate for old UI-files in which "container" is not set properly: + // Apply "container" from DOM only if true (else, eg classes from QFrame might not accept + // dropping child widgets on them as container=false). This also allows for + // QWidget-derived stacked pages. + if (domIsContainer) + item->setContainer(domIsContainer); + + addFakeMethodsToWidgetDataBase(custom_widget, static_cast(item)); + custom_widget_list.removeAt(i); + classInserted = true; + } + } + // Skip failed item. + if (!classInserted) + i++; + } + +} + +void QSimpleResource::handleDomCustomWidgets(const QDesignerFormEditorInterface *core, + const DomCustomWidgets *dom_custom_widgets) +{ + if (dom_custom_widgets == 0) + return; + QList custom_widget_list = dom_custom_widgets->elementCustomWidget(); + // Attempt to insert each item derived from its base class. + // This should at most require two iterations in the event that the classes are out of order + // (derived first, max depth: promoted custom plugin = 2) + for (int iteration = 0; iteration < 2; iteration++) { + addCustomWidgetsToWidgetDatabase(core, custom_widget_list); + if (custom_widget_list.empty()) + return; + } + // Oops, there are classes left whose base class could not be found. + // Default them to QWidget with warnings. + const QString fallBackBaseClass = QLatin1String("QWidget"); + for (int i=0; i < custom_widget_list.size(); i++ ) { + DomCustomWidget *custom_widget = custom_widget_list[i]; + const QString customClassName = custom_widget->elementClass(); + const QString base_class = custom_widget->elementExtends(); + qDebug() << "** WARNING The base class " << base_class << " of the custom widget class " << customClassName + << " could not be found. Defaulting to " << fallBackBaseClass << '.'; + custom_widget->setElementExtends(fallBackBaseClass); + } + // One more pass. + addCustomWidgetsToWidgetDatabase(core, custom_widget_list); +} + // ------------ FormBuilderClipboard FormBuilderClipboard::FormBuilderClipboard(QWidget *w) diff --git a/tools/designer/src/lib/shared/qsimpleresource_p.h b/tools/designer/src/lib/shared/qsimpleresource_p.h index 8d45c3c..a25cb88 100644 --- a/tools/designer/src/lib/shared/qsimpleresource_p.h +++ b/tools/designer/src/lib/shared/qsimpleresource_p.h @@ -55,15 +55,21 @@ #include "shared_global_p.h" #include "abstractformbuilder.h" +#include QT_BEGIN_NAMESPACE class DomScript; +class DomCustomWidgets; +class DomCustomWidget; +class DomSlots; class QDesignerFormEditorInterface; namespace qdesigner_internal { +class WidgetDataBaseItem; + class QDESIGNER_SHARED_EXPORT QSimpleResource : public QAbstractFormBuilder { public: @@ -92,6 +98,11 @@ public: static QString customWidgetScript(QDesignerFormEditorInterface *core, const QString &className); static bool hasCustomWidgetScript(QDesignerFormEditorInterface *core, QObject *object); + // Implementation for FormBuilder::createDomCustomWidgets() that adds + // the custom widgets to the widget database + static void handleDomCustomWidgets(const QDesignerFormEditorInterface *core, + const DomCustomWidgets *dom_custom_widgets); + protected: virtual QIcon nameToIcon(const QString &filePath, const QString &qrcPath); virtual QString iconToFilePath(const QIcon &pm) const; @@ -105,7 +116,13 @@ protected: typedef QList DomScripts; static void addScript(const QString &script, ScriptSource source, DomScripts &domScripts); + static bool addFakeMethods(const DomSlots *domSlots, QStringList &fakeSlots, QStringList &fakeSignals); + private: + static void addCustomWidgetsToWidgetDatabase(const QDesignerFormEditorInterface *core, + QList& custom_widget_list); + static void addFakeMethodsToWidgetDataBase(const DomCustomWidget *domCustomWidget, WidgetDataBaseItem *item); + static bool m_warningsEnabled; QDesignerFormEditorInterface *m_core; }; -- cgit v0.12 From 72798fc4dfc1af73cde542f9017dfec5cb020173 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 10:29:04 +0200 Subject: kill unused private functions --- src/corelib/statemachine/qabstractstate.cpp | 5 ----- src/corelib/statemachine/qabstractstate_p.h | 1 - src/corelib/statemachine/qabstracttransition.cpp | 5 ----- src/corelib/statemachine/qabstracttransition_p.h | 1 - src/corelib/statemachine/qhistorystate.cpp | 5 ----- src/corelib/statemachine/qhistorystate_p.h | 1 - 6 files changed, 18 deletions(-) diff --git a/src/corelib/statemachine/qabstractstate.cpp b/src/corelib/statemachine/qabstractstate.cpp index 7e59a7d..942722f 100644 --- a/src/corelib/statemachine/qabstractstate.cpp +++ b/src/corelib/statemachine/qabstractstate.cpp @@ -84,11 +84,6 @@ QAbstractStatePrivate *QAbstractStatePrivate::get(QAbstractState *q) return q->d_func(); } -const QAbstractStatePrivate *QAbstractStatePrivate::get(const QAbstractState *q) -{ - return q->d_func(); -} - QStateMachine *QAbstractStatePrivate::machine() const { Q_Q(const QAbstractState); diff --git a/src/corelib/statemachine/qabstractstate_p.h b/src/corelib/statemachine/qabstractstate_p.h index 1a99d6c..2aad47e 100644 --- a/src/corelib/statemachine/qabstractstate_p.h +++ b/src/corelib/statemachine/qabstractstate_p.h @@ -69,7 +69,6 @@ public: QAbstractStatePrivate(); static QAbstractStatePrivate *get(QAbstractState *q); - static const QAbstractStatePrivate *get(const QAbstractState *q); QStateMachine *machine() const; diff --git a/src/corelib/statemachine/qabstracttransition.cpp b/src/corelib/statemachine/qabstracttransition.cpp index 68423cb..dfcafeb 100644 --- a/src/corelib/statemachine/qabstracttransition.cpp +++ b/src/corelib/statemachine/qabstracttransition.cpp @@ -108,11 +108,6 @@ QAbstractTransitionPrivate *QAbstractTransitionPrivate::get(QAbstractTransition return q->d_func(); } -const QAbstractTransitionPrivate *QAbstractTransitionPrivate::get(const QAbstractTransition *q) -{ - return q->d_func(); -} - QStateMachine *QAbstractTransitionPrivate::machine() const { Q_Q(const QAbstractTransition); diff --git a/src/corelib/statemachine/qabstracttransition_p.h b/src/corelib/statemachine/qabstracttransition_p.h index a6db220..f067984 100644 --- a/src/corelib/statemachine/qabstracttransition_p.h +++ b/src/corelib/statemachine/qabstracttransition_p.h @@ -73,7 +73,6 @@ public: QAbstractTransitionPrivate(); static QAbstractTransitionPrivate *get(QAbstractTransition *q); - static const QAbstractTransitionPrivate *get(const QAbstractTransition *q); bool callEventTest(QEvent *e); void callOnTransition(QEvent *e); diff --git a/src/corelib/statemachine/qhistorystate.cpp b/src/corelib/statemachine/qhistorystate.cpp index d1b2391..517faa8 100644 --- a/src/corelib/statemachine/qhistorystate.cpp +++ b/src/corelib/statemachine/qhistorystate.cpp @@ -126,11 +126,6 @@ QHistoryStatePrivate *QHistoryStatePrivate::get(QHistoryState *q) return q->d_func(); } -const QHistoryStatePrivate *QHistoryStatePrivate::get(const QHistoryState *q) -{ - return q->d_func(); -} - /*! Constructs a new shallow history state with the given \a parent state. */ diff --git a/src/corelib/statemachine/qhistorystate_p.h b/src/corelib/statemachine/qhistorystate_p.h index 2f17496..5aaa64c 100644 --- a/src/corelib/statemachine/qhistorystate_p.h +++ b/src/corelib/statemachine/qhistorystate_p.h @@ -68,7 +68,6 @@ public: QHistoryStatePrivate(); static QHistoryStatePrivate *get(QHistoryState *q); - static const QHistoryStatePrivate *get(const QHistoryState *q); QAbstractState *defaultState; QHistoryState::HistoryType historyType; -- cgit v0.12 From 5cd9be6c2702ce1f4292003ac3e864f08a0311f3 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Fri, 22 May 2009 10:49:32 +0200 Subject: Fix toolbutton text incorrectly clipped on windows In 4.5 the toolbutton icon rendering was changed somewhat and the bottom line of text for tool buttons icons with TextUnderIcon set is incorrectly clipped on Windows. The style reserves only 5 pixels but tries to use 6 pixels for text and icon spacing, hence we adjust the text rect one pixel up. This should be safe considering the fact that we have a margin on both sides of the icon already and avoids actually moving the icon positioning. Task-number: 252554 Reviewed-by: trond --- src/gui/styles/qcommonstyle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/styles/qcommonstyle.cpp b/src/gui/styles/qcommonstyle.cpp index 3cae08a..f3d1537 100644 --- a/src/gui/styles/qcommonstyle.cpp +++ b/src/gui/styles/qcommonstyle.cpp @@ -1693,7 +1693,7 @@ void QCommonStyle::drawControl(ControlElement element, const QStyleOption *opt, if (toolbutton->toolButtonStyle == Qt::ToolButtonTextUnderIcon) { pr.setHeight(pmSize.height() + 6); - tr.adjust(0, pr.height(), 0, -3); + tr.adjust(0, pr.height() - 1, 0, -3); pr.translate(shiftX, shiftY); if (!hasArrow) { drawItemPixmap(p, pr, Qt::AlignCenter, pm); -- cgit v0.12 From 8502f76e820ab79181a1b8ac54c8431b298a2023 Mon Sep 17 00:00:00 2001 From: "Bradley T. Hughes" Date: Fri, 22 May 2009 10:53:31 +0200 Subject: Mark data as static, use fetch-and-store instead of test-and-set Mark the objectCount and mutex-pool as static as they won't ever be externed. Use fetch-and-store zero instead of test-and-set from current value to zero. --- src/corelib/kernel/qobject.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index cfd8493..1e9e284 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -92,8 +92,8 @@ static int *queuedConnectionTypes(const QList &typeNames) return types; } -QBasicAtomicPointer signalSlotMutexes = Q_BASIC_ATOMIC_INITIALIZER(0); -QBasicAtomicInt objectCount = Q_BASIC_ATOMIC_INITIALIZER(0); +static QBasicAtomicPointer signalSlotMutexes = Q_BASIC_ATOMIC_INITIALIZER(0); +static QBasicAtomicInt objectCount = Q_BASIC_ATOMIC_INITIALIZER(0); /** \internal * mutex to be locked when accessing the connectionlists or the senders list @@ -117,8 +117,7 @@ extern "C" Q_CORE_EXPORT void qt_addObject(QObject *) extern "C" Q_CORE_EXPORT void qt_removeObject(QObject *) { if(!objectCount.deref()) { - QMutexPool *old = signalSlotMutexes; - signalSlotMutexes.testAndSetAcquire(old, 0); + QMutexPool *old = signalSlotMutexes.fetchAndStoreAcquire(0); delete old; } } -- cgit v0.12 From 31fcf8e77f8ef8020edfbfd224cf6e68cb0450bf Mon Sep 17 00:00:00 2001 From: "Bradley T. Hughes" Date: Fri, 22 May 2009 11:01:39 +0200 Subject: Update the QMutexPool API to be more like QMutex If we ever decide to make this class public, the interfaces should be similar. --- src/corelib/thread/qmutexpool.cpp | 14 +++++++------- src/corelib/thread/qmutexpool_p.h | 4 ++-- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/corelib/thread/qmutexpool.cpp b/src/corelib/thread/qmutexpool.cpp index 96a9940..77a3cca 100644 --- a/src/corelib/thread/qmutexpool.cpp +++ b/src/corelib/thread/qmutexpool.cpp @@ -49,7 +49,7 @@ QT_BEGIN_NAMESPACE // qt_global_mutexpool is here for backwards compatability only, // use QMutexpool::instance() in new clode. Q_CORE_EXPORT QMutexPool *qt_global_mutexpool = 0; -Q_GLOBAL_STATIC_WITH_ARGS(QMutexPool, globalMutexPool, (true)) +Q_GLOBAL_STATIC_WITH_ARGS(QMutexPool, globalMutexPool, (QMutex::Recursive)) /*! \class QMutexPool @@ -88,15 +88,15 @@ Q_GLOBAL_STATIC_WITH_ARGS(QMutexPool, globalMutexPool, (true)) */ /*! - Constructs a QMutexPool, reserving space for \a size QMutexes. If - \a recursive is true, all QMutexes in the pool will be recursive - mutexes; otherwise they will all be non-recursive (the default). + Constructs a QMutexPool, reserving space for \a size QMutexes. All + mutexes in the pool are created with \a recursionMode. By default, + all mutexes are non-recursive. The QMutexes are created when needed, and deleted when the QMutexPool is destructed. */ -QMutexPool::QMutexPool(bool recursive, int size) - : mutexes(size), count(size), recurs(recursive) +QMutexPool::QMutexPool(QMutex::RecursionMode recursionMode, int size) + : mutexes(size), count(size), recursionMode(recursionMode) { for (int index = 0; index < count; ++index) { mutexes[index] = 0; @@ -134,7 +134,7 @@ QMutex *QMutexPool::get(const void *address) if (!mutexes[index]) { // mutex not created, create one - QMutex *newMutex = new QMutex(recurs ? QMutex::Recursive : QMutex::NonRecursive); + QMutex *newMutex = new QMutex(recursionMode); if (!mutexes[index].testAndSetOrdered(0, newMutex)) delete newMutex; } diff --git a/src/corelib/thread/qmutexpool_p.h b/src/corelib/thread/qmutexpool_p.h index 1009ebb..4c1e32c 100644 --- a/src/corelib/thread/qmutexpool_p.h +++ b/src/corelib/thread/qmutexpool_p.h @@ -64,7 +64,7 @@ QT_BEGIN_NAMESPACE class Q_CORE_EXPORT QMutexPool { public: - explicit QMutexPool(bool recursive = false, int size = 128); + explicit QMutexPool(QMutex::RecursionMode recursionMode = QMutex::NonRecursive, int size = 128); ~QMutexPool(); QMutex *get(const void *address); @@ -74,7 +74,7 @@ public: private: QVarLengthArray, 128> mutexes; int count; - bool recurs; + QMutex::RecursionMode recursionMode; }; extern Q_CORE_EXPORT QMutexPool *qt_global_mutexpool; -- cgit v0.12 From 6b7736e5cc352f1326989eee8dd9ef87f2b9a486 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 22 May 2009 11:06:28 +0200 Subject: Doc - removing the constraint on font size. Reviewed-By: David Boddie --- tools/qdoc3/test/classic.css | 3 --- 1 file changed, 3 deletions(-) diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index 8e9eb78..e700e0a 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -1,9 +1,6 @@ BODY,H1,H2,H3,H4,H5,H6,P,CENTER,TD,TH,UL,DL,DIV { font-family: Arial, Geneva, Helvetica, sans-serif; } -BODY,TD { - font-size: 90%; -} H1 { text-align: center; font-size: 160%; -- cgit v0.12 From 8ad5020940f10d4ecc5c5e8b3b9656531cb84ef3 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 20 May 2009 16:38:47 +0200 Subject: Add properties to QGraphicsItem to change the transformations component With the new properties it is possible to easily animate. Setting a transform using setTransform is incompatible with thoses properties. Accessing thoses propeties if you set previously a transform will give you the default values. Acknowledged-by: Code made with Andreas. Documentation written with Thierry. This still need a more in depth code review and documentation review. But it is urgent to commit now because the Animation API integration depends on it. --- src/gui/graphicsview/qgraphicsitem.cpp | 431 +++++++++++++++++++-- src/gui/graphicsview/qgraphicsitem.h | 41 +- src/gui/graphicsview/qgraphicsitem_p.h | 79 +++- src/gui/graphicsview/qgraphicswidget.h | 9 +- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 88 +++++ tests/benchmarks/qgraphicsitem/qgraphicsitem.pro | 6 + .../benchmarks/qgraphicsitem/tst_qgraphicsitem.cpp | 170 ++++++++ 7 files changed, 780 insertions(+), 44 deletions(-) create mode 100644 tests/benchmarks/qgraphicsitem/qgraphicsitem.pro create mode 100644 tests/benchmarks/qgraphicsitem/tst_qgraphicsitem.cpp diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 72b832a..b7e88f4 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -130,12 +130,18 @@ \img graphicsview-parentchild.png + \section Transformation + QGraphicsItem supports affine transformations in addition to its base position, pos(). To change the item's transformation, you can either pass - a transformation matrix to setTransform(), or call one of the convenience - functions rotate(), scale(), translate(), or shear(). Item transformations - accumulate from parent to child, so if both a parent and child item are - rotated 90 degrees, the child's total transformation will be 180 degrees. + a transformation matrix to setTransform(), or set the different transformation + properties (transformOrigin, x/y/zRotation, x/yScale, horizontal/verticalShear). + Note that setting the transformation matrix conflicts with using the properties. + Setting the properties will overwrite the transformation set with setTransform, + and using setTransform will reset the properties. + + Item transformations accumulate from parent to child, so if both a parent and child + item are rotated 90 degrees, the child's total transformation will be 180 degrees. Similarly, if the item's parent is scaled to 2x its original size, its children will also be twice as large. An item's transformation does not affect its own local geometry; all geometry functions (e.g., contains(), @@ -146,6 +152,22 @@ and scenePos(), which returns its position in scene coordinates. To reset an item's matrix, call resetTransform(). + The order you set the transformation properties does not affect the resulting transformation + The resulting transformation is always computed in the following order + + \code + [Origin] [RotateX] [RotateY] [RotateZ] [Shear] [Scale] [-Origin] + \endcode + + So the transformation is equivalent to the following code + + \code + QTransform().translate(xOrigin, yOrigin).rotate(xRotation, Qt::XAxis).rotate(yRotation, Qt::YAxis).rotate(zRotation, Qt::ZAxis) + .shear(horizontalShear, verticalShear).scale(xScale, yScale).translate(-xOrigin, -yOrigin); + \endcode + + \section Painting + The paint() function is called by QGraphicsView to paint the item's contents. The item has no background or default fill of its own; whatever is behind the item will shine through all areas that are not explicitly @@ -161,6 +183,8 @@ high z-values. Stacking order applies to sibling items; parents are always drawn before their children. + \section Events + QGraphicsItem receives events from QGraphicsScene through the virtual function sceneEvent(). This function distributes the most common events to a set of convenience event handlers: @@ -186,6 +210,8 @@ by the virtual function sceneEventFilter(). You can remove item event filters by calling removeSceneEventFilter(). + \section Custom Data + Sometimes it's useful to register custom data with an item, be it a custom item, or a standard item. You can call setData() on any item to store data in it using a key-value pair (the key being an integer, and the value is a @@ -338,16 +364,17 @@ \value ItemTransformChange The item's transformation matrix changes. This notification is only sent when the item's local transformation matrix - changes (i.e., as a result of calling setTransform(), or one of the - convenience transformation functions, such as rotate()). The value + changes (i.e., as a result of calling setTransform(). The value argument is the new matrix (i.e., a QTransform); to get the old matrix, - call transform(). Do not call setTransform() or any of the transformation - convenience functions in itemChange() as this notification is delivered; + call transform(). Do not call setTransform() or set any of the transformation + properties in itemChange() as this notification is delivered; instead, you can return the new matrix from itemChange(). + This notification is not sent if you change the transformation properties. \value ItemTransformHasChanged The item's transformation matrix has - changed. This notification is only sent after the item's local - trasformation matrix has changed. The value argument is the new matrix + changed either because setTransform is called, or one of the transformation + properties is changed. This notification is only sent after the item's local + transformation matrix has changed. The value argument is the new matrix (same as transform()), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). @@ -2559,8 +2586,13 @@ QMatrix QGraphicsItem::matrix() const /*! \since 4.3 - Returns this item's transformation matrix. If no matrix has been set, the - identity matrix is returned. + Returns this item's transformation matrix. + + Either the one set by setTransform, or the resulting transformation from + all the transfmation properties + + If no matrix or transformation property has been set, the + identity matrix is returned. \sa setTransform(), sceneTransform() */ @@ -2568,10 +2600,307 @@ QTransform QGraphicsItem::transform() const { if (!d_ptr->hasTransform) return QTransform(); + if (d_ptr->hasDecomposedTransform && d_ptr->dirtyTransform) { + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + QTransform x; + decomposed->generateTransform(&x); + QVariant v(x); + d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, v); + d_ptr->dirtyTransform = 0; + d_ptr->dirtyTransformComponents = 1; + const_cast(this)->itemChange(ItemTransformHasChanged, v); + return x; + } return qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform)); } /*! + \property QGraphicsItem::xRotation + + \since 4.6 + + This property holds the rotation angle in degrees around the X axis + + The default is 0 + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, this function return the default value. + + \sa {Transformations} +*/ +qreal QGraphicsItem::xRotation() const +{ + return d_ptr->decomposedTransform()->xRotation; +} + +void QGraphicsItem::setXRotation(qreal angle) +{ + if (!d_ptr->dirtyTransform) { + d_ptr->fullUpdateHelper(true); + prepareGeometryChange(); + } + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + decomposed->xRotation = angle; + if (!d_ptr->dirtyTransform) + d_ptr->invalidateSceneTransformCache(); + d_ptr->dirtyTransform = 1; + d_ptr->hasTransform = 1; +} + +/*! + \property QGraphicsItem::yRotation + + \since 4.6 + + This property holds the rotation angle in degrees around the Y axis + + The default is 0 + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, this function return the default value. + + \sa {Transformations} +*/ +qreal QGraphicsItem::yRotation() const +{ + return d_ptr->decomposedTransform()->yRotation; +} + +void QGraphicsItem::setYRotation(qreal angle) +{ + if (!d_ptr->dirtyTransform) { + d_ptr->fullUpdateHelper(true); + prepareGeometryChange(); + } + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + decomposed->yRotation = angle; + if (!d_ptr->dirtyTransform) + d_ptr->invalidateSceneTransformCache(); + d_ptr->dirtyTransform = 1; + d_ptr->hasTransform = 1; +} + +/*! + \property QGraphicsItem::zRotation + + \since 4.6 + + This property holds the rotation angle in degrees around the Z axis + + The default is 0 + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, this function return the default value. + + \sa {Transformations} +*/ +qreal QGraphicsItem::zRotation() const +{ + return d_ptr->decomposedTransform()->zRotation; +} + +void QGraphicsItem::setZRotation(qreal angle) +{ + if (!d_ptr->dirtyTransform) { + d_ptr->fullUpdateHelper(true); + prepareGeometryChange(); + } + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + decomposed->zRotation = angle; + if (!d_ptr->dirtyTransform) + d_ptr->invalidateSceneTransformCache(); + d_ptr->dirtyTransform = 1; + d_ptr->hasTransform = 1; +} + +void QGraphicsItem::setRotation(qreal x, qreal y, qreal z) +{ + setXRotation(x); + setYRotation(y); + setZRotation(z); +} + +/*! + \property QGraphicsItem::xScale + + \since 4.6 + + This property holds the scale factor on the X axis. + + The default is 1 + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, this function return the default value. + + \sa {Transformations} +*/ +qreal QGraphicsItem::xScale() const +{ + return d_ptr->decomposedTransform()->xScale; +} + +void QGraphicsItem::setXScale(qreal factor) +{ + if (!d_ptr->dirtyTransform) { + d_ptr->fullUpdateHelper(true); + prepareGeometryChange(); + } + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + decomposed->xScale = factor; + if (!d_ptr->dirtyTransform) + d_ptr->invalidateSceneTransformCache(); + d_ptr->dirtyTransform = 1; + d_ptr->hasTransform = 1; +} + +/*! + \property QGraphicsItem::yScale + + \since 4.6 + + This property holds the scale factor on the Y axis. + + The default is 1 + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, this function return the default value. + + \sa {Transformations} +*/ +qreal QGraphicsItem::yScale() const +{ + return d_ptr->decomposedTransform()->yScale; +} + +void QGraphicsItem::setYScale(qreal factor) +{ + if (!d_ptr->dirtyTransform) { + d_ptr->fullUpdateHelper(true); + prepareGeometryChange(); + } + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + decomposed->yScale = factor; + if (!d_ptr->dirtyTransform) + d_ptr->invalidateSceneTransformCache(); + d_ptr->dirtyTransform = 1; + d_ptr->hasTransform = 1; +} + +void QGraphicsItem::setScale(qreal sx, qreal sy) +{ + setXScale(sx); + setYScale(sy); +} + +/*! + \property QGraphicsItem::horizontalShear + + \since 4.6 + + This property holds the horizontal shear. + + The default is 0. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, this function return the default value. + + \sa {Transformations} +*/ +qreal QGraphicsItem::horizontalShear() const +{ + return d_ptr->decomposedTransform()->horizontalShear; +} + +void QGraphicsItem::setHorizontalShear(qreal shear) +{ + if (!d_ptr->dirtyTransform) { + d_ptr->fullUpdateHelper(true); + prepareGeometryChange(); + } + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + decomposed->horizontalShear = shear; + if (!d_ptr->dirtyTransform) + d_ptr->invalidateSceneTransformCache(); + d_ptr->dirtyTransform = 1; + d_ptr->hasTransform = 1; +} + +/*! + \property QGraphicsItem::verticalShear + + \since 4.6 + + This property holds the vertical shear. + + The default is 0. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, this function return the default value. + + \sa {Transformations} +*/ +qreal QGraphicsItem::verticalShear() const +{ + return d_ptr->decomposedTransform()->verticalShear; +} + +void QGraphicsItem::setVerticalShear(qreal shear) +{ + if (!d_ptr->dirtyTransform) { + d_ptr->fullUpdateHelper(true); + prepareGeometryChange(); + } + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + decomposed->verticalShear = shear; + if (!d_ptr->dirtyTransform) + d_ptr->invalidateSceneTransformCache(); + d_ptr->dirtyTransform = 1; + d_ptr->hasTransform = 1; +} + +void QGraphicsItem::setShear(qreal sh, qreal sv) +{ + setHorizontalShear(sh); + setVerticalShear(sv); +} + +/*! + \property QGraphicsItem::transformOrigin + + \since 4.6 + + This property holds the transformation origin for the transformation properties. + This does not apply to the transformation set by setTransform. + + The default is QPointF(0,0). + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, this function return the default value. + + \sa {Transformations} +*/ +QPointF QGraphicsItem::transformOrigin() const +{ + const QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + return QPointF(decomposed->xOrigin, decomposed->yOrigin); +} + +void QGraphicsItem::setTransformOrigin(const QPointF &origin) +{ + if (!d_ptr->dirtyTransform) { + d_ptr->fullUpdateHelper(true); + prepareGeometryChange(); + } + QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); + decomposed->xOrigin = origin.x(); + decomposed->yOrigin = origin.y(); + if (!d_ptr->dirtyTransform) + d_ptr->invalidateSceneTransformCache(); + d_ptr->dirtyTransform = 1; + d_ptr->hasTransform = 1; +} + +/*! \obsolete Use sceneTransform() instead. @@ -2846,7 +3175,7 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co Use setTransform() instead. - \sa transform(), rotate(), scale(), shear(), translate(), {The Graphics View Coordinate System} + \sa transform(), {The Graphics View Coordinate System} */ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) { @@ -2872,6 +3201,8 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) d_ptr->hasTransform = !newTransform.isIdentity(); d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); d_ptr->invalidateSceneTransformCache(); + if (d_ptr->hasDecomposedTransform) + d_ptr->dirtyTransform = 1; // Send post-notification. // NB! We have to change the value from QMatrix to QTransform. @@ -2894,7 +3225,10 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) to map an item coordiate to a scene coordinate, or mapFromScene() to map from scene coordinates to item coordinates. - \sa transform(), rotate(), scale(), shear(), translate(), {The Graphics View Coordinate System} + \warning using this function conflicts with using the transformation properties. + If you set a transformation, getting the properties will return default values. + + \sa transform(), setRotation(), setScale(), setShear(), setTransformOrigin() {The Graphics View Coordinate System} */ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) { @@ -2920,6 +3254,8 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) d_ptr->hasTransform = !newTransform.isIdentity(); d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); d_ptr->invalidateSceneTransformCache(); + if (d_ptr->hasDecomposedTransform) + d_ptr->dirtyTransform = 1; // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -2938,8 +3274,9 @@ void QGraphicsItem::resetMatrix() /*! \since 4.3 - Resets this item's transformation matrix to the identity matrix. This is - equivalent to calling \c setTransform(QTransform()). + Resets this item's transformation matrix to the identity matrix or + all the transformation properties to their default values. + This is equivalent to calling \c setTransform(QTransform()). \sa setTransform(), transform() */ @@ -2949,6 +3286,9 @@ void QGraphicsItem::resetTransform() } /*! + \obsolete + Use setZRotation() instead + Rotates the current item transformation \a angle degrees clockwise around its origin. To translate around an arbitrary point (x, y), you need to combine translation and rotation with setTransform(). @@ -2957,6 +3297,9 @@ void QGraphicsItem::resetTransform() \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 6 + \warning using this function conflicts with using the transformation properties. + Getting those properties after using this function will return default values. + \sa setTransform(), transform(), scale(), shear(), translate() */ void QGraphicsItem::rotate(qreal angle) @@ -2965,6 +3308,9 @@ void QGraphicsItem::rotate(qreal angle) } /*! + \obsolete + Use setScale() instead + Scales the current item transformation by (\a sx, \a sy) around its origin. To scale from an arbitrary point (x, y), you need to combine translation and scaling with setTransform(). @@ -2973,7 +3319,10 @@ void QGraphicsItem::rotate(qreal angle) \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 7 - \sa setTransform(), transform(), rotate(), shear(), translate() + \warning using this function conflicts with using the transformation properties. + Getting those properties after using this function will return default values. + + \sa setTransform(), transform() */ void QGraphicsItem::scale(qreal sx, qreal sy) { @@ -2981,9 +3330,15 @@ void QGraphicsItem::scale(qreal sx, qreal sy) } /*! + \obsolete + Use setShear instead. + Shears the current item transformation by (\a sh, \a sv). - \sa setTransform(), transform(), rotate(), scale(), translate() + \warning using this function conflicts with using the transformation properties. + Getting those properties after using this function will return default values. + + \sa setTransform(), transform() */ void QGraphicsItem::shear(qreal sh, qreal sv) { @@ -2991,13 +3346,19 @@ void QGraphicsItem::shear(qreal sh, qreal sv) } /*! + \obsolete + Use setPos() or setTransformOrigin() instead. + Translates the current item transformation by (\a dx, \a dy). If all you want is to move an item, you should call moveBy() or setPos() instead; this function changes the item's translation, which is conceptually separate from its position. - \sa setTransform(), transform(), rotate(), scale(), shear() + \warning using this function conflicts with using the transformation properties. + Getting those properties after using this function will return default values. + + \sa setTransform(), transform() */ void QGraphicsItem::translate(qreal dx, qreal dy) { @@ -3121,7 +3482,7 @@ QRectF QGraphicsItem::childrenBoundingRect() const Although the item's shape can be arbitrary, the bounding rect is always rectangular, and it is unaffected by the items' - transformation (scale(), rotate(), etc.). + transformation. If you want to change the item's bounding rectangle, you must first call prepareGeometryChange(). This notifies the scene of the imminent change, @@ -8143,19 +8504,19 @@ bool QGraphicsTextItem::sceneEvent(QEvent *event) void QGraphicsTextItem::mousePressEvent(QGraphicsSceneMouseEvent *event) { if ((QGraphicsItem::d_ptr->flags & (ItemIsSelectable | ItemIsMovable)) - && (event->buttons() & Qt::LeftButton) && dd->_q_mouseOnEdge(event)) { - // User left-pressed on edge of selectable/movable item, use - // base impl. - dd->useDefaultImpl = true; + && (event->buttons() & Qt::LeftButton) && dd->_q_mouseOnEdge(event)) { + // User left-pressed on edge of selectable/movable item, use + // base impl. + dd->useDefaultImpl = true; } else if (event->buttons() == event->button() - && dd->control->textInteractionFlags() == Qt::NoTextInteraction) { - // User pressed first button on non-interactive item. - dd->useDefaultImpl = true; + && dd->control->textInteractionFlags() == Qt::NoTextInteraction) { + // User pressed first button on non-interactive item. + dd->useDefaultImpl = true; } if (dd->useDefaultImpl) { QGraphicsItem::mousePressEvent(event); - if (!event->isAccepted()) - dd->useDefaultImpl = false; + if (!event->isAccepted()) + dd->useDefaultImpl = false; return; } dd->sendControlEvent(event); @@ -8180,14 +8541,14 @@ void QGraphicsTextItem::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) { if (dd->useDefaultImpl) { QGraphicsItem::mouseReleaseEvent(event); - if (dd->control->textInteractionFlags() == Qt::NoTextInteraction - && !event->buttons()) { - // User released last button on non-interactive item. + if (dd->control->textInteractionFlags() == Qt::NoTextInteraction + && !event->buttons()) { + // User released last button on non-interactive item. dd->useDefaultImpl = false; - } else if ((event->buttons() & Qt::LeftButton) == 0) { - // User released the left button on an interactive item. + } else if ((event->buttons() & Qt::LeftButton) == 0) { + // User released the left button on an interactive item. dd->useDefaultImpl = false; - } + } return; } dd->sendControlEvent(event); diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index 0a0179e..f6ee197 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -241,11 +241,41 @@ public: QTransform itemTransform(const QGraphicsItem *other, bool *ok = 0) const; void setTransform(const QTransform &matrix, bool combine = false); void resetTransform(); - - void rotate(qreal angle); - void scale(qreal sx, qreal sy); - void shear(qreal sh, qreal sv); - void translate(qreal dx, qreal dy); + + void rotate(qreal angle); // ### obsolete + void scale(qreal sx, qreal sy); // ### obsolete + void shear(qreal sh, qreal sv); // ### obsolete + void translate(qreal dx, qreal dy); // ### obsolete + + qreal xRotation() const; + void setXRotation(qreal angle); + + qreal yRotation() const; + void setYRotation(qreal angle); + + qreal zRotation() const; + void setZRotation(qreal angle); + void setRotation(qreal x, qreal y, qreal z); + + qreal xScale() const; + void setXScale(qreal factor); + + qreal yScale() const; + void setYScale(qreal factor); + void setScale(qreal sx, qreal sy); + + qreal horizontalShear() const; + void setHorizontalShear(qreal shear); + + qreal verticalShear() const; + void setVerticalShear(qreal shear); + void setShear(qreal sh, qreal sv); + + QPointF transformOrigin() const; + void setTransformOrigin(const QPointF &origin); + inline void setTransformOrigin(qreal x, qreal y) + { setTransformOrigin(QPointF(x,y)); } + virtual void advance(int phase); // Stacking order @@ -1015,4 +1045,3 @@ QT_END_NAMESPACE QT_END_HEADER #endif // QGRAPHICSITEM_H - diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 820ef04..cebc8ca 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -56,6 +56,8 @@ #include "qgraphicsitem.h" #include "qpixmapcache.h" +#include + #if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW QT_BEGIN_NAMESPACE @@ -101,7 +103,8 @@ public: ExtraMaxDeviceCoordCacheSize, ExtraBoundingRegionGranularity, ExtraOpacity, - ExtraEffectiveOpacity + ExtraEffectiveOpacity, + ExtraDecomposedTransform }; enum AncestorFlag { @@ -145,6 +148,9 @@ public: inSetPosHelper(0), flags(0), allChildrenCombineOpacity(1), + hasDecomposedTransform(0), + dirtyTransform(0), + dirtyTransformComponents(0), globalStackingOrder(-1), sceneTransformIndex(-1), q_ptr(0) @@ -331,15 +337,84 @@ public: // New 32 bits quint32 flags : 10; quint32 allChildrenCombineOpacity : 1; - quint32 padding : 21; // feel free to use + quint32 hasDecomposedTransform : 1; + quint32 dirtyTransform : 1; + quint32 dirtyTransformComponents : 1; + quint32 padding : 18; // feel free to use // Optional stacking order int globalStackingOrder; int sceneTransformIndex; + struct DecomposedTransform; + DecomposedTransform *decomposedTransform() const + { + QGraphicsItemPrivate *that = const_cast(this); + DecomposedTransform *decomposed; + if (hasDecomposedTransform) { + decomposed = qVariantValue(extra(ExtraDecomposedTransform)); + } else { + decomposed = new DecomposedTransform; + that->setExtra(ExtraDecomposedTransform, qVariantFromValue(decomposed)); + that->hasDecomposedTransform = 1; + if (!dirtyTransformComponents) + decomposed->reset(); + } + if (dirtyTransformComponents) { + decomposed->initFrom(q_ptr->transform()); + that->dirtyTransformComponents = 0; + } + return decomposed; + } + + struct DecomposedTransform { + qreal xScale; + qreal yScale; + qreal xRotation; + qreal yRotation; + qreal zRotation; + qreal horizontalShear; + qreal verticalShear; + qreal xOrigin; + qreal yOrigin; + + inline void reset() + { + xScale = 1.0; + yScale = 1.0; + xRotation = 0.0; + yRotation = 0.0; + zRotation = 0.0; + horizontalShear = 0.0; + verticalShear = 0.0; + xOrigin = 0.0; + yOrigin = 0.0; + } + + inline void initFrom(const QTransform &x) + { + reset(); + // ### decompose transform + Q_UNUSED(x); + } + + inline void generateTransform(QTransform *x) const + { + x->translate(xOrigin, yOrigin); + x->rotate(xRotation, Qt::XAxis); + x->rotate(yRotation, Qt::YAxis); + x->rotate(zRotation, Qt::ZAxis); + x->shear(horizontalShear, verticalShear); + x->scale(xScale, yScale); + x->translate(-xOrigin, -yOrigin); + } + }; + QGraphicsItem *q_ptr; }; +Q_DECLARE_METATYPE(QGraphicsItemPrivate::DecomposedTransform *) + QT_END_NAMESPACE #endif // QT_NO_GRAPHICSVIEW diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h index 34f1c5f..a5c9068 100644 --- a/src/gui/graphicsview/qgraphicswidget.h +++ b/src/gui/graphicsview/qgraphicswidget.h @@ -81,7 +81,14 @@ class Q_GUI_EXPORT QGraphicsWidget : public QObject, public QGraphicsItem, publi Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity) Q_PROPERTY(QPointF pos READ pos WRITE setPos) Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry) - + Q_PROPERTY(QPointF transformOrigin READ transformOrigin WRITE setTransformOrigin) + Q_PROPERTY(qreal xRotation READ xRotation WRITE setXRotation) + Q_PROPERTY(qreal yRotation READ yRotation WRITE setYRotation) + Q_PROPERTY(qreal zRotation READ zRotation WRITE setZRotation) + Q_PROPERTY(qreal xScale READ xScale WRITE setXScale) + Q_PROPERTY(qreal yScale READ yScale WRITE setYScale) + Q_PROPERTY(qreal horizontalShear READ horizontalShear WRITE setHorizontalShear) + Q_PROPERTY(qreal verticalShear READ verticalShear WRITE setVerticalShear) public: QGraphicsWidget(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); ~QGraphicsWidget(); diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index b3ae60a..d41b3b4 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -219,6 +219,8 @@ private slots: void updateCachedItemAfterMove(); void deviceTransform_data(); void deviceTransform(); + void setTransformProperties_data(); + void setTransformProperties(); // task specific tests below me void task141694_textItemEnsureVisible(); @@ -6390,5 +6392,91 @@ void tst_QGraphicsItem::deviceTransform() QCOMPARE(rect3->deviceTransform(deviceX).map(QPointF(50, 50)), mapResult3); } +void tst_QGraphicsItem::setTransformProperties_data() +{ + QTest::addColumn("origin"); + QTest::addColumn("rotationX"); + QTest::addColumn("rotationY"); + QTest::addColumn("rotationZ"); + QTest::addColumn("scaleX"); + QTest::addColumn("scaleY"); + QTest::addColumn("shearX"); + QTest::addColumn("shearY"); + + QTest::newRow("nothing") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) + << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("rotationZ") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(42.2) + << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("rotationXY") << QPointF() << qreal(12.5) << qreal(53.6) << qreal(0.0) + << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("rotationXYZ") << QPointF() << qreal(-25) << qreal(12) << qreal(556) + << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("rotationXYZ dicentred") << QPointF(-53, 25.2) + << qreal(-2578.2) << qreal(4565.2) << qreal(56) + << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("Scale") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) + << qreal(6) << qreal(0.5) << qreal(0.0) << qreal(0.0); + + QTest::newRow("Shear") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) + << qreal(0.0) << qreal(0.0) << qreal(2.2) << qreal(0.5); + + QTest::newRow("Scale and Shear") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) + << qreal(5.2) << qreal(2.1) << qreal(5.2) << qreal(5.5); + + QTest::newRow("Everything") << QPointF() << qreal(41) << qreal(-23) << qreal(0.56) + << qreal(8.2) << qreal(-0.2) << qreal(-12) << qreal(-0.8); + + QTest::newRow("Everything dicentred") << QPointF(qreal(22.3), qreal(-56.2)) << qreal(-175) << qreal(196) << qreal(-1260) + << qreal(4) << qreal(2) << qreal(2.56) << qreal(0.8); +} + +void tst_QGraphicsItem::setTransformProperties() +{ + QFETCH(QPointF,origin); + QFETCH(qreal,rotationX); + QFETCH(qreal,rotationY); + QFETCH(qreal,rotationZ); + QFETCH(qreal,scaleX); + QFETCH(qreal,scaleY); + QFETCH(qreal,shearX); + QFETCH(qreal,shearY); + + QTransform result; + result.translate(origin.x(), origin.y()); + result.rotate(rotationX, Qt::XAxis); + result.rotate(rotationY, Qt::YAxis); + result.rotate(rotationZ, Qt::ZAxis); + result.shear(shearX, shearY); + result.scale(scaleX, scaleY); + result.translate(-origin.x(), -origin.y()); + + QGraphicsScene scene; + QGraphicsRectItem *item = new QGraphicsRectItem(QRectF(0, 0, 100, 100)); + scene.addItem(item); + item->setPos(100, 100); + + item->setRotation(rotationX, rotationY, rotationZ); + item->setScale(scaleX, scaleY); + item->setShear(shearX, shearY); + item->setTransformOrigin(origin); + + QCOMPARE(item->xRotation(), rotationX); + QCOMPARE(item->yRotation(), rotationY); + QCOMPARE(item->zRotation(), rotationZ); + QCOMPARE(item->xScale(), scaleX); + QCOMPARE(item->yScale(), scaleY); + QCOMPARE(item->horizontalShear(), shearX); + QCOMPARE(item->verticalShear(), shearY); + QCOMPARE(item->transformOrigin(), origin); + + QCOMPARE(result, item->transform()); +} + + QTEST_MAIN(tst_QGraphicsItem) #include "tst_qgraphicsitem.moc" diff --git a/tests/benchmarks/qgraphicsitem/qgraphicsitem.pro b/tests/benchmarks/qgraphicsitem/qgraphicsitem.pro new file mode 100644 index 0000000..c8fc07b --- /dev/null +++ b/tests/benchmarks/qgraphicsitem/qgraphicsitem.pro @@ -0,0 +1,6 @@ +load(qttest_p4) +TEMPLATE = app +TARGET = tst_qgraphicsitem + +SOURCES += tst_qgraphicsitem.cpp + diff --git a/tests/benchmarks/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/benchmarks/qgraphicsitem/tst_qgraphicsitem.cpp new file mode 100644 index 0000000..68e3aa1 --- /dev/null +++ b/tests/benchmarks/qgraphicsitem/tst_qgraphicsitem.cpp @@ -0,0 +1,170 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +****************************************************************************/ + +#include +#include +#include +#include + +//TESTED_FILES= + +class tst_QGraphicsItem : public QObject +{ + Q_OBJECT + +public: + tst_QGraphicsItem(); + virtual ~tst_QGraphicsItem(); + +public slots: + void init(); + void cleanup(); + +private slots: + void setPos_data(); + void setPos(); + void setTransform_data(); + void setTransform(); + void rotate(); + void scale(); + void shear(); + void translate(); + void setRotation(); + void setRotationXYZ(); +}; + +tst_QGraphicsItem::tst_QGraphicsItem() +{ +} + +tst_QGraphicsItem::~tst_QGraphicsItem() +{ +} + +void tst_QGraphicsItem::init() +{ +} + +void tst_QGraphicsItem::cleanup() +{ +} + +void tst_QGraphicsItem::setPos_data() +{ + QTest::addColumn("pos"); + + QTest::newRow("0, 0") << QPointF(0, 0); + QTest::newRow("10, 10") << QPointF(10, 10); + QTest::newRow("-10, -10") << QPointF(-10, -10); +} + +void tst_QGraphicsItem::setPos() +{ + QFETCH(QPointF, pos); + + QGraphicsScene scene; + QGraphicsRectItem *rect = scene.addRect(QRectF(0, 0, 100, 100)); + + QBENCHMARK { + rect->setPos(10, 10); + rect->transform(); // prevent lazy optimizing + } +} + +void tst_QGraphicsItem::setTransform_data() +{ + QTest::addColumn("transform"); + + QTest::newRow("id") << QTransform(); + QTest::newRow("rotate 45z") << QTransform().rotate(45); + QTest::newRow("scale 2x2") << QTransform().scale(2, 2); + QTest::newRow("translate 100, 100") << QTransform().translate(100, 100); + QTest::newRow("rotate 45x 45y 45z") << QTransform().rotate(45, Qt::XAxis) + .rotate(45, Qt::YAxis).rotate(45, Qt::ZAxis); +} + +void tst_QGraphicsItem::setTransform() +{ + QFETCH(QTransform, transform); + + QGraphicsScene scene; + QGraphicsRectItem *item = scene.addRect(QRectF(0, 0, 100, 100)); + + QBENCHMARK { + item->setTransform(transform); + item->transform(); // prevent lazy optimizing + } +} + +void tst_QGraphicsItem::rotate() +{ + QGraphicsScene scene; + QGraphicsItem *item = scene.addRect(QRectF(0, 0, 100, 100)); + + QBENCHMARK { + item->rotate(45); + item->transform(); // prevent lazy optimizing + } +} + +void tst_QGraphicsItem::scale() +{ + QGraphicsScene scene; + QGraphicsItem *item = scene.addRect(QRectF(0, 0, 100, 100)); + + QBENCHMARK { + item->scale(2, 2); + item->transform(); // prevent lazy optimizing + } +} + +void tst_QGraphicsItem::shear() +{ + QGraphicsScene scene; + QGraphicsItem *item = scene.addRect(QRectF(0, 0, 100, 100)); + + QBENCHMARK { + item->shear(1.5, 1.5); + item->transform(); // prevent lazy optimizing + } +} + +void tst_QGraphicsItem::translate() +{ + QGraphicsScene scene; + QGraphicsItem *item = scene.addRect(QRectF(0, 0, 100, 100)); + + QBENCHMARK { + item->translate(100, 100); + item->transform(); // prevent lazy optimizing + } +} + +void tst_QGraphicsItem::setRotation() +{ + QGraphicsScene scene; + QGraphicsItem *item = scene.addRect(QRectF(0, 0, 100, 100)); + + QBENCHMARK { + item->setXRotation(45); + item->transform(); // prevent lazy optimizing + } +} + +void tst_QGraphicsItem::setRotationXYZ() +{ + QGraphicsScene scene; + QGraphicsItem *item = scene.addRect(QRectF(0, 0, 100, 100)); + + QBENCHMARK { + item->setRotation(45, 45, 45); + item->transform(); // prevent lazy optimizing + } +} + +QTEST_MAIN(tst_QGraphicsItem) +#include "tst_qgraphicsitem.moc" -- cgit v0.12 From 308a105bf6ae6eb5702440728428a96b5806b085 Mon Sep 17 00:00:00 2001 From: Ariya Hidayat Date: Fri, 22 May 2009 11:08:38 +0200 Subject: Revert "Ignore GCC warning of unsafe floating point comparisons." MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 30f7edc0aab629499b74263391ae529ad31b2ff8. There is no way to restore float-equal warning using the pragma trick. This means (as it was mentioned in the said commit log) anyone that includes qtransform.h will be forced to deal with float-equal. Reviewed-by: Samuel Rødal --- src/gui/painting/qtransform.h | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/gui/painting/qtransform.h b/src/gui/painting/qtransform.h index 4a33969..c76409b 100644 --- a/src/gui/painting/qtransform.h +++ b/src/gui/painting/qtransform.h @@ -255,13 +255,6 @@ inline qreal QTransform::dy() const return affine._dy; } -#if defined(Q_CC_GNU) -# define Q_CC_GNU_VERSION (((__GNUC__)<<16)|((__GNUC_MINOR__)<<8)|(__GNUC_PATCHLEVEL__)) -# if Q_CC_GNU_VERSION >= 0x040201 -# pragma GCC diagnostic ignored "-Wfloat-equal" -# endif -#endif - inline QTransform &QTransform::operator*=(qreal num) { if (num == 1.) @@ -318,13 +311,6 @@ inline QTransform &QTransform::operator-=(qreal num) return *this; } -#if defined(Q_CC_GNU_VERSION) -# if Q_CC_GNU_VERSION >= 0x040201 -# pragma GCC diagnostic warning "-Wfloat-equal" -# endif -# undef Q_CC_GNU_VERSION -#endif - /****** stream functions *******************/ Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QTransform &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QTransform &); -- cgit v0.12 From 815a8c4a297cde2b8f778c4afa36958e324f8ead Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Fri, 22 May 2009 11:17:29 +0200 Subject: Fixed an issue with text drawing to QImages on Mac/Cocoa. We currently don't support subpixel hinting when drawing text to a QImage on Mac. The alpha map that is returned by the font engine is a plain 8 bit gray mask, which means we have to switch off subpixel hinting when we draw the glyph for caching. Task-number: 249178 Reviewed-by: Samuel --- src/gui/text/qfontengine_mac.mm | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gui/text/qfontengine_mac.mm b/src/gui/text/qfontengine_mac.mm index 425cab2..d397e4a 100644 --- a/src/gui/text/qfontengine_mac.mm +++ b/src/gui/text/qfontengine_mac.mm @@ -553,7 +553,9 @@ QImage QCoreTextFontEngine::alphaMapForGlyph(glyph_t glyph) 8, im.bytesPerLine(), colorspace, cgflags); CGContextSetFontSize(ctx, fontDef.pixelSize); - CGContextSetShouldAntialias(ctx, fontDef.pointSize > qt_antialiasing_threshold && !(fontDef.styleStrategy & QFont::NoAntialias)); + CGContextSetShouldAntialias(ctx, fontDef.pointSize > qt_antialiasing_threshold + && !(fontDef.styleStrategy & QFont::NoAntialias)); + CGContextSetShouldSmoothFonts(ctx, false); CGAffineTransform oldTextMatrix = CGContextGetTextMatrix(ctx); CGAffineTransform cgMatrix = CGAffineTransformMake(1, 0, 0, 1, 0, 0); -- cgit v0.12 From 5eec99263c9133e3a8177f463c537c75dfe9215b Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 11:24:33 +0200 Subject: add more tests --- tests/auto/qstatemachine/tst_qstatemachine.cpp | 89 ++++++++++++++++++++++---- 1 file changed, 75 insertions(+), 14 deletions(-) diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index 6b219d2..05c45ca 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -985,6 +985,7 @@ void tst_QStateMachine::rootState() QVERIFY(qobject_cast(machine.rootState()) != 0); QCOMPARE(qobject_cast(machine.rootState())->parentState(), (QState*)0); QCOMPARE(machine.rootState()->parent(), (QObject*)&machine); + QCOMPARE(machine.rootState()->machine(), &machine); QState *s1 = new QState(machine.rootState()); QCOMPARE(s1->parentState(), machine.rootState()); @@ -1006,7 +1007,9 @@ void tst_QStateMachine::addAndRemoveState() QState *s1 = new QState(); QCOMPARE(s1->parentState(), (QState*)0); + QCOMPARE(s1->machine(), (QStateMachine*)0); machine.addState(s1); + QCOMPARE(s1->machine(), &machine); QCOMPARE(s1->parentState(), machine.rootState()); QCOMPARE(root_d->childStates().size(), 2); QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); @@ -1063,8 +1066,29 @@ void tst_QStateMachine::stateEntryAndExit() TestState *s2 = new TestState(machine.rootState()); QFinalState *s3 = new QFinalState(machine.rootState()); + TestTransition *t = new TestTransition(s2); + QCOMPARE(t->machine(), (QStateMachine*)0); + QCOMPARE(t->sourceState(), (QState*)0); + QCOMPARE(t->targetState(), s2); + QCOMPARE(t->targetStates().size(), 1); + QCOMPARE(t->targetStates().at(0), s2); + t->setTargetState(0); + QCOMPARE(t->targetState(), (QState*)0); + QVERIFY(t->targetStates().isEmpty()); + t->setTargetState(s2); + QCOMPARE(t->targetState(), s2); + QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::setTargetStates: target state(s) cannot be null"); + t->setTargetStates(QList() << 0); + QCOMPARE(t->targetState(), s2); + t->setTargetStates(QList() << s2); + QCOMPARE(t->targetState(), s2); + QCOMPARE(t->targetStates().size(), 1); + QCOMPARE(t->targetStates().at(0), s2); QCOMPARE(s1->addTransition(t), (QAbstractTransition*)t); + QCOMPARE(t->sourceState(), s1); + QCOMPARE(t->machine(), &machine); + { QAbstractTransition *trans = s2->addTransition(s3); QVERIFY(trans != 0); @@ -1081,6 +1105,7 @@ void tst_QStateMachine::stateEntryAndExit() QSignalSpy stoppedSpy(&machine, SIGNAL(stopped())); QSignalSpy finishedSpy(&machine, SIGNAL(finished())); machine.setInitialState(s1); + QCOMPARE(machine.initialState(), (QAbstractState*)s1); QVERIFY(machine.configuration().isEmpty()); globalTick = 0; QVERIFY(!machine.isRunning()); @@ -1222,9 +1247,22 @@ void tst_QStateMachine::assignPropertyWithAnimation() s2->assignProperty(&obj, "foo", 456); s2->assignProperty(&obj, "bar", 789); QAbstractTransition *trans = s1->addTransition(s2); + QVERIFY(trans->animations().isEmpty()); + QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::addAnimation: cannot add null animation"); + trans->addAnimation(0); QPropertyAnimation anim(&obj, "foo"); anim.setDuration(250); trans->addAnimation(&anim); + QCOMPARE(trans->animations().size(), 1); + QCOMPARE(trans->animations().at(0), (QAbstractAnimation*)&anim); + QCOMPARE(anim.parent(), (QObject*)0); + QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::removeAnimation: cannot remove null animation"); + trans->removeAnimation(0); + trans->removeAnimation(&anim); + QVERIFY(trans->animations().isEmpty()); + trans->addAnimation(&anim); + QCOMPARE(trans->animations().size(), 1); + QCOMPARE(trans->animations().at(0), (QAbstractAnimation*)&anim); QFinalState *s3 = new QFinalState(machine.rootState()); s2->addTransition(s2, SIGNAL(polished()), s3); @@ -1548,8 +1586,8 @@ Q_SIGNALS: class TestSignalTransition : public QSignalTransition { public: - TestSignalTransition() - : QSignalTransition() {} + TestSignalTransition(QState *sourceState = 0) + : QSignalTransition(sourceState) {} TestSignalTransition(QObject *sender, const char *signal, QAbstractState *target) : QSignalTransition(sender, signal, QList() << target) {} @@ -1722,15 +1760,23 @@ void tst_QStateMachine::signalTransitions() void tst_QStateMachine::eventTransitions() { QPushButton button; - { + for (int x = 0; x < 2; ++x) { QStateMachine machine; QState *s0 = new QState(machine.rootState()); QFinalState *s1 = new QFinalState(machine.rootState()); - QMouseEventTransition *trans = new QMouseEventTransition(&button, QEvent::MouseButtonPress, Qt::LeftButton); + QMouseEventTransition *trans; + if (x == 0) { + trans = new QMouseEventTransition(&button, QEvent::MouseButtonPress, Qt::LeftButton); + QCOMPARE(trans->targetState(), (QAbstractState*)0); + trans->setTargetState(s1); + } else { + trans = new QMouseEventTransition(&button, QEvent::MouseButtonPress, + Qt::LeftButton, QList() << s1); + } QCOMPARE(trans->eventType(), QEvent::MouseButtonPress); QCOMPARE(trans->button(), Qt::LeftButton); - trans->setTargetState(s1); + QCOMPARE(trans->targetState(), (QAbstractState*)s1); s0->addTransition(trans); QSignalSpy finishedSpy(&machine, SIGNAL(finished())); @@ -1739,25 +1785,40 @@ void tst_QStateMachine::eventTransitions() QCoreApplication::processEvents(); QTest::mousePress(&button, Qt::LeftButton); - QCoreApplication::processEvents(); - QTRY_COMPARE(finishedSpy.count(), 1); QTest::mousePress(&button, Qt::LeftButton); + + trans->setEventType(QEvent::MouseButtonRelease); + QCOMPARE(trans->eventType(), QEvent::MouseButtonRelease); + machine.start(); + QCoreApplication::processEvents(); + QTest::mouseRelease(&button, Qt::LeftButton); + QTRY_COMPARE(finishedSpy.count(), 2); } - { + for (int x = 0; x < 3; ++x) { QStateMachine machine; QState *s0 = new QState(machine.rootState()); QFinalState *s1 = new QFinalState(machine.rootState()); - QEventTransition *trans = new QEventTransition(); - QCOMPARE(trans->eventObject(), (QObject*)0); - QCOMPARE(trans->eventType(), QEvent::None); - trans->setEventObject(&button); + QEventTransition *trans; + if (x == 0) { + trans = new QEventTransition(); + QCOMPARE(trans->eventObject(), (QObject*)0); + QCOMPARE(trans->eventType(), QEvent::None); + trans->setEventObject(&button); + trans->setEventType(QEvent::MouseButtonPress); + trans->setTargetState(s1); + } else if (x == 1) { + trans = new QEventTransition(&button, QEvent::MouseButtonPress); + trans->setTargetState(s1); + } else { + trans = new QEventTransition(&button, QEvent::MouseButtonPress, + QList() << s1); + } QCOMPARE(trans->eventObject(), (QObject*)&button); - trans->setEventType(QEvent::MouseButtonPress); QCOMPARE(trans->eventType(), QEvent::MouseButtonPress); - trans->setTargetState(s1); + QCOMPARE(trans->targetState(), (QAbstractState*)s1); s0->addTransition(trans); QSignalSpy finishedSpy(&machine, SIGNAL(finished())); -- cgit v0.12 From 6c1d7e57ee8d7988ab9592e4112b1f28fd1d03ce Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Mon, 4 May 2009 20:49:41 +0200 Subject: Fixed strict aliasing breaks with sockaddr_XXX structs. This case it was possible to fix by using a union of the types when we actually declare the variable. Besides, this avoids a bunch of #ifdef for IPv6 functionality. Reviewed-By: Oswald Buddenhagen --- src/network/socket/qnativesocketengine_p.h | 9 ++++ src/network/socket/qnativesocketengine_unix.cpp | 61 ++++++++----------------- 2 files changed, 29 insertions(+), 41 deletions(-) diff --git a/src/network/socket/qnativesocketengine_p.h b/src/network/socket/qnativesocketengine_p.h index 3366f2d..825c333 100644 --- a/src/network/socket/qnativesocketengine_p.h +++ b/src/network/socket/qnativesocketengine_p.h @@ -90,6 +90,15 @@ static inline int qt_socket_socket(int domain, int type, int protocol) #endif +union qt_sockaddr { + sockaddr a; + sockaddr_in a4; +#if !defined(QT_NO_IPV6) + sockaddr_in6 a6; +#endif + sockaddr_storage storage; +}; + class QNativeSocketEnginePrivate; class Q_AUTOTEST_EXPORT QNativeSocketEngine : public QAbstractSocketEngine diff --git a/src/network/socket/qnativesocketengine_unix.cpp b/src/network/socket/qnativesocketengine_unix.cpp index cc372a6..2b11e8e 100644 --- a/src/network/socket/qnativesocketengine_unix.cpp +++ b/src/network/socket/qnativesocketengine_unix.cpp @@ -114,36 +114,34 @@ static void qt_ignore_sigpipe() Extracts the port and address from a sockaddr, and stores them in \a port and \a addr if they are non-null. */ -static inline void qt_socket_getPortAndAddress(struct sockaddr *sa, quint16 *port, QHostAddress *addr) +static inline void qt_socket_getPortAndAddress(const qt_sockaddr *s, quint16 *port, QHostAddress *addr) { #if !defined(QT_NO_IPV6) - if (sa->sa_family == AF_INET6) { - struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa; + if (s->a.sa_family == AF_INET6) { Q_IPV6ADDR tmp; - memcpy(&tmp, &sa6->sin6_addr.s6_addr, sizeof(tmp)); + memcpy(&tmp, &s->a6.sin6_addr.s6_addr, sizeof(tmp)); if (addr) { QHostAddress tmpAddress; tmpAddress.setAddress(tmp); *addr = tmpAddress; #ifndef QT_NO_IPV6IFNAME char scopeid[IFNAMSIZ]; - if (::if_indextoname(sa6->sin6_scope_id, scopeid) > 0) { + if (::if_indextoname(s->a6.sin6_scope_id, scopeid) > 0) { addr->setScopeId(QLatin1String(scopeid)); } else #endif - addr->setScopeId(QString::number(sa6->sin6_scope_id)); + addr->setScopeId(QString::number(s->a6.sin6_scope_id)); } if (port) - *port = ntohs(sa6->sin6_port); + *port = ntohs(s->a6.sin6_port); return; } #endif - struct sockaddr_in *sa4 = (struct sockaddr_in *)sa; if (port) - *port = ntohs(sa4->sin_port); + *port = ntohs(s->a4.sin_port); if (addr) { QHostAddress tmpAddress; - tmpAddress.setAddress(ntohl(sa4->sin_addr.s_addr)); + tmpAddress.setAddress(ntohl(s->a4.sin_addr.s_addr)); *addr = tmpAddress; } } @@ -521,26 +519,16 @@ qint64 QNativeSocketEnginePrivate::nativeBytesAvailable() const bool QNativeSocketEnginePrivate::nativeHasPendingDatagrams() const { // Create a sockaddr struct and reset its port number. -#if !defined(QT_NO_IPV6) - struct sockaddr_storage storage; - sockaddr_in6 *storagePtrIPv6 = reinterpret_cast(&storage); - storagePtrIPv6->sin6_port = 0; -#else - struct sockaddr storage; -#endif - sockaddr *storagePtr = reinterpret_cast(&storage); - storagePtr->sa_family = 0; - - sockaddr_in *storagePtrIPv4 = reinterpret_cast(&storage); - storagePtrIPv4->sin_port = 0; + qt_sockaddr storage; QT_SOCKLEN_T storageSize = sizeof(storage); + memset(&storage, 0, storageSize); // Peek 0 bytes into the next message. The size of the message may // well be 0, so we can't check recvfrom's return value. ssize_t readBytes; do { char c; - readBytes = ::recvfrom(socketDescriptor, &c, 1, MSG_PEEK, storagePtr, &storageSize); + readBytes = ::recvfrom(socketDescriptor, &c, 1, MSG_PEEK, &storage.a, &storageSize); } while (readBytes == -1 && errno == EINTR); // If there's no error, or if our buffer was too small, there must be a @@ -583,11 +571,7 @@ qint64 QNativeSocketEnginePrivate::nativePendingDatagramSize() const qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxSize, QHostAddress *address, quint16 *port) { -#if !defined(QT_NO_IPV6) - struct sockaddr_storage aa; -#else - struct sockaddr_in aa; -#endif + qt_sockaddr aa; memset(&aa, 0, sizeof(aa)); QT_SOCKLEN_T sz; sz = sizeof(aa); @@ -596,13 +580,13 @@ qint64 QNativeSocketEnginePrivate::nativeReceiveDatagram(char *data, qint64 maxS do { char c; recvFromResult = ::recvfrom(socketDescriptor, maxSize ? data : &c, maxSize ? maxSize : 1, - 0, (struct sockaddr *)&aa, &sz); + 0, &aa.a, &sz); } while (recvFromResult == -1 && errno == EINTR); if (recvFromResult == -1) { setError(QAbstractSocket::NetworkError, ReceiveDatagramErrorString); } else if (port || address) { - qt_socket_getPortAndAddress((struct sockaddr *) &aa, port, address); + qt_socket_getPortAndAddress(&aa, port, address); } #if defined (QNATIVESOCKETENGINE_DEBUG) @@ -682,21 +666,16 @@ bool QNativeSocketEnginePrivate::fetchConnectionParameters() if (socketDescriptor == -1) return false; -#if !defined(QT_NO_IPV6) - struct sockaddr_storage sa; -#else - struct sockaddr_in sa; -#endif - struct sockaddr *sockAddrPtr = (struct sockaddr *) &sa; + qt_sockaddr sa; QT_SOCKLEN_T sockAddrSize = sizeof(sa); // Determine local address memset(&sa, 0, sizeof(sa)); - if (::getsockname(socketDescriptor, sockAddrPtr, &sockAddrSize) == 0) { - qt_socket_getPortAndAddress(sockAddrPtr, &localPort, &localAddress); + if (::getsockname(socketDescriptor, &sa.a, &sockAddrSize) == 0) { + qt_socket_getPortAndAddress(&sa, &localPort, &localAddress); // Determine protocol family - switch (sockAddrPtr->sa_family) { + switch (sa.a.sa_family) { case AF_INET: socketProtocol = QAbstractSocket::IPv4Protocol; break; @@ -716,8 +695,8 @@ bool QNativeSocketEnginePrivate::fetchConnectionParameters() } // Determine the remote address - if (!::getpeername(socketDescriptor, sockAddrPtr, &sockAddrSize)) - qt_socket_getPortAndAddress(sockAddrPtr, &peerPort, &peerAddress); + if (!::getpeername(socketDescriptor, &sa.a, &sockAddrSize)) + qt_socket_getPortAndAddress(&sa, &peerPort, &peerAddress); // Determine the socket type (UDP/TCP) int value = 0; -- cgit v0.12 From 5a62f2add2cba756a132f94a114d770285f01d9c Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Tue, 19 May 2009 18:10:06 +0200 Subject: Add an autotest to check that the network test server works MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This test verifies that the network test server is behaving as expected. I think I caught all the services we need testing in the server, but there's still some work to be done: 1) verify that the FTP files are there where they're supposed to be 2) verify that FTP writable areas are writable 3) verify that the HTTP server has the correct files too 4) verify that the HTTP server requests credentials for the protected area 5) attempt to do NTLM authentication to verify the password (probably can't be done with netChat) 6) add Windows SMB tests (//qt-test-server/etc.) 7) add SQL tests (connecting to the SQL server ports) It would be good as well if we could not use QtNetwork. If you break QtNetwork, this test breaks too, so we don't know where the fault is. However, rewriting networking code will add another source of bugs (same for the NTLM authentication). Reviewed-By: João Abecasis --- tests/auto/_networkselftest/_networkselftest.pro | 6 + .../auto/_networkselftest/tst_networkselftest.cpp | 592 +++++++++++++++++++++ tests/auto/auto.pro | 3 +- 3 files changed, 600 insertions(+), 1 deletion(-) create mode 100644 tests/auto/_networkselftest/_networkselftest.pro create mode 100644 tests/auto/_networkselftest/tst_networkselftest.cpp diff --git a/tests/auto/_networkselftest/_networkselftest.pro b/tests/auto/_networkselftest/_networkselftest.pro new file mode 100644 index 0000000..9e2ad0e --- /dev/null +++ b/tests/auto/_networkselftest/_networkselftest.pro @@ -0,0 +1,6 @@ +load(qttest_p4) + +SOURCES += tst_networkselftest.cpp +QT = core network +DEFINES += SRCDIR=\\\"$$PWD\\\" + diff --git a/tests/auto/_networkselftest/tst_networkselftest.cpp b/tests/auto/_networkselftest/tst_networkselftest.cpp new file mode 100644 index 0000000..dab4433 --- /dev/null +++ b/tests/auto/_networkselftest/tst_networkselftest.cpp @@ -0,0 +1,592 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include "../network-settings.h" + +class tst_NetworkSelfTest: public QObject +{ + Q_OBJECT +private slots: + void hostTest(); + void dnsResolution_data(); + void dnsResolution(); + void serverReachability(); + void remotePortsOpen_data(); + void remotePortsOpen(); + + // specific protocol tests + void ftpServer(); + void imapServer(); + void httpServer(); + void httpsServer(); + void httpProxy(); + void httpProxyBasicAuth(); + void httpProxyNtlmAuth(); + void socks5Proxy(); + void socks5ProxyAuth(); +}; + +class Chat +{ +public: + enum Type { + Reconnect, + Send, + Expect, + SkipBytes, + DiscardUntil, + DiscardUntilDisconnect, + Disconnect, + RemoteDisconnect, + StartEncryption + }; + Chat(Type t, const QByteArray &d) + : data(d), type(t) + { + } + Chat(Type t, int val = 0) + : value(val), type(t) + { + } + + static inline Chat send(const QByteArray &data) + { return Chat(Send, data); } + static inline Chat expect(const QByteArray &data) + { return Chat(Expect, data); } + static inline Chat discardUntil(const QByteArray &data) + { return Chat(DiscardUntil, data); } + static inline Chat skipBytes(int count) + { return Chat(SkipBytes, count); } + + QByteArray data; + int value; + Type type; +}; + +static QString prettyByteArray(const QByteArray &array) +{ + // any control chars? + QString result; + result.reserve(array.length() + array.length() / 3); + for (int i = 0; i < array.length(); ++i) { + char c = array.at(i); + switch (c) { + case '\n': + result += "\\n"; + continue; + case '\r': + result += "\\r"; + continue; + case '\t': + result += "\\t"; + continue; + case '"': + result += "\\\""; + continue; + default: + break; + } + + if (c < 0x20 || uchar(c) >= 0x7f) { + result += '\\'; + result += QString::number(uchar(c), 8); + } else { + result += c; + } + } + return result; +} + +static bool doSocketRead(QTcpSocket *socket, int minBytesAvailable, int timeout = 2000) +{ + QTime timer; + timer.start(); + forever { + if (socket->bytesAvailable() >= minBytesAvailable) + return true; + if (socket->state() == QAbstractSocket::UnconnectedState + || timer.elapsed() >= timeout) + return false; + if (!socket->waitForReadyRead(timeout - timer.elapsed())) + return false; + } +} + +static bool doSocketFlush(QTcpSocket *socket, int timeout = 2000) +{ +#ifndef QT_NO_OPENSSL + QSslSocket *sslSocket = qobject_cast(socket); +#endif + QTime timer; + timer.start(); + forever { + if (socket->bytesToWrite() == 0 +#ifndef QT_NO_OPENSSL + && sslSocket->encryptedBytesToWrite() == 0 +#endif + ) + return true; + if (socket->state() == QAbstractSocket::UnconnectedState + || timer.elapsed() >= timeout) + return false; + if (!socket->waitForBytesWritten(timeout - timer.elapsed())) + return false; + } +} + +static void netChat(int port, const QList &chat) +{ +#ifndef QT_NO_OPENSSL + QSslSocket socket; +#else + QTcpSocket socket; +#endif + + socket.connectToHost(QtNetworkSettings::serverName(), port); + qDebug() << 0 << "Connecting to server on port" << port; + QVERIFY2(socket.waitForConnected(10000), + QString("Failed to connect to server in step 0: %1").arg(socket.errorString()).toLocal8Bit()); + + // now start the chat + QList::ConstIterator it = chat.constBegin(); + for (int i = 1; it != chat.constEnd(); ++it, ++i) { + if (it->type != Chat::Reconnect + && socket.state() != QAbstractSocket::ConnectedState + && socket.state() != QAbstractSocket::ClosingState) + QFAIL(QString("Internal error: socket is in invalid state %1 in step %2") + .arg(socket.state()).arg(i).toLocal8Bit()); + + switch (it->type) { + case Chat::Expect: { + qDebug() << i << "Expecting" << prettyByteArray(it->data); + if (!doSocketRead(&socket, it->data.length())) + QFAIL(QString("Failed to receive data in step %1: timeout").arg(i).toLocal8Bit()); + + // pop that many bytes off the socket + QByteArray received = socket.read(it->data.length()); + + // is it what we expected? + QVERIFY2(received == it->data, + QString("Did not receive expected data in step %1: data received was:\n%2") + .arg(i).arg(prettyByteArray(received)).toLocal8Bit()); + + break; + } + + case Chat::DiscardUntil: + qDebug() << i << "Discarding until" << prettyByteArray(it->data); + while (true) { + // scan the buffer until we have our string + if (!doSocketRead(&socket, it->data.length())) + QFAIL(QString("Failed to receive data in step %1: timeout").arg(i).toLocal8Bit()); + + QByteArray buffer; + buffer.resize(socket.bytesAvailable()); + socket.peek(buffer.data(), socket.bytesAvailable()); + + int pos = buffer.indexOf(it->data); + if (pos == -1) { + // data not found, keep trying + continue; + } + + buffer = socket.read(pos + it->data.length()); + qDebug() << i << "Discarded" << prettyByteArray(buffer); + break; + } + break; + + case Chat::SkipBytes: { + qDebug() << i << "Skipping" << it->value << "bytes"; + if (!doSocketRead(&socket, it->value)) + QFAIL(QString("Failed to receive data in step %1: timeout").arg(i).toLocal8Bit()); + + // now discard the bytes + QByteArray buffer = socket.read(it->value); + qDebug() << i << "Skipped" << prettyByteArray(buffer); + break; + } + + case Chat::Send: { + qDebug() << i << "Sending" << prettyByteArray(it->data); + socket.write(it->data); + if (!doSocketFlush(&socket)) { + QVERIFY2(socket.state() == QAbstractSocket::ConnectedState, + QString("Socket disconnected while sending data in step %1").arg(i).toLocal8Bit()); + QFAIL(QString("Failed to send data in step %1: timeout").arg(i).toLocal8Bit()); + } + break; + } + + case Chat::Disconnect: + qDebug() << i << "Disconnecting from host"; + socket.disconnectFromHost(); + + // is this the last command? + if (it + 1 != chat.constEnd()) + break; + + // fall through: + case Chat::RemoteDisconnect: + case Chat::DiscardUntilDisconnect: + qDebug() << i << "Waiting for remote disconnect"; + if (socket.state() != QAbstractSocket::UnconnectedState) + socket.waitForDisconnected(10000); + QVERIFY2(socket.state() == QAbstractSocket::UnconnectedState, + QString("Socket did not disconnect as expected in step %1").arg(i).toLocal8Bit()); + + // any data left? + if (it->type == Chat::DiscardUntilDisconnect) { + QByteArray buffer = socket.readAll(); + qDebug() << i << "Discarded in the process:" << prettyByteArray(buffer); + } + + if (socket.bytesAvailable() != 0) + QFAIL(QString("Unexpected bytes still on buffer when disconnecting in step %1:\n%2") + .arg(i).arg(prettyByteArray(socket.readAll())).toLocal8Bit()); + break; + + case Chat::Reconnect: + qDebug() << i << "Reconnecting to server on port" << port; + socket.connectToHost(QtNetworkSettings::serverName(), port); + QVERIFY2(socket.waitForConnected(10000), + QString("Failed to reconnect to server in step %1: %2").arg(i).arg(socket.errorString()).toLocal8Bit()); + break; + + case Chat::StartEncryption: +#ifdef QT_NO_OPENSSL + QFAIL("Internal error: SSL required for this test"); +#else + qDebug() << i << "Starting client encryption"; + socket.ignoreSslErrors(); + socket.startClientEncryption(); + QVERIFY2(socket.waitForEncrypted(5000), + QString("Failed to start client encryption in step %1: %2").arg(i) + .arg(socket.errorString()).toLocal8Bit()); + break; +#endif + } + } +} + +void tst_NetworkSelfTest::hostTest() +{ + // this is a localhost self-test + QHostInfo localhost = QHostInfo::fromName("localhost"); + QCOMPARE(localhost.error(), QHostInfo::NoError); + QVERIFY(!localhost.addresses().isEmpty()); + + QTcpServer server; + QVERIFY(server.listen()); + + QTcpSocket socket; + socket.connectToHost("127.0.0.1", server.serverPort()); + QVERIFY(socket.waitForConnected(10000)); +} + +void tst_NetworkSelfTest::dnsResolution_data() +{ + QTest::addColumn("hostName"); + QTest::newRow("local-name") << QtNetworkSettings::serverLocalName(); + QTest::newRow("fqdn") << QtNetworkSettings::serverName(); +} + +void tst_NetworkSelfTest::dnsResolution() +{ + QFETCH(QString, hostName); + QHostInfo resolved = QHostInfo::fromName(hostName); + QVERIFY2(resolved.error() == QHostInfo::NoError, + QString("Failed to resolve hostname %1: %2").arg(hostName, resolved.errorString()).toLocal8Bit()); +} + +void tst_NetworkSelfTest::serverReachability() +{ + // check that we get a proper error connecting to port 1 + QTcpSocket socket; + socket.connectToHost(QtNetworkSettings::serverName(), 1); + socket.waitForConnected(10000); + QVERIFY2(socket.state() == QAbstractSocket::UnconnectedState, "Socket connected unexpectedly!"); + QVERIFY2(socket.error() == QAbstractSocket::ConnectionRefusedError, + QString("Could not reach server: %1").arg(socket.errorString()).toLocal8Bit()); +} + +void tst_NetworkSelfTest::remotePortsOpen_data() +{ + QTest::addColumn("portNumber"); + QTest::newRow("ftp") << 21; + QTest::newRow("ssh") << 22; + QTest::newRow("imap") << 143; + QTest::newRow("http") << 80; + QTest::newRow("https") << 443; + QTest::newRow("http-proxy") << 3128; + QTest::newRow("http-proxy-auth-basic") << 3129; + QTest::newRow("http-proxy-auth-ntlm") << 3130; + QTest::newRow("socks5-proxy") << 1080; + QTest::newRow("socks5-proxy-auth") << 1081; +} + +void tst_NetworkSelfTest::remotePortsOpen() +{ + QFETCH(int, portNumber); + QTcpSocket socket; + socket.connectToHost(QtNetworkSettings::serverName(), portNumber); + + if (!socket.waitForConnected(10000)) { + if (socket.error() == QAbstractSocket::SocketTimeoutError) + QFAIL(QString("Network timeout connecting to the server on port %1").arg(portNumber).toLocal8Bit()); + else + QFAIL(QString("Error connecting to server on port %1: %2").arg(portNumber).arg(socket.errorString()).toLocal8Bit()); + } + QVERIFY(socket.state() == QAbstractSocket::ConnectedState); +} + +static QList ftpChat() +{ + return QList() << Chat::expect("220") + << Chat::discardUntil("\r\n") + << Chat::send("USER anonymous\r\n") + << Chat::expect("331") + << Chat::discardUntil("\r\n") + << Chat::send("PASS user@hostname\r\n") + << Chat::expect("230") + << Chat::discardUntil("\r\n") + << Chat::send("QUIT\r\n") + << Chat::expect("221") + << Chat::discardUntil("\r\n") + << Chat::RemoteDisconnect; +} + +void tst_NetworkSelfTest::ftpServer() +{ + netChat(21, ftpChat()); +} + +void tst_NetworkSelfTest::imapServer() +{ + netChat(143, QList() + << Chat::expect("* OK ") + << Chat::discardUntil("\r\n") + << Chat::send("1 CAPABILITY\r\n") + << Chat::expect("* CAPABILITY ") + << Chat::discardUntil("1 OK") + << Chat::discardUntil("\r\n") + << Chat::send("2 LOGOUT\r\n") + << Chat::discardUntil("2 OK") + << Chat::discardUntil("\r\n") + << Chat::RemoteDisconnect); +} + +void tst_NetworkSelfTest::httpServer() +{ + netChat(80, QList() + // HTTP/0.9 chat: + << Chat::send("GET /\r\n") + << Chat::DiscardUntilDisconnect + + // HTTP/1.0 chat: + << Chat::Reconnect + << Chat::send("GET / HTTP/1.0\r\n" + "Host: " + QtNetworkSettings::serverName().toLatin1() + "\r\n" + "Connection: close\r\n" + "\r\n") + << Chat::expect("HTTP/1.") + << Chat::discardUntil(" ") + << Chat::expect("200 ") + << Chat::DiscardUntilDisconnect + + // HTTP/1.0 POST: + << Chat::Reconnect + << Chat::send("POST / HTTP/1.0\r\n" + "Content-Length: 5\r\n" + "Host: " + QtNetworkSettings::serverName().toLatin1() + "\r\n" + "Connection: close\r\n" + "\r\n" + "Hello") + << Chat::expect("HTTP/1.") + << Chat::discardUntil(" ") + << Chat::expect("200 ") + << Chat::DiscardUntilDisconnect + ); +} + +void tst_NetworkSelfTest::httpsServer() +{ +#ifndef QT_NO_OPENSSL + netChat(443, QList() + << Chat::StartEncryption + << Chat::send("GET / HTTP/1.0\r\n" + "Host: " + QtNetworkSettings::serverName().toLatin1() + "\r\n" + "Connection: close\r\n" + "\r\n") + << Chat::expect("HTTP/1.") + << Chat::discardUntil(" ") + << Chat::expect("200 ") + << Chat::DiscardUntilDisconnect); +#else + QSKIP("SSL not enabled, cannot test"); +#endif +} + +void tst_NetworkSelfTest::httpProxy() +{ + netChat(3128, QList() + // proxy GET + << Chat::send("GET http://" + QtNetworkSettings::serverName().toLatin1() + "/ HTTP/1.0\r\n" + "Host: " + QtNetworkSettings::serverName().toLatin1() + "\r\n" + "Proxy-connection: close\r\n" + "\r\n") + << Chat::expect("HTTP/1.") + << Chat::discardUntil(" ") + << Chat::expect("200 ") + << Chat::DiscardUntilDisconnect + + // proxy CONNECT + << Chat::Reconnect + << Chat::send("CONNECT " + QtNetworkSettings::serverName().toLatin1() + ":21 HTTP/1.0\r\n" + "\r\n") + << Chat::expect("HTTP/1.") + << Chat::discardUntil(" ") + << Chat::expect("200 ") + << Chat::discardUntil("\r\n\r\n") + << ftpChat()); +} + +void tst_NetworkSelfTest::httpProxyBasicAuth() +{ + netChat(3129, QList() + // test auth required response + << Chat::send("GET http://" + QtNetworkSettings::serverName().toLatin1() + "/ HTTP/1.0\r\n" + "Host: " + QtNetworkSettings::serverName().toLatin1() + "\r\n" + "Proxy-connection: close\r\n" + "\r\n") + << Chat::expect("HTTP/1.") + << Chat::discardUntil(" ") + << Chat::expect("407 ") + << Chat::discardUntil("\r\nProxy-Authenticate: Basic realm=\"") + << Chat::DiscardUntilDisconnect + + // now try sending our credentials + << Chat::Reconnect + << Chat::send("GET http://" + QtNetworkSettings::serverName().toLatin1() + "/ HTTP/1.0\r\n" + "Host: " + QtNetworkSettings::serverName().toLatin1() + "\r\n" + "Proxy-connection: close\r\n" + "Proxy-Authorization: Basic cXNvY2tzdGVzdDpwYXNzd29yZA==\r\n" + "\r\n") + << Chat::expect("HTTP/1.") + << Chat::discardUntil(" ") + << Chat::expect("200 ") + << Chat::DiscardUntilDisconnect); +} + +void tst_NetworkSelfTest::httpProxyNtlmAuth() +{ + netChat(3130, QList() + // test auth required response + << Chat::send("GET http://" + QtNetworkSettings::serverName().toLatin1() + "/ HTTP/1.0\r\n" + "Host: " + QtNetworkSettings::serverName().toLatin1() + "\r\n" + "Proxy-connection: keep-alive\r\n" // NTLM auth will disconnect + "\r\n") + << Chat::expect("HTTP/1.") + << Chat::discardUntil(" ") + << Chat::expect("407 ") + << Chat::discardUntil("\r\nProxy-Authenticate: NTLM\r\n") + << Chat::DiscardUntilDisconnect + ); +} + +// SOCKSv5 is a binary protocol +static const char handshakeNoAuth[] = "\5\1\0"; +static const char handshakeOkNoAuth[] = "\5\0"; +static const char handshakeAuthPassword[] = "\5\1\2\1\12qsockstest\10password"; +static const char handshakeOkPasswdAuth[] = "\5\2\1\0"; +static const char handshakeAuthNotOk[] = "\5\377"; +static const char connect1[] = "\5\1\0\1\177\0\0\1\0\25"; // Connect IPv4 127.0.0.1 port 21 +static const char connect2[] = "\5\1\0\3\11localhost\0\25"; // Connect hostname localhost 21 +static const char connected[] = "\5\0\0"; + +void tst_NetworkSelfTest::socks5Proxy() +{ + netChat(1080, QList() + // IP address connection + << Chat::send(QByteArray(handshakeNoAuth, -1 + sizeof handshakeNoAuth)) + << Chat::expect(QByteArray(handshakeOkNoAuth, -1 + sizeof handshakeOkNoAuth)) + << Chat::send(QByteArray(connect1, -1 + sizeof connect1)) + << Chat::expect(QByteArray(connected, -1 + sizeof connected)) + << Chat::expect("\1") // IPv4 address following + << Chat::skipBytes(6) // the server's local address and port + << ftpChat() + + // hostname connection + << Chat::Reconnect + << Chat::send(QByteArray(handshakeNoAuth, -1 + sizeof handshakeNoAuth)) + << Chat::expect(QByteArray(handshakeOkNoAuth, -1 + sizeof handshakeOkNoAuth)) + << Chat::send(QByteArray(connect2, -1 + sizeof connect2)) + << Chat::expect(QByteArray(connected, -1 + sizeof connected)) + << Chat::expect("\1") // IPv4 address following + << Chat::skipBytes(6) // the server's local address and port + << ftpChat() + ); +} + +void tst_NetworkSelfTest::socks5ProxyAuth() +{ + netChat(1081, QList() + // unauthenticated connect -- will get error + << Chat::send(QByteArray(handshakeNoAuth, -1 + sizeof handshakeNoAuth)) + << Chat::expect(QByteArray(handshakeAuthNotOk, -1 + sizeof handshakeAuthNotOk)) + << Chat::RemoteDisconnect + + // now try to connect with authentication + << Chat::Reconnect + << Chat::send(QByteArray(handshakeAuthPassword, -1 + sizeof handshakeAuthPassword)) + << Chat::expect(QByteArray(handshakeOkPasswdAuth, -1 + sizeof handshakeOkPasswdAuth)) + << Chat::send(QByteArray(connect1, -1 + sizeof connect1)) + << Chat::expect(QByteArray(connected, -1 + sizeof connected)) + << Chat::expect("\1") // IPv4 address following + << Chat::skipBytes(6) // the server's local address and port + << ftpChat() + ); +} + +QTEST_MAIN(tst_NetworkSelfTest) +#include "tst_networkselftest.moc" diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro index 60e6657..1cdb840 100644 --- a/tests/auto/auto.pro +++ b/tests/auto/auto.pro @@ -4,7 +4,8 @@ TEMPLATE = subdirs !wince*:SUBDIRS += \ headers -SUBDIRS += bic \ +SUBDIRS += _networkselftest \ + bic \ collections \ compile \ compilerwarnings \ -- cgit v0.12 From 87911c6c97b11bd7d10a38698460174b6cadfbe8 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Wed, 20 May 2009 09:50:47 +0200 Subject: Fix a leak because of an old legacy of QPixmapCache string API We have to replace the pixmap in the cache if it was previously there, we don't need to insert a new pixmap if a full update has been triggered. Reviewed-by:mbm --- src/gui/graphicsview/qgraphicsscene.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 1fbda85..126ea5b 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -4759,10 +4759,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } // Find pixmap in cache. - if (!itemCache->allExposed) - pixmapFound = QPixmapCache::find(pixmapKey, &pix); - else - pixmapFound = false; + pixmapFound = QPixmapCache::find(pixmapKey, &pix); // Render using item coordinate cache mode. if (cacheMode == QGraphicsItem::ItemCoordinateCache) { -- cgit v0.12 From 2a8d3ae2a4cf0eeaf007ad9a8fd9543aed9da3da Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 12:08:30 +0200 Subject: add more tests --- tests/auto/qstatemachine/tst_qstatemachine.cpp | 188 ++++++++++++++++--------- 1 file changed, 124 insertions(+), 64 deletions(-) diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index 05c45ca..40c01bd 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -931,6 +931,7 @@ void tst_QStateMachine::customErrorStateNotInGraph() void tst_QStateMachine::restoreProperties() { QStateMachine machine; + QCOMPARE(machine.globalRestorePolicy(), QStateMachine::DoNotRestoreProperties); machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); QObject *object = new QObject(&machine); @@ -1094,6 +1095,12 @@ void tst_QStateMachine::stateEntryAndExit() QVERIFY(trans != 0); QCOMPARE(trans->sourceState(), (QAbstractState*)s2); QCOMPARE(trans->targetState(), (QAbstractState*)s3); + { + char warning[256]; + sprintf(warning, "QState::removeTransition: transition %p's source state (%p) is different from this state (%p)", trans, s2, s1); + QTest::ignoreMessage(QtWarningMsg, warning); + s1->removeTransition(trans); + } s2->removeTransition(trans); QCOMPARE(trans->sourceState(), (QAbstractState*)0); QCOMPARE(trans->targetState(), (QAbstractState*)s3); @@ -1106,6 +1113,13 @@ void tst_QStateMachine::stateEntryAndExit() QSignalSpy finishedSpy(&machine, SIGNAL(finished())); machine.setInitialState(s1); QCOMPARE(machine.initialState(), (QAbstractState*)s1); + { + char warning[256]; + sprintf(warning, "QState::setInitialState: state %p is not a child of this state (%p)", machine.rootState(), machine.rootState()); + QTest::ignoreMessage(QtWarningMsg, warning); + machine.setInitialState(machine.rootState()); + QCOMPARE(machine.initialState(), (QAbstractState*)s1); + } QVERIFY(machine.configuration().isEmpty()); globalTick = 0; QVERIFY(!machine.isRunning()); @@ -1238,6 +1252,11 @@ void tst_QStateMachine::assignPropertyWithAnimation() // Single animation { QStateMachine machine; + QVERIFY(machine.animationsEnabled()); + machine.setAnimationsEnabled(false); + QVERIFY(!machine.animationsEnabled()); + machine.setAnimationsEnabled(true); + QVERIFY(machine.animationsEnabled()); QObject obj; obj.setProperty("foo", 321); obj.setProperty("bar", 654); @@ -1338,6 +1357,10 @@ void tst_QStateMachine::assignPropertyWithAnimation() obj.setProperty("bar", 654); QState *s1 = new QState(machine.rootState()); QCOMPARE(s1->childMode(), QState::ExclusiveStates); + s1->setChildMode(QState::ParallelStates); + QCOMPARE(s1->childMode(), QState::ParallelStates); + s1->setChildMode(QState::ExclusiveStates); + QCOMPARE(s1->childMode(), QState::ExclusiveStates); QCOMPARE(s1->initialState(), (QAbstractState*)0); s1->setObjectName("s1"); s1->assignProperty(&obj, "foo", 123); @@ -1411,47 +1434,59 @@ class StringEventPoster : public QState { public: StringEventPoster(QStateMachine *machine, const QString &value, QState *parent = 0) - : QState(parent), m_machine(machine), m_value(value) {} + : QState(parent), m_machine(machine), m_value(value), m_delay(0) {} void setString(const QString &value) { m_value = value; } + void setDelay(int delay) + { m_delay = delay; } protected: virtual void onEntry(QEvent *) { - m_machine->postEvent(new StringEvent(m_value)); + m_machine->postEvent(new StringEvent(m_value), m_delay); } virtual void onExit(QEvent *) {} private: QStateMachine *m_machine; QString m_value; + int m_delay; }; void tst_QStateMachine::postEvent() { - QStateMachine machine; - StringEventPoster *s1 = new StringEventPoster(&machine, "a"); - QFinalState *s2 = new QFinalState; - s1->addTransition(new StringTransition("a", s2)); - machine.addState(s1); - machine.addState(s2); - machine.setInitialState(s1); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s2)); + for (int x = 0; x < 2; ++x) { + QStateMachine machine; + { + QEvent e(QEvent::None); + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::postEvent: cannot post event when the state machine is not running"); + machine.postEvent(&e); + } + StringEventPoster *s1 = new StringEventPoster(&machine, "a"); + if (x == 1) + s1->setDelay(100); + QFinalState *s2 = new QFinalState; + s1->addTransition(new StringTransition("a", s2)); + machine.addState(s1); + machine.addState(s2); + machine.setInitialState(s1); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s2)); - s1->setString("b"); - QFinalState *s3 = new QFinalState(); - machine.addState(s3); - s1->addTransition(new StringTransition("b", s3)); - finishedSpy.clear(); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s3)); + s1->setString("b"); + QFinalState *s3 = new QFinalState(); + machine.addState(s3); + s1->addTransition(new StringTransition("b", s3)); + finishedSpy.clear(); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s3)); + } } void tst_QStateMachine::stateFinished() @@ -1488,6 +1523,12 @@ void tst_QStateMachine::parallelStates() QFinalState *s1_2_f = new QFinalState(s1_2); s1_2_1->addTransition(s1_2_f); s1_2->setInitialState(s1_2_1); + { + char warning[256]; + sprintf(warning, "QState::setInitialState: ignoring attempt to set initial state of parallel state group %p", s1); + QTest::ignoreMessage(QtWarningMsg, warning); + s1->setInitialState(0); + } machine.addState(s1); QFinalState *s2 = new QFinalState(); @@ -1955,53 +1996,72 @@ void tst_QStateMachine::eventTransitions() void tst_QStateMachine::historyStates() { - QStateMachine machine; - QState *root = machine.rootState(); - QState *s0 = new QState(root); - QState *s00 = new QState(s0); - QState *s01 = new QState(s0); - QHistoryState *s0h = new QHistoryState(s0); - QState *s1 = new QState(root); - QFinalState *s2 = new QFinalState(root); - - s00->addTransition(new StringTransition("a", s01)); - s0->addTransition(new StringTransition("b", s1)); - s1->addTransition(new StringTransition("c", s0h)); - s0->addTransition(new StringTransition("d", s2)); - - root->setInitialState(s0); - s0->setInitialState(s00); + for (int x = 0; x < 2; ++x) { + QStateMachine machine; + QState *root = machine.rootState(); + QState *s0 = new QState(root); + QState *s00 = new QState(s0); + QState *s01 = new QState(s0); + QHistoryState *s0h; + if (x == 0) { + s0h = new QHistoryState(s0); + QCOMPARE(s0h->historyType(), QHistoryState::ShallowHistory); + s0h->setHistoryType(QHistoryState::DeepHistory); + } else { + s0h = new QHistoryState(QHistoryState::DeepHistory, s0); + } + QCOMPARE(s0h->historyType(), QHistoryState::DeepHistory); + s0h->setHistoryType(QHistoryState::ShallowHistory); + QCOMPARE(s0h->historyType(), QHistoryState::ShallowHistory); + QCOMPARE(s0h->defaultState(), (QAbstractState*)0); + s0h->setDefaultState(s00); + QCOMPARE(s0h->defaultState(), (QAbstractState*)s00); + char warning[256]; + sprintf(warning, "QHistoryState::setDefaultState: state %p does not belong to this history state's group (%p)", s0, s0); + QTest::ignoreMessage(QtWarningMsg, warning); + s0h->setDefaultState(s0); + QState *s1 = new QState(root); + QFinalState *s2 = new QFinalState(root); + + s00->addTransition(new StringTransition("a", s01)); + s0->addTransition(new StringTransition("b", s1)); + s1->addTransition(new StringTransition("c", s0h)); + s0->addTransition(new StringTransition("d", s2)); + + root->setInitialState(s0); + s0->setInitialState(s00); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s0)); - QVERIFY(machine.configuration().contains(s00)); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s0)); + QVERIFY(machine.configuration().contains(s00)); - machine.postEvent(new StringEvent("a")); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s0)); - QVERIFY(machine.configuration().contains(s01)); + machine.postEvent(new StringEvent("a")); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s0)); + QVERIFY(machine.configuration().contains(s01)); - machine.postEvent(new StringEvent("b")); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); + machine.postEvent(new StringEvent("b")); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); - machine.postEvent(new StringEvent("c")); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s0)); - QVERIFY(machine.configuration().contains(s01)); + machine.postEvent(new StringEvent("c")); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s0)); + QVERIFY(machine.configuration().contains(s01)); - machine.postEvent(new StringEvent("d")); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s2)); + machine.postEvent(new StringEvent("d")); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s2)); - QTRY_COMPARE(finishedSpy.count(), 1); + QTRY_COMPARE(finishedSpy.count(), 1); + } } void tst_QStateMachine::startAndStop() -- cgit v0.12 From 42fe40e777a35818dcb9f7cd00ddf93e44477e36 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Fri, 22 May 2009 12:17:59 +0200 Subject: Revert "update the padnavigator example and suppress the padnavigator-ng" This reverts commit 1cad8c56002a61a6240e6580cdbd784209821fa6. Conflicts: examples/graphicsview/padnavigator/roundrectitem.cpp --- .../padnavigator/images/artsfftscope.png | Bin 1290 -> 1291 bytes examples/graphicsview/padnavigator/main.cpp | 4 + examples/graphicsview/padnavigator/panel.cpp | 168 ++++++++++----------- examples/graphicsview/padnavigator/panel.h | 29 ++-- .../graphicsview/padnavigator/roundrectitem.cpp | 109 ++++++++----- examples/graphicsview/padnavigator/roundrectitem.h | 16 +- examples/graphicsview/padnavigator/splashitem.cpp | 25 +-- examples/graphicsview/padnavigator/splashitem.h | 6 + 8 files changed, 207 insertions(+), 150 deletions(-) diff --git a/examples/graphicsview/padnavigator/images/artsfftscope.png b/examples/graphicsview/padnavigator/images/artsfftscope.png index 756a1cf..4db003f 100644 Binary files a/examples/graphicsview/padnavigator/images/artsfftscope.png and b/examples/graphicsview/padnavigator/images/artsfftscope.png differ diff --git a/examples/graphicsview/padnavigator/main.cpp b/examples/graphicsview/padnavigator/main.cpp index f7d6f90..dc5ff0c 100644 --- a/examples/graphicsview/padnavigator/main.cpp +++ b/examples/graphicsview/padnavigator/main.cpp @@ -40,6 +40,10 @@ ****************************************************************************/ #include +#ifndef QT_NO_OPENGL +# include +#endif + #include "panel.h" int main(int argc, char *argv[]) diff --git a/examples/graphicsview/padnavigator/panel.cpp b/examples/graphicsview/padnavigator/panel.cpp index c088fbc..28a3cb4 100644 --- a/examples/graphicsview/padnavigator/panel.cpp +++ b/examples/graphicsview/padnavigator/panel.cpp @@ -50,15 +50,15 @@ #endif #include +#include + Panel::Panel(int width, int height) - : selectedIndex(0), - grid(width*height), + : selectedX(0), + selectedY(0), width(width), height(height), flipped(false), - flippingGroup(0), - rotationXanim(0), - rotationYanim(0) + flipLeft(true) { setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); @@ -72,9 +72,12 @@ Panel::Panel(int width, int height) #endif setMinimumSize(50, 50); + selectionTimeLine = new QTimeLine(150, this); + flipTimeLine = new QTimeLine(500, this); + QRectF bounds((-width / 2.0) * 150, (-height / 2.0) * 150, width * 150, height * 150); - QGraphicsScene *scene = new QGraphicsScene(bounds, this); + scene = new QGraphicsScene(bounds, this); scene->setItemIndexMethod(QGraphicsScene::NoIndex); setScene(scene); @@ -87,24 +90,28 @@ Panel::Panel(int width, int height) ui->hostName->setFocus(); backItem = new RoundRectItem(bounds, embed->palette().window(), embed); - backItem->setYRotation(180); + backItem->setTransform(QTransform().rotate(180, Qt::YAxis)); backItem->setParentItem(baseItem); selectionItem = new RoundRectItem(QRectF(-60, -60, 120, 120), Qt::gray); selectionItem->setParentItem(baseItem); selectionItem->setZValue(-1); - selectionItem->setPos(posForLocation(0)); + selectionItem->setPos(posForLocation(0, 0)); + startPos = selectionItem->pos(); - int currentIndex = 0; + grid = new QGraphicsItem **[height]; + for (int y = 0; y < height; ++y) { + grid[y] = new QGraphicsItem *[width]; + for (int x = 0; x < width; ++x) { RoundRectItem *item = new RoundRectItem(QRectF(-54, -54, 108, 108), QColor(214, 240, 110, 128)); - item->setPos(posForLocation(currentIndex)); + item->setPos(posForLocation(x, y)); item->setParentItem(baseItem); item->setFlag(QGraphicsItem::ItemIsFocusable); - grid[currentIndex++] = item; + grid[y][x] = item; switch (qrand() % 9) { case 0: item->setPixmap(QPixmap(":/images/kontact_contacts.png")); break; @@ -124,10 +131,14 @@ Panel::Panel(int width, int height) } } - grid.first()->setFocus(); + grid[0][0]->setFocus(); connect(backItem, SIGNAL(activated()), this, SLOT(flip())); + connect(selectionTimeLine, SIGNAL(valueChanged(qreal)), + this, SLOT(updateSelectionStep(qreal))); + connect(flipTimeLine, SIGNAL(valueChanged(qreal)), + this, SLOT(updateFlipStep(qreal))); splash = new SplashItem; splash->setZValue(5); @@ -136,15 +147,16 @@ Panel::Panel(int width, int height) splash->grabKeyboard(); - //initialize the position - baseItem->setYRotation(selectionItem->x()/6.); - baseItem->setXRotation(selectionItem->y()/6.); + updateSelectionStep(0); setWindowTitle(tr("Pad Navigator Example")); } Panel::~Panel() { + for (int y = 0; y < height; ++y) + delete [] grid[y]; + delete [] grid; } void Panel::keyPressEvent(QKeyEvent *event) @@ -154,93 +166,73 @@ void Panel::keyPressEvent(QKeyEvent *event) return; } - selectedIndex = (selectedIndex + grid.count() + (event->key() == Qt::Key_Right) - (event->key() == Qt::Key_Left) - + width * ((event->key() == Qt::Key_Down) - (event->key() == Qt::Key_Up))) % grid.count(); - grid[selectedIndex]->setFocus(); - - const QPointF pos = posForLocation(selectedIndex); - - const double angleY = pos.x() / 6., - angleX = pos.y() / 6.; - - QAnimationGroup *group = new QParallelAnimationGroup(); - - QVariantAnimation *anim = new QPropertyAnimation(baseItem, "xRotation"); - anim->setEndValue(angleX); - anim->setDuration(150); - anim->setEasingCurve(QEasingCurve::OutInSine); - group->addAnimation(anim); - - anim = new QPropertyAnimation(baseItem, "yRotation"); - anim->setEndValue(angleY); - anim->setDuration(150); - anim->setEasingCurve(QEasingCurve::OutInSine); - group->addAnimation(anim); - - anim = new QPropertyAnimation(selectionItem, "pos"); - anim->setEndValue(pos); - anim->setDuration(150); - anim->setEasingCurve(QEasingCurve::Linear); - group->addAnimation(anim); - - group->start(QAbstractAnimation::DeleteWhenStopped); + selectedX = (selectedX + width + (event->key() == Qt::Key_Right) - (event->key() == Qt::Key_Left)) % width; + selectedY = (selectedY + height + (event->key() == Qt::Key_Down) - (event->key() == Qt::Key_Up)) % height; + grid[selectedY][selectedX]->setFocus(); + + selectionTimeLine->stop(); + startPos = selectionItem->pos(); + endPos = posForLocation(selectedX, selectedY); + selectionTimeLine->start(); } void Panel::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); - fitInView(scene()->sceneRect(), Qt::KeepAspectRatio); + fitInView(scene->sceneRect(), Qt::KeepAspectRatio); } -void Panel::flip() +void Panel::updateSelectionStep(qreal val) { - grid[selectedIndex]->setFocus(); - - if (flippingGroup == 0) { - flippingGroup = new QParallelAnimationGroup(this); - - const qreal zoomOut = qreal(.75); - - //slight scaling down while flipping - QVariantAnimation *anim = new QPropertyAnimation(baseItem, "yScale"); - anim->setKeyValueAt(qreal(.5), zoomOut); - anim->setEndValue(1); - anim->setEasingCurve(QEasingCurve::OutInSine); - anim->setDuration(500); - flippingGroup->addAnimation(anim); - - anim = new QPropertyAnimation(baseItem, "xScale"); - anim->setKeyValueAt(qreal(.5), zoomOut); - anim->setEndValue(1); - anim->setEasingCurve(QEasingCurve::OutInSine); - anim->setDuration(500); - flippingGroup->addAnimation(anim); - - rotationXanim = new QPropertyAnimation(baseItem, "xRotation"); - rotationXanim->setEndValue(0); - rotationXanim->setDuration(500); - flippingGroup->addAnimation(rotationXanim); - - rotationYanim = new QPropertyAnimation(baseItem, "yRotation"); - rotationYanim->setStartValue(0); - rotationYanim->setEndValue(180); - rotationYanim->setDuration(500); - flippingGroup->addAnimation(rotationYanim); - } + QPointF newPos(startPos.x() + (endPos - startPos).x() * val, + startPos.y() + (endPos - startPos).y() * val); + selectionItem->setPos(newPos); + + QTransform transform; + yrot = newPos.x() / 6.0; + xrot = newPos.y() / 6.0; + transform.rotate(newPos.x() / 6.0, Qt::YAxis); + transform.rotate(newPos.y() / 6.0, Qt::XAxis); + baseItem->setTransform(transform); +} - if (flippingGroup->currentTime() != 0 && flippingGroup->direction() == QAbstractAnimation::Forward) - flippingGroup->setDirection(QAbstractAnimation::Backward); +void Panel::updateFlipStep(qreal val) +{ + qreal finalxrot = xrot - xrot * val; + qreal finalyrot; + if (flipLeft) + finalyrot = yrot - yrot * val - 180 * val; else - flippingGroup->setDirection(QAbstractAnimation::Forward); + finalyrot = yrot - yrot * val + 180 * val; + QTransform transform; + transform.rotate(finalyrot, Qt::YAxis); + transform.rotate(finalxrot, Qt::XAxis); + qreal scale = 1 - sin(3.14 * val) * 0.3; + transform.scale(scale, scale); + baseItem->setTransform(transform); + if (val == 0) + grid[selectedY][selectedX]->setFocus(); +} - flippingGroup->start(); - flipped = !flipped; +void Panel::flip() +{ + if (flipTimeLine->state() == QTimeLine::Running) + return; + + if (flipTimeLine->currentValue() == 0) { + flipTimeLine->setDirection(QTimeLine::Forward); + flipTimeLine->start(); + flipped = true; + flipLeft = selectionItem->pos().x() < 0; + } else { + flipTimeLine->setDirection(QTimeLine::Backward); + flipTimeLine->start(); + flipped = false; + } } -QPointF Panel::posForLocation(int index) const +QPointF Panel::posForLocation(int x, int y) const { - const int x = index % width, - y = index / width; return QPointF(x * 150, y * 150) - QPointF((width - 1) * 75, (height - 1) * 75); } diff --git a/examples/graphicsview/padnavigator/panel.h b/examples/graphicsview/padnavigator/panel.h index cc03530..03876b7 100644 --- a/examples/graphicsview/padnavigator/panel.h +++ b/examples/graphicsview/padnavigator/panel.h @@ -40,12 +40,10 @@ ****************************************************************************/ #include -#include QT_BEGIN_NAMESPACE +class QTimeLine; class Ui_BackSide; -class QAnimationGroup; -class QPropertyAnimation; QT_END_NAMESPACE; class RoundRectItem; @@ -62,24 +60,33 @@ protected: void resizeEvent(QResizeEvent *event); private Q_SLOTS: + void updateSelectionStep(qreal val); + void updateFlipStep(qreal val); void flip(); private: - QPointF posForLocation(int index) const; + QPointF posForLocation(int x, int y) const; - QGraphicsWidget *selectionItem; - QGraphicsWidget *baseItem; + QGraphicsScene *scene; + RoundRectItem *selectionItem; + RoundRectItem *baseItem; RoundRectItem *backItem; QGraphicsWidget *splash; - int selectedIndex; + QTimeLine *selectionTimeLine; + QTimeLine *flipTimeLine; + int selectedX, selectedY; - QVector grid; + QGraphicsItem ***grid; + QPointF startPos; + QPointF endPos; + qreal xrot, yrot; + qreal xrot2, yrot2; + int width; int height; bool flipped; - Ui_BackSide *ui; + bool flipLeft; - QAnimationGroup *flippingGroup; - QPropertyAnimation *rotationXanim, *rotationYanim; + Ui_BackSide *ui; }; diff --git a/examples/graphicsview/padnavigator/roundrectitem.cpp b/examples/graphicsview/padnavigator/roundrectitem.cpp index 73d6d33..c5dc35d 100644 --- a/examples/graphicsview/padnavigator/roundrectitem.cpp +++ b/examples/graphicsview/padnavigator/roundrectitem.cpp @@ -44,61 +44,72 @@ #include RoundRectItem::RoundRectItem(const QRectF &rect, const QBrush &brush, QWidget *embeddedWidget) - : QGraphicsWidget(), - m_rect(rect), + : QGraphicsRectItem(rect), brush(brush), + timeLine(75), + lastVal(0), + opa(1), proxyWidget(0) { + connect(&timeLine, SIGNAL(valueChanged(qreal)), + this, SLOT(updateValue(qreal))); + if (embeddedWidget) { proxyWidget = new QGraphicsProxyWidget(this); proxyWidget->setFocusPolicy(Qt::StrongFocus); proxyWidget->setWidget(embeddedWidget); + proxyWidget->setGeometry(boundingRect().adjusted(25, 25, -25, -25)); } } void RoundRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { - const bool widgetHidden = parentItem() == 0 || qAbs(static_cast(parentItem())->yRotation()) < 90; - - if (proxyWidget) { - if (widgetHidden) { + QTransform x = painter->worldTransform(); + + QLineF unit = x.map(QLineF(0, 0, 1, 1)); + if (unit.p1().x() > unit.p2().x() || unit.p1().y() > unit.p2().y()) { + if (proxyWidget && proxyWidget->isVisible()) { proxyWidget->hide(); - } else { - if (!proxyWidget->isVisible()) { - proxyWidget->setGeometry(boundingRect().adjusted(25, 25, -25, -25)); - proxyWidget->show(); - proxyWidget->setFocus(); - } - painter->setBrush(brush); - painter->setPen(QPen(Qt::black, 1)); - painter->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - painter->drawRoundRect(m_rect); + proxyWidget->setGeometry(rect()); } - } else if (widgetHidden) { - painter->setPen(Qt::NoPen); - painter->setBrush(QColor(0, 0, 0, 64)); - painter->drawRoundRect(m_rect.translated(2, 2)); + return; + } - QLinearGradient gradient(m_rect.topLeft(), m_rect.bottomRight()); + if (proxyWidget && !proxyWidget->isVisible()) { + proxyWidget->show(); + proxyWidget->setFocus(); + } + if (proxyWidget && proxyWidget->pos() != QPoint()) + proxyWidget->setGeometry(boundingRect().adjusted(25, 25, -25, -25)); + + painter->setOpacity(opacity()); + painter->setPen(Qt::NoPen); + painter->setBrush(QColor(0, 0, 0, 64)); + painter->drawRoundRect(rect().translated(2, 2)); + + if (!proxyWidget) { + QLinearGradient gradient(rect().topLeft(), rect().bottomRight()); const QColor col = brush.color(); gradient.setColorAt(0, col); - gradient.setColorAt(1, col.dark(200)); + gradient.setColorAt(1, col.dark(int(200 + lastVal * 50))); painter->setBrush(gradient); - painter->setPen(QPen(Qt::black, 1)); - painter->drawRoundRect(m_rect); - if (!pix.isNull()) { - painter->scale(qreal(1.95), qreal(1.95)); - painter->drawPixmap(-pix.width() / 2, -pix.height() / 2, pix); - } + } else { + painter->setBrush(brush); } + painter->setPen(QPen(Qt::black, 1)); + painter->drawRoundRect(rect()); + if (!pix.isNull()) { + painter->scale(1.95, 1.95); + painter->drawPixmap(-pix.width() / 2, -pix.height() / 2, pix);; + } } QRectF RoundRectItem::boundingRect() const { - qreal penW = qreal(.5); - qreal shadowW = 2; - return m_rect.adjusted(-penW, -penW, penW + shadowW, penW + shadowW); + qreal penW = 0.5; + qreal shadowW = 2.0; + return rect().adjusted(-penW, -penW, penW + shadowW, penW + shadowW); } void RoundRectItem::setPixmap(const QPixmap &pixmap) @@ -108,26 +119,46 @@ void RoundRectItem::setPixmap(const QPixmap &pixmap) update(); } +qreal RoundRectItem::opacity() const +{ + RoundRectItem *parent = parentItem() ? (RoundRectItem *)parentItem() : 0; + return opa + (parent ? parent->opacity() : 0); +} + +void RoundRectItem::setOpacity(qreal opacity) +{ + opa = opacity; + update(); +} + void RoundRectItem::keyPressEvent(QKeyEvent *event) { - if (event->isAutoRepeat() || event->key() != Qt::Key_Return) { - QGraphicsWidget::keyPressEvent(event); + if (event->isAutoRepeat() || event->key() != Qt::Key_Return + || (timeLine.state() == QTimeLine::Running && timeLine.direction() == QTimeLine::Forward)) { + QGraphicsRectItem::keyPressEvent(event); return; } - if (!proxyWidget) - setScale(qreal(.9), qreal(.9)); - + timeLine.stop(); + timeLine.setDirection(QTimeLine::Forward); + timeLine.start(); emit activated(); } void RoundRectItem::keyReleaseEvent(QKeyEvent *event) { - if (event->isAutoRepeat() || event->key() != Qt::Key_Return) { - QGraphicsWidget::keyReleaseEvent(event); + if (event->key() != Qt::Key_Return) { + QGraphicsRectItem::keyReleaseEvent(event); return; } + timeLine.stop(); + timeLine.setDirection(QTimeLine::Backward); + timeLine.start(); +} +void RoundRectItem::updateValue(qreal value) +{ + lastVal = value; if (!proxyWidget) - setScale(1, 1); + setTransform(QTransform().scale(1 - value / 10.0, 1 - value / 10.0)); } diff --git a/examples/graphicsview/padnavigator/roundrectitem.h b/examples/graphicsview/padnavigator/roundrectitem.h index b0d44dd..33e33d7 100644 --- a/examples/graphicsview/padnavigator/roundrectitem.h +++ b/examples/graphicsview/padnavigator/roundrectitem.h @@ -40,14 +40,15 @@ ****************************************************************************/ #include +#include +#include #include -#include QT_BEGIN_NAMESPACE class QGraphicsProxyWidget; QT_END_NAMESPACE; -class RoundRectItem : public QGraphicsWidget +class RoundRectItem : public QObject, public QGraphicsRectItem { Q_OBJECT public: @@ -58,6 +59,9 @@ public: void setPixmap(const QPixmap &pixmap); + qreal opacity() const; + void setOpacity(qreal opacity); + Q_SIGNALS: void activated(); @@ -65,9 +69,15 @@ protected: void keyPressEvent(QKeyEvent *event); void keyReleaseEvent(QKeyEvent *event); +private slots: + void updateValue(qreal value); + private: - QRectF m_rect; QBrush brush; QPixmap pix; + QTimeLine timeLine; + qreal lastVal; + qreal opa; + QGraphicsProxyWidget *proxyWidget; }; diff --git a/examples/graphicsview/padnavigator/splashitem.cpp b/examples/graphicsview/padnavigator/splashitem.cpp index a83d4d5..2a374bf 100644 --- a/examples/graphicsview/padnavigator/splashitem.cpp +++ b/examples/graphicsview/padnavigator/splashitem.cpp @@ -46,6 +46,12 @@ SplashItem::SplashItem(QGraphicsItem *parent) : QGraphicsWidget(parent) { + opacity = 1.0; + + + timeLine = new QTimeLine(350); + timeLine->setCurveShape(QTimeLine::EaseInCurve); + connect(timeLine, SIGNAL(valueChanged(qreal)), this, SLOT(setValue(qreal))); text = tr("Welcome to the Pad Navigator Example. You can use the" " keyboard arrows to navigate the icons, and press enter" @@ -55,6 +61,7 @@ SplashItem::SplashItem(QGraphicsItem *parent) void SplashItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { + painter->setOpacity(opacity); painter->setPen(QPen(Qt::black, 2)); painter->setBrush(QColor(245, 245, 255, 220)); painter->setClipRect(rect()); @@ -72,14 +79,14 @@ void SplashItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWid void SplashItem::keyPressEvent(QKeyEvent * /* event */) { - QVariantAnimation *anim = new QPropertyAnimation(this, "pos"); - anim->setEndValue(QPointF(x(), scene()->sceneRect().top() - rect().height())); - anim->setDuration(350); - anim->start(QAbstractAnimation::DeleteWhenStopped); - - anim = new QPropertyAnimation(this, "opacity"); - anim->setEndValue(0); - anim->start(QAbstractAnimation::DeleteWhenStopped); + if (timeLine->state() == QTimeLine::NotRunning) + timeLine->start(); +} - connect(anim, SIGNAL(finished()), SLOT(close())); +void SplashItem::setValue(qreal value) +{ + opacity = 1 - value; + setPos(x(), scene()->sceneRect().top() - rect().height() * value); + if (value == 1) + hide(); } diff --git a/examples/graphicsview/padnavigator/splashitem.h b/examples/graphicsview/padnavigator/splashitem.h index e2655ec..982bbe2 100644 --- a/examples/graphicsview/padnavigator/splashitem.h +++ b/examples/graphicsview/padnavigator/splashitem.h @@ -40,6 +40,7 @@ ****************************************************************************/ #include +#include #include class SplashItem : public QGraphicsWidget @@ -52,6 +53,11 @@ public: protected: void keyPressEvent(QKeyEvent *event); +private Q_SLOTS: + void setValue(qreal value); + private: + QTimeLine *timeLine; QString text; + qreal opacity; }; -- cgit v0.12 From 0babd12eb7e982f47b379fe70f011daffbb8c6e8 Mon Sep 17 00:00:00 2001 From: Ariya Hidayat Date: Fri, 22 May 2009 12:57:57 +0200 Subject: Updated WebKit from /home/ariya/dev/webkit/qtwebkit-4.5 to origin/qtwebkit-4.5 ( 4ee8af9348b3f57d3c0f3575ae0a58336cf07a92 ) Changes in WebKit since the last update: ++ b/LayoutTests/ChangeLog 2009-05-20 Holger Hans Peter Freyther Reviewed by Anders Carlsson. https://bugs.webkit.org/show_bug.cgi?id=24510 Add a test case that Netscape Plugin can properly determine if a given object has a specific method and property. The test will ask the plugin to call hasproperty and hasmethod and will compare the result with what is expected. This approach is taken from netscape-get-property-return-value.html * plugins/netscape-invoke-browserfuncs-expected.txt: Added. * plugins/netscape-invoke-browserfuncs.html: Added. ++ b/WebCore/ChangeLog 2009-05-19 Kenneth Rohde Christiansen Reviewed by Simon Hausmann. Do not call the parent implementation (Widget::) in show() and hide() of the PluginViewQt, as it always changes the visible state of the platformWidget (equal to the platformPluginWidget in the Qt port), thus ignoring the isParentVisible() test. * plugins/qt/PluginViewQt.cpp: (WebCore::PluginView::show): (WebCore::PluginView::hide): 2009-04-22 Tamas Szirbucz Reviewed by Ariya Hidayat. https://bugs.webkit.org/show_bug.cgi?id=25023 Delete reply in QNetworkReplyHandler::abort() to avoid leak. * platform/network/qt/QNetworkReplyHandler.cpp: (WebCore::QNetworkReplyHandler::abort): 2009-05-20 Holger Hans Peter Freyther Reviewed by Anders Carlsson. https://bugs.webkit.org/show_bug.cgi?id=24510 Fix a bug where the browserfuncs were not properly assigned, make hasproperty use _NP_HasProperty and hasmethod _NP_HasMethod. Test: plugins/netscape-invoke-browserfuncs.html * plugins/gtk/PluginPackageGtk.cpp: (WebCore::PluginPackage::load): Fix assignment * plugins/qt/PluginPackageQt.cpp: (WebCore::PluginPackage::load): Fix assignment ++ b/WebKit/qt/ChangeLog 2009-05-19 Kenneth Rohde Christiansen Reviewed by Simon Hausmann. Fix a plugin bug in the WebKit code, similar to the one in WebCore. The problem is when a non visible QtPluginWidget would show it self in a sibling frame. The problem was due to our clipping. In Qt, if setMask is set with an empty QRegion, no clipping will be performed, so in that case we hide the PluginContainer * WebCoreSupport/FrameLoaderClientQt.cpp: (WebCore::): ++ b/WebKitTools/ChangeLog 2009-05-14 Holger Hans Peter Freyther Reviewed by Anders Carlsson. https://bugs.webkit.org/show_bug.cgi?id=24510 where Add testHasProperty and testHasMethod to the existing functions of the PluginObject to be able to test the browser hasproperty and hasmethod implementation. Invoke them from pluginInvoke. Change the defines to an enum to avoid manually updating NUM_METHOD_IDENTIFIERS and assigning numbers. * DumpRenderTree/TestNetscapePlugIn.subproj/PluginObject.cpp: (testHasProperty): test hasproperty (testHasMethod): test hasmethod (pluginInvoke): invoke the two --- src/3rdparty/webkit/VERSION | 2 +- src/3rdparty/webkit/WebCore/ChangeLog | 39 ++++++++++++++++++++++ .../platform/network/qt/QNetworkReplyHandler.cpp | 1 + .../webkit/WebCore/plugins/qt/PluginPackageQt.cpp | 4 +-- .../webkit/WebCore/plugins/qt/PluginViewQt.cpp | 8 +++-- src/3rdparty/webkit/WebKit/qt/ChangeLog | 14 ++++++++ .../qt/WebCoreSupport/FrameLoaderClientQt.cpp | 8 ++++- 7 files changed, 70 insertions(+), 6 deletions(-) diff --git a/src/3rdparty/webkit/VERSION b/src/3rdparty/webkit/VERSION index 7adbd6f..7d5d1c5 100644 --- a/src/3rdparty/webkit/VERSION +++ b/src/3rdparty/webkit/VERSION @@ -8,4 +8,4 @@ The commit imported was from the and has the sha1 checksum - 40b523e9eaaba38c182e5a9c319f0069ebf98330 + 4ee8af9348b3f57d3c0f3575ae0a58336cf07a92 diff --git a/src/3rdparty/webkit/WebCore/ChangeLog b/src/3rdparty/webkit/WebCore/ChangeLog index a4cb62d..072beee 100644 --- a/src/3rdparty/webkit/WebCore/ChangeLog +++ b/src/3rdparty/webkit/WebCore/ChangeLog @@ -1,3 +1,42 @@ +2009-05-19 Kenneth Rohde Christiansen + + Reviewed by Simon Hausmann. + + Do not call the parent implementation (Widget::) in show() and hide() + of the PluginViewQt, as it always changes the visible state of the + platformWidget (equal to the platformPluginWidget in the Qt port), + thus ignoring the isParentVisible() test. + + * plugins/qt/PluginViewQt.cpp: + (WebCore::PluginView::show): + (WebCore::PluginView::hide): + +2009-04-22 Tamas Szirbucz + + Reviewed by Ariya Hidayat. + + https://bugs.webkit.org/show_bug.cgi?id=25023 + Delete reply in QNetworkReplyHandler::abort() to avoid leak. + + * platform/network/qt/QNetworkReplyHandler.cpp: + (WebCore::QNetworkReplyHandler::abort): + +2009-05-20 Holger Hans Peter Freyther + + Reviewed by Anders Carlsson. + + https://bugs.webkit.org/show_bug.cgi?id=24510 + + Fix a bug where the browserfuncs were not properly assigned, + make hasproperty use _NP_HasProperty and hasmethod _NP_HasMethod. + + Test: plugins/netscape-invoke-browserfuncs.html + + * plugins/gtk/PluginPackageGtk.cpp: + (WebCore::PluginPackage::load): Fix assignment + * plugins/qt/PluginPackageQt.cpp: + (WebCore::PluginPackage::load): Fix assignment + 2009-05-11 Yael Aharon Reviewed by Holger Freyther. diff --git a/src/3rdparty/webkit/WebCore/platform/network/qt/QNetworkReplyHandler.cpp b/src/3rdparty/webkit/WebCore/platform/network/qt/QNetworkReplyHandler.cpp index 2c730a6..3e9b239 100644 --- a/src/3rdparty/webkit/WebCore/platform/network/qt/QNetworkReplyHandler.cpp +++ b/src/3rdparty/webkit/WebCore/platform/network/qt/QNetworkReplyHandler.cpp @@ -174,6 +174,7 @@ void QNetworkReplyHandler::abort() if (m_reply) { QNetworkReply* reply = release(); reply->abort(); + reply->deleteLater(); deleteLater(); } } diff --git a/src/3rdparty/webkit/WebCore/plugins/qt/PluginPackageQt.cpp b/src/3rdparty/webkit/WebCore/plugins/qt/PluginPackageQt.cpp index 4387813..13f5394 100644 --- a/src/3rdparty/webkit/WebCore/plugins/qt/PluginPackageQt.cpp +++ b/src/3rdparty/webkit/WebCore/plugins/qt/PluginPackageQt.cpp @@ -151,8 +151,8 @@ bool PluginPackage::load() m_browserFuncs.getproperty = _NPN_GetProperty; m_browserFuncs.setproperty = _NPN_SetProperty; m_browserFuncs.removeproperty = _NPN_RemoveProperty; - m_browserFuncs.hasproperty = _NPN_HasMethod; - m_browserFuncs.hasmethod = _NPN_HasProperty; + m_browserFuncs.hasproperty = _NPN_HasProperty; + m_browserFuncs.hasmethod = _NPN_HasMethod; m_browserFuncs.setexception = _NPN_SetException; m_browserFuncs.enumerate = _NPN_Enumerate; m_browserFuncs.construct = _NPN_Construct; diff --git a/src/3rdparty/webkit/WebCore/plugins/qt/PluginViewQt.cpp b/src/3rdparty/webkit/WebCore/plugins/qt/PluginViewQt.cpp index 43c772f..e856f92 100644 --- a/src/3rdparty/webkit/WebCore/plugins/qt/PluginViewQt.cpp +++ b/src/3rdparty/webkit/WebCore/plugins/qt/PluginViewQt.cpp @@ -113,7 +113,9 @@ void PluginView::show() if (isParentVisible() && platformPluginWidget()) platformPluginWidget()->setVisible(true); - Widget::show(); + // do not call parent impl. here as it will set the platformWidget + // (same as platformPluginWidget in the Qt port) to visible, even + // when parent isn't visible. } void PluginView::hide() @@ -123,7 +125,9 @@ void PluginView::hide() if (isParentVisible() && platformPluginWidget()) platformPluginWidget()->setVisible(false); - Widget::hide(); + // do not call parent impl. here as it will set the platformWidget + // (same as platformPluginWidget in the Qt port) to invisible, even + // when parent isn't visible. } void PluginView::paint(GraphicsContext* context, const IntRect& rect) diff --git a/src/3rdparty/webkit/WebKit/qt/ChangeLog b/src/3rdparty/webkit/WebKit/qt/ChangeLog index 2aeb8da..d9f925a 100644 --- a/src/3rdparty/webkit/WebKit/qt/ChangeLog +++ b/src/3rdparty/webkit/WebKit/qt/ChangeLog @@ -1,3 +1,17 @@ +2009-05-19 Kenneth Rohde Christiansen + + Reviewed by Simon Hausmann. + + Fix a plugin bug in the WebKit code, similar to the one in WebCore. + + The problem is when a non visible QtPluginWidget would show it self + in a sibling frame. The problem was due to our clipping. In Qt, + if setMask is set with an empty QRegion, no clipping will + be performed, so in that case we hide the PluginContainer + + * WebCoreSupport/FrameLoaderClientQt.cpp: + (WebCore::): + 2009-03-27 Erik L. Bunce Reviewed by Simon Hausmann. diff --git a/src/3rdparty/webkit/WebKit/qt/WebCoreSupport/FrameLoaderClientQt.cpp b/src/3rdparty/webkit/WebKit/qt/WebCoreSupport/FrameLoaderClientQt.cpp index c421d42..a2b33c0 100644 --- a/src/3rdparty/webkit/WebKit/qt/WebCoreSupport/FrameLoaderClientQt.cpp +++ b/src/3rdparty/webkit/WebKit/qt/WebCoreSupport/FrameLoaderClientQt.cpp @@ -1058,7 +1058,13 @@ public: IntRect clipRect(static_cast(parentScrollView)->windowClipRect()); clipRect.move(-windowRect.x(), -windowRect.y()); clipRect.intersect(platformWidget()->rect()); - platformWidget()->setMask(QRegion(clipRect.x(), clipRect.y(), clipRect.width(), clipRect.height())); + + QRegion clipRegion = QRegion(clipRect); + platformWidget()->setMask(clipRegion); + + // if setMask is set with an empty QRegion, no clipping will + // be performed, so in that case we hide the platformWidget + platformWidget()->setVisible(!clipRegion.isEmpty()); } }; -- cgit v0.12 From ec8c6b9f5a25f9d4c437fbb13f073aeebc09cb3f Mon Sep 17 00:00:00 2001 From: Ariya Hidayat Date: Fri, 22 May 2009 13:09:17 +0200 Subject: Updates QtWebKit sections in changes-4.5.2 after commit 0babd12e. --- dist/changes-4.5.2 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index b3e808f..1e00208 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -42,8 +42,8 @@ Third party components Memory (r41527, r43764, r43828, r43830) JavaScript (r39882, r40086, r40131, r40133) Rendering (r41285, r41296, r41659, r42887) - Network (r41664, r42516) - Plugins (r41346, r43550) + Network (r41664, r42516, r42747) + Plugins (r41346, r43550, r43915, r43917, r43923) Clipboard (r41360) **************************************************************************** -- cgit v0.12 From 5a734e4657161e0877b32181df35a56241b21de4 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Fri, 22 May 2009 13:24:44 +0200 Subject: Fix the way the transform and the properties are marked as dirty in QGraphicsItem Acknowledged-by: Thierry --- src/gui/graphicsview/qgraphicsitem.cpp | 9 +++-- src/gui/graphicsview/qgraphicsitem_p.h | 2 +- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 50 ++++++++++++++++++++++---- 3 files changed, 49 insertions(+), 12 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index b7e88f4..828dd4f 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -2607,7 +2607,6 @@ QTransform QGraphicsItem::transform() const QVariant v(x); d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, v); d_ptr->dirtyTransform = 0; - d_ptr->dirtyTransformComponents = 1; const_cast(this)->itemChange(ItemTransformHasChanged, v); return x; } @@ -3200,9 +3199,9 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) prepareGeometryChange(); d_ptr->hasTransform = !newTransform.isIdentity(); d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); + d_ptr->dirtyTransformComponents = 1; + d_ptr->dirtyTransform = 0; d_ptr->invalidateSceneTransformCache(); - if (d_ptr->hasDecomposedTransform) - d_ptr->dirtyTransform = 1; // Send post-notification. // NB! We have to change the value from QMatrix to QTransform. @@ -3253,9 +3252,9 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) prepareGeometryChange(); d_ptr->hasTransform = !newTransform.isIdentity(); d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); + d_ptr->dirtyTransformComponents = 1; + d_ptr->dirtyTransform = 0; d_ptr->invalidateSceneTransformCache(); - if (d_ptr->hasDecomposedTransform) - d_ptr->dirtyTransform = 1; // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index cebc8ca..b2569c1 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -346,7 +346,7 @@ public: int globalStackingOrder; int sceneTransformIndex; - struct DecomposedTransform; + struct DecomposedTransform; DecomposedTransform *decomposedTransform() const { QGraphicsItemPrivate *that = const_cast(this); diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index d41b3b4..c03c420 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -6404,26 +6404,26 @@ void tst_QGraphicsItem::setTransformProperties_data() QTest::addColumn("shearY"); QTest::newRow("nothing") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) - << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); QTest::newRow("rotationZ") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(42.2) - << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); QTest::newRow("rotationXY") << QPointF() << qreal(12.5) << qreal(53.6) << qreal(0.0) - << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); QTest::newRow("rotationXYZ") << QPointF() << qreal(-25) << qreal(12) << qreal(556) - << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); QTest::newRow("rotationXYZ dicentred") << QPointF(-53, 25.2) << qreal(-2578.2) << qreal(4565.2) << qreal(56) - << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(0.0); + << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); QTest::newRow("Scale") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(6) << qreal(0.5) << qreal(0.0) << qreal(0.0); QTest::newRow("Shear") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) - << qreal(0.0) << qreal(0.0) << qreal(2.2) << qreal(0.5); + << qreal(1) << qreal(1) << qreal(2.2) << qreal(0.5); QTest::newRow("Scale and Shear") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) << qreal(5.2) << qreal(2.1) << qreal(5.2) << qreal(5.5); @@ -6475,6 +6475,44 @@ void tst_QGraphicsItem::setTransformProperties() QCOMPARE(item->transformOrigin(), origin); QCOMPARE(result, item->transform()); + + //----------------------------------------------------------------- + //Change the rotation Z + item->setZRotation(45); + QTransform result2; + result2.translate(origin.x(), origin.y()); + result2.rotate(rotationX, Qt::XAxis); + result2.rotate(rotationY, Qt::YAxis); + result2.rotate(45, Qt::ZAxis); + result2.shear(shearX, shearY); + result2.scale(scaleX, scaleY); + result2.translate(-origin.x(), -origin.y()); + + QCOMPARE(item->xRotation(), rotationX); + QCOMPARE(item->yRotation(), rotationY); + QCOMPARE(item->zRotation(), 45.0); + QCOMPARE(item->xScale(), scaleX); + QCOMPARE(item->yScale(), scaleY); + QCOMPARE(item->horizontalShear(), shearX); + QCOMPARE(item->verticalShear(), shearY); + QCOMPARE(item->transformOrigin(), origin); + + QCOMPARE(result2, item->transform()); + + //----------------------------------------------------------------- + // calling setTransform() should reset the properties to their default + item->setTransform(result); + + QCOMPARE(item->xRotation(), 0.0); + QCOMPARE(item->yRotation(), 0.0); + QCOMPARE(item->zRotation(), 0.0); + QCOMPARE(item->xScale(), 1.0); + QCOMPARE(item->yScale(), 1.0); + QCOMPARE(item->horizontalShear(), 0.0); + QCOMPARE(item->verticalShear(), 0.0); + QCOMPARE(item->transformOrigin(), QPointF(0,0)); + + QCOMPARE(result, item->transform()); } -- cgit v0.12 From 1a709fbe25a2446a9b311ded88aec5565258f3ac Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 13:11:41 +0200 Subject: Say hello to animation API & state machine API --- demos/qtdemo/xml/examples.xml | 15 + doc/src/animation.qdoc | 368 ++ doc/src/diagrams/animations-architecture.svg | 351 ++ .../diagrams/programs/easingcurve/easingcurve.pro | 13 + doc/src/diagrams/programs/easingcurve/main.cpp | 90 + doc/src/examples-overview.qdoc | 8 + doc/src/examples.qdoc | 17 + doc/src/examples/eventtransitions.qdoc | 86 + doc/src/examples/factorial.qdoc | 102 + doc/src/examples/pingpong.qdoc | 107 + doc/src/examples/stickman.qdoc | 115 + doc/src/examples/tankgame.qdoc | 117 + doc/src/examples/trafficlight.qdoc | 99 + doc/src/examples/twowaybutton.qdoc | 82 + doc/src/external-resources.qdoc | 10 + doc/src/groups.qdoc | 23 + doc/src/images/animations-architecture.png | Bin 0 -> 27619 bytes doc/src/images/factorial-example.png | Bin 0 -> 4032 bytes doc/src/images/pingpong-example.png | Bin 0 -> 7843 bytes doc/src/images/qeasingcurve-cosinecurve.png | Bin 0 -> 2544 bytes doc/src/images/qeasingcurve-inback.png | Bin 0 -> 2225 bytes doc/src/images/qeasingcurve-inbounce.png | Bin 0 -> 2378 bytes doc/src/images/qeasingcurve-incirc.png | Bin 0 -> 2138 bytes doc/src/images/qeasingcurve-incubic.png | Bin 0 -> 2230 bytes doc/src/images/qeasingcurve-incurve.png | Bin 0 -> 2325 bytes doc/src/images/qeasingcurve-inelastic.png | Bin 0 -> 2314 bytes doc/src/images/qeasingcurve-inexpo.png | Bin 0 -> 2183 bytes doc/src/images/qeasingcurve-inoutback.png | Bin 0 -> 2460 bytes doc/src/images/qeasingcurve-inoutbounce.png | Bin 0 -> 2522 bytes doc/src/images/qeasingcurve-inoutcirc.png | Bin 0 -> 2352 bytes doc/src/images/qeasingcurve-inoutcubic.png | Bin 0 -> 2410 bytes doc/src/images/qeasingcurve-inoutelastic.png | Bin 0 -> 2485 bytes doc/src/images/qeasingcurve-inoutexpo.png | Bin 0 -> 2383 bytes doc/src/images/qeasingcurve-inoutquad.png | Bin 0 -> 2392 bytes doc/src/images/qeasingcurve-inoutquart.png | Bin 0 -> 2331 bytes doc/src/images/qeasingcurve-inoutquint.png | Bin 0 -> 2244 bytes doc/src/images/qeasingcurve-inoutsine.png | Bin 0 -> 2405 bytes doc/src/images/qeasingcurve-inquad.png | Bin 0 -> 2283 bytes doc/src/images/qeasingcurve-inquart.png | Bin 0 -> 2261 bytes doc/src/images/qeasingcurve-inquint.png | Bin 0 -> 2178 bytes doc/src/images/qeasingcurve-insine.png | Bin 0 -> 2167 bytes doc/src/images/qeasingcurve-linear.png | Bin 0 -> 2165 bytes doc/src/images/qeasingcurve-outback.png | Bin 0 -> 2371 bytes doc/src/images/qeasingcurve-outbounce.png | Bin 0 -> 2481 bytes doc/src/images/qeasingcurve-outcirc.png | Bin 0 -> 2269 bytes doc/src/images/qeasingcurve-outcubic.png | Bin 0 -> 2336 bytes doc/src/images/qeasingcurve-outcurve.png | Bin 0 -> 2389 bytes doc/src/images/qeasingcurve-outelastic.png | Bin 0 -> 2402 bytes doc/src/images/qeasingcurve-outexpo.png | Bin 0 -> 2299 bytes doc/src/images/qeasingcurve-outinback.png | Bin 0 -> 2400 bytes doc/src/images/qeasingcurve-outinbounce.png | Bin 0 -> 2568 bytes doc/src/images/qeasingcurve-outincirc.png | Bin 0 -> 2339 bytes doc/src/images/qeasingcurve-outincubic.png | Bin 0 -> 2393 bytes doc/src/images/qeasingcurve-outinelastic.png | Bin 0 -> 2517 bytes doc/src/images/qeasingcurve-outinexpo.png | Bin 0 -> 2377 bytes doc/src/images/qeasingcurve-outinquad.png | Bin 0 -> 2380 bytes doc/src/images/qeasingcurve-outinquart.png | Bin 0 -> 2319 bytes doc/src/images/qeasingcurve-outinquint.png | Bin 0 -> 2248 bytes doc/src/images/qeasingcurve-outinsine.png | Bin 0 -> 2388 bytes doc/src/images/qeasingcurve-outquad.png | Bin 0 -> 2324 bytes doc/src/images/qeasingcurve-outquart.png | Bin 0 -> 2304 bytes doc/src/images/qeasingcurve-outquint.png | Bin 0 -> 2242 bytes doc/src/images/qeasingcurve-outsine.png | Bin 0 -> 2364 bytes doc/src/images/qeasingcurve-sinecurve.png | Bin 0 -> 2470 bytes doc/src/images/statemachine-button-history.png | Bin 0 -> 8493 bytes doc/src/images/statemachine-button-nested.png | Bin 0 -> 7051 bytes doc/src/images/statemachine-button.png | Bin 0 -> 4233 bytes doc/src/images/statemachine-customevents.png | Bin 0 -> 2544 bytes doc/src/images/statemachine-customevents2.png | Bin 0 -> 6713 bytes doc/src/images/statemachine-finished.png | Bin 0 -> 5518 bytes doc/src/images/statemachine-nonparallel.png | Bin 0 -> 5350 bytes doc/src/images/statemachine-parallel.png | Bin 0 -> 8631 bytes doc/src/images/stickman-example.png | Bin 0 -> 18867 bytes doc/src/images/stickman-example1.png | Bin 0 -> 64543 bytes doc/src/images/stickman-example2.png | Bin 0 -> 37412 bytes doc/src/images/stickman-example3.png | Bin 0 -> 23591 bytes doc/src/images/tankgame-example.png | Bin 0 -> 16089 bytes doc/src/images/trafficlight-example.png | Bin 0 -> 5325 bytes doc/src/images/trafficlight-example1.png | Bin 0 -> 3694 bytes doc/src/images/trafficlight-example2.png | Bin 0 -> 7257 bytes doc/src/snippets/animation/sequential/icons.qrc | 6 + .../snippets/animation/sequential/icons/left.png | Bin 0 -> 413 bytes .../snippets/animation/sequential/icons/right.png | Bin 0 -> 414 bytes doc/src/snippets/animation/sequential/main.cpp | 50 + .../snippets/animation/sequential/sequential.pro | 4 + doc/src/snippets/animation/sequential/tracer.cpp | 25 + doc/src/snippets/animation/sequential/tracer.h | 23 + .../code/src_corelib_tools_qeasingcurve.cpp | 4 + doc/src/statemachine.qdoc | 645 ++++ examples/animation/README | 38 + examples/animation/animatedtiles/animatedtiles.pro | 8 + examples/animation/animatedtiles/animatedtiles.qrc | 11 + .../animatedtiles/images/Time-For-Lunch-2.jpg | Bin 0 -> 32471 bytes .../animation/animatedtiles/images/centered.png | Bin 0 -> 892 bytes .../animation/animatedtiles/images/ellipse.png | Bin 0 -> 10767 bytes .../animation/animatedtiles/images/figure8.png | Bin 0 -> 14050 bytes .../animation/animatedtiles/images/kinetic.png | Bin 0 -> 6776 bytes examples/animation/animatedtiles/images/random.png | Bin 0 -> 14969 bytes examples/animation/animatedtiles/images/tile.png | Bin 0 -> 16337 bytes examples/animation/animatedtiles/main.cpp | 280 ++ examples/animation/animation.pro | 16 + .../appchooser/accessories-dictionary.png | Bin 0 -> 5396 bytes examples/animation/appchooser/akregator.png | Bin 0 -> 4873 bytes examples/animation/appchooser/appchooser.pro | 8 + examples/animation/appchooser/appchooser.qrc | 8 + examples/animation/appchooser/digikam.png | Bin 0 -> 3334 bytes examples/animation/appchooser/k3b.png | Bin 0 -> 8220 bytes examples/animation/appchooser/main.cpp | 158 + examples/animation/easing/animation.h | 101 + examples/animation/easing/easing.pro | 14 + examples/animation/easing/easing.qrc | 5 + examples/animation/easing/form.ui | 201 ++ examples/animation/easing/images/qt-logo.png | Bin 0 -> 5149 bytes examples/animation/easing/main.cpp | 53 + examples/animation/easing/window.cpp | 163 + examples/animation/easing/window.h | 79 + examples/animation/moveblocks/main.cpp | 296 ++ examples/animation/moveblocks/moveblocks.pro | 7 + .../animation/states/accessories-dictionary.png | Bin 0 -> 5396 bytes examples/animation/states/akregator.png | Bin 0 -> 4873 bytes examples/animation/states/digikam.png | Bin 0 -> 3334 bytes examples/animation/states/help-browser.png | Bin 0 -> 6984 bytes examples/animation/states/k3b.png | Bin 0 -> 8220 bytes examples/animation/states/kchart.png | Bin 0 -> 4887 bytes examples/animation/states/main.cpp | 284 ++ examples/animation/states/states.pro | 8 + examples/animation/states/states.qrc | 10 + examples/animation/stickman/animation.cpp | 193 ++ examples/animation/stickman/animation.h | 83 + examples/animation/stickman/animations/chilling | Bin 0 -> 6508 bytes examples/animation/stickman/animations/dancing | Bin 0 -> 2348 bytes examples/animation/stickman/animations/dead | Bin 0 -> 268 bytes examples/animation/stickman/animations/jumping | Bin 0 -> 1308 bytes .../animation/stickman/editor/animationdialog.cpp | 192 ++ .../animation/stickman/editor/animationdialog.h | 84 + examples/animation/stickman/editor/editor.pri | 2 + examples/animation/stickman/editor/mainwindow.cpp | 76 + examples/animation/stickman/editor/mainwindow.h | 58 + examples/animation/stickman/graphicsview.cpp | 81 + examples/animation/stickman/graphicsview.h | 64 + examples/animation/stickman/lifecycle.cpp | 212 ++ examples/animation/stickman/lifecycle.h | 80 + examples/animation/stickman/main.cpp | 97 + examples/animation/stickman/node.cpp | 92 + examples/animation/stickman/node.h | 72 + examples/animation/stickman/stickman.cpp | 339 ++ examples/animation/stickman/stickman.h | 103 + examples/animation/stickman/stickman.pro | 19 + examples/animation/sub-attaq/animationmanager.cpp | 93 + examples/animation/sub-attaq/animationmanager.h | 70 + examples/animation/sub-attaq/boat.cpp | 318 ++ examples/animation/sub-attaq/boat.h | 102 + examples/animation/sub-attaq/boat_p.h | 256 ++ examples/animation/sub-attaq/bomb.cpp | 124 + examples/animation/sub-attaq/bomb.h | 76 + .../sub-attaq/custompropertyanimation.cpp | 108 + .../animation/sub-attaq/custompropertyanimation.h | 114 + examples/animation/sub-attaq/data.xml | 15 + examples/animation/sub-attaq/graphicsscene.cpp | 374 +++ examples/animation/sub-attaq/graphicsscene.h | 131 + examples/animation/sub-attaq/main.cpp | 57 + examples/animation/sub-attaq/mainwindow.cpp | 92 + examples/animation/sub-attaq/mainwindow.h | 64 + .../animation/sub-attaq/pics/big/background.png | Bin 0 -> 48858 bytes examples/animation/sub-attaq/pics/big/boat.png | Bin 0 -> 5198 bytes examples/animation/sub-attaq/pics/big/bomb.png | Bin 0 -> 760 bytes .../sub-attaq/pics/big/explosion/boat/step1.png | Bin 0 -> 5760 bytes .../sub-attaq/pics/big/explosion/boat/step2.png | Bin 0 -> 9976 bytes .../sub-attaq/pics/big/explosion/boat/step3.png | Bin 0 -> 12411 bytes .../sub-attaq/pics/big/explosion/boat/step4.png | Bin 0 -> 15438 bytes .../pics/big/explosion/submarine/step1.png | Bin 0 -> 3354 bytes .../pics/big/explosion/submarine/step2.png | Bin 0 -> 6205 bytes .../pics/big/explosion/submarine/step3.png | Bin 0 -> 6678 bytes .../pics/big/explosion/submarine/step4.png | Bin 0 -> 6666 bytes .../animation/sub-attaq/pics/big/submarine.png | Bin 0 -> 3202 bytes examples/animation/sub-attaq/pics/big/surface.png | Bin 0 -> 575 bytes examples/animation/sub-attaq/pics/big/torpedo.png | Bin 0 -> 951 bytes .../sub-attaq/pics/scalable/background-n810.svg | 171 + .../sub-attaq/pics/scalable/background.svg | 171 + .../animation/sub-attaq/pics/scalable/boat.svg | 279 ++ .../animation/sub-attaq/pics/scalable/bomb.svg | 138 + .../animation/sub-attaq/pics/scalable/sand.svg | 103 + examples/animation/sub-attaq/pics/scalable/see.svg | 44 + examples/animation/sub-attaq/pics/scalable/sky.svg | 45 + .../sub-attaq/pics/scalable/sub-attaq.svg | 1473 ++++++++ .../sub-attaq/pics/scalable/submarine.svg | 214 ++ .../animation/sub-attaq/pics/scalable/surface.svg | 49 + .../animation/sub-attaq/pics/scalable/torpedo.svg | 127 + .../animation/sub-attaq/pics/small/background.png | Bin 0 -> 34634 bytes examples/animation/sub-attaq/pics/small/boat.png | Bin 0 -> 2394 bytes examples/animation/sub-attaq/pics/small/bomb.png | Bin 0 -> 760 bytes .../animation/sub-attaq/pics/small/submarine.png | Bin 0 -> 1338 bytes .../animation/sub-attaq/pics/small/surface.png | Bin 0 -> 502 bytes .../animation/sub-attaq/pics/small/torpedo.png | Bin 0 -> 951 bytes .../animation/sub-attaq/pics/welcome/logo-a.png | Bin 0 -> 5972 bytes .../animation/sub-attaq/pics/welcome/logo-a2.png | Bin 0 -> 5969 bytes .../animation/sub-attaq/pics/welcome/logo-b.png | Bin 0 -> 6869 bytes .../animation/sub-attaq/pics/welcome/logo-dash.png | Bin 0 -> 2255 bytes .../animation/sub-attaq/pics/welcome/logo-excl.png | Bin 0 -> 2740 bytes .../animation/sub-attaq/pics/welcome/logo-q.png | Bin 0 -> 7016 bytes .../animation/sub-attaq/pics/welcome/logo-s.png | Bin 0 -> 5817 bytes .../animation/sub-attaq/pics/welcome/logo-t.png | Bin 0 -> 3717 bytes .../animation/sub-attaq/pics/welcome/logo-t2.png | Bin 0 -> 3688 bytes .../animation/sub-attaq/pics/welcome/logo-u.png | Bin 0 -> 5374 bytes examples/animation/sub-attaq/pixmapitem.cpp | 59 + examples/animation/sub-attaq/pixmapitem.h | 63 + examples/animation/sub-attaq/progressitem.cpp | 67 + examples/animation/sub-attaq/progressitem.h | 61 + examples/animation/sub-attaq/qanimationstate.cpp | 171 + examples/animation/sub-attaq/qanimationstate.h | 92 + examples/animation/sub-attaq/states.cpp | 325 ++ examples/animation/sub-attaq/states.h | 180 + examples/animation/sub-attaq/sub-attaq.pro | 36 + examples/animation/sub-attaq/subattaq.qrc | 38 + examples/animation/sub-attaq/submarine.cpp | 211 ++ examples/animation/sub-attaq/submarine.h | 92 + examples/animation/sub-attaq/submarine_p.h | 139 + examples/animation/sub-attaq/torpedo.cpp | 120 + examples/animation/sub-attaq/torpedo.h | 76 + examples/examples.pro | 2 + examples/statemachine/README | 36 + .../eventtransitions/eventtransitions.pro | 7 + examples/statemachine/eventtransitions/main.cpp | 116 + examples/statemachine/factorial/factorial.pro | 11 + examples/statemachine/factorial/main.cpp | 182 + examples/statemachine/pingpong/main.cpp | 145 + examples/statemachine/pingpong/pingpong.pro | 11 + examples/statemachine/statemachine.pro | 15 + examples/statemachine/tankgame/gameitem.cpp | 129 + examples/statemachine/tankgame/gameitem.h | 66 + .../statemachine/tankgame/gameovertransition.cpp | 80 + .../statemachine/tankgame/gameovertransition.h | 63 + examples/statemachine/tankgame/main.cpp | 53 + examples/statemachine/tankgame/mainwindow.cpp | 342 ++ examples/statemachine/tankgame/mainwindow.h | 93 + examples/statemachine/tankgame/plugin.h | 62 + examples/statemachine/tankgame/rocketitem.cpp | 101 + examples/statemachine/tankgame/rocketitem.h | 66 + examples/statemachine/tankgame/tankgame.pro | 19 + examples/statemachine/tankgame/tankitem.cpp | 302 ++ examples/statemachine/tankgame/tankitem.h | 109 + .../tankgameplugins/random_ai/random_ai.pro | 13 + .../tankgameplugins/random_ai/random_ai_plugin.cpp | 79 + .../tankgameplugins/random_ai/random_ai_plugin.h | 105 + .../tankgameplugins/seek_ai/seek_ai.cpp | 89 + .../statemachine/tankgameplugins/seek_ai/seek_ai.h | 249 ++ .../tankgameplugins/seek_ai/seek_ai.pro | 13 + .../tankgameplugins/spin_ai/spin_ai.cpp | 70 + .../statemachine/tankgameplugins/spin_ai/spin_ai.h | 92 + .../tankgameplugins/spin_ai/spin_ai.pro | 13 + .../spin_ai_with_error/spin_ai_with_error.cpp | 70 + .../spin_ai_with_error/spin_ai_with_error.h | 92 + .../spin_ai_with_error/spin_ai_with_error.pro | 13 + .../tankgameplugins/tankgameplugins.pro | 11 + examples/statemachine/trafficlight/main.cpp | 190 ++ .../statemachine/trafficlight/trafficlight.pro | 7 + examples/statemachine/twowaybutton/main.cpp | 86 + .../statemachine/twowaybutton/twowaybutton.pro | 7 + mkspecs/win32-icc/qmake.conf | 2 +- src/3rdparty/easing/easing.cpp | 670 ++++ src/3rdparty/easing/legal.qdoc | 35 + src/corelib/animation/animation.pri | 25 + src/corelib/animation/qabstractanimation.cpp | 759 +++++ src/corelib/animation/qabstractanimation.h | 137 + src/corelib/animation/qabstractanimation_p.h | 136 + src/corelib/animation/qanimationgroup.cpp | 309 ++ src/corelib/animation/qanimationgroup.h | 88 + src/corelib/animation/qanimationgroup_p.h | 79 + src/corelib/animation/qparallelanimationgroup.cpp | 316 ++ src/corelib/animation/qparallelanimationgroup.h | 86 + src/corelib/animation/qparallelanimationgroup_p.h | 85 + src/corelib/animation/qpauseanimation.cpp | 154 + src/corelib/animation/qpauseanimation.h | 84 + src/corelib/animation/qpropertyanimation.cpp | 316 ++ src/corelib/animation/qpropertyanimation.h | 90 + src/corelib/animation/qpropertyanimation_p.h | 89 + .../animation/qsequentialanimationgroup.cpp | 594 ++++ src/corelib/animation/qsequentialanimationgroup.h | 96 + .../animation/qsequentialanimationgroup_p.h | 111 + src/corelib/animation/qvariantanimation.cpp | 644 ++++ src/corelib/animation/qvariantanimation.h | 130 + src/corelib/animation/qvariantanimation_p.h | 130 + src/corelib/corelib.pro | 2 + src/corelib/kernel/kernel.pri | 8 +- src/corelib/kernel/qcoreevent.cpp | 2 + src/corelib/kernel/qcoreevent.h | 8 +- src/corelib/statemachine/qabstractstate.cpp | 202 ++ src/corelib/statemachine/qabstractstate.h | 90 + src/corelib/statemachine/qabstractstate_p.h | 84 + src/corelib/statemachine/qabstracttransition.cpp | 342 ++ src/corelib/statemachine/qabstracttransition.h | 111 + src/corelib/statemachine/qabstracttransition_p.h | 91 + src/corelib/statemachine/qeventtransition.cpp | 282 ++ src/corelib/statemachine/qeventtransition.h | 96 + src/corelib/statemachine/qeventtransition_p.h | 78 + src/corelib/statemachine/qfinalstate.cpp | 134 + src/corelib/statemachine/qfinalstate.h | 76 + src/corelib/statemachine/qhistorystate.cpp | 223 ++ src/corelib/statemachine/qhistorystate.h | 91 + src/corelib/statemachine/qhistorystate_p.h | 79 + src/corelib/statemachine/qsignalevent.h | 77 + src/corelib/statemachine/qsignaleventgenerator_p.h | 78 + src/corelib/statemachine/qsignaltransition.cpp | 257 ++ src/corelib/statemachine/qsignaltransition.h | 89 + src/corelib/statemachine/qsignaltransition_p.h | 78 + src/corelib/statemachine/qstate.cpp | 497 +++ src/corelib/statemachine/qstate.h | 113 + src/corelib/statemachine/qstate_p.h | 108 + src/corelib/statemachine/qstatemachine.cpp | 2216 ++++++++++++ src/corelib/statemachine/qstatemachine.h | 166 + src/corelib/statemachine/qstatemachine_p.h | 217 ++ src/corelib/statemachine/qwrappedevent.h | 76 + src/corelib/statemachine/statemachine.pri | 30 + src/corelib/tools/qeasingcurve.cpp | 846 +++++ src/corelib/tools/qeasingcurve.h | 114 + src/corelib/tools/qtimeline.cpp | 114 +- src/corelib/tools/qtimeline.h | 5 + src/corelib/tools/tools.pri | 2 + src/gui/animation/animation.pri | 3 + src/gui/animation/qguivariantanimation.cpp | 75 + src/gui/graphicsview/qgraphicsitem_p.h | 12 +- src/gui/graphicsview/qgraphicsproxywidget.cpp | 2 + src/gui/graphicsview/qgraphicsproxywidget.h | 2 + src/gui/gui.pro | 2 + src/gui/kernel/qapplication.cpp | 6 + src/gui/painting/qdrawhelper.cpp | 8 +- src/gui/statemachine/qbasickeyeventtransition.cpp | 203 ++ src/gui/statemachine/qbasickeyeventtransition_p.h | 93 + .../statemachine/qbasicmouseeventtransition.cpp | 208 ++ .../statemachine/qbasicmouseeventtransition_p.h | 98 + src/gui/statemachine/qguistatemachine.cpp | 559 +++ src/gui/statemachine/qkeyeventtransition.cpp | 186 + src/gui/statemachine/qkeyeventtransition.h | 87 + src/gui/statemachine/qmouseeventtransition.cpp | 216 ++ src/gui/statemachine/qmouseeventtransition.h | 92 + src/gui/statemachine/statemachine.pri | 13 + tests/auto/auto.pro | 6 + tests/auto/qanimationgroup/qanimationgroup.pro | 5 + tests/auto/qanimationgroup/tst_qanimationgroup.cpp | 413 +++ tests/auto/qeasingcurve/qeasingcurve.pro | 3 + tests/auto/qeasingcurve/tst_qeasingcurve.cpp | 487 +++ tests/auto/qmake/testdata/bundle-spaces/some-file | 6 + .../qparallelanimationgroup.pro | 5 + .../tst_qparallelanimationgroup.cpp | 834 +++++ .../auto/qpropertyanimation/qpropertyanimation.pro | 5 + .../qpropertyanimation/tst_qpropertyanimation.cpp | 919 +++++ .../qsequentialanimationgroup.pro | 5 + .../tst_qsequentialanimationgroup.cpp | 1649 +++++++++ tests/auto/qstate/qstate.pro | 5 + tests/auto/qstate/tst_qstate.cpp | 340 ++ tests/auto/qstatemachine/qstatemachine.pro | 4 + tests/auto/qstatemachine/tst_qstatemachine.cpp | 3548 ++++++++++++++++++++ tests/benchmarks/benchmarks.pro | 1 + tests/benchmarks/qanimation/dummyanimation.cpp | 20 + tests/benchmarks/qanimation/dummyanimation.h | 19 + tests/benchmarks/qanimation/dummyobject.cpp | 25 + tests/benchmarks/qanimation/dummyobject.h | 23 + tests/benchmarks/qanimation/main.cpp | 150 + tests/benchmarks/qanimation/qanimation.pro | 18 + tests/benchmarks/qanimation/rectanimation.cpp | 58 + tests/benchmarks/qanimation/rectanimation.h | 30 + tests/benchmarks/qvariant/qvariant.pro | 1 - tests/benchmarks/qvariant/tst_qvariant.cpp | 115 +- 363 files changed, 38378 insertions(+), 130 deletions(-) create mode 100644 doc/src/animation.qdoc create mode 100644 doc/src/diagrams/animations-architecture.svg create mode 100644 doc/src/diagrams/programs/easingcurve/easingcurve.pro create mode 100644 doc/src/diagrams/programs/easingcurve/main.cpp create mode 100644 doc/src/examples/eventtransitions.qdoc create mode 100644 doc/src/examples/factorial.qdoc create mode 100644 doc/src/examples/pingpong.qdoc create mode 100644 doc/src/examples/stickman.qdoc create mode 100644 doc/src/examples/tankgame.qdoc create mode 100644 doc/src/examples/trafficlight.qdoc create mode 100644 doc/src/examples/twowaybutton.qdoc create mode 100644 doc/src/images/animations-architecture.png create mode 100644 doc/src/images/factorial-example.png create mode 100644 doc/src/images/pingpong-example.png create mode 100644 doc/src/images/qeasingcurve-cosinecurve.png create mode 100644 doc/src/images/qeasingcurve-inback.png create mode 100644 doc/src/images/qeasingcurve-inbounce.png create mode 100644 doc/src/images/qeasingcurve-incirc.png create mode 100644 doc/src/images/qeasingcurve-incubic.png create mode 100644 doc/src/images/qeasingcurve-incurve.png create mode 100644 doc/src/images/qeasingcurve-inelastic.png create mode 100644 doc/src/images/qeasingcurve-inexpo.png create mode 100644 doc/src/images/qeasingcurve-inoutback.png create mode 100644 doc/src/images/qeasingcurve-inoutbounce.png create mode 100644 doc/src/images/qeasingcurve-inoutcirc.png create mode 100644 doc/src/images/qeasingcurve-inoutcubic.png create mode 100644 doc/src/images/qeasingcurve-inoutelastic.png create mode 100644 doc/src/images/qeasingcurve-inoutexpo.png create mode 100644 doc/src/images/qeasingcurve-inoutquad.png create mode 100644 doc/src/images/qeasingcurve-inoutquart.png create mode 100644 doc/src/images/qeasingcurve-inoutquint.png create mode 100644 doc/src/images/qeasingcurve-inoutsine.png create mode 100644 doc/src/images/qeasingcurve-inquad.png create mode 100644 doc/src/images/qeasingcurve-inquart.png create mode 100644 doc/src/images/qeasingcurve-inquint.png create mode 100644 doc/src/images/qeasingcurve-insine.png create mode 100644 doc/src/images/qeasingcurve-linear.png create mode 100644 doc/src/images/qeasingcurve-outback.png create mode 100644 doc/src/images/qeasingcurve-outbounce.png create mode 100644 doc/src/images/qeasingcurve-outcirc.png create mode 100644 doc/src/images/qeasingcurve-outcubic.png create mode 100644 doc/src/images/qeasingcurve-outcurve.png create mode 100644 doc/src/images/qeasingcurve-outelastic.png create mode 100644 doc/src/images/qeasingcurve-outexpo.png create mode 100644 doc/src/images/qeasingcurve-outinback.png create mode 100644 doc/src/images/qeasingcurve-outinbounce.png create mode 100644 doc/src/images/qeasingcurve-outincirc.png create mode 100644 doc/src/images/qeasingcurve-outincubic.png create mode 100644 doc/src/images/qeasingcurve-outinelastic.png create mode 100644 doc/src/images/qeasingcurve-outinexpo.png create mode 100644 doc/src/images/qeasingcurve-outinquad.png create mode 100644 doc/src/images/qeasingcurve-outinquart.png create mode 100644 doc/src/images/qeasingcurve-outinquint.png create mode 100644 doc/src/images/qeasingcurve-outinsine.png create mode 100644 doc/src/images/qeasingcurve-outquad.png create mode 100644 doc/src/images/qeasingcurve-outquart.png create mode 100644 doc/src/images/qeasingcurve-outquint.png create mode 100644 doc/src/images/qeasingcurve-outsine.png create mode 100644 doc/src/images/qeasingcurve-sinecurve.png create mode 100644 doc/src/images/statemachine-button-history.png create mode 100644 doc/src/images/statemachine-button-nested.png create mode 100644 doc/src/images/statemachine-button.png create mode 100644 doc/src/images/statemachine-customevents.png create mode 100644 doc/src/images/statemachine-customevents2.png create mode 100644 doc/src/images/statemachine-finished.png create mode 100644 doc/src/images/statemachine-nonparallel.png create mode 100644 doc/src/images/statemachine-parallel.png create mode 100644 doc/src/images/stickman-example.png create mode 100644 doc/src/images/stickman-example1.png create mode 100644 doc/src/images/stickman-example2.png create mode 100644 doc/src/images/stickman-example3.png create mode 100644 doc/src/images/tankgame-example.png create mode 100644 doc/src/images/trafficlight-example.png create mode 100644 doc/src/images/trafficlight-example1.png create mode 100644 doc/src/images/trafficlight-example2.png create mode 100644 doc/src/snippets/animation/sequential/icons.qrc create mode 100644 doc/src/snippets/animation/sequential/icons/left.png create mode 100644 doc/src/snippets/animation/sequential/icons/right.png create mode 100644 doc/src/snippets/animation/sequential/main.cpp create mode 100644 doc/src/snippets/animation/sequential/sequential.pro create mode 100644 doc/src/snippets/animation/sequential/tracer.cpp create mode 100644 doc/src/snippets/animation/sequential/tracer.h create mode 100644 doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp create mode 100644 doc/src/statemachine.qdoc create mode 100644 examples/animation/README create mode 100644 examples/animation/animatedtiles/animatedtiles.pro create mode 100644 examples/animation/animatedtiles/animatedtiles.qrc create mode 100644 examples/animation/animatedtiles/images/Time-For-Lunch-2.jpg create mode 100644 examples/animation/animatedtiles/images/centered.png create mode 100644 examples/animation/animatedtiles/images/ellipse.png create mode 100644 examples/animation/animatedtiles/images/figure8.png create mode 100644 examples/animation/animatedtiles/images/kinetic.png create mode 100644 examples/animation/animatedtiles/images/random.png create mode 100644 examples/animation/animatedtiles/images/tile.png create mode 100644 examples/animation/animatedtiles/main.cpp create mode 100644 examples/animation/animation.pro create mode 100644 examples/animation/appchooser/accessories-dictionary.png create mode 100644 examples/animation/appchooser/akregator.png create mode 100644 examples/animation/appchooser/appchooser.pro create mode 100644 examples/animation/appchooser/appchooser.qrc create mode 100644 examples/animation/appchooser/digikam.png create mode 100644 examples/animation/appchooser/k3b.png create mode 100644 examples/animation/appchooser/main.cpp create mode 100644 examples/animation/easing/animation.h create mode 100644 examples/animation/easing/easing.pro create mode 100644 examples/animation/easing/easing.qrc create mode 100644 examples/animation/easing/form.ui create mode 100644 examples/animation/easing/images/qt-logo.png create mode 100644 examples/animation/easing/main.cpp create mode 100644 examples/animation/easing/window.cpp create mode 100644 examples/animation/easing/window.h create mode 100644 examples/animation/moveblocks/main.cpp create mode 100644 examples/animation/moveblocks/moveblocks.pro create mode 100644 examples/animation/states/accessories-dictionary.png create mode 100644 examples/animation/states/akregator.png create mode 100644 examples/animation/states/digikam.png create mode 100644 examples/animation/states/help-browser.png create mode 100644 examples/animation/states/k3b.png create mode 100644 examples/animation/states/kchart.png create mode 100644 examples/animation/states/main.cpp create mode 100644 examples/animation/states/states.pro create mode 100644 examples/animation/states/states.qrc create mode 100644 examples/animation/stickman/animation.cpp create mode 100644 examples/animation/stickman/animation.h create mode 100644 examples/animation/stickman/animations/chilling create mode 100644 examples/animation/stickman/animations/dancing create mode 100644 examples/animation/stickman/animations/dead create mode 100644 examples/animation/stickman/animations/jumping create mode 100644 examples/animation/stickman/editor/animationdialog.cpp create mode 100644 examples/animation/stickman/editor/animationdialog.h create mode 100644 examples/animation/stickman/editor/editor.pri create mode 100644 examples/animation/stickman/editor/mainwindow.cpp create mode 100644 examples/animation/stickman/editor/mainwindow.h create mode 100644 examples/animation/stickman/graphicsview.cpp create mode 100644 examples/animation/stickman/graphicsview.h create mode 100644 examples/animation/stickman/lifecycle.cpp create mode 100644 examples/animation/stickman/lifecycle.h create mode 100644 examples/animation/stickman/main.cpp create mode 100644 examples/animation/stickman/node.cpp create mode 100644 examples/animation/stickman/node.h create mode 100644 examples/animation/stickman/stickman.cpp create mode 100644 examples/animation/stickman/stickman.h create mode 100644 examples/animation/stickman/stickman.pro create mode 100644 examples/animation/sub-attaq/animationmanager.cpp create mode 100644 examples/animation/sub-attaq/animationmanager.h create mode 100644 examples/animation/sub-attaq/boat.cpp create mode 100644 examples/animation/sub-attaq/boat.h create mode 100644 examples/animation/sub-attaq/boat_p.h create mode 100644 examples/animation/sub-attaq/bomb.cpp create mode 100644 examples/animation/sub-attaq/bomb.h create mode 100644 examples/animation/sub-attaq/custompropertyanimation.cpp create mode 100644 examples/animation/sub-attaq/custompropertyanimation.h create mode 100644 examples/animation/sub-attaq/data.xml create mode 100644 examples/animation/sub-attaq/graphicsscene.cpp create mode 100644 examples/animation/sub-attaq/graphicsscene.h create mode 100644 examples/animation/sub-attaq/main.cpp create mode 100644 examples/animation/sub-attaq/mainwindow.cpp create mode 100644 examples/animation/sub-attaq/mainwindow.h create mode 100644 examples/animation/sub-attaq/pics/big/background.png create mode 100644 examples/animation/sub-attaq/pics/big/boat.png create mode 100644 examples/animation/sub-attaq/pics/big/bomb.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step1.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step2.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step3.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step4.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png create mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png create mode 100644 examples/animation/sub-attaq/pics/big/submarine.png create mode 100644 examples/animation/sub-attaq/pics/big/surface.png create mode 100644 examples/animation/sub-attaq/pics/big/torpedo.png create mode 100644 examples/animation/sub-attaq/pics/scalable/background-n810.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/background.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/boat.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/bomb.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/sand.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/see.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/sky.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/sub-attaq.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/submarine.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/surface.svg create mode 100644 examples/animation/sub-attaq/pics/scalable/torpedo.svg create mode 100644 examples/animation/sub-attaq/pics/small/background.png create mode 100644 examples/animation/sub-attaq/pics/small/boat.png create mode 100644 examples/animation/sub-attaq/pics/small/bomb.png create mode 100644 examples/animation/sub-attaq/pics/small/submarine.png create mode 100644 examples/animation/sub-attaq/pics/small/surface.png create mode 100644 examples/animation/sub-attaq/pics/small/torpedo.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-a.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-a2.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-b.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-dash.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-excl.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-q.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-s.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-t.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-t2.png create mode 100644 examples/animation/sub-attaq/pics/welcome/logo-u.png create mode 100644 examples/animation/sub-attaq/pixmapitem.cpp create mode 100644 examples/animation/sub-attaq/pixmapitem.h create mode 100644 examples/animation/sub-attaq/progressitem.cpp create mode 100644 examples/animation/sub-attaq/progressitem.h create mode 100644 examples/animation/sub-attaq/qanimationstate.cpp create mode 100644 examples/animation/sub-attaq/qanimationstate.h create mode 100644 examples/animation/sub-attaq/states.cpp create mode 100644 examples/animation/sub-attaq/states.h create mode 100644 examples/animation/sub-attaq/sub-attaq.pro create mode 100644 examples/animation/sub-attaq/subattaq.qrc create mode 100644 examples/animation/sub-attaq/submarine.cpp create mode 100644 examples/animation/sub-attaq/submarine.h create mode 100644 examples/animation/sub-attaq/submarine_p.h create mode 100644 examples/animation/sub-attaq/torpedo.cpp create mode 100644 examples/animation/sub-attaq/torpedo.h create mode 100644 examples/statemachine/README create mode 100644 examples/statemachine/eventtransitions/eventtransitions.pro create mode 100644 examples/statemachine/eventtransitions/main.cpp create mode 100644 examples/statemachine/factorial/factorial.pro create mode 100644 examples/statemachine/factorial/main.cpp create mode 100644 examples/statemachine/pingpong/main.cpp create mode 100644 examples/statemachine/pingpong/pingpong.pro create mode 100644 examples/statemachine/statemachine.pro create mode 100644 examples/statemachine/tankgame/gameitem.cpp create mode 100644 examples/statemachine/tankgame/gameitem.h create mode 100644 examples/statemachine/tankgame/gameovertransition.cpp create mode 100644 examples/statemachine/tankgame/gameovertransition.h create mode 100644 examples/statemachine/tankgame/main.cpp create mode 100644 examples/statemachine/tankgame/mainwindow.cpp create mode 100644 examples/statemachine/tankgame/mainwindow.h create mode 100644 examples/statemachine/tankgame/plugin.h create mode 100644 examples/statemachine/tankgame/rocketitem.cpp create mode 100644 examples/statemachine/tankgame/rocketitem.h create mode 100644 examples/statemachine/tankgame/tankgame.pro create mode 100644 examples/statemachine/tankgame/tankitem.cpp create mode 100644 examples/statemachine/tankgame/tankitem.h create mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai.pro create mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp create mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h create mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp create mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.h create mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro create mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp create mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.h create mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro create mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp create mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h create mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro create mode 100644 examples/statemachine/tankgameplugins/tankgameplugins.pro create mode 100644 examples/statemachine/trafficlight/main.cpp create mode 100644 examples/statemachine/trafficlight/trafficlight.pro create mode 100644 examples/statemachine/twowaybutton/main.cpp create mode 100644 examples/statemachine/twowaybutton/twowaybutton.pro create mode 100644 src/3rdparty/easing/easing.cpp create mode 100644 src/3rdparty/easing/legal.qdoc create mode 100644 src/corelib/animation/animation.pri create mode 100644 src/corelib/animation/qabstractanimation.cpp create mode 100644 src/corelib/animation/qabstractanimation.h create mode 100644 src/corelib/animation/qabstractanimation_p.h create mode 100644 src/corelib/animation/qanimationgroup.cpp create mode 100644 src/corelib/animation/qanimationgroup.h create mode 100644 src/corelib/animation/qanimationgroup_p.h create mode 100644 src/corelib/animation/qparallelanimationgroup.cpp create mode 100644 src/corelib/animation/qparallelanimationgroup.h create mode 100644 src/corelib/animation/qparallelanimationgroup_p.h create mode 100644 src/corelib/animation/qpauseanimation.cpp create mode 100644 src/corelib/animation/qpauseanimation.h create mode 100644 src/corelib/animation/qpropertyanimation.cpp create mode 100644 src/corelib/animation/qpropertyanimation.h create mode 100644 src/corelib/animation/qpropertyanimation_p.h create mode 100644 src/corelib/animation/qsequentialanimationgroup.cpp create mode 100644 src/corelib/animation/qsequentialanimationgroup.h create mode 100644 src/corelib/animation/qsequentialanimationgroup_p.h create mode 100644 src/corelib/animation/qvariantanimation.cpp create mode 100644 src/corelib/animation/qvariantanimation.h create mode 100644 src/corelib/animation/qvariantanimation_p.h create mode 100644 src/corelib/statemachine/qabstractstate.cpp create mode 100644 src/corelib/statemachine/qabstractstate.h create mode 100644 src/corelib/statemachine/qabstractstate_p.h create mode 100644 src/corelib/statemachine/qabstracttransition.cpp create mode 100644 src/corelib/statemachine/qabstracttransition.h create mode 100644 src/corelib/statemachine/qabstracttransition_p.h create mode 100644 src/corelib/statemachine/qeventtransition.cpp create mode 100644 src/corelib/statemachine/qeventtransition.h create mode 100644 src/corelib/statemachine/qeventtransition_p.h create mode 100644 src/corelib/statemachine/qfinalstate.cpp create mode 100644 src/corelib/statemachine/qfinalstate.h create mode 100644 src/corelib/statemachine/qhistorystate.cpp create mode 100644 src/corelib/statemachine/qhistorystate.h create mode 100644 src/corelib/statemachine/qhistorystate_p.h create mode 100644 src/corelib/statemachine/qsignalevent.h create mode 100644 src/corelib/statemachine/qsignaleventgenerator_p.h create mode 100644 src/corelib/statemachine/qsignaltransition.cpp create mode 100644 src/corelib/statemachine/qsignaltransition.h create mode 100644 src/corelib/statemachine/qsignaltransition_p.h create mode 100644 src/corelib/statemachine/qstate.cpp create mode 100644 src/corelib/statemachine/qstate.h create mode 100644 src/corelib/statemachine/qstate_p.h create mode 100644 src/corelib/statemachine/qstatemachine.cpp create mode 100644 src/corelib/statemachine/qstatemachine.h create mode 100644 src/corelib/statemachine/qstatemachine_p.h create mode 100644 src/corelib/statemachine/qwrappedevent.h create mode 100644 src/corelib/statemachine/statemachine.pri create mode 100644 src/corelib/tools/qeasingcurve.cpp create mode 100644 src/corelib/tools/qeasingcurve.h create mode 100644 src/gui/animation/animation.pri create mode 100644 src/gui/animation/qguivariantanimation.cpp create mode 100644 src/gui/statemachine/qbasickeyeventtransition.cpp create mode 100644 src/gui/statemachine/qbasickeyeventtransition_p.h create mode 100644 src/gui/statemachine/qbasicmouseeventtransition.cpp create mode 100644 src/gui/statemachine/qbasicmouseeventtransition_p.h create mode 100644 src/gui/statemachine/qguistatemachine.cpp create mode 100644 src/gui/statemachine/qkeyeventtransition.cpp create mode 100644 src/gui/statemachine/qkeyeventtransition.h create mode 100644 src/gui/statemachine/qmouseeventtransition.cpp create mode 100644 src/gui/statemachine/qmouseeventtransition.h create mode 100644 src/gui/statemachine/statemachine.pri create mode 100644 tests/auto/qanimationgroup/qanimationgroup.pro create mode 100644 tests/auto/qanimationgroup/tst_qanimationgroup.cpp create mode 100644 tests/auto/qeasingcurve/qeasingcurve.pro create mode 100644 tests/auto/qeasingcurve/tst_qeasingcurve.cpp create mode 100644 tests/auto/qparallelanimationgroup/qparallelanimationgroup.pro create mode 100644 tests/auto/qparallelanimationgroup/tst_qparallelanimationgroup.cpp create mode 100644 tests/auto/qpropertyanimation/qpropertyanimation.pro create mode 100644 tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp create mode 100644 tests/auto/qsequentialanimationgroup/qsequentialanimationgroup.pro create mode 100644 tests/auto/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp create mode 100644 tests/auto/qstate/qstate.pro create mode 100644 tests/auto/qstate/tst_qstate.cpp create mode 100644 tests/auto/qstatemachine/qstatemachine.pro create mode 100644 tests/auto/qstatemachine/tst_qstatemachine.cpp create mode 100644 tests/benchmarks/qanimation/dummyanimation.cpp create mode 100644 tests/benchmarks/qanimation/dummyanimation.h create mode 100644 tests/benchmarks/qanimation/dummyobject.cpp create mode 100644 tests/benchmarks/qanimation/dummyobject.h create mode 100644 tests/benchmarks/qanimation/main.cpp create mode 100644 tests/benchmarks/qanimation/qanimation.pro create mode 100644 tests/benchmarks/qanimation/rectanimation.cpp create mode 100644 tests/benchmarks/qanimation/rectanimation.h diff --git a/demos/qtdemo/xml/examples.xml b/demos/qtdemo/xml/examples.xml index 96a3e80..2560848 100644 --- a/demos/qtdemo/xml/examples.xml +++ b/demos/qtdemo/xml/examples.xml @@ -19,6 +19,15 @@ + + + + + + + + + @@ -167,6 +176,12 @@ + + + + + + diff --git a/doc/src/animation.qdoc b/doc/src/animation.qdoc new file mode 100644 index 0000000..b4e603c --- /dev/null +++ b/doc/src/animation.qdoc @@ -0,0 +1,368 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page animation-overview.html + \title The Animation Framework + \ingroup architecture + \ingroup animation + \brief An overview of the Animation Framework + + \keyword Animation + + The animation framework is part of the Kinetic project, and aims + to provide an easy way for creating animated and smooth GUI's. By + animating Qt properties, the framework provides great freedom for + animating widgets and other \l{QObject}s. The framework can also + be used with the Graphics View framework. + + In this overview, we explain the basics of its architecture. We + also show examples of the most common techniques that the + framework allows for animating QObjects and graphics items. + + \tableofcontents + + \section1 The Animation Architecture + + We will in this section take a high-level look at the animation + framework's architecture and how it is used to animate Qt + properties. The following diagram shows the most important classes + in the animation framework. + + \image animations-architecture.png + + The animation framework foundation consists of the base class + QAbstractAnimation, and its two subclasses QVariantAnimation and + QAnimationGroup. QAbstractAnimation is the ancestor of all + animations. It represents basic properties that are common for all + animations in the framework; notably, the ability to start, stop, + and pause an animation. It is also receives the time change + notifications. + + The animation framework further provides the QPropertyAnimation + class, which inherits QVariantAnimation and performs animation of + a Qt property, which is part of Qt's \l{Meta-Object + System}{meta-object system}. The class performs an interpolation + over the property using an easing curve. So when you want to + animate a value, you can declare it as a property and make your + class a QObject. Note that this gives us great freedom in + animating already existing widgets and other \l{QObject}s. + + Complex animations can be constructed by building a tree structure + of \l{QAbstractAnimation}s. The tree is built by using + \l{QAnimationGroup}s, which function as containers for other + animations. Note also that the groups are subclasses of + QAbstractAnimation, so groups can themselves contain other groups. + + The animation framework can be used on its own, but is also + designed to be part of the state machine framework (See the + \l{The State Machine Framework}{state machine framework} for an + introduction to the Qt state machine). The state machine provides + a special state that can play an animation. A QState can also set + properties when the state is entered or exited, and this special + animation state will interpolate between these values when given a + QPropertyAnimation. We will look more closely at this later. + + Behind the scenes, the animations are controlled by a global + timer, which sends \l{QAbstractAnimation::updateCurrentTime()}{updates} to + all animations that are playing. + + For detailed descriptions of the classes' function and roles in + the framework, please look up their class descriptions. + + \section1 Animating Qt Properties + + As mentioned in the previous section, the QPropertyAnimation class + can interpolate over Qt properties. It is this class that should + be used for animation of values; in fact, its superclass, + QVariantAnimation, is an abstract class, and cannot be used + directly. + + A major reason we chose to animate Qt properties is that it + presents us with freedom to animate already existing classes in + the Qt API. Notably, the QWidget class (which we can also embed in + a QGraphicsView) has properties for its bounds, colors, etc. + Let's look at a small example: + + \code + QPushButton button("Animated Button"); + button.show(); + + QPropertyAnimation animation(&button, "geometry"); + animation.setDuration(10000); + animation.setStartValue(QRect(0, 0, 100, 30)); + animation.setEndValue(QRect(250, 250, 100, 30)); + + animation.start(); + \endcode + + This code will move \c button from the top left corner of the + screen to the position (250, 250) in 10 seconds (10000 milliseconds). + + The example above will do a linear interpolation between the + start and end value. It is also possible to set values + situated between the start and end value. The interpolation + will then go by these points. + + \code + QPushButton button("Animated Button"); + button.show(); + + QPropertyAnimation animation(&button, "geometry"); + animation.setDuration(10000); + + animation.setKeyValueAt(0, QRect(0, 0, 100, 30)); + animation.setKeyValueAt(0.8, QRect(250, 250, 100, 30)); + animation.setKeyValueAt(1, QRect(0, 0, 100, 30)); + + animation.start(); + \endcode + + In this example, the animation will take the button to (250, 250) + in 8 seconds, and then move it back to its original position in + the remaining 2 seconds. The movement will be linearly + interpolated between these points. + + You also have the possibility to animate values of a QObject + that is not declared as a Qt property. The only requirement is + that this value has a setter. You can then subclass the class + containing the value and declare a property that uses this setter. + Note that each Qt property requires a getter, so you will need to + provide a getter yourself if this is not defined. + + \code + class MyGraphicsRectItem : public QObject, public QGraphicsRectItem + { + Q_OBJECT + Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry) + }; + \endcode + + In the above code example, we subclass QGraphicsRectItem and + define a geometry property. We can now animate the widgets + geometry even if QGraphicsRectItem does not provide the geometry + property. + + For a general introduction to the Qt property system, see its + \l{Qt's Property System}{overview}. + + \section1 Animations and the Graphics View Framework + + When you want to animate \l{QGraphicsItem}s, you also use + QPropertyAnimation. However, QGraphicsItem does not inherit QObject. + A good solution is to subclass the graphics item you wish to animate. + This class will then also inherit QObject. + This way, QPropertyAnimation can be used for \l{QGraphicsItem}s. + The example below shows how this is done. Another possibility is + to inherit QGraphicsWidget, which already is a QObject. + + \code + class Pixmap : public QObject, public QGraphicsPixmapItem + { + Q_OBJECT + Q_PROPERTY(QPointF pos READ pos WRITE setPos) + ... + \endcode + + As described in the previous section, we need to define + properties that we wish to animate. + + Note that QObject must be the first class inherited as the + meta-object system demands this. + + \warning The QItemAnimation class, which was initially intended + for animating \l{QGraphicsItem}s may be deprecated or removed from + the animation framework. + + \omit (need something about the list of animations). \endomit + + \section1 Easing Curves + + As mentioned, QPropertyAnimation performs an interpolation between + the start and end property value. In addition to adding more key + values to the animation, you can also use an easing curve. Easing + curves describe a function that controls how the speed of the + interpolation between 0 and 1 should be, and are useful if you + want to control the speed of an animation without changing the + path of the interpolation. + + \code + QPushButton button("Animated Button"); + button.show(); + + QPropertyAnimation animation(&button, "geometry"); + animation.setDuration(3000); + animation.setStartValue(QRect(0, 0, 100, 30)); + animation.setEndValue(QRect(250, 250, 100, 30)); + + animation.setEasingCurve(QEasingCurve::OutBounce); + + animation.start(); + \endcode + + Here the animation will follow a curve that makes it bounce like a + ball as if it was dropped from the start to the end position. + QEasingCurve has a large collection of curves for you to choose + from. These are defined by the QEasingCurve::Type enum. If you are + in need of another curve, you can also implement one yourself, and + register it with QEasingCurve. + + \omit Drop this for the first Lab release + (Example of custom easing curve (without the actual impl of + the function I expect) + \endomit + + \section1 Putting Animations Together + + An application will often contain more than one animation. For + instance, you might want to move more than one graphics item + simultaneously or move them in sequence after each other. + + The subclasses of QAnimationGroup (QSequentialAnimationGroup and + QParallelAnimationGroup) are containers for other animations so + that these animations can be animated either in sequence or + parallel. The QAnimationGroup is an example of an animation that + does not animate properties, but it gets notified of time changes + periodically. This enables it to forward those time changes to its + contained animations, and thereby controlling when its animations + are played. + + Let's look at code examples that use both + QSequentialAnimationGroup and QParallelAnimationGroup, starting + off with the latter. + + \code + QPushButton *bonnie = new QPushButton("Bonnie"); + bonnie->show(); + + QPushButton *clyde = new QPushButton("Clyde"); + clyde->show(); + + QPropertyAnimation *anim1 = new QPropertyAnimation(bonnie, "geometry"); + // Set up anim1 + + QPropertyAnimation *anim2 = new QPropertyAnimation(clyde, "geometry"); + // Set up anim2 + + QParallelAnimationGroup *group = new QParallelAnimationGroup; + group->addAnimation(anim1); + group->addAnimation(anim2); + + group->start(); + \endcode + + A parallel group plays more than one animation at the same time. + Calling its \l{QAbstractAnimation::}{start()} function will start + all animations it governs. + + \code + QPushButton button("Animated Button"); + button.show(); + + QPropertyAnimation anim1(&button, "geometry"); + anim1.setDuration(3000); + anim1.setStartValue(QRect(0, 0, 100, 30)); + anim1.setEndValue(QRect(500, 500, 100, 30)); + + QPropertyAnimation anim2(&button, "geometry"); + anim2.setDuration(3000); + anim2.setStartValue(QRect(500, 500, 100, 30)); + anim2.setEndValue(QRect(1000, 500, 100, 30)); + + QSequentialAnimationGroup group; + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + + group.start(); + \endcode + + As you no doubt have guessed, QSequentialAnimationGroup plays + its animations in sequence. It starts the next animation in + the list after the previous is finished. + + Since an animation group is an animation itself, you can add + it to another group. This way, you can build a tree structure + of animations which specifies when the animations are played + in relation to each other. + + \section1 Animations and States + + When using a \l{The State Machine Framework}{state machine}, we + have a special state, QAnimationState, that will play one or more + animations. + + The QState::addAnimatedTransition() convenience function lets you + associate an animation to a state transition. The function will + create the QAnimationState for you, and insert it into the state + machine. We also have the possibility to associate properties with + the states rather than setting the start and end values ourselves. + Below is a complete code example that animates the geometry of a + QPushButton. + + \code + QPushButton *button = new QPushButton("Animated Button"); + button->show(); + + QStateMachine *machine = new QStateMachine; + + QState *state1 = new QState(machine->rootState()); + state1->setPropertyOnEntry(button, "geometry", + QRect(0, 0, 100, 30)); + machine->setInitialState(state1); + + QState *state2 = new QState(machine->rootState()); + state2->setPropertyOnEntry(button, "geometry", + QRect(250, 250, 100, 30)); + + state1->addAnimatedTransition(button, SIGNAL(clicked()), state2, + new QPropertyAnimation(button, "geometry")); + state2->addAnimatedTransition(button, SIGNAL(clicked()), state1, + new QPropertyAnimation(button, "geometry")); + + machine->start(); + \endcode + + For a more comprehensive example of how to use the state machine + framework for animations, see the states example (it lives in the + \c{examples/animation/states} directory). +*/ + diff --git a/doc/src/diagrams/animations-architecture.svg b/doc/src/diagrams/animations-architecture.svg new file mode 100644 index 0000000..0246510 --- /dev/null +++ b/doc/src/diagrams/animations-architecture.svg @@ -0,0 +1,351 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + QAbstractAnimation + + QVariantAnimation + + QAnimationGroup + + + + QPropertyAnimation + + + QSequentialAnimationGroup + + QParallelAnimationGroup + + + + diff --git a/doc/src/diagrams/programs/easingcurve/easingcurve.pro b/doc/src/diagrams/programs/easingcurve/easingcurve.pro new file mode 100644 index 0000000..0b80127 --- /dev/null +++ b/doc/src/diagrams/programs/easingcurve/easingcurve.pro @@ -0,0 +1,13 @@ +###################################################################### +# Automatically generated by qmake (2.01a) fr 13. feb 13:26:38 2009 +###################################################################### + +TEMPLATE = app +TARGET = +DEPENDPATH += . +INCLUDEPATH += . + +# Input +SOURCES += main.cpp + +CONFIG += console \ No newline at end of file diff --git a/doc/src/diagrams/programs/easingcurve/main.cpp b/doc/src/diagrams/programs/easingcurve/main.cpp new file mode 100644 index 0000000..98e9d37 --- /dev/null +++ b/doc/src/diagrams/programs/easingcurve/main.cpp @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the $MODULE$ of the Qt Toolkit. +** +** $TROLLTECH_DUAL_LICENSE$ +** +****************************************************************************/ + +#include + +void createCurveIcons(); + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + createCurveIcons(); + return app.exit(); +} + +void createCurveIcons() +{ + QDir dir(QDir::current()); + if (dir.dirName() == QLatin1String("debug") || dir.dirName() == QLatin1String("release")) { + dir.cdUp(); + } + dir.cdUp(); + dir.cdUp(); + dir.cdUp(); + QSize iconSize(128, 128); + QPixmap pix(iconSize); + QPainter painter(&pix); + QLinearGradient gradient(0,0, 0, iconSize.height()); + gradient.setColorAt(0.0, QColor(240, 240, 240)); + gradient.setColorAt(1.0, QColor(224, 224, 224)); + QBrush brush(gradient); + const QMetaObject &mo = QEasingCurve::staticMetaObject; + QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type")); + QFont oldFont = painter.font(); + // Skip QEasingCurve::Custom + QString output(QString::fromAscii("%1/images").arg(dir.absolutePath())); + printf("Generating images to %s\n", qPrintable(output)); + for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) { + painter.setFont(oldFont); + QString name(QLatin1String(metaEnum.key(i))); + painter.fillRect(QRect(QPoint(0, 0), iconSize), brush); + QEasingCurve curve((QEasingCurve::Type)i); + painter.setPen(QColor(0, 0, 255, 64)); + qreal xAxis = iconSize.height()/1.5; + qreal yAxis = iconSize.width()/3; + painter.drawLine(0, xAxis, iconSize.width(), xAxis); // hor + painter.drawLine(yAxis, 0, yAxis, iconSize.height()); // ver + + qreal curveScale = iconSize.height()/2; + + painter.drawLine(yAxis - 2, xAxis - curveScale, yAxis + 2, xAxis - curveScale); // hor + painter.drawLine(yAxis + curveScale, xAxis + 2, yAxis + curveScale, xAxis - 2); // ver + painter.drawText(yAxis + curveScale - 8, xAxis - curveScale - 4, QLatin1String("(1,1)")); + + painter.drawText(yAxis + 42, xAxis + 10, QLatin1String("progress")); + painter.drawText(15, xAxis - curveScale - 10, QLatin1String("ease")); + + painter.setPen(QPen(Qt::red, 1, Qt::DotLine)); + painter.drawLine(yAxis, xAxis - curveScale, yAxis + curveScale, xAxis - curveScale); // hor + painter.drawLine(yAxis + curveScale, xAxis, yAxis + curveScale, xAxis - curveScale); // ver + + QPoint currentPos(yAxis, xAxis); + + painter.setPen(Qt::black); + QFont font = oldFont; + font.setPixelSize(oldFont.pixelSize() + 15); + painter.setFont(font); + painter.drawText(0, iconSize.height() - 20, iconSize.width(), 20, Qt::AlignHCenter, name); + + for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { + QPoint to; + to.setX(yAxis + curveScale * t); + to.setY(xAxis - curveScale * curve.valueForProgress(t)); + painter.drawLine(currentPos, to); + currentPos = to; + } + QString fileName(QString::fromAscii("qeasingcurve-%1.png").arg(name.toLower())); + printf("%s\n", qPrintable(fileName)); + pix.save(QString::fromAscii("%1/%2").arg(output).arg(fileName), "PNG"); + } +} + + diff --git a/doc/src/examples-overview.qdoc b/doc/src/examples-overview.qdoc index 549574d..92ccd4e 100644 --- a/doc/src/examples-overview.qdoc +++ b/doc/src/examples-overview.qdoc @@ -319,6 +319,14 @@ from displaying Web pages within a Qt user interface to an implementation of a basic function Web browser. + \section1 \l{Qt Examples#State Machine}{State Machine} + + Qt provides a powerful hierchical finite state machine through the Qt State + Machine classes. + + These examples demonstrate the fundamental aspects of implementing + Statecharts with Qt. + \section1 \l{Qt Examples#Qt for Embedded Linux}{Qt for Embedded Linux} \l{Qt Examples#Qt for Embedded Linux}{\inlineimage qt-embedded-examples.png diff --git a/doc/src/examples.qdoc b/doc/src/examples.qdoc index 29c6c0b..c55d29f 100644 --- a/doc/src/examples.qdoc +++ b/doc/src/examples.qdoc @@ -86,6 +86,12 @@ \o \l{activeqt/webbrowser}{Web Browser}\raisedaster \o \l{activeqt/wrapper}{Wrapper}\raisedaster \endlist + + \section1 Animation + + \list + \o \l{animation/stickman}{Stick man}\raisedaster + \endlist \section1 Concurrent Programming @@ -308,6 +314,17 @@ \o \l{sql/sqlwidgetmapper}{SQL Widget Mapper}\raisedaster \endlist + \section1 State Machine + + \list + \o \l{statemachine/eventtransitions}{Event Transitions}\raisedaster + \o \l{statemachine/factorial}{Factorial States}\raisedaster + \o \l{statemachine/pingpong}{Ping Pong States}\raisedaster + \o \l{statemachine/trafficlight}{Traffic Light}\raisedaster + \o \l{statemachine/twowaybutton}{Two-way Button}\raisedaster + \o \l{statemachine/tankgame}{Tank Game}\raisedaster + \endlist + \section1 Threads \list diff --git a/doc/src/examples/eventtransitions.qdoc b/doc/src/examples/eventtransitions.qdoc new file mode 100644 index 0000000..3b956bb --- /dev/null +++ b/doc/src/examples/eventtransitions.qdoc @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example statemachine/eventtransitions + \title Event Transitions Example + + The Event Transitions example shows how to use event transitions, a + feature of \l{The State Machine Framework}. + + \snippet examples/statemachine/eventtransitions/main.cpp 0 + + The \c Window class's constructors begins by creating a button. + + \snippet examples/statemachine/eventtransitions/main.cpp 1 + + Two states, \c s1 and \c s2, are created; upon entry they will assign + "Outside" and "Inside" to the button's text, respectively. + + \snippet examples/statemachine/eventtransitions/main.cpp 2 + + When the button receives an event of type QEvent::Enter and the state + machine is in state \c s1, the machine will transition to state \c s2. + + \snippet examples/statemachine/eventtransitions/main.cpp 3 + + When the button receives an event of type QEvent::Leave and the state + machine is in state \c s2, the machine will transition back to state \c + s1. + + \snippet examples/statemachine/eventtransitions/main.cpp 4 + + Next, the state \c s3 is created. \c s3 will be entered when the button + receives an event of type QEvent::MouseButtonPress and the state machine + is in state \c s2. When the button receives an event of type + QEvent::MouseButtonRelease and the state machine is in state \c s3, the + machine will transition back to state \c s2. + + \snippet examples/statemachine/eventtransitions/main.cpp 5 + + Finally, the states are added to the machine as top-level states, the + initial state is set to be \c s1 ("Outside"), and the machine is started. + + \snippet examples/statemachine/eventtransitions/main.cpp 6 + + The main() function constructs a Window object and shows it. + +*/ diff --git a/doc/src/examples/factorial.qdoc b/doc/src/examples/factorial.qdoc new file mode 100644 index 0000000..2a72e0a --- /dev/null +++ b/doc/src/examples/factorial.qdoc @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example statemachine/factorial + \title Factorial States Example + + The Factorial States example shows how to use \l{The State Machine + Framework} to calculate the factorial of an integer. + + The statechart for calculating the factorial looks as follows: + + \img factorial-example.png + \omit + \caption This is a caption + \endomit + + In other words, the state machine calculates the factorial of 6 and prints + the result. + + \snippet examples/statemachine/factorial/main.cpp 0 + + The Factorial class is used to hold the data of the computation, \c x and + \c fac. It also provides a signal that's emitted whenever the value of \c + x changes. + + \snippet examples/statemachine/factorial/main.cpp 1 + + The FactorialLoopTransition class implements the guard (\c x > 1) and + calculations (\c fac = \c x * \c fac; \c x = \c x - 1) of the factorial + loop. + + \snippet examples/statemachine/factorial/main.cpp 2 + + The FactorialDoneTransition class implements the guard (\c x <= 1) that + terminates the factorial computation. It also prints the final result to + standard output. + + \snippet examples/statemachine/factorial/main.cpp 3 + + The application's main() function first creates the application object, a + Factorial object and a state machine. + + \snippet examples/statemachine/factorial/main.cpp 4 + + The \c compute state is created, and the initial values of \c x and \c fac + are defined. A FactorialLoopTransition object is created and added to the + state. + + \snippet examples/statemachine/factorial/main.cpp 5 + + A final state, \c done, is created, and a FactorialDoneTransition object + is created with \c done as its target state. The transition is then added + to the \c compute state. + + \snippet examples/statemachine/factorial/main.cpp 6 + + The machine's initial state is set to be the \c compute state. We connect + the QStateMachine::finished() signal to the QCoreApplication::quit() slot, + so the application will quit when the state machine's work is + done. Finally, the state machine is started, and the application's event + loop is entered. + + */ diff --git a/doc/src/examples/pingpong.qdoc b/doc/src/examples/pingpong.qdoc new file mode 100644 index 0000000..040e429 --- /dev/null +++ b/doc/src/examples/pingpong.qdoc @@ -0,0 +1,107 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example statemachine/pingpong + \title Ping Pong States Example + + The Ping Pong States example shows how to use parallel states together + with custom events and transitions in \l{The State Machine Framework}. + + This example implements a statechart where two states communicate by + posting events to the state machine. The state chart looks as follows: + + \img pingpong-example.png + \omit + \caption This is a caption + \endomit + + The \c pinger and \c ponger states are parallel states, i.e. they are + entered simultaneously and will take transitions independently of + eachother. + + The \c pinger state will post the first \c ping event upon entry; the \c + ponger state will respond by posting a \c pong event; this will cause the + \c pinger state to post a new \c ping event; and so on. + + \snippet examples/statemachine/pingpong/main.cpp 0 + + Two custom events are defined, \c PingEvent and \c PongEvent. + + \snippet examples/statemachine/pingpong/main.cpp 1 + + The \c Pinger class defines a state that posts a \c PingEvent to the state + machine when the state is entered. + + \snippet examples/statemachine/pingpong/main.cpp 2 + + The \c PingTransition class defines a transition that is triggered by + events of type \c PingEvent, and that posts a \c PongEvent (with a delay + of 500 milliseconds) to the state machine when the transition is + triggered. + + \snippet examples/statemachine/pingpong/main.cpp 3 + + The \c PongTransition class defines a transition that is triggered by + events of type \c PongEvent, and that posts a \c PingEvent (with a delay + of 500 milliseconds) to the state machine when the transition is + triggered. + + \snippet examples/statemachine/pingpong/main.cpp 4 + + The main() function begins by creating a state machine and a parallel + state group. + + \snippet examples/statemachine/pingpong/main.cpp 5 + + Next, the \c pinger and \c ponger states are created, with the parallel + state group as their parent state. Note that the transitions are \e + targetless. When such a transition is triggered, the source state won't be + exited and re-entered; only the transition's onTransition() function will + be called, and the state machine's configuration will remain the same, + which is precisely what we want in this case. + + \snippet examples/statemachine/pingpong/main.cpp 6 + + Finally, the group is added to the state machine, the machine is started, + and the application event loop is entered. + + */ diff --git a/doc/src/examples/stickman.qdoc b/doc/src/examples/stickman.qdoc new file mode 100644 index 0000000..49f4953 --- /dev/null +++ b/doc/src/examples/stickman.qdoc @@ -0,0 +1,115 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example animation/stickman + \title Stickman Example + + The Stickman example shows how to animate transitions in a state machine to implement key frame + animations. + + \image stickman-example.png + + In this example, we will write a small application which animates the joints in a skeleton and + projects a stickman figure on top. The stickman can be either "alive" or "dead", and when in the + "alive" state, he can be performing different actions defined by key frame animations. + + Animations are implemented as composite states. Each child state of the animation state + represents a frame in the animation by setting the position of each joint in the stickman's + skeleton to the positions defined for the particular frame. The frames are then bound together + with animated transitions that trigger on the source state's polished() signal. Thus, the + machine will enter the state representing the next frame in the animation immediately after it + has finished animating into the previous frame. + + \image stickman-example1.png + + The states for an animation is constructed by reading a custom animation file format and + creating states that assign values to the the "position" properties of each of the nodes in the + skeleton graph. + + \snippet examples/animation/stickman/lifecycle.cpp 1 + + The states are then bound together with signal transitions that listen to the polished() signal. + + \snippet examples/animation/stickman/lifecycle.cpp 2 + + The last frame state is given a transition to the first one, so that the animation will loop + until it is interrupted when a transition out from the animation state is taken. To get smooth + animations between the different key frames, we set a default animation on the state machine. + This is a parallel animation group which contains animations for all the "position" properties + and will be selected by default when taking any transition that leads into a state that assigns + values to these properties. + + \snippet examples/animation/stickman/lifecycle.cpp 3 + + Several such animation states are constructed, and are placed together as children of a top + level "alive" state which represents the stickman life cycle. Transitions go from the parent + state to the child state to ensure that each of the child states inherit them. + + \image stickman-example2.png + + This saves us the effort of connect every state to every state with identical transitions. The + state machine makes sure that transitions between the key frame animations are also smooth by + applying the default animation when interrupting one and starting another. + + Finally, there is a transition out from the "alive" state and into the "dead" state. This is + a custom transition type called LightningSrikesTransition which samples every second and + triggers at random (one out of fifty times on average.) + + \snippet examples/animation/stickman/lifecycle.cpp 4 + + When it triggers, the machine will first enter a "lightningBlink" state which uses a timer to + pause for a brief period of time while the background color of the scene is white. This gives us + a flash effect when the lightning strikes. + + \snippet examples/animation/stickman/lifecycle.cpp 5 + + We start and stop a QTimer object when entering and exiting the state. Then we transition into + the "dead" state when the timer times out. + + \snippet examples/animation/stickman/lifecycle.cpp 0 + + When the machine is in the "dead" state, it will be unresponsive. This is because the "dead" + state has no transitions leading out. + + \image stickman-example3.png + +*/ diff --git a/doc/src/examples/tankgame.qdoc b/doc/src/examples/tankgame.qdoc new file mode 100644 index 0000000..ab3e0f4 --- /dev/null +++ b/doc/src/examples/tankgame.qdoc @@ -0,0 +1,117 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example statemachine/tankgame + \title Tank Game Example + + The Tank Game example is part of the in \l{The State Machine Framework}. It shows how to use + parallel states to implement artificial intelligence controllers that run in parallel, and error + states to handle run-time errors in parts of the state graph created by external plugins. + + \image tankgame-example.png + + In this example we write a simple game. The application runs a state machine with two main + states: A "stopped" state and a "running" state. The user can load plugins from the disk by + selecting the "Add tank" menu item. + + When the "Add tank" menu item is selected, the "plugins" subdirectory in the example's + directory is searched for compatible plugins. If any are found, they will be listed in a + dialog box created using QInputDialog::getItem(). + + \snippet examples/statemachine/tankgame/mainwindow.cpp 1 + + If the user selects a plugin, the application will construct a TankItem object, which inherits + from QGraphicsItem and QObject, and which implements an agreed-upon interface using the + meta-object mechanism. + + \snippet examples/statemachine/tankgame/tankitem.h 0 + + The tank item will be passed to the plugin's create() function. This will in turn return a + QState object which is expected to implement an artificial intelligence which controls the + tank and attempts to destroy other tanks it detects. + + \snippet examples/statemachine/tankgame/mainwindow.cpp 2 + + Each returned QState object becomes a descendant of a \c region in the "running" state, which is + defined as a parallel state. This means that entering the "running" state will cause each of the + plugged-in QState objects to be entered simultaneously, allowing the tanks to run independently + of each other. + + \snippet examples/statemachine/tankgame/mainwindow.cpp 0 + + The maximum number of tanks on the map is four, and when this number is reached, the + "Add tank" menu item should be disabled. This is implemented by giving the "stopped" state two + children which define whether the map is full or not. + + \snippet examples/statemachine/tankgame/mainwindow.cpp 5 + + To make sure that we go into the correct child state when returning from the "running" state + (if the "Stop game" menu item is selected while the game is running) we also give the "stopped" + state a history state which we make the initial state of "stopped" state. + + \snippet examples/statemachine/tankgame/mainwindow.cpp 3 + + Since part of the state graph is defined by external plugins, we have no way of controlling + whether they contain errors. By default, run-time errors are handled in the state machine by + entering a top level state which prints out an error message and never exits. If we were to + use this default behavior, a run-time error in any of the plugins would cause the "running" + state to exit, and thus all the other tanks to stop running as well. A better solution would + be if the broken plugin was disabled and the rest of the tanks allowed to continue as before. + + This is done by setting the error state of the plugin's top-most state to a special error state + defined specifically for the plugin in question. + + \snippet examples/statemachine/tankgame/mainwindow.cpp 4 + + If a run-time error occurs in \c pluginState or any of its descendants, the state machine will + search the hierarchy of ancestors until it finds a state whose error state is different from + \c null. (Note that if we are worried that a plugin could inadvertedly be overriding our + error state, we could search the descendants of \c pluginState and verify that their error + states are set to \c null before accepting the plugin.) + + The specialized \c errorState sets the "enabled" property of the tank item in question to false, + causing it to be painted with a red cross over it to indicate that it is no longer running. + Since the error state is a child of the same region in the parallel "running" state as + \c pluginState, it will not exit the "running" state, and the other tanks will continue running + without disruption. + +*/ diff --git a/doc/src/examples/trafficlight.qdoc b/doc/src/examples/trafficlight.qdoc new file mode 100644 index 0000000..ae62127 --- /dev/null +++ b/doc/src/examples/trafficlight.qdoc @@ -0,0 +1,99 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example statemachine/trafficlight + \title Traffic Light Example + + The Traffic Light example shows how to use \l{The State Machine Framework} + to implement the control flow of a traffic light. + + \image trafficlight-example.png + + In this example we write a TrafficLightWidget class. The traffic light has + three lights: Red, yellow and green. The traffic light transitions from + one light to another (red to yellow to green to yellow to red again) at + certain intervals. + + \snippet examples/statemachine/trafficlight/main.cpp 0 + + The LightWidget class represents a single light of the traffic light. It + provides an \c on property and two slots, turnOn() and turnOff(), to turn + the light on and off, respectively. The widget paints itself in the color + that's passed to the constructor. + + \snippet examples/statemachine/trafficlight/main.cpp 1 + + The TrafficLightWidget class represents the visual part of the traffic + light; it's a widget that contains three lights arranged vertically, and + provides accessor functions for these. + + \snippet examples/statemachine/trafficlight/main.cpp 2 + + The createLightState() function creates a state that turns a light on when + the state is entered, and off when the state is exited. The state uses a + timer, and as we shall see the timeout is used to transition from one + LightState to another. Here is the statechart for the light state: + + \img trafficlight-example1.png + \omit + \caption This is a caption + \endomit + + \snippet examples/statemachine/trafficlight/main.cpp 3 + + The TrafficLight class combines the TrafficLightWidget with a state + machine. The state graph has four states: red-to-yellow, yellow-to-green, + green-to-yellow and yellow-to-red. The initial state is red-to-yellow; + when the state's timer times out, the state machine transitions to + yellow-to-green. The same process repeats through the other states. + This is what the statechart looks like: + + \img trafficlight-example2.png + \omit + \caption This is a caption + \endomit + + \snippet examples/statemachine/trafficlight/main.cpp 4 + + The main() function constructs a TrafficLight and shows it. + +*/ diff --git a/doc/src/examples/twowaybutton.qdoc b/doc/src/examples/twowaybutton.qdoc new file mode 100644 index 0000000..87de2e8 --- /dev/null +++ b/doc/src/examples/twowaybutton.qdoc @@ -0,0 +1,82 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \example statemachine/twowaybutton + \title Two-way Button Example + + The Two-way button example shows how to use \l{The State Machine + Framework} to implement a simple state machine that toggles the current + state when a button is clicked. + + \snippet examples/statemachine/twowaybutton/main.cpp 0 + + The application's main() function begins by constructing the application + object, a button and a state machine. + + \snippet examples/statemachine/twowaybutton/main.cpp 1 + + The state machine has two states; \c on and \c off. When either state is + entered, the text of the button will be set accordingly. + + \snippet examples/statemachine/twowaybutton/main.cpp 2 + + When the state machine is in the \c off state and the button is clicked, + it will transition to the \c on state; when the state machine is in the \c + on state and the button is clicked, it will transition to the \c off + state. + + \snippet examples/statemachine/twowaybutton/main.cpp 3 + + The states are added to the state machine; they become top-level (sibling) + states. + + \snippet examples/statemachine/twowaybutton/main.cpp 4 + + The initial state is \c off; this is the state the state machine will + immediately transition to once the state machine is started. + + \snippet examples/statemachine/twowaybutton/main.cpp 5 + + Finally, the button is resized and made visible, and the application event + loop is entered. + +*/ diff --git a/doc/src/external-resources.qdoc b/doc/src/external-resources.qdoc index f48c3d7..3bfb5af 100644 --- a/doc/src/external-resources.qdoc +++ b/doc/src/external-resources.qdoc @@ -334,6 +334,16 @@ */ /*! + \externalpage http://www.w3.org/TR/scxml/ + \title State Chart XML: State Machine Notation for Control Abstraction +*/ + +/*! + \externalpage http://www.wisdom.weizmann.ac.il/~dharel/SCANNED.PAPERS/Statecharts.pdf + \title Statecharts: A visual formalism for complex systems +*/ + +/*! \externalpage http://www.gnu.org/licenses/gpl.html \title GNU General Public License */ diff --git a/doc/src/groups.qdoc b/doc/src/groups.qdoc index c9cedc4..3c4da53 100644 --- a/doc/src/groups.qdoc +++ b/doc/src/groups.qdoc @@ -69,6 +69,18 @@ */ /*! + \group animation + \ingroup groups + + \title Animation Framework + \brief Classes for animations, states and transitions. + + These classes provide a framework for creating both simple and complex + animations. \l{The Animation Framework} also provides states and animated + transitions, making it easy to create animated stateful forms. +*/ + +/*! \group abstractwidgets \title Abstract Widget Classes \ingroup groups @@ -597,3 +609,14 @@ These classes are relevant to developers who are working with Qt Script's debugging features. */ + +/*! + \group statemachine + \ingroup groups + + \title State Machine Classes + \brief Classes for constructing and executing state graphs. + + These classes are provided by \l{The State Machine Framework} for creating + event-driven state machines. +*/ diff --git a/doc/src/images/animations-architecture.png b/doc/src/images/animations-architecture.png new file mode 100644 index 0000000..9b581af Binary files /dev/null and b/doc/src/images/animations-architecture.png differ diff --git a/doc/src/images/factorial-example.png b/doc/src/images/factorial-example.png new file mode 100644 index 0000000..8fb1cc6 Binary files /dev/null and b/doc/src/images/factorial-example.png differ diff --git a/doc/src/images/pingpong-example.png b/doc/src/images/pingpong-example.png new file mode 100644 index 0000000..af707e4 Binary files /dev/null and b/doc/src/images/pingpong-example.png differ diff --git a/doc/src/images/qeasingcurve-cosinecurve.png b/doc/src/images/qeasingcurve-cosinecurve.png new file mode 100644 index 0000000..b27e763 Binary files /dev/null and b/doc/src/images/qeasingcurve-cosinecurve.png differ diff --git a/doc/src/images/qeasingcurve-inback.png b/doc/src/images/qeasingcurve-inback.png new file mode 100644 index 0000000..8506c0f Binary files /dev/null and b/doc/src/images/qeasingcurve-inback.png differ diff --git a/doc/src/images/qeasingcurve-inbounce.png b/doc/src/images/qeasingcurve-inbounce.png new file mode 100644 index 0000000..275b38c Binary files /dev/null and b/doc/src/images/qeasingcurve-inbounce.png differ diff --git a/doc/src/images/qeasingcurve-incirc.png b/doc/src/images/qeasingcurve-incirc.png new file mode 100644 index 0000000..b985e9c Binary files /dev/null and b/doc/src/images/qeasingcurve-incirc.png differ diff --git a/doc/src/images/qeasingcurve-incubic.png b/doc/src/images/qeasingcurve-incubic.png new file mode 100644 index 0000000..e417ee1 Binary files /dev/null and b/doc/src/images/qeasingcurve-incubic.png differ diff --git a/doc/src/images/qeasingcurve-incurve.png b/doc/src/images/qeasingcurve-incurve.png new file mode 100644 index 0000000..d9a9340 Binary files /dev/null and b/doc/src/images/qeasingcurve-incurve.png differ diff --git a/doc/src/images/qeasingcurve-inelastic.png b/doc/src/images/qeasingcurve-inelastic.png new file mode 100644 index 0000000..b242fd3 Binary files /dev/null and b/doc/src/images/qeasingcurve-inelastic.png differ diff --git a/doc/src/images/qeasingcurve-inexpo.png b/doc/src/images/qeasingcurve-inexpo.png new file mode 100644 index 0000000..f06316c Binary files /dev/null and b/doc/src/images/qeasingcurve-inexpo.png differ diff --git a/doc/src/images/qeasingcurve-inoutback.png b/doc/src/images/qeasingcurve-inoutback.png new file mode 100644 index 0000000..9fd1446 Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutback.png differ diff --git a/doc/src/images/qeasingcurve-inoutbounce.png b/doc/src/images/qeasingcurve-inoutbounce.png new file mode 100644 index 0000000..fb65f31 Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutbounce.png differ diff --git a/doc/src/images/qeasingcurve-inoutcirc.png b/doc/src/images/qeasingcurve-inoutcirc.png new file mode 100644 index 0000000..123cc54 Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutcirc.png differ diff --git a/doc/src/images/qeasingcurve-inoutcubic.png b/doc/src/images/qeasingcurve-inoutcubic.png new file mode 100644 index 0000000..b07695c Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutcubic.png differ diff --git a/doc/src/images/qeasingcurve-inoutelastic.png b/doc/src/images/qeasingcurve-inoutelastic.png new file mode 100644 index 0000000..65851e1 Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutelastic.png differ diff --git a/doc/src/images/qeasingcurve-inoutexpo.png b/doc/src/images/qeasingcurve-inoutexpo.png new file mode 100644 index 0000000..7cbfb13 Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutexpo.png differ diff --git a/doc/src/images/qeasingcurve-inoutquad.png b/doc/src/images/qeasingcurve-inoutquad.png new file mode 100644 index 0000000..c5eed06 Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutquad.png differ diff --git a/doc/src/images/qeasingcurve-inoutquart.png b/doc/src/images/qeasingcurve-inoutquart.png new file mode 100644 index 0000000..3b66c0d Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutquart.png differ diff --git a/doc/src/images/qeasingcurve-inoutquint.png b/doc/src/images/qeasingcurve-inoutquint.png new file mode 100644 index 0000000..c74efe9 Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutquint.png differ diff --git a/doc/src/images/qeasingcurve-inoutsine.png b/doc/src/images/qeasingcurve-inoutsine.png new file mode 100644 index 0000000..5964f31 Binary files /dev/null and b/doc/src/images/qeasingcurve-inoutsine.png differ diff --git a/doc/src/images/qeasingcurve-inquad.png b/doc/src/images/qeasingcurve-inquad.png new file mode 100644 index 0000000..3373310 Binary files /dev/null and b/doc/src/images/qeasingcurve-inquad.png differ diff --git a/doc/src/images/qeasingcurve-inquart.png b/doc/src/images/qeasingcurve-inquart.png new file mode 100644 index 0000000..28086d8 Binary files /dev/null and b/doc/src/images/qeasingcurve-inquart.png differ diff --git a/doc/src/images/qeasingcurve-inquint.png b/doc/src/images/qeasingcurve-inquint.png new file mode 100644 index 0000000..330aa85 Binary files /dev/null and b/doc/src/images/qeasingcurve-inquint.png differ diff --git a/doc/src/images/qeasingcurve-insine.png b/doc/src/images/qeasingcurve-insine.png new file mode 100644 index 0000000..63d9238 Binary files /dev/null and b/doc/src/images/qeasingcurve-insine.png differ diff --git a/doc/src/images/qeasingcurve-linear.png b/doc/src/images/qeasingcurve-linear.png new file mode 100644 index 0000000..2a05885 Binary files /dev/null and b/doc/src/images/qeasingcurve-linear.png differ diff --git a/doc/src/images/qeasingcurve-outback.png b/doc/src/images/qeasingcurve-outback.png new file mode 100644 index 0000000..7cb34c6 Binary files /dev/null and b/doc/src/images/qeasingcurve-outback.png differ diff --git a/doc/src/images/qeasingcurve-outbounce.png b/doc/src/images/qeasingcurve-outbounce.png new file mode 100644 index 0000000..932fc16 Binary files /dev/null and b/doc/src/images/qeasingcurve-outbounce.png differ diff --git a/doc/src/images/qeasingcurve-outcirc.png b/doc/src/images/qeasingcurve-outcirc.png new file mode 100644 index 0000000..a1a6cb6 Binary files /dev/null and b/doc/src/images/qeasingcurve-outcirc.png differ diff --git a/doc/src/images/qeasingcurve-outcubic.png b/doc/src/images/qeasingcurve-outcubic.png new file mode 100644 index 0000000..aa1d604 Binary files /dev/null and b/doc/src/images/qeasingcurve-outcubic.png differ diff --git a/doc/src/images/qeasingcurve-outcurve.png b/doc/src/images/qeasingcurve-outcurve.png new file mode 100644 index 0000000..a949ae4 Binary files /dev/null and b/doc/src/images/qeasingcurve-outcurve.png differ diff --git a/doc/src/images/qeasingcurve-outelastic.png b/doc/src/images/qeasingcurve-outelastic.png new file mode 100644 index 0000000..2a9ba39 Binary files /dev/null and b/doc/src/images/qeasingcurve-outelastic.png differ diff --git a/doc/src/images/qeasingcurve-outexpo.png b/doc/src/images/qeasingcurve-outexpo.png new file mode 100644 index 0000000..e771c2e Binary files /dev/null and b/doc/src/images/qeasingcurve-outexpo.png differ diff --git a/doc/src/images/qeasingcurve-outinback.png b/doc/src/images/qeasingcurve-outinback.png new file mode 100644 index 0000000..7523727 Binary files /dev/null and b/doc/src/images/qeasingcurve-outinback.png differ diff --git a/doc/src/images/qeasingcurve-outinbounce.png b/doc/src/images/qeasingcurve-outinbounce.png new file mode 100644 index 0000000..ab73d02 Binary files /dev/null and b/doc/src/images/qeasingcurve-outinbounce.png differ diff --git a/doc/src/images/qeasingcurve-outincirc.png b/doc/src/images/qeasingcurve-outincirc.png new file mode 100644 index 0000000..ec4b8d3 Binary files /dev/null and b/doc/src/images/qeasingcurve-outincirc.png differ diff --git a/doc/src/images/qeasingcurve-outincubic.png b/doc/src/images/qeasingcurve-outincubic.png new file mode 100644 index 0000000..8b8ae68 Binary files /dev/null and b/doc/src/images/qeasingcurve-outincubic.png differ diff --git a/doc/src/images/qeasingcurve-outinelastic.png b/doc/src/images/qeasingcurve-outinelastic.png new file mode 100644 index 0000000..89dde2c Binary files /dev/null and b/doc/src/images/qeasingcurve-outinelastic.png differ diff --git a/doc/src/images/qeasingcurve-outinexpo.png b/doc/src/images/qeasingcurve-outinexpo.png new file mode 100644 index 0000000..5909901 Binary files /dev/null and b/doc/src/images/qeasingcurve-outinexpo.png differ diff --git a/doc/src/images/qeasingcurve-outinquad.png b/doc/src/images/qeasingcurve-outinquad.png new file mode 100644 index 0000000..7ddefee Binary files /dev/null and b/doc/src/images/qeasingcurve-outinquad.png differ diff --git a/doc/src/images/qeasingcurve-outinquart.png b/doc/src/images/qeasingcurve-outinquart.png new file mode 100644 index 0000000..00ef597 Binary files /dev/null and b/doc/src/images/qeasingcurve-outinquart.png differ diff --git a/doc/src/images/qeasingcurve-outinquint.png b/doc/src/images/qeasingcurve-outinquint.png new file mode 100644 index 0000000..361bfaa4 Binary files /dev/null and b/doc/src/images/qeasingcurve-outinquint.png differ diff --git a/doc/src/images/qeasingcurve-outinsine.png b/doc/src/images/qeasingcurve-outinsine.png new file mode 100644 index 0000000..1737041 Binary files /dev/null and b/doc/src/images/qeasingcurve-outinsine.png differ diff --git a/doc/src/images/qeasingcurve-outquad.png b/doc/src/images/qeasingcurve-outquad.png new file mode 100644 index 0000000..6f27cbd Binary files /dev/null and b/doc/src/images/qeasingcurve-outquad.png differ diff --git a/doc/src/images/qeasingcurve-outquart.png b/doc/src/images/qeasingcurve-outquart.png new file mode 100644 index 0000000..d45a0b8 Binary files /dev/null and b/doc/src/images/qeasingcurve-outquart.png differ diff --git a/doc/src/images/qeasingcurve-outquint.png b/doc/src/images/qeasingcurve-outquint.png new file mode 100644 index 0000000..6e7df0e Binary files /dev/null and b/doc/src/images/qeasingcurve-outquint.png differ diff --git a/doc/src/images/qeasingcurve-outsine.png b/doc/src/images/qeasingcurve-outsine.png new file mode 100644 index 0000000..7546a0d Binary files /dev/null and b/doc/src/images/qeasingcurve-outsine.png differ diff --git a/doc/src/images/qeasingcurve-sinecurve.png b/doc/src/images/qeasingcurve-sinecurve.png new file mode 100644 index 0000000..ca67d44 Binary files /dev/null and b/doc/src/images/qeasingcurve-sinecurve.png differ diff --git a/doc/src/images/statemachine-button-history.png b/doc/src/images/statemachine-button-history.png new file mode 100644 index 0000000..7f51cae Binary files /dev/null and b/doc/src/images/statemachine-button-history.png differ diff --git a/doc/src/images/statemachine-button-nested.png b/doc/src/images/statemachine-button-nested.png new file mode 100644 index 0000000..762ac14 Binary files /dev/null and b/doc/src/images/statemachine-button-nested.png differ diff --git a/doc/src/images/statemachine-button.png b/doc/src/images/statemachine-button.png new file mode 100644 index 0000000..10102bd Binary files /dev/null and b/doc/src/images/statemachine-button.png differ diff --git a/doc/src/images/statemachine-customevents.png b/doc/src/images/statemachine-customevents.png new file mode 100644 index 0000000..62a4222 Binary files /dev/null and b/doc/src/images/statemachine-customevents.png differ diff --git a/doc/src/images/statemachine-customevents2.png b/doc/src/images/statemachine-customevents2.png new file mode 100644 index 0000000..57b37ef Binary files /dev/null and b/doc/src/images/statemachine-customevents2.png differ diff --git a/doc/src/images/statemachine-finished.png b/doc/src/images/statemachine-finished.png new file mode 100644 index 0000000..0ac081d Binary files /dev/null and b/doc/src/images/statemachine-finished.png differ diff --git a/doc/src/images/statemachine-nonparallel.png b/doc/src/images/statemachine-nonparallel.png new file mode 100644 index 0000000..f9850a7 Binary files /dev/null and b/doc/src/images/statemachine-nonparallel.png differ diff --git a/doc/src/images/statemachine-parallel.png b/doc/src/images/statemachine-parallel.png new file mode 100644 index 0000000..a65c297 Binary files /dev/null and b/doc/src/images/statemachine-parallel.png differ diff --git a/doc/src/images/stickman-example.png b/doc/src/images/stickman-example.png new file mode 100644 index 0000000..a40f37b Binary files /dev/null and b/doc/src/images/stickman-example.png differ diff --git a/doc/src/images/stickman-example1.png b/doc/src/images/stickman-example1.png new file mode 100644 index 0000000..1596a68 Binary files /dev/null and b/doc/src/images/stickman-example1.png differ diff --git a/doc/src/images/stickman-example2.png b/doc/src/images/stickman-example2.png new file mode 100644 index 0000000..980276a Binary files /dev/null and b/doc/src/images/stickman-example2.png differ diff --git a/doc/src/images/stickman-example3.png b/doc/src/images/stickman-example3.png new file mode 100644 index 0000000..3635ff7 Binary files /dev/null and b/doc/src/images/stickman-example3.png differ diff --git a/doc/src/images/tankgame-example.png b/doc/src/images/tankgame-example.png new file mode 100644 index 0000000..9e17e30 Binary files /dev/null and b/doc/src/images/tankgame-example.png differ diff --git a/doc/src/images/trafficlight-example.png b/doc/src/images/trafficlight-example.png new file mode 100644 index 0000000..3431542 Binary files /dev/null and b/doc/src/images/trafficlight-example.png differ diff --git a/doc/src/images/trafficlight-example1.png b/doc/src/images/trafficlight-example1.png new file mode 100644 index 0000000..ec8c7ff Binary files /dev/null and b/doc/src/images/trafficlight-example1.png differ diff --git a/doc/src/images/trafficlight-example2.png b/doc/src/images/trafficlight-example2.png new file mode 100644 index 0000000..a12e4db Binary files /dev/null and b/doc/src/images/trafficlight-example2.png differ diff --git a/doc/src/snippets/animation/sequential/icons.qrc b/doc/src/snippets/animation/sequential/icons.qrc new file mode 100644 index 0000000..d55f797 --- /dev/null +++ b/doc/src/snippets/animation/sequential/icons.qrc @@ -0,0 +1,6 @@ + + + icons/left.png + icons/right.png + + diff --git a/doc/src/snippets/animation/sequential/icons/left.png b/doc/src/snippets/animation/sequential/icons/left.png new file mode 100644 index 0000000..5dd8da0 Binary files /dev/null and b/doc/src/snippets/animation/sequential/icons/left.png differ diff --git a/doc/src/snippets/animation/sequential/icons/right.png b/doc/src/snippets/animation/sequential/icons/right.png new file mode 100644 index 0000000..ac61326 Binary files /dev/null and b/doc/src/snippets/animation/sequential/icons/right.png differ diff --git a/doc/src/snippets/animation/sequential/main.cpp b/doc/src/snippets/animation/sequential/main.cpp new file mode 100644 index 0000000..aff8f29 --- /dev/null +++ b/doc/src/snippets/animation/sequential/main.cpp @@ -0,0 +1,50 @@ +#include +#include +#include +#include +#include "tracer.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + + QWidget window; + window.resize(720, 96); + window.show(); + + QLabel *label1 = new QLabel(&window); + label1->setPixmap(QPixmap(":/icons/left.png")); + label1->move(16, 16); + label1->show(); + + QLabel *label2 = new QLabel(&window); + label2->setPixmap(QPixmap(":/icons/right.png")); + label2->move(320, 16); + label2->show(); + + QPropertyAnimation *anim1 = new QPropertyAnimation(label1, "pos"); + anim1->setDuration(2500); + anim1->setStartValue(QPoint(16, 16)); + anim1->setEndValue(QPoint(320, 16)); + + QPropertyAnimation *anim2 = new QPropertyAnimation(label2, "pos"); + anim2->setDuration(2500); + anim2->setStartValue(QPoint(320, 16)); + anim2->setEndValue(QPoint(640, 16)); + + QSequentialAnimationGroup group; + group.addAnimation(anim1); + group.addAnimation(anim2); + + Tracer tracer(&window); + + QObject::connect(anim1, SIGNAL(valueChanged(QVariant)), + &tracer, SLOT(recordValue(QVariant))); + QObject::connect(anim2, SIGNAL(valueChanged(QVariant)), + &tracer, SLOT(recordValue(QVariant))); + QObject::connect(anim1, SIGNAL(finished()), &tracer, SLOT(checkValue())); + QObject::connect(anim2, SIGNAL(finished()), &tracer, SLOT(checkValue())); + + group.start(); + return app.exec(); +} diff --git a/doc/src/snippets/animation/sequential/sequential.pro b/doc/src/snippets/animation/sequential/sequential.pro new file mode 100644 index 0000000..fcf017f --- /dev/null +++ b/doc/src/snippets/animation/sequential/sequential.pro @@ -0,0 +1,4 @@ +HEADERS = tracer.h +RESOURCES = icons.qrc +SOURCES = main.cpp \ + tracer.cpp diff --git a/doc/src/snippets/animation/sequential/tracer.cpp b/doc/src/snippets/animation/sequential/tracer.cpp new file mode 100644 index 0000000..49bd51e --- /dev/null +++ b/doc/src/snippets/animation/sequential/tracer.cpp @@ -0,0 +1,25 @@ +#include +#include +#include +#include "tracer.h" + +Tracer::Tracer(QObject *parent) + : QObject(parent) +{ +} + +void Tracer::checkValue() +{ + QAbstractAnimation *animation = static_cast(sender()); + if (time != animation->duration()) { + qDebug() << "Animation's last recorded time" << time; + qDebug() << "Expected" << animation->duration(); + } +} + +void Tracer::recordValue(const QVariant &value) +{ + QAbstractAnimation *animation = static_cast(sender()); + this->value = value; + time = animation->currentTime(); +} diff --git a/doc/src/snippets/animation/sequential/tracer.h b/doc/src/snippets/animation/sequential/tracer.h new file mode 100644 index 0000000..1adb018 --- /dev/null +++ b/doc/src/snippets/animation/sequential/tracer.h @@ -0,0 +1,23 @@ +#ifndef TRACER_H +#define TRACER_H + +#include +#include + +class Tracer : public QObject +{ + Q_OBJECT + +public: + Tracer(QObject *parent = 0); + +public slots: + void checkValue(); + void recordValue(const QVariant &value); + +private: + QVariant value; + int time; +}; + +#endif diff --git a/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp b/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp new file mode 100644 index 0000000..65358ea --- /dev/null +++ b/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp @@ -0,0 +1,4 @@ +//! [0] +qreal myEasingFunction(qreal progress); +//! [0] + diff --git a/doc/src/statemachine.qdoc b/doc/src/statemachine.qdoc new file mode 100644 index 0000000..5a89f4d --- /dev/null +++ b/doc/src/statemachine.qdoc @@ -0,0 +1,645 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the documentation of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \page statemachine-api.html + \title The State Machine Framework + \brief An overview of the State Machine framework for constructing and executing state graphs. + \ingroup architecture + + \tableofcontents + + The State Machine framework provides classes for creating and executing + state graphs. The concepts and notation are based on those from Harel's + \l{Statecharts: A visual formalism for complex systems}{Statecharts}, which + is also the basis of UML state diagrams. The semantics of state machine + execution are based on \l{State Chart XML: State Machine Notation for + Control Abstraction}{State Chart XML (SCXML)}. + + Statecharts provide a graphical way of modeling how a system reacts to + stimuli. This is done by defining the possible \e states that the system can + be in, and how the system can move from one state to another (\e transitions + between states). A key characteristic of event-driven systems (such as Qt + applications) is that behavior often depends not only on the last or current + event, but also the events that preceded it. With statecharts, this + information is easy to express. + + The State Machine framework provides an API and execution model that can be + used to effectively embed the elements and semantics of statecharts in Qt + applications. The framework integrates tightly with Qt's meta-object system; + for example, transitions between states can be triggered by signals, and + states can be configured to set properties and invoke methods on QObjects. + Qt's event system is used to drive the state machines. + + \section1 A Simple State Machine + + To demonstrate the core functionality of the State Machine API, let's look + at a small example: A state machine with three states, \c s1, \c s2 and \c + s3. The state machine is controlled by a single QPushButton; when the button + is clicked, the machine transitions to another state. Initially, the state + machine is in state \c s1. The statechart for this machine is as follows: + + \img statemachine-button.png + \omit + \caption This is a caption + \endomit + + The following snippet shows the code needed to create such a state machine. + First, we create the state machine and states: + + \code + QStateMachine machine; + QState *s1 = new QState(); + QState *s2 = new QState(); + QState *s3 = new QState(); + \endcode + + Then, we create the transitions by using the QState::addTransition() + function: + + \code + s1->addTransition(button, SIGNAL(clicked()), s2); + s2->addTransition(button, SIGNAL(clicked()), s3); + s3->addTransition(button, SIGNAL(clicked()), s1); + \endcode + + Next, we add the states to the machine and set the machine's initial state: + + \code + machine.addState(s1); + machine.addState(s2); + machine.addState(s3); + machine.setInitialState(s1); + \endcode + + Finally, we start the state machine: + + \code + machine.start(); + \endcode + + The state machine executes asynchronously, i.e. it becomes part of your + application's event loop. + + \section1 Doing Useful Work on State Entry and Exit + + The above state machine merely transitions from one state to another, it + doesn't perform any operations. The QState::assignProperty() function can be + used to have a state set a property of a QObject when the state is + entered. In the following snippet, the value that should be assigned to a + QLabel's text property is specified for each state: + + \code + s1->assignProperty(label, "text", "In state s1"); + s2->assignProperty(label, "text", "In state s2"); + s3->assignProperty(label, "text", "In state s3"); + \endcode + + When any of the states is entered, the label's text will be changed + accordingly. + + The QState::entered() signal is emitted when the state is entered, and the + QState::exited() signal is emitted when the state is exited. In the + following snippet, the button's showMaximized() slot will be called when + state \c s3 is entered, and the button's showMinimized() slot will be called + when \c s3 is exited: + + \code + QObject::connect(s3, SIGNAL(entered()), button, SLOT(showMaximized())); + QObject::connect(s3, SIGNAL(exited()), button, SLOT(showMinimized())); + \endcode + + Custom states can reimplement QAbstractState::onEntry() and + QAbstractState::onExit(). + + \section1 State Machines That Finish + + The state machine defined in the previous section never finishes. In order + for a state machine to be able to finish, it needs to have a top-level \e + final state (QFinalState object). When the state machine enters a top-level + final state, the machine will emit the QStateMachine::finished() signal and + halt. + + All you need to do to introduce a final state in the graph is create a + QFinalState object and use it as the target of one or more transitions. + + \section1 Sharing Transitions By Grouping States + + Assume we wanted the user to be able to quit the application at any time by + clicking a Quit button. In order to achieve this, we need to create a final + state and make it the target of a transition associated with the Quit + button's clicked() signal. We could add a transition from each of \c s1, \c + s2 and \c s3; however, this seems redundant, and one would also have to + remember to add such a transition from every new state that is added in the + future. + + We can achieve the same behavior (namely that clicking the Quit button quits + the state machine, regardless of which state the state machine is in) by + grouping states \c s1, \c s2 and \c s3. This is done by creating a new + top-level state and making the three original states children of the new + state. The following diagram shows the new state machine. + + \img statemachine-button-nested.png + \omit + \caption This is a caption + \endomit + + The three original states have been renamed \c s11, \c s12 and \c s13 to + reflect that they are now children of the new top-level state, \c s1. Child + states implicitly inherit the transitions of their parent state. This means + it is now sufficient to add a single transition from \c s1 to the final + state \c s2. New states added to \c s1 will also automatically inherit this + transition. + + All that's needed to group states is to specify the proper parent when the + state is created. You also need to specify which of the child states is the + initial one (i.e. which child state the state machine should enter when the + parent state is the target of a transition). + + \code + QState *s1 = new QState(); + QState *s11 = new QState(s1); + QState *s12 = new QState(s1); + QState *s13 = new QState(s1); + s1->setInitialState(s11); + machine.addState(s1); + \endcode + + \code + QFinalState *s2 = new QFinalState(); + s1->addTransition(quitButton, SIGNAL(clicked()), s2); + machine.addState(s2); + + QObject::connect(&machine, SIGNAL(finished()), QApplication::instance(), SLOT(quit())); + \endcode + + In this case we want the application to quit when the state machine is + finished, so the machine's finished() signal is connected to the + application's quit() slot. + + A child state can override an inherited transition. For example, the + following code adds a transition that effectively causes the Quit button to + be ignored when the state machine is in state \c s12. + + \code + s12>addTransition(quitButton, SIGNAL(clicked()), s12); + \endcode + + A transition can have any state as its target, i.e. the target state does + not have to be on the same level in the state hierarchy as the source state. + + \section1 Using History States to Save and Restore the Current State + + Imagine that we wanted to add an "interrupt" mechanism to the example + discussed in the previous section; the user should be able to click a button + to have the state machine perform some non-related task, after which the + state machine should resume whatever it was doing before (i.e. return to the + old state, which is one of \c s11, \c s12 and \c s13 in this case). + + Such behavior can easily be modeled using \e{history states}. A history + state (QHistoryState object) is a pseudo-state that represents the child + state that the parent state was in the last time the parent state was + exited. + + A history state is created as a child of the state for which we wish to + record the current child state; when the state machine detects the presence + of such a state at runtime, it automatically records the current (real) + child state when the parent state is exited. A transition to the history + state is in fact a transition to the child state that the state machine had + previously saved; the state machine automatically "forwards" the transition + to the real child state. + + The following diagram shows the state machine after the interrupt mechanism + has been added. + + \img statemachine-button-history.png + \omit + \caption This is a caption + \endomit + + The following code shows how it can be implemented; in this example we + simply display a message box when \c s3 is entered, then immediately return + to the previous child state of \c s1 via the history state. + + \code + QHistoryState *s1h = s1->addHistoryState(); + + QState *s3 = new QState(); + s3->assignProperty(label, "text", "In s3"); + QMessageBox mbox; + mbox.addButton(QMessageBox::Ok); + mbox.setText("Interrupted!"); + mbox.setIcon(QMessageBox::Information); + QObject::connect(s3, SIGNAL(entered()), &mbox, SLOT(exec())); + s3->addTransition(s1h); + machine.addState(s3); + + s1->addTransition(interruptButton, SIGNAL(clicked()), s3); + \endcode + + \section1 Using Parallel States to Avoid a Combinatorial Explosion of States + + Assume that you wanted to model a set of mutually exclusive properties of a + car in a single state machine. Let's say the properties we are interested in + are Clean vs Dirty, and Moving vs Not moving. It would take four mutually + exclusive states and eight transitions to be able to represent and freely + move between all possible combinations. + + \img statemachine-nonparallel.png + \omit + \caption This is a caption + \endomit + + If we added a third property (say, Red vs Blue), the total number of states + would double, to eight; and if we added a fourth property (say, Enclosed vs + Convertible), the total number of states would double again, to 16. + + Using parallel states, the total number of states and transitions grows + linearly as we add more properties, instead of exponentially. Furthermore, + states can be added to or removed from the parallel state without affecting + any of their sibling states. + + \img statemachine-parallel.png + \omit + \caption This is a caption + \endomit + + To create a parallel state group, pass QState::ParallelStates to the QState + constructor. + + \code + QState *s1 = new QState(QState::ParallelStates); + // s11 and s12 will be entered in parallel + QState *s11 = new QState(s1); + QState *s12 = new QState(s1); + \endcode + + When a parallel state group is entered, all its child states will be + simultaneously entered. Transitions within the individual child states + operate normally. However, any of the child states may take a transition + outside the parent state. When this happens, the parent state and all of its + child states are exited. + + \section1 Detecting that a Composite State has Finished + + A child state can be final (a QFinalState object); when a final child state + is entered, the parent state emits the QState::finished() signal. The + following diagram shows a composite state \c s1 which does some processing + before entering a final state: + + \img statemachine-finished.png + \omit + \caption This is a caption + \endomit + + When \c s1 's final state is entered, \c s1 will automatically emit + finished(). We use a signal transition to cause this event to trigger a + state change: + + \code + s1->addTransition(s1, SIGNAL(finished()), s2); + \endcode + + Using final states in composite states is useful when you want to hide the + internal details of a composite state; i.e. the only thing the outside world + should be able to do is enter the state, and get a notification when the + state has completed its work. This is a very powerful abstraction and + encapsulation mechanism when building complex (deeply nested) state + machines. (In the above example, you could of course create a transition + directly from \c s1 's \c done state rather than relying on \c s1 's + finished() signal, but with the consequence that implementation details of + \c s1 are exposed and depended on). + + For parallel state groups, the QState::finished() signal is emitted when \e + all the child states have entered final states. + + \section1 Events, Transitions and Guards + + A QStateMachine runs its own event loop. For signal transitions + (QSignalTransition objects), QStateMachine automatically posts a + QSignalEvent to itself when it intercepts the corresponding signal; + similarly, for QObject event transitions (QEventTransition objects) a + QWrappedEvent is posted. + + You can post your own events to the state machine using + QStateMachine::postEvent(). + + When posting a custom event to the state machine, you typically also have + one or more custom transitions that can be triggered from events of that + type. To create such a transition, you subclass QAbstractTransition and + reimplement QAbstractTransition::eventTest(), where you check if an event + matches your event type (and optionally other criteria, e.g. attributes of + the event object). + + Here we define our own custom event type, \c StringEvent, for posting + strings to the state machine: + + \code + struct StringEvent : public QEvent + { + StringEvent(const QString &val) + : QEvent(QEvent::Type(QEvent::User+1)), + value(val) {} + + QString value; + }; + \endcode + + Next, we define a transition that only triggers when the event's string + matches a particular string (a \e guarded transition): + + \code + class StringTransition : public QAbstractTransition + { + public: + StringTransition(const QString &value) + : m_value(value) {} + + protected: + virtual bool eventTest(QEvent *e) const + { + if (e->type() != QEvent::Type(QEvent::User+1)) // StringEvent + return false; + StringEvent *se = static_cast(e); + return (m_value == se->value); + } + + virtual void onTransition(QEvent *) {} + + private: + QString m_value; + }; + \endcode + + In the eventTest() reimplementation, we first check if the event type is the + desired one; if so, we cast the event to a StringEvent and perform the + string comparison. + + The following is a statechart that uses the custom event and transition: + + \img statemachine-customevents.png + \omit + \caption This is a caption + \endomit + + Here's what the implementation of the statechart looks like: + + \code + QStateMachine machine; + QState *s1 = new QState(); + QState *s2 = new QState(); + QFinalState *done = new QFinalState(); + + StringTransition *t1 = new StringTransition("Hello"); + t1->setTargetState(s2); + s1->addTransition(t1); + StringTransition *t2 = new StringTransition("world"); + t2->setTargetState(done); + s2->addTransition(t2); + + machine.addState(s1); + machine.addState(s2); + machine.addState(done); + machine.setInitialState(s1); + \endcode + + Once the machine is started, we can post events to it. + + \code + machine.postEvent(new StringEvent("Hello")); + machine.postEvent(new StringEvent("world")); + \endcode + + An event that is not handled by any relevant transition will be silently + consumed by the state machine. It can be useful to group states and provide + a default handling of such events; for example, as illustrated in the + following statechart: + + \img statemachine-customevents2.png + \omit + \caption This is a caption + \endomit + + For deeply nested statecharts, you can add such "fallback" transitions at + the level of granularity that's most appropriate. + + \section1 Using Restore Policy To Automatically Restore Properties + + In some state machines it can be useful to focus the attention on assigning properties in states, + not on restoring them when the state is no longer active. If you know that a property should + always be restored to its initial value when the machine enters a state that does not explicitly + give the property a value, you can set the global restore policy to + QStateMachine::RestoreProperties. + + \code + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + \endcode + + When this restore policy is set, the machine will automatically restore all properties. If it + enters a state where a given property is not set, it will first search the hierarchy of ancestors + to see if the property is defined there. If it is, the property will be restored to the value + defined by the closest ancestor. If not, it will be restored to its initial value (i.e. the + value of the property before any property assignments in states were executed.) + + Take the following code: + \code + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + + QState *s1 = new QState(); + s1->assignProperty(object, "fooBar", 1.0); + machine.addState(s1); + machine.setInitialState(s1); + + QState *s2 = new QState(); + machine.addState(s2); + \endcode + + Lets say the property \c fooBar is 0.0 when the machine starts. When the machine is in state + \c s1, the property will be 1.0, since the state explicitly assigns this value to it. When the + machine is in state \c s2, no value is explicitly defined for the property, so it will implicitly + be restored to 0.0. + + If we are using nested states, the parent defines a value for the property which is inherited by + all descendants that do not explicitly assign a value to the property. + \code + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + + QState *s1 = new QState(); + s1->assignProperty(object, "fooBar", 1.0); + machine.addState(s1); + machine.setInitialState(s1); + + QState *s2 = new QState(s1); + s2->assignProperty(object, "fooBar", 2.0); + s1->setInitialState(s2); + + QState *s3 = new QState(s1); + \endcode + + Here \c s1 has two children: \c s2 and \c s3. When \c s2 is entered, the property \c fooBar + will have the value 2.0, since this is explicitly defined for the state. When the machine is in + state \c s3, no value is defined for the state, but \c s1 defines the property to be 1.0, so this + is the value that will be assigned to \c fooBar. + + \section1 Animating Property Assignments + + The State Machine API connects with the Animation API in Qt to allow automatically animating + properties as they are assigned in states. + + Say we have the following code: + \code + QState *s1 = new QState(); + QState *s2 = new QState(); + + s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); + s2->assignProperty(button, "geometry", QRectF(0, 0, 100, 100)); + + s1->addTransition(button, SIGNAL(clicked()), s2); + \endcode + + Here we define two states of a user interface. In \c s1 the \c button is small, and in \c s2 + it is bigger. If we click the button to transition from \c s1 to \c s2, the geometry of the button + will be set immediately when a given state has been entered. If we want the transition to be + smooth, however, all we need to do is make a QPropertyAnimation and add this to the transition + object. + + \code + QState *s1 = new QState(); + QState *s2 = new QState(); + + s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); + s2->assignProperty(button, "geometry", QRectF(0, 0, 100, 100)); + + QSignalTransition *transition = s1->addTransition(button, SIGNAL(clicked()), s2); + transition->addAnimation(new QPropertyAnimation(button, "geometry")); + \endcode + + Adding an animation for the property in question means that the property assignment will no + longer take immediate effect when the state has been entered. Instead, the animation will start + playing when the state has been entered and smoothly animate the property assignment. Since we + do not set the start value or end value of the animation, these will be set implicitly. The + start value of the animation will be the property's current value when the animation starts, and + the end value will be set based on the property assignments defined for the state. + + If the global restore policy of the state machine is set to QStateMachine::RestoreProperties, + it is possible to also add animations for the property restorations. + + \section1 Detecting That All Properties Have Been Set In A State + + When animations are used to assign properties, a state no longer defines the exact values that a + property will have when the machine is in the given state. While the animation is running, the + property can potentially have any value, depending on the animation. + + In some cases, it can be useful to be able to detect when the property has actually been assigned + the value defined by a state. For this, we can use the state's polished() signal. + \code + QState *s1 = new QState(); + s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); + + QState *s2 = new QState(); + + s1->addTransition(s1, SIGNAL(polished()), s2); + \endcode + + The machine will be in state \c s1 until the \c geometry property has been set. Then it will + immediately transition into \c s2. If the transition into \c s1 has an animation for the \c + geometry property, then the machine will stay in \c s1 until the animation has finished. If there + is no animation, it will simply set the property and immediately enter state \c s2. + + Either way, when the machine is in state \c s2, the property \c geometry has been assigned the + defined value. + + If the global restore policy is set to QStateMachine::RestoreProperties, the state will not emit + the polished() signal until these have been executed as well. + + \section1 What happens if a state is exited before the animation has finished + + If a state has property assignments, and the transition into the state has animations for the + properties, the state can potentially be exited before the properties have been assigned to the + values defines by the state. This is true in particular when there are transitions out from the + state that do not depend on the state being polished, as described in the previous section. + + The State Machine API guarantees that a property assigned by the state machine either: + \list + \o Has a value explicitly assigned to the property. + \o Is currently being animated into a value explicitly assigned to the property. + \endlist + + When a state is exited prior to the animation finishing, the behavior of the state machine depends + on the target state of the transition. If the target state explicitly assigns a value to the + property, no additional action will be taken. The property will be assigned the value defined by + the target state. + + If the target state does not assign any value to the property, there are two + options: By default, the property will be assigned the value defined by the state it is leaving + (the value it would have been assigned if the animation had been permitted to finish playing.) If + a global restore policy is set, however, this will take precedence, and the property will be + restored as usual. + + \section1 Default Animations + + As described earlier, you can add animations to transitions to make sure property assignments + in the target state are animated. If you want a specific animation to be used for a given property + regardless of which transition is taken, you can add it as a default animation to the state + machine. This is in particular useful when the properties assigned (or restored) by specific + states is not known when the machine is constructed. + + \code + QState *s1 = new QState(); + QState *s2 = new QState(); + + s2->assignProperty(object, "fooBar", 2.0); + s1->addTransition(s2); + + QStateMachine machine; + machine.setInitialState(s1); + machine.addDefaultAnimation(new QPropertyAnimation(object, "fooBar")); + \endcode + + When the machine is in state \c s2, the machine will play the default animation for the + property \c fooBar since this property is assigned by \c s2. + + Note that animations explicitly set on transitions will take precedence over any default + animation for the given property. +*/ diff --git a/examples/animation/README b/examples/animation/README new file mode 100644 index 0000000..6a892f8 --- /dev/null +++ b/examples/animation/README @@ -0,0 +1,38 @@ +The animation framework aims to provide an easy way for creating animated and +smooth GUI's. By animating Qt properties, the framework provides great freedom +for animating widgets and other QObjects. The framework can also be used with +the Graphics View framework. + +The example launcher provided with Qt can be used to explore each of the +examples in this directory. + +Documentation for these examples can be found via the Tutorial and Examples +link in the main Qt documentation. + + +Finding the Qt Examples and Demos launcher +========================================== + +On Windows: + +The launcher can be accessed via the Windows Start menu. Select the menu +entry entitled "Qt Examples and Demos" entry in the submenu containing +the Qt tools. + +On Mac OS X: + +For the binary distribution, the qtdemo executable is installed in the +/Developer/Applications/Qt directory. For the source distribution, it is +installed alongside the other Qt tools on the path specified when Qt is +configured. + +On Unix/Linux: + +The qtdemo executable is installed alongside the other Qt tools on the path +specified when Qt is configured. + +On all platforms: + +The source code for the launcher can be found in the demos/qtdemo directory +in the Qt package. This example is built at the same time as the Qt libraries, +tools, examples, and demonstrations. diff --git a/examples/animation/animatedtiles/animatedtiles.pro b/examples/animation/animatedtiles/animatedtiles.pro new file mode 100644 index 0000000..1840b17 --- /dev/null +++ b/examples/animation/animatedtiles/animatedtiles.pro @@ -0,0 +1,8 @@ +SOURCES = main.cpp +RESOURCES = animatedtiles.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/animatedtiles +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS animatedtiles.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/animatedtiles +INSTALLS += target sources diff --git a/examples/animation/animatedtiles/animatedtiles.qrc b/examples/animation/animatedtiles/animatedtiles.qrc new file mode 100644 index 0000000..c43a979 --- /dev/null +++ b/examples/animation/animatedtiles/animatedtiles.qrc @@ -0,0 +1,11 @@ + + + images/Time-For-Lunch-2.jpg + images/centered.png + images/ellipse.png + images/figure8.png + images/kinetic.png + images/random.png + images/tile.png + + diff --git a/examples/animation/animatedtiles/images/Time-For-Lunch-2.jpg b/examples/animation/animatedtiles/images/Time-For-Lunch-2.jpg new file mode 100644 index 0000000..c57a555 Binary files /dev/null and b/examples/animation/animatedtiles/images/Time-For-Lunch-2.jpg differ diff --git a/examples/animation/animatedtiles/images/centered.png b/examples/animation/animatedtiles/images/centered.png new file mode 100644 index 0000000..e416156 Binary files /dev/null and b/examples/animation/animatedtiles/images/centered.png differ diff --git a/examples/animation/animatedtiles/images/ellipse.png b/examples/animation/animatedtiles/images/ellipse.png new file mode 100644 index 0000000..2c3ba88 Binary files /dev/null and b/examples/animation/animatedtiles/images/ellipse.png differ diff --git a/examples/animation/animatedtiles/images/figure8.png b/examples/animation/animatedtiles/images/figure8.png new file mode 100644 index 0000000..6b05804 Binary files /dev/null and b/examples/animation/animatedtiles/images/figure8.png differ diff --git a/examples/animation/animatedtiles/images/kinetic.png b/examples/animation/animatedtiles/images/kinetic.png new file mode 100644 index 0000000..55cfa55 Binary files /dev/null and b/examples/animation/animatedtiles/images/kinetic.png differ diff --git a/examples/animation/animatedtiles/images/random.png b/examples/animation/animatedtiles/images/random.png new file mode 100644 index 0000000..415d96f Binary files /dev/null and b/examples/animation/animatedtiles/images/random.png differ diff --git a/examples/animation/animatedtiles/images/tile.png b/examples/animation/animatedtiles/images/tile.png new file mode 100644 index 0000000..c8f39d8 Binary files /dev/null and b/examples/animation/animatedtiles/images/tile.png differ diff --git a/examples/animation/animatedtiles/main.cpp b/examples/animation/animatedtiles/main.cpp new file mode 100644 index 0000000..4b1d99d --- /dev/null +++ b/examples/animation/animatedtiles/main.cpp @@ -0,0 +1,280 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +class Pixmap : public QObject, public QGraphicsPixmapItem +{ + Q_OBJECT + Q_PROPERTY(QPointF pos READ pos WRITE setPos) +public: + Pixmap(const QPixmap &pix) + : QObject(), QGraphicsPixmapItem(pix) + { + setCacheMode(DeviceCoordinateCache); + } +}; + +class Button : public QGraphicsWidget +{ + Q_OBJECT +public: + Button(const QPixmap &pixmap, QGraphicsItem *parent = 0) + : QGraphicsWidget(parent), _pix(pixmap) + { + setAcceptHoverEvents(true); + setCacheMode(DeviceCoordinateCache); + } + + QRectF boundingRect() const + { + return QRectF(-65, -65, 130, 130); + } + + QPainterPath shape() const + { + QPainterPath path; + path.addEllipse(boundingRect()); + return path; + } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) + { + bool down = option->state & QStyle::State_Sunken; + QRectF r = boundingRect(); + QLinearGradient grad(r.topLeft(), r.bottomRight()); + grad.setColorAt(down ? 1 : 0, option->state & QStyle::State_MouseOver ? Qt::white : Qt::lightGray); + grad.setColorAt(down ? 0 : 1, Qt::darkGray); + painter->setPen(Qt::darkGray); + painter->setBrush(grad); + painter->drawEllipse(r); + QLinearGradient grad2(r.topLeft(), r.bottomRight()); + grad.setColorAt(down ? 1 : 0, Qt::darkGray); + grad.setColorAt(down ? 0 : 1, Qt::lightGray); + painter->setPen(Qt::NoPen); + painter->setBrush(grad); + if (down) + painter->translate(2, 2); + painter->drawEllipse(r.adjusted(5, 5, -5, -5)); + painter->drawPixmap(-_pix.width()/2, -_pix.height()/2, _pix); + } + +signals: + void pressed(); + +protected: + void mousePressEvent(QGraphicsSceneMouseEvent *) + { + emit pressed(); + update(); + } + + void mouseReleaseEvent(QGraphicsSceneMouseEvent *) + { + update(); + } + +private: + QPixmap _pix; +}; + +class View : public QGraphicsView +{ +public: + View(QGraphicsScene *scene) : QGraphicsView(scene) { } + +protected: + void resizeEvent(QResizeEvent *event) + { + QGraphicsView::resizeEvent(event); + fitInView(sceneRect(), Qt::KeepAspectRatio); + } +}; + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(animatedtiles); + + QApplication app(argc, argv); + + QPixmap kineticPix(":/images/kinetic.png"); + QPixmap bgPix(":/images/Time-For-Lunch-2.jpg"); + + QGraphicsScene scene(-350, -350, 700, 700); + + QList items; + for (int i = 0; i < 64; ++i) { + Pixmap *item = new Pixmap(kineticPix); + item->setOffset(-kineticPix.width()/2, -kineticPix.height()/2); + item->setZValue(i); + items << item; + scene.addItem(item); + } + + // Buttons + QGraphicsItem *buttonParent = new QGraphicsRectItem; + Button *ellipseButton = new Button(QPixmap(":/images/ellipse.png"), buttonParent); + Button *figure8Button = new Button(QPixmap(":/images/figure8.png"), buttonParent); + Button *randomButton = new Button(QPixmap(":/images/random.png"), buttonParent); + Button *tiledButton = new Button(QPixmap(":/images/tile.png"), buttonParent); + Button *centeredButton = new Button(QPixmap(":/images/centered.png"), buttonParent); + + ellipseButton->setPos(-100, -100); + figure8Button->setPos(100, -100); + randomButton->setPos(0, 0); + tiledButton->setPos(-100, 100); + centeredButton->setPos(100, 100); + + scene.addItem(buttonParent); + buttonParent->scale(0.75, 0.75); + buttonParent->setPos(200, 200); + buttonParent->setZValue(65); + + // States + QState *rootState = new QState; + QState *ellipseState = new QState(rootState); + QState *figure8State = new QState(rootState); + QState *randomState = new QState(rootState); + QState *tiledState = new QState(rootState); + QState *centeredState = new QState(rootState); + + // Values + for (int i = 0; i < 64; ++i) { + Pixmap *item = items.at(i); + // Ellipse + ellipseState->assignProperty(item, "pos", + QPointF(cos((i / 63.0) * 6.28) * 250, + sin((i / 63.0) * 6.28) * 250)); + + // Figure 8 + figure8State->assignProperty(item, "pos", + QPointF(sin((i / 63.0) * 6.28) * 250, + sin(((i * 2)/63.0) * 6.28) * 250)); + + // Random + randomState->assignProperty(item, "pos", + QPointF(-250 + qrand() % 500, + -250 + qrand() % 500)); + + // Tiled + tiledState->assignProperty(item, "pos", + QPointF(((i % 8) - 4) * kineticPix.width() + kineticPix.width() / 2, + ((i / 8) - 4) * kineticPix.height() + kineticPix.height() / 2)); + + // Centered + centeredState->assignProperty(item, "pos", QPointF()); + } + + // Ui + View *view = new View(&scene); + view->setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, "Animated Tiles")); + view->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); + view->setBackgroundBrush(bgPix); + view->setCacheMode(QGraphicsView::CacheBackground); + view->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); + view->show(); + + QStateMachine states; + states.addState(rootState); + states.setInitialState(rootState); + rootState->setInitialState(centeredState); + + QParallelAnimationGroup *group = new QParallelAnimationGroup; + for (int i = 0; i < 64; ++i) { + QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); + anim->setDuration(750 + i * 25); + anim->setEasingCurve(QEasingCurve::InOutBack); + group->addAnimation(anim); + } + QAbstractTransition *trans = rootState->addTransition(ellipseButton, SIGNAL(pressed()), ellipseState); + trans->addAnimation(group); + + group = new QParallelAnimationGroup; + for (int i = 0; i < 64; ++i) { + QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); + anim->setDuration(750 + i * 25); + anim->setEasingCurve(QEasingCurve::InOutBack); + group->addAnimation(anim); + } + trans = rootState->addTransition(figure8Button, SIGNAL(pressed()), figure8State); + trans->addAnimation(group); + + group = new QParallelAnimationGroup; + for (int i = 0; i < 64; ++i) { + QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); + anim->setDuration(750 + i * 25); + anim->setEasingCurve(QEasingCurve::InOutBack); + group->addAnimation(anim); + } + trans = rootState->addTransition(randomButton, SIGNAL(pressed()), randomState); + trans->addAnimation(group); + + group = new QParallelAnimationGroup; + for (int i = 0; i < 64; ++i) { + QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); + anim->setDuration(750 + i * 25); + anim->setEasingCurve(QEasingCurve::InOutBack); + group->addAnimation(anim); + } + trans = rootState->addTransition(tiledButton, SIGNAL(pressed()), tiledState); + trans->addAnimation(group); + + group = new QParallelAnimationGroup; + for (int i = 0; i < 64; ++i) { + QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); + anim->setDuration(750 + i * 25); + anim->setEasingCurve(QEasingCurve::InOutBack); + group->addAnimation(anim); + } + trans = rootState->addTransition(centeredButton, SIGNAL(pressed()), centeredState); + trans->addAnimation(group); + + states.start(); + QTimer timer; + timer.start(125); + timer.setSingleShot(true); + rootState->addTransition(&timer, SIGNAL(timeout()), ellipseState); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/animation/animation.pro b/examples/animation/animation.pro new file mode 100644 index 0000000..9a2874b --- /dev/null +++ b/examples/animation/animation.pro @@ -0,0 +1,16 @@ +TEMPLATE = \ + subdirs +SUBDIRS += \ + animatedtiles \ + appchooser \ + easing \ + moveblocks \ + states \ + stickman \ + sub-attaq + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS animation.pro README +sources.path = $$[QT_INSTALL_EXAMPLES]/animation +INSTALLS += target sources diff --git a/examples/animation/appchooser/accessories-dictionary.png b/examples/animation/appchooser/accessories-dictionary.png new file mode 100644 index 0000000..e9bd55d Binary files /dev/null and b/examples/animation/appchooser/accessories-dictionary.png differ diff --git a/examples/animation/appchooser/akregator.png b/examples/animation/appchooser/akregator.png new file mode 100644 index 0000000..a086f45 Binary files /dev/null and b/examples/animation/appchooser/akregator.png differ diff --git a/examples/animation/appchooser/appchooser.pro b/examples/animation/appchooser/appchooser.pro new file mode 100644 index 0000000..847b60a --- /dev/null +++ b/examples/animation/appchooser/appchooser.pro @@ -0,0 +1,8 @@ +SOURCES = main.cpp +RESOURCES = appchooser.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/appchooser +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS appchooser.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/appchooser +INSTALLS += target sources diff --git a/examples/animation/appchooser/appchooser.qrc b/examples/animation/appchooser/appchooser.qrc new file mode 100644 index 0000000..28a3e1c --- /dev/null +++ b/examples/animation/appchooser/appchooser.qrc @@ -0,0 +1,8 @@ + + + accessories-dictionary.png + akregator.png + digikam.png + k3b.png + + diff --git a/examples/animation/appchooser/digikam.png b/examples/animation/appchooser/digikam.png new file mode 100644 index 0000000..9de9fb2 Binary files /dev/null and b/examples/animation/appchooser/digikam.png differ diff --git a/examples/animation/appchooser/k3b.png b/examples/animation/appchooser/k3b.png new file mode 100644 index 0000000..bbcafcf Binary files /dev/null and b/examples/animation/appchooser/k3b.png differ diff --git a/examples/animation/appchooser/main.cpp b/examples/animation/appchooser/main.cpp new file mode 100644 index 0000000..44457f7 --- /dev/null +++ b/examples/animation/appchooser/main.cpp @@ -0,0 +1,158 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + + +class Pixmap : public QGraphicsWidget +{ + Q_OBJECT + +public: + Pixmap(const QPixmap &pix, QGraphicsItem *parent = 0) + : QGraphicsWidget(parent), orig(pix), p(pix) + { + } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) + { + painter->drawPixmap(QPointF(), p); + } + + virtual void mousePressEvent(QGraphicsSceneMouseEvent * ) + { + emit clicked(); + } + + virtual void setGeometry(const QRectF &rect) + { + QGraphicsWidget::setGeometry(rect); + + if (rect.size().width() > orig.size().width()) + p = orig.scaled(rect.size().toSize()); + else + p = orig; + } + +Q_SIGNALS: + void clicked(); + +private: + QPixmap orig; + QPixmap p; +}; + +void createStates(const QObjectList &objects, + const QRect &selectedRect, QState *parent) +{ + for (int i = 0; i < objects.size(); ++i) { + QState *state = new QState(parent); + state->assignProperty(objects.at(i), "geometry", selectedRect); + parent->addTransition(objects.at(i), SIGNAL(clicked()), state); + } +} + +void createAnimations(const QObjectList &objects, QStateMachine *machine) +{ + for (int i=0; iaddDefaultAnimation(new QPropertyAnimation(objects.at(i), "geometry")); +} + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(appchooser); + + QApplication app(argc, argv); + + Pixmap *p1 = new Pixmap(QPixmap(":/digikam.png")); + Pixmap *p2 = new Pixmap(QPixmap(":/akregator.png")); + Pixmap *p3 = new Pixmap(QPixmap(":/accessories-dictionary.png")); + Pixmap *p4 = new Pixmap(QPixmap(":/k3b.png")); + + p1->setObjectName("p1"); + p2->setObjectName("p2"); + p3->setObjectName("p3"); + p4->setObjectName("p4"); + + p1->setGeometry(QRectF(0.0, 0.0, 64.0, 64.0)); + p2->setGeometry(QRectF(236.0, 0.0, 64.0, 64.0)); + p3->setGeometry(QRectF(236.0, 236.0, 64.0, 64.0)); + p4->setGeometry(QRectF(0.0, 236.0, 64.0, 64.0)); + + QGraphicsScene scene(0, 0, 300, 300); + scene.setBackgroundBrush(Qt::white); + scene.addItem(p1); + scene.addItem(p2); + scene.addItem(p3); + scene.addItem(p4); + + QGraphicsView window(&scene); + window.setFrameStyle(0); + window.setAlignment(Qt::AlignLeft | Qt::AlignTop); + window.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + window.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + + QState *group = new QState(machine.rootState()); + group->setObjectName("group"); + QRect selectedRect(86, 86, 128, 128); + + QState *idleState = new QState(group); + group->setInitialState(idleState); + + QObjectList objects; + objects << p1 << p2 << p3 << p4; + createStates(objects, selectedRect, group); + createAnimations(objects, &machine); + + machine.setInitialState(group); + machine.start(); + + window.resize(300, 300); + window.show(); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/animation/easing/animation.h b/examples/animation/easing/animation.h new file mode 100644 index 0000000..d4d699d --- /dev/null +++ b/examples/animation/easing/animation.h @@ -0,0 +1,101 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ANIMATION_H +#define ANIMATION_H + +#include + +#include + +class Animation : public QPropertyAnimation { +public: + enum PathType { + LinearPath, + CirclePath, + NPathTypes + }; + Animation(QObject *target, const QByteArray &prop) + : QPropertyAnimation(target, prop) + { + setPathType(LinearPath); + } + + void setPathType(PathType pathType) + { + if (pathType >= NPathTypes) + qWarning("Unknown pathType %d", pathType); + + m_pathType = pathType; + m_path = QPainterPath(); + } + + void updateCurrentTime(int msecs) + { + if (m_pathType == CirclePath) { + if (m_path.isEmpty()) { + QPointF to = endValue().toPointF(); + QPointF from = startValue().toPointF(); + m_path.moveTo(from); + m_path.addEllipse(QRectF(from, to)); + } + int dura = duration(); + const qreal progress = ((dura == 0) ? 1 : ((((currentTime() - 1) % dura) + 1) / qreal(dura))); + + qreal easedProgress = easingCurve().valueForProgress(progress); + if (easedProgress > 1.0) { + easedProgress -= 1.0; + } else if (easedProgress < 0) { + easedProgress += 1.0; + } + QPointF pt = m_path.pointAtPercent(easedProgress); + updateCurrentValue(pt); + emit valueChanged(pt); + } else { + QPropertyAnimation::updateCurrentTime(msecs); + } + } + + QPainterPath m_path; + PathType m_pathType; +}; + +#endif // ANIMATION_H diff --git a/examples/animation/easing/easing.pro b/examples/animation/easing/easing.pro new file mode 100644 index 0000000..8e8a35f --- /dev/null +++ b/examples/animation/easing/easing.pro @@ -0,0 +1,14 @@ +HEADERS = window.h \ + animation.h +SOURCES = main.cpp \ + window.cpp + +FORMS = form.ui + +RESOURCES = easing.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/easing +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS easing.pro images +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/easing +INSTALLS += target sources diff --git a/examples/animation/easing/easing.qrc b/examples/animation/easing/easing.qrc new file mode 100644 index 0000000..7e112d3 --- /dev/null +++ b/examples/animation/easing/easing.qrc @@ -0,0 +1,5 @@ + + + images/qt-logo.png + + \ No newline at end of file diff --git a/examples/animation/easing/form.ui b/examples/animation/easing/form.ui new file mode 100644 index 0000000..b60ade8 --- /dev/null +++ b/examples/animation/easing/form.ui @@ -0,0 +1,201 @@ + + + Form + + + + 0 + 0 + 545 + 471 + + + + Easing curves + + + + + + + 0 + 0 + + + + + 16777215 + 120 + + + + Qt::ScrollBarAlwaysOff + + + QListView::Static + + + false + + + QListView::IconMode + + + false + + + + + + + + + Path type + + + + + + Line + + + true + + + buttonGroup + + + + + + + Circle + + + buttonGroup + + + + + + + + + + + 0 + 0 + + + + Properties + + + + QFormLayout::AllNonFixedFieldsGrow + + + + + Period + + + + + + + false + + + -1.000000000000000 + + + 0.100000000000000 + + + -1.000000000000000 + + + + + + + Amplitude + + + + + + + false + + + -1.000000000000000 + + + 0.100000000000000 + + + -1.000000000000000 + + + + + + + Overshoot + + + + + + + false + + + -1.000000000000000 + + + 0.100000000000000 + + + -1.000000000000000 + + + + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + 0 + 0 + + + + + + + + + + + + diff --git a/examples/animation/easing/images/qt-logo.png b/examples/animation/easing/images/qt-logo.png new file mode 100644 index 0000000..14ddf2a Binary files /dev/null and b/examples/animation/easing/images/qt-logo.png differ diff --git a/examples/animation/easing/main.cpp b/examples/animation/easing/main.cpp new file mode 100644 index 0000000..bd10df2 --- /dev/null +++ b/examples/animation/easing/main.cpp @@ -0,0 +1,53 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "window.h" + +int main(int argc, char **argv) +{ + Q_INIT_RESOURCE(easing); + QApplication app(argc, argv); + Window w; + w.resize(400, 400); + w.show(); + return app.exec(); +} diff --git a/examples/animation/easing/window.cpp b/examples/animation/easing/window.cpp new file mode 100644 index 0000000..cf4be15 --- /dev/null +++ b/examples/animation/easing/window.cpp @@ -0,0 +1,163 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "window.h" + +Window::Window(QWidget *parent) + : QWidget(parent), m_iconSize(64, 64) +{ + m_ui.setupUi(this); + QButtonGroup *buttonGroup = qFindChild(this); // ### workaround for uic in 4.4 + m_ui.easingCurvePicker->setIconSize(m_iconSize); + m_ui.easingCurvePicker->setMinimumHeight(m_iconSize.height() + 50); + buttonGroup->setId(m_ui.lineRadio, 0); + buttonGroup->setId(m_ui.circleRadio, 1); + + QEasingCurve dummy; + m_ui.periodSpinBox->setValue(dummy.period()); + m_ui.amplitudeSpinBox->setValue(dummy.amplitude()); + m_ui.overshootSpinBox->setValue(dummy.overshoot()); + + connect(m_ui.easingCurvePicker, SIGNAL(currentRowChanged(int)), this, SLOT(curveChanged(int))); + connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(pathChanged(int))); + connect(m_ui.periodSpinBox, SIGNAL(valueChanged(double)), this, SLOT(periodChanged(double))); + connect(m_ui.amplitudeSpinBox, SIGNAL(valueChanged(double)), this, SLOT(amplitudeChanged(double))); + connect(m_ui.overshootSpinBox, SIGNAL(valueChanged(double)), this, SLOT(overshootChanged(double))); + createCurveIcons(); + + QPixmap pix(QLatin1String(":/images/qt-logo.png")); + m_item = new PixmapItem(pix); + m_scene.addItem(m_item); + m_ui.graphicsView->setScene(&m_scene); + + m_anim = new Animation(m_item, "pos"); + m_anim->setEasingCurve(QEasingCurve::OutBounce); + m_ui.easingCurvePicker->setCurrentRow(int(QEasingCurve::OutBounce)); + + startAnimation(); +} + +void Window::createCurveIcons() +{ + QPixmap pix(m_iconSize); + QPainter painter(&pix); + QLinearGradient gradient(0,0, 0, m_iconSize.height()); + gradient.setColorAt(0.0, QColor(240, 240, 240)); + gradient.setColorAt(1.0, QColor(224, 224, 224)); + QBrush brush(gradient); + const QMetaObject &mo = QEasingCurve::staticMetaObject; + QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type")); + // Skip QEasingCurve::Custom + for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) { + painter.fillRect(QRect(QPoint(0, 0), m_iconSize), brush); + QEasingCurve curve((QEasingCurve::Type)i); + painter.setPen(QColor(0, 0, 255, 64)); + qreal xAxis = m_iconSize.height()/1.5; + qreal yAxis = m_iconSize.width()/3; + painter.drawLine(0, xAxis, m_iconSize.width(), xAxis); + painter.drawLine(yAxis, 0, yAxis, m_iconSize.height()); + painter.setPen(Qt::black); + + qreal curveScale = m_iconSize.height()/2; + QPoint currentPos(yAxis, xAxis); + + for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { + QPoint to; + to.setX(yAxis + curveScale * t); + to.setY(xAxis - curveScale * curve.valueForProgress(t)); + painter.drawLine(currentPos, to); + currentPos = to; + } + QListWidgetItem *item = new QListWidgetItem; + item->setIcon(QIcon(pix)); + item->setText(metaEnum.key(i)); + m_ui.easingCurvePicker->addItem(item); + } +} + +void Window::startAnimation() +{ + m_anim->setStartValue(QPointF(0, 0)); + m_anim->setEndValue(QPointF(100, 100)); + m_anim->setDuration(2000); + m_anim->setLoopCount(-1); // forever + m_anim->start(); +} + +void Window::curveChanged(int row) +{ + QEasingCurve::Type curveType = (QEasingCurve::Type)row; + m_anim->setEasingCurve(curveType); + m_anim->setCurrentTime(0); + + bool isElastic = curveType >= QEasingCurve::InElastic && curveType <= QEasingCurve::OutInElastic; + bool isBounce = curveType >= QEasingCurve::InBounce && curveType <= QEasingCurve::OutInBounce; + m_ui.periodSpinBox->setEnabled(isElastic); + m_ui.amplitudeSpinBox->setEnabled(isElastic || isBounce); + m_ui.overshootSpinBox->setEnabled(curveType >= QEasingCurve::InBack && curveType <= QEasingCurve::OutInBack); +} + +void Window::pathChanged(int index) +{ + m_anim->setPathType((Animation::PathType)index); +} + +void Window::periodChanged(double value) +{ + QEasingCurve curve = m_anim->easingCurve(); + curve.setPeriod(value); + m_anim->setEasingCurve(curve); +} + +void Window::amplitudeChanged(double value) +{ + QEasingCurve curve = m_anim->easingCurve(); + curve.setAmplitude(value); + m_anim->setEasingCurve(curve); +} + +void Window::overshootChanged(double value) +{ + QEasingCurve curve = m_anim->easingCurve(); + curve.setOvershoot(value); + m_anim->setEasingCurve(curve); +} + diff --git a/examples/animation/easing/window.h b/examples/animation/easing/window.h new file mode 100644 index 0000000..f3a8cb3 --- /dev/null +++ b/examples/animation/easing/window.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "ui_form.h" +#include "animation.h" + +class PixmapItem : public QObject, public QGraphicsPixmapItem +{ + Q_OBJECT + Q_PROPERTY(QPointF pos READ pos WRITE setPos) +public: + PixmapItem(const QPixmap &pix) : QGraphicsPixmapItem(pix) + { + } +}; + +class Window : public QWidget { + Q_OBJECT +public: + Window(QWidget *parent = 0); +private slots: + void curveChanged(int row); + void pathChanged(int index); + void periodChanged(double); + void amplitudeChanged(double); + void overshootChanged(double); + +private: + void createCurveIcons(); + void startAnimation(); + + Ui::Form m_ui; + QGraphicsScene m_scene; + PixmapItem *m_item; + Animation *m_anim; + QSize m_iconSize; + + +}; diff --git a/examples/animation/moveblocks/main.cpp b/examples/animation/moveblocks/main.cpp new file mode 100644 index 0000000..b00485e --- /dev/null +++ b/examples/animation/moveblocks/main.cpp @@ -0,0 +1,296 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +class StateSwitchEvent: public QEvent +{ +public: + StateSwitchEvent() + : QEvent(Type(StateSwitchType)) + { + } + + StateSwitchEvent(int rand) + : QEvent(Type(StateSwitchType)), + m_rand(rand) + { + } + + enum { StateSwitchType = QEvent::User + 256 }; + + int rand() const { return m_rand; } + +private: + int m_rand; +}; + + +class QGraphicsRectWidget : public QGraphicsWidget +{ +public: + void paint(QPainter *painter, const QStyleOptionGraphicsItem *, + QWidget *) + { + painter->fillRect(rect(), Qt::blue); + } +}; + +class StateSwitchTransition: public QAbstractTransition +{ +public: + StateSwitchTransition(int rand) + : QAbstractTransition(), + m_rand(rand) + { + } + +protected: + virtual bool eventTest(QEvent *event) + { + return (event->type() == QEvent::Type(StateSwitchEvent::StateSwitchType)) + && (static_cast(event)->rand() == m_rand); + } + + virtual void onTransition(QEvent *) {} + +private: + int m_rand; +}; + +class StateSwitcher : public QState +{ + Q_OBJECT +public: + StateSwitcher(QStateMachine *machine) + : QState(machine->rootState()), m_machine(machine), + m_stateCount(0), m_lastIndex(0) + { } + + virtual void onEntry(QEvent *) + { + int n; + while ((n = (qrand() % m_stateCount + 1)) == m_lastIndex) + { } + m_lastIndex = n; + m_machine->postEvent(new StateSwitchEvent(n)); + } + virtual void onExit(QEvent *) {} + + void addState(QState *state, QAbstractAnimation *animation) { + StateSwitchTransition *trans = new StateSwitchTransition(++m_stateCount); + trans->setTargetState(state); + addTransition(trans); + trans->addAnimation(animation); + } + + +private: + QStateMachine *m_machine; + int m_stateCount; + int m_lastIndex; +}; + +QState *createGeometryState(QObject *w1, const QRect &rect1, + QObject *w2, const QRect &rect2, + QObject *w3, const QRect &rect3, + QObject *w4, const QRect &rect4, + QState *parent) +{ + QState *result = new QState(parent); + result->assignProperty(w1, "geometry", rect1); + result->assignProperty(w1, "geometry", rect1); + result->assignProperty(w2, "geometry", rect2); + result->assignProperty(w3, "geometry", rect3); + result->assignProperty(w4, "geometry", rect4); + + return result; +} + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + +#if 0 + QWidget window; + QPalette palette; + palette.setBrush(QPalette::Window, Qt::black); + window.setPalette(palette); + QPushButton *button1 = new QPushButton("A", &window); + QPushButton *button2 = new QPushButton("B", &window); + QPushButton *button3 = new QPushButton("C", &window); + QPushButton *button4 = new QPushButton("D", &window); + + button1->setObjectName("button1"); + button2->setObjectName("button2"); + button3->setObjectName("button3"); + button4->setObjectName("button4"); +#else + QGraphicsRectWidget *button1 = new QGraphicsRectWidget; + QGraphicsRectWidget *button2 = new QGraphicsRectWidget; + QGraphicsRectWidget *button3 = new QGraphicsRectWidget; + QGraphicsRectWidget *button4 = new QGraphicsRectWidget; + button2->setZValue(1); + button3->setZValue(2); + button4->setZValue(3); + QGraphicsScene scene(0, 0, 300, 300); + scene.setBackgroundBrush(Qt::black); + scene.addItem(button1); + scene.addItem(button2); + scene.addItem(button3); + scene.addItem(button4); + + QGraphicsView window(&scene); + window.setFrameStyle(0); + window.setAlignment(Qt::AlignLeft | Qt::AlignTop); + window.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + window.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); +#endif + QStateMachine machine; + + QState *group = new QState(); + group->setObjectName("group"); + QTimer timer; + timer.setInterval(1250); + timer.setSingleShot(true); + QObject::connect(group, SIGNAL(entered()), &timer, SLOT(start())); + + QState *state1; + QState *state2; + QState *state3; + QState *state4; + QState *state5; + QState *state6; + QState *state7; + + state1 = createGeometryState(button1, QRect(100, 0, 50, 50), + button2, QRect(150, 0, 50, 50), + button3, QRect(200, 0, 50, 50), + button4, QRect(250, 0, 50, 50), + group); + state2 = createGeometryState(button1, QRect(250, 100, 50, 50), + button2, QRect(250, 150, 50, 50), + button3, QRect(250, 200, 50, 50), + button4, QRect(250, 250, 50, 50), + group); + state3 = createGeometryState(button1, QRect(150, 250, 50, 50), + button2, QRect(100, 250, 50, 50), + button3, QRect(50, 250, 50, 50), + button4, QRect(0, 250, 50, 50), + group); + state4 = createGeometryState(button1, QRect(0, 150, 50, 50), + button2, QRect(0, 100, 50, 50), + button3, QRect(0, 50, 50, 50), + button4, QRect(0, 0, 50, 50), + group); + state5 = createGeometryState(button1, QRect(100, 100, 50, 50), + button2, QRect(150, 100, 50, 50), + button3, QRect(100, 150, 50, 50), + button4, QRect(150, 150, 50, 50), + group); + state6 = createGeometryState(button1, QRect(50, 50, 50, 50), + button2, QRect(200, 50, 50, 50), + button3, QRect(50, 200, 50, 50), + button4, QRect(200, 200, 50, 50), + group); + state7 = createGeometryState(button1, QRect(0, 0, 50, 50), + button2, QRect(250, 0, 50, 50), + button3, QRect(0, 250, 50, 50), + button4, QRect(250, 250, 50, 50), + group); + group->setInitialState(state1); + + QParallelAnimationGroup animationGroup; + QSequentialAnimationGroup *subGroup; + + QPropertyAnimation *anim = new QPropertyAnimation(button4, "geometry"); + anim->setDuration(1000); + anim->setEasingCurve(QEasingCurve::OutElastic); + animationGroup.addAnimation(anim); + + subGroup = new QSequentialAnimationGroup(&animationGroup); + subGroup->addPause(100); + anim = new QPropertyAnimation(button3, "geometry"); + anim->setDuration(1000); + anim->setEasingCurve(QEasingCurve::OutElastic); + subGroup->addAnimation(anim); + + subGroup = new QSequentialAnimationGroup(&animationGroup); + subGroup->addPause(150); + anim = new QPropertyAnimation(button2, "geometry"); + anim->setDuration(1000); + anim->setEasingCurve(QEasingCurve::OutElastic); + subGroup->addAnimation(anim); + + subGroup = new QSequentialAnimationGroup(&animationGroup); + subGroup->addPause(200); + anim = new QPropertyAnimation(button1, "geometry"); + anim->setDuration(1000); + anim->setEasingCurve(QEasingCurve::OutElastic); + subGroup->addAnimation(anim); + + StateSwitcher *stateSwitcher = new StateSwitcher(&machine); + stateSwitcher->setObjectName("stateSwitcher"); + group->addTransition(&timer, SIGNAL(timeout()), stateSwitcher); + stateSwitcher->addState(state1, &animationGroup); + stateSwitcher->addState(state2, &animationGroup); + stateSwitcher->addState(state3, &animationGroup); + stateSwitcher->addState(state4, &animationGroup); + stateSwitcher->addState(state5, &animationGroup); + stateSwitcher->addState(state6, &animationGroup); + stateSwitcher->addState(state7, &animationGroup); + + machine.addState(group); + machine.setInitialState(group); + machine.start(); + + + window.resize(300, 300); + window.show(); + + qsrand(time(0)); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/animation/moveblocks/moveblocks.pro b/examples/animation/moveblocks/moveblocks.pro new file mode 100644 index 0000000..b8e88b2 --- /dev/null +++ b/examples/animation/moveblocks/moveblocks.pro @@ -0,0 +1,7 @@ +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/moveblocks +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS moveblocks.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/moveblocks +INSTALLS += target sources diff --git a/examples/animation/states/accessories-dictionary.png b/examples/animation/states/accessories-dictionary.png new file mode 100644 index 0000000..e9bd55d Binary files /dev/null and b/examples/animation/states/accessories-dictionary.png differ diff --git a/examples/animation/states/akregator.png b/examples/animation/states/akregator.png new file mode 100644 index 0000000..a086f45 Binary files /dev/null and b/examples/animation/states/akregator.png differ diff --git a/examples/animation/states/digikam.png b/examples/animation/states/digikam.png new file mode 100644 index 0000000..9de9fb2 Binary files /dev/null and b/examples/animation/states/digikam.png differ diff --git a/examples/animation/states/help-browser.png b/examples/animation/states/help-browser.png new file mode 100644 index 0000000..db92faa Binary files /dev/null and b/examples/animation/states/help-browser.png differ diff --git a/examples/animation/states/k3b.png b/examples/animation/states/k3b.png new file mode 100644 index 0000000..bbcafcf Binary files /dev/null and b/examples/animation/states/k3b.png differ diff --git a/examples/animation/states/kchart.png b/examples/animation/states/kchart.png new file mode 100644 index 0000000..1dd115b Binary files /dev/null and b/examples/animation/states/kchart.png differ diff --git a/examples/animation/states/main.cpp b/examples/animation/states/main.cpp new file mode 100644 index 0000000..17a7a8e --- /dev/null +++ b/examples/animation/states/main.cpp @@ -0,0 +1,284 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +class Pixmap : public QGraphicsWidget +{ + Q_OBJECT +public: + Pixmap(const QPixmap &pix) : QGraphicsWidget(), p(pix) + { + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) + { + painter->drawPixmap(QPointF(), p); + } + +protected: + QSizeF sizeHint(Qt::SizeHint, const QSizeF & = QSizeF()) + { + return QSizeF(p.width(), p.height()); + } + +private: + QPixmap p; +}; + +int main(int argc, char *argv[]) +{ + Q_INIT_RESOURCE(states); + + QApplication app(argc, argv); + + // Text edit and button + QTextEdit *edit = new QTextEdit; + edit->setText("asdf lkjha yuoiqwe asd iuaysd u iasyd uiy " + "asdf lkjha yuoiqwe asd iuaysd u iasyd uiy " + "asdf lkjha yuoiqwe asd iuaysd u iasyd uiy " + "asdf lkjha yuoiqwe asd iuaysd u iasyd uiy!"); + + QPushButton *button = new QPushButton; + QGraphicsProxyWidget *buttonProxy = new QGraphicsProxyWidget; + buttonProxy->setWidget(button); + QGraphicsProxyWidget *editProxy = new QGraphicsProxyWidget; + editProxy->setWidget(edit); + + QGroupBox *box = new QGroupBox; + box->setFlat(true); + box->setTitle("Options"); + + QVBoxLayout *layout2 = new QVBoxLayout; + box->setLayout(layout2); + layout2->addWidget(new QRadioButton("Herring")); + layout2->addWidget(new QRadioButton("Blue Parrot")); + layout2->addWidget(new QRadioButton("Petunias")); + layout2->addStretch(); + + QGraphicsProxyWidget *boxProxy = new QGraphicsProxyWidget; + boxProxy->setWidget(box); + + // Parent widget + QGraphicsWidget *widget = new QGraphicsWidget; + QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical, widget); + layout->addItem(editProxy); + layout->addItem(buttonProxy); + widget->setLayout(layout); + + Pixmap *p1 = new Pixmap(QPixmap(":/digikam.png")); + Pixmap *p2 = new Pixmap(QPixmap(":/akregator.png")); + Pixmap *p3 = new Pixmap(QPixmap(":/accessories-dictionary.png")); + Pixmap *p4 = new Pixmap(QPixmap(":/k3b.png")); + Pixmap *p5 = new Pixmap(QPixmap(":/help-browser.png")); + Pixmap *p6 = new Pixmap(QPixmap(":/kchart.png")); + + QGraphicsScene scene(0, 0, 400, 300); + scene.setBackgroundBrush(scene.palette().window()); + scene.addItem(widget); + scene.addItem(boxProxy); + scene.addItem(p1); + scene.addItem(p2); + scene.addItem(p3); + scene.addItem(p4); + scene.addItem(p5); + scene.addItem(p6); + + QStateMachine machine; + QState *root = machine.rootState(); + QState *state1 = new QState(root); + QState *state2 = new QState(root); + QState *state3 = new QState(root); + machine.setInitialState(state1); + + // State 1 + state1->assignProperty(button, "text", "Switch to state 2"); + state1->assignProperty(widget, "geometry", QRectF(0, 0, 400, 150)); + state1->assignProperty(box, "geometry", QRect(-200, 150, 200, 150)); + state1->assignProperty(p1, "geometry", QRectF(68, 185, 64, 64)); + state1->assignProperty(p2, "geometry", QRectF(168, 185, 64, 64)); + state1->assignProperty(p3, "geometry", QRectF(268, 185, 64, 64)); + state1->assignProperty(p4, "geometry", QRectF(68-150, 48-150, 64, 64)); + state1->assignProperty(p5, "geometry", QRectF(168, 48-150, 64, 64)); + state1->assignProperty(p6, "geometry", QRectF(268+150, 48-150, 64, 64)); + state1->assignProperty(p1, "zRotation", qreal(0)); + state1->assignProperty(p2, "zRotation", qreal(0)); + state1->assignProperty(p3, "zRotation", qreal(0)); + state1->assignProperty(p4, "zRotation", qreal(-270)); + state1->assignProperty(p5, "zRotation", qreal(-90)); + state1->assignProperty(p6, "zRotation", qreal(270)); + state1->assignProperty(boxProxy, "opacity", qreal(0)); + state1->assignProperty(p1, "opacity", qreal(1)); + state1->assignProperty(p2, "opacity", qreal(1)); + state1->assignProperty(p3, "opacity", qreal(1)); + state1->assignProperty(p4, "opacity", qreal(0)); + state1->assignProperty(p5, "opacity", qreal(0)); + state1->assignProperty(p6, "opacity", qreal(0)); + + // State 2 + state2->assignProperty(button, "text", "Switch to state 3"); + state2->assignProperty(widget, "geometry", QRectF(200, 150, 200, 150)); + state2->assignProperty(box, "geometry", QRect(9, 150, 190, 150)); + state2->assignProperty(p1, "geometry", QRectF(68-150, 185+150, 64, 64)); + state2->assignProperty(p2, "geometry", QRectF(168, 185+150, 64, 64)); + state2->assignProperty(p3, "geometry", QRectF(268+150, 185+150, 64, 64)); + state2->assignProperty(p4, "geometry", QRectF(64, 48, 64, 64)); + state2->assignProperty(p5, "geometry", QRectF(168, 48, 64, 64)); + state2->assignProperty(p6, "geometry", QRectF(268, 48, 64, 64)); + state2->assignProperty(p1, "zRotation", qreal(-270)); + state2->assignProperty(p2, "zRotation", qreal(90)); + state2->assignProperty(p3, "zRotation", qreal(270)); + state2->assignProperty(p4, "zRotation", qreal(0)); + state2->assignProperty(p5, "zRotation", qreal(0)); + state2->assignProperty(p6, "zRotation", qreal(0)); + state2->assignProperty(boxProxy, "opacity", qreal(1)); + state2->assignProperty(p1, "opacity", qreal(0)); + state2->assignProperty(p2, "opacity", qreal(0)); + state2->assignProperty(p3, "opacity", qreal(0)); + state2->assignProperty(p4, "opacity", qreal(1)); + state2->assignProperty(p5, "opacity", qreal(1)); + state2->assignProperty(p6, "opacity", qreal(1)); + + // State 3 + state3->assignProperty(button, "text", "Switch to state 1"); + state3->assignProperty(p1, "geometry", QRectF(5, 5, 64, 64)); + state3->assignProperty(p2, "geometry", QRectF(5, 5 + 64 + 5, 64, 64)); + state3->assignProperty(p3, "geometry", QRectF(5, 5 + (64 + 5) + 64, 64, 64)); + state3->assignProperty(p4, "geometry", QRectF(5 + 64 + 5, 5, 64, 64)); + state3->assignProperty(p5, "geometry", QRectF(5 + 64 + 5, 5 + 64 + 5, 64, 64)); + state3->assignProperty(p6, "geometry", QRectF(5 + 64 + 5, 5 + (64 + 5) + 64, 64, 64)); + state3->assignProperty(widget, "geometry", QRectF(138, 5, 400 - 138, 200)); + state3->assignProperty(box, "geometry", QRect(5, 205, 400, 90)); + state3->assignProperty(p1, "opacity", qreal(1)); + state3->assignProperty(p2, "opacity", qreal(1)); + state3->assignProperty(p3, "opacity", qreal(1)); + state3->assignProperty(p4, "opacity", qreal(1)); + state3->assignProperty(p5, "opacity", qreal(1)); + state3->assignProperty(p6, "opacity", qreal(1)); + + QParallelAnimationGroup animation1; + + QSequentialAnimationGroup *animation1SubGroup; + animation1SubGroup = new QSequentialAnimationGroup(&animation1); + animation1SubGroup->addPause(250); + animation1SubGroup->addAnimation(new QPropertyAnimation(box, "geometry")); + + animation1.addAnimation(new QPropertyAnimation(widget, "geometry")); + animation1.addAnimation(new QPropertyAnimation(p1, "geometry")); + animation1.addAnimation(new QPropertyAnimation(p2, "geometry")); + animation1.addAnimation(new QPropertyAnimation(p3, "geometry")); + animation1.addAnimation(new QPropertyAnimation(p4, "geometry")); + animation1.addAnimation(new QPropertyAnimation(p5, "geometry")); + animation1.addAnimation(new QPropertyAnimation(p6, "geometry")); + animation1.addAnimation(new QPropertyAnimation(p1, "zRotation")); + animation1.addAnimation(new QPropertyAnimation(p2, "zRotation")); + animation1.addAnimation(new QPropertyAnimation(p3, "zRotation")); + animation1.addAnimation(new QPropertyAnimation(p4, "zRotation")); + animation1.addAnimation(new QPropertyAnimation(p5, "zRotation")); + animation1.addAnimation(new QPropertyAnimation(p6, "zRotation")); + animation1.addAnimation(new QPropertyAnimation(p1, "opacity")); + animation1.addAnimation(new QPropertyAnimation(p2, "opacity")); + animation1.addAnimation(new QPropertyAnimation(p3, "opacity")); + animation1.addAnimation(new QPropertyAnimation(p4, "opacity")); + animation1.addAnimation(new QPropertyAnimation(p5, "opacity")); + animation1.addAnimation(new QPropertyAnimation(p6, "opacity")); + + QParallelAnimationGroup animation2; + animation2.addAnimation(new QPropertyAnimation(box, "geometry")); + animation2.addAnimation(new QPropertyAnimation(widget, "geometry")); + animation2.addAnimation(new QPropertyAnimation(p1, "geometry")); + animation2.addAnimation(new QPropertyAnimation(p2, "geometry")); + animation2.addAnimation(new QPropertyAnimation(p3, "geometry")); + animation2.addAnimation(new QPropertyAnimation(p4, "geometry")); + animation2.addAnimation(new QPropertyAnimation(p5, "geometry")); + animation2.addAnimation(new QPropertyAnimation(p6, "geometry")); + animation2.addAnimation(new QPropertyAnimation(p1, "zRotation")); + animation2.addAnimation(new QPropertyAnimation(p2, "zRotation")); + animation2.addAnimation(new QPropertyAnimation(p3, "zRotation")); + animation2.addAnimation(new QPropertyAnimation(p4, "zRotation")); + animation2.addAnimation(new QPropertyAnimation(p5, "zRotation")); + animation2.addAnimation(new QPropertyAnimation(p6, "zRotation")); + animation2.addAnimation(new QPropertyAnimation(p1, "opacity")); + animation2.addAnimation(new QPropertyAnimation(p2, "opacity")); + animation2.addAnimation(new QPropertyAnimation(p3, "opacity")); + animation2.addAnimation(new QPropertyAnimation(p4, "opacity")); + animation2.addAnimation(new QPropertyAnimation(p5, "opacity")); + animation2.addAnimation(new QPropertyAnimation(p6, "opacity")); + + QParallelAnimationGroup animation3; + animation3.addAnimation(new QPropertyAnimation(box, "geometry")); + animation3.addAnimation(new QPropertyAnimation(widget, "geometry")); + animation3.addAnimation(new QPropertyAnimation(p1, "geometry")); + animation3.addAnimation(new QPropertyAnimation(p2, "geometry")); + animation3.addAnimation(new QPropertyAnimation(p3, "geometry")); + animation3.addAnimation(new QPropertyAnimation(p4, "geometry")); + animation3.addAnimation(new QPropertyAnimation(p5, "geometry")); + animation3.addAnimation(new QPropertyAnimation(p6, "geometry")); + animation3.addAnimation(new QPropertyAnimation(p1, "zRotation")); + animation3.addAnimation(new QPropertyAnimation(p2, "zRotation")); + animation3.addAnimation(new QPropertyAnimation(p3, "zRotation")); + animation3.addAnimation(new QPropertyAnimation(p4, "zRotation")); + animation3.addAnimation(new QPropertyAnimation(p5, "zRotation")); + animation3.addAnimation(new QPropertyAnimation(p6, "zRotation")); + animation3.addAnimation(new QPropertyAnimation(p1, "opacity")); + animation3.addAnimation(new QPropertyAnimation(p2, "opacity")); + animation3.addAnimation(new QPropertyAnimation(p3, "opacity")); + animation3.addAnimation(new QPropertyAnimation(p4, "opacity")); + animation3.addAnimation(new QPropertyAnimation(p5, "opacity")); + animation3.addAnimation(new QPropertyAnimation(p6, "opacity")); + + QAbstractTransition *t1 = state1->addTransition(button, SIGNAL(clicked()), state2); + t1->addAnimation(&animation1); + QAbstractTransition *t2 = state2->addTransition(button, SIGNAL(clicked()), state3); + t2->addAnimation(&animation2); + QAbstractTransition *t3 = state3->addTransition(button, SIGNAL(clicked()), state1); + t3->addAnimation(&animation3); + + machine.start(); + + QGraphicsView view(&scene); + view.show(); + + return app.exec(); +} + +#include "main.moc" diff --git a/examples/animation/states/states.pro b/examples/animation/states/states.pro new file mode 100644 index 0000000..f4d1e0b --- /dev/null +++ b/examples/animation/states/states.pro @@ -0,0 +1,8 @@ +SOURCES += main.cpp +RESOURCES += states.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/states +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS states.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/states +INSTALLS += target sources diff --git a/examples/animation/states/states.qrc b/examples/animation/states/states.qrc new file mode 100644 index 0000000..60ab3f7 --- /dev/null +++ b/examples/animation/states/states.qrc @@ -0,0 +1,10 @@ + + + accessories-dictionary.png + akregator.png + digikam.png + help-browser.png + k3b.png + kchart.png + + diff --git a/examples/animation/stickman/animation.cpp b/examples/animation/stickman/animation.cpp new file mode 100644 index 0000000..c2c6bd1 --- /dev/null +++ b/examples/animation/stickman/animation.cpp @@ -0,0 +1,193 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "animation.h" + +#include +#include +#include + +class Frame +{ +public: + Frame() { + } + + int nodeCount() const + { + return m_nodePositions.size(); + } + + void setNodeCount(int nodeCount) + { + while (nodeCount > m_nodePositions.size()) + m_nodePositions.append(QPointF()); + + while (nodeCount < m_nodePositions.size()) + m_nodePositions.removeLast(); + } + + QPointF nodePos(int idx) const + { + return m_nodePositions.at(idx); + } + + void setNodePos(int idx, const QPointF &pos) + { + m_nodePositions[idx] = pos; + } + +private: + QList m_nodePositions; +}; + +Animation::Animation() +{ + m_currentFrame = 0; + m_frames.append(new Frame); +} + +Animation::~Animation() +{ + qDeleteAll(m_frames); +} + +void Animation::setTotalFrames(int totalFrames) +{ + while (m_frames.size() < totalFrames) + m_frames.append(new Frame); + + while (totalFrames < m_frames.size()) + delete m_frames.takeLast(); +} + +int Animation::totalFrames() const +{ + return m_frames.size(); +} + +void Animation::setCurrentFrame(int currentFrame) +{ + m_currentFrame = qMax(qMin(currentFrame, totalFrames()-1), 0); +} + +int Animation::currentFrame() const +{ + return m_currentFrame; +} + +void Animation::setNodeCount(int nodeCount) +{ + Frame *frame = m_frames.at(m_currentFrame); + frame->setNodeCount(nodeCount); +} + +int Animation::nodeCount() const +{ + Frame *frame = m_frames.at(m_currentFrame); + return frame->nodeCount(); +} + +void Animation::setNodePos(int idx, const QPointF &pos) +{ + Frame *frame = m_frames.at(m_currentFrame); + frame->setNodePos(idx, pos); +} + +QPointF Animation::nodePos(int idx) const +{ + Frame *frame = m_frames.at(m_currentFrame); + return frame->nodePos(idx); +} + +QString Animation::name() const +{ + return m_name; +} + +void Animation::setName(const QString &name) +{ + m_name = name; +} + +void Animation::save(QIODevice *device) const +{ + QDataStream stream(device); + stream << m_name; + stream << m_frames.size(); + foreach (Frame *frame, m_frames) { + stream << frame->nodeCount(); + for (int i=0; inodeCount(); ++i) + stream << frame->nodePos(i); + } +} + +void Animation::load(QIODevice *device) +{ + if (!m_frames.isEmpty()) + qDeleteAll(m_frames); + + m_frames.clear(); + + QDataStream stream(device); + stream >> m_name; + + int frameCount; + stream >> frameCount; + + for (int i=0; i> nodeCount; + + Frame *frame = new Frame; + frame->setNodeCount(nodeCount); + + for (int j=0; j> pos; + + frame->setNodePos(j, pos); + } + + m_frames.append(frame); + } +} diff --git a/examples/animation/stickman/animation.h b/examples/animation/stickman/animation.h new file mode 100644 index 0000000..b0b39c9 --- /dev/null +++ b/examples/animation/stickman/animation.h @@ -0,0 +1,83 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ANIMATION_H +#define ANIMATION_H + +#include +#include +#include + +class Frame; +QT_BEGIN_NAMESPACE +class QIODevice; +QT_END_NAMESPACE +class Animation +{ +public: + Animation(); + ~Animation(); + + void setTotalFrames(int totalFrames); + int totalFrames() const; + + void setCurrentFrame(int currentFrame); + int currentFrame() const; + + void setNodeCount(int nodeCount); + int nodeCount() const; + + void setNodePos(int idx, const QPointF &pos); + QPointF nodePos(int idx) const; + + QString name() const; + void setName(const QString &name); + + void save(QIODevice *device) const; + void load(QIODevice *device); + +private: + QString m_name; + QList m_frames; + int m_currentFrame; +}; + +#endif diff --git a/examples/animation/stickman/animations/chilling b/examples/animation/stickman/animations/chilling new file mode 100644 index 0000000..a81fc7a Binary files /dev/null and b/examples/animation/stickman/animations/chilling differ diff --git a/examples/animation/stickman/animations/dancing b/examples/animation/stickman/animations/dancing new file mode 100644 index 0000000..462f66f Binary files /dev/null and b/examples/animation/stickman/animations/dancing differ diff --git a/examples/animation/stickman/animations/dead b/examples/animation/stickman/animations/dead new file mode 100644 index 0000000..9859b4b Binary files /dev/null and b/examples/animation/stickman/animations/dead differ diff --git a/examples/animation/stickman/animations/jumping b/examples/animation/stickman/animations/jumping new file mode 100644 index 0000000..12661a1 Binary files /dev/null and b/examples/animation/stickman/animations/jumping differ diff --git a/examples/animation/stickman/editor/animationdialog.cpp b/examples/animation/stickman/editor/animationdialog.cpp new file mode 100644 index 0000000..441517d --- /dev/null +++ b/examples/animation/stickman/editor/animationdialog.cpp @@ -0,0 +1,192 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "animationdialog.h" +#include "stickman.h" +#include "animation.h" +#include "node.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +AnimationDialog::AnimationDialog(StickMan *stickman, QWidget *parent) + : QDialog(parent), m_animation(0), m_stickman(stickman) +{ + initUi(); +} + +AnimationDialog::~AnimationDialog() +{ + delete m_animation; +} + +void AnimationDialog::initUi() +{ + setWindowTitle("Animation"); + setEnabled(false); + + // Second page + m_currentFrame = new QSpinBox(); + m_totalFrames = new QSpinBox(); + m_name = new QLineEdit(); + + connect(m_currentFrame, SIGNAL(valueChanged(int)), this, SLOT(currentFrameChanged(int))); + connect(m_totalFrames, SIGNAL(valueChanged(int)), this, SLOT(totalFramesChanged(int))); + connect(m_name, SIGNAL(textChanged(QString)), this, SLOT(setCurrentAnimationName(QString))); + + QGridLayout *gridLayout = new QGridLayout(this); + gridLayout->addWidget(new QLabel("Name:"), 0, 0, 1, 2); + gridLayout->addWidget(m_name, 0, 2, 1, 2); + gridLayout->addWidget(new QLabel("Frame:"), 1, 0); + gridLayout->addWidget(m_currentFrame, 1, 1); + gridLayout->addWidget(new QLabel("of total # of frames: "), 1, 2); + gridLayout->addWidget(m_totalFrames, 1, 3); +} + +void AnimationDialog::initFromAnimation() +{ + m_currentFrame->setRange(0, m_animation->totalFrames()-1); + m_currentFrame->setValue(m_animation->currentFrame()); + + m_totalFrames->setRange(1, 1000); + m_totalFrames->setValue(m_animation->totalFrames()); + + m_name->setText(m_animation->name()); +} + +void AnimationDialog::saveAnimation() +{ + saveCurrentFrame(); + + QString fileName = QFileDialog::getSaveFileName(this, "Save animation"); + + QFile file(fileName); + if (file.open(QIODevice::WriteOnly)) + m_animation->save(&file); +} + +void AnimationDialog::loadAnimation() +{ + if (maybeSave() != QMessageBox::Cancel) { + QString fileName = QFileDialog::getOpenFileName(this, "Open animation"); + + QFile file(fileName); + if (file.open(QIODevice::ReadOnly)) { + if (m_animation == 0) + newAnimation(); + + m_animation->load(&file); + stickManFromCurrentFrame(); + initFromAnimation(); + } + } +} + +QMessageBox::StandardButton AnimationDialog::maybeSave() +{ + if (m_animation == 0) + return QMessageBox::No; + + QMessageBox::StandardButton button = QMessageBox::question(this, "Save?", "Do you want to save your changes?", + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + if (button == QMessageBox::Save) + saveAnimation(); + + return button; +} + +void AnimationDialog::newAnimation() +{ + if (maybeSave() != QMessageBox::Cancel) { + setEnabled(true); + delete m_animation; + m_animation = new Animation(); + initFromAnimation(); + } +} + +// Gets the data from the stickman and stores it in current frame +void AnimationDialog::saveCurrentFrame() +{ + int count = m_stickman->nodeCount(); + m_animation->setNodeCount(count); + for (int i=0; inode(i); + m_animation->setNodePos(i, node->pos()); + } +} + +// Gets the data from the current frame and sets the stickman +void AnimationDialog::stickManFromCurrentFrame() +{ + int count = m_animation->nodeCount(); + for (int i=0;inode(i); + node->setPos(m_animation->nodePos(i)); + } +} + +void AnimationDialog::currentFrameChanged(int currentFrame) +{ + saveCurrentFrame(); + qDebug("currentFrame: %d", currentFrame); + m_animation->setCurrentFrame(currentFrame); + stickManFromCurrentFrame(); + initFromAnimation(); +} + +void AnimationDialog::totalFramesChanged(int totalFrames) +{ + m_animation->setTotalFrames(totalFrames); + stickManFromCurrentFrame(); + initFromAnimation(); +} + +void AnimationDialog::setCurrentAnimationName(const QString &name) +{ + m_animation->setName(name); +} diff --git a/examples/animation/stickman/editor/animationdialog.h b/examples/animation/stickman/editor/animationdialog.h new file mode 100644 index 0000000..6025088 --- /dev/null +++ b/examples/animation/stickman/editor/animationdialog.h @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ANIMATIONDIALOG_H +#define ANIMATIONDIALOG_H + +#include +#include + +QT_BEGIN_NAMESPACE +class QSpinBox; +class QLineEdit; +QT_END_NAMESPACE +class StickMan; +class Animation; +class AnimationDialog: public QDialog +{ + Q_OBJECT +public: + AnimationDialog(StickMan *stickMan, QWidget *parent = 0); + ~AnimationDialog(); + +public slots: + void currentFrameChanged(int currentFrame); + void totalFramesChanged(int totalFrames); + void setCurrentAnimationName(const QString &name); + + void newAnimation(); + void saveAnimation(); + void loadAnimation(); + +private: + void saveCurrentFrame(); + void stickManFromCurrentFrame(); + void initFromAnimation(); + void initUi(); + QMessageBox::StandardButton maybeSave(); + + QSpinBox *m_currentFrame; + QSpinBox *m_totalFrames; + QLineEdit *m_name; + Animation *m_animation; + StickMan *m_stickman; +}; + +#endif diff --git a/examples/animation/stickman/editor/editor.pri b/examples/animation/stickman/editor/editor.pri new file mode 100644 index 0000000..7ad9edb --- /dev/null +++ b/examples/animation/stickman/editor/editor.pri @@ -0,0 +1,2 @@ +SOURCES += $$PWD/animationdialog.cpp $$PWD/mainwindow.cpp +HEADERS += $$PWD/animationdialog.h $$PWD/mainwindow.h diff --git a/examples/animation/stickman/editor/mainwindow.cpp b/examples/animation/stickman/editor/mainwindow.cpp new file mode 100644 index 0000000..c6464c6 --- /dev/null +++ b/examples/animation/stickman/editor/mainwindow.cpp @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mainwindow.h" +#include "animationdialog.h" +#include "stickman.h" + +#include +#include + +MainWindow::MainWindow(StickMan *stickMan) +{ + initActions(stickMan); +} + +MainWindow::~MainWindow() +{ +} + +void MainWindow::initActions(StickMan *stickMan) +{ + AnimationDialog *dialog = new AnimationDialog(stickMan, this); + dialog->show(); + + QMenu *fileMenu = menuBar()->addMenu("&File"); + QAction *loadAction = fileMenu->addAction("&Open"); + QAction *saveAction = fileMenu->addAction("&Save"); + QAction *exitAction = fileMenu->addAction("E&xit"); + + QMenu *animationMenu = menuBar()->addMenu("&Animation"); + QAction *newAnimationAction = animationMenu->addAction("&New animation"); + + connect(loadAction, SIGNAL(triggered()), dialog, SLOT(loadAnimation())); + connect(saveAction, SIGNAL(triggered()), dialog, SLOT(saveAnimation())); + connect(exitAction, SIGNAL(triggered()), QApplication::instance(), SLOT(quit())); + connect(newAnimationAction, SIGNAL(triggered()), dialog, SLOT(newAnimation())); + +} diff --git a/examples/animation/stickman/editor/mainwindow.h b/examples/animation/stickman/editor/mainwindow.h new file mode 100644 index 0000000..4c2b949 --- /dev/null +++ b/examples/animation/stickman/editor/mainwindow.h @@ -0,0 +1,58 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include + +class StickMan; +class MainWindow: public QMainWindow +{ +public: + MainWindow(StickMan *stickMan); + ~MainWindow(); + +private: + void initActions(StickMan *stickMan); +}; + +#endif diff --git a/examples/animation/stickman/graphicsview.cpp b/examples/animation/stickman/graphicsview.cpp new file mode 100644 index 0000000..754f3bc --- /dev/null +++ b/examples/animation/stickman/graphicsview.cpp @@ -0,0 +1,81 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "graphicsview.h" +#include "editor/mainwindow.h" +#include "stickman.h" + +#include +#include +#include + +GraphicsView::GraphicsView(QWidget *parent) : QGraphicsView(parent), m_editor(0) {} + +void GraphicsView::keyPressEvent(QKeyEvent *e) +{ + if (e->key() == Qt::Key_Escape) + close(); + +#if 0 + if (e->key() == Qt::Key_F1) { + if (m_editor == 0) { + QGraphicsScene *scene = new QGraphicsScene; + StickMan *stickMan = new StickMan; + stickMan->setDrawSticks(true); + scene->addItem(stickMan); + + QGraphicsView *view = new QGraphicsView; + view->setBackgroundBrush(Qt::black); + view->setRenderHints(QPainter::Antialiasing); + view->setScene(scene); + + m_editor = new MainWindow(stickMan); + m_editor->setCentralWidget(view); + } + + m_editor->showMaximized(); + } +#endif + + emit keyPressed(Qt::Key(e->key())); +} + + diff --git a/examples/animation/stickman/graphicsview.h b/examples/animation/stickman/graphicsview.h new file mode 100644 index 0000000..2515418 --- /dev/null +++ b/examples/animation/stickman/graphicsview.h @@ -0,0 +1,64 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GRAPHICSVIEW_H +#define GRAPHICSVIEW + +#include + +class MainWindow; +class GraphicsView: public QGraphicsView +{ + Q_OBJECT +public: + GraphicsView(QWidget *parent = 0); + +protected: + void keyPressEvent(QKeyEvent *); + +signals: + void keyPressed(int key); + +private: + MainWindow *m_editor; +}; + +#endif diff --git a/examples/animation/stickman/lifecycle.cpp b/examples/animation/stickman/lifecycle.cpp new file mode 100644 index 0000000..eb4ed11 --- /dev/null +++ b/examples/animation/stickman/lifecycle.cpp @@ -0,0 +1,212 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "lifecycle.h" +#include "stickman.h" +#include "node.h" +#include "animation.h" +#include "graphicsview.h" + +#include +#include + +class KeyPressTransition: public QSignalTransition +{ +public: + KeyPressTransition(GraphicsView *receiver, Qt::Key key) + : QSignalTransition(receiver, SIGNAL(keyPressed(int))), m_key(key) + { + } + KeyPressTransition(GraphicsView *receiver, Qt::Key key, QAbstractState *target) + : QSignalTransition(receiver, SIGNAL(keyPressed(int)), QList() << target), m_key(key) + { + } + + virtual bool eventTest(QEvent *e) + { + if (QSignalTransition::eventTest(e)) { + QVariant key = static_cast(e)->arguments().at(0); + return (key.toInt() == int(m_key)); + } + + return false; + } +private: + Qt::Key m_key; +}; + +//! [4] +class LightningStrikesTransition: public QEventTransition +{ +public: + LightningStrikesTransition(QAbstractState *target) + : QEventTransition(this, QEvent::Timer, QList() << target) + { + qsrand((uint)QDateTime::currentDateTime().toTime_t()); + startTimer(1000); + } + + virtual bool eventTest(QEvent *e) + { + return QEventTransition::eventTest(e) && ((qrand() % 50) == 0); + } +}; +//! [4] + +LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) + : m_stickMan(stickMan), m_keyReceiver(keyReceiver) +{ + // Create animation group to be used for all transitions + m_animationGroup = new QParallelAnimationGroup(); + const int stickManNodeCount = m_stickMan->nodeCount(); + for (int i=0; inode(i), "position"); + m_animationGroup->addAnimation(pa); + } + + // Set up intial state graph +//! [3] + m_machine = new QStateMachine(); + m_machine->addDefaultAnimation(m_animationGroup); +//! [3] + + m_alive = new QState(m_machine->rootState()); + m_alive->setObjectName("alive"); + + // Make it blink when lightning strikes before entering dead animation + QState *lightningBlink = new QState(m_machine->rootState()); + lightningBlink->assignProperty(m_stickMan->scene(), "backgroundBrush", Qt::white); + lightningBlink->assignProperty(m_stickMan, "penColor", Qt::black); + lightningBlink->assignProperty(m_stickMan, "fillColor", Qt::white); + lightningBlink->assignProperty(m_stickMan, "isDead", true); + +//! [5] + QTimer *timer = new QTimer(lightningBlink); + timer->setSingleShot(true); + timer->setInterval(100); + QObject::connect(lightningBlink, SIGNAL(entered()), timer, SLOT(start())); + QObject::connect(lightningBlink, SIGNAL(exited()), timer, SLOT(stop())); +//! [5] + + m_dead = new QState(m_machine->rootState()); + m_dead->assignProperty(m_stickMan->scene(), "backgroundBrush", Qt::black); + m_dead->assignProperty(m_stickMan, "penColor", Qt::white); + m_dead->assignProperty(m_stickMan, "fillColor", Qt::black); + m_dead->setObjectName("dead"); + + // Idle state (sets no properties) + m_idle = new QState(m_alive); + m_idle->setObjectName("idle"); + + m_alive->setInitialState(m_idle); + + // Lightning strikes at random + m_alive->addTransition(new LightningStrikesTransition(lightningBlink)); +//! [0] + lightningBlink->addTransition(timer, SIGNAL(timeout()), m_dead); +//! [0] + + m_machine->setInitialState(m_alive); +} + +void LifeCycle::setDeathAnimation(const QString &fileName) +{ + QState *deathAnimation = makeState(m_dead, fileName); + m_dead->setInitialState(deathAnimation); +} + +void LifeCycle::start() +{ + m_machine->start(); +} + +void LifeCycle::addActivity(const QString &fileName, Qt::Key key) +{ + QState *state = makeState(m_alive, fileName); + m_alive->addTransition(new KeyPressTransition(m_keyReceiver, key, state)); +} + +QState *LifeCycle::makeState(QState *parentState, const QString &animationFileName) +{ + QState *topLevel = new QState(parentState); + + Animation animation; + { + QFile file(animationFileName); + if (file.open(QIODevice::ReadOnly)) + animation.load(&file); + } + + const int frameCount = animation.totalFrames(); + QState *previousState = 0; + for (int i=0; iassignProperty(m_stickMan->node(j), "position", animation.nodePos(j)); +//! [1] + + frameState->setObjectName(QString::fromLatin1("frame %0").arg(i)); + if (previousState == 0) + topLevel->setInitialState(frameState); + else +//! [2] + previousState->addTransition(previousState, SIGNAL(polished()), frameState); +//! [2] + + previousState = frameState; + } + + // Loop + previousState->addTransition(previousState, SIGNAL(polished()), topLevel->initialState()); + + return topLevel; + +} + +LifeCycle::~LifeCycle() +{ + delete m_machine; + delete m_animationGroup; +} diff --git a/examples/animation/stickman/lifecycle.h b/examples/animation/stickman/lifecycle.h new file mode 100644 index 0000000..2be4762 --- /dev/null +++ b/examples/animation/stickman/lifecycle.h @@ -0,0 +1,80 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef LIFECYCLE_H +#define LIFECYCLE_H + +#include + +class StickMan; +QT_BEGIN_NAMESPACE +class QStateMachine; +class QAnimationGroup; +class QState; +class QAbstractState; +class QAbstractTransition; +QT_END_NAMESPACE +class GraphicsView; +class LifeCycle +{ +public: + LifeCycle(StickMan *stickMan, GraphicsView *keyEventReceiver); + ~LifeCycle(); + + void setDeathAnimation(const QString &fileName); + void addActivity(const QString &fileName, Qt::Key key); + + void start(); + +private: + QState *makeState(QState *parentState, const QString &animationFileName); + + StickMan *m_stickMan; + QStateMachine *m_machine; + QAnimationGroup *m_animationGroup; + GraphicsView *m_keyReceiver; + + QState *m_alive; + QState *m_dead; + QState *m_idle; +}; + +#endif diff --git a/examples/animation/stickman/main.cpp b/examples/animation/stickman/main.cpp new file mode 100644 index 0000000..62d8252 --- /dev/null +++ b/examples/animation/stickman/main.cpp @@ -0,0 +1,97 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "animation.h" +#include "node.h" +#include "lifecycle.h" +#include "stickman.h" +#include "graphicsview.h" + +#include +#include + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + StickMan *stickMan = new StickMan; + stickMan->setDrawSticks(false); + + QGraphicsTextItem *textItem = new QGraphicsTextItem(); + textItem->setHtml("Stickman" + "

" + "Tell the stickman what to do!" + "

" + "

" + "

  • Press J to make the stickman jump.
  • " + "
  • Press D to make the stickman dance.
  • " + "
  • Press C to make him chill out.
  • " + "
  • When you are done, press Escape.
  • " + "

    " + "

    If he is unlucky, the stickman will get struck by lightning, and never jump, dance or chill out again." + "

    "); + qreal w = textItem->boundingRect().width(); + QRectF stickManBoundingRect = stickMan->mapToScene(stickMan->boundingRect()).boundingRect(); + textItem->setPos(-w / 2.0, stickManBoundingRect.bottom() + 25.0); + + QGraphicsScene *scene = new QGraphicsScene(); + scene->addItem(stickMan); + scene->addItem(textItem); + scene->setBackgroundBrush(Qt::black); + + GraphicsView *view = new GraphicsView(); + view->setRenderHints(QPainter::Antialiasing); + view->setTransformationAnchor(QGraphicsView::NoAnchor); + view->setScene(scene); + view->showFullScreen(); + view->setFocus(); + view->setSceneRect(scene->sceneRect()); + + LifeCycle *cycle = new LifeCycle(stickMan, view); + cycle->setDeathAnimation("animations/dead"); + + cycle->addActivity("animations/jumping", Qt::Key_J); + cycle->addActivity("animations/dancing", Qt::Key_D); + cycle->addActivity("animations/chilling", Qt::Key_C); + cycle->start(); + + return app.exec(); +} diff --git a/examples/animation/stickman/node.cpp b/examples/animation/stickman/node.cpp new file mode 100644 index 0000000..9c485d9 --- /dev/null +++ b/examples/animation/stickman/node.cpp @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "node.h" +#include "stickman.h" + +#include +#include +#include + +Node::Node(const QPointF &pos, QGraphicsItem *parent) + : QGraphicsItem(parent), m_dragging(false) +{ + setPos(pos); +} + +Node::~Node() +{ +} + +QRectF Node::boundingRect() const +{ + return QRectF(-6.0, -6.0, 12.0, 12.0); +} + +void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + painter->setPen(Qt::white); + painter->drawEllipse(QPointF(0.0, 0.0), 5.0, 5.0); +} + +QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) +{ + if (change == QGraphicsItem::ItemPositionChange) + emit positionChanged(); + + return QGraphicsItem::itemChange(change, value); +} + +void Node::mousePressEvent(QGraphicsSceneMouseEvent *) +{ + m_dragging = true; +} + +void Node::mouseMoveEvent(QGraphicsSceneMouseEvent *event) +{ + if (m_dragging) + setPos(mapToParent(event->pos())); +} + +void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *) +{ + m_dragging = false; +} diff --git a/examples/animation/stickman/node.h b/examples/animation/stickman/node.h new file mode 100644 index 0000000..72eae87 --- /dev/null +++ b/examples/animation/stickman/node.h @@ -0,0 +1,72 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef NODE_H +#define NODE_H + +#include + +class Node: public QObject, public QGraphicsItem +{ + Q_OBJECT + Q_PROPERTY(QPointF position READ pos WRITE setPos); +public: + Node(const QPointF &pos, QGraphicsItem *parent = 0); + ~Node(); + + QRectF boundingRect() const; + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + +signals: + void positionChanged(); + +protected: + QVariant itemChange(GraphicsItemChange change, const QVariant &value); + + void mousePressEvent(QGraphicsSceneMouseEvent *); + void mouseMoveEvent(QGraphicsSceneMouseEvent *); + void mouseReleaseEvent(QGraphicsSceneMouseEvent *); + +private: + bool m_dragging; +}; + +#endif diff --git a/examples/animation/stickman/stickman.cpp b/examples/animation/stickman/stickman.cpp new file mode 100644 index 0000000..e00ea41 --- /dev/null +++ b/examples/animation/stickman/stickman.cpp @@ -0,0 +1,339 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "stickman.h" +#include "node.h" + +#include +#include + +#define _USE_MATH_DEFINES +#include + +static const int NodeCount = 16; +static const qreal Coords[NodeCount * 2] = { + 0.0, -150.0, // head, #0 + + 0.0, -100.0, // body pentagon, top->bottom, left->right, #1 - 5 + -50.0, -50.0, + 50.0, -50.0, + -25.0, 50.0, + 25.0, 50.0, + + -100.0, 0.0, // right arm, #6 - 7 + -125.0, 50.0, + + 100.0, 0.0, // left arm, #8 - 9 + 125.0, 50.0, + + -35.0, 75.0, // lower body, #10 - 11 + 35.0, 75.0, + + -25.0, 200.0, // right leg, #12 - 13 + -30.0, 300.0, + + 25.0, 200.0, // left leg, #14 - 15 + 30.0, 300.0 + +}; + +static const int BoneCount = 24; +static const int Bones[BoneCount * 2] = { + 0, 1, // neck + + 1, 2, // body + 1, 3, + 1, 4, + 1, 5, + 2, 3, + 2, 4, + 2, 5, + 3, 4, + 3, 5, + 4, 5, + + 2, 6, // right arm + 6, 7, + + 3, 8, // left arm + 8, 9, + + 4, 10, // lower body + 4, 11, + 5, 10, + 5, 11, + 10, 11, + + 10, 12, // right leg + 12, 13, + + 11, 14, // left leg + 14, 15 + +}; + +StickMan::StickMan() +{ + m_nodes = new Node*[NodeCount]; + m_sticks = true; + m_isDead = false; + m_pixmap = QPixmap("images/head.png"); + m_penColor = Qt::white; + m_fillColor = Qt::black; + + // Set up start position of limbs + for (int i=0; ipos() - node2->pos(); + m_perfectBoneLengths[i] = sqrt(pow(dist.x(),2) + pow(dist.y(),2)); + } + + startTimer(10); +} + +StickMan::~StickMan() +{ + delete m_nodes; +} + +void StickMan::childPositionChanged() +{ + prepareGeometryChange(); +} + +void StickMan::setDrawSticks(bool on) +{ + m_sticks = on; + for (int i=0;isetVisible(on); + } +} + +QRectF StickMan::boundingRect() const +{ + // account for head radius=50.0 plus pen which is 5.0 + return childrenBoundingRect().adjusted(-55.0, -55.0, 55.0, 55.0); +} + +int StickMan::nodeCount() const +{ + return NodeCount; +} + +Node *StickMan::node(int idx) const +{ + if (idx >= 0 && idx < NodeCount) + return m_nodes[idx]; + else + return 0; +} + +void StickMan::timerEvent(QTimerEvent *) +{ + update(); +} + +void StickMan::stabilize() +{ + static const qreal threshold = 0.001; + + for (int i=0; ipos(); + QPointF pos2 = node2->pos(); + + QPointF dist = pos1 - pos2; + qreal length = sqrt(pow(dist.x(),2) + pow(dist.y(),2)); + qreal diff = (length - m_perfectBoneLengths[i]) / length; + + QPointF p = dist * (0.5 * diff); + if (p.x() > threshold && p.y() > threshold) { + pos1 -= p; + pos2 += p; + + node1->setPos(pos1); + node2->setPos(pos2); + } + } +} + +QPointF StickMan::posFor(int idx) const +{ + return m_nodes[idx]->pos(); +} + +//#include +void StickMan::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + /* static int frames = 0; + static QTime time; + if (frames++ % 100 == 0) { + frames = 1; + time.restart(); + } + + if (time.elapsed() > 0) { + painter->setPen(Qt::white); + painter->drawText(0, 0, QString::number(frames / (time.elapsed() / 1000.0))); + }*/ + + stabilize(); + if (m_sticks) { + painter->setPen(Qt::white); + for (int i=0; idrawLine(node1->pos(), node2->pos()); + } + } else { + // first bone is neck and will be used for head + + QPainterPath path; + path.moveTo(posFor(0)); + path.lineTo(posFor(1)); + + // right arm + path.lineTo(posFor(2)); + path.lineTo(posFor(6)); + path.lineTo(posFor(7)); + + // left arm + path.moveTo(posFor(3)); + path.lineTo(posFor(8)); + path.lineTo(posFor(9)); + + // body + path.moveTo(posFor(2)); + path.lineTo(posFor(4)); + path.lineTo(posFor(10)); + path.lineTo(posFor(11)); + path.lineTo(posFor(5)); + path.lineTo(posFor(3)); + path.lineTo(posFor(1)); + + // right leg + path.moveTo(posFor(10)); + path.lineTo(posFor(12)); + path.lineTo(posFor(13)); + + // left leg + path.moveTo(posFor(11)); + path.lineTo(posFor(14)); + path.lineTo(posFor(15)); + + painter->setPen(QPen(m_penColor, 5.0, Qt::SolidLine, Qt::RoundCap)); + painter->drawPath(path); + + { + int n1 = Bones[0]; + int n2 = Bones[1]; + Node *node1 = m_nodes[n1]; + Node *node2 = m_nodes[n2]; + + QPointF dist = node2->pos() - node1->pos(); + + qreal sinAngle = dist.x() / sqrt(pow(dist.x(), 2) + pow(dist.y(), 2)); + qreal angle = asin(sinAngle) * 180.0 / M_PI; + + QPointF headPos = node1->pos(); + painter->translate(headPos); + painter->rotate(-angle); + + painter->setBrush(m_fillColor); + painter->drawEllipse(QPointF(0,0), 50.0, 50.0); + + painter->setBrush(m_penColor); + painter->setPen(QPen(m_penColor, 2.5, Qt::SolidLine, Qt::RoundCap)); + + // eyes + if (m_isDead) { + painter->drawLine(-30.0, -30.0, -20.0, -20.0); + painter->drawLine(-20.0, -30.0, -30.0, -20.0); + + painter->drawLine(20.0, -30.0, 30.0, -20.0); + painter->drawLine(30.0, -30.0, 20.0, -20.0); + } else { + painter->drawChord(QRectF(-30.0, -30.0, 25.0, 70.0), 30.0*16, 120.0*16); + painter->drawChord(QRectF(5.0, -30.0, 25.0, 70.0), 30.0*16, 120.0*16); + } + + // mouth + if (m_isDead) { + painter->drawLine(-28.0, 2.0, 29.0, 2.0); + } else { + painter->setBrush(QColor(128, 0, 64 )); + painter->drawChord(QRectF(-28.0, 2.0-55.0/2.0, 57.0, 55.0), 0.0, -180.0*16); + } + + // pupils + if (!m_isDead) { + painter->setPen(QPen(m_fillColor, 1.0, Qt::SolidLine, Qt::RoundCap)); + painter->setBrush(m_fillColor); + painter->drawEllipse(QPointF(-12.0, -25.0), 5.0, 5.0); + painter->drawEllipse(QPointF(22.0, -25.0), 5.0, 5.0); + } + } + } +} + + + diff --git a/examples/animation/stickman/stickman.h b/examples/animation/stickman/stickman.h new file mode 100644 index 0000000..6395272 --- /dev/null +++ b/examples/animation/stickman/stickman.h @@ -0,0 +1,103 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef STICKMAN_H +#define STICKMAN_H + +#include + +const int LimbCount = 16; + +class Node; +QT_BEGIN_NAMESPACE +class QTimer; +QT_END_NAMESPACE +class StickMan: public QObject, public QGraphicsItem +{ + Q_OBJECT + Q_PROPERTY(QColor penColor WRITE setPenColor READ penColor) + Q_PROPERTY(QColor fillColor WRITE setFillColor READ fillColor) + Q_PROPERTY(bool isDead WRITE setIsDead READ isDead) +public: + StickMan(); + ~StickMan(); + + virtual QRectF boundingRect() const; + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + + int nodeCount() const; + Node *node(int idx) const; + + void setDrawSticks(bool on); + bool drawSticks() const { return m_sticks; } + + QColor penColor() const { return m_penColor; } + void setPenColor(const QColor &color) { m_penColor = color; } + + QColor fillColor() const { return m_fillColor; } + void setFillColor(const QColor &color) { m_fillColor = color; } + + bool isDead() const { return m_isDead; } + void setIsDead(bool isDead) { m_isDead = isDead; } + +public slots: + void stabilize(); + void childPositionChanged(); + +protected: + void timerEvent(QTimerEvent *e); + +private: + QPointF posFor(int idx) const; + + Node **m_nodes; + qreal *m_perfectBoneLengths; + + uint m_sticks : 1; + uint m_isDead : 1; + uint m_reserved : 30; + + QPixmap m_pixmap; + QColor m_penColor; + QColor m_fillColor; +}; + +#endif // STICKMAN_H diff --git a/examples/animation/stickman/stickman.pro b/examples/animation/stickman/stickman.pro new file mode 100644 index 0000000..956b49c --- /dev/null +++ b/examples/animation/stickman/stickman.pro @@ -0,0 +1,19 @@ +HEADERS += stickman.h \ + animation.h \ + node.h \ + lifecycle.h \ + graphicsview.h +SOURCES += main.cpp \ + stickman.cpp \ + animation.cpp \ + node.cpp \ + lifecycle.cpp \ + graphicsview.cpp + +include(editor/editor.pri) + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/stickman +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS stickman.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/stickman +INSTALLS += target sources diff --git a/examples/animation/sub-attaq/animationmanager.cpp b/examples/animation/sub-attaq/animationmanager.cpp new file mode 100644 index 0000000..477d3bd --- /dev/null +++ b/examples/animation/sub-attaq/animationmanager.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "animationmanager.h" + +//Qt +#include +#include + +// the universe's only animation manager +AnimationManager *AnimationManager::instance = 0; + +AnimationManager::AnimationManager() +{ +} + +AnimationManager *AnimationManager::self() +{ + if (!instance) + instance = new AnimationManager; + return instance; +} + +void AnimationManager::registerAnimation(QAbstractAnimation *anim) +{ + animations.append(anim); +} + +void AnimationManager::unregisterAnimation(QAbstractAnimation *anim) +{ + animations.removeAll(anim); +} + +void AnimationManager::unregisterAllAnimations() +{ + animations.clear(); +} + +void AnimationManager::pauseAll() +{ + foreach (QAbstractAnimation* animation, animations) + { + if (animation->state() == QAbstractAnimation::Running) + animation->pause(); + } +} +void AnimationManager::resumeAll() +{ + foreach (QAbstractAnimation* animation, animations) + { + if (animation->state() == QAbstractAnimation::Paused) + animation->resume(); + } +} diff --git a/examples/animation/sub-attaq/animationmanager.h b/examples/animation/sub-attaq/animationmanager.h new file mode 100644 index 0000000..a563c96 --- /dev/null +++ b/examples/animation/sub-attaq/animationmanager.h @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ANIMATIONMANAGER_H +#define ANIMATIONMANAGER_H + +#include + +QT_BEGIN_NAMESPACE +class QAbstractAnimation; +QT_END_NAMESPACE + +class AnimationManager : public QObject +{ +Q_OBJECT +public: + AnimationManager(); + void registerAnimation(QAbstractAnimation *anim); + void unregisterAnimation(QAbstractAnimation *anim); + void unregisterAllAnimations(); + static AnimationManager *self(); + +public slots: + void pauseAll(); + void resumeAll(); + +private: + static AnimationManager *instance; + QList animations; +}; + +#endif // ANIMATIONMANAGER_H diff --git a/examples/animation/sub-attaq/boat.cpp b/examples/animation/sub-attaq/boat.cpp new file mode 100644 index 0000000..63d12bb --- /dev/null +++ b/examples/animation/sub-attaq/boat.cpp @@ -0,0 +1,318 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "boat.h" +#include "boat_p.h" +#include "bomb.h" +#include "pixmapitem.h" +#include "graphicsscene.h" +#include "animationmanager.h" +#include "custompropertyanimation.h" +#include "qanimationstate.h" + +//Qt +#include +#include +#include +#include +#include +#include + +static QAbstractAnimation *setupDestroyAnimation(Boat *boat) +{ + QSequentialAnimationGroup *group = new QSequentialAnimationGroup(boat); +#if QT_VERSION >=0x040500 + PixmapItem *step1 = new PixmapItem(QString("explosion/boat/step1"),GraphicsScene::Big, boat); + step1->setZValue(6); + PixmapItem *step2 = new PixmapItem(QString("explosion/boat/step2"),GraphicsScene::Big, boat); + step2->setZValue(6); + PixmapItem *step3 = new PixmapItem(QString("explosion/boat/step3"),GraphicsScene::Big, boat); + step3->setZValue(6); + PixmapItem *step4 = new PixmapItem(QString("explosion/boat/step4"),GraphicsScene::Big, boat); + step4->setZValue(6); + step1->setOpacity(0); + step2->setOpacity(0); + step3->setOpacity(0); + step4->setOpacity(0); + CustomPropertyAnimation *anim1 = new CustomPropertyAnimation(boat); + anim1->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim1->setDuration(100); + anim1->setEndValue(1); + CustomPropertyAnimation *anim2 = new CustomPropertyAnimation(boat); + anim2->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim2->setDuration(100); + anim2->setEndValue(1); + CustomPropertyAnimation *anim3 = new CustomPropertyAnimation(boat); + anim3->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim3->setDuration(100); + anim3->setEndValue(1); + CustomPropertyAnimation *anim4 = new CustomPropertyAnimation(boat); + anim4->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim4->setDuration(100); + anim4->setEndValue(1); + CustomPropertyAnimation *anim5 = new CustomPropertyAnimation(boat); + anim5->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim5->setDuration(100); + anim5->setEndValue(0); + CustomPropertyAnimation *anim6 = new CustomPropertyAnimation(boat); + anim6->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim6->setDuration(100); + anim6->setEndValue(0); + CustomPropertyAnimation *anim7 = new CustomPropertyAnimation(boat); + anim7->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim7->setDuration(100); + anim7->setEndValue(0); + CustomPropertyAnimation *anim8 = new CustomPropertyAnimation(boat); + anim8->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim8->setDuration(100); + anim8->setEndValue(0); + group->addAnimation(anim1); + group->addAnimation(anim2); + group->addAnimation(anim3); + group->addAnimation(anim4); + group->addAnimation(anim5); + group->addAnimation(anim6); + group->addAnimation(anim7); + group->addAnimation(anim8); +#else + // work around for a bug where we don't transition if the duration is zero. + QtPauseAnimation *anim = new QtPauseAnimation(group); + anim->setDuration(1); + group->addAnimation(anim); +#endif + AnimationManager::self()->registerAnimation(group); + return group; +} + + + +Boat::Boat(QGraphicsItem * parent, Qt::WindowFlags wFlags) + : QGraphicsWidget(parent,wFlags), speed(0), bombsAlreadyLaunched(0), direction(Boat::None), movementAnimation(0) +{ + pixmapItem = new PixmapItem(QString("boat"),GraphicsScene::Big, this); + setZValue(4); + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable); + resize(pixmapItem->boundingRect().size()); + + //The movement animation used to animate the boat + movementAnimation = new QPropertyAnimation(this, "pos"); + + //The movement animation used to animate the boat + destroyAnimation = setupDestroyAnimation(this); + + //We setup the state machien of the boat + machine = new QStateMachine(this); + QState *moving = new QState(machine->rootState()); + StopState *stopState = new StopState(this, moving); + machine->setInitialState(moving); + moving->setInitialState(stopState); + MoveStateRight *moveStateRight = new MoveStateRight(this, moving); + MoveStateLeft *moveStateLeft = new MoveStateLeft(this, moving); + LaunchStateRight *launchStateRight = new LaunchStateRight(this, machine->rootState()); + LaunchStateLeft *launchStateLeft = new LaunchStateLeft(this, machine->rootState()); + + //then setup the transitions for the rightMove state + KeyStopTransition *leftStopRight = new KeyStopTransition(this, QEvent::KeyPress, Qt::Key_Left); + leftStopRight->setTargetState(stopState); + KeyMoveTransition *leftMoveRight = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Left); + leftMoveRight->setTargetState(moveStateRight); + KeyMoveTransition *rightMoveRight = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); + rightMoveRight->setTargetState(moveStateRight); + KeyMoveTransition *rightMoveStop = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); + rightMoveStop->setTargetState(moveStateRight); + + //then setup the transitions for the leftMove state + KeyStopTransition *rightStopLeft = new KeyStopTransition(this, QEvent::KeyPress, Qt::Key_Right); + rightStopLeft->setTargetState(stopState); + KeyMoveTransition *rightMoveLeft = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); + rightMoveLeft->setTargetState(moveStateLeft); + KeyMoveTransition *leftMoveLeft = new KeyMoveTransition(this, QEvent::KeyPress,Qt::Key_Left); + leftMoveLeft->setTargetState(moveStateLeft); + KeyMoveTransition *leftMoveStop = new KeyMoveTransition(this, QEvent::KeyPress,Qt::Key_Left); + leftMoveStop->setTargetState(moveStateLeft); + + //We set up the right move state + moveStateRight->addTransition(leftStopRight); + moveStateRight->addTransition(leftMoveRight); + moveStateRight->addTransition(rightMoveRight); + stopState->addTransition(rightMoveStop); + + //We set up the left move state + moveStateLeft->addTransition(rightStopLeft); + moveStateLeft->addTransition(leftMoveLeft); + moveStateLeft->addTransition(rightMoveLeft); + stopState->addTransition(leftMoveStop); + + //The animation is finished, it means we reached the border of the screen, the boat is stopped so we move to the stop state + moveStateLeft->addTransition(movementAnimation, SIGNAL(finished()), stopState); + moveStateRight->addTransition(movementAnimation, SIGNAL(finished()), stopState); + + //We set up the keys for dropping bombs + KeyLaunchTransition *upFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); + upFireLeft->setTargetState(launchStateRight); + KeyLaunchTransition *upFireRight = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); + upFireRight->setTargetState(launchStateRight); + KeyLaunchTransition *upFireStop = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); + upFireStop->setTargetState(launchStateRight); + KeyLaunchTransition *downFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); + downFireLeft->setTargetState(launchStateLeft); + KeyLaunchTransition *downFireRight = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); + downFireRight->setTargetState(launchStateLeft); + KeyLaunchTransition *downFireMove = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); + downFireMove->setTargetState(launchStateLeft); + + //We set up transitions for fire up + moveStateRight->addTransition(upFireRight); + moveStateLeft->addTransition(upFireLeft); + stopState->addTransition(upFireStop); + + //We set up transitions for fire down + moveStateRight->addTransition(downFireRight); + moveStateLeft->addTransition(downFireLeft); + stopState->addTransition(downFireMove); + + //Finally the launch state should come back to its original state + QHistoryState *historyState = new QHistoryState(moving); + launchStateLeft->addTransition(historyState); + launchStateRight->addTransition(historyState); + + QFinalState *final = new QFinalState(machine->rootState()); + + //This state play the destroyed animation + QAnimationState *destroyedState = new QAnimationState(machine->rootState()); + destroyedState->setAnimation(destroyAnimation); + + //Play a nice animation when the boat is destroyed + moving->addTransition(this, SIGNAL(boatDestroyed()),destroyedState); + + //Transition to final state when the destroyed animation is finished + destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); + + //The machine has finished to be executed, then the boat is dead + connect(machine,SIGNAL(finished()),this, SIGNAL(boatExecutionFinished())); + +} + +void Boat::run() +{ + //We register animations + AnimationManager::self()->registerAnimation(movementAnimation); + AnimationManager::self()->registerAnimation(destroyAnimation); + machine->start(); +} + +void Boat::stop() +{ + movementAnimation->stop(); + machine->stop(); +} + +void Boat::updateBoatMovement() +{ + if (speed == 0 || direction == Boat::None) { + movementAnimation->stop(); + return; + } + + movementAnimation->stop(); + movementAnimation->setStartValue(pos()); + + if (direction == Boat::Left) { + movementAnimation->setEndValue(QPointF(0,y())); + movementAnimation->setDuration(x()/speed*15); + } + else /*if (direction == Boat::Right)*/ { + movementAnimation->setEndValue(QPointF(scene()->width()-size().width(),y())); + movementAnimation->setDuration((scene()->width()-size().width()-x())/speed*15); + } + movementAnimation->start(); +} + +void Boat::destroy() +{ + movementAnimation->stop(); + emit boatDestroyed(); +} + +int Boat::bombsLaunched() const +{ + return bombsAlreadyLaunched; +} + +void Boat::setBombsLaunched(int number) +{ + if (number > MAX_BOMB) { + qWarning("Boat::setBombsLaunched : It impossible to launch that number of bombs"); + return; + } + bombsAlreadyLaunched = number; +} + +int Boat::currentSpeed() const +{ + return speed; +} + +void Boat::setCurrentSpeed(int speed) +{ + if (speed > 3 || speed < 0) { + qWarning("Boat::setCurrentSpeed: The boat can't run on that speed"); + return; + } + this->speed = speed; +} + +enum Boat::Movement Boat::currentDirection() const +{ + return direction; +} + +void Boat::setCurrentDirection(Movement direction) +{ + this->direction = direction; +} + +int Boat::type() const +{ + return Type; +} diff --git a/examples/animation/sub-attaq/boat.h b/examples/animation/sub-attaq/boat.h new file mode 100644 index 0000000..08a9fa2 --- /dev/null +++ b/examples/animation/sub-attaq/boat.h @@ -0,0 +1,102 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __BOAT__H__ +#define __BOAT__H__ + +//Qt +#include +#include + +#include + +class PixmapItem; +class Bomb; +QT_BEGIN_NAMESPACE +class QVariantAnimation; +class QAbstractAnimation; +class QStateMachine; +QT_END_NAMESPACE + +class Boat : public QGraphicsWidget +{ +Q_OBJECT +Q_PROPERTY(QPointF pos READ pos WRITE setPos) +public: + enum Movement { + None = 0, + Left, + Right + }; + enum { Type = UserType + 2 }; + Boat(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); + void destroy(); + void run(); + void stop(); + + int bombsLaunched() const; + void setBombsLaunched(int number); + + int currentSpeed() const; + void setCurrentSpeed(int speed); + + enum Movement currentDirection() const; + void setCurrentDirection(Movement direction); + + void updateBoatMovement(); + + virtual int type() const; + +Q_SIGNALS: + void boatDestroyed(); + void boatExecutionFinished(); + +private: + int speed; + int bombsAlreadyLaunched; + Movement direction; + QVariantAnimation *movementAnimation; + QAbstractAnimation *destroyAnimation; + QStateMachine *machine; + PixmapItem *pixmapItem; +}; + +#endif //__BOAT__H__ diff --git a/examples/animation/sub-attaq/boat_p.h b/examples/animation/sub-attaq/boat_p.h new file mode 100644 index 0000000..a8a24a6 --- /dev/null +++ b/examples/animation/sub-attaq/boat_p.h @@ -0,0 +1,256 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef BOAT_P_H +#define BOAT_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +//Own +#include "bomb.h" +#include "graphicsscene.h" + +// Qt +#include + +static const int MAX_BOMB = 5; + + +//These transtion test if we have to stop the boat (i.e current speed is 1) +class KeyStopTransition : public QKeyEventTransition +{ +public: + KeyStopTransition(Boat *boat, QEvent::Type type, int key) + : QKeyEventTransition(boat, type, key) + { + this->boat = boat; + this->key = key; + } +protected: + virtual bool eventTest(QEvent *event) + { + Q_UNUSED(event); + if (!QKeyEventTransition::eventTest(event)) + return false; + if (boat->currentSpeed() == 1) + return true; + else + return false; + } +private: + Boat * boat; + int key; +}; + +//These transtion test if we have to move the boat (i.e current speed was 0 or another value) + class KeyMoveTransition : public QKeyEventTransition +{ +public: + KeyMoveTransition(Boat *boat, QEvent::Type type, int key) + : QKeyEventTransition(boat, type, key) + { + this->boat = boat; + this->key = key; + } +protected: + virtual bool eventTest(QEvent *event) + { + Q_UNUSED(event); + if (!QKeyEventTransition::eventTest(event)) + return false; + if (boat->currentSpeed() >= 0) + return true; + else + return false; + + } + void onTransition(QEvent *) + { + //We decrease the speed if needed + if (key == Qt::Key_Left && boat->currentDirection() == Boat::Right) + boat->setCurrentSpeed(boat->currentSpeed() - 1); + else if (key == Qt::Key_Right && boat->currentDirection() == Boat::Left) + boat->setCurrentSpeed(boat->currentSpeed() - 1); + else if (boat->currentSpeed() < 3) + boat->setCurrentSpeed(boat->currentSpeed() + 1); + boat->updateBoatMovement(); + } +private: + Boat * boat; + int key; +}; + +//This transition trigger the bombs launch + class KeyLaunchTransition : public QKeyEventTransition +{ +public: + KeyLaunchTransition(Boat *boat, QEvent::Type type, int key) + : QKeyEventTransition(boat, type, key) + { + this->boat = boat; + this->key = key; + } +protected: + virtual bool eventTest(QEvent *event) + { + Q_UNUSED(event); + if (!QKeyEventTransition::eventTest(event)) + return false; + //We have enough bomb? + if (boat->bombsLaunched() < MAX_BOMB) + return true; + else + return false; + } +private: + Boat * boat; + int key; +}; + +//This state is describing when the boat is moving right +class MoveStateRight : public QState +{ +public: + MoveStateRight(Boat *boat,QState *parent = 0) : QState(parent) + { + this->boat = boat; + } +protected: + void onEntry(QEvent *) + { + boat->setCurrentDirection(Boat::Right); + boat->updateBoatMovement(); + } +private: + Boat * boat; +}; + + //This state is describing when the boat is moving left +class MoveStateLeft : public QState +{ +public: + MoveStateLeft(Boat *boat,QState *parent = 0) : QState(parent) + { + this->boat = boat; + } +protected: + void onEntry(QEvent *) + { + boat->setCurrentDirection(Boat::Left); + boat->updateBoatMovement(); + } +private: + Boat * boat; +}; + +//This state is describing when the boat is in a stand by position +class StopState : public QState +{ +public: + StopState(Boat *boat,QState *parent = 0) : QState(parent) + { + this->boat = boat; + } +protected: + void onEntry(QEvent *) + { + boat->setCurrentSpeed(0); + boat->setCurrentDirection(Boat::None); + boat->updateBoatMovement(); + } +private: + Boat * boat; +}; + +//This state is describing the launch of the torpedo on the right +class LaunchStateRight : public QState +{ +public: + LaunchStateRight(Boat *boat,QState *parent = 0) : QState(parent) + { + this->boat = boat; + } +protected: + void onEntry(QEvent *) + { + Bomb *b = new Bomb(); + b->setPos(boat->x()+boat->size().width(),boat->y()); + GraphicsScene *scene = static_cast(boat->scene()); + scene->addItem(b); + b->launch(Bomb::Right); + boat->setBombsLaunched(boat->bombsLaunched() + 1); + } +private: + Boat * boat; +}; + +//This state is describing the launch of the torpedo on the left +class LaunchStateLeft : public QState +{ +public: + LaunchStateLeft(Boat *boat,QState *parent = 0) : QState(parent) + { + this->boat = boat; + } +protected: + void onEntry(QEvent *) + { + Bomb *b = new Bomb(); + b->setPos(boat->x() - b->size().width(), boat->y()); + GraphicsScene *scene = static_cast(boat->scene()); + scene->addItem(b); + b->launch(Bomb::Left); + boat->setBombsLaunched(boat->bombsLaunched() + 1); + } +private: + Boat * boat; +}; + +#endif // BOAT_P_H diff --git a/examples/animation/sub-attaq/bomb.cpp b/examples/animation/sub-attaq/bomb.cpp new file mode 100644 index 0000000..f1f5324 --- /dev/null +++ b/examples/animation/sub-attaq/bomb.cpp @@ -0,0 +1,124 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "bomb.h" +#include "submarine.h" +#include "pixmapitem.h" +#include "animationmanager.h" +#include "qanimationstate.h" + +//Qt +#include +#include +#include +#include + +Bomb::Bomb(QGraphicsItem * parent, Qt::WindowFlags wFlags) + : QGraphicsWidget(parent,wFlags), launchAnimation(0) +{ + pixmapItem = new PixmapItem(QString("bomb"),GraphicsScene::Big, this); + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + setFlags(QGraphicsItem::ItemIsMovable); + setZValue(2); + resize(pixmapItem->boundingRect().size()); +} + +void Bomb::launch(Bomb::Direction direction) +{ + launchAnimation = new QSequentialAnimationGroup(); + AnimationManager::self()->registerAnimation(launchAnimation); + qreal delta = direction == Right ? 20 : - 20; + QPropertyAnimation *anim = new QPropertyAnimation(this, "pos"); + anim->setEndValue(QPointF(x() + delta,y() - 20)); + anim->setDuration(150); + launchAnimation->addAnimation(anim); + anim = new QPropertyAnimation(this, "pos"); + anim->setEndValue(QPointF(x() + delta*2, y() )); + anim->setDuration(150); + launchAnimation->addAnimation(anim); + anim = new QPropertyAnimation(this, "pos"); + anim->setEndValue(QPointF(x() + delta*2,scene()->height())); + anim->setDuration(y()/2*60); + launchAnimation->addAnimation(anim); + connect(anim,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationLaunchValueChanged(const QVariant &))); + + //We setup the state machine of the bomb + QStateMachine *machine = new QStateMachine(this); + + //This state is when the launch animation is playing + QAnimationState *launched = new QAnimationState(machine->rootState()); + launched->setAnimation(launchAnimation); + + //End + QFinalState *final = new QFinalState(machine->rootState()); + + machine->setInitialState(launched); + + //### Add a nice animation when the bomb is destroyed + launched->addTransition(this, SIGNAL(bombExplosed()),final); + + //If the animation is finished, then we move to the final state + launched->addTransition(launched, SIGNAL(animationFinished()), final); + + //The machine has finished to be executed, then the boat is dead + connect(machine,SIGNAL(finished()),this, SIGNAL(bombExecutionFinished())); + + machine->start(); + +} + +void Bomb::onAnimationLaunchValueChanged(const QVariant &) +{ + foreach (QGraphicsItem * item , collidingItems(Qt::IntersectsItemBoundingRect)) { + if (item->type() == SubMarine::Type) { + SubMarine *s = static_cast(item); + destroy(); + s->destroy(); + } + } +} + +void Bomb::destroy() +{ + launchAnimation->stop(); + emit bombExplosed(); +} diff --git a/examples/animation/sub-attaq/bomb.h b/examples/animation/sub-attaq/bomb.h new file mode 100644 index 0000000..226d056 --- /dev/null +++ b/examples/animation/sub-attaq/bomb.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __BOMB__H__ +#define __BOMB__H__ + +//Qt +#include +#include + +class PixmapItem; + +class Bomb : public QGraphicsWidget +{ +Q_OBJECT +Q_PROPERTY(QPointF pos READ pos WRITE setPos) +public: + enum Direction { + Left = 0, + Right + }; + Bomb(QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0); + void launch(Direction direction); + void destroy(); + +Q_SIGNALS: + void bombExplosed(); + void bombExecutionFinished(); + +private slots: + void onAnimationLaunchValueChanged(const QVariant &); + +private: + QAnimationGroup *launchAnimation; + PixmapItem *pixmapItem; +}; + +#endif //__BOMB__H__ diff --git a/examples/animation/sub-attaq/custompropertyanimation.cpp b/examples/animation/sub-attaq/custompropertyanimation.cpp new file mode 100644 index 0000000..8226cca --- /dev/null +++ b/examples/animation/sub-attaq/custompropertyanimation.cpp @@ -0,0 +1,108 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "custompropertyanimation.h" + +// Qt +#include + +CustomPropertyAnimation::CustomPropertyAnimation(QObject *parent) : + QVariantAnimation(parent), animProp(0) +{ +} + +CustomPropertyAnimation::~CustomPropertyAnimation() +{ +} + +void CustomPropertyAnimation::setProperty(AbstractProperty *_animProp) +{ + if (animProp == _animProp) + return; + delete animProp; + animProp = _animProp; +} + +/*! + \reimp + */ +void CustomPropertyAnimation::updateCurrentValue(const QVariant &value) +{ + if (!animProp || state() == QAbstractAnimation::Stopped) + return; + + animProp->write(value); +} + + +/*! + \reimp +*/ +void CustomPropertyAnimation::updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState) +{ + // Initialize start value + if (oldState == QAbstractAnimation::Stopped) { + if (!animProp) + return; + QVariant def = animProp->read(); + if (def.isValid()) { + const int t = def.userType(); + KeyValues values = keyValues(); + //this ensures that all the keyValues are of type t + for (int i = 0; i < values.count(); ++i) { + QVariantAnimation::KeyValue &pair = values[i]; + if (pair.second.userType() != t) + pair.second.convert(static_cast(t)); + } + //let's now update the key values + setKeyValues(values); + } + + if (animProp && !startValue().isValid() && currentTime() == 0 + || (currentTime() == duration() && currentLoop() == (loopCount() - 1))) { + setStartValue(def); + } + } + + QVariantAnimation::updateState(oldState, newState); +} + +#include "moc_custompropertyanimation.cpp" diff --git a/examples/animation/sub-attaq/custompropertyanimation.h b/examples/animation/sub-attaq/custompropertyanimation.h new file mode 100644 index 0000000..8654aeb --- /dev/null +++ b/examples/animation/sub-attaq/custompropertyanimation.h @@ -0,0 +1,114 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef CUSTOMPROPERTYANIMATION_H +#define CUSTOMPROPERTYANIMATION_H + +#include + +QT_BEGIN_NAMESPACE +class QGraphicsItem; +QT_END_NAMESPACE + +struct AbstractProperty +{ + virtual QVariant read() const = 0; + virtual void write(const QVariant &value) = 0; +}; + + +class CustomPropertyAnimation : public QVariantAnimation +{ + Q_OBJECT + + template + class MemberFunctionProperty : public AbstractProperty + { + public: + typedef T (Target::*Getter)(void) const; + typedef void (Target::*Setter)(T2); + + MemberFunctionProperty(Target* target, Getter getter, Setter setter) + : m_target(target), m_getter(getter), m_setter(setter) {} + + virtual void write(const QVariant &value) + { + if (m_setter) (m_target->*m_setter)(qVariantValue(value)); + } + + virtual QVariant read() const + { + if (m_getter) return qVariantFromValue((m_target->*m_getter)()); + return QVariant(); + } + + private: + Target *m_target; + Getter m_getter; + Setter m_setter; + }; + +public: + CustomPropertyAnimation(QObject *parent = 0); + ~CustomPropertyAnimation(); + + template + void setMemberFunctions(Target* target, T (Target::*getter)() const, void (Target::*setter)(const T& )) + { + setProperty(new MemberFunctionProperty(target, getter, setter)); + } + + template + void setMemberFunctions(Target* target, T (Target::*getter)() const, void (Target::*setter)(T)) + { + setProperty(new MemberFunctionProperty(target, getter, setter)); + } + + void updateCurrentValue(const QVariant &value); + void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); + void setProperty(AbstractProperty *animProp); + +private: + Q_DISABLE_COPY(CustomPropertyAnimation); + AbstractProperty *animProp; +}; + +#endif // CUSTOMPROPERTYANIMATION_H diff --git a/examples/animation/sub-attaq/data.xml b/examples/animation/sub-attaq/data.xml new file mode 100644 index 0000000..41d4754 --- /dev/null +++ b/examples/animation/sub-attaq/data.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/graphicsscene.cpp b/examples/animation/sub-attaq/graphicsscene.cpp new file mode 100644 index 0000000..f2d41bc --- /dev/null +++ b/examples/animation/sub-attaq/graphicsscene.cpp @@ -0,0 +1,374 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "graphicsscene.h" +#include "states.h" +#include "boat.h" +#include "submarine.h" +#include "torpedo.h" +#include "bomb.h" +#include "pixmapitem.h" +#include "custompropertyanimation.h" +#include "animationmanager.h" +#include "qanimationstate.h" +#include "progressitem.h" + +//Qt +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//helper function that creates an animation for position and inserts it into group +static CustomPropertyAnimation *addGraphicsItemPosAnimation(QSequentialAnimationGroup *group, + QGraphicsItem *item, const QPointF &endPos) +{ + CustomPropertyAnimation *ret = new CustomPropertyAnimation(group); + ret->setMemberFunctions(item, &QGraphicsItem::pos, &QGraphicsItem::setPos); + ret->setEndValue(endPos); + ret->setDuration(200); + ret->setEasingCurve(QEasingCurve::OutElastic); + group->addPause(50); + return ret; +} + +//helper function that creates an animation for opacity and inserts it into group +static void addGraphicsItemFadeoutAnimation(QAnimationGroup *group, QGraphicsItem *item) +{ +#if QT_VERSION >=0x040500 + CustomPropertyAnimation *anim = new CustomPropertyAnimation(group); + anim->setMemberFunctions(item, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim->setDuration(800); + anim->setEndValue(0); + anim->setEasingCurve(QEasingCurve::OutQuad); +#else + // work around for a bug where we don't transition if the duration is zero. + QtPauseAnimation *anim = new QtPauseAnimation(group); + anim->setDuration(1); +#endif +} + +GraphicsScene::GraphicsScene(int x, int y, int width, int height, Mode mode) + : QGraphicsScene(x,y,width,height), mode(mode), newAction(0), quitAction(0), boat(0) +{ + backgroundItem = new PixmapItem(QString("background"),mode); + backgroundItem->setZValue(1); + backgroundItem->setPos(0,0); + addItem(backgroundItem); + + PixmapItem *surfaceItem = new PixmapItem(QString("surface"),mode); + surfaceItem->setZValue(3); + surfaceItem->setPos(0,sealLevel() - surfaceItem->boundingRect().height()/2); + addItem(surfaceItem); + + //The item that display score and level + progressItem = new ProgressItem(backgroundItem); + + //We create the boat + boat = new Boat(); + addItem(boat); + boat->setPos(this->width()/2, sealLevel() - boat->size().height()); + boat->hide(); + + //parse the xml that contain all data of the game + QXmlStreamReader reader; + QFile file(QDir::currentPath() + "/data.xml"); + file.open(QIODevice::ReadOnly); + reader.setDevice(&file); + LevelDescription currentLevel; + while (!reader.atEnd()) { + reader.readNext(); + if (reader.tokenType() == QXmlStreamReader::StartElement) { + if (reader.name() == "submarine") + { + SubmarineDescription desc; + desc.name = reader.attributes().value("name").toString(); + desc.points = reader.attributes().value("points").toString().toInt(); + desc.type = reader.attributes().value("type").toString().toInt(); + submarinesData.append(desc); + } + if (reader.name() == "level") + { + currentLevel.id = reader.attributes().value("id").toString().toInt(); + currentLevel.name = reader.attributes().value("name").toString(); + } + if (reader.name() == "subinstance") + { + currentLevel.submarines.append(qMakePair(reader.attributes().value("type").toString().toInt(),reader.attributes().value("nb").toString().toInt())); + } + } + if (reader.tokenType() == QXmlStreamReader::EndElement) { + if (reader.name() == "level") + { + levelsData.insert(currentLevel.id,currentLevel); + currentLevel.submarines.clear(); + } + } + } +} + +qreal GraphicsScene::sealLevel() const +{ + if (mode == Big) + return 220; + else + return 160; +} + +void GraphicsScene::setupScene(const QList &actions) +{ + newAction = actions.at(0); + quitAction = actions.at(1); + + QGraphicsItem *logo_s = addWelcomeItem(QPixmap(":/logo-s")); + QGraphicsItem *logo_u = addWelcomeItem(QPixmap(":/logo-u")); + QGraphicsItem *logo_b = addWelcomeItem(QPixmap(":/logo-b")); + QGraphicsItem *logo_dash = addWelcomeItem(QPixmap(":/logo-dash")); + QGraphicsItem *logo_a = addWelcomeItem(QPixmap(":/logo-a")); + QGraphicsItem *logo_t = addWelcomeItem(QPixmap(":/logo-t")); + QGraphicsItem *logo_t2 = addWelcomeItem(QPixmap(":/logo-t2")); + QGraphicsItem *logo_a2 = addWelcomeItem(QPixmap(":/logo-a2")); + QGraphicsItem *logo_q = addWelcomeItem(QPixmap(":/logo-q")); + QGraphicsItem *logo_excl = addWelcomeItem(QPixmap(":/logo-excl")); + logo_s->setZValue(3); + logo_u->setZValue(4); + logo_b->setZValue(5); + logo_dash->setZValue(6); + logo_a->setZValue(7); + logo_t->setZValue(8); + logo_t2->setZValue(9); + logo_a2->setZValue(10); + logo_q->setZValue(11); + logo_excl->setZValue(12); + logo_s->setPos(QPointF(-1000, -1000)); + logo_u->setPos(QPointF(-800, -1000)); + logo_b->setPos(QPointF(-600, -1000)); + logo_dash->setPos(QPointF(-400, -1000)); + logo_a->setPos(QPointF(1000, 2000)); + logo_t->setPos(QPointF(800, 2000)); + logo_t2->setPos(QPointF(600, 2000)); + logo_a2->setPos(QPointF(400, 2000)); + logo_q->setPos(QPointF(200, 2000)); + logo_excl->setPos(QPointF(0, 2000)); + + QSequentialAnimationGroup * lettersGroupMoving = new QSequentialAnimationGroup(this); + QParallelAnimationGroup * lettersGroupFading = new QParallelAnimationGroup(this); + + //creation of the animations for moving letters + addGraphicsItemPosAnimation(lettersGroupMoving, logo_s, QPointF(300, 150)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_u, QPointF(350, 150)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_b, QPointF(400, 120)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_dash, QPointF(460, 150)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_a, QPointF(350, 250)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_t, QPointF(400, 250)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_t2, QPointF(430, 250)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_a2, QPointF(465, 250)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_q, QPointF(510, 250)); + addGraphicsItemPosAnimation(lettersGroupMoving, logo_excl, QPointF(570, 220)); + + //creation of the animations for fading out the letters + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_s); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_u); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_b); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_dash); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_a); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_t); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_t2); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_a2); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_q); + addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_excl); + connect(lettersGroupFading, SIGNAL(finished()), this, SLOT(onIntroAnimationFinished())); + + QStateMachine *machine = new QStateMachine(this); + + //This state is when the player is playing + PlayState *gameState = new PlayState(this,machine->rootState()); + + //Final state + QFinalState *final = new QFinalState(machine->rootState()); + + //Animation when the player enter in the game + QAnimationState *lettersMovingState = new QAnimationState(machine->rootState()); + lettersMovingState->setAnimation(lettersGroupMoving); + + //Animation when the welcome screen disappear + QAnimationState *lettersFadingState = new QAnimationState(machine->rootState()); + lettersFadingState->setAnimation(lettersGroupFading); + + //if new game then we fade out the welcome screen and start playing + lettersMovingState->addTransition(newAction, SIGNAL(triggered()),lettersFadingState); + lettersFadingState->addTransition(lettersFadingState, SIGNAL(animationFinished()),gameState); + + //New Game is triggered then player start playing + gameState->addTransition(newAction, SIGNAL(triggered()),gameState); + + //Wanna quit, then connect to CTRL+Q + gameState->addTransition(quitAction, SIGNAL(triggered()),final); + lettersMovingState->addTransition(quitAction, SIGNAL(triggered()),final); + + //Welcome screen is the initial state + machine->setInitialState(lettersMovingState); + + machine->start(); + + //We reach the final state, then we quit + connect(machine,SIGNAL(finished()),this, SLOT(onQuitGameTriggered())); +} + +void GraphicsScene::addItem(Bomb *bomb) +{ + bombs.insert(bomb); + connect(bomb,SIGNAL(bombExecutionFinished()),this, SLOT(onBombExecutionFinished())); + QGraphicsScene::addItem(bomb); +} + +void GraphicsScene::addItem(Torpedo *torpedo) +{ + torpedos.insert(torpedo); + connect(torpedo,SIGNAL(torpedoExecutionFinished()),this, SLOT(onTorpedoExecutionFinished())); + QGraphicsScene::addItem(torpedo); +} + +void GraphicsScene::addItem(SubMarine *submarine) +{ + submarines.insert(submarine); + connect(submarine,SIGNAL(subMarineExecutionFinished()),this, SLOT(onSubMarineExecutionFinished())); + QGraphicsScene::addItem(submarine); +} + +void GraphicsScene::addItem(QGraphicsItem *item) +{ + QGraphicsScene::addItem(item); +} + +void GraphicsScene::mousePressEvent (QGraphicsSceneMouseEvent * event) +{ + event->ignore(); +} + +void GraphicsScene::onQuitGameTriggered() +{ + qApp->closeAllWindows(); +} + +void GraphicsScene::onBombExecutionFinished() +{ + Bomb *bomb = qobject_cast(sender()); + bombs.remove(bomb); + bomb->deleteLater(); + if (boat) + boat->setBombsLaunched(boat->bombsLaunched() - 1); +} + +void GraphicsScene::onTorpedoExecutionFinished() +{ + Torpedo *torpedo = qobject_cast(sender()); + torpedos.remove(torpedo); + torpedo->deleteLater(); +} + +void GraphicsScene::onSubMarineExecutionFinished() +{ + SubMarine *submarine = qobject_cast(sender()); + submarines.remove(submarine); + if (submarines.count() == 0) { + emit allSubMarineDestroyed(submarine->points()); + } else { + emit subMarineDestroyed(submarine->points()); + } + submarine->deleteLater(); +} + +int GraphicsScene::remainingSubMarines() const +{ + return submarines.count(); +} + +void GraphicsScene::clearScene() +{ + foreach (SubMarine *sub,submarines) { + sub->destroy(); + sub->deleteLater(); + } + + foreach (Torpedo *torpedo,torpedos) { + torpedo->destroy(); + torpedo->deleteLater(); + } + + foreach (Bomb *bomb,bombs) { + bomb->destroy(); + bomb->deleteLater(); + } + + submarines.clear(); + bombs.clear(); + torpedos.clear(); + + AnimationManager::self()->unregisterAllAnimations(); + + boat->stop(); + boat->hide(); +} + +QGraphicsPixmapItem *GraphicsScene::addWelcomeItem(const QPixmap &pm) +{ + QGraphicsPixmapItem *item = addPixmap(pm); + welcomeItems << item; + return item; +} + +void GraphicsScene::onIntroAnimationFinished() +{ + qDeleteAll(welcomeItems); + welcomeItems.clear(); +} + diff --git a/examples/animation/sub-attaq/graphicsscene.h b/examples/animation/sub-attaq/graphicsscene.h new file mode 100644 index 0000000..8b0ea96 --- /dev/null +++ b/examples/animation/sub-attaq/graphicsscene.h @@ -0,0 +1,131 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __GRAPHICSSCENE__H__ +#define __GRAPHICSSCENE__H__ + +//Qt +#include +#include +#include + + +class Boat; +class SubMarine; +class Torpedo; +class Bomb; +class PixmapItem; +class ProgressItem; +QT_BEGIN_NAMESPACE +class QAction; +QT_END_NAMESPACE + +class GraphicsScene : public QGraphicsScene +{ +Q_OBJECT +public: + enum Mode { + Big = 0, + Small + }; + + struct SubmarineDescription { + int type; + int points; + QString name; + }; + + struct LevelDescription { + int id; + QString name; + QList > submarines; + }; + + GraphicsScene(int x, int y, int width, int height, Mode mode = Big); + qreal sealLevel() const; + void setupScene(const QList &actions); + void addItem(Bomb *bomb); + void addItem(Torpedo *torpedo); + void addItem(SubMarine *submarine); + void addItem(QGraphicsItem *item); + int remainingSubMarines() const; + void clearScene(); + QGraphicsPixmapItem *addWelcomeItem(const QPixmap &pm); + +Q_SIGNALS: + void subMarineDestroyed(int); + void allSubMarineDestroyed(int); + +protected: + void mousePressEvent (QGraphicsSceneMouseEvent * event); + +private slots: + void onQuitGameTriggered(); + void onBombExecutionFinished(); + void onTorpedoExecutionFinished(); + void onSubMarineExecutionFinished(); + void onIntroAnimationFinished(); + +private: + Mode mode; + PixmapItem *backgroundItem; + ProgressItem *progressItem; + QAction * newAction; + QAction * quitAction; + Boat *boat; + QSet submarines; + QSet bombs; + QSet torpedos; + QVector welcomeItems; + QVector submarinesData; + QHash levelsData; + + friend class PauseState; + friend class PlayState; + friend class LevelState; + friend class LostState; + friend class WinState; + friend class WinTransition; + friend class UpdateScoreTransition; +}; + +#endif //__GRAPHICSSCENE__H__ + diff --git a/examples/animation/sub-attaq/main.cpp b/examples/animation/sub-attaq/main.cpp new file mode 100644 index 0000000..ffaa86f --- /dev/null +++ b/examples/animation/sub-attaq/main.cpp @@ -0,0 +1,57 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include "mainwindow.h" + +int main(int argc, char *argv[]) +{ + QApplication app(argc, argv); + Q_INIT_RESOURCE(subattaq); + + qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); + + MainWindow w; + w.show(); + + return app.exec(); +} diff --git a/examples/animation/sub-attaq/mainwindow.cpp b/examples/animation/sub-attaq/mainwindow.cpp new file mode 100644 index 0000000..a166241 --- /dev/null +++ b/examples/animation/sub-attaq/mainwindow.cpp @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "mainwindow.h" +#include "graphicsscene.h" + +#ifndef QT_NO_OPENGL + #include +#endif +//Qt +#include + +MainWindow::MainWindow() : QMainWindow(0) +{ + QMenuBar *menuBar = new QMenuBar; + QMenu *file = new QMenu(tr("&File"),menuBar); + + QAction *newAction = new QAction(tr("New Game"),file); + newAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_N)); + file->addAction(newAction); + QAction *quitAction = new QAction(tr("Quit"),file); + quitAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q)); + file->addAction(quitAction); + + menuBar->addMenu(file); + setMenuBar(menuBar); + + QStringList list = QApplication::arguments(); + if (list.contains("-fullscreen")) { + scene = new GraphicsScene(0, 0, 750, 400,GraphicsScene::Small); + setWindowState(Qt::WindowFullScreen); + } else { + scene = new GraphicsScene(0, 0, 880, 630); + layout()->setSizeConstraint(QLayout::SetFixedSize); + } + + view = new QGraphicsView(scene,this); + view->setAlignment(Qt::AlignLeft | Qt::AlignTop); + QList actions; + actions << newAction << quitAction; + scene->setupScene(actions); +#ifndef QT_NO_OPENGL + view->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); +#endif + + setCentralWidget(view); + +} + +MainWindow::~MainWindow() +{ +} + diff --git a/examples/animation/sub-attaq/mainwindow.h b/examples/animation/sub-attaq/mainwindow.h new file mode 100644 index 0000000..87f194a --- /dev/null +++ b/examples/animation/sub-attaq/mainwindow.h @@ -0,0 +1,64 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __MAINWINDOW__H__ +#define __MAINWINDOW__H__ + +//Qt +#include +class GraphicsScene; +QT_BEGIN_NAMESPACE +class QGraphicsView; +QT_END_NAMESPACE + +class MainWindow : public QMainWindow +{ +Q_OBJECT +public: + MainWindow(); + ~MainWindow(); + +private: + GraphicsScene *scene; + QGraphicsView *view; +}; + +#endif //__MAINWINDOW__H__ diff --git a/examples/animation/sub-attaq/pics/big/background.png b/examples/animation/sub-attaq/pics/big/background.png new file mode 100644 index 0000000..9f58157 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/background.png differ diff --git a/examples/animation/sub-attaq/pics/big/boat.png b/examples/animation/sub-attaq/pics/big/boat.png new file mode 100644 index 0000000..be82dff Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/boat.png differ diff --git a/examples/animation/sub-attaq/pics/big/bomb.png b/examples/animation/sub-attaq/pics/big/bomb.png new file mode 100644 index 0000000..3af5f2f Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/bomb.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png new file mode 100644 index 0000000..c9fd8b0 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png new file mode 100644 index 0000000..7528f2d Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png new file mode 100644 index 0000000..aae9c9c Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png new file mode 100644 index 0000000..d697c1b Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png new file mode 100644 index 0000000..88ca514 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png new file mode 100644 index 0000000..524f589 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png new file mode 100644 index 0000000..2cca1e8 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png new file mode 100644 index 0000000..82100a8 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png differ diff --git a/examples/animation/sub-attaq/pics/big/submarine.png b/examples/animation/sub-attaq/pics/big/submarine.png new file mode 100644 index 0000000..df435dc Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/submarine.png differ diff --git a/examples/animation/sub-attaq/pics/big/surface.png b/examples/animation/sub-attaq/pics/big/surface.png new file mode 100644 index 0000000..4eba29e Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/surface.png differ diff --git a/examples/animation/sub-attaq/pics/big/torpedo.png b/examples/animation/sub-attaq/pics/big/torpedo.png new file mode 100644 index 0000000..f9c2687 Binary files /dev/null and b/examples/animation/sub-attaq/pics/big/torpedo.png differ diff --git a/examples/animation/sub-attaq/pics/scalable/background-n810.svg b/examples/animation/sub-attaq/pics/scalable/background-n810.svg new file mode 100644 index 0000000..ece9f7a --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/background-n810.svg @@ -0,0 +1,171 @@ + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/background.svg b/examples/animation/sub-attaq/pics/scalable/background.svg new file mode 100644 index 0000000..0be2680 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/background.svg @@ -0,0 +1,171 @@ + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/boat.svg b/examples/animation/sub-attaq/pics/scalable/boat.svg new file mode 100644 index 0000000..5298821b --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/boat.svg @@ -0,0 +1,279 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/bomb.svg b/examples/animation/sub-attaq/pics/scalable/bomb.svg new file mode 100644 index 0000000..294771a --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/bomb.svg @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/sand.svg b/examples/animation/sub-attaq/pics/scalable/sand.svg new file mode 100644 index 0000000..8af11b7 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/sand.svg @@ -0,0 +1,103 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/see.svg b/examples/animation/sub-attaq/pics/scalable/see.svg new file mode 100644 index 0000000..0666691 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/see.svg @@ -0,0 +1,44 @@ + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/sky.svg b/examples/animation/sub-attaq/pics/scalable/sky.svg new file mode 100644 index 0000000..1546c08 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/sky.svg @@ -0,0 +1,45 @@ + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg b/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg new file mode 100644 index 0000000..b075179 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg @@ -0,0 +1,1473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/submarine.svg b/examples/animation/sub-attaq/pics/scalable/submarine.svg new file mode 100644 index 0000000..8a0ffdd --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/submarine.svg @@ -0,0 +1,214 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/surface.svg b/examples/animation/sub-attaq/pics/scalable/surface.svg new file mode 100644 index 0000000..40ed239 --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/surface.svg @@ -0,0 +1,49 @@ + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/scalable/torpedo.svg b/examples/animation/sub-attaq/pics/scalable/torpedo.svg new file mode 100644 index 0000000..48e429d --- /dev/null +++ b/examples/animation/sub-attaq/pics/scalable/torpedo.svg @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/examples/animation/sub-attaq/pics/small/background.png b/examples/animation/sub-attaq/pics/small/background.png new file mode 100644 index 0000000..5ad3db6 Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/background.png differ diff --git a/examples/animation/sub-attaq/pics/small/boat.png b/examples/animation/sub-attaq/pics/small/boat.png new file mode 100644 index 0000000..114ccc3 Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/boat.png differ diff --git a/examples/animation/sub-attaq/pics/small/bomb.png b/examples/animation/sub-attaq/pics/small/bomb.png new file mode 100644 index 0000000..3af5f2f Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/bomb.png differ diff --git a/examples/animation/sub-attaq/pics/small/submarine.png b/examples/animation/sub-attaq/pics/small/submarine.png new file mode 100644 index 0000000..0c0c350 Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/submarine.png differ diff --git a/examples/animation/sub-attaq/pics/small/surface.png b/examples/animation/sub-attaq/pics/small/surface.png new file mode 100644 index 0000000..06d0e47 Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/surface.png differ diff --git a/examples/animation/sub-attaq/pics/small/torpedo.png b/examples/animation/sub-attaq/pics/small/torpedo.png new file mode 100644 index 0000000..f9c2687 Binary files /dev/null and b/examples/animation/sub-attaq/pics/small/torpedo.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-a.png b/examples/animation/sub-attaq/pics/welcome/logo-a.png new file mode 100644 index 0000000..67dd76d Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-a.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-a2.png b/examples/animation/sub-attaq/pics/welcome/logo-a2.png new file mode 100644 index 0000000..17668b0 Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-a2.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-b.png b/examples/animation/sub-attaq/pics/welcome/logo-b.png new file mode 100644 index 0000000..cf6c045 Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-b.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-dash.png b/examples/animation/sub-attaq/pics/welcome/logo-dash.png new file mode 100644 index 0000000..219233c Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-dash.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-excl.png b/examples/animation/sub-attaq/pics/welcome/logo-excl.png new file mode 100644 index 0000000..8dd0a2e Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-excl.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-q.png b/examples/animation/sub-attaq/pics/welcome/logo-q.png new file mode 100644 index 0000000..86e588d Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-q.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-s.png b/examples/animation/sub-attaq/pics/welcome/logo-s.png new file mode 100644 index 0000000..7b6a36e Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-s.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-t.png b/examples/animation/sub-attaq/pics/welcome/logo-t.png new file mode 100644 index 0000000..b2e3526 Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-t.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-t2.png b/examples/animation/sub-attaq/pics/welcome/logo-t2.png new file mode 100644 index 0000000..b11a778 Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-t2.png differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-u.png b/examples/animation/sub-attaq/pics/welcome/logo-u.png new file mode 100644 index 0000000..24eede8 Binary files /dev/null and b/examples/animation/sub-attaq/pics/welcome/logo-u.png differ diff --git a/examples/animation/sub-attaq/pixmapitem.cpp b/examples/animation/sub-attaq/pixmapitem.cpp new file mode 100644 index 0000000..22a363f --- /dev/null +++ b/examples/animation/sub-attaq/pixmapitem.cpp @@ -0,0 +1,59 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "pixmapitem.h" + +//Qt +#include + +PixmapItem::PixmapItem(const QString &fileName,GraphicsScene::Mode mode, QGraphicsItem * parent) : QGraphicsPixmapItem(parent),name(fileName) +{ + loadPixmap(mode); +} + +void PixmapItem::loadPixmap(GraphicsScene::Mode mode) +{ + if (mode == GraphicsScene::Big) + setPixmap(":/big/" + name); + else + setPixmap(":/small/" + name); +} diff --git a/examples/animation/sub-attaq/pixmapitem.h b/examples/animation/sub-attaq/pixmapitem.h new file mode 100644 index 0000000..31022c1 --- /dev/null +++ b/examples/animation/sub-attaq/pixmapitem.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __PIXMAPITEM__H__ +#define __PIXMAPITEM__H__ + +//Own +#include "graphicsscene.h" + +//Qt +#include + +class PixmapItem : public QGraphicsPixmapItem +{ +public: + PixmapItem(const QString &fileName, GraphicsScene::Mode mode, QGraphicsItem * parent = 0); + +private: + void loadPixmap(GraphicsScene::Mode mode); + + QString name; + QPixmap pixmap; +}; + +#endif //__PIXMAPITEM__H__ diff --git a/examples/animation/sub-attaq/progressitem.cpp b/examples/animation/sub-attaq/progressitem.cpp new file mode 100644 index 0000000..59ccb9a --- /dev/null +++ b/examples/animation/sub-attaq/progressitem.cpp @@ -0,0 +1,67 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "progressitem.h" +#include "pixmapitem.h" + +ProgressItem::ProgressItem (QGraphicsItem * parent) + : QGraphicsTextItem(parent), currentLevel(1), currentScore(0) +{ + setFont(QFont("Comic Sans MS")); + setPos(parentItem()->boundingRect().topRight() - QPointF(180, -5)); +} + +void ProgressItem::setLevel(int level) +{ + currentLevel = level; + updateProgress(); +} + +void ProgressItem::setScore(int score) +{ + currentScore = score; + updateProgress(); +} + +void ProgressItem::updateProgress() +{ + setHtml(QString("Level : %1 Score : %2").arg(currentLevel).arg(currentScore)); +} diff --git a/examples/animation/sub-attaq/progressitem.h b/examples/animation/sub-attaq/progressitem.h new file mode 100644 index 0000000..7b8db4d --- /dev/null +++ b/examples/animation/sub-attaq/progressitem.h @@ -0,0 +1,61 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PROGRESSITEM_H +#define PROGRESSITEM_H + +//Qt +#include + +class ProgressItem : public QGraphicsTextItem +{ +public: + ProgressItem(QGraphicsItem * parent = 0); + void setLevel(int level); + void setScore(int score); + +private: + void updateProgress(); + int currentLevel; + int currentScore; +}; + +#endif // PROGRESSITEM_H diff --git a/examples/animation/sub-attaq/qanimationstate.cpp b/examples/animation/sub-attaq/qanimationstate.cpp new file mode 100644 index 0000000..26e0ef3 --- /dev/null +++ b/examples/animation/sub-attaq/qanimationstate.cpp @@ -0,0 +1,171 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qanimationstate.h" + +#include +#include + + +QT_BEGIN_NAMESPACE + +/*! +\class QAnimationState + +\brief The QAnimationState class provides state that handle an animation and emit +a signal when this animation is finished. + +\ingroup statemachine + +QAnimationState provides a state that handle an animation. It will start this animation +when the state is entered and stop it when it is leaved. When the animation has finished the +state emit animationFinished signal. +QAnimationState is part of \l{The State Machine Framework}. + +\code +QStateMachine machine; +QAnimationState *s = new QAnimationState(machine->rootState()); +QPropertyAnimation *animation = new QPropertyAnimation(obj, "pos"); +s->setAnimation(animation); +QState *s2 = new QState(machine->rootState()); +s->addTransition(s, SIGNAL(animationFinished()), s2); +machine.start(); +\endcode + +\sa QState, {The Animation Framework} +*/ + + +#ifndef QT_NO_ANIMATION + +class QAnimationStatePrivate : public QStatePrivate +{ + Q_DECLARE_PUBLIC(QAnimationState) +public: + QAnimationStatePrivate() + : animation(0) + { + + } + ~QAnimationStatePrivate() {} + + QAbstractAnimation *animation; +}; + +/*! + Constructs a new state with the given \a parent state. +*/ +QAnimationState::QAnimationState(QState *parent) + : QState(*new QAnimationStatePrivate, parent) +{ +} + +/*! + Destroys the animation state. +*/ +QAnimationState::~QAnimationState() +{ +} + +/*! + Set an \a animation for this QAnimationState. If an animation was previously handle by this + state then it won't emit animationFinished for the old animation. The QAnimationState doesn't + take the ownership of the animation. +*/ +void QAnimationState::setAnimation(QAbstractAnimation *animation) +{ + Q_D(QAnimationState); + + if (animation == d->animation) + return; + + //Disconnect from the previous animation if exist + if(d->animation) + disconnect(d->animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); + + d->animation = animation; + + if (d->animation) { + //connect the new animation + connect(d->animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); + } +} + +/*! + Returns the animation handle by this animation state, or 0 if there is no animation. +*/ +QAbstractAnimation* QAnimationState::animation() const +{ + Q_D(const QAnimationState); + return d->animation; +} + +/*! + \reimp +*/ +void QAnimationState::onEntry(QEvent *) +{ + Q_D(QAnimationState); + if (d->animation) + d->animation->start(); +} + +/*! + \reimp +*/ +void QAnimationState::onExit(QEvent *) +{ + Q_D(QAnimationState); + if (d->animation) + d->animation->stop(); +} + +/*! + \reimp +*/ +bool QAnimationState::event(QEvent *e) +{ + return QState::event(e); +} + +QT_END_NAMESPACE + +#endif diff --git a/examples/animation/sub-attaq/qanimationstate.h b/examples/animation/sub-attaq/qanimationstate.h new file mode 100644 index 0000000..88c0a6d --- /dev/null +++ b/examples/animation/sub-attaq/qanimationstate.h @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QANIMATIONSTATE_H +#define QANIMATIONSTATE_H + +#ifndef QT_STATEMACHINE_SOLUTION +# include +# include +#else +# include "qstate.h" +# include "qabstractanimation.h" +#endif + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Gui) + +#ifndef QT_NO_ANIMATION + +class QAnimationStatePrivate; + +class QAnimationState : public QState +{ + Q_OBJECT +public: + QAnimationState(QState *parent = 0); + ~QAnimationState(); + + void setAnimation(QAbstractAnimation *animation); + QAbstractAnimation* animation() const; + +Q_SIGNALS: + void animationFinished(); + +protected: + void onEntry(QEvent *); + void onExit(QEvent *); + bool event(QEvent *e); + +private: + Q_DISABLE_COPY(QAnimationState) + Q_DECLARE_PRIVATE(QAnimationState) +}; + +#endif + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QANIMATIONSTATE_H diff --git a/examples/animation/sub-attaq/states.cpp b/examples/animation/sub-attaq/states.cpp new file mode 100644 index 0000000..adc8bd0 --- /dev/null +++ b/examples/animation/sub-attaq/states.cpp @@ -0,0 +1,325 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "states.h" +#include "graphicsscene.h" +#include "boat.h" +#include "submarine.h" +#include "torpedo.h" +#include "animationmanager.h" +#include "progressitem.h" + +//Qt +#include +#include +#include +#include +#include +#include + +PlayState::PlayState(GraphicsScene *scene, QState *parent) + : QState(parent), + scene(scene), + machine(0), + currentLevel(0), + score(0) +{ +} + +PlayState::~PlayState() +{ +} + +void PlayState::onEntry(QEvent *) +{ + //We are now playing? + if (machine) { + machine->stop(); + scene->clearScene(); + currentLevel = 0; + score = 0; + delete machine; + } + + machine = new QStateMachine(this); + + //This state is when player is playing + LevelState *levelState = new LevelState(scene, this, machine->rootState()); + + //This state is when the player is actually playing but the game is not paused + QState *playingState = new QState(levelState); + levelState->setInitialState(playingState); + + //This state is when the game is paused + PauseState *pauseState = new PauseState(scene, levelState); + + //We have one view, it receive the key press event + QKeyEventTransition *pressPplay = new QKeyEventTransition(scene->views().at(0), QEvent::KeyPress, Qt::Key_P); + pressPplay->setTargetState(pauseState); + QKeyEventTransition *pressPpause = new QKeyEventTransition(scene->views().at(0), QEvent::KeyPress, Qt::Key_P); + pressPpause->setTargetState(playingState); + + //Pause "P" is triggered, the player pause the game + playingState->addTransition(pressPplay); + + //To get back playing when the game has been paused + pauseState->addTransition(pressPpause); + + //This state is when player have lost + LostState *lostState = new LostState(scene, this, machine->rootState()); + + //This state is when player have won + WinState *winState = new WinState(scene, this, machine->rootState()); + + //The boat has been destroyed then the game is finished + levelState->addTransition(scene->boat, SIGNAL(boatExecutionFinished()),lostState); + + //This transition check if we won or not + WinTransition *winTransition = new WinTransition(scene, this, winState); + + //The boat has been destroyed then the game is finished + levelState->addTransition(winTransition); + + //This state is an animation when the score changed + UpdateScoreState *scoreState = new UpdateScoreState(this, levelState); + + //This transition update the score when a submarine die + UpdateScoreTransition *scoreTransition = new UpdateScoreTransition(scene, this, levelState); + scoreTransition->setTargetState(scoreState); + + //The boat has been destroyed then the game is finished + playingState->addTransition(scoreTransition); + + //We go back to play state + scoreState->addTransition(playingState); + + //We start playing!!! + machine->setInitialState(levelState); + + //Final state + QFinalState *final = new QFinalState(machine->rootState()); + + //This transition is triggered when the player press space after completing a level + CustomSpaceTransition *spaceTransition = new CustomSpaceTransition(scene->views().at(0), this, QEvent::KeyPress, Qt::Key_Space); + spaceTransition->setTargetState(levelState); + winState->addTransition(spaceTransition); + + //We lost we should reach the final state + lostState->addTransition(lostState, SIGNAL(finished()), final); + + machine->start(); +} + +LevelState::LevelState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) +{ +} +void LevelState::onEntry(QEvent *) +{ + initializeLevel(); +} + +void LevelState::initializeLevel() +{ + //we re-init the boat + scene->boat->setPos(scene->width()/2, scene->sealLevel() - scene->boat->size().height()); + scene->boat->setCurrentSpeed(0); + scene->boat->setCurrentDirection(Boat::None); + scene->boat->setBombsLaunched(0); + scene->boat->show(); + scene->setFocusItem(scene->boat,Qt::OtherFocusReason); + scene->boat->run(); + + scene->progressItem->setScore(game->score); + scene->progressItem->setLevel(game->currentLevel + 1); + + GraphicsScene::LevelDescription currentLevelDescription = scene->levelsData.value(game->currentLevel); + + for (int i = 0; i < currentLevelDescription.submarines.size(); ++i ) { + + QPair subContent = currentLevelDescription.submarines.at(i); + GraphicsScene::SubmarineDescription submarineDesc = scene->submarinesData.at(subContent.first); + + for (int j = 0; j < subContent.second; ++j ) { + SubMarine *sub = new SubMarine(submarineDesc.type, submarineDesc.name, submarineDesc.points); + scene->addItem(sub); + int random = (qrand() % 15 + 1); + qreal x = random == 13 || random == 5 ? 0 : scene->width() - sub->size().width(); + qreal y = scene->height() -(qrand() % 150 + 1) - sub->size().height(); + sub->setPos(x,y); + sub->setCurrentDirection(x == 0 ? SubMarine::Right : SubMarine::Left); + sub->setCurrentSpeed(qrand() % 3 + 1); + } + } +} + +/** Pause State */ +PauseState::PauseState(GraphicsScene *scene, QState *parent) : QState(parent),scene(scene) +{ +} +void PauseState::onEntry(QEvent *) +{ + AnimationManager::self()->pauseAll(); + scene->boat->setEnabled(false); +} +void PauseState::onExit(QEvent *) +{ + AnimationManager::self()->resumeAll(); + scene->boat->setEnabled(true); + scene->boat->setFocus(); +} + +/** Lost State */ +LostState::LostState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) +{ +} + +void LostState::onEntry(QEvent *) +{ + //The message to display + QString message = QString("You lose on level %1. Your score is %2.").arg(game->currentLevel+1).arg(game->score); + + //We set the level back to 0 + game->currentLevel = 0; + + //We set the score back to 0 + game->score = 0; + + //We clear the scene + scene->clearScene(); + + //we have only one view + QMessageBox::information(scene->views().at(0),"You lose",message); +} + +/** Win State */ +WinState::WinState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) +{ +} + +void WinState::onEntry(QEvent *) +{ + //We clear the scene + scene->clearScene(); + + QString message; + if (scene->levelsData.size() - 1 != game->currentLevel) { + message = QString("You win the level %1. Your score is %2.\nPress Space to continue after closing this dialog.").arg(game->currentLevel+1).arg(game->score); + //We increment the level number + game->currentLevel++; + } else { + message = QString("You finish the game on level %1. Your score is %2.").arg(game->currentLevel+1).arg(game->score); + //We set the level back to 0 + game->currentLevel = 0; + //We set the score back to 0 + game->score = 0; + } + + //we have only one view + QMessageBox::information(scene->views().at(0),"You win",message); +} + +/** UpdateScore State */ +UpdateScoreState::UpdateScoreState(PlayState *game, QState *parent) : QState(parent) +{ + this->game = game; +} +void UpdateScoreState::onEntry(QEvent *e) +{ + QState::onEntry(e); +} + +/** Win transition */ +UpdateScoreTransition::UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) + : QSignalTransition(scene,SIGNAL(subMarineDestroyed(int)), QList() << target), + game(game), scene(scene) +{ +} + +bool UpdateScoreTransition::eventTest(QEvent *event) +{ + if (!QSignalTransition::eventTest(event)) + return false; + else { + QSignalEvent *se = static_cast(event); + game->score += se->arguments().at(0).toInt(); + scene->progressItem->setScore(game->score); + return true; + } +} + +/** Win transition */ +WinTransition::WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) + : QSignalTransition(scene,SIGNAL(allSubMarineDestroyed(int)), QList() << target), + game(game), scene(scene) +{ +} + +bool WinTransition::eventTest(QEvent *event) +{ + if (!QSignalTransition::eventTest(event)) + return false; + else { + QSignalEvent *se = static_cast(event); + game->score += se->arguments().at(0).toInt(); + scene->progressItem->setScore(game->score); + return true; + } +} + +/** Space transition */ +CustomSpaceTransition::CustomSpaceTransition(QWidget *widget, PlayState *game, QEvent::Type type, int key) + : QKeyEventTransition(widget, type, key), + game(game) +{ +} + +bool CustomSpaceTransition::eventTest(QEvent *event) +{ + Q_UNUSED(event); + if (!QKeyEventTransition::eventTest(event)) + return false; + if (game->currentLevel != 0) + return true; + else + return false; + +} diff --git a/examples/animation/sub-attaq/states.h b/examples/animation/sub-attaq/states.h new file mode 100644 index 0000000..71375e0 --- /dev/null +++ b/examples/animation/sub-attaq/states.h @@ -0,0 +1,180 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef STATES_H +#define STATES_H + +//Qt +#include +#include +#include +#include +#include + +class GraphicsScene; +class Boat; +class SubMarine; +QT_BEGIN_NAMESPACE +class QStateMachine; +QT_END_NAMESPACE + +class PlayState : public QState +{ +public: + PlayState(GraphicsScene *scene, QState *parent = 0); + ~PlayState(); + + protected: + void onEntry(QEvent *); + +private : + GraphicsScene *scene; + QStateMachine *machine; + int currentLevel; + int score; + QState *parallelChild; + + friend class UpdateScoreState; + friend class UpdateScoreTransition; + friend class WinTransition; + friend class CustomSpaceTransition; + friend class WinState; + friend class LostState; + friend class LevelState; +}; + +class LevelState : public QState +{ +public: + LevelState(GraphicsScene *scene, PlayState *game, QState *parent = 0); +protected: + void onEntry(QEvent *); +private : + void initializeLevel(); + GraphicsScene *scene; + PlayState *game; +}; + +class PauseState : public QState +{ +public: + PauseState(GraphicsScene *scene, QState *parent = 0); + +protected: + void onEntry(QEvent *); + void onExit(QEvent *); +private : + GraphicsScene *scene; + Boat *boat; +}; + +class LostState : public QState +{ +public: + LostState(GraphicsScene *scene, PlayState *game, QState *parent = 0); + +protected: + void onEntry(QEvent *); +private : + GraphicsScene *scene; + PlayState *game; +}; + +class WinState : public QState +{ +public: + WinState(GraphicsScene *scene, PlayState *game, QState *parent = 0); + +protected: + void onEntry(QEvent *); +private : + GraphicsScene *scene; + PlayState *game; +}; + +class UpdateScoreState : public QState +{ +public: + UpdateScoreState(PlayState *game, QState *parent); +protected: + void onEntry(QEvent *); +private: + QPropertyAnimation *scoreAnimation; + PlayState *game; +}; + +//These transtion is used to update the score +class UpdateScoreTransition : public QSignalTransition +{ +public: + UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target); +protected: + virtual bool eventTest(QEvent *event); +private: + PlayState * game; + GraphicsScene *scene; +}; + +//These transtion test if we have won the game +class WinTransition : public QSignalTransition +{ +public: + WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target); +protected: + virtual bool eventTest(QEvent *event); +private: + PlayState * game; + GraphicsScene *scene; +}; + +//These transtion is true if one level has been completed and the player want to continue + class CustomSpaceTransition : public QKeyEventTransition +{ +public: + CustomSpaceTransition(QWidget *widget, PlayState *game, QEvent::Type type, int key); +protected: + virtual bool eventTest(QEvent *event); +private: + PlayState *game; + int key; +}; + +#endif // STATES_H diff --git a/examples/animation/sub-attaq/sub-attaq.pro b/examples/animation/sub-attaq/sub-attaq.pro new file mode 100644 index 0000000..d13a099 --- /dev/null +++ b/examples/animation/sub-attaq/sub-attaq.pro @@ -0,0 +1,36 @@ +contains(QT_CONFIG, opengl):QT += opengl + +HEADERS += boat.h \ + bomb.h \ + mainwindow.h \ + submarine.h \ + torpedo.h \ + pixmapitem.h \ + graphicsscene.h \ + animationmanager.h \ + states.h \ + boat_p.h \ + submarine_p.h \ + custompropertyanimation.h \ + qanimationstate.h \ + progressitem.h +SOURCES += boat.cpp \ + bomb.cpp \ + main.cpp \ + mainwindow.cpp \ + submarine.cpp \ + torpedo.cpp \ + pixmapitem.cpp \ + graphicsscene.cpp \ + animationmanager.cpp \ + states.cpp \ + custompropertyanimation.cpp \ + qanimationstate.cpp \ + progressitem.cpp +RESOURCES += subattaq.qrc + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/animation/sub-attaq +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS sub-attaq.pro pics +sources.path = $$[QT_INSTALL_EXAMPLES]/animation/sub-attaq +INSTALLS += target sources diff --git a/examples/animation/sub-attaq/subattaq.qrc b/examples/animation/sub-attaq/subattaq.qrc new file mode 100644 index 0000000..c76f8ef --- /dev/null +++ b/examples/animation/sub-attaq/subattaq.qrc @@ -0,0 +1,38 @@ + + + pics/scalable/sub-attaq.svg + pics/scalable/submarine.svg + pics/scalable/boat.svg + pics/scalable/torpedo.svg + pics/welcome/logo-s.png + pics/welcome/logo-u.png + pics/welcome/logo-b.png + pics/welcome/logo-dash.png + pics/welcome/logo-a.png + pics/welcome/logo-t.png + pics/welcome/logo-t2.png + pics/welcome/logo-a2.png + pics/welcome/logo-q.png + pics/welcome/logo-excl.png + pics/big/background.png + pics/big/boat.png + pics/big/bomb.png + pics/big/submarine.png + pics/big/surface.png + pics/big/torpedo.png + pics/small/background.png + pics/small/boat.png + pics/small/bomb.png + pics/small/submarine.png + pics/small/surface.png + pics/small/torpedo.png + pics/big/explosion/boat/step1.png + pics/big/explosion/boat/step2.png + pics/big/explosion/boat/step3.png + pics/big/explosion/boat/step4.png + pics/big/explosion/submarine/step1.png + pics/big/explosion/submarine/step2.png + pics/big/explosion/submarine/step3.png + pics/big/explosion/submarine/step4.png + + diff --git a/examples/animation/sub-attaq/submarine.cpp b/examples/animation/sub-attaq/submarine.cpp new file mode 100644 index 0000000..d8cf1da --- /dev/null +++ b/examples/animation/sub-attaq/submarine.cpp @@ -0,0 +1,211 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "submarine.h" +#include "submarine_p.h" +#include "torpedo.h" +#include "pixmapitem.h" +#include "graphicsscene.h" +#include "animationmanager.h" +#include "custompropertyanimation.h" +#include "qanimationstate.h" + +#include +#include +#include +#include + +static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub) +{ + QSequentialAnimationGroup *group = new QSequentialAnimationGroup(sub); +#if QT_VERSION >=0x040500 + PixmapItem *step1 = new PixmapItem(QString("explosion/submarine/step1"),GraphicsScene::Big, sub); + step1->setZValue(6); + PixmapItem *step2 = new PixmapItem(QString("explosion/submarine/step2"),GraphicsScene::Big, sub); + step2->setZValue(6); + PixmapItem *step3 = new PixmapItem(QString("explosion/submarine/step3"),GraphicsScene::Big, sub); + step3->setZValue(6); + PixmapItem *step4 = new PixmapItem(QString("explosion/submarine/step4"),GraphicsScene::Big, sub); + step4->setZValue(6); + step1->setOpacity(0); + step2->setOpacity(0); + step3->setOpacity(0); + step4->setOpacity(0); + CustomPropertyAnimation *anim1 = new CustomPropertyAnimation(sub); + anim1->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim1->setDuration(100); + anim1->setEndValue(1); + CustomPropertyAnimation *anim2 = new CustomPropertyAnimation(sub); + anim2->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim2->setDuration(100); + anim2->setEndValue(1); + CustomPropertyAnimation *anim3 = new CustomPropertyAnimation(sub); + anim3->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim3->setDuration(100); + anim3->setEndValue(1); + CustomPropertyAnimation *anim4 = new CustomPropertyAnimation(sub); + anim4->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); + anim4->setDuration(100); + anim4->setEndValue(1); + group->addAnimation(anim1); + group->addAnimation(anim2); + group->addAnimation(anim3); + group->addAnimation(anim4); +#else + // work around for a bug where we don't transition if the duration is zero. + QtPauseAnimation *anim = new QtPauseAnimation(group); + anim->setDuration(1); + group->addAnimation(anim); +#endif + AnimationManager::self()->registerAnimation(group); + return group; +} + + +SubMarine::SubMarine(int type, const QString &name, int points, QGraphicsItem * parent, Qt::WindowFlags wFlags) + : QGraphicsWidget(parent,wFlags), subType(type), subName(name), subPoints(points), speed(0), direction(SubMarine::None) +{ + pixmapItem = new PixmapItem(QString("submarine"),GraphicsScene::Big, this); + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + setZValue(5); + setFlags(QGraphicsItem::ItemIsMovable); + resize(pixmapItem->boundingRect().width(),pixmapItem->boundingRect().height()); + setTransformOrigin(boundingRect().center()); + + //We setup the state machine of the submarine + QStateMachine *machine = new QStateMachine(this); + + //This state is when the boat is moving/rotating + QState *moving = new QState(machine->rootState()); + + //This state is when the boat is moving from left to right + MovementState *movement = new MovementState(this, moving); + + //This state is when the boat is moving from left to right + ReturnState *rotation = new ReturnState(this, moving); + + //This is the initial state of the moving root state + moving->setInitialState(movement); + + movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving); + + //This is the initial state of the machine + machine->setInitialState(moving); + + //End + QFinalState *final = new QFinalState(machine->rootState()); + + //If the moving animation is finished we move to the return state + movement->addTransition(movement, SIGNAL(animationFinished()), rotation); + + //If the return animation is finished we move to the moving state + rotation->addTransition(rotation, SIGNAL(animationFinished()), movement); + + //This state play the destroyed animation + QAnimationState *destroyedState = new QAnimationState(machine->rootState()); + destroyedState->setAnimation(setupDestroyAnimation(this)); + + //Play a nice animation when the submarine is destroyed + moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState); + + //Transition to final state when the destroyed animation is finished + destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); + + //The machine has finished to be executed, then the submarine is dead + connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished())); + + machine->start(); +} + +int SubMarine::points() +{ + return subPoints; +} + +void SubMarine::setCurrentDirection(SubMarine::Movement direction) +{ + if (this->direction == direction) + return; + if (direction == SubMarine::Right && this->direction == SubMarine::None) { + setYRotation(180); + } + this->direction = direction; +} + +enum SubMarine::Movement SubMarine::currentDirection() const +{ + return direction; +} + +void SubMarine::setCurrentSpeed(int speed) +{ + if (speed < 0 || speed > 3) { + qWarning("SubMarine::setCurrentSpeed : The speed is invalid"); + } + this->speed = speed; + emit subMarineStateChanged(); +} + +int SubMarine::currentSpeed() const +{ + return speed; +} + +void SubMarine::launchTorpedo(int speed) +{ + Torpedo * torp = new Torpedo(); + GraphicsScene *scene = static_cast(this->scene()); + scene->addItem(torp); + torp->setPos(x(), y()); + torp->setCurrentSpeed(speed); + torp->launch(); +} + +void SubMarine::destroy() +{ + emit subMarineDestroyed(); +} + +int SubMarine::type() const +{ + return Type; +} diff --git a/examples/animation/sub-attaq/submarine.h b/examples/animation/sub-attaq/submarine.h new file mode 100644 index 0000000..4001603 --- /dev/null +++ b/examples/animation/sub-attaq/submarine.h @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __SUBMARINE__H__ +#define __SUBMARINE__H__ + +//Qt +#include +#include + +class PixmapItem; + +class Torpedo; + +class SubMarine : public QGraphicsWidget +{ +Q_OBJECT +public: + enum Movement { + None = 0, + Left, + Right + }; + enum { Type = UserType + 1 }; + SubMarine(int type, const QString &name, int points, QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0); + + int points(); + + void setCurrentDirection(Movement direction); + enum Movement currentDirection() const; + + void setCurrentSpeed(int speed); + int currentSpeed() const; + + void launchTorpedo(int speed); + void destroy(); + + virtual int type() const; + +Q_SIGNALS: + void subMarineDestroyed(); + void subMarineExecutionFinished(); + void subMarineStateChanged(); + +private: + int subType; + QString subName; + int subPoints; + int speed; + Movement direction; + PixmapItem *pixmapItem; +}; + +#endif //__SUBMARINE__H__ diff --git a/examples/animation/sub-attaq/submarine_p.h b/examples/animation/sub-attaq/submarine_p.h new file mode 100644 index 0000000..8c31eb7 --- /dev/null +++ b/examples/animation/sub-attaq/submarine_p.h @@ -0,0 +1,139 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SUBMARINE_P_H +#define SUBMARINE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +//Own +#include "animationmanager.h" +#include "submarine.h" +#include "qanimationstate.h" + +//Qt +#include +#include + +//This state is describing when the boat is moving right +class MovementState : public QAnimationState +{ +Q_OBJECT +public: + MovementState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) + { + movementAnimation = new QPropertyAnimation(submarine, "pos"); + connect(movementAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationMovementValueChanged(const QVariant &))); + setAnimation(movementAnimation); + AnimationManager::self()->registerAnimation(movementAnimation); + this->submarine = submarine; + } + +protected slots: + void onAnimationMovementValueChanged(const QVariant &) + { + if (qrand() % 200 + 1 == 3) + submarine->launchTorpedo(qrand() % 3 + 1); + } + +protected: + void onEntry(QEvent *e) + { + if (submarine->currentDirection() == SubMarine::Left) { + movementAnimation->setEndValue(QPointF(0,submarine->y())); + movementAnimation->setDuration(submarine->x()/submarine->currentSpeed()*12); + } + else /*if (submarine->currentDirection() == SubMarine::Right)*/ { + movementAnimation->setEndValue(QPointF(submarine->scene()->width()-submarine->size().width(),submarine->y())); + movementAnimation->setDuration((submarine->scene()->width()-submarine->size().width()-submarine->x())/submarine->currentSpeed()*12); + } + movementAnimation->setStartValue(submarine->pos()); + QAnimationState::onEntry(e); + } + +private: + SubMarine *submarine; + QPropertyAnimation *movementAnimation; +}; + +//This state is describing when the boat is moving right +class ReturnState : public QAnimationState +{ +public: + ReturnState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) + { + returnAnimation = new QPropertyAnimation(submarine, "yRotation"); + AnimationManager::self()->registerAnimation(returnAnimation); + setAnimation(returnAnimation); + this->submarine = submarine; + } + +protected: + void onEntry(QEvent *e) + { + returnAnimation->stop(); + returnAnimation->setStartValue(submarine->yRotation()); + returnAnimation->setEndValue(submarine->currentDirection() == SubMarine::Right ? 360. : 180.); + returnAnimation->setDuration(500); + QAnimationState::onEntry(e); + } + + void onExit(QEvent *e) + { + submarine->currentDirection() == SubMarine::Right ? submarine->setCurrentDirection(SubMarine::Left) : submarine->setCurrentDirection(SubMarine::Right); + QAnimationState::onExit(e); + } + +private: + SubMarine *submarine; + QPropertyAnimation *returnAnimation; +}; + +#endif // SUBMARINE_P_H diff --git a/examples/animation/sub-attaq/torpedo.cpp b/examples/animation/sub-attaq/torpedo.cpp new file mode 100644 index 0000000..02a54fc --- /dev/null +++ b/examples/animation/sub-attaq/torpedo.cpp @@ -0,0 +1,120 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +//Own +#include "torpedo.h" +#include "pixmapitem.h" +#include "boat.h" +#include "graphicsscene.h" +#include "animationmanager.h" +#include "qanimationstate.h" + +#include +#include +#include + +Torpedo::Torpedo(QGraphicsItem * parent, Qt::WindowFlags wFlags) + : QGraphicsWidget(parent,wFlags), currentSpeed(0), launchAnimation(0) +{ + pixmapItem = new PixmapItem(QString::fromLatin1("torpedo"),GraphicsScene::Big, this); + setZValue(2); + setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + setFlags(QGraphicsItem::ItemIsMovable); + resize(pixmapItem->boundingRect().size()); +} + +void Torpedo::launch() +{ + launchAnimation = new QPropertyAnimation(this, "pos"); + AnimationManager::self()->registerAnimation(launchAnimation); + launchAnimation->setEndValue(QPointF(x(),qobject_cast(scene())->sealLevel() - 15)); + launchAnimation->setEasingCurve(QEasingCurve::InQuad); + launchAnimation->setDuration(y()/currentSpeed*10); + connect(launchAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationLaunchValueChanged(const QVariant &))); + + //We setup the state machine of the torpedo + QStateMachine *machine = new QStateMachine(this); + + //This state is when the launch animation is playing + QAnimationState *launched = new QAnimationState(machine->rootState()); + launched->setAnimation(launchAnimation); + + //End + QFinalState *final = new QFinalState(machine->rootState()); + + machine->setInitialState(launched); + + //### Add a nice animation when the torpedo is destroyed + launched->addTransition(this, SIGNAL(torpedoExplosed()),final); + + //If the animation is finished, then we move to the final state + launched->addTransition(launched, SIGNAL(animationFinished()), final); + + //The machine has finished to be executed, then the boat is dead + connect(machine,SIGNAL(finished()),this, SIGNAL(torpedoExecutionFinished())); + + machine->start(); +} + +void Torpedo::setCurrentSpeed(int speed) +{ + if (speed < 0) { + qWarning("Torpedo::setCurrentSpeed : The speed is invalid"); + return; + } + currentSpeed = speed; +} + +void Torpedo::onAnimationLaunchValueChanged(const QVariant &) +{ + foreach (QGraphicsItem *item , collidingItems(Qt::IntersectsItemBoundingRect)) { + if (item->type() == Boat::Type) { + Boat *b = static_cast(item); + b->destroy(); + } + } +} + +void Torpedo::destroy() +{ + launchAnimation->stop(); + emit torpedoExplosed(); +} diff --git a/examples/animation/sub-attaq/torpedo.h b/examples/animation/sub-attaq/torpedo.h new file mode 100644 index 0000000..4a0f457 --- /dev/null +++ b/examples/animation/sub-attaq/torpedo.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef __TORPEDO__H__ +#define __TORPEDO__H__ + +//Qt +#include + +#include +#include + +class PixmapItem; + +class Torpedo : public QGraphicsWidget +{ +Q_OBJECT +Q_PROPERTY(QPointF pos READ pos WRITE setPos) +public: + Torpedo(QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0); + void launch(); + void setCurrentSpeed(int speed); + void destroy(); + +Q_SIGNALS: + void torpedoExplosed(); + void torpedoExecutionFinished(); + +private slots: + void onAnimationLaunchValueChanged(const QVariant &); + +private: + int currentSpeed; + PixmapItem *pixmapItem; + QVariantAnimation *launchAnimation; +}; + +#endif //__TORPEDO__H__ diff --git a/examples/examples.pro b/examples/examples.pro index 41501a0..bfcf9b4 100644 --- a/examples/examples.pro +++ b/examples/examples.pro @@ -1,5 +1,6 @@ TEMPLATE = subdirs SUBDIRS = \ + animation \ desktop \ dialogs \ draganddrop \ @@ -14,6 +15,7 @@ SUBDIRS = \ qtconcurrent \ richtext \ sql \ + statemachine \ threads \ tools \ tutorials \ diff --git a/examples/statemachine/README b/examples/statemachine/README new file mode 100644 index 0000000..2879e67 --- /dev/null +++ b/examples/statemachine/README @@ -0,0 +1,36 @@ +Qt is provided with a powerful hierchical finite state machine through +the Qt State Machine classes. + +The example launcher provided with Qt can be used to explore each of the +examples in this directory. + +Documentation for these examples can be found via the Tutorial and Examples +link in the main Qt documentation. + + +Finding the Qt Examples and Demos launcher +========================================== + +On Windows: + +The launcher can be accessed via the Windows Start menu. Select the menu +entry entitled "Qt Examples and Demos" entry in the submenu containing +the Qt tools. + +On Mac OS X: + +For the binary distribution, the qtdemo executable is installed in the +/Developer/Applications/Qt directory. For the source distribution, it is +installed alongside the other Qt tools on the path specified when Qt is +configured. + +On Unix/Linux: + +The qtdemo executable is installed alongside the other Qt tools on the path +specified when Qt is configured. + +On all platforms: + +The source code for the launcher can be found in the demos/qtdemo directory +in the Qt package. This example is built at the same time as the Qt libraries, +tools, examples, and demonstrations. diff --git a/examples/statemachine/eventtransitions/eventtransitions.pro b/examples/statemachine/eventtransitions/eventtransitions.pro new file mode 100644 index 0000000..7e92cf2 --- /dev/null +++ b/examples/statemachine/eventtransitions/eventtransitions.pro @@ -0,0 +1,7 @@ +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/eventtransitions +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS eventtransitions.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/eventtransitions +INSTALLS += target sources diff --git a/examples/statemachine/eventtransitions/main.cpp b/examples/statemachine/eventtransitions/main.cpp new file mode 100644 index 0000000..aba0c73 --- /dev/null +++ b/examples/statemachine/eventtransitions/main.cpp @@ -0,0 +1,116 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#ifdef QT_STATEMACHINE_SOLUTION +#include +#include +#include +#endif + +//! [0] +class Window : public QWidget +{ +public: + Window(QWidget *parent = 0) + : QWidget(parent) + { + QPushButton *button = new QPushButton(this); + button->setGeometry(QRect(100, 100, 100, 100)); +//! [0] + +//! [1] + QStateMachine *machine = new QStateMachine(this); + + QState *s1 = new QState(); + s1->assignProperty(button, "text", "Outside"); + + QState *s2 = new QState(); + s2->assignProperty(button, "text", "Inside"); +//! [1] + +//! [2] + QEventTransition *enterTransition = new QEventTransition(button, QEvent::Enter); + enterTransition->setTargetState(s2); + s1->addTransition(enterTransition); +//! [2] + +//! [3] + QEventTransition *leaveTransition = new QEventTransition(button, QEvent::Leave); + leaveTransition->setTargetState(s1); + s2->addTransition(leaveTransition); +//! [3] + +//! [4] + QState *s3 = new QState(); + s3->assignProperty(button, "text", "Pressing..."); + + QEventTransition *pressTransition = new QEventTransition(button, QEvent::MouseButtonPress); + pressTransition->setTargetState(s3); + s2->addTransition(pressTransition); + + QEventTransition *releaseTransition = new QEventTransition(button, QEvent::MouseButtonRelease); + releaseTransition->setTargetState(s2); + s3->addTransition(releaseTransition); +//! [4] + +//! [5] + machine->addState(s1); + machine->addState(s2); + machine->addState(s3); + + machine->setInitialState(s1); + machine->start(); + } +}; +//! [5] + +//! [6] +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + Window window; + window.resize(300, 300); + window.show(); + + return app.exec(); +} +//! [6] diff --git a/examples/statemachine/factorial/factorial.pro b/examples/statemachine/factorial/factorial.pro new file mode 100644 index 0000000..14a6833 --- /dev/null +++ b/examples/statemachine/factorial/factorial.pro @@ -0,0 +1,11 @@ +QT = core +win32: CONFIG += console +mac:CONFIG -= app_bundle + +SOURCES += main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/factorial +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS factorial.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/factorial +INSTALLS += target sources diff --git a/examples/statemachine/factorial/main.cpp b/examples/statemachine/factorial/main.cpp new file mode 100644 index 0000000..1065eb8 --- /dev/null +++ b/examples/statemachine/factorial/main.cpp @@ -0,0 +1,182 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#ifdef QT_STATEMACHINE_SOLUTION +#include +#include +#include +#include +#endif + +//! [0] +class Factorial : public QObject +{ + Q_OBJECT + Q_PROPERTY(int x READ x WRITE setX) + Q_PROPERTY(int fac READ fac WRITE setFac) +public: + Factorial(QObject *parent = 0) + : QObject(parent), m_x(-1), m_fac(1) + { + } + + int x() const + { + return m_x; + } + + void setX(int x) + { + if (x == m_x) + return; + m_x = x; + emit xChanged(x); + } + + int fac() const + { + return m_fac; + } + + void setFac(int fac) + { + m_fac = fac; + } + +Q_SIGNALS: + void xChanged(int value); + +private: + int m_x; + int m_fac; +}; +//! [0] + +//! [1] +class FactorialLoopTransition : public QSignalTransition +{ +public: + FactorialLoopTransition(Factorial *fact) + : QSignalTransition(fact, SIGNAL(xChanged(int))), m_fact(fact) + {} + + virtual bool eventTest(QEvent *e) + { + if (!QSignalTransition::eventTest(e)) + return false; + QSignalEvent *se = static_cast(e); + return se->arguments().at(0).toInt() > 1; + } + + virtual void onTransition(QEvent *e) + { + QSignalEvent *se = static_cast(e); + int x = se->arguments().at(0).toInt(); + int fac = m_fact->property("fac").toInt(); + m_fact->setProperty("fac", x * fac); + m_fact->setProperty("x", x - 1); + } + +private: + Factorial *m_fact; +}; +//! [1] + +//! [2] +class FactorialDoneTransition : public QSignalTransition +{ +public: + FactorialDoneTransition(Factorial *fact) + : QSignalTransition(fact, SIGNAL(xChanged(int))), m_fact(fact) + {} + + virtual bool eventTest(QEvent *e) + { + if (!QSignalTransition::eventTest(e)) + return false; + QSignalEvent *se = static_cast(e); + return se->arguments().at(0).toInt() <= 1; + } + + virtual void onTransition(QEvent *) + { + fprintf(stdout, "%d\n", m_fact->property("fac").toInt()); + } + +private: + Factorial *m_fact; +}; +//! [2] + +//! [3] +int main(int argc, char **argv) +{ + QCoreApplication app(argc, argv); + Factorial factorial; + QStateMachine machine; +//! [3] + +//! [4] + QState *compute = new QState(machine.rootState()); + compute->assignProperty(&factorial, "fac", 1); + compute->assignProperty(&factorial, "x", 6); + compute->addTransition(new FactorialLoopTransition(&factorial)); +//! [4] + +//! [5] + QFinalState *done = new QFinalState(machine.rootState()); + FactorialDoneTransition *doneTransition = new FactorialDoneTransition(&factorial); + doneTransition->setTargetState(done); + compute->addTransition(doneTransition); +//! [5] + +//! [6] + machine.setInitialState(compute); + QObject::connect(&machine, SIGNAL(finished()), &app, SLOT(quit())); + machine.start(); + + return app.exec(); +} +//! [6] + +#include "main.moc" diff --git a/examples/statemachine/pingpong/main.cpp b/examples/statemachine/pingpong/main.cpp new file mode 100644 index 0000000..331627e --- /dev/null +++ b/examples/statemachine/pingpong/main.cpp @@ -0,0 +1,145 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#ifdef QT_STATEMACHINE_SOLUTION +#include +#include +#include +#endif + +//! [0] +class PingEvent : public QEvent +{ +public: + PingEvent() : QEvent(QEvent::Type(QEvent::User+2)) + {} +}; + +class PongEvent : public QEvent +{ +public: + PongEvent() : QEvent(QEvent::Type(QEvent::User+3)) + {} +}; +//! [0] + +//! [1] +class Pinger : public QState +{ +public: + Pinger(QState *parent) + : QState(parent) {} + +protected: + virtual void onEntry(QEvent *) + { + machine()->postEvent(new PingEvent()); + fprintf(stdout, "ping?\n"); + } +}; +//! [1] + +//! [3] +class PongTransition : public QAbstractTransition +{ +public: + PongTransition() {} + +protected: + virtual bool eventTest(QEvent *e) { + return (e->type() == QEvent::User+3); + } + virtual void onTransition(QEvent *) + { + machine()->postEvent(new PingEvent(), 500); + fprintf(stdout, "ping?\n"); + } +}; +//! [3] + +//! [2] +class PingTransition : public QAbstractTransition +{ +public: + PingTransition() {} + +protected: + virtual bool eventTest(QEvent *e) { + return (e->type() == QEvent::User+2); + } + virtual void onTransition(QEvent *) + { + machine()->postEvent(new PongEvent(), 500); + fprintf(stdout, "pong!\n"); + } +}; +//! [2] + +//! [4] +int main(int argc, char **argv) +{ + QCoreApplication app(argc, argv); + + QStateMachine machine; + QState *group = new QState(QState::ParallelStates); + group->setObjectName("group"); +//! [4] + +//! [5] + Pinger *pinger = new Pinger(group); + pinger->setObjectName("pinger"); + pinger->addTransition(new PongTransition()); + + QState *ponger = new QState(group); + ponger->setObjectName("ponger"); + ponger->addTransition(new PingTransition()); +//! [5] + +//! [6] + machine.addState(group); + machine.setInitialState(group); + machine.start(); + + return app.exec(); +} +//! [6] diff --git a/examples/statemachine/pingpong/pingpong.pro b/examples/statemachine/pingpong/pingpong.pro new file mode 100644 index 0000000..42eab6c --- /dev/null +++ b/examples/statemachine/pingpong/pingpong.pro @@ -0,0 +1,11 @@ +QT = core +win32: CONFIG += console +mac:CONFIG -= app_bundle + +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/pingpong +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS pingpong.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/pingpong +INSTALLS += target sources diff --git a/examples/statemachine/statemachine.pro b/examples/statemachine/statemachine.pro new file mode 100644 index 0000000..5074a3c --- /dev/null +++ b/examples/statemachine/statemachine.pro @@ -0,0 +1,15 @@ +TEMPLATE = subdirs +SUBDIRS = \ + eventtransitions \ + factorial \ + pingpong \ + trafficlight \ + twowaybutton \ + tankgame \ + tankgameplugins + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS statemachine.pro README +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine +INSTALLS += target sources diff --git a/examples/statemachine/tankgame/gameitem.cpp b/examples/statemachine/tankgame/gameitem.cpp new file mode 100644 index 0000000..ad8b37c --- /dev/null +++ b/examples/statemachine/tankgame/gameitem.cpp @@ -0,0 +1,129 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "gameitem.h" + +#include +#include + +GameItem::GameItem(QObject *parent) : QObject(parent) +{ +} + +QPointF GameItem::tryMove(const QPointF &requestedPosition, QLineF *collidedLine, + QGraphicsItem **collidedItem) const +{ + QLineF movementPath(pos(), requestedPosition); + + qreal cannonLength = 0.0; + { + QPointF p1 = boundingRect().center(); + QPointF p2 = QPointF(boundingRect().right() + 10.0, p1.y()); + + cannonLength = QLineF(mapToScene(p1), mapToScene(p2)).length(); + } + + movementPath.setLength(movementPath.length() + cannonLength); + + QRectF boundingRectPath(QPointF(qMin(movementPath.x1(), movementPath.x2()), qMin(movementPath.y1(), movementPath.y2())), + QPointF(qMax(movementPath.x1(), movementPath.x2()), qMax(movementPath.y1(), movementPath.y2()))); + + QList itemsInRect = scene()->items(boundingRectPath, Qt::IntersectsItemBoundingRect); + + QPointF nextPoint = requestedPosition; + QRectF sceneRect = scene()->sceneRect(); + + foreach (QGraphicsItem *item, itemsInRect) { + if (item == static_cast(this)) + continue; + + QPolygonF mappedBoundingRect = item->mapToScene(item->boundingRect()); + for (int i=0; isceneRect().topLeft(), scene()->sceneRect().bottomLeft()); + } + + if (nextPoint.x() > sceneRect.right()) { + nextPoint.rx() = sceneRect.right(); + if (collidedLine != 0) + *collidedLine = QLineF(scene()->sceneRect().topRight(), scene()->sceneRect().bottomRight()); + } + + if (nextPoint.y() < sceneRect.top()) { + nextPoint.ry() = sceneRect.top(); + if (collidedLine != 0) + *collidedLine = QLineF(scene()->sceneRect().topLeft(), scene()->sceneRect().topRight()); + } + + if (nextPoint.y() > sceneRect.bottom()) { + nextPoint.ry() = sceneRect.bottom(); + if (collidedLine != 0) + *collidedLine = QLineF(scene()->sceneRect().bottomLeft(), scene()->sceneRect().bottomRight()); + } + + return nextPoint; +} + diff --git a/examples/statemachine/tankgame/gameitem.h b/examples/statemachine/tankgame/gameitem.h new file mode 100644 index 0000000..90b0a6c --- /dev/null +++ b/examples/statemachine/tankgame/gameitem.h @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GAMEITEM_H +#define GAMEITEM_H + +#include + +QT_BEGIN_NAMESPACE +class QLineF; +QT_END_NAMESPACE +class GameItem: public QObject, public QGraphicsItem +{ + Q_OBJECT +public: + enum { Type = UserType + 1 }; + int type() const { return Type; } + + GameItem(QObject *parent = 0); + + virtual void idle(qreal elapsed) = 0; + +protected: + QPointF tryMove(const QPointF &requestedPosition, QLineF *collidedLine = 0, + QGraphicsItem **collidedItem = 0) const; +}; + +#endif diff --git a/examples/statemachine/tankgame/gameovertransition.cpp b/examples/statemachine/tankgame/gameovertransition.cpp new file mode 100644 index 0000000..360e902 --- /dev/null +++ b/examples/statemachine/tankgame/gameovertransition.cpp @@ -0,0 +1,80 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "gameovertransition.h" +#include "tankitem.h" + +#include +#include + +GameOverTransition::GameOverTransition(QAbstractState *targetState) + : QSignalTransition(new QSignalMapper(), SIGNAL(mapped(QObject*))) +{ + setTargetState(targetState); + + QSignalMapper *mapper = qobject_cast(senderObject()); + mapper->setParent(this); +} + +void GameOverTransition::addTankItem(TankItem *tankItem) +{ + m_tankItems.append(tankItem); + + QSignalMapper *mapper = qobject_cast(senderObject()); + mapper->setMapping(tankItem, tankItem); + connect(tankItem, SIGNAL(aboutToBeDestroyed()), mapper, SLOT(map())); +} + +bool GameOverTransition::eventTest(QEvent *e) +{ + bool ret = QSignalTransition::eventTest(e); + + if (ret) { + QSignalEvent *signalEvent = static_cast(e); + QObject *sender = qvariant_cast(signalEvent->arguments().at(0)); + TankItem *tankItem = qobject_cast(sender); + m_tankItems.removeAll(tankItem); + + return m_tankItems.size() <= 1; + } else { + return false; + } +} diff --git a/examples/statemachine/tankgame/gameovertransition.h b/examples/statemachine/tankgame/gameovertransition.h new file mode 100644 index 0000000..5e99a75 --- /dev/null +++ b/examples/statemachine/tankgame/gameovertransition.h @@ -0,0 +1,63 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef GAMEOVERTRANSITION_H +#define GAMEOVERTRANSITION_H + +#include + +class TankItem; +class GameOverTransition: public QSignalTransition +{ + Q_OBJECT +public: + GameOverTransition(QAbstractState *targetState); + + void addTankItem(TankItem *tankItem); + +protected: + bool eventTest(QEvent *event); + +private: + QList m_tankItems; +}; + +#endif diff --git a/examples/statemachine/tankgame/main.cpp b/examples/statemachine/tankgame/main.cpp new file mode 100644 index 0000000..185ad68 --- /dev/null +++ b/examples/statemachine/tankgame/main.cpp @@ -0,0 +1,53 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "mainwindow.h" + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + MainWindow mainWindow; + mainWindow.show(); + + return app.exec(); +} diff --git a/examples/statemachine/tankgame/mainwindow.cpp b/examples/statemachine/tankgame/mainwindow.cpp new file mode 100644 index 0000000..46e0db3 --- /dev/null +++ b/examples/statemachine/tankgame/mainwindow.cpp @@ -0,0 +1,342 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "mainwindow.h" +#include "tankitem.h" +#include "rocketitem.h" +#include "plugin.h" +#include "gameovertransition.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MainWindow::MainWindow(QWidget *parent) + : QMainWindow(parent), m_scene(0), m_machine(0), m_runningState(0), m_started(false) +{ + init(); +} + +MainWindow::~MainWindow() +{ +} + +void MainWindow::addWall(const QRectF &wall) +{ + QGraphicsRectItem *item = new QGraphicsRectItem; + item->setRect(wall); + item->setBrush(Qt::darkGreen); + item->setPen(QPen(Qt::black, 0)); + + m_scene->addItem(item); +} + +void MainWindow::init() +{ + setWindowTitle("Pluggable Tank Game"); + + QGraphicsView *view = new QGraphicsView(this); + view->setRenderHints(QPainter::Antialiasing); + setCentralWidget(view); + + m_scene = new QGraphicsScene(this); + view->setScene(m_scene); + + QRectF sceneRect = QRectF(-200.0, -200.0, 400.0, 400.0); + m_scene->setSceneRect(sceneRect); + + { + TankItem *item = new TankItem(this); + + item->setPos(m_scene->sceneRect().topLeft() + QPointF(30.0, 30.0)); + item->setDirection(45.0); + item->setColor(Qt::red); + + m_spawns.append(item); + } + + { + TankItem *item = new TankItem(this); + + item->setPos(m_scene->sceneRect().topRight() + QPointF(-30.0, 30.0)); + item->setDirection(135.0); + item->setColor(Qt::green); + + m_spawns.append(item); + } + + { + TankItem *item = new TankItem(this); + + item->setPos(m_scene->sceneRect().bottomRight() + QPointF(-30.0, -30.0)); + item->setDirection(225.0); + item->setColor(Qt::blue); + + m_spawns.append(item); + } + + { + TankItem *item = new TankItem(this); + + item->setPos(m_scene->sceneRect().bottomLeft() + QPointF(30.0, -30.0)); + item->setDirection(315.0); + item->setColor(Qt::yellow); + + m_spawns.append(item); + } + + QPointF centerOfMap = sceneRect.center(); + + addWall(QRectF(centerOfMap + QPointF(-50.0, -60.0), centerOfMap + QPointF(50.0, -50.0))); + addWall(QRectF(centerOfMap - QPointF(-50.0, -60.0), centerOfMap - QPointF(50.0, -50.0))); + addWall(QRectF(centerOfMap + QPointF(-50.0, -50.0), centerOfMap + QPointF(-40.0, 50.0))); + addWall(QRectF(centerOfMap - QPointF(-50.0, -50.0), centerOfMap - QPointF(-40.0, 50.0))); + + addWall(QRectF(sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, -10.0), + sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, 100.0))); + addWall(QRectF(sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, 10.0), + sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, -100.0))); + addWall(QRectF(sceneRect.topLeft() + QPointF(-10.0, sceneRect.height() / 2.0 - 5.0), + sceneRect.topLeft() + QPointF(100.0, sceneRect.height() / 2.0 + 5.0))); + addWall(QRectF(sceneRect.topRight() + QPointF(10.0, sceneRect.height() / 2.0 - 5.0), + sceneRect.topRight() + QPointF(-100.0, sceneRect.height() / 2.0 + 5.0))); + + + QAction *addTankAction = menuBar()->addAction("&Add tank"); + QAction *runGameAction = menuBar()->addAction("&Run game"); + runGameAction->setObjectName("runGameAction"); + QAction *stopGameAction = menuBar()->addAction("&Stop game"); + menuBar()->addSeparator(); + QAction *quitAction = menuBar()->addAction("&Quit"); + + connect(addTankAction, SIGNAL(triggered()), this, SLOT(addTank())); + connect(quitAction, SIGNAL(triggered()), this, SLOT(close())); + + m_machine = new QStateMachine(this); + QState *stoppedState = new QState(m_machine->rootState()); + stoppedState->setObjectName("stoppedState"); + stoppedState->assignProperty(runGameAction, "enabled", true); + stoppedState->assignProperty(stopGameAction, "enabled", false); + stoppedState->assignProperty(this, "started", false); + m_machine->setInitialState(stoppedState); + +//! [5] + QState *spawnsAvailable = new QState(stoppedState); + spawnsAvailable->assignProperty(addTankAction, "enabled", true); + + QState *noSpawnsAvailable = new QState(stoppedState); + noSpawnsAvailable->assignProperty(addTankAction, "enabled", false); +//! [5] + spawnsAvailable->setObjectName("spawnsAvailable"); + noSpawnsAvailable->setObjectName("noSpawnsAvailable"); + + spawnsAvailable->addTransition(this, SIGNAL(mapFull()), noSpawnsAvailable); + +//! [3] + QHistoryState *hs = new QHistoryState(stoppedState); + hs->setDefaultState(spawnsAvailable); +//! [3] + hs->setObjectName("hs"); + + stoppedState->setInitialState(hs); + +//! [0] + m_runningState = new QState(QState::ParallelStates, m_machine->rootState()); +//! [0] + m_runningState->setObjectName("runningState"); + m_runningState->assignProperty(addTankAction, "enabled", false); + m_runningState->assignProperty(runGameAction, "enabled", false); + m_runningState->assignProperty(stopGameAction, "enabled", true); + + QState *gameOverState = new QState(m_machine->rootState()); + gameOverState->setObjectName("gameOverState"); + gameOverState->assignProperty(stopGameAction, "enabled", false); + connect(gameOverState, SIGNAL(entered()), this, SLOT(gameOver())); + + stoppedState->addTransition(runGameAction, SIGNAL(triggered()), m_runningState); + m_runningState->addTransition(stopGameAction, SIGNAL(triggered()), stoppedState); + + m_gameOverTransition = new GameOverTransition(gameOverState); + m_runningState->addTransition(m_gameOverTransition); + + QTimer *timer = new QTimer(this); + timer->setInterval(100); + connect(timer, SIGNAL(timeout()), this, SLOT(runStep())); + connect(m_runningState, SIGNAL(entered()), timer, SLOT(start())); + connect(m_runningState, SIGNAL(exited()), timer, SLOT(stop())); + + m_machine->start(); + m_time.start(); +} + +void MainWindow::runStep() +{ + if (!m_started) { + m_time.restart(); + m_started = true; + } else { + int elapsed = m_time.elapsed(); + if (elapsed > 0) { + m_time.restart(); + qreal elapsedSecs = elapsed / 1000.0; + QList items = m_scene->items(); + foreach (QGraphicsItem *item, items) { + if (GameItem *gameItem = qgraphicsitem_cast(item)) + gameItem->idle(elapsedSecs); + } + } + } +} + +void MainWindow::gameOver() +{ + QList items = m_scene->items(); + + TankItem *lastTankStanding = 0; + foreach (QGraphicsItem *item, items) { + if (GameItem *gameItem = qgraphicsitem_cast(item)) { + if ((lastTankStanding = qobject_cast(gameItem)) != 0) + break; + } + } + + QMessageBox::information(this, "Game over!", + QString::fromLatin1("The tank played by '%1' has won!").arg(lastTankStanding->objectName())); +} + +void MainWindow::addRocket() +{ + TankItem *tankItem = qobject_cast(sender()); + if (tankItem != 0) { + RocketItem *rocketItem = new RocketItem; + + QPointF s = tankItem->mapToScene(QPointF(tankItem->boundingRect().right() + 10.0, + tankItem->boundingRect().center().y())); + rocketItem->setPos(s); + rocketItem->setDirection(tankItem->direction()); + m_scene->addItem(rocketItem); + } +} + +void MainWindow::addTank() +{ + Q_ASSERT(!m_spawns.isEmpty()); + + QDir pluginsDir(qApp->applicationDirPath()); +#if defined(Q_OS_WIN) + if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") + pluginsDir.cdUp(); +#elif defined(Q_OS_MAC) + if (pluginsDir.dirName() == "MacOS") { + pluginsDir.cdUp(); + pluginsDir.cdUp(); + pluginsDir.cdUp(); + } +#endif + + pluginsDir.cd("plugins"); + + QStringList itemNames; + QList items; + foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { + QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); + QObject *possiblePlugin = loader.instance(); + if (Plugin *plugin = qobject_cast(possiblePlugin)) { + QString objectName = possiblePlugin->objectName(); + if (objectName.isEmpty()) + objectName = fileName; + + itemNames.append(objectName); + items.append(plugin); + } + } + + if (items.isEmpty()) { + QMessageBox::information(this, "No tank types found", "Please build the errorstateplugins directory"); + return; + } + + bool ok; +//! [1] + QString selectedName = QInputDialog::getItem(this, "Select a tank type", "Tank types", + itemNames, 0, false, &ok); +//! [1] + + if (ok && !selectedName.isEmpty()) { + int idx = itemNames.indexOf(selectedName); + if (Plugin *plugin = idx >= 0 ? items.at(idx) : 0) { + TankItem *tankItem = m_spawns.takeLast(); + tankItem->setObjectName(selectedName); + tankItem->setToolTip(selectedName); + m_scene->addItem(tankItem); + connect(tankItem, SIGNAL(cannonFired()), this, SLOT(addRocket())); + if (m_spawns.isEmpty()) + emit mapFull(); + + m_gameOverTransition->addTankItem(tankItem); + + QState *region = new QState(m_runningState); + region->setObjectName(QString::fromLatin1("region%1").arg(m_spawns.size())); +//! [2] + QState *pluginState = plugin->create(region, tankItem); +//! [2] + region->setInitialState(pluginState); + + // If the plugin has an error it is disabled +//! [4] + QState *errorState = new QState(region); + errorState->setObjectName(QString::fromLatin1("errorState%1").arg(m_spawns.size())); + errorState->assignProperty(tankItem, "enabled", false); + pluginState->setErrorState(errorState); +//! [4] + } + } +} + diff --git a/examples/statemachine/tankgame/mainwindow.h b/examples/statemachine/tankgame/mainwindow.h new file mode 100644 index 0000000..4ae8f7a --- /dev/null +++ b/examples/statemachine/tankgame/mainwindow.h @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef MAINWINDOW_H +#define MAINWINDOW_H + +#include +#include + +QT_BEGIN_NAMESPACE +class QGraphicsScene; +class QStateMachine; +class QState; +QT_END_NAMESPACE +class GameOverTransition; +class TankItem; + +class MainWindow: public QMainWindow +{ + Q_OBJECT + Q_PROPERTY(bool started READ started WRITE setStarted) +public: + MainWindow(QWidget *parent = 0); + ~MainWindow(); + + void setStarted(bool b) { m_started = b; } + bool started() const { return m_started; } + +public slots: + void addTank(); + void addRocket(); + void runStep(); + void gameOver(); + +signals: + void mapFull(); + +private: + void init(); + void addWall(const QRectF &wall); + + QGraphicsScene *m_scene; + + QStateMachine *m_machine; + QState *m_runningState; + GameOverTransition *m_gameOverTransition; + + QList m_spawns; + QTime m_time; + + bool m_started : 1; +}; + +#endif + diff --git a/examples/statemachine/tankgame/plugin.h b/examples/statemachine/tankgame/plugin.h new file mode 100644 index 0000000..ddd10b7 --- /dev/null +++ b/examples/statemachine/tankgame/plugin.h @@ -0,0 +1,62 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef PLUGIN_H +#define PLUGIN_H + +#include + +QT_BEGIN_NAMESPACE +class QState; +QT_END_NAMESPACE +class Plugin +{ +public: + virtual ~Plugin() {} + + virtual QState *create(QState *parentState, QObject *tank) = 0; +}; + +QT_BEGIN_NAMESPACE +Q_DECLARE_INTERFACE(Plugin, "TankPlugin") +QT_END_NAMESPACE + +#endif diff --git a/examples/statemachine/tankgame/rocketitem.cpp b/examples/statemachine/tankgame/rocketitem.cpp new file mode 100644 index 0000000..3ace8e8 --- /dev/null +++ b/examples/statemachine/tankgame/rocketitem.cpp @@ -0,0 +1,101 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "rocketitem.h" +#include "tankitem.h" + +#include +#include + +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +RocketItem::RocketItem(QObject *parent) + : GameItem(parent), m_direction(0.0), m_distance(300.0) +{ +} + +QRectF RocketItem::boundingRect() const +{ + return QRectF(-1.0, -1.0, 2.0, 2.0); +} + +void RocketItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + painter->setBrush(Qt::black); + painter->drawEllipse(boundingRect()); +} + +void RocketItem::idle(qreal elapsed) +{ + qreal dist = elapsed * speed(); + + m_distance -= dist; + if (m_distance < 0.0) { + scene()->removeItem(this); + delete this; + return; + } + + qreal a = m_direction * M_PI / 180.0; + + qreal yd = dist * sin(a); + qreal xd = dist * sin(M_PI / 2.0 - a); + + QPointF requestedPosition = pos() + QPointF(xd, yd); + QGraphicsItem *collidedItem = 0; + QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); + if (requestedPosition == nextPosition) { + setPos(nextPosition); + } else { + if (GameItem *gameItem = qgraphicsitem_cast(collidedItem)) { + TankItem *tankItem = qobject_cast(gameItem); + if (tankItem != 0) + tankItem->hitByRocket(); + } + + scene()->removeItem(this); + delete this; + } +} diff --git a/examples/statemachine/tankgame/rocketitem.h b/examples/statemachine/tankgame/rocketitem.h new file mode 100644 index 0000000..31146a6 --- /dev/null +++ b/examples/statemachine/tankgame/rocketitem.h @@ -0,0 +1,66 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef ROCKETITEM_H +#define ROCKETITEM_H + +#include "gameitem.h" + +class RocketItem: public GameItem +{ + Q_OBJECT +public: + RocketItem(QObject *parent = 0); + + virtual void idle(qreal elapsed); + qreal speed() const { return 100.0; } + void setDirection(qreal direction) { m_direction = direction; } + +protected: + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + QRectF boundingRect() const; + +private: + qreal m_direction; + qreal m_distance; +}; + +#endif diff --git a/examples/statemachine/tankgame/tankgame.pro b/examples/statemachine/tankgame/tankgame.pro new file mode 100644 index 0000000..59415be --- /dev/null +++ b/examples/statemachine/tankgame/tankgame.pro @@ -0,0 +1,19 @@ +HEADERS += mainwindow.h \ + plugin.h \ + tankitem.h \ + rocketitem.h \ + gameitem.h \ + gameovertransition.h +SOURCES += main.cpp \ + mainwindow.cpp \ + tankitem.cpp \ + rocketitem.cpp \ + gameitem.cpp \ + gameovertransition.cpp +CONFIG += console + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS tankgame.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame +INSTALLS += target sources diff --git a/examples/statemachine/tankgame/tankitem.cpp b/examples/statemachine/tankgame/tankitem.cpp new file mode 100644 index 0000000..393d65f --- /dev/null +++ b/examples/statemachine/tankgame/tankitem.cpp @@ -0,0 +1,302 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "tankitem.h" + +#include +#include +#include + +#include + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +class Action +{ +public: + Action(TankItem *item) : m_item(item) + { + } + + TankItem *item() const { return m_item; } + void setItem(TankItem *item) { m_item = item; } + + virtual bool apply(qreal timeDelta) = 0; + +private: + TankItem *m_item; +}; + +class MoveAction: public Action +{ +public: + MoveAction(TankItem *item, qreal distance) + : Action(item), m_distance(distance) + { + m_reverse = m_distance < 0.0; + } + + bool apply(qreal timeDelta) + { + qreal dist = timeDelta * item()->speed() * (m_reverse ? -1.0 : 1.0); + + bool done = false; + if (qAbs(m_distance) < qAbs(dist)) { + done = true; + dist = m_distance; + } + m_distance -= dist; + + qreal a = item()->direction() * M_PI / 180.0; + + qreal yd = dist * sin(a); + qreal xd = dist * sin(M_PI / 2.0 - a); + + item()->setPos(item()->pos() + QPointF(xd, yd)); + return !done; + } + +private: + qreal m_distance; + bool m_reverse; +}; + +class TurnAction: public Action +{ +public: + TurnAction(TankItem *item, qreal distance) + : Action(item), m_distance(distance) + { + m_reverse = m_distance < 0.0; + } + + bool apply(qreal timeDelta) + { + qreal dist = timeDelta * item()->angularSpeed() * (m_reverse ? -1.0 : 1.0); + bool done = false; + if (qAbs(m_distance) < qAbs(dist)) { + done = true; + dist = m_distance; + } + m_distance -= dist; + + item()->setDirection(item()->direction() + dist); + return !done; + } + +private: + qreal m_distance; + bool m_reverse; +}; + +TankItem::TankItem(QObject *parent) + : GameItem(parent), m_currentAction(0), m_currentDirection(0.0), m_enabled(true) +{ + connect(this, SIGNAL(cannonFired()), this, SIGNAL(actionCompleted())); +} + +void TankItem::idle(qreal elapsed) +{ + if (m_enabled) { + if (m_currentAction != 0) { + if (!m_currentAction->apply(elapsed)) { + setAction(0); + emit actionCompleted(); + } + + QGraphicsItem *item = 0; + qreal distance = distanceToObstacle(&item); + if (TankItem *tankItem = qgraphicsitem_cast(item)) + emit tankSpotted(tankItem->direction(), distance); + } + } +} + +void TankItem::hitByRocket() +{ + emit aboutToBeDestroyed(); + deleteLater(); +} + +void TankItem::setAction(Action *newAction) +{ + if (m_currentAction != 0) + delete m_currentAction; + + m_currentAction = newAction; +} + +void TankItem::fireCannon() +{ + emit cannonFired(); +} + +void TankItem::moveForwards(qreal length) +{ + setAction(new MoveAction(this, length)); +} + +void TankItem::moveBackwards(qreal length) +{ + setAction(new MoveAction(this, -length)); +} + +void TankItem::turn(qreal degrees) +{ + setAction(new TurnAction(this, degrees)); +} + +void TankItem::turnTo(qreal degrees) +{ + setAction(new TurnAction(this, degrees - direction())); +} + +void TankItem::stop() +{ + setAction(0); +} + +QVariant TankItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) +{ + if (change == ItemPositionChange && scene()) { + QPointF requestedPosition = value.toPointF(); + QLineF collidedLine; + QPointF nextPoint = tryMove(requestedPosition, &collidedLine); + if (nextPoint != requestedPosition) + emit collision(collidedLine); + return nextPoint; + } else { + return QGraphicsItem::itemChange(change, value); + } +} + + +void TankItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) +{ + QRectF brect = boundingRect(); + + painter->setBrush(m_color); + painter->setPen(Qt::black); + + // body + painter->drawRect(brect.adjusted(0.0, 4.0, -2.0, -4.0)); + + // cannon + QRectF cannonBase = brect.adjusted(10.0, 6.0, -12.0, -6.0); + painter->drawEllipse(cannonBase); + + painter->drawRect(QRectF(QPointF(cannonBase.center().x(), cannonBase.center().y() - 2.0), + QPointF(brect.right(), cannonBase.center().y() + 2.0))); + + // left track + painter->setBrush(QBrush(Qt::black, Qt::VerPattern)); + QRectF leftTrackRect = QRectF(brect.topLeft(), QPointF(brect.right() - 2.0, brect.top() + 4.0)); + painter->fillRect(leftTrackRect, Qt::darkYellow); + painter->drawRect(leftTrackRect); + + // right track + QRectF rightTrackRect = QRectF(QPointF(brect.left(), brect.bottom() - 4.0), + QPointF(brect.right() - 2.0, brect.bottom())); + painter->fillRect(rightTrackRect, Qt::darkYellow); + painter->drawRect(rightTrackRect); + + if (!m_enabled) { + painter->setPen(QPen(Qt::red, 5)); + + painter->drawEllipse(brect); + + QPainterPath path; + path.addEllipse(brect); + painter->setClipPath(path); + painter->drawLine(brect.topRight(), brect.bottomLeft()); + } +} + +QRectF TankItem::boundingRect() const +{ + return QRectF(-20.0, -10.0, 40.0, 20.0); +} + +qreal TankItem::direction() const +{ + return m_currentDirection; +} + +void TankItem::setDirection(qreal newDirection) +{ + int fullRotations = int(newDirection) / 360; + newDirection -= fullRotations * 360.0; + + qreal diff = newDirection - m_currentDirection; + m_currentDirection = newDirection; + rotate(diff); +} + +qreal TankItem::distanceToObstacle(QGraphicsItem **obstacle) const +{ + qreal dist = sqrt(pow(scene()->sceneRect().width(), 2) + pow(scene()->sceneRect().height(), 2)); + + qreal a = m_currentDirection * M_PI / 180.0; + + qreal yd = dist * sin(a); + qreal xd = dist * sin(M_PI / 2.0 - a); + + QPointF requestedPosition = pos() + QPointF(xd, yd); + QGraphicsItem *collidedItem = 0; + QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); + if (collidedItem != 0) { + if (obstacle != 0) + *obstacle = collidedItem; + + QPointF d = nextPosition - pos(); + return sqrt(pow(d.x(), 2) + pow(d.y(), 2)); + } else { + return 0.0; + } +} + +qreal TankItem::distanceToObstacle() const +{ + return distanceToObstacle(0); +} + diff --git a/examples/statemachine/tankgame/tankitem.h b/examples/statemachine/tankgame/tankitem.h new file mode 100644 index 0000000..942fca8 --- /dev/null +++ b/examples/statemachine/tankgame/tankitem.h @@ -0,0 +1,109 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef TANKITEM_H +#define TANKITEM_H + +#include "gameitem.h" + +#include + +class Action; +class TankItem: public GameItem +{ + Q_OBJECT + Q_PROPERTY(bool enabled READ enabled WRITE setEnabled) + Q_PROPERTY(qreal direction READ direction WRITE turnTo) + Q_PROPERTY(qreal distanceToObstacle READ distanceToObstacle) +public: + TankItem(QObject *parent = 0); + + void setColor(const QColor &color) { m_color = color; } + QColor color() const { return m_color; } + + void idle(qreal elapsed); + void setDirection(qreal newDirection); + + qreal speed() const { return 90.0; } + qreal angularSpeed() const { return 90.0; } + + QRectF boundingRect() const; + + void hitByRocket(); + + void setEnabled(bool b) { m_enabled = b; } + bool enabled() const { return m_enabled; } + + qreal direction() const; + qreal distanceToObstacle() const; + qreal distanceToObstacle(QGraphicsItem **item) const; + +//! [0] +signals: + void tankSpotted(qreal direction, qreal distance); + void collision(const QLineF &collidedLine); + void actionCompleted(); + void cannonFired(); + void aboutToBeDestroyed(); + +public slots: + void moveForwards(qreal length = 10.0); + void moveBackwards(qreal length = 10.0); + void turn(qreal degrees = 30.0); + void turnTo(qreal degrees = 0.0); + void stop(); + void fireCannon(); +//! [0] + +protected: + virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); + QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); + +private: + void setAction(Action *newAction); + + Action *m_currentAction; + qreal m_currentDirection; + QColor m_color; + bool m_enabled; +}; + +#endif diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai.pro b/examples/statemachine/tankgameplugins/random_ai/random_ai.pro new file mode 100644 index 0000000..5bc0b26 --- /dev/null +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai.pro @@ -0,0 +1,13 @@ +TEMPLATE = lib +CONFIG += plugin +INCLUDEPATH += ../.. +HEADERS = random_ai_plugin.h +SOURCES = random_ai_plugin.cpp +TARGET = $$qtLibraryTarget(random_ai) +DESTDIR = ../../tankgame/plugins + +#! [0] +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS random_ai.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/random_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp new file mode 100644 index 0000000..d360de9 --- /dev/null +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "random_ai_plugin.h" + +#include +#include + +#include + +QState *RandomAiPlugin::create(QState *parentState, QObject *tank) +{ + qsrand(uint(time(NULL))); + + QState *topLevel = new QState(parentState); + + QState *selectNextActionState = new SelectActionState(topLevel); + topLevel->setInitialState(selectNextActionState); + + QState *fireState = new RandomDistanceState(topLevel); + connect(fireState, SIGNAL(distanceComputed(qreal)), tank, SLOT(fireCannon())); + selectNextActionState->addTransition(selectNextActionState, SIGNAL(fireSelected()), fireState); + + QState *moveForwardsState = new RandomDistanceState(topLevel); + connect(moveForwardsState, SIGNAL(distanceComputed(qreal)), tank, SLOT(moveForwards(qreal))); + selectNextActionState->addTransition(selectNextActionState, SIGNAL(moveForwardsSelected()), moveForwardsState); + + QState *moveBackwardsState = new RandomDistanceState(topLevel); + connect(moveBackwardsState, SIGNAL(distanceComputed(qreal)), tank, SLOT(moveBackwards(qreal))); + selectNextActionState->addTransition(selectNextActionState, SIGNAL(moveBackwardsSelected()), moveBackwardsState); + + QState *turnState = new RandomDistanceState(topLevel); + connect(turnState, SIGNAL(distanceComputed(qreal)), tank, SLOT(turn(qreal))); + selectNextActionState->addTransition(selectNextActionState, SIGNAL(turnSelected()), turnState); + + topLevel->addTransition(tank, SIGNAL(actionCompleted()), selectNextActionState); + + return topLevel; +} + +Q_EXPORT_PLUGIN2(random_ai, RandomAiPlugin) diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h new file mode 100644 index 0000000..9faeeac --- /dev/null +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h @@ -0,0 +1,105 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef RANDOM_AI_PLUGIN_H +#define RANDOM_AI_PLUGIN_H + +#include +#include + +#include + +class SelectActionState: public QState +{ + Q_OBJECT +public: + SelectActionState(QState *parent = 0) : QState(parent) + { + } + +signals: + void fireSelected(); + void moveForwardsSelected(); + void moveBackwardsSelected(); + void turnSelected(); + +protected: + void onEntry(QEvent *) + { + int rand = qrand() % 4; + switch (rand) { + case 0: emit fireSelected(); break; + case 1: emit moveForwardsSelected(); break; + case 2: emit moveBackwardsSelected(); break; + case 3: emit turnSelected(); break; + }; + } +}; + +class RandomDistanceState: public QState +{ + Q_OBJECT +public: + RandomDistanceState(QState *parent = 0) : QState(parent) + { + } + +signals: + void distanceComputed(qreal distance); + +protected: + void onEntry(QEvent *) + { + emit distanceComputed(qreal(qrand() % 180)); + } +}; + +class RandomAiPlugin: public QObject, public Plugin +{ + Q_OBJECT + Q_INTERFACES(Plugin) +public: + RandomAiPlugin() { setObjectName("Random"); } + + virtual QState *create(QState *parentState, QObject *tank); +}; + +#endif // RANDOM_AI_PLUGIN_H diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp new file mode 100644 index 0000000..6aae015 --- /dev/null +++ b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp @@ -0,0 +1,89 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "seek_ai.h" + +QState *SeekAi::create(QState *parentState, QObject *tank) +{ + QState *topLevel = new QState(parentState); + topLevel->setObjectName("topLevel"); + + QState *seek = new QState(topLevel); + seek->setObjectName("seek"); + topLevel->setInitialState(seek); + + QState *lookForNearestWall = new SearchState(tank, seek); + lookForNearestWall->setObjectName("lookForNearestWall"); + seek->setInitialState(lookForNearestWall); + + QState *driveToFirstObstacle = new QState(seek); + driveToFirstObstacle->setObjectName("driveToFirstObstacle"); + lookForNearestWall->addTransition(lookForNearestWall, SIGNAL(nearestObstacleStraightAhead()), + driveToFirstObstacle); + + QState *drive = new QState(driveToFirstObstacle); + drive->setObjectName("drive"); + driveToFirstObstacle->setInitialState(drive); + connect(drive, SIGNAL(entered()), tank, SLOT(moveForwards())); + connect(drive, SIGNAL(exited()), tank, SLOT(stop())); + + // Go in loop + QState *finishedDriving = new QState(driveToFirstObstacle); + finishedDriving->setObjectName("finishedDriving"); + drive->addTransition(tank, SIGNAL(actionCompleted()), finishedDriving); + finishedDriving->addTransition(drive); + + QState *turnTo = new QState(seek); + turnTo->setObjectName("turnTo"); + driveToFirstObstacle->addTransition(new CollisionTransition(tank, turnTo)); + + turnTo->addTransition(tank, SIGNAL(actionCompleted()), driveToFirstObstacle); + + ChaseState *chase = new ChaseState(tank, topLevel); + chase->setObjectName("chase"); + seek->addTransition(new TankSpottedTransition(tank, chase)); + chase->addTransition(chase, SIGNAL(finished()), driveToFirstObstacle); + chase->addTransition(new TankSpottedTransition(tank, chase)); + + return topLevel; +} + +Q_EXPORT_PLUGIN2(seek_ai, SeekAi) diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h new file mode 100644 index 0000000..e44ad07 --- /dev/null +++ b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h @@ -0,0 +1,249 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SEEK_AI_H +#define SEEK_AI_H + +#include + +#include +#include +#include +#include +#include +#include +#include + +class SearchState: public QState +{ + Q_OBJECT +public: + SearchState(QObject *tank, QState *parentState = 0) + : QState(parentState), + m_tank(tank), + m_distanceToTurn(360.0), + m_nearestDistance(-1.0), + m_directionOfNearestObstacle(0.0) + { + } + +public slots: + void turnAlittle() + { + qreal dist = m_tank->property("distanceToObstacle").toDouble(); + + if (m_nearestDistance < 0.0 || dist < m_nearestDistance) { + m_nearestDistance = dist; + m_directionOfNearestObstacle = m_tank->property("direction").toDouble(); + } + + m_distanceToTurn -= 10.0; + if (m_distanceToTurn < 0.0) { + disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); + connect(m_tank, SIGNAL(actionCompleted()), this, SIGNAL(nearestObstacleStraightAhead())); + m_tank->setProperty("direction", m_directionOfNearestObstacle); + } + + qreal currentDirection = m_tank->property("direction").toDouble(); + m_tank->setProperty("direction", currentDirection + 10.0); + } + +signals: + void nearestObstacleStraightAhead(); + +protected: + void onEntry(QEvent *) + { + connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); + turnAlittle(); + } + + void onExit(QEvent *) + { + disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); + disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(nearestObstacleStraightAhead())); + } + +private: + QObject *m_tank; + + qreal m_distanceToTurn; + qreal m_nearestDistance; + qreal m_directionOfNearestObstacle; +}; + +class CollisionTransition: public QSignalTransition +{ +public: + CollisionTransition(QObject *tank, QState *turnTo) + : QSignalTransition(tank, SIGNAL(collision(QLineF))), + m_tank(tank), + m_turnTo(turnTo) + { + setTargetState(turnTo); + } + +protected: + bool eventTest(QEvent *event) + { + bool b = QSignalTransition::eventTest(event); + if (b) { + QSignalEvent *se = static_cast(event); + m_lastLine = se->arguments().at(0).toLineF(); + } + return b; + } + + void onTransition(QEvent *) + { + qreal angleOfWall = m_lastLine.angle(); + + qreal newDirection; + if (qrand() % 2 == 0) + newDirection = angleOfWall; + else + newDirection = angleOfWall - 180.0; + + m_turnTo->assignProperty(m_tank, "direction", newDirection); + } + +private: + QLineF m_lastLine; + QObject *m_tank; + QState *m_turnTo; +}; + +class ChaseState: public QState +{ + class GoToLocationState: public QState + { + public: + GoToLocationState(QObject *tank, QState *parentState = 0) + : QState(parentState), m_tank(tank), m_distance(0.0) + { + } + + void setDistance(qreal distance) { m_distance = distance; } + + protected: + void onEntry() + { + QMetaObject::invokeMethod(m_tank, "moveForwards", Q_ARG(qreal, m_distance)); + } + + private: + QObject *m_tank; + qreal m_distance; + }; + +public: + ChaseState(QObject *tank, QState *parentState = 0) : QState(parentState), m_tank(tank) + { + QState *fireCannon = new QState(this); + fireCannon->setObjectName("fireCannon"); + connect(fireCannon, SIGNAL(entered()), tank, SLOT(fireCannon())); + setInitialState(fireCannon); + + m_goToLocation = new GoToLocationState(tank, this); + m_goToLocation->setObjectName("goToLocation"); + fireCannon->addTransition(tank, SIGNAL(actionCompleted()), m_goToLocation); + + m_turnToDirection = new QState(this); + m_turnToDirection->setObjectName("turnToDirection"); + m_goToLocation->addTransition(tank, SIGNAL(actionCompleted()), m_turnToDirection); + + QFinalState *finalState = new QFinalState(this); + finalState->setObjectName("finalState"); + m_turnToDirection->addTransition(tank, SIGNAL(actionCompleted()), finalState); + } + + void setDirection(qreal direction) + { + m_turnToDirection->assignProperty(m_tank, "direction", direction); + } + + void setDistance(qreal distance) + { + m_goToLocation->setDistance(distance); + } + +private: + QObject *m_tank; + GoToLocationState *m_goToLocation; + QState *m_turnToDirection; + +}; + +class TankSpottedTransition: public QSignalTransition +{ +public: + TankSpottedTransition(QObject *tank, ChaseState *target) : QSignalTransition(tank, SIGNAL(tankSpotted(qreal,qreal))), m_chase(target) + { + setTargetState(target); + } + +protected: + bool eventTest(QEvent *event) + { + bool b = QSignalTransition::eventTest(event); + if (b) { + QSignalEvent *se = static_cast(event); + m_chase->setDirection(se->arguments().at(0).toDouble()); + m_chase->setDistance(se->arguments().at(1).toDouble()); + } + return b; + } + +private: + ChaseState *m_chase; +}; + +class SeekAi: public QObject, public Plugin +{ + Q_OBJECT + Q_INTERFACES(Plugin) +public: + SeekAi() { setObjectName("Seek and destroy"); } + + virtual QState *create(QState *parentState, QObject *tank); +}; + +#endif diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro new file mode 100644 index 0000000..0d8bf2e --- /dev/null +++ b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro @@ -0,0 +1,13 @@ +TEMPLATE = lib +CONFIG += plugin +INCLUDEPATH += ../.. +HEADERS = seek_ai.h +SOURCES = seek_ai.cpp +TARGET = $$qtLibraryTarget(seek_ai) +DESTDIR = ../../tankgame/plugins + +#! [0] +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS seek_ai.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/seek_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp new file mode 100644 index 0000000..581a6b2 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spin_ai.h" + +#include + +QState *SpinAi::create(QState *parentState, QObject *tank) +{ + QState *topLevel = new QState(parentState); + QState *spinState = new SpinState(tank, topLevel); + topLevel->setInitialState(spinState); + + // When tank is spotted, fire two times and go back to spin state + QState *fireState = new QState(topLevel); + + QState *fireOnce = new QState(fireState); + fireState->setInitialState(fireOnce); + connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); + + QState *fireTwice = new QState(fireState); + connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); + + fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); + fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); + + spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); + + return topLevel; +} + +Q_EXPORT_PLUGIN2(spin_ai, SpinAi) diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h new file mode 100644 index 0000000..652e8b8 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPIN_AI_H +#define SPIN_AI_H + +#include + +#include +#include +#include + +class SpinState: public QState +{ + Q_OBJECT +public: + SpinState(QObject *tank, QState *parent) : QState(parent), m_tank(tank) + { + } + +public slots: + void spin() + { + m_tank->setProperty("direction", m_tank->property("direction").toDouble() + 90.0); + } + +protected: + void onEntry(QEvent *) + { + connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); + spin(); + } + + void onExit(QEvent *) + { + disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); + } + +private: + QObject *m_tank; + +}; + +class SpinAi: public QObject, public Plugin +{ + Q_OBJECT + Q_INTERFACES(Plugin) +public: + SpinAi() { setObjectName("Spin and destroy"); } + + virtual QState *create(QState *parentState, QObject *tank); +}; + +#endif diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro new file mode 100644 index 0000000..8ab4da0 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro @@ -0,0 +1,13 @@ +TEMPLATE = lib +CONFIG += plugin +INCLUDEPATH += ../.. +HEADERS = spin_ai.h +SOURCES = spin_ai.cpp +TARGET = $$qtLibraryTarget(spin_ai) +DESTDIR = ../../tankgame/plugins + +#! [0] +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS spin_ai.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/spin_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp new file mode 100644 index 0000000..19137b2 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp @@ -0,0 +1,70 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "spin_ai_with_error.h" + +#include + +QState *SpinAiWithError::create(QState *parentState, QObject *tank) +{ + QState *topLevel = new QState(parentState); + QState *spinState = new SpinState(tank, topLevel); + topLevel->setInitialState(spinState); + + // When tank is spotted, fire two times and go back to spin state + // (no initial state set for fireState will lead to run-time error in machine) + QState *fireState = new QState(topLevel); + + QState *fireOnce = new QState(fireState); + connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); + + QState *fireTwice = new QState(fireState); + connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); + + fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); + fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); + + spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); + + return topLevel; +} + +Q_EXPORT_PLUGIN2(spin_ai_with_error, SpinAiWithError) diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h new file mode 100644 index 0000000..e040bf2 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef SPIN_AI_WITH_ERROR_H +#define SPIN_AI_WITH_ERROR_H + +#include + +#include +#include +#include + +class SpinState: public QState +{ + Q_OBJECT +public: + SpinState(QObject *tank, QState *parent) : QState(parent), m_tank(tank) + { + } + +public slots: + void spin() + { + m_tank->setProperty("direction", m_tank->property("direction").toDouble() + 90.0); + } + +protected: + void onEntry(QEvent *) + { + connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); + spin(); + } + + void onExit(QEvent *) + { + disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); + } + +private: + QObject *m_tank; + +}; + +class SpinAiWithError: public QObject, public Plugin +{ + Q_OBJECT + Q_INTERFACES(Plugin) +public: + SpinAiWithError() { setObjectName("Spin and destroy with runtime error in state machine"); } + + virtual QState *create(QState *parentState, QObject *tank); +}; + +#endif diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro new file mode 100644 index 0000000..124cf98 --- /dev/null +++ b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro @@ -0,0 +1,13 @@ +TEMPLATE = lib +CONFIG += plugin +INCLUDEPATH += ../.. +HEADERS = spin_ai_with_error.h +SOURCES = spin_ai_with_error.cpp +TARGET = $$qtLibraryTarget(spin_ai_with_error) +DESTDIR = ../../tankgame/plugins + +#! [0] +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS spin_ai_with_error.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/spin_ai_with_error \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/tankgameplugins.pro b/examples/statemachine/tankgameplugins/tankgameplugins.pro new file mode 100644 index 0000000..a098e03 --- /dev/null +++ b/examples/statemachine/tankgameplugins/tankgameplugins.pro @@ -0,0 +1,11 @@ +TEMPLATE = subdirs +SUBDIRS = random_ai \ + spin_ai_with_error \ + spin_ai \ + seek_ai + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS tankgameplugins.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins +INSTALLS += target sources diff --git a/examples/statemachine/trafficlight/main.cpp b/examples/statemachine/trafficlight/main.cpp new file mode 100644 index 0000000..8a46fff --- /dev/null +++ b/examples/statemachine/trafficlight/main.cpp @@ -0,0 +1,190 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#ifdef QT_STATEMACHINE_SOLUTION +#include +#include +#include +#endif + +//! [0] +class LightWidget : public QWidget +{ + Q_OBJECT + Q_PROPERTY(bool on READ isOn WRITE setOn) +public: + LightWidget(const QColor &color, QWidget *parent = 0) + : QWidget(parent), m_color(color), m_on(false) {} + + bool isOn() const + { return m_on; } + void setOn(bool on) + { + if (on == m_on) + return; + m_on = on; + update(); + } + +public slots: + void turnOff() { setOn(false); } + void turnOn() { setOn(true); } + +protected: + virtual void paintEvent(QPaintEvent *) + { + if (!m_on) + return; + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.setBrush(m_color); + painter.drawEllipse(0, 0, width(), height()); + } + +private: + QColor m_color; + bool m_on; +}; +//! [0] + +//! [1] +class TrafficLightWidget : public QWidget +{ +public: + TrafficLightWidget(QWidget *parent = 0) + : QWidget(parent) + { + QVBoxLayout *vbox = new QVBoxLayout(this); + m_red = new LightWidget(Qt::red); + vbox->addWidget(m_red); + m_yellow = new LightWidget(Qt::yellow); + vbox->addWidget(m_yellow); + m_green = new LightWidget(Qt::green); + vbox->addWidget(m_green); + QPalette pal = palette(); + pal.setColor(QPalette::Background, Qt::black); + setPalette(pal); + setAutoFillBackground(true); + } + + LightWidget *redLight() const + { return m_red; } + LightWidget *yellowLight() const + { return m_yellow; } + LightWidget *greenLight() const + { return m_green; } + +private: + LightWidget *m_red; + LightWidget *m_yellow; + LightWidget *m_green; +}; +//! [1] + +//! [2] +QState *createLightState(LightWidget *light, int duration, QState *parent = 0) +{ + QState *lightState = new QState(parent); + QTimer *timer = new QTimer(lightState); + timer->setInterval(duration); + timer->setSingleShot(true); + QState *timing = new QState(lightState); + QObject::connect(timing, SIGNAL(entered()), light, SLOT(turnOn())); + QObject::connect(timing, SIGNAL(entered()), timer, SLOT(start())); + QObject::connect(timing, SIGNAL(exited()), light, SLOT(turnOff())); + QFinalState *done = new QFinalState(lightState); + timing->addTransition(timer, SIGNAL(timeout()), done); + lightState->setInitialState(timing); + return lightState; +} +//! [2] + +//! [3] +class TrafficLight : public QWidget +{ +public: + TrafficLight(QWidget *parent = 0) + : QWidget(parent) + { + QVBoxLayout *vbox = new QVBoxLayout(this); + TrafficLightWidget *widget = new TrafficLightWidget(); + vbox->addWidget(widget); + vbox->setMargin(0); + + QStateMachine *machine = new QStateMachine(this); + QState *redGoingYellow = createLightState(widget->redLight(), 3000); + redGoingYellow->setObjectName("redGoingYellow"); + QState *yellowGoingGreen = createLightState(widget->yellowLight(), 1000); + yellowGoingGreen->setObjectName("yellowGoingGreen"); + redGoingYellow->addTransition(redGoingYellow, SIGNAL(finished()), yellowGoingGreen); + QState *greenGoingYellow = createLightState(widget->greenLight(), 3000); + greenGoingYellow->setObjectName("greenGoingYellow"); + yellowGoingGreen->addTransition(yellowGoingGreen, SIGNAL(finished()), greenGoingYellow); + QState *yellowGoingRed = createLightState(widget->yellowLight(), 1000); + yellowGoingRed->setObjectName("yellowGoingRed"); + greenGoingYellow->addTransition(greenGoingYellow, SIGNAL(finished()), yellowGoingRed); + yellowGoingRed->addTransition(yellowGoingRed, SIGNAL(finished()), redGoingYellow); + + machine->addState(redGoingYellow); + machine->addState(yellowGoingGreen); + machine->addState(greenGoingYellow); + machine->addState(yellowGoingRed); + machine->setInitialState(redGoingYellow); + machine->start(); + } +}; +//! [3] + +//! [4] +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + + TrafficLight widget; + widget.resize(110, 300); + widget.show(); + + return app.exec(); +} +//! [4] + +#include "main.moc" diff --git a/examples/statemachine/trafficlight/trafficlight.pro b/examples/statemachine/trafficlight/trafficlight.pro new file mode 100644 index 0000000..684575a --- /dev/null +++ b/examples/statemachine/trafficlight/trafficlight.pro @@ -0,0 +1,7 @@ +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/trafficlight +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS trafficlight.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/trafficlight +INSTALLS += target sources diff --git a/examples/statemachine/twowaybutton/main.cpp b/examples/statemachine/twowaybutton/main.cpp new file mode 100644 index 0000000..a2c6e45 --- /dev/null +++ b/examples/statemachine/twowaybutton/main.cpp @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#ifdef QT_STATEMACHINE_SOLUTION +#include +#include +#endif + +//! [0] +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + QPushButton button; + QStateMachine machine; +//! [0] + +//! [1] + QState *off = new QState(); + off->assignProperty(&button, "text", "Off"); + off->setObjectName("off"); + + QState *on = new QState(); + on->setObjectName("on"); + on->assignProperty(&button, "text", "On"); +//! [1] + +//! [2] + off->addTransition(&button, SIGNAL(clicked()), on); + on->addTransition(&button, SIGNAL(clicked()), off); +//! [2] + +//! [3] + machine.addState(off); + machine.addState(on); +//! [3] + +//! [4] + machine.setInitialState(off); + machine.start(); +//! [4] + +//! [5] + button.resize(100, 50); + button.show(); + return app.exec(); +} +//! [5] diff --git a/examples/statemachine/twowaybutton/twowaybutton.pro b/examples/statemachine/twowaybutton/twowaybutton.pro new file mode 100644 index 0000000..f6cbc57 --- /dev/null +++ b/examples/statemachine/twowaybutton/twowaybutton.pro @@ -0,0 +1,7 @@ +SOURCES = main.cpp + +# install +target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/twowaybutton +sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS twowaybutton.pro +sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/twowaybutton +INSTALLS += target sources diff --git a/mkspecs/win32-icc/qmake.conf b/mkspecs/win32-icc/qmake.conf index 03582fc..78c947d 100644 --- a/mkspecs/win32-icc/qmake.conf +++ b/mkspecs/win32-icc/qmake.conf @@ -16,7 +16,7 @@ QMAKE_LEX = flex QMAKE_LEXFLAGS = QMAKE_YACC = byacc QMAKE_YACCFLAGS = -d -QMAKE_CFLAGS = -nologo -Zm200 /Qprec +QMAKE_CFLAGS = -nologo -Zm200 /Qprec /Qwd1744,1738 QMAKE_CFLAGS_WARN_ON = -W3 /Qwd673 QMAKE_CFLAGS_WARN_OFF = -W0 /Qwd673 QMAKE_CFLAGS_RELEASE = -O2 -MD diff --git a/src/3rdparty/easing/easing.cpp b/src/3rdparty/easing/easing.cpp new file mode 100644 index 0000000..81af40f --- /dev/null +++ b/src/3rdparty/easing/easing.cpp @@ -0,0 +1,670 @@ +/* +Disclaimer for Robert Penner's Easing Equations license: + +TERMS OF USE - EASING EQUATIONS + +Open source under the BSD License. + +Copyright © 2001 Robert Penner +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +#include +#include +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif +#ifndef M_PI_2 +#define M_PI_2 (M_PI / 2) +#endif + +QT_USE_NAMESPACE + +/** + * Easing equation function for a simple linear tweening, with no easing. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeNone(qreal progress) +{ + return progress; +} + +/** + * Easing equation function for a quadratic (t^2) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInQuad(qreal t) +{ + return t*t; +} + +/** +* Easing equation function for a quadratic (t^2) easing out: decelerating to zero velocity. +* +* @param t Current time (in frames or seconds). +* @return The correct value. +*/ +static qreal easeOutQuad(qreal t) +{ + return -t*(t-2); +} + +/** + * Easing equation function for a quadratic (t^2) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInOutQuad(qreal t) +{ + t*=2.0; + if (t < 1) { + return t*t/qreal(2); + } else { + --t; + return -0.5 * (t*(t-2) - 1); + } +} + +/** + * Easing equation function for a quadratic (t^2) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutInQuad(qreal t) +{ + if (t < 0.5) return easeOutQuad (t*2)/2; + return easeInQuad((2*t)-1)/2 + 0.5; +} + +/** + * Easing equation function for a cubic (t^3) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInCubic(qreal t) +{ + return t*t*t; +} + +/** + * Easing equation function for a cubic (t^3) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutCubic(qreal t) +{ + t-=1.0; + return t*t*t + 1; +} + +/** + * Easing equation function for a cubic (t^3) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInOutCubic(qreal t) +{ + t*=2.0; + if(t < 1) { + return 0.5*t*t*t; + } else { + t -= qreal(2.0); + return 0.5*(t*t*t + 2); + } +} + +/** + * Easing equation function for a cubic (t^3) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutInCubic(qreal t) +{ + if (t < 0.5) return easeOutCubic (2*t)/2; + return easeInCubic(2*t - 1)/2 + 0.5; +} + +/** + * Easing equation function for a quartic (t^4) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInQuart(qreal t) +{ + return t*t*t*t; +} + +/** + * Easing equation function for a quartic (t^4) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutQuart(qreal t) +{ + t-= qreal(1.0); + return - (t*t*t*t- 1); +} + +/** + * Easing equation function for a quartic (t^4) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInOutQuart(qreal t) +{ + t*=2; + if (t < 1) return 0.5*t*t*t*t; + else { + t -= 2.0f; + return -0.5 * (t*t*t*t- 2); + } +} + +/** + * Easing equation function for a quartic (t^4) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutInQuart(qreal t) +{ + if (t < 0.5) return easeOutQuart (2*t)/2; + return easeInQuart(2*t-1)/2 + 0.5; +} + +/** + * Easing equation function for a quintic (t^5) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInQuint(qreal t) +{ + return t*t*t*t*t; +} + +/** + * Easing equation function for a quintic (t^5) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutQuint(qreal t) +{ + t-=1.0; + return t*t*t*t*t + 1; +} + +/** + * Easing equation function for a quintic (t^5) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInOutQuint(qreal t) +{ + t*=2.0; + if (t < 1) return 0.5*t*t*t*t*t; + else { + t -= 2.0; + return 0.5*(t*t*t*t*t + 2); + } +} + +/** + * Easing equation function for a quintic (t^5) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutInQuint(qreal t) +{ + if (t < 0.5) return easeOutQuint (2*t)/2; + return easeInQuint(2*t - 1)/2 + 0.5; +} + +/** + * Easing equation function for a sinusoidal (sin(t)) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInSine(qreal t) +{ + return (t == 1.0) ? 1.0 : -::cos(t * M_PI_2) + 1.0; +} + +/** + * Easing equation function for a sinusoidal (sin(t)) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutSine(qreal t) +{ + return ::sin(t* M_PI_2); +} + +/** + * Easing equation function for a sinusoidal (sin(t)) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInOutSine(qreal t) +{ + return -0.5 * (::cos(M_PI*t) - 1); +} + +/** + * Easing equation function for a sinusoidal (sin(t)) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutInSine(qreal t) +{ + if (t < 0.5) return easeOutSine (2*t)/2; + return easeInSine(2*t - 1)/2 + 0.5; +} + +/** + * Easing equation function for an exponential (2^t) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInExpo(qreal t) +{ + return (t==0 || t == 1.0) ? t : ::qPow(2.0, 10 * (t - 1)) - qreal(0.001); +} + +/** + * Easing equation function for an exponential (2^t) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutExpo(qreal t) +{ + return (t==1.0) ? 1.0 : 1.001 * (-::qPow(2.0f, -10 * t) + 1); +} + +/** + * Easing equation function for an exponential (2^t) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInOutExpo(qreal t) +{ + if (t==0.0) return qreal(0.0); + if (t==1.0) return qreal(1.0); + t*=2.0; + if (t < 1) return 0.5 * ::qPow(qreal(2.0), 10 * (t - 1)) - 0.0005; + return 0.5 * 1.0005 * (-::qPow(qreal(2.0), -10 * (t - 1)) + 2); +} + +/** + * Easing equation function for an exponential (2^t) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutInExpo(qreal t) +{ + if (t < 0.5) return easeOutExpo (2*t)/2; + return easeInExpo(2*t - 1)/2 + 0.5; +} + +/** + * Easing equation function for a circular (sqrt(1-t^2)) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInCirc(qreal t) +{ + return -(::sqrt(1 - t*t) - 1); +} + +/** + * Easing equation function for a circular (sqrt(1-t^2)) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutCirc(qreal t) +{ + t-= qreal(1.0); + return ::sqrt(1 - t* t); +} + +/** + * Easing equation function for a circular (sqrt(1-t^2)) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeInOutCirc(qreal t) +{ + t*=qreal(2.0); + if (t < 1) { + return -0.5 * (::sqrt(1 - t*t) - 1); + } else { + t -= qreal(2.0); + return 0.5 * (::sqrt(1 - t*t) + 1); + } +} + +/** + * Easing equation function for a circular (sqrt(1-t^2)) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @return The correct value. + */ +static qreal easeOutInCirc(qreal t) +{ + if (t < 0.5) return easeOutCirc (2*t)/2; + return easeInCirc(2*t - 1)/2 + 0.5; +} + +static qreal easeInElastic_helper(qreal t, qreal b, qreal c, qreal d, qreal a, qreal p) +{ + if (t==0) return b; + qreal t_adj = (qreal)t / (qreal)d; + if (t_adj==1) return b+c; + + qreal s; + if(a < ::fabs(c)) { + a = c; + s = p / 4.0f; + } else { + s = p / (2 * M_PI) * ::asin(c / a); + } + + t_adj -= 1.0f; + return -(a*::qPow(2.0f,10*t_adj) * ::sin( (t_adj*d-s)*(2*M_PI)/p )) + b; +} + +/** + * Easing equation function for an elastic (exponentially decaying sine wave) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ +static qreal easeInElastic(qreal t, qreal a, qreal p) +{ + return easeInElastic_helper(t, 0, 1, 1, a, p); +} + +static qreal easeOutElastic_helper(qreal t, qreal /*b*/, qreal c, qreal /*d*/, qreal a, qreal p) +{ + if (t==0) return 0; + if (t==1) return c; + + qreal s; + if(a < c) { + a = c; + s = p / 4.0f; + } else { + s = p / (2 * M_PI) * ::asin(c / a); + } + + return (a*::qPow(2.0f,-10*t) * ::sin( (t-s)*(2*M_PI)/p ) + c); +} + +/** + * Easing equation function for an elastic (exponentially decaying sine wave) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ +static qreal easeOutElastic(qreal t, qreal a, qreal p) +{ + return easeOutElastic_helper(t, 0, 1, 1, a, p); +} + +/** + * Easing equation function for an elastic (exponentially decaying sine wave) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ +static qreal easeInOutElastic(qreal t, qreal a, qreal p) +{ + if (t==0) return 0.0; + t*=2.0; + if (t==2) return 1.0; + + qreal s; + if(a < 1.0) { + a = 1.0; + s = p / 4.0f; + } else { + s = p / (2 * M_PI) * ::asin(1.0 / a); + } + + if (t < 1) return -.5*(a*::qPow(2.0f,10*(t-1)) * ::sin( (t-1-s)*(2*M_PI)/p )); + return a*::qPow(2.0f,-10*(t-1)) * ::sin( (t-1-s)*(2*M_PI)/p )*.5 + 1.0; +} + +/** + * Easing equation function for an elastic (exponentially decaying sine wave) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param a Amplitude. + * @param p Period. + * @return The correct value. + */ +static qreal easeOutInElastic(qreal t, qreal a, qreal p) +{ + if (t < 0.5) return easeOutElastic_helper(t*2, 0, 0.5, 1.0, a, p); + return easeInElastic_helper(2*t - 1.0, 0.5, 0.5, 1.0, a, p); +} + +/** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ +static qreal easeInBack(qreal t, qreal s) +{ + return t*t*((s+1)*t - s); +} + +/** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ +static qreal easeOutBack(qreal t, qreal s) +{ + t-= qreal(1.0); + return t*t*((s+1)*t+ s) + 1; +} + +/** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ +static qreal easeInOutBack(qreal t, qreal s) +{ + t *= 2.0; + if (t < 1) { + s *= 1.525f; + return 0.5*(t*t*((s+1)*t - s)); + } else { + t -= 2; + s *= 1.525f; + return 0.5*(t*t*((s+1)*t+ s) + 2); + } +} + +/** + * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). + * @return The correct value. + */ +static qreal easeOutInBack(qreal t, qreal s) +{ + if (t < 0.5) return easeOutBack (2*t, s)/2; + return easeInBack(2*t - 1, s)/2 + 0.5; +} + +static qreal easeOutBounce_helper(qreal t, qreal c, qreal a) +{ + if (t == 1.0) return c; + if (t < (4/11.0)) { + return c*(7.5625*t*t); + } else if (t < (8/11.0)) { + t -= (6/11.0); + return -a * (1. - (7.5625*t*t + .75)) + c; + } else if (t < (10/11.0)) { + t -= (9/11.0); + return -a * (1. - (7.5625*t*t + .9375)) + c; + } else { + t -= (21/22.0); + return -a * (1. - (7.5625*t*t + .984375)) + c; + } +} + +/** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param a Amplitude. + * @return The correct value. + */ +static qreal easeOutBounce(qreal t, qreal a) +{ + return easeOutBounce_helper(t, 1, a); +} + +/** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. + * + * @param t Current time (in frames or seconds). + * @param a Amplitude. + * @return The correct value. + */ +static qreal easeInBounce(qreal t, qreal a) +{ + return 1.0 - easeOutBounce_helper(1.0-t, 1.0, a); +} + + +/** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. + * + * @param t Current time (in frames or seconds). + * @param a Amplitude. + * @return The correct value. + */ +static qreal easeInOutBounce(qreal t, qreal a) +{ + if (t < 0.5) return easeInBounce (2*t, a)/2; + else return (t == 1.0) ? 1.0 : easeOutBounce (2*t - 1, a)/2 + 0.5; +} + +/** + * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out/in: deceleration until halfway, then acceleration. + * + * @param t Current time (in frames or seconds). + * @param a Amplitude. + * @return The correct value. + */ +static qreal easeOutInBounce(qreal t, qreal a) +{ + if (t < 0.5) return easeOutBounce_helper(t*2, 0.5, a); + return 1.0 - easeOutBounce_helper (2.0-2*t, 0.5, a); +} + +static inline qreal qt_sinProgress(qreal value) +{ + return qSin((value * M_PI) - M_PI_2) / 2 + qreal(0.5); +} + +static inline qreal qt_smoothBeginEndMixFactor(qreal value) +{ + return qMin(qMax(1 - value * 2 + qreal(0.3), qreal(0.0)), qreal(1.0)); +} + +// SmoothBegin blends Smooth and Linear Interpolation. +// Progress 0 - 0.3 : Smooth only +// Progress 0.3 - ~ 0.5 : Mix of Smooth and Linear +// Progress ~ 0.5 - 1 : Linear only + +/** + * Easing function that starts growing slowly, then increases in speed. At the end of the curve the speed will be constant. + */ +static qreal easeInCurve(qreal t) +{ + const qreal sinProgress = qt_sinProgress(t); + const qreal mix = qt_smoothBeginEndMixFactor(t); + return sinProgress * mix + t * (1 - mix); +} + +/** + * Easing function that starts growing steadily, then ends slowly. The speed will be constant at the beginning of the curve. + */ +static qreal easeOutCurve(qreal t) +{ + const qreal sinProgress = qt_sinProgress(t); + const qreal mix = qt_smoothBeginEndMixFactor(1 - t); + return sinProgress * mix + t * (1 - mix); +} + +/** + * Easing function where the value grows sinusoidally. Note that the calculated end value will be 0 rather than 1. + */ +static qreal easeSineCurve(qreal t) +{ + return (qSin(((t * M_PI * 2)) - M_PI_2) + 1) / 2; +} + +/** + * Easing function where the value grows cosinusoidally. Note that the calculated start value will be 0.5 and the end value will be 0.5 + * contrary to the usual 0 to 1 easing curve. + */ +static qreal easeCosineCurve(qreal t) +{ + return (qCos(((t * M_PI * 2)) - M_PI_2) + 1) / 2; +} + diff --git a/src/3rdparty/easing/legal.qdoc b/src/3rdparty/easing/legal.qdoc new file mode 100644 index 0000000..25f67e1 --- /dev/null +++ b/src/3rdparty/easing/legal.qdoc @@ -0,0 +1,35 @@ +/*! +\page legal-easing.html +\title Easing Equations by Robert Penner +\ingroup animation + +\legalese +\code +Copyright (c) 2001 Robert Penner +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + + * Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + * Neither the name of the author nor the names of contributors may be used + to endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +\endcode +\endlegalese +*/ diff --git a/src/corelib/animation/animation.pri b/src/corelib/animation/animation.pri new file mode 100644 index 0000000..cb7850c --- /dev/null +++ b/src/corelib/animation/animation.pri @@ -0,0 +1,25 @@ +# Qt core animation module + +HEADERS += \ + animation/qabstractanimation.h \ + animation/qabstractanimation_p.h \ + animation/qvariantanimation.h \ + animation/qvariantanimation_p.h \ + animation/qpropertyanimation.h \ + animation/qpropertyanimation_p.h \ + animation/qanimationgroup.h \ + animation/qanimationgroup_p.h \ + animation/qsequentialanimationgroup.h \ + animation/qsequentialanimationgroup_p.h \ + animation/qparallelanimationgroup.h \ + animation/qparallelanimationgroup_p.h \ + animation/qpauseanimation.h + +SOURCES += \ + animation/qabstractanimation.cpp \ + animation/qvariantanimation.cpp \ + animation/qpropertyanimation.cpp \ + animation/qanimationgroup.cpp \ + animation/qsequentialanimationgroup.cpp \ + animation/qparallelanimationgroup.cpp \ + animation/qpauseanimation.cpp diff --git a/src/corelib/animation/qabstractanimation.cpp b/src/corelib/animation/qabstractanimation.cpp new file mode 100644 index 0000000..94a94d1 --- /dev/null +++ b/src/corelib/animation/qabstractanimation.cpp @@ -0,0 +1,759 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \class QAbstractAnimation + \ingroup animation + \brief The QAbstractAnimation class is the base of all animations. + \since 4.6 + + The class defines the functions for the functionality shared by + all animations. By inheriting this class, you can create custom + animations that plug into the rest of the animation framework. + + The progress of an animation is given by its current time + (currentTime()), which is measured in milliseconds from the start + of the animation (0) to its end (duration()). The value is updated + automatically while the animation is running. It can also be set + directly with setCurrentTime(). + + At any point an animation is in one of three states: + \l{QAbstractAnimation::}{Running}, + \l{QAbstractAnimation::}{Stopped}, or + \l{QAbstractAnimation::}{Paused}--as defined by the + \l{QAbstractAnimation::}{State} enum. The current state can be + changed by calling start(), stop(), pause(), or resume(). An + animation will always reset its \l{currentTime()}{current time} + when it is started. If paused, it will continue with the same + current time when resumed. When an animation is stopped, it cannot + be resumed, but will keep its current time (until started again). + QAbstractAnimation will emit stateChanged() whenever its state + changes. + + An animation can loop any number of times by setting the loopCount + property. When an animation's current time reaches its duration(), + it will reset the current time and keep running. A loop count of 1 + (the default value) means that the animation will run one time. + Note that a duration of -1 means that the animation will run until + stopped; the current time will increase indefinitely. When the + current time equals duration() and the animation is in its + final loop, the \l{QAbstractAnimation::}{Stopped} state is + entered, and the finished() signal is emitted. + + QAbstractAnimation provides pure virtual functions used by + subclasses to track the progress of the animation: duration() and + updateCurrentTime(). The duration() function lets you report a + duration for the animation (as discussed above). The current time + is delivered by the animation framework through calls to + updateCurrentTime(). By reimplementing this function, you can + track the animation progress. Note that neither the interval + between calls nor the number of calls to this function are + defined; though, it will normally be 60 updates per second. + + By reimplementing updateState(), you can track the animation's + state changes, which is particularly useful for animations that + are not driven by time. + + \sa QVariantAnimation, QPropertyAnimation, QAnimationGroup, {The Animation Framework} +*/ + +/*! + \enum QAbstractAnimation::DeletionPolicy + + \value KeepWhenStopped The animation will not be deleted when stopped. + \value DeleteWhenStopped The animation will be automatically deleted when + stopped. +*/ + +/*! + \fn QAbstractAnimation::finished() + + QAbstractAnimation emits this signal after the animation has stopped and + has reached the end. + + This signal is emitted after stateChanged(). + + \sa stateChanged() +*/ + +/*! + \fn QAbstractAnimation::stateChanged(QAbstractAnimation::State oldState, QAbstractAnimation::State newState) + + QAbstractAnimation emits this signal whenever the state of the animation has + changed from \a oldState to \a newState. This signal is emitted after the virtual + updateState() function is called. + + \sa updateState() +*/ + +/*! + \fn QAbstractAnimation::currentLoopChanged(int currentLoop) + + QAbstractAnimation emits this signal whenever the current loop + changes. \a currentLoop is the current loop. + + \sa currentLoop(), loopCount() +*/ + +/*! + \fn QAbstractAnimation::directionChanged(QAbstractAnimation::Direction newDirection); + + QAbstractAnimation emits this signal whenever the direction has been + changed. \a newDirection is the new direction. + + \sa direction +*/ + +#ifndef QT_NO_ANIMATION + +#include "qabstractanimation.h" +#include "qanimationgroup.h" +#include + +#include "qabstractanimation_p.h" + +#include +#include +#include +#include + +#define DEFAULT_TIMER_INTERVAL 16 + +QT_BEGIN_NAMESPACE + +Q_GLOBAL_STATIC(QThreadStorage, unifiedTimer); + +QUnifiedTimer::QUnifiedTimer() : QObject(), lastTick(0), timingInterval(DEFAULT_TIMER_INTERVAL), consistentTiming(false) +{ +} + +QUnifiedTimer *QUnifiedTimer::instance() +{ + QUnifiedTimer *inst; + if (!unifiedTimer()->hasLocalData()) { + inst = new QUnifiedTimer; + unifiedTimer()->setLocalData(inst); + } else { + inst = unifiedTimer()->localData(); + } + return inst; +} + +void QUnifiedTimer::updateRecentlyStartedAnimations() +{ + if (animationsToStart.isEmpty()) + return; + + animations += animationsToStart; + updateTimer(); //we make sure we start the timer there + + animationsToStart.clear(); +} + +/* + defines the timing interval. Default is DEFAULT_TIMER_INTERVAL +*/ +void QUnifiedTimer::setTimingInterval(int interval) +{ + timingInterval = interval; + if (animationTimer.isActive()) { + //we changed the timing interval + animationTimer.start(timingInterval, this); + } +} + +/* + this allows to have a consistent timer interval at each tick from the timer + not taking the real time that passed into account. +*/ +void QUnifiedTimer::setConsistentTiming(bool b) +{ + consistentTiming = b; +} + +int QUnifiedTimer::elapsedTime() const +{ + return lastTick; +} + +void QUnifiedTimer::timerEvent(QTimerEvent *event) +{ + //this is simply the time we last received a tick + const int oldLastTick = lastTick; + if (time.isValid()) + lastTick = consistentTiming ? oldLastTick + timingInterval : time.elapsed(); + + //we transfer the waiting animations into the "really running" state + updateRecentlyStartedAnimations(); + + if (event->timerId() == startStopAnimationTimer.timerId()) { + startStopAnimationTimer.stop(); + if (animations.isEmpty()) { + animationTimer.stop(); + time = QTime(); + } else { + animationTimer.start(timingInterval, this); + lastTick = 0; + time.start(); + } + } else if (event->timerId() == animationTimer.timerId()) { + const int delta = lastTick - oldLastTick; + for (int i = 0; i < animations.count(); ++i) { + QAbstractAnimation *animation = animations.at(i); + int elapsed = QAbstractAnimationPrivate::get(animation)->totalCurrentTime + + (animation->direction() == QAbstractAnimation::Forward ? delta : -delta); + animation->setCurrentTime(elapsed); + } + } +} + +void QUnifiedTimer::updateTimer() +{ + //we delay the call to start and stop for the animation timer so that if you + //stop and start animations in batch you don't stop/start the timer too often. + if (!startStopAnimationTimer.isActive()) + startStopAnimationTimer.start(0, this); // we delay the actual start of the animation +} + +void QUnifiedTimer::registerAnimation(QAbstractAnimation *animation) +{ + if (animations.contains(animation) ||animationsToStart.contains(animation)) + return; + animationsToStart << animation; + updateTimer(); +} + +void QUnifiedTimer::unregisterAnimation(QAbstractAnimation *animation) +{ + animations.removeAll(animation); + animationsToStart.removeAll(animation); + updateTimer(); +} + + +void QAbstractAnimationPrivate::setState(QAbstractAnimation::State newState) +{ + Q_Q(QAbstractAnimation); + if (state == newState) + return; + + QAbstractAnimation::State oldState = state; + int oldCurrentTime = currentTime; + int oldCurrentLoop = currentLoop; + QAbstractAnimation::Direction oldDirection = direction; + + state = newState; + + QPointer guard(q); + + guard->updateState(oldState, newState); + + //this is to be safe if updateState changes the state + if (state == oldState) + return; + + // Notify state change + if (guard) + emit guard->stateChanged(oldState, newState); + + // Enter running state. + switch (state) + { + case QAbstractAnimation::Paused: + case QAbstractAnimation::Running: + { + // Rewind + if (oldState == QAbstractAnimation::Stopped) { + if (guard) { + if (direction == QAbstractAnimation::Forward) + q->setCurrentTime(0); + else + q->setCurrentTime(loopCount == -1 ? q->duration() : q->totalDuration()); + } + + // Check if the setCurrentTime() function called stop(). + // This can happen for a 0-duration animation + if (state == QAbstractAnimation::Stopped) + return; + } + + // Register timer if our parent is not running. + if (state == QAbstractAnimation::Running && guard) { + if (!group || group->state() == QAbstractAnimation::Stopped) { + QUnifiedTimer::instance()->registerAnimation(q); + } + } else { + //new state is paused + QUnifiedTimer::instance()->unregisterAnimation(q); + } + } + break; + case QAbstractAnimation::Stopped: + // Leave running state. + int dura = q->duration(); + if (deleteWhenStopped && guard) + q->deleteLater(); + + QUnifiedTimer::instance()->unregisterAnimation(q); + + if (dura == -1 || loopCount < 0 + || (oldDirection == QAbstractAnimation::Forward && (oldCurrentTime * (oldCurrentLoop + 1)) == (dura * loopCount)) + || (oldDirection == QAbstractAnimation::Backward && oldCurrentTime == 0)) { + if (guard) + emit q->finished(); + } + break; + } + +} + +/*! + Constructs the QAbstractAnimation base class, and passes \a parent to + QObject's constructor. + + \sa QVariantAnimation, QAnimationGroup +*/ +QAbstractAnimation::QAbstractAnimation(QObject *parent) + : QObject(*new QAbstractAnimationPrivate, 0) +{ + // Allow auto-add on reparent + setParent(parent); +} + +/*! + \internal +*/ +QAbstractAnimation::QAbstractAnimation(QAbstractAnimationPrivate &dd, QObject *parent) + : QObject(dd, 0) +{ + // Allow auto-add on reparent + setParent(parent); +} + +/*! + Stops the animation if it's running, then destroys the + QAbstractAnimation. If the animation is part of a QAnimationGroup, it is + automatically removed before it's destroyed. +*/ +QAbstractAnimation::~QAbstractAnimation() +{ + Q_D(QAbstractAnimation); + //we can't call stop here. Otherwise we get pure virtual calls + if (d->state != Stopped) { + QAbstractAnimation::State oldState = d->state; + d->state = Stopped; + emit stateChanged(oldState, d->state); + QUnifiedTimer::instance()->unregisterAnimation(this); + } +} + +/*! + \property QAbstractAnimation::state + \brief state of the animation. + + This property describes the current state of the animation. When the + animation state changes, QAbstractAnimation emits the stateChanged() + signal. +*/ +QAbstractAnimation::State QAbstractAnimation::state() const +{ + Q_D(const QAbstractAnimation); + return d->state; +} + +/*! + If this animation is part of a QAnimationGroup, this function returns a + pointer to the group; otherwise, it returns 0. + + \sa QAnimationGroup::addAnimation() +*/ +QAnimationGroup *QAbstractAnimation::group() const +{ + Q_D(const QAbstractAnimation); + return d->group; +} + +/*! + \enum QAbstractAnimation::State + + This enum describes the state of the animation. + + \value Stopped The animation is not running. This is the initial state + of QAbstractAnimation, and the state QAbstractAnimation reenters when finished. The current + time remain unchanged until either setCurrentTime() is + called, or the animation is started by calling start(). + + \value Paused The animation is paused (i.e., temporarily + suspended). Calling resume() will resume animation activity. + + \value Running The animation is running. While control is in the event + loop, QAbstractAnimation will update its current time at regular intervals, + calling updateCurrentTime() when appropriate. + + \sa state(), stateChanged() +*/ + +/*! + \enum QAbstractAnimation::Direction + + This enum describes the direction of the animation when in \l Running state. + + \value Forward The current time of the animation increases with time (i.e., + moves from 0 and towards the end / duration). + + \value Backward The current time of the animation decreases with time (i.e., + moves from the end / duration and towards 0). + + \sa direction +*/ + +/*! + \property QAbstractAnimation::direction + \brief the direction of the animation when it is in \l Running + state. + + This direction indicates whether the time moves from 0 towards the + animation duration, or from the value of the duration and towards 0 after + start() has been called. + + By default, this property is set to \l Forward. +*/ +QAbstractAnimation::Direction QAbstractAnimation::direction() const +{ + Q_D(const QAbstractAnimation); + return d->direction; +} +void QAbstractAnimation::setDirection(Direction direction) +{ + Q_D(QAbstractAnimation); + if (d->direction == direction) + return; + + d->direction = direction; + if (state() == Stopped) { + if (direction == Backward) { + d->currentTime = duration(); + d->currentLoop = d->loopCount - 1; + } else { + d->currentTime = 0; + d->currentLoop = 0; + } + } + updateDirection(direction); + emit directionChanged(direction); +} + +/*! + \property QAbstractAnimation::duration + \brief the duration of the animation. + + If the duration is -1, it means that the duration is undefined. + In this case, loopCount is ignored. +*/ + +/*! + \property QAbstractAnimation::loopCount + \brief the loop count of the animation + + This property describes the loop count of the animation as an integer. + By default this value is 1, indicating that the animation + should run once only, and then stop. By changing it you can let the + animation loop several times. With a value of 0, the animation will not + run at all, and with a value of -1, the animation will loop forever + until stopped. + It is not supported to have loop on an animation that has an undefined + duration. It will only run once. +*/ +int QAbstractAnimation::loopCount() const +{ + Q_D(const QAbstractAnimation); + return d->loopCount; +} +void QAbstractAnimation::setLoopCount(int loopCount) +{ + Q_D(QAbstractAnimation); + d->loopCount = loopCount; +} + +/*! + \property QAbstractAnimation::currentLoop + \brief the current loop of the animation + + This property describes the current loop of the animation. By default, + the animation's loop count is 1, and so the current loop will + always be 0. If the loop count is 2 and the animation runs past its + duration, it will automatically rewind and restart at current time 0, and + current loop 1, and so on. + + When the current loop changes, QAbstractAnimation emits the + currentLoopChanged() signal. +*/ +int QAbstractAnimation::currentLoop() const +{ + Q_D(const QAbstractAnimation); + return d->currentLoop; +} + +/*! + \fn virtual int QAbstractAnimation::duration() const = 0 + + This pure virtual function returns the duration of the animation, and + defines for how long QAbstractAnimation should update the current + time. This duration is local, and does not include the loop count. + + A return value of -1 indicates that the animation has no defined duration; + the animation should run forever until stopped. This is useful for + animations that are not time driven, or where you cannot easily predict + its duration (e.g., event driven audio playback in a game). + + If the animation is a parallel QAnimationGroup, the duration will be the longest + duration of all its animations. If the animation is a sequential QAnimationGroup, + the duration will be the sum of the duration of all its animations. + \sa loopCount +*/ + +/*! + Returns the total and effective duration of the animation, including the + loop count. + + \sa duration(), currentTime +*/ +int QAbstractAnimation::totalDuration() const +{ + Q_D(const QAbstractAnimation); + if (d->loopCount < 0) + return -1; + int dura = duration(); + if (dura == -1) + return -1; + return dura * d->loopCount; +} + +/*! + \property QAbstractAnimation::currentTime + \brief the current time and progress of the animation + + This property describes the animation's current time. You can change the + current time by calling setCurrentTime, or you can call start() and let + the animation run, setting the current time automatically as the animation + progresses. + + The animation's current time starts at 0, and ends at duration(). If the + animation's loopCount is larger than 1, the current time will rewind and + start at 0 again for the consecutive loops. If the animation has a pause. + currentTime will also include the duration of the pause. + + \sa loopCount + */ +int QAbstractAnimation::currentTime() const +{ + Q_D(const QAbstractAnimation); + return d->currentTime; +} +void QAbstractAnimation::setCurrentTime(int msecs) +{ + Q_D(QAbstractAnimation); + msecs = qMax(msecs, 0); + + // Calculate new time and loop. + int dura = duration(); + int totalDura = (d->loopCount < 0 || dura == -1) ? -1 : dura * d->loopCount; + if (totalDura != -1) + msecs = qMin(totalDura, msecs); + d->totalCurrentTime = msecs; + + // Update new values. + int oldLoop = d->currentLoop; + d->currentLoop = ((dura <= 0) ? 0 : (msecs / dura)); + if (d->currentLoop == d->loopCount) { + //we're at the end + d->currentTime = qMax(0, dura); + d->currentLoop = qMax(0, d->loopCount - 1); + } else { + if (d->direction == Forward) { + d->currentTime = (dura <= 0) ? msecs : (msecs % dura); + } else { + d->currentTime = (dura <= 0) ? msecs : ((msecs - 1) % dura) + 1; + if (d->currentTime == dura) + --d->currentLoop; + } + } + + updateCurrentTime(msecs); + if (d->currentLoop != oldLoop) + emit currentLoopChanged(d->currentLoop); + + // All animations are responsible for stopping the animation when their + // own end state is reached; in this case the animation is time driven, + // and has reached the end. + if ((d->direction == Forward && d->totalCurrentTime == totalDura) + || (d->direction == Backward && d->totalCurrentTime == 0)) { + stop(); + } +} + +/*! + Starts the animation. The \a policy argument says whether or not the + animation should be deleted when it's done. When the animation starts, the + stateChanged() signal is emitted, and state() returns Running. When control + reaches the event loop, the animation will run by itself, periodically + calling updateCurrentTime() as the animation progresses. + + If the animation is currently stopped or has already reached the end, + calling start() will rewind the animation and start again from the beginning. + When the animation reaches the end, the animation will either stop, or + if the loop level is more than 1, it will rewind and continue from the beginning. + + If the animation is already running, this function does nothing. + + \sa stop(), state() +*/ +void QAbstractAnimation::start(DeletionPolicy policy) +{ + Q_D(QAbstractAnimation); + if (d->state == Running) + return; + d->setState(Running); + d->deleteWhenStopped = policy; +} + +/*! + Stops the animation. When the animation is stopped, it emits the stateChanged() + signal, and state() returns Stopped. The current time is not changed. + + If the animation stops by itself after reaching the end (i.e., + currentTime() == duration() and currentLoop() > loopCount() - 1), the + finished() signal is emitted. + + \sa start(), state() + */ +void QAbstractAnimation::stop() +{ + Q_D(QAbstractAnimation); + + d->setState(Stopped); +} + +/*! + Pauses the animation. When the animation is paused, state() returns Paused. + The currenttime will remain unchanged until resume() or start() is called. + If you want to continue from the current time, call resume(). + + + \sa start(), state(), resume() + */ +void QAbstractAnimation::pause() +{ + Q_D(QAbstractAnimation); + if (d->state == Stopped) { + qWarning("QAbstractAnimation::pause: Cannot pause a stopped animation"); + return; + } + + d->setState(Paused); +} + +/*! + Resumes the animation after it was paused. When the animation is resumed, + it emits the resumed() and stateChanged() signals. The currenttime is not + changed. + + \sa start(), pause(), state() + */ +void QAbstractAnimation::resume() +{ + Q_D(QAbstractAnimation); + if (d->state != Paused) { + qWarning("QAbstractAnimation::resume: " + "Cannot resume an animation that is not paused"); + return; + } + + d->setState(Running); +} + +/*! + \reimp +*/ +bool QAbstractAnimation::event(QEvent *event) +{ + return QObject::event(event); +} + +/*! + \fn virtual void QAbstractAnimation::updateCurrentTime(int msecs) = 0; + + This pure virtual function is called every time the animation's current + time changes. The \a msecs argument is the current time. + + \sa updateState() +*/ + +/*! + This virtual function is called by QAbstractAnimation when the state + of the animation is changed from \a oldState to \a newState. + + \sa start(), stop(), pause(), resume() +*/ +void QAbstractAnimation::updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) +{ + Q_UNUSED(oldState); + Q_UNUSED(newState); +} + +/*! + This virtual function is called by QAbstractAnimation when the direction + of the animation is changed. The \a direction argument is the new direction. + + \sa setDirection(), direction() +*/ +void QAbstractAnimation::updateDirection(QAbstractAnimation::Direction direction) +{ + Q_UNUSED(direction); +} + + +QT_END_NAMESPACE + +#include "moc_qabstractanimation.cpp" + +#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qabstractanimation.h b/src/corelib/animation/qabstractanimation.h new file mode 100644 index 0000000..d6d50dc --- /dev/null +++ b/src/corelib/animation/qabstractanimation.h @@ -0,0 +1,137 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QABSTRACTANIMATION_H +#define QABSTRACTANIMATION_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +#ifndef QT_NO_ANIMATION + +class QAnimationGroup; +class QSequentialAnimationGroup; + +class QAbstractAnimationPrivate; +class Q_CORE_EXPORT QAbstractAnimation : public QObject +{ + Q_OBJECT + Q_PROPERTY(State state READ state NOTIFY stateChanged) + Q_PROPERTY(int loopCount READ loopCount WRITE setLoopCount) + Q_PROPERTY(int currentTime READ currentTime WRITE setCurrentTime) + Q_PROPERTY(int currentLoop READ currentLoop NOTIFY currentLoopChanged) + Q_PROPERTY(Direction direction READ direction WRITE setDirection NOTIFY directionChanged) + Q_PROPERTY(int duration READ duration) + +public: + enum Direction { + Forward, + Backward + }; + + enum State { + Stopped, + Paused, + Running + }; + + enum DeletionPolicy { + KeepWhenStopped = 0, + DeleteWhenStopped + }; + + QAbstractAnimation(QObject *parent = 0); + virtual ~QAbstractAnimation(); + + State state() const; + + QAnimationGroup *group() const; + + Direction direction() const; + void setDirection(Direction direction); + + int loopCount() const; + void setLoopCount(int loopCount); + int currentLoop() const; + + virtual int duration() const = 0; + int totalDuration() const; + + int currentTime() const; + +Q_SIGNALS: + void finished(); + void stateChanged(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); + void currentLoopChanged(int currentLoop); + void directionChanged(QAbstractAnimation::Direction); + +public Q_SLOTS: + void start(QAbstractAnimation::DeletionPolicy policy = KeepWhenStopped); + void pause(); + void resume(); + void stop(); + void setCurrentTime(int msecs); + +protected: + QAbstractAnimation(QAbstractAnimationPrivate &dd, QObject *parent = 0); + bool event(QEvent *event); + + virtual void updateCurrentTime(int msecs) = 0; + virtual void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); + virtual void updateDirection(QAbstractAnimation::Direction direction); + +private: + Q_DISABLE_COPY(QAbstractAnimation) + Q_DECLARE_PRIVATE(QAbstractAnimation) +}; + +#endif //QT_NO_ANIMATION + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QABSTRACTANIMATION_H diff --git a/src/corelib/animation/qabstractanimation_p.h b/src/corelib/animation/qabstractanimation_p.h new file mode 100644 index 0000000..e64554c --- /dev/null +++ b/src/corelib/animation/qabstractanimation_p.h @@ -0,0 +1,136 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QABSTRACTANIMATION_P_H +#define QABSTRACTANIMATION_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of QIODevice. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QAnimationGroup; +class QAbstractAnimation; +class QAbstractAnimationPrivate : public QObjectPrivate +{ +public: + QAbstractAnimationPrivate() + : state(QAbstractAnimation::Stopped), + direction(QAbstractAnimation::Forward), + deleteWhenStopped(false), + totalCurrentTime(0), + currentTime(0), + loopCount(1), + currentLoop(0), + group(0) + { + } + + virtual ~QAbstractAnimationPrivate() {} + + static QAbstractAnimationPrivate *get(QAbstractAnimation *q) + { + return q->d_func(); + } + + QAbstractAnimation::State state; + QAbstractAnimation::Direction direction; + bool deleteWhenStopped; + void setState(QAbstractAnimation::State state); + + int totalCurrentTime; + int currentTime; + int loopCount; + int currentLoop; + + QAnimationGroup *group; + +private: + Q_DECLARE_PUBLIC(QAbstractAnimation) +}; + + +class Q_CORE_EXPORT QUnifiedTimer : public QObject +{ +private: + QUnifiedTimer(); + +public: + static QUnifiedTimer *instance(); + + void registerAnimation(QAbstractAnimation *animation); + void unregisterAnimation(QAbstractAnimation *animation); + + void setTimingInterval(int interval); + void setConsistentTiming(bool consistent); + + int elapsedTime() const; + +protected: + void timerEvent(QTimerEvent *); + void updateTimer(); + +private: + void updateRecentlyStartedAnimations(); + + QBasicTimer animationTimer, startStopAnimationTimer; + QTime time; + int lastTick; + int timingInterval; + bool consistentTiming; + QList animations, animationsToStart; +}; + +QT_END_NAMESPACE +#endif diff --git a/src/corelib/animation/qanimationgroup.cpp b/src/corelib/animation/qanimationgroup.cpp new file mode 100644 index 0000000..ed06eff --- /dev/null +++ b/src/corelib/animation/qanimationgroup.cpp @@ -0,0 +1,309 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \class QAnimationGroup + \brief The QAnimationGroup class is an abstract base class for groups of animations. + \since 4.6 + \ingroup animation + + An animation group is a container for animations (subclasses of + QAbstractAnimation). A group is usually responsible for managing + the \l{QAbstractAnimation::State}{state} of its animations, i.e., + it decides when to start, stop, resume, and pause them. Currently, + Qt provides two such groups: QParallelAnimationGroup and + QSequentialAnimationGroup. Look up their class descriptions for + details. + + Since QAnimationGroup inherits from QAbstractAnimation, you can + combine groups, and easily construct complex animation graphs. + You can query QAbstractAnimation for the group it belongs to + (using the \l{QAbstractAnimation::}{group()} function). + + To start a top-level animation group, you simply use the + \l{QAbstractAnimation::}{start()} function from + QAbstractAnimation. By a top-level animation group, we think of a + group that itself is not contained within another group. Starting + sub groups directly is not supported, and may lead to unexpected + behavior. + + \omit OK, we'll put in a snippet on this here \endomit + + QAnimationGroup provides methods for adding and retrieving + animations. Besides that, you can remove animations by calling + remove(), and clear the animation group by calling + clearAnimations(). You may keep track of changes in the group's + animations by listening to QEvent::ChildAdded and + QEvent::ChildRemoved events. + + \omit OK, let's find a snippet here as well. \endomit + + QAnimationGroup takes ownership of the animations it manages, and + ensures that they are deleted when the animation group is deleted. + + You can also use a \l{The State Machine Framework}{state machine} + to create complex animations. The framework provides a special + state, QAnimationState, that plays an animation upon entry and + transitions to a new state when the animation has finished + playing. This technique can also be combined with using animation + groups. + + \sa QAbstractAnimation, QVariantAnimation, {The Animation Framework} +*/ + +#ifndef QT_NO_ANIMATION + +#include "qanimationgroup.h" +#include +#include +#include "qanimationgroup_p.h" + +QT_BEGIN_NAMESPACE + + +/*! + Constructs a QAnimationGroup. + \a parent is passed to QObject's constructor. +*/ +QAnimationGroup::QAnimationGroup(QObject *parent) + : QAbstractAnimation(*new QAnimationGroupPrivate, parent) +{ +} + +/*! + \internal +*/ +QAnimationGroup::QAnimationGroup(QAnimationGroupPrivate &dd, QObject *parent) + : QAbstractAnimation(dd, parent) +{ +} + +/*! + Destroys the animation group. It will also destroy all its animations. +*/ +QAnimationGroup::~QAnimationGroup() +{ +} + +/*! + Returns a pointer to the animation at \a index in this group. This + function is useful when you need access to a particular animation. \a + index is between 0 and animationCount() - 1. + + \sa animationCount(), indexOfAnimation() +*/ +QAbstractAnimation *QAnimationGroup::animationAt(int index) const +{ + Q_D(const QAnimationGroup); + + if (index < 0 || index >= d->animations.size()) { + qWarning("QAnimationGroup::animationAt: index is out of bounds"); + return 0; + } + + return d->animations.at(index); +} + + +/*! + Returns the number of animations managed by this group. + + \sa indexOfAnimation(), addAnimation(), animationAt() +*/ +int QAnimationGroup::animationCount() const +{ + Q_D(const QAnimationGroup); + return d->animations.size(); +} + +/*! + Returns the index of \a animation. The returned index can be passed + to the other functions that take an index as an argument. + + \sa insertAnimationAt(), animationAt(), takeAnimationAt() +*/ +int QAnimationGroup::indexOfAnimation(QAbstractAnimation *animation) const +{ + Q_D(const QAnimationGroup); + return d->animations.indexOf(animation); +} + +/*! + Adds \a animation to this group. This will call insertAnimationAt with + index equals to animationCount(). + + \note The group takes ownership of the animation. + + \sa removeAnimation() +*/ +void QAnimationGroup::addAnimation(QAbstractAnimation *animation) +{ + Q_D(QAnimationGroup); + insertAnimationAt(d->animations.count(), animation); +} + +/*! + Inserts \a animation into this animation group at \a index. + If \a index is 0 the animation is inserted at the beginning. + If \a index is animationCount(), the animation is inserted at the end. + + \note The group takes ownership of the animation. + + \sa takeAnimationAt(), addAnimation(), indexOfAnimation(), removeAnimation() +*/ +void QAnimationGroup::insertAnimationAt(int index, QAbstractAnimation *animation) +{ + Q_D(QAnimationGroup); + + if (index < 0 || index > d->animations.size()) { + qWarning("QAnimationGroup::insertAnimationAt: index is out of bounds"); + return; + } + + if (QAnimationGroup *oldGroup = animation->group()) + oldGroup->removeAnimation(animation); + + d->animations.insert(index, animation); + QAbstractAnimationPrivate::get(animation)->group = this; + // this will make sure that ChildAdded event is sent to 'this' + animation->setParent(this); + d->animationInsertedAt(index); +} + +/*! + Removes \a animation from this group. The ownership of \a animation is + transferred to the caller. + + \sa takeAnimationAt(), insertAnimationAt(), addAnimation() +*/ +void QAnimationGroup::removeAnimation(QAbstractAnimation *animation) +{ + Q_D(QAnimationGroup); + + if (!animation) { + qWarning("QAnimationGroup::remove: cannot remove null animation"); + return; + } + int index = d->animations.indexOf(animation); + if (index == -1) { + qWarning("QAnimationGroup::remove: animation is not part of this group"); + return; + } + + takeAnimationAt(index); +} + +/*! + Returns the animation at \a index and removes it from the animation group. + + \note The ownership of the animation is transferred to the caller. + + \sa removeAnimation(), addAnimation(), insertAnimation(), indexOfAnimation() +*/ +QAbstractAnimation *QAnimationGroup::takeAnimationAt(int index) +{ + Q_D(QAnimationGroup); + if (index < 0 || index >= d->animations.size()) { + qWarning("QAnimationGroup::takeAnimationAt: no animation at index %d", index); + return 0; + } + QAbstractAnimation *animation = d->animations.at(index); + QAbstractAnimationPrivate::get(animation)->group = 0; + // ### removing from list before doing setParent to avoid inifinite recursion + // in ChildRemoved event + d->animations.removeAt(index); + animation->setParent(0); + d->animationRemovedAt(index); + return animation; +} + +/*! + Removes and deletes all animations in this animation group, and resets the current + time to 0. + + \sa addAnimation(), removeAnimation() +*/ +void QAnimationGroup::clearAnimations() +{ + Q_D(QAnimationGroup); + qDeleteAll(d->animations); +} + +/*! + \reimp +*/ +bool QAnimationGroup::event(QEvent *event) +{ + Q_D(QAnimationGroup); + if (event->type() == QEvent::ChildAdded) { + QChildEvent *childEvent = static_cast(event); + if (QAbstractAnimation *a = qobject_cast(childEvent->child())) { + if (a->group() != this) + addAnimation(a); + } + } else if (event->type() == QEvent::ChildRemoved) { + QChildEvent *childEvent = static_cast(event); + QAbstractAnimation *a = static_cast(childEvent->child()); + // You can only rely on the child being a QObject because in the QEvent::ChildRemoved + // case it might be called from the destructor. + int index = d->animations.indexOf(a); + if (index != -1) + takeAnimationAt(index); + } + return QAbstractAnimation::event(event); +} + + +void QAnimationGroupPrivate::animationRemovedAt(int index) +{ + Q_Q(QAnimationGroup); + Q_UNUSED(index); + if (animations.isEmpty()) { + currentTime = 0; + q->stop(); + } +} + +QT_END_NAMESPACE + +#include "moc_qanimationgroup.cpp" + +#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qanimationgroup.h b/src/corelib/animation/qanimationgroup.h new file mode 100644 index 0000000..263bc38 --- /dev/null +++ b/src/corelib/animation/qanimationgroup.h @@ -0,0 +1,88 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QANIMATIONGROUP_H +#define QANIMATIONGROUP_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +#ifndef QT_NO_ANIMATION + +class QAnimationGroupPrivate; +class Q_CORE_EXPORT QAnimationGroup : public QAbstractAnimation +{ + Q_OBJECT + +public: + QAnimationGroup(QObject *parent = 0); + ~QAnimationGroup(); + + QAbstractAnimation *animationAt(int index) const; + int animationCount() const; + int indexOfAnimation(QAbstractAnimation *animation) const; + void addAnimation(QAbstractAnimation *animation); + void insertAnimationAt(int index, QAbstractAnimation *animation); + void removeAnimation(QAbstractAnimation *animation); + QAbstractAnimation *takeAnimationAt(int index); + void clearAnimations(); + +protected: + QAnimationGroup(QAnimationGroupPrivate &dd, QObject *parent); + bool event(QEvent *event); + +private: + Q_DISABLE_COPY(QAnimationGroup) + Q_DECLARE_PRIVATE(QAnimationGroup) +}; + +#endif //QT_NO_ANIMATION + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif //QANIMATIONGROUP_H diff --git a/src/corelib/animation/qanimationgroup_p.h b/src/corelib/animation/qanimationgroup_p.h new file mode 100644 index 0000000..a7bd0fa --- /dev/null +++ b/src/corelib/animation/qanimationgroup_p.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QANIMATIONGROUP_P_H +#define QANIMATIONGROUP_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of QIODevice. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qanimationgroup.h" + +#include + +#include "qabstractanimation_p.h" + +QT_BEGIN_NAMESPACE + +class QAnimationGroupPrivate : public QAbstractAnimationPrivate +{ + Q_DECLARE_PUBLIC(QAnimationGroup) +public: + QAnimationGroupPrivate() + { } + + virtual void animationInsertedAt(int index) { Q_UNUSED(index) }; + virtual void animationRemovedAt(int index); + + QList animations; +}; + +QT_END_NAMESPACE + +#endif //QANIMATIONGROUP_P_H diff --git a/src/corelib/animation/qparallelanimationgroup.cpp b/src/corelib/animation/qparallelanimationgroup.cpp new file mode 100644 index 0000000..13f6073 --- /dev/null +++ b/src/corelib/animation/qparallelanimationgroup.cpp @@ -0,0 +1,316 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \class QParallelAnimationGroup + \brief The QParallelAnimationGroup class provides a parallel group of animations. + \since 4.6 + \ingroup animation + + QParallelAnimationGroup--a \l{QAnimationGroup}{container for + animations}--starts all its animations when it is + \l{QAbstractAnimation::start()}{started} itself, i.e., runs all + animations in parallel. The animation group finishes when the + longest lasting animation has finished. + + You can treat QParallelAnimation as any other QAbstractAnimation, + e.g., pause, resume, or add it to other animation groups. + + \code + QParallelAnimationGroup *group = new QParallelAnimationGroup; + group->addAnimation(anim1); + group->addAnimation(anim2); + + group->start(); + \endcode + + In this example, \c anim1 and \c anim2 are two + \l{QPropertyAnimation}s that have already been set up. + + \sa QAnimationGroup, QPropertyAnimation, {The Animation Framework} +*/ + +#ifndef QT_NO_ANIMATION + +#include "qparallelanimationgroup.h" +#include "qparallelanimationgroup_p.h" +//#define QANIMATION_DEBUG +QT_BEGIN_NAMESPACE + +/*! + Constructs a QParallelAnimationGroup. + \a parent is passed to QObject's constructor. +*/ +QParallelAnimationGroup::QParallelAnimationGroup(QObject *parent) + : QAnimationGroup(*new QParallelAnimationGroupPrivate, parent) +{ +} + +/*! + \internal +*/ +QParallelAnimationGroup::QParallelAnimationGroup(QParallelAnimationGroupPrivate &dd, + QObject *parent) + : QAnimationGroup(dd, parent) +{ +} + +/*! + Destroys the animation group. It will also destroy all its animations. +*/ +QParallelAnimationGroup::~QParallelAnimationGroup() +{ +} + +/*! + \reimp +*/ +int QParallelAnimationGroup::duration() const +{ + Q_D(const QParallelAnimationGroup); + int ret = 0; + + for (int i = 0; i < d->animations.size(); ++i) { + QAbstractAnimation *animation = d->animations.at(i); + const int currentDuration = animation->totalDuration(); + if (currentDuration == -1) + return -1; // Undetermined length + + ret = qMax(ret, currentDuration); + } + + return ret; +} + +/*! + \reimp +*/ +void QParallelAnimationGroup::updateCurrentTime(int) +{ + Q_D(QParallelAnimationGroup); + if (d->animations.isEmpty()) + return; + + if (d->currentLoop > d->lastLoop) { + // simulate completion of the loop + int dura = duration(); + if (dura > 0) { + foreach (QAbstractAnimation *animation, d->animations) { + animation->setCurrentTime(dura); // will stop + } + } + } else if (d->currentLoop < d->lastLoop) { + // simulate completion of the loop seeking backwards + foreach (QAbstractAnimation *animation, d->animations) { + animation->setCurrentTime(0); + animation->stop(); + } + } + + bool timeFwd = ((d->currentLoop == d->lastLoop && d->currentTime >= d->lastCurrentTime) + || d->currentLoop > d->lastLoop); +#ifdef QANIMATION_DEBUG + qDebug("QParallellAnimationGroup %5d: setCurrentTime(%d), loop:%d, last:%d, timeFwd:%d, lastcurrent:%d, %d", + __LINE__, d->currentTime, d->currentLoop, d->lastLoop, timeFwd, d->lastCurrentTime, state()); +#endif + // finally move into the actual time of the current loop + foreach (QAbstractAnimation *animation, d->animations) { + const int dura = animation->totalDuration(); + if (dura == -1 && d->isUncontrolledAnimationFinished(animation)) + continue; + if (dura == -1 || (d->currentTime <= dura && dura != 0) + || (dura == 0 && d->currentLoop != d->lastLoop)) { + switch (state()) { + case Running: + animation->start(); + break; + case Paused: + animation->pause(); + break; + case Stopped: + default: + break; + } + } + + if (dura <= 0) { + if (dura == -1) + animation->setCurrentTime(d->currentTime); + continue; + } + + if ((timeFwd && d->lastCurrentTime <= dura) + || (!timeFwd && d->currentTime <= dura)) + animation->setCurrentTime(d->currentTime); + if (d->currentTime > dura) + animation->stop(); + } + d->lastLoop = d->currentLoop; + d->lastCurrentTime = d->currentTime; +} + +/*! + \reimp +*/ +void QParallelAnimationGroup::updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) +{ + Q_D(QParallelAnimationGroup); + QAnimationGroup::updateState(oldState, newState); + + switch (newState) { + case Stopped: + foreach (QAbstractAnimation *animation, d->animations) + animation->stop(); + d->disconnectUncontrolledAnimations(); + break; + case Paused: + foreach (QAbstractAnimation *animation, d->animations) + animation->pause(); + break; + case Running: + d->connectUncontrolledAnimations(); + foreach (QAbstractAnimation *animation, d->animations) { + animation->stop(); + animation->setDirection(d->direction); + animation->start(); + } + break; + } +} + +void QParallelAnimationGroupPrivate::_q_uncontrolledAnimationFinished() +{ + Q_Q(QParallelAnimationGroup); + + QAbstractAnimation *animation = qobject_cast(q->sender()); + Q_ASSERT(animation); + + int uncontrolledRunningCount = 0; + if (animation->duration() == -1 || animation->loopCount() < 0) { + QHash::iterator it = uncontrolledFinishTime.begin(); + while (it != uncontrolledFinishTime.end()) { + if (it.key() == animation) { + *it = animation->currentTime(); + } + if (it.value() == -1) + ++uncontrolledRunningCount; + ++it; + } + } + + if (uncontrolledRunningCount > 0) + return; + + int maxDuration = 0; + foreach (QAbstractAnimation *a, animations) + maxDuration = qMax(maxDuration, a->totalDuration()); + + if (currentTime >= maxDuration) + q->stop(); +} + +void QParallelAnimationGroupPrivate::disconnectUncontrolledAnimations() +{ + Q_Q(QParallelAnimationGroup); + + QHash::iterator it = uncontrolledFinishTime.begin(); + while (it != uncontrolledFinishTime.end()) { + QObject::disconnect(it.key(), SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); + ++it; + } + + uncontrolledFinishTime.clear(); +} + +void QParallelAnimationGroupPrivate::connectUncontrolledAnimations() +{ + Q_Q(QParallelAnimationGroup); + + foreach (QAbstractAnimation *animation, animations) { + if (animation->duration() == -1 || animation->loopCount() < 0) { + uncontrolledFinishTime[animation] = -1; + QObject::connect(animation, SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); + } + } +} + +bool QParallelAnimationGroupPrivate::isUncontrolledAnimationFinished(QAbstractAnimation *anim) const +{ + return uncontrolledFinishTime.value(anim, -1) >= 0; +} + +/*! + \reimp +*/ +void QParallelAnimationGroup::updateDirection(QAbstractAnimation::Direction direction) +{ + Q_D(QParallelAnimationGroup); + //we need to update the direction of the current animation + if (state() != Stopped) { + foreach(QAbstractAnimation *anim, d->animations) { + anim->setDirection(direction); + } + } else { + if (direction == Forward) { + d->lastLoop = 0; + d->lastCurrentTime = 0; + } else { + // Looping backwards with loopCount == -1 does not really work well... + d->lastLoop = (d->loopCount == -1 ? 0 : d->loopCount - 1); + d->lastCurrentTime = duration(); + } + } +} + +/*! + \reimp +*/ +bool QParallelAnimationGroup::event(QEvent *event) +{ + return QAnimationGroup::event(event); +} + +QT_END_NAMESPACE + +#include "moc_qparallelanimationgroup.cpp" + +#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qparallelanimationgroup.h b/src/corelib/animation/qparallelanimationgroup.h new file mode 100644 index 0000000..57a8146 --- /dev/null +++ b/src/corelib/animation/qparallelanimationgroup.h @@ -0,0 +1,86 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QPARALLELANIMATIONGROUP_H +#define QPARALLELANIMATIONGROUP_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +#ifndef QT_NO_ANIMATION + +class QParallelAnimationGroupPrivate; +class Q_CORE_EXPORT QParallelAnimationGroup : public QAnimationGroup +{ + Q_OBJECT + +public: + QParallelAnimationGroup(QObject *parent = 0); + ~QParallelAnimationGroup(); + + int duration() const; + +protected: + QParallelAnimationGroup(QParallelAnimationGroupPrivate &dd, QObject *parent); + bool event(QEvent *event); + + void updateCurrentTime(int msecs); + void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); + void updateDirection(QAbstractAnimation::Direction direction); + +private: + Q_DISABLE_COPY(QParallelAnimationGroup) + Q_DECLARE_PRIVATE(QParallelAnimationGroup) + Q_PRIVATE_SLOT(d_func(), void _q_uncontrolledAnimationFinished()) +}; + +#endif //QT_NO_ANIMATION + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QPARALLELANIMATIONGROUP diff --git a/src/corelib/animation/qparallelanimationgroup_p.h b/src/corelib/animation/qparallelanimationgroup_p.h new file mode 100644 index 0000000..f36d972 --- /dev/null +++ b/src/corelib/animation/qparallelanimationgroup_p.h @@ -0,0 +1,85 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QPARALLELANIMATIONGROUP_P_H +#define QPARALLELANIMATIONGROUP_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of QIODevice. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qparallelanimationgroup.h" +#include "qanimationgroup_p.h" +#include + +QT_BEGIN_NAMESPACE + +class QParallelAnimationGroupPrivate : public QAnimationGroupPrivate +{ + Q_DECLARE_PUBLIC(QParallelAnimationGroup) +public: + QParallelAnimationGroupPrivate() + : lastLoop(0), lastCurrentTime(0) + { + } + + QHash uncontrolledFinishTime; + int lastLoop; + int lastCurrentTime; + + bool isUncontrolledAnimationFinished(QAbstractAnimation *anim) const; + void connectUncontrolledAnimations(); + void disconnectUncontrolledAnimations(); + + // private slot + void _q_uncontrolledAnimationFinished(); +}; + +QT_END_NAMESPACE + +#endif //QPARALLELANIMATIONGROUP_P_H diff --git a/src/corelib/animation/qpauseanimation.cpp b/src/corelib/animation/qpauseanimation.cpp new file mode 100644 index 0000000..b175f0c --- /dev/null +++ b/src/corelib/animation/qpauseanimation.cpp @@ -0,0 +1,154 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \class QPauseAnimation + \brief The QPauseAnimation class provides a pause for QSequentialAnimationGroup. + \since 4.6 + \ingroup animation + + If you wish to introduce a delay between animations in a + QSequentialAnimationGroup, you can insert a QPauseAnimation. This + class does not animate anything, but does not + \l{QAbstractAnimation::finished()}{finish} before a specified + number of milliseconds have elapsed from when it was started. You + specify the duration of the pause in the constructor. It can also + be set directly with setDuration(). + + It is not necessary to construct a QPauseAnimation yourself. + QSequentialAnimationGroup provides the convenience functions + \l{QSequentialAnimationGroup::}{addPause()} and + \l{QSequentialAnimationGroup::}{insertPauseAt()}. These functions + simply take the number of milliseconds the pause should last. + + \sa QSequentialAnimationGroup +*/ + +#ifndef QT_NO_ANIMATION + +#include "qpauseanimation.h" +#include "qabstractanimation_p.h" + + +QT_BEGIN_NAMESPACE + +class QPauseAnimationPrivate : public QAbstractAnimationPrivate +{ +public: + QPauseAnimationPrivate() : QAbstractAnimationPrivate(), duration(0) + { + } + + int duration; +}; + +/*! + Constructs a QPauseAnimation. + \a parent is passed to QObject's constructor. + The default duration is 0. +*/ + +QPauseAnimation::QPauseAnimation(QObject *parent) : QAbstractAnimation(*new QPauseAnimationPrivate, parent) +{ +} + +/*! + Constructs a QPauseAnimation. + \a msecs is the duration of the pause. + \a parent is passed to QObject's constructor. +*/ + +QPauseAnimation::QPauseAnimation(int msecs, QObject *parent) : QAbstractAnimation(*new QPauseAnimationPrivate, parent) +{ + setDuration(msecs); +} + +/*! + Destroys the pause animation. +*/ +QPauseAnimation::~QPauseAnimation() +{ +} + +/*! + \property QPauseAnimation::duration + \brief the duration of the pause. + + The duration of the pause. The duration should not be negative. +*/ +int QPauseAnimation::duration() const +{ + Q_D(const QPauseAnimation); + return d->duration; +} + +void QPauseAnimation::setDuration(int msecs) +{ + if (msecs < 0) { + qWarning("QPauseAnimation::setDuration: cannot set a negative duration"); + return; + } + Q_D(QPauseAnimation); + d->duration = msecs; +} + +/*! + \reimp + */ +bool QPauseAnimation::event(QEvent *e) +{ + return QAbstractAnimation::event(e); +} + +/*! + \reimp + */ +void QPauseAnimation::updateCurrentTime(int msecs) +{ + Q_UNUSED(msecs); +} + + +QT_END_NAMESPACE + +#include "moc_qpauseanimation.cpp" + +#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qpauseanimation.h b/src/corelib/animation/qpauseanimation.h new file mode 100644 index 0000000..cb6e041 --- /dev/null +++ b/src/corelib/animation/qpauseanimation.h @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QPAUSEANIMATION_P_H +#define QPAUSEANIMATION_P_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +#ifndef QT_NO_ANIMATION + +class QPauseAnimationPrivate; + +class Q_CORE_EXPORT QPauseAnimation : public QAbstractAnimation +{ + Q_OBJECT + Q_PROPERTY(int duration READ duration WRITE setDuration) +public: + QPauseAnimation(QObject *parent = 0); + QPauseAnimation(int msecs, QObject *parent = 0); + ~QPauseAnimation(); + + int duration() const; + void setDuration(int msecs); + +protected: + bool event(QEvent *e); + void updateCurrentTime(int msecs); + +private: + Q_DISABLE_COPY(QPauseAnimation) + Q_DECLARE_PRIVATE(QPauseAnimation) +}; + +#endif //QT_NO_ANIMATION + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QPAUSEANIMATION_P_H diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp new file mode 100644 index 0000000..9a17049 --- /dev/null +++ b/src/corelib/animation/qpropertyanimation.cpp @@ -0,0 +1,316 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \class QPropertyAnimation + \brief The QPropertyAnimation class animates Qt properties + \since 4.6 + \ingroup animation + + QPropertyAnimation interpolates over \l{Qt's Property System}{Qt + properties}. As property values are stored in \l{QVariant}s, the + class inherits QVariantAnimation, and supports animation of the + same \l{QVariant::Type}{variant types} as its super class. + + A class declaring properties must be a QObject. To make it + possible to animate a property, it must provide a setter (so that + QPropertyAnimation can set the property's value). Note that this + makes it possible to animate many of Qt's widgets. Let's look at + an example: + + \code + QPropertyAnimation animation(myWidget, "geometry"); + animation.setDuration(10000); + animation.setStartValue(QRect(0, 0, 100, 30)); + animation.setEndValue(QRect(250, 250, 100, 30)); + + animation.start(); + \endcode + + The property name and the QObject instance of which property + should be animated are passed to the constructor. You can then + specify the start and end value of the property. The procedure is + equal for properties in classes you have implemented + yourself--just check with QVariantAnimation that your QVariant + type is supported. + + The QVariantAnimation class description explains how to set up the + animation in detail. Note, however, that if a start value is not + set, the property will start at the value it had when the + QPropertyAnimation instance was created. + + QPropertyAnimation works like a charm on its own. For complex + animations that, for instance, contain several objects, + QAnimationGroup is provided. An animation group is an animation + that can contain other animations, and that can manage when its + animations are played. Look at QParallelAnimationGroup for an + example. + + \sa QVariantAnimation, QAnimationGroup, {The Animation Framework} +*/ + +#ifndef QT_NO_ANIMATION + +#include "qpropertyanimation.h" +#include "qanimationgroup.h" +#include + +#include "qpropertyanimation_p.h" + +#include +#include + +QT_BEGIN_NAMESPACE + +typedef QPair QPropertyAnimationPair; +typedef QHash QPropertyAnimationHash; +Q_GLOBAL_STATIC(QPropertyAnimationHash, _q_runningAnimations); +Q_GLOBAL_STATIC_WITH_ARGS(QMutex, guardHashLock, (QMutex::Recursive) ) + +void QPropertyAnimationPrivate::updateMetaProperty() +{ + if (!target || propertyName.isEmpty()) + return; + + if (hasMetaProperty == 0 && !property.isValid()) { + const QMetaObject *mo = target->metaObject(); + propertyIndex = mo->indexOfProperty(propertyName); + if (propertyIndex != -1) { + hasMetaProperty = 1; + property = mo->property(propertyIndex); + propertyType = property.userType(); + } else { + if (!target->dynamicPropertyNames().contains(propertyName)) + qWarning("QPropertyAnimation: you're trying to animate a non-existing property %s of your QObject", propertyName.constData()); + hasMetaProperty = 2; + } + } + + if (property.isValid()) + convertValues(propertyType); +} + +void QPropertyAnimationPrivate::updateProperty(const QVariant &newValue) +{ + if (!target || state == QAbstractAnimation::Stopped) + return; + + if (hasMetaProperty == 1) { + if (newValue.userType() == propertyType) { + //no conversion is needed, we directly call the QObject::qt_metacall + void *data = const_cast(newValue.constData()); + target->qt_metacall(QMetaObject::WriteProperty, propertyIndex, &data); + } else { + property.write(target, newValue); + } + } else { + target->setProperty(propertyName.constData(), newValue); + } +} + +void QPropertyAnimationPrivate::_q_targetDestroyed() +{ + Q_Q(QPropertyAnimation); + //we stop here so that this animation is removed from the global hash + q->stop(); + target = 0; +} + +/*! + Construct a QPropertyAnimation object. \a parent is passed to QObject's + constructor. +*/ +QPropertyAnimation::QPropertyAnimation(QObject *parent) + : QVariantAnimation(*new QPropertyAnimationPrivate, parent) +{ +} + +/*! + Construct a QPropertyAnimation object. \a parent is passed to QObject's + constructor. The animation changes the property \a propertyName on \a + target. The default duration is 250ms. + + \sa targetObject, propertyName +*/ +QPropertyAnimation::QPropertyAnimation(QObject *target, const QByteArray &propertyName, QObject *parent) + : QVariantAnimation(*new QPropertyAnimationPrivate, parent) +{ + setTargetObject(target); + setPropertyName(propertyName); +} + +/*! + Destroys the QPropertyAnimation instance. + */ +QPropertyAnimation::~QPropertyAnimation() +{ + stop(); +} + +/*! + \property QPropertyAnimation::targetObject + \brief the target QObject for this animation. + + This property defines the target QObject for this animation. + */ +QObject *QPropertyAnimation::targetObject() const +{ + Q_D(const QPropertyAnimation); + return d->target; +} + +void QPropertyAnimation::setTargetObject(QObject *target) +{ + Q_D(QPropertyAnimation); + if (d->target == target) + return; + + if (d->state != QAbstractAnimation::Stopped) { + qWarning("QPropertyAnimation::setTargetObject: you can't change the target of a running animation"); + return; + } + + //we need to get notified when the target is destroyed + if (d->target) + disconnect(d->target, SIGNAL(destroyed()), this, SLOT(_q_targetDestroyed())); + + if (target) + connect(target, SIGNAL(destroyed()), SLOT(_q_targetDestroyed())); + + d->target = target; + d->hasMetaProperty = 0; + d->updateMetaProperty(); +} + +/*! + \property QPropertyAnimation::propertyName + \brief the target property name for this animation + + This property defines the target property name for this animation. The + property name is required for the animation to operate. + */ +QByteArray QPropertyAnimation::propertyName() const +{ + Q_D(const QPropertyAnimation); + return d->propertyName; +} + +void QPropertyAnimation::setPropertyName(const QByteArray &propertyName) +{ + Q_D(QPropertyAnimation); + if (d->state != QAbstractAnimation::Stopped) { + qWarning("QPropertyAnimation::setPropertyName: you can't change the property name of a running animation"); + return; + } + + d->propertyName = propertyName; + d->hasMetaProperty = 0; + d->updateMetaProperty(); +} + + +/*! + \reimp + */ +bool QPropertyAnimation::event(QEvent *event) +{ + return QVariantAnimation::event(event); +} + +/*! + This virtual function is called by QVariantAnimation whenever the current value + changes. \a value is the new, updated value. It updates the current value + of the property on the target object. + + \sa currentValue, currentTime + */ +void QPropertyAnimation::updateCurrentValue(const QVariant &value) +{ + Q_D(QPropertyAnimation); + d->updateProperty(value); +} + +/*! + \reimp + + If the startValue is not defined when the state of the animation changes from Stopped to Running, + the current property value is used as the initial value for the animation. +*/ +void QPropertyAnimation::updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) +{ + Q_D(QPropertyAnimation); + + if (!d->target) { + qWarning("QPropertyAnimation::updateState: Changing state of an animation without target"); + return; + } + + QVariantAnimation::updateState(oldState, newState); + QMutexLocker locker(guardHashLock()); + QPropertyAnimationHash * hash = _q_runningAnimations(); + QPropertyAnimationPair key(d->target, d->propertyName); + if (newState == Running) { + d->updateMetaProperty(); + QPropertyAnimation *oldAnim = hash->value(key, 0); + if (oldAnim) { + // try to stop the top level group + QAbstractAnimation *current = oldAnim; + while (current->group() && current->state() != Stopped) + current = current->group(); + current->stop(); + } + hash->insert(key, this); + + // update the default start value + if (oldState == Stopped) { + d->setDefaultStartValue(d->target->property(d->propertyName.constData())); + } + } else if (hash->value(key) == this) { + hash->remove(key); + } +} + +#include "moc_qpropertyanimation.cpp" + +QT_END_NAMESPACE + +#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qpropertyanimation.h b/src/corelib/animation/qpropertyanimation.h new file mode 100644 index 0000000..5b06bd2 --- /dev/null +++ b/src/corelib/animation/qpropertyanimation.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QPROPERTYANIMATION_H +#define QPROPERTYANIMATION_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +#ifndef QT_NO_ANIMATION + +class QPropertyAnimationPrivate; +class Q_CORE_EXPORT QPropertyAnimation : public QVariantAnimation +{ + Q_OBJECT + Q_PROPERTY(QByteArray propertyName READ propertyName WRITE setPropertyName) + Q_PROPERTY(QObject* targetObject READ targetObject WRITE setTargetObject) + +public: + QPropertyAnimation(QObject *parent = 0); + QPropertyAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0); + ~QPropertyAnimation(); + + QObject *targetObject() const; + void setTargetObject(QObject *target); + + QByteArray propertyName() const; + void setPropertyName(const QByteArray &propertyName); + +protected: + bool event(QEvent *event); + + void updateCurrentValue(const QVariant &value); + void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); + Q_PRIVATE_SLOT(d_func(), void _q_targetDestroyed()); +private: + Q_DISABLE_COPY(QPropertyAnimation) + Q_DECLARE_PRIVATE(QPropertyAnimation) +}; + +#endif //QT_NO_ANIMATION + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QPROPERTYANIMATION_H diff --git a/src/corelib/animation/qpropertyanimation_p.h b/src/corelib/animation/qpropertyanimation_p.h new file mode 100644 index 0000000..b51d039 --- /dev/null +++ b/src/corelib/animation/qpropertyanimation_p.h @@ -0,0 +1,89 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QPROPERTYANIMATION_P_H +#define QPROPERTYANIMATION_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of QIODevice. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qpropertyanimation.h" +#include + +#include "qvariantanimation_p.h" + +QT_BEGIN_NAMESPACE + +class QPropertyAnimationPrivate : public QVariantAnimationPrivate +{ + Q_DECLARE_PUBLIC(QPropertyAnimation) +public: + QPropertyAnimationPrivate() + : target(0), propertyType(0), propertyIndex(0), hasMetaProperty(false) + { + } + + void _q_targetDestroyed(); + + QObject *target; + + //for the QProperty + QMetaProperty property; + int propertyType; + int propertyIndex; + + int hasMetaProperty; + QByteArray propertyName; + void updateProperty(const QVariant &); + void updateMetaProperty(); +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/animation/qsequentialanimationgroup.cpp b/src/corelib/animation/qsequentialanimationgroup.cpp new file mode 100644 index 0000000..14814a7 --- /dev/null +++ b/src/corelib/animation/qsequentialanimationgroup.cpp @@ -0,0 +1,594 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/*! + \class QSequentialAnimationGroup + \brief The QSequentialAnimationGroup class provides a sequential group of animations. + \since 4.6 + \ingroup animation + + QSequentialAnimationGroup is a QAnimationGroup that runs its + animations in sequence, i.e., it starts one animation after + another has finished playing. The animations are played in the + order they are added to the group (using + \l{QAnimationGroup::}{addAnimation()} or + \l{QAnimationGroup::}{insertAnimationAt()}). The animation group + finishes when its last animation has finished. + + At each moment there is at most one animation that is active in + the group; it is returned by currentAnimation(). An empty group + has no current animation. + + A sequential animation group can be treated as any other + animation, i.e., it can be started, stopped, and added to other + groups. You can also call addPause() or insertPauseAt() to add a + pause to a sequential animation group. + + \code + QSequentialAnimationGroup group; + + group.addAnimation(anim1); + group.addAnimation(anim2); + + group.start(); + \endcode + + In this example, \c anim1 and \c anim2 are two already set up + \l{QPropertyAnimation}s. + + \sa QAnimationGroup, QAbstractAnimation, {The Animation Framework} +*/ + +#ifndef QT_NO_ANIMATION + +#include "qsequentialanimationgroup.h" +#include "qsequentialanimationgroup_p.h" + +#include "qpauseanimation.h" + +#include + +QT_BEGIN_NAMESPACE + + + +bool QSequentialAnimationGroupPrivate::atEnd() const +{ + // we try to detect if we're at the end of the group + //this is true if the following conditions are true: + // 1. we're in the last loop + // 2. the direction is forward + // 3. the current animation is the last one + // 4. the current animation has reached its end + const int animTotalCurrentTime = QAbstractAnimationPrivate::get(currentAnimation)->totalCurrentTime; + return (currentLoop == loopCount - 1 + && direction == QAbstractAnimation::Forward + && currentAnimation == animations.last() + && animTotalCurrentTime == animationActualTotalDuration(currentAnimationIndex)); +} + +int QSequentialAnimationGroupPrivate::animationActualTotalDuration(int index) const +{ + QAbstractAnimation *anim = animations.at(index); + int ret = anim->totalDuration(); + if (ret == -1 && actualDuration.size() > index) + ret = actualDuration.at(index); //we can try the actual duration there + return ret; +} + +QSequentialAnimationGroupPrivate::AnimationIndex QSequentialAnimationGroupPrivate::indexForTime(int msecs) const +{ + Q_Q(const QSequentialAnimationGroup); + Q_ASSERT(!animations.isEmpty()); + + AnimationIndex ret; + int duration = 0; + + // in case duration is -1, currentLoop will always be 0 + ret.timeOffset = currentLoop * q->duration(); + + for (int i = 0; i < animations.size(); ++i) { + duration = animationActualTotalDuration(i); + + // 'animation' is the current animation if one of these reasons is true: + // 1. it's duration is undefined + // 2. it ends after msecs + // 3. it is the last animation (this can happen in case there is at least 1 uncontrolled animation) + // 4. it ends exactly in msecs and the direction is backwards + if (duration == -1 || msecs < (ret.timeOffset + duration) + || (msecs == (ret.timeOffset + duration) && direction == QAbstractAnimation::Backward)) { + ret.index = i; + return ret; + } + + // 'animation' has a non-null defined duration and is not the one at time 'msecs'. + ret.timeOffset += duration; + } + + // this can only happen when one of those conditions is true: + // 1. the duration of the group is undefined and we passed its actual duration + // 2. there are only 0-duration animations in the group + ret.timeOffset -= duration; + ret.index = animations.size() - 1; + return ret; +} + +void QSequentialAnimationGroupPrivate::restart() +{ + // restarting the group by making the first/last animation the current one + if (direction == QAbstractAnimation::Forward) { + lastLoop = 0; + if (currentAnimationIndex == 0) + activateCurrentAnimation(); + else + setCurrentAnimation(0); + } else { // direction == QAbstractAnimation::Backward + lastLoop = loopCount - 1; + int index = animations.size() - 1; + if (currentAnimationIndex == index) + activateCurrentAnimation(); + else + setCurrentAnimation(index); + } +} + +/*! + \internal + This manages advancing the execution of a group running forwards (time has gone forward), + which is the same behaviour for rewinding the execution of a group running backwards + (time has gone backward). +*/ +void QSequentialAnimationGroupPrivate::advanceForwards(const AnimationIndex &newAnimationIndex) +{ + if (lastLoop < currentLoop) { + // we need to fast forward to the end + for (int i = currentAnimationIndex; i < animations.size(); ++i) { + QAbstractAnimation *anim = animations.at(i); + setCurrentAnimation(i, true); + anim->setCurrentTime(animationActualTotalDuration(i)); + } + // this will make sure the current animation is reset to the beginning + if (animations.size() == 1) + // we need to force activation because setCurrentAnimation will have no effect + activateCurrentAnimation(); + else + setCurrentAnimation(0, true); + } + + // and now we need to fast forward from the current position to + for (int i = currentAnimationIndex; i < newAnimationIndex.index; ++i) { //### WRONG, + QAbstractAnimation *anim = animations.at(i); + setCurrentAnimation(i, true); + anim->setCurrentTime(animationActualTotalDuration(i)); + } + // setting the new current animation will happen later +} + +/*! + \internal + This manages rewinding the execution of a group running forwards (time has gone forward), + which is the same behaviour for advancing the execution of a group running backwards + (time has gone backward). +*/ +void QSequentialAnimationGroupPrivate::rewindForwards(const AnimationIndex &newAnimationIndex) +{ + if (lastLoop > currentLoop) { + // we need to fast rewind to the beginning + for (int i = currentAnimationIndex; i >= 0 ; --i) { + QAbstractAnimation *anim = animations.at(i); + setCurrentAnimation(i, true); + anim->setCurrentTime(0); + } + // this will make sure the current animation is reset to the end + if (animations.size() == 1) + // we need to force activation because setCurrentAnimation will have no effect + activateCurrentAnimation(); + else + setCurrentAnimation(animations.count() - 1, true); + } + + // and now we need to fast rewind from the current position to + for (int i = currentAnimationIndex; i > newAnimationIndex.index; --i) { + QAbstractAnimation *anim = animations.at(i); + setCurrentAnimation(i, true); + anim->setCurrentTime(0); + } + // setting the new current animation will happen later +} + +/*! + \fn QSequentialAnimationGroup::currentAnimationChanged(QAbstractAnimation *current) + + QSequentialAnimationGroup emits this signal when currentAnimation + has been changed. \a current is the current animation. + + \sa currentAnimation() +*/ + + +/*! + Constructs a QSequentialAnimationGroup. + \a parent is passed to QObject's constructor. +*/ +QSequentialAnimationGroup::QSequentialAnimationGroup(QObject *parent) + : QAnimationGroup(*new QSequentialAnimationGroupPrivate, parent) +{ +} + +/*! + \internal +*/ +QSequentialAnimationGroup::QSequentialAnimationGroup(QSequentialAnimationGroupPrivate &dd, + QObject *parent) + : QAnimationGroup(dd, parent) +{ +} + +/*! + Destroys the animation group. It will also destroy all its animations. +*/ +QSequentialAnimationGroup::~QSequentialAnimationGroup() +{ +} + +/*! + Adds a pause of \a msecs to this animation group. + The pause is considered as a special type of animation, thus count() will be + increased by one. + \sa insertPauseAt(), QAnimationGroup::addAnimation() +*/ +QPauseAnimation *QSequentialAnimationGroup::addPause(int msecs) +{ + QPauseAnimation *pause = new QPauseAnimation(msecs); + addAnimation(pause); + return pause; +} + +/*! + Inserts a pause of \a msecs milliseconds at \a index in this animation + group. + + \sa addPause(), QAnimationGroup::insertAnimationAt() +*/ +QPauseAnimation *QSequentialAnimationGroup::insertPauseAt(int index, int msecs) +{ + Q_D(const QSequentialAnimationGroup); + + if (index < 0 || index > d->animations.size()) { + qWarning("QSequentialAnimationGroup::insertPauseAt: index is out of bounds"); + return 0; + } + + QPauseAnimation *pause = new QPauseAnimation(msecs); + insertAnimationAt(index, pause); + return pause; +} + + +/*! + \property QSequentialAnimationGroup::currentAnimation + Returns the animation in the current time. + + \sa currentAnimationChanged() +*/ +QAbstractAnimation *QSequentialAnimationGroup::currentAnimation() const +{ + Q_D(const QSequentialAnimationGroup); + return d->currentAnimation; +} + +/*! + \reimp +*/ +int QSequentialAnimationGroup::duration() const +{ + Q_D(const QSequentialAnimationGroup); + int ret = 0; + + for (int i = 0; i < d->animations.size(); ++i) { + QAbstractAnimation *animation = d->animations.at(i); + const int currentDuration = animation->totalDuration(); + if (currentDuration == -1) + return -1; // Undetermined length + + ret += currentDuration; + } + + return ret; +} + +/*! + \reimp +*/ +void QSequentialAnimationGroup::updateCurrentTime(int msecs) +{ + Q_D(QSequentialAnimationGroup); + if (!d->currentAnimation) + return; + + const QSequentialAnimationGroupPrivate::AnimationIndex newAnimationIndex = d->indexForTime(msecs); + + // remove unneeded animations from actualDuration list + while (newAnimationIndex.index < d->actualDuration.size()) + d->actualDuration.removeLast(); + + // newAnimationIndex.index is the new current animation + if (d->lastLoop < d->currentLoop + || (d->lastLoop == d->currentLoop && d->currentAnimationIndex < newAnimationIndex.index)) { + // advancing with forward direction is the same as rewinding with backwards direction + d->advanceForwards(newAnimationIndex); + } else if (d->lastLoop > d->currentLoop + || (d->lastLoop == d->currentLoop && d->currentAnimationIndex > newAnimationIndex.index)) { + // rewinding with forward direction is the same as advancing with backwards direction + d->rewindForwards(newAnimationIndex); + } + + d->setCurrentAnimation(newAnimationIndex.index); + + const int newCurrentTime = msecs - newAnimationIndex.timeOffset; + + if (d->currentAnimation) { + d->currentAnimation->setCurrentTime(newCurrentTime); + if (d->atEnd()) { + //we make sure that we don't exceed the duration here + d->currentTime += QAbstractAnimationPrivate::get(d->currentAnimation)->totalCurrentTime - newCurrentTime; + stop(); + } + } else { + //the only case where currentAnimation could be null + //is when all animations have been removed + Q_ASSERT(d->animations.isEmpty()); + d->currentTime = 0; + stop(); + } + + d->lastLoop = d->currentLoop; +} + +/*! + \reimp +*/ +void QSequentialAnimationGroup::updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) +{ + Q_D(QSequentialAnimationGroup); + QAnimationGroup::updateState(oldState, newState); + + if (!d->currentAnimation) + return; + + switch (newState) { + case Stopped: + d->currentAnimation->stop(); + break; + case Paused: + if (oldState == d->currentAnimation->state() + && oldState == QSequentialAnimationGroup::Running) { + d->currentAnimation->pause(); + } + else + d->restart(); + break; + case Running: + if (oldState == d->currentAnimation->state() + && oldState == QSequentialAnimationGroup::Paused) + d->currentAnimation->start(); + else + d->restart(); + break; + } +} + +/*! + \reimp +*/ +void QSequentialAnimationGroup::updateDirection(QAbstractAnimation::Direction direction) +{ + Q_D(QSequentialAnimationGroup); + // we need to update the direction of the current animation + if (state() != Stopped && d->currentAnimation) + d->currentAnimation->setDirection(direction); +} + +/*! + \reimp +*/ +bool QSequentialAnimationGroup::event(QEvent *event) +{ + return QAnimationGroup::event(event); +} + +void QSequentialAnimationGroupPrivate::setCurrentAnimation(int index, bool intermediate) +{ + Q_Q(QSequentialAnimationGroup); + + index = qMin(index, animations.count() - 1); + + if (index == -1) { + Q_ASSERT(animations.isEmpty()); + currentAnimationIndex = -1; + currentAnimation = 0; + return; + } + + // need these two checks below because this func can be called after the current animation + // has been removed + if (index == currentAnimationIndex && animations.at(index) == currentAnimation) + return; + + // stop the old current animation + if (currentAnimation) + currentAnimation->stop(); + + currentAnimation = animations.at(index); + currentAnimationIndex = index; + + emit q->currentAnimationChanged(currentAnimation); + + activateCurrentAnimation(intermediate); +} + +void QSequentialAnimationGroupPrivate::activateCurrentAnimation(bool intermediate) +{ + Q_Q(QSequentialAnimationGroup); + + if (!currentAnimation) + return; + + if (state == QSequentialAnimationGroup::Stopped) + return; + + currentAnimation->stop(); + + // we ensure the direction is consistent with the group's direction + currentAnimation->setDirection(direction); + + // connects to the finish signal of uncontrolled animations + if (currentAnimation->totalDuration() == -1) + QObject::connect(currentAnimation, SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); + + currentAnimation->start(); + if (!intermediate && state == QSequentialAnimationGroup::Paused) + currentAnimation->pause(); +} + +void QSequentialAnimationGroupPrivate::_q_uncontrolledAnimationFinished() +{ + Q_Q(QSequentialAnimationGroup); + Q_ASSERT(qobject_cast(q->sender()) == currentAnimation); + + // we trust the duration returned by the animation + while (actualDuration.size() < (currentAnimationIndex + 1)) + actualDuration.append(-1); + actualDuration[currentAnimationIndex] = currentAnimation->currentTime(); + + QObject::disconnect(currentAnimation, SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); + + if ((direction == QAbstractAnimation::Forward && currentAnimation == animations.last()) + || (direction == QAbstractAnimation::Backward && currentAnimationIndex == 0)) { + // we don't handle looping of a group with undefined duration + q->stop(); + } else if (direction == QAbstractAnimation::Forward) { + // set the current animation to be the next one + setCurrentAnimation(currentAnimationIndex + 1); + } else { + // set the current animation to be the previous one + setCurrentAnimation(currentAnimationIndex - 1); + } +} + +/*! + \internal + This method is called whenever an animation is added to + the group at index \a index. + Note: We only support insertion after the current animation +*/ +void QSequentialAnimationGroupPrivate::animationInsertedAt(int index) +{ + if (currentAnimation == 0) + setCurrentAnimation(0); // initialize the current animation + + if (currentAnimationIndex == index + && currentAnimation->currentTime() == 0 && currentAnimation->currentLoop() == 0) { + //in this case we simply insert an animation before the current one has actually started + setCurrentAnimation(index); + } + + //we update currentAnimationIndex in case it has changed (the animation pointer is still valid) + currentAnimationIndex = animations.indexOf(currentAnimation); + + if (index < currentAnimationIndex || currentLoop != 0) { + qWarning("QSequentialGroup::insertAnimationAt only supports to add animations after the current one."); + return; //we're not affected because it is added after the current one + } +} + +/*! + \internal + This method is called whenever an animation is removed from + the group at index \a index. The animation is no more listed when this + method is called. +*/ +void QSequentialAnimationGroupPrivate::animationRemovedAt(int index) +{ + Q_Q(QSequentialAnimationGroup); + QAnimationGroupPrivate::animationRemovedAt(index); + + Q_ASSERT(currentAnimation); // currentAnimation should always be set + + if (actualDuration.size() > index) + actualDuration.removeAt(index); + + const int currentIndex = animations.indexOf(currentAnimation); + if (currentIndex == -1) { + //we're removing the current animation, let's update it to another one + if (index < animations.count()) + setCurrentAnimation(index); //let's try to take the next one + else if (index > 0) + setCurrentAnimation(index - 1); + else// case all animations were removed + setCurrentAnimation(-1); + } else if (currentAnimationIndex > index) { + currentAnimationIndex--; + } + + // duration of the previous animations up to the current animation + currentTime = 0; + for (int i = 0; i < currentAnimationIndex; ++i) { + const int current = animationActualTotalDuration(i); + currentTime += current; + } + + if (currentIndex != -1) { + //the current animation is not the one being removed + //so we add its current time to the current time of this group + currentTime += QAbstractAnimationPrivate::get(currentAnimation)->totalCurrentTime; + } + + //let's also update the total current time + totalCurrentTime = currentTime + loopCount * q->duration(); +} + +QT_END_NAMESPACE + +#include "moc_qsequentialanimationgroup.cpp" + +#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qsequentialanimationgroup.h b/src/corelib/animation/qsequentialanimationgroup.h new file mode 100644 index 0000000..4701a76 --- /dev/null +++ b/src/corelib/animation/qsequentialanimationgroup.h @@ -0,0 +1,96 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSEQUENTIALANIMATIONGROUP_H +#define QSEQUENTIALANIMATIONGROUP_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +#ifndef QT_NO_ANIMATION + +class QPauseAnimation; +class QSequentialAnimationGroupPrivate; + +class Q_CORE_EXPORT QSequentialAnimationGroup : public QAnimationGroup +{ + Q_OBJECT + Q_PROPERTY(QAbstractAnimation* currentAnimation READ currentAnimation NOTIFY currentAnimationChanged) + +public: + QSequentialAnimationGroup(QObject *parent = 0); + ~QSequentialAnimationGroup(); + + QPauseAnimation *addPause(int msecs); + QPauseAnimation *insertPauseAt(int index, int msecs); + + QAbstractAnimation *currentAnimation() const; + int duration() const; + +Q_SIGNALS: + void currentAnimationChanged(QAbstractAnimation *current); + +protected: + QSequentialAnimationGroup(QSequentialAnimationGroupPrivate &dd, QObject *parent); + bool event(QEvent *event); + + void updateCurrentTime(int msecs); + void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); + void updateDirection(QAbstractAnimation::Direction direction); + +private: + Q_DISABLE_COPY(QSequentialAnimationGroup) + Q_DECLARE_PRIVATE(QSequentialAnimationGroup) + Q_PRIVATE_SLOT(d_func(), void _q_uncontrolledAnimationFinished()) +}; + +#endif //QT_NO_ANIMATION + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif //QSEQUENTIALANIMATIONGROUP_H diff --git a/src/corelib/animation/qsequentialanimationgroup_p.h b/src/corelib/animation/qsequentialanimationgroup_p.h new file mode 100644 index 0000000..3ac90f8 --- /dev/null +++ b/src/corelib/animation/qsequentialanimationgroup_p.h @@ -0,0 +1,111 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSEQUENTIALANIMATIONGROUP_P_H +#define QSEQUENTIALANIMATIONGROUP_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of QIODevice. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qsequentialanimationgroup.h" +#include "qanimationgroup_p.h" + + +QT_BEGIN_NAMESPACE + +class QSequentialAnimationGroupPrivate : public QAnimationGroupPrivate +{ + Q_DECLARE_PUBLIC(QSequentialAnimationGroup) +public: + QSequentialAnimationGroupPrivate() + : currentAnimation(0), currentAnimationIndex(-1), lastLoop(0) + { } + + + struct AnimationIndex + { + AnimationIndex() : index(0), timeOffset(0) {} + // index points to the animation at timeOffset, skipping 0 duration animations. + // Note that the index semantic is slightly different depending on the direction. + int index; // the index of the animation in timeOffset + int timeOffset; // time offset when the animation at index starts. + }; + + int animationActualTotalDuration(int index) const; + AnimationIndex indexForTime(int msecs) const; + + void setCurrentAnimation(int index, bool intermediate = false); + void activateCurrentAnimation(bool intermediate = false); + + void animationInsertedAt(int index); + void animationRemovedAt(int index); + + bool atEnd() const; + + QAbstractAnimation *currentAnimation; + int currentAnimationIndex; + + // this is the actual duration of uncontrolled animations + // it helps seeking and even going forward + QList actualDuration; + + void restart(); + int lastLoop; + + // handle time changes + void rewindForwards(const AnimationIndex &newAnimationIndex); + void advanceForwards(const AnimationIndex &newAnimationIndex); + + // private slot + void _q_uncontrolledAnimationFinished(); +}; + +QT_END_NAMESPACE + +#endif //QSEQUENTIALANIMATIONGROUP_P_H diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp new file mode 100644 index 0000000..a6834bb --- /dev/null +++ b/src/corelib/animation/qvariantanimation.cpp @@ -0,0 +1,644 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT_NO_ANIMATION + +#include "qvariantanimation.h" +#include "qvariantanimation_p.h" + +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +/*! + \class QVariantAnimation + \ingroup animation + \brief The QVariantAnimation class provides an abstract base class for animations. + \since 4.6 + + This class is part of \l{The Animation Framework}. It serves as a + base class for property and item animations, with functions for + shared functionality. + + QVariantAnimation cannot be used directly as it is an abstract + class; it does not implement + \l{QAbstractAnimation::}{updateCurrentValue()} from + QAbstractAnimation. The class performs interpolation over + \l{QVariant}s, but leaves using the interpolated values to its + subclasses. Currently, Qt provides QPropertyAnimation, which + animates Qt \l{Qt's Property System}{properties}. See the + QPropertyAnimation class description if you wish to animate such + properties. + + You can then set start and end values for the property by calling + setStartValue() and setEndValue(), and finally call start() to + start the animation. QVariantAnimation will interpolate the + property of the target object and emit valueChanged(). To react to + a change in the current value you have to reimplement the + updateCurrentValue() virtual function. + + It is also possible to set values at specified steps situated + between the start and end value. The interpolation will then + touch these points at the specified steps. Note that the start and + end values are defined as the key values at 0.0 and 1.0. + + There are two ways to affect how QVariantAnimation interpolates + the values. You can set an easing curve by calling + setEasingCurve(), and configure the duration by calling + setDuration(). You can change how the QVariants are interpolated + by creating a subclass of QVariantAnimation, and reimplementing + the virtual interpolated() function. + + Subclassing QVariantAnimation can be an alternative if you have + \l{QVariant}s that you do not wish to declare as Qt properties. + Note, however, that you in most cases will be better off declaring + your QVariant as a property. + + Not all QVariant types are supported. Below is a list of currently + supported QVariant types: + + \list + \o \l{QMetaType::}{Int} + \o \l{QMetaType::}{Double} + \o \l{QMetaType::}{Float} + \o \l{QMetaType::}{QLine} + \o \l{QMetaType::}{QLineF} + \o \l{QMetaType::}{QPoint} + \o \l{QMetaType::}{QSize} + \o \l{QMetaType::}{QSizeF} + \o \l{QMetaType::}{QRect} + \o \l{QMetaType::}{QRectF} + \endlist + + If you need to interpolate other variant types, including custom + types, you have to implement interpolation for these yourself. + You do this by reimplementing interpolated(), which returns + interpolation values for the value being interpolated. + + \omit We need some snippets around here. \endomit + + \sa QPropertyAnimation, QAbstractAnimation, {The Animation Framework} +*/ + +/*! + \fn void QVariantAnimation::valueChanged(const QVariant &value) + + QVariantAnimation emits this signal whenever the current \a value changes. + + \sa currentValue, startValue, endValue +*/ + +static bool animationValueLessThan(const QVariantAnimation::KeyValue &p1, const QVariantAnimation::KeyValue &p2) +{ + return p1.first < p2.first; +} + +template<> Q_INLINE_TEMPLATE QRect _q_interpolate(const QRect &f, const QRect &t, qreal progress) +{ + QRect ret; + ret.setCoords(_q_interpolate(f.left(), t.left(), progress), + _q_interpolate(f.top(), t.top(), progress), + _q_interpolate(f.right(), t.right(), progress), + _q_interpolate(f.bottom(), t.bottom(), progress)); + return ret; +} + +template<> Q_INLINE_TEMPLATE QRectF _q_interpolate(const QRectF &f, const QRectF &t, qreal progress) +{ + qreal x1, y1, w1, h1; + f.getRect(&x1, &y1, &w1, &h1); + qreal x2, y2, w2, h2; + t.getRect(&x2, &y2, &w2, &h2); + return QRectF(_q_interpolate(x1, x2, progress), _q_interpolate(y1, y2, progress), + _q_interpolate(w1, w2, progress), _q_interpolate(h1, h2, progress)); +} + +template<> Q_INLINE_TEMPLATE QLine _q_interpolate(const QLine &f, const QLine &t, qreal progress) +{ + return QLine( _q_interpolate(f.p1(), t.p1(), progress), _q_interpolate(f.p2(), t.p2(), progress)); +} + +template<> Q_INLINE_TEMPLATE QLineF _q_interpolate(const QLineF &f, const QLineF &t, qreal progress) +{ + return QLineF( _q_interpolate(f.p1(), t.p1(), progress), _q_interpolate(f.p2(), t.p2(), progress)); +} + +void QVariantAnimationPrivate::convertValues(int t) +{ + //this ensures that all the keyValues are of type t + for (int i = 0; i < keyValues.count(); ++i) { + QVariantAnimation::KeyValue &pair = keyValues[i]; + if (pair.second.userType() != t) + pair.second.convert(static_cast(t)); + } + interpolator = 0; // if the type changed we need to update the interpolator +} + +/*! + \internal + The goal of this function is to update the currentInterval member. As a consequence, we also + need to update the currentValue. + Set \a force to true to always recalculate the interval. +*/ +void QVariantAnimationPrivate::recalculateCurrentInterval(bool force/*=false*/) +{ + // can't interpolate if we have only 1 key value + if (keyValues.count() <= 1) + return; + + const qreal progress = easing.valueForProgress(((duration == 0) ? qreal(1) : qreal(currentTime) / qreal(duration))); + + if (force || progress < currentInterval.start.first || progress > currentInterval.end.first) { + //let's update currentInterval + QVariantAnimation::KeyValues::const_iterator itStart = qLowerBound(keyValues.constBegin(), + keyValues.constEnd(), + qMakePair(progress, QVariant()), + animationValueLessThan); + QVariantAnimation::KeyValues::const_iterator itEnd = itStart; + + // If we are at the end we should continue to use the last keyValues in case of extrapolation (progress > 1.0). + // This is because the easing function can return a value slightly outside the range [0, 1] + if (itStart != keyValues.constEnd()) { + // this can't happen because we always prepend the default start value there + if (itStart == keyValues.constBegin()) { + ++itEnd; + } else { + --itStart; + } + + // update all the values of the currentInterval + currentInterval.start = *itStart; + currentInterval.end = *itEnd; + } + } + setCurrentValueForProgress(progress); +} + +void QVariantAnimationPrivate::setCurrentValueForProgress(const qreal progress) +{ + Q_Q(QVariantAnimation); + + const qreal startProgress = currentInterval.start.first; + const qreal endProgress = currentInterval.end.first; + const qreal localProgress = (progress - startProgress) / (endProgress - startProgress); + + QVariant ret = q->interpolated(currentInterval.start.second, + currentInterval.end.second, + localProgress); + qSwap(currentValue, ret); + q->updateCurrentValue(currentValue); + if ((connectedSignals & changedSignalMask) && currentValue != ret) { + //the value has changed + emit q->valueChanged(currentValue); + } +} + +QVariant QVariantAnimationPrivate::valueAt(qreal step) const +{ + QVariantAnimation::KeyValues::const_iterator result = + qBinaryFind(keyValues.begin(), keyValues.end(), qMakePair(step, QVariant()), animationValueLessThan); + if (result != keyValues.constEnd()) + return result->second; + + return QVariant(); +} + +void QVariantAnimationPrivate::setValueAt(qreal step, const QVariant &value) +{ + if (step < qreal(0.0) || step > qreal(1.0)) { + qWarning("QVariantAnimation::setValueAt: invalid step = %f", step); + return; + } + + QVariantAnimation::KeyValue pair(step, value); + + QVariantAnimation::KeyValues::iterator result = qLowerBound(keyValues.begin(), keyValues.end(), pair, animationValueLessThan); + if (result == keyValues.end() || result->first != step) { + keyValues.insert(result, pair); + } else { + if (value.isValid()) + result->second = value; // replaces the previous value + else if (step == 0 && !hasStartValue && defaultStartValue.isValid()) + result->second = defaultStartValue; // resets to the default start value + else + keyValues.erase(result); // removes the previous value + } + + recalculateCurrentInterval(/*force=*/true); +} + +void QVariantAnimationPrivate::setDefaultStartValue(const QVariant &value) +{ + defaultStartValue = value; + if (!hasStartValue) + setValueAt(0, value); +} + +/*! + Construct a QVariantAnimation object. \a parent is passed to QAbstractAnimation's + constructor. +*/ +QVariantAnimation::QVariantAnimation(QObject *parent) : QAbstractAnimation(*new QVariantAnimationPrivate, parent) +{ + d_func()->init(); +} + +/*! + \internal +*/ +QVariantAnimation::QVariantAnimation(QVariantAnimationPrivate &dd, QObject *parent) : QAbstractAnimation(dd, parent) +{ + d_func()->init(); +} + +/*! + Destroys the animation. +*/ +QVariantAnimation::~QVariantAnimation() +{ +} + +/*! + \property QVariantAnimation::easingCurve + \brief the easing curve of the animation + + This property defines the easing curve of the animation. By + default, a linear easing curve is used, resulting in linear + interpolation. Other curves are provided, for instance, + QEasingCurve::InCirc, which provides a circular entry curve. + Another example is QEasingCurve::InOutElastic, which provides an + elastic effect on the values of the interpolated variant. + + The easing curve is used with the interpolator, the interpolated() + virtual function, the animation's duration, and iterationCount, to + control how the current value changes as the animation progresses. +*/ +QEasingCurve QVariantAnimation::easingCurve() const +{ + Q_D(const QVariantAnimation); + return d->easing; +} + +void QVariantAnimation::setEasingCurve(const QEasingCurve &easing) +{ + Q_D(QVariantAnimation); + d->easing = easing; + d->recalculateCurrentInterval(); +} + +Q_GLOBAL_STATIC(QVector, registeredInterpolators) +Q_GLOBAL_STATIC(QReadWriteLock, registeredInterpolatorsLock) + +/*! + \fn void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) + \relates QVariantAnimation + \threadsafe + + Registers a custom interpolator \a func for the template type \c{T}. + The interpolator has to be registered before the animation is constructed. + To unregister (and use the default interpolator) set \a func to 0. + */ + +/*! + \internal + \typedef QVariantAnimation::Interpolator + + This is a typedef for a pointer to a function with the following + signature: + \code + QVariant myInterpolator(const QVariant &from, const QVariant &to, qreal progress); + \endcode + +*/ + +/*! \internal + * Registers a custom interpolator \a func for the specific \a interpolationType. + * The interpolator has to be registered before the animation is constructed. + * To unregister (and use the default interpolator) set \a func to 0. + */ +void QVariantAnimation::registerInterpolator(QVariantAnimation::Interpolator func, int interpolationType) +{ + // will override any existing interpolators + QWriteLocker locker(registeredInterpolatorsLock()); + if (int(interpolationType) >= registeredInterpolators()->count()) + registeredInterpolators()->resize(int(interpolationType) + 1); + registeredInterpolators()->replace(interpolationType, func); +} + + +template static inline QVariantAnimation::Interpolator castToInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) +{ + return reinterpret_cast(func); +} + +QVariantAnimation::Interpolator QVariantAnimationPrivate::getInterpolator(int interpolationType) +{ + QReadLocker locker(registeredInterpolatorsLock()); + QVariantAnimation::Interpolator ret = 0; + if (interpolationType < registeredInterpolators()->count()) { + ret = registeredInterpolators()->at(interpolationType); + if (ret) return ret; + } + + switch(interpolationType) + { + case QMetaType::Int: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::Double: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::Float: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::QLine: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::QLineF: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::QPoint: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::QPointF: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::QSize: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::QSizeF: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::QRect: + return castToInterpolator(_q_interpolateVariant); + case QMetaType::QRectF: + return castToInterpolator(_q_interpolateVariant); + default: + return 0; //this type is not handled + } +} + +/*! + \property QVariantAnimation::duration + \brief the duration of the animation + + This property describes the duration in milliseconds of the + animation. The default duration is 250 milliseconds. + + \sa QAbstractAnimation::duration() + */ +int QVariantAnimation::duration() const +{ + Q_D(const QVariantAnimation); + return d->duration; +} + +void QVariantAnimation::setDuration(int msecs) +{ + Q_D(QVariantAnimation); + if (msecs < 0) { + qWarning("QVariantAnimation::setDuration: cannot set a negative duration"); + return; + } + if (d->duration == msecs) + return; + d->duration = msecs; + d->recalculateCurrentInterval(); +} + +/*! + \property QVariantAnimation::startValue + \brief the optional start value of the animation + + This property describes the optional start value of the animation. If + omitted, or if a null QVariant is assigned as the start value, the + animation will use the current position of the end when the animation + is started. + + \sa endValue +*/ +QVariant QVariantAnimation::startValue() const +{ + return keyValueAt(0); +} + +void QVariantAnimation::setStartValue(const QVariant &value) +{ + setKeyValueAt(0, value); +} + +/*! + \property QVariantAnimation::endValue + \brief the end value of the animation + + This property describes the end value of the animation. + + \sa startValue + */ +QVariant QVariantAnimation::endValue() const +{ + return keyValueAt(1); +} + +void QVariantAnimation::setEndValue(const QVariant &value) +{ + setKeyValueAt(1, value); +} + + +/*! + Returns the key frame value for the given \a step. The given \a step + must be in the range 0 to 1. If there is no KeyValue for \a step, + it returns an invalid QVariant. + + \sa keyValues(), setKeyValueAt() +*/ +QVariant QVariantAnimation::keyValueAt(qreal step) const +{ + Q_D(const QVariantAnimation); + if (step == 0 && !d->hasStartValue) + return QVariant(); //special case where we don't have an explicit startValue + + return d->valueAt(step); +} + +/*! + \typedef QVariantAnimation::KeyValue + + This is a typedef for QPair. +*/ +/*! + \typedef QVariantAnimation::KeyValues + + This is a typedef for QVector +*/ + +/*! + Creates a key frame at the given \a step with the given \a value. + The given \a step must be in the range 0 to 1. + + \sa setKeyValues(), keyValueAt() +*/ +void QVariantAnimation::setKeyValueAt(qreal step, const QVariant &value) +{ + Q_D(QVariantAnimation); + if (step == 0) + d->hasStartValue = value.isValid(); + d->setValueAt(step, value); +} + +/*! + Returns the key frames of this animation. + + \sa keyValueAt(), setKeyValues() +*/ +QVariantAnimation::KeyValues QVariantAnimation::keyValues() const +{ + Q_D(const QVariantAnimation); + QVariantAnimation::KeyValues ret = d->keyValues; + //in case we added the default start value, we remove it + if (!d->hasStartValue && !ret.isEmpty() && ret.at(0).first == 0) + ret.remove(0); + return ret; +} + +/*! + Replaces the current set of key frames with the given \a keyValues. + the step of the key frames must be in the range 0 to 1. + + \sa keyValues(), keyValueAt() +*/ +void QVariantAnimation::setKeyValues(const KeyValues &keyValues) +{ + Q_D(QVariantAnimation); + d->keyValues = keyValues; + qSort(d->keyValues.begin(), d->keyValues.end(), animationValueLessThan); + d->hasStartValue = !d->keyValues.isEmpty() && d->keyValues.at(0).first == 0; + d->recalculateCurrentInterval(/*force=*/true); +} + +/*! + \property QVariantAnimation::currentValue + \brief the current value of the animation. + + This property describes the current value; an interpolated value + between the \l{startValue}{start value} and the \l{endValue}{end + value}, using the current time for progress. The value itself is + obtained from interpolated(), which is called repeatedly as the + animation is running. + + QVariantAnimation calls the virtual updateCurrentValue() function + when the current value changes. This is particularly useful for + subclasses that need to track updates. For example, + QPropertyAnimation uses this function to animate Qt \l{Qt's + Property System}{properties}. + + \sa startValue, endValue +*/ +QVariant QVariantAnimation::currentValue() const +{ + Q_D(const QVariantAnimation); + if (!d->currentValue.isValid()) + const_cast(d)->recalculateCurrentInterval(); + return d->currentValue; +} + +/*! + \reimp + */ +bool QVariantAnimation::event(QEvent *event) +{ + return QAbstractAnimation::event(event); +} + +/*! + \reimp +*/ +void QVariantAnimation::updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) +{ + Q_UNUSED(oldState); + Q_UNUSED(newState); +} + +/*! + + This virtual function returns the linear interpolation between + variants \a from and \a to, at \a progress, usually a value + between 0 and 1. You can reimplement this function in a subclass + of QVariantAnimation to provide your own interpolation algorithm. + + Note that in order for the interpolation to work with a + QEasingCurve that return a value smaller than 0 or larger than 1 + (such as QEasingCurve::InBack) you should make sure that it can + extrapolate. If the semantic of the datatype does not allow + extrapolation this function should handle that gracefully. + + You should call the QVariantAnimation implementation of this + function if you want your class to handle the types already + supported by Qt (see class QVariantAnimation description for a + list of supported types). + + \sa QEasingCurve + */ +QVariant QVariantAnimation::interpolated(const QVariant &from, const QVariant &to, qreal progress) const +{ + Q_D(const QVariantAnimation); + if (d->interpolator == 0) { + if (from.userType() == to.userType()) + d->interpolator = QVariantAnimationPrivate::getInterpolator(from.userType()); + if (d->interpolator == 0) //no interpolator found + return QVariant(); + } + + return d->interpolator(from.constData(), to.constData(), progress); +} + +/*! + \reimp + */ +void QVariantAnimation::updateCurrentTime(int msecs) +{ + Q_D(QVariantAnimation); + Q_UNUSED(msecs); + d->recalculateCurrentInterval(); +} + +QT_END_NAMESPACE + +#include "moc_qvariantanimation.cpp" + +#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qvariantanimation.h b/src/corelib/animation/qvariantanimation.h new file mode 100644 index 0000000..5b90930 --- /dev/null +++ b/src/corelib/animation/qvariantanimation.h @@ -0,0 +1,130 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QANIMATION_H +#define QANIMATION_H + +#include +#include +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +#ifndef QT_NO_ANIMATION + +class QVariantAnimationPrivate; +class Q_CORE_EXPORT QVariantAnimation : public QAbstractAnimation +{ + Q_OBJECT + Q_PROPERTY(QVariant startValue READ startValue WRITE setStartValue) + Q_PROPERTY(QVariant endValue READ endValue WRITE setEndValue) + Q_PROPERTY(QVariant currentValue READ currentValue NOTIFY currentValueChanged) + Q_PROPERTY(int duration READ duration WRITE setDuration) + Q_PROPERTY(QEasingCurve easingCurve READ easingCurve WRITE setEasingCurve) + +public: + typedef QPair KeyValue; + typedef QVector KeyValues; + + QVariantAnimation(QObject *parent = 0); + ~QVariantAnimation(); + + QVariant startValue() const; + void setStartValue(const QVariant &value); + + QVariant endValue() const; + void setEndValue(const QVariant &value); + + QVariant keyValueAt(qreal step) const; + void setKeyValueAt(qreal step, const QVariant &value); + + KeyValues keyValues() const; + void setKeyValues(const KeyValues &values); + + QVariant currentValue() const; + + int duration() const; + void setDuration(int msecs); + + QEasingCurve easingCurve() const; + void setEasingCurve(const QEasingCurve &easing); + + typedef QVariant (*Interpolator)(const void *from, const void *to, qreal progress); + +Q_SIGNALS: + void valueChanged(const QVariant &value); + +protected: + QVariantAnimation(QVariantAnimationPrivate &dd, QObject *parent = 0); + bool event(QEvent *event); + + void updateCurrentTime(int msecs); + void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); + + virtual void updateCurrentValue(const QVariant &value) = 0; + virtual QVariant interpolated(const QVariant &from, const QVariant &to, qreal progress) const; + +private: + template friend void qRegisterAnimationInterpolator(QVariant (*func)(const T &, const T &, qreal)); + static void registerInterpolator(Interpolator func, int interpolationType); + + Q_DISABLE_COPY(QVariantAnimation) + Q_DECLARE_PRIVATE(QVariantAnimation) +}; + +template +static void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) { + QVariantAnimation::registerInterpolator(reinterpret_cast(func), qMetaTypeId()); +} + +#endif //QT_NO_ANIMATION + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif //QANIMATION_H diff --git a/src/corelib/animation/qvariantanimation_p.h b/src/corelib/animation/qvariantanimation_p.h new file mode 100644 index 0000000..0d296db --- /dev/null +++ b/src/corelib/animation/qvariantanimation_p.h @@ -0,0 +1,130 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QANIMATION_P_H +#define QANIMATION_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of QIODevice. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qvariantanimation.h" +#include +#include +#include + +#include "qabstractanimation_p.h" + +QT_BEGIN_NAMESPACE + +class QVariantAnimationPrivate : public QAbstractAnimationPrivate +{ + Q_DECLARE_PUBLIC(QVariantAnimation) +public: + + QVariantAnimationPrivate() : duration(250), hasStartValue(false) + { + } + + void init() + { + //we keep the mask so that we emit valueChanged only when needed (for performance reasons) + changedSignalMask = (1 << q_func()->metaObject()->indexOfSignal("valueChanged(QVariant)")); + currentInterval.start.first = currentInterval.end.first = 2; //will force the initial refresh + interpolator = 0; + } + + static QVariantAnimationPrivate *get(QVariantAnimation *q) + { + return q->d_func(); + } + + void setDefaultStartValue(const QVariant &value); + + int duration; + QEasingCurve easing; + + QVariantAnimation::KeyValues keyValues; + QVariant currentValue; + QVariant defaultStartValue; + bool hasStartValue; + + //this is used to keep track of the KeyValue interval in which we currently are + struct + { + QVariantAnimation::KeyValue start, end; + } currentInterval; + + mutable QVariantAnimation::Interpolator interpolator; + + quint32 changedSignalMask; + + void setCurrentValueForProgress(const qreal progress); + void recalculateCurrentInterval(bool force=false); + void setValueAt(qreal, const QVariant &); + QVariant valueAt(qreal step) const; + void convertValues(int t); + + static QVariantAnimation::Interpolator getInterpolator(int interpolationType); +}; + +//this should make the interpolation faster +template inline T _q_interpolate(const T &f, const T &t, qreal progress) +{ + return T(f + (t - f) * progress); +} + +template inline QVariant _q_interpolateVariant(const T &from, const T &to, qreal progress) +{ + return _q_interpolate(from, to, progress); +} + + +QT_END_NAMESPACE + +#endif //QANIMATION_P_H diff --git a/src/corelib/corelib.pro b/src/corelib/corelib.pro index f99d57f..db51d43 100644 --- a/src/corelib/corelib.pro +++ b/src/corelib/corelib.pro @@ -5,6 +5,7 @@ DEFINES += QT_BUILD_CORE_LIB QT_NO_USING_NAMESPACE win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x67000000 include(../qbase.pri) +include(animation/animation.pri) include(arch/arch.pri) include(concurrent/concurrent.pri) include(global/global.pri) @@ -14,6 +15,7 @@ include(io/io.pri) include(plugin/plugin.pri) include(kernel/kernel.pri) include(codecs/codecs.pri) +include(statemachine/statemachine.pri) include(xml/xml.pri) mac|darwin:LIBS += -framework ApplicationServices diff --git a/src/corelib/kernel/kernel.pri b/src/corelib/kernel/kernel.pri index 68649a6..ecef555 100644 --- a/src/corelib/kernel/kernel.pri +++ b/src/corelib/kernel/kernel.pri @@ -12,7 +12,7 @@ HEADERS += \ kernel/qcoreevent.h \ kernel/qmetaobject.h \ kernel/qmetatype.h \ - kernel/qmimedata.h \ + kernel/qmimedata.h \ kernel/qobject.h \ kernel/qobjectdefs.h \ kernel/qsignalmapper.h \ @@ -27,8 +27,8 @@ HEADERS += \ kernel/qvariant_p.h \ kernel/qmetaobject_p.h \ kernel/qobject_p.h \ - kernel/qcoreglobaldata_p.h \ - kernel/qsharedmemory.h \ + kernel/qcoreglobaldata_p.h \ + kernel/qsharedmemory.h \ kernel/qsharedmemory_p.h \ kernel/qsystemsemaphore.h \ kernel/qsystemsemaphore_p.h \ @@ -43,7 +43,7 @@ SOURCES += \ kernel/qcoreevent.cpp \ kernel/qmetaobject.cpp \ kernel/qmetatype.cpp \ - kernel/qmimedata.cpp \ + kernel/qmimedata.cpp \ kernel/qobject.cpp \ kernel/qobjectcleanuphandler.cpp \ kernel/qsignalmapper.cpp \ diff --git a/src/corelib/kernel/qcoreevent.cpp b/src/corelib/kernel/qcoreevent.cpp index 11a2d3c..d6b0174 100644 --- a/src/corelib/kernel/qcoreevent.cpp +++ b/src/corelib/kernel/qcoreevent.cpp @@ -264,6 +264,8 @@ QT_BEGIN_NAMESPACE \omitvalue NetworkReplyUpdated \omitvalue FutureCallOut \omitvalue CocoaRequestModal + \omitvalue Wrapped + \omitvalue Signal */ /*! diff --git a/src/corelib/kernel/qcoreevent.h b/src/corelib/kernel/qcoreevent.h index fa472e6..18188a8 100644 --- a/src/corelib/kernel/qcoreevent.h +++ b/src/corelib/kernel/qcoreevent.h @@ -44,6 +44,7 @@ #include #include +#include QT_BEGIN_HEADER @@ -54,7 +55,9 @@ QT_MODULE(Core) class QEventPrivate; class Q_CORE_EXPORT QEvent // event base class { + Q_GADGET QDOC_PROPERTY(bool accepted READ isAccepted WRITE setAccepted) + Q_ENUMS(Type) public: enum Type { /* @@ -266,7 +269,10 @@ public: CocoaRequestModal = 190, // Internal for requesting an application modal Cocoa Window MacGLClearDrawable = 191, // Internal Cocoa, the window has changed, so we must clear - // 512 reserved for Qt Jambi's MetaCall event + Signal = 192, + Wrapped = 193, + + // 512 reserved for Qt Jambi's MetaCall event // 513 reserved for Qt Jambi's DeleteOnMainThread event User = 1000, // first user event id diff --git a/src/corelib/statemachine/qabstractstate.cpp b/src/corelib/statemachine/qabstractstate.cpp new file mode 100644 index 0000000..942722f --- /dev/null +++ b/src/corelib/statemachine/qabstractstate.cpp @@ -0,0 +1,202 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qabstractstate.h" +#include "qabstractstate_p.h" +#include "qstate.h" +#include "qstate_p.h" +#include "qstatemachine.h" +#include "qstatemachine_p.h" + +QT_BEGIN_NAMESPACE + +/*! + \class QAbstractState + + \brief The QAbstractState class is the base class of states of a QStateMachine. + + \since 4.6 + \ingroup statemachine + + The QAbstractState class is the abstract base class of states that are part + of a QStateMachine. It defines the interface that all state objects have in + common. QAbstractState is part of \l{The State Machine Framework}. + + The entered() signal is emitted when the state has been entered. The + exited() signal is emitted when the state has been exited. + + The parentState() function returns the state's parent state. The machine() + function returns the state machine that the state is part of. + + \section1 Subclassing + + The onEntry() function is called when the state is entered; reimplement this + function to perform custom processing when the state is entered. + + The onExit() function is called when the state is exited; reimplement this + function to perform custom processing when the state is exited. +*/ + +QAbstractStatePrivate::QAbstractStatePrivate() +{ +} + +QAbstractStatePrivate *QAbstractStatePrivate::get(QAbstractState *q) +{ + return q->d_func(); +} + +QStateMachine *QAbstractStatePrivate::machine() const +{ + Q_Q(const QAbstractState); + QObject *par = q->parent(); + while (par != 0) { + if (QStateMachine *mach = qobject_cast(par)) + return mach; + par = par->parent(); + } + return 0; +} + +void QAbstractStatePrivate::callOnEntry(QEvent *e) +{ + Q_Q(QAbstractState); + q->onEntry(e); +} + +void QAbstractStatePrivate::callOnExit(QEvent *e) +{ + Q_Q(QAbstractState); + q->onExit(e); +} + +void QAbstractStatePrivate::emitEntered() +{ + Q_Q(QAbstractState); + emit q->entered(); +} + +void QAbstractStatePrivate::emitExited() +{ + Q_Q(QAbstractState); + emit q->exited(); +} + +/*! + Constructs a new state with the given \a parent state. +*/ +QAbstractState::QAbstractState(QState *parent) + : QObject(*new QAbstractStatePrivate, parent) +{ +} + +/*! + \internal +*/ +QAbstractState::QAbstractState(QAbstractStatePrivate &dd, QState *parent) + : QObject(dd, parent) +{ +} + +/*! + Destroys this state. +*/ +QAbstractState::~QAbstractState() +{ +} + +/*! + Returns this state's parent state, or 0 if the state has no parent state. +*/ +QState *QAbstractState::parentState() const +{ + return qobject_cast(parent()); +} + +/*! + Returns the state machine that this state is part of, or 0 if the state is + not part of a state machine. +*/ +QStateMachine *QAbstractState::machine() const +{ + Q_D(const QAbstractState); + return d->machine(); +} + +/*! + \fn QAbstractState::onExit(QEvent *event) + + This function is called when the state is exited. The given \a event is what + caused the state to be exited. Reimplement this function to perform custom + processing when the state is exited. +*/ + +/*! + \fn QAbstractState::onEntry(QEvent *event) + + This function is called when the state is entered. The given \a event is + what caused the state to be entered. Reimplement this function to perform + custom processing when the state is entered. +*/ + +/*! + \fn QAbstractState::entered() + + This signal is emitted when the state has been entered (after onEntry() has + been called). +*/ + +/*! + \fn QAbstractState::exited() + + This signal is emitted when the state has been exited (after onExit() has + been called). +*/ + +/*! + \reimp +*/ +bool QAbstractState::event(QEvent *e) +{ + return QObject::event(e); +} + +QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qabstractstate.h b/src/corelib/statemachine/qabstractstate.h new file mode 100644 index 0000000..d0ebb52 --- /dev/null +++ b/src/corelib/statemachine/qabstractstate.h @@ -0,0 +1,90 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QABSTRACTSTATE_H +#define QABSTRACTSTATE_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QState; +class QStateMachine; + +class QAbstractStatePrivate; +class Q_CORE_EXPORT QAbstractState : public QObject +{ + Q_OBJECT +public: + ~QAbstractState(); + + QState *parentState() const; + QStateMachine *machine() const; + +Q_SIGNALS: + void entered(); + void exited(); + +protected: + QAbstractState(QState *parent = 0); + + virtual void onEntry(QEvent *event) = 0; + virtual void onExit(QEvent *event) = 0; + + bool event(QEvent *e); + +protected: + QAbstractState(QAbstractStatePrivate &dd, QState *parent); + +private: + Q_DISABLE_COPY(QAbstractState) + Q_DECLARE_PRIVATE(QAbstractState) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qabstractstate_p.h b/src/corelib/statemachine/qabstractstate_p.h new file mode 100644 index 0000000..2aad47e --- /dev/null +++ b/src/corelib/statemachine/qabstractstate_p.h @@ -0,0 +1,84 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QABSTRACTSTATE_P_H +#define QABSTRACTSTATE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +class QStateMachine; + +class QAbstractState; +class Q_CORE_EXPORT QAbstractStatePrivate + : public QObjectPrivate +{ + Q_DECLARE_PUBLIC(QAbstractState) + +public: + QAbstractStatePrivate(); + + static QAbstractStatePrivate *get(QAbstractState *q); + + QStateMachine *machine() const; + + void callOnEntry(QEvent *e); + void callOnExit(QEvent *e); + + void emitEntered(); + void emitExited(); +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/statemachine/qabstracttransition.cpp b/src/corelib/statemachine/qabstracttransition.cpp new file mode 100644 index 0000000..dfcafeb --- /dev/null +++ b/src/corelib/statemachine/qabstracttransition.cpp @@ -0,0 +1,342 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qabstracttransition.h" +#include "qabstracttransition_p.h" +#include "qabstractstate.h" +#include "qstate.h" +#include "qstatemachine.h" + +QT_BEGIN_NAMESPACE + +/*! + \class QAbstractTransition + + \brief The QAbstractTransition class is the base class of transitions between QAbstractState objects. + + \since 4.6 + \ingroup statemachine + + The QAbstractTransition class is the abstract base class of transitions + between states (QAbstractState objects) of a + QStateMachine. QAbstractTransition is part of \l{The State Machine + Framework}. + + The sourceState() function returns the source of the transition. The + targetStates() function returns the targets of the transition. The machine() + function returns the state machine that the transition is part of. + + Transitions can cause animations to be played. Use the addAnimation() + function to add an animation to the transition. + + \section1 Subclassing + + The eventTest() function is called by the state machine to determine whether + an event should trigger the transition. In your reimplementation you + typically check the event type and cast the event object to the proper type, + and check that one or more properties of the event meet your criteria. + + The onTransition() function is called when the transition is triggered; + reimplement this function to perform custom processing for the transition. +*/ + +/*! + \property QAbstractTransition::sourceState + + \brief the source state (parent) of this transition +*/ + +/*! + \property QAbstractTransition::targetState + + \brief the target state of this transition +*/ + +/*! + \property QAbstractTransition::targetStates + + \brief the target states of this transition + + If multiple states are specified, all must be descendants of the same + parallel group state. +*/ + +QAbstractTransitionPrivate::QAbstractTransitionPrivate() +{ +} + +QAbstractTransitionPrivate *QAbstractTransitionPrivate::get(QAbstractTransition *q) +{ + return q->d_func(); +} + +QStateMachine *QAbstractTransitionPrivate::machine() const +{ + Q_Q(const QAbstractTransition); + QObject *par = q->parent(); + while (par != 0) { + if (QStateMachine *mach = qobject_cast(par)) + return mach; + par = par->parent(); + } + return 0; +} + +bool QAbstractTransitionPrivate::callEventTest(QEvent *e) +{ + Q_Q(QAbstractTransition); + return q->eventTest(e); +} + +void QAbstractTransitionPrivate::callOnTransition(QEvent *e) +{ + Q_Q(QAbstractTransition); + q->onTransition(e); +} + +QState *QAbstractTransitionPrivate::sourceState() const +{ + Q_Q(const QAbstractTransition); + return qobject_cast(q->parent()); +} + +/*! + Constructs a new QAbstractTransition object with the given \a sourceState. +*/ +QAbstractTransition::QAbstractTransition(QState *sourceState) + : QObject(*new QAbstractTransitionPrivate, sourceState) +{ +} + +/*! + Constructs a new QAbstractTransition object with the given \a targets and \a + sourceState. +*/ +QAbstractTransition::QAbstractTransition(const QList &targets, + QState *sourceState) + : QObject(*new QAbstractTransitionPrivate, sourceState) +{ + setTargetStates(targets); +} + +/*! + \internal +*/ +QAbstractTransition::QAbstractTransition(QAbstractTransitionPrivate &dd, + QState *parent) + : QObject(dd, parent) +{ +} + +/*! + \internal +*/ +QAbstractTransition::QAbstractTransition(QAbstractTransitionPrivate &dd, + const QList &targets, + QState *parent) + : QObject(dd, parent) +{ + setTargetStates(targets); +} + +/*! + Destroys this transition. +*/ +QAbstractTransition::~QAbstractTransition() +{ +} + +/*! + Returns the source state of this transition, or 0 if this transition has no + source state. +*/ +QState *QAbstractTransition::sourceState() const +{ + Q_D(const QAbstractTransition); + return d->sourceState(); +} + +/*! + Returns the target state of this transition, or 0 if the transition has no + target. +*/ +QAbstractState *QAbstractTransition::targetState() const +{ + Q_D(const QAbstractTransition); + if (d->targetStates.isEmpty()) + return 0; + return d->targetStates.first(); +} + +/*! + Sets the \a target state of this transition. +*/ +void QAbstractTransition::setTargetState(QAbstractState* target) +{ + Q_D(QAbstractTransition); + if (!target) + d->targetStates.clear(); + else + setTargetStates(QList() << target); +} + +/*! + Returns the target states of this transition, or an empty list if this + transition has no target states. +*/ +QList QAbstractTransition::targetStates() const +{ + Q_D(const QAbstractTransition); + QList result; + for (int i = 0; i < d->targetStates.size(); ++i) { + QAbstractState *target = d->targetStates.at(i); + if (target) + result.append(target); + } + return result; +} + +/*! + Sets the target states of this transition to be the given \a targets. +*/ +void QAbstractTransition::setTargetStates(const QList &targets) +{ + Q_D(QAbstractTransition); + + for (int i=0; imachine() != 0 && target->machine()->rootState() == target) { + qWarning("QAbstractTransition::setTargetStates: root state cannot be target of transition"); + return; + } + } + + d->targetStates.clear(); + for (int i = 0; i < targets.size(); ++i) + d->targetStates.append(targets.at(i)); +} + +/*! + Returns the state machine that this transition is part of, or 0 if the + transition is not part of a state machine. +*/ +QStateMachine *QAbstractTransition::machine() const +{ + Q_D(const QAbstractTransition); + return d->machine(); +} + +#ifndef QT_NO_ANIMATION + +/*! + Adds the given \a animation to this transition. + The transition does not take ownership of the animation. + + \sa removeAnimation(), animations() +*/ +void QAbstractTransition::addAnimation(QAbstractAnimation *animation) +{ + Q_D(QAbstractTransition); + if (!animation) { + qWarning("QAbstractTransition::addAnimation: cannot add null animation"); + return; + } + d->animations.append(animation); +} + +/*! + Removes the given \a animation from this transition. + + \sa addAnimation() +*/ +void QAbstractTransition::removeAnimation(QAbstractAnimation *animation) +{ + Q_D(QAbstractTransition); + if (!animation) { + qWarning("QAbstractTransition::removeAnimation: cannot remove null animation"); + return; + } + d->animations.removeOne(animation); +} + +/*! + Returns the list of animations associated with this transition, or an empty + list if it has no animations. + + \sa addAnimation() +*/ +QList QAbstractTransition::animations() const +{ + Q_D(const QAbstractTransition); + return d->animations; +} + +#endif + +/*! + \fn QAbstractTransition::eventTest(QEvent *event) + + This function is called to determine whether the given \a event should cause + this transition to trigger. Reimplement this function and return true if the + event should trigger the transition, otherwise return false. +*/ + +/*! + \fn QAbstractTransition::onTransition(QEvent *event) + + This function is called when the transition is triggered. The given \a event + is what caused the transition to trigger. Reimplement this function to + perform custom processing when the transition is triggered. +*/ + +/*! + \reimp +*/ +bool QAbstractTransition::event(QEvent *e) +{ + return QObject::event(e); +} + +QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qabstracttransition.h b/src/corelib/statemachine/qabstracttransition.h new file mode 100644 index 0000000..c63d55a --- /dev/null +++ b/src/corelib/statemachine/qabstracttransition.h @@ -0,0 +1,111 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QABSTRACTTRANSITION_H +#define QABSTRACTTRANSITION_H + +#include + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QEvent; +class QAbstractState; +class QState; +class QStateMachine; + +#ifndef QT_NO_ANIMATION +class QAbstractAnimation; +#endif + +class QAbstractTransitionPrivate; +class Q_CORE_EXPORT QAbstractTransition : public QObject +{ + Q_OBJECT + Q_PROPERTY(QState* sourceState READ sourceState) + Q_PROPERTY(QAbstractState* targetState READ targetState WRITE setTargetState) + Q_PROPERTY(QList targetStates READ targetStates WRITE setTargetStates) +public: + QAbstractTransition(QState *sourceState = 0); + QAbstractTransition(const QList &targets, QState *sourceState = 0); + virtual ~QAbstractTransition(); + + QState *sourceState() const; + QAbstractState *targetState() const; + void setTargetState(QAbstractState* target); + QList targetStates() const; + void setTargetStates(const QList &targets); + + QStateMachine *machine() const; + +#ifndef QT_NO_ANIMATION + void addAnimation(QAbstractAnimation *animation); + void removeAnimation(QAbstractAnimation *animation); + QList animations() const; +#endif + +protected: + virtual bool eventTest(QEvent *event) = 0; + + virtual void onTransition(QEvent *event) = 0; + + bool event(QEvent *e); + +protected: + QAbstractTransition(QAbstractTransitionPrivate &dd, QState *parent); + QAbstractTransition(QAbstractTransitionPrivate &dd, + const QList &targets, QState *parent); + +private: + Q_DISABLE_COPY(QAbstractTransition) + Q_DECLARE_PRIVATE(QAbstractTransition) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qabstracttransition_p.h b/src/corelib/statemachine/qabstracttransition_p.h new file mode 100644 index 0000000..f067984 --- /dev/null +++ b/src/corelib/statemachine/qabstracttransition_p.h @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QABSTRACTTRANSITION_P_H +#define QABSTRACTTRANSITION_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +#include +#include + +QT_BEGIN_NAMESPACE + +class QAbstractState; +class QState; +class QStateMachine; + +class QAbstractTransition; +class Q_CORE_EXPORT QAbstractTransitionPrivate + : public QObjectPrivate +{ + Q_DECLARE_PUBLIC(QAbstractTransition) +public: + QAbstractTransitionPrivate(); + + static QAbstractTransitionPrivate *get(QAbstractTransition *q); + + bool callEventTest(QEvent *e); + void callOnTransition(QEvent *e); + QState *sourceState() const; + QStateMachine *machine() const; + + QList > targetStates; + +#ifndef QT_NO_ANIMATION + QList animations; +#endif +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/statemachine/qeventtransition.cpp b/src/corelib/statemachine/qeventtransition.cpp new file mode 100644 index 0000000..74eb577 --- /dev/null +++ b/src/corelib/statemachine/qeventtransition.cpp @@ -0,0 +1,282 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qeventtransition.h" +#include "qeventtransition_p.h" +#include "qwrappedevent.h" +#include "qstate.h" +#include "qstate_p.h" +#include "qstatemachine.h" +#include "qstatemachine_p.h" +#include + +QT_BEGIN_NAMESPACE + +/*! + \class QEventTransition + + \brief The QEventTransition class provides a QObject-specific transition for Qt events. + + \since 4.6 + \ingroup statemachine + + A QEventTransition object binds an event to a particular QObject. + QEventTransition is part of \l{The State Machine Framework}. + + Example: + + \code + QPushButton *button = ...; + QState *s1 = ...; + QState *s2 = ...; + // If in s1 and the button receives an Enter event, transition to s2 + QEventTransition *enterTransition = new QEventTransition(button, QEvent::Enter); + enterTransition->setTargetState(s2); + s1->addTransition(enterTransition); + // If in s2 and the button receives an Exit event, transition back to s1 + QEventTransition *leaveTransition = new QEventTransition(button, QEvent::Leave); + leaveTransition->setTargetState(s1); + s2->addTransition(leaveTransition); + \endcode + + \section1 Subclassing + + When reimplementing the eventTest() function, you should first call the base + implementation to verify that the event is a QWrappedEvent for the proper + object and event type. You may then cast the event to a QWrappedEvent and + get the original event by calling QWrappedEvent::event(), and perform + additional checks on that object. + + \sa QState::addTransition() +*/ + +/*! + \property QEventTransition::eventObject + + \brief the event source that this event transition is associated with +*/ + +/*! + \property QEventTransition::eventType + + \brief the type of event that this event transition is associated with +*/ +QEventTransitionPrivate::QEventTransitionPrivate() +{ + object = 0; + eventType = QEvent::None; + registered = false; +} + +QEventTransitionPrivate *QEventTransitionPrivate::get(QEventTransition *q) +{ + return q->d_func(); +} + +void QEventTransitionPrivate::invalidate() +{ + Q_Q(QEventTransition); + if (registered) { + QState *source = sourceState(); + QStatePrivate *source_d = QStatePrivate::get(source); + QStateMachinePrivate *mach = QStateMachinePrivate::get(source_d->machine()); + if (mach) { + mach->unregisterEventTransition(q); + if (mach->configuration.contains(source)) + mach->registerEventTransition(q); + } + } +} + +/*! + Constructs a new QEventTransition object with the given \a sourceState. +*/ +QEventTransition::QEventTransition(QState *sourceState) + : QAbstractTransition(*new QEventTransitionPrivate, sourceState) +{ +} + +/*! + Constructs a new QEventTransition object associated with events of the given + \a type for the given \a object, and with the given \a sourceState. +*/ +QEventTransition::QEventTransition(QObject *object, QEvent::Type type, + QState *sourceState) + : QAbstractTransition(*new QEventTransitionPrivate, sourceState) +{ + Q_D(QEventTransition); + d->registered = false; + d->object = object; + d->eventType = type; +} + +/*! + Constructs a new QEventTransition object associated with events of the given + \a type for the given \a object. The transition has the given \a targets and + \a sourceState. +*/ +QEventTransition::QEventTransition(QObject *object, QEvent::Type type, + const QList &targets, + QState *sourceState) + : QAbstractTransition(*new QEventTransitionPrivate, targets, sourceState) +{ + Q_D(QEventTransition); + d->registered = false; + d->object = object; + d->eventType = type; +} + +/*! + \internal +*/ +QEventTransition::QEventTransition(QEventTransitionPrivate &dd, QState *parent) + : QAbstractTransition(dd, parent) +{ +} + +/*! + \internal +*/ +QEventTransition::QEventTransition(QEventTransitionPrivate &dd, QObject *object, + QEvent::Type type, QState *parent) + : QAbstractTransition(dd, parent) +{ + Q_D(QEventTransition); + d->registered = false; + d->object = object; + d->eventType = type; +} + +/*! + \internal +*/ +QEventTransition::QEventTransition(QEventTransitionPrivate &dd, QObject *object, + QEvent::Type type, const QList &targets, + QState *parent) + : QAbstractTransition(dd, targets, parent) +{ + Q_D(QEventTransition); + d->registered = false; + d->object = object; + d->eventType = type; +} + +/*! + Destroys this QObject event transition. +*/ +QEventTransition::~QEventTransition() +{ +} + +/*! + Returns the event type that this event transition is associated with. +*/ +QEvent::Type QEventTransition::eventType() const +{ + Q_D(const QEventTransition); + return d->eventType; +} + +/*! + Sets the event \a type that this event transition is associated with. +*/ +void QEventTransition::setEventType(QEvent::Type type) +{ + Q_D(QEventTransition); + if (d->eventType == type) + return; + d->eventType = type; + d->invalidate(); +} + +/*! + Returns the event source associated with this event transition. +*/ +QObject *QEventTransition::eventObject() const +{ + Q_D(const QEventTransition); + return d->object; +} + +/*! + Sets the event source associated with this event transition to be the given + \a object. +*/ +void QEventTransition::setEventObject(QObject *object) +{ + Q_D(QEventTransition); + if (d->object == object) + return; + d->object = object; + d->invalidate(); +} + +/*! + \reimp +*/ +bool QEventTransition::eventTest(QEvent *event) +{ + Q_D(const QEventTransition); + if (event->type() == QEvent::Wrapped) { + QWrappedEvent *we = static_cast(event); + return (we->object() == d->object) + && (we->event()->type() == d->eventType); + } + return false; +} + +/*! + \reimp +*/ +void QEventTransition::onTransition(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \reimp +*/ +bool QEventTransition::event(QEvent *e) +{ + return QAbstractTransition::event(e); +} + +QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qeventtransition.h b/src/corelib/statemachine/qeventtransition.h new file mode 100644 index 0000000..3530bdd --- /dev/null +++ b/src/corelib/statemachine/qeventtransition.h @@ -0,0 +1,96 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QEVENTTRANSITION_H +#define QEVENTTRANSITION_H + +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QEventTransitionPrivate; +class Q_CORE_EXPORT QEventTransition : public QAbstractTransition +{ + Q_OBJECT + Q_PROPERTY(QObject* eventObject READ eventObject WRITE setEventObject) + Q_PROPERTY(QEvent::Type eventType READ eventType WRITE setEventType) +public: + QEventTransition(QState *sourceState = 0); + QEventTransition(QObject *object, QEvent::Type type, QState *sourceState = 0); + QEventTransition(QObject *object, QEvent::Type type, + const QList &targets, QState *sourceState = 0); + ~QEventTransition(); + + QObject *eventObject() const; + void setEventObject(QObject *object); + + QEvent::Type eventType() const; + void setEventType(QEvent::Type type); + +protected: + bool eventTest(QEvent *event); + void onTransition(QEvent *event); + + bool event(QEvent *e); + +protected: + QEventTransition(QEventTransitionPrivate &dd, QState *parent); + QEventTransition(QEventTransitionPrivate &dd, QObject *object, + QEvent::Type type, QState *parent); + QEventTransition(QEventTransitionPrivate &dd, QObject *object, + QEvent::Type type, const QList &targets, + QState *parent); + +private: + Q_DISABLE_COPY(QEventTransition) + Q_DECLARE_PRIVATE(QEventTransition) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qeventtransition_p.h b/src/corelib/statemachine/qeventtransition_p.h new file mode 100644 index 0000000..fca8c0d --- /dev/null +++ b/src/corelib/statemachine/qeventtransition_p.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QEVENTTRANSITION_P_H +#define QEVENTTRANSITION_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qabstracttransition_p.h" + +QT_BEGIN_NAMESPACE + +class QEventTransition; +class Q_CORE_EXPORT QEventTransitionPrivate : public QAbstractTransitionPrivate +{ + Q_DECLARE_PUBLIC(QEventTransition) +public: + QEventTransitionPrivate(); + + static QEventTransitionPrivate *get(QEventTransition *q); + + void invalidate(); + + bool registered; + QObject *object; + QEvent::Type eventType; +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/statemachine/qfinalstate.cpp b/src/corelib/statemachine/qfinalstate.cpp new file mode 100644 index 0000000..0980336 --- /dev/null +++ b/src/corelib/statemachine/qfinalstate.cpp @@ -0,0 +1,134 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qfinalstate.h" +#include "qabstractstate_p.h" + +QT_BEGIN_NAMESPACE + +/*! + \class QFinalState + + \brief The QFinalState class provides a final state. + + \since 4.6 + \ingroup statemachine + + A final state is used to communicate that (part of) a QStateMachine has + finished its work. When a final top-level state is entered, the state + machine's \l{QStateMachine::finished()}{finished}() signal is emitted. In + general, when a final substate (a child of a QState) is entered, the parent + state's \l{QState::finished()}{finished}() signal is emitted. QFinalState + is part of \l{The State Machine Framework}. + + To use a final state, you create a QFinalState object and add a transition + to it from another state. Example: + + \code + QPushButton button; + + QStateMachine machine; + QState *s1 = new QState(); + QFinalState *s2 = new QFinalState(); + s1->addTransition(&button, SIGNAL(clicked()), s2); + machine.addState(s1); + machine.addState(s2); + + QObject::connect(&machine, SIGNAL(finished()), QApplication::instance(), SLOT(quit())); + machine.setInitialState(s1); + machine.start(); + \endcode + + \sa QStateMachine::finished(), QState::finished() +*/ + +class QFinalStatePrivate : public QAbstractStatePrivate +{ + Q_DECLARE_PUBLIC(QFinalState) + +public: + QFinalStatePrivate(); +}; + +QFinalStatePrivate::QFinalStatePrivate() +{ +} + +/*! + Constructs a new QFinalState object with the given \a parent state. +*/ +QFinalState::QFinalState(QState *parent) + : QAbstractState(*new QFinalStatePrivate, parent) +{ +} + +/*! + Destroys this final state. +*/ +QFinalState::~QFinalState() +{ +} + +/*! + \reimp +*/ +void QFinalState::onEntry(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \reimp +*/ +void QFinalState::onExit(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \reimp +*/ +bool QFinalState::event(QEvent *e) +{ + return QAbstractState::event(e); +} + +QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qfinalstate.h b/src/corelib/statemachine/qfinalstate.h new file mode 100644 index 0000000..fa68394 --- /dev/null +++ b/src/corelib/statemachine/qfinalstate.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFINALSTATE_H +#define QFINALSTATE_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QFinalStatePrivate; +class Q_CORE_EXPORT QFinalState : public QAbstractState +{ + Q_OBJECT +public: + QFinalState(QState *parent = 0); + ~QFinalState(); + +protected: + void onEntry(QEvent *event); + void onExit(QEvent *event); + + bool event(QEvent *e); + +private: + Q_DISABLE_COPY(QFinalState) + Q_DECLARE_PRIVATE(QFinalState) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qhistorystate.cpp b/src/corelib/statemachine/qhistorystate.cpp new file mode 100644 index 0000000..517faa8 --- /dev/null +++ b/src/corelib/statemachine/qhistorystate.cpp @@ -0,0 +1,223 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qhistorystate.h" +#include "qhistorystate_p.h" + +QT_BEGIN_NAMESPACE + +/*! + \class QHistoryState + + \brief The QHistoryState class provides a means of returning to a previously active substate. + + \since 4.6 + \ingroup statemachine + + A history state is a pseudo-state that represents the child state that the + parent state was in the last time the parent state was exited. A transition + with a history state as its target is in fact a transition to one of the + other child states of the parent state. QHistoryState is part of \l{The + State Machine Framework}. + + Use the setDefaultState() function to set the state that should be entered + if the parent state has never been entered. Example: + + \code + QStateMachine machine; + + QState *s1 = new QState(); + QState *s11 = new QState(s1); + QState *s12 = new QState(s1); + + QHistoryState *s1h = new QHistoryState(s1); + s1h->setDefaultState(s11); + + machine.addState(s1); + + QState *s2 = new QState(); + machine.addState(s2); + + QPushButton *button = new QPushButton(); + // Clicking the button will cause the state machine to enter the child state + // that s1 was in the last time s1 was exited, or the history state's default + // state if s1 has never been entered. + s1->addTransition(button, SIGNAL(clicked()), s1h); + \endcode + + By default a history state is shallow, meaning that it won't remember nested + states. This can be configured through the historyType property. +*/ + +/*! + \property QHistoryState::defaultState + + \brief the default state of this history state +*/ + +/*! + \property QHistoryState::historyType + + \brief the type of history that this history state records + + The default value of this property is QHistoryState::ShallowHistory. +*/ + +/*! + \enum QHistoryState::HistoryType + + This enum specifies the type of history that a QHistoryState records. + + \value ShallowHistory Only the immediate child states of the parent state + are recorded. In this case a transition with the history state as its + target will end up in the immediate child state that the parent was in the + last time it was exited. This is the default. + + \value DeepHistory Nested states are recorded. In this case a transition + with the history state as its target will end up in the most deeply nested + descendant state the parent was in the last time it was exited. +*/ + +QHistoryStatePrivate::QHistoryStatePrivate() + : defaultState(0) +{ +} + +QHistoryStatePrivate *QHistoryStatePrivate::get(QHistoryState *q) +{ + return q->d_func(); +} + +/*! + Constructs a new shallow history state with the given \a parent state. +*/ +QHistoryState::QHistoryState(QState *parent) + : QAbstractState(*new QHistoryStatePrivate, parent) +{ + Q_D(QHistoryState); + d->historyType = ShallowHistory; +} +/*! + Constructs a new history state of the given \a type, with the given \a + parent state. +*/ +QHistoryState::QHistoryState(HistoryType type, QState *parent) + : QAbstractState(*new QHistoryStatePrivate, parent) +{ + Q_D(QHistoryState); + d->historyType = type; +} + +/*! + Destroys this history state. +*/ +QHistoryState::~QHistoryState() +{ +} + +/*! + Returns this history state's default state. The default state indicates the + state to transition to if the parent state has never been entered before. +*/ +QAbstractState *QHistoryState::defaultState() const +{ + Q_D(const QHistoryState); + return d->defaultState; +} + +/*! + Sets this history state's default state to be the given \a state. + \a state must be a sibling of this history state. +*/ +void QHistoryState::setDefaultState(QAbstractState *state) +{ + Q_D(QHistoryState); + if (state && state->parentState() != parentState()) { + qWarning("QHistoryState::setDefaultState: state %p does not belong " + "to this history state's group (%p)", state, parentState()); + return; + } + d->defaultState = state; +} + +/*! + Returns the type of history that this history state records. +*/ +QHistoryState::HistoryType QHistoryState::historyType() const +{ + Q_D(const QHistoryState); + return d->historyType; +} + +/*! + Sets the \a type of history that this history state records. +*/ +void QHistoryState::setHistoryType(HistoryType type) +{ + Q_D(QHistoryState); + d->historyType = type; +} + +/*! + \reimp +*/ +void QHistoryState::onEntry(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \reimp +*/ +void QHistoryState::onExit(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \reimp +*/ +bool QHistoryState::event(QEvent *e) +{ + return QAbstractState::event(e); +} + +QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qhistorystate.h b/src/corelib/statemachine/qhistorystate.h new file mode 100644 index 0000000..a0682bd --- /dev/null +++ b/src/corelib/statemachine/qhistorystate.h @@ -0,0 +1,91 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QHISTORYSTATE_H +#define QHISTORYSTATE_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QHistoryStatePrivate; +class Q_CORE_EXPORT QHistoryState : public QAbstractState +{ + Q_OBJECT + Q_PROPERTY(QAbstractState* defaultState READ defaultState WRITE setDefaultState) + Q_PROPERTY(HistoryType historyType READ historyType WRITE setHistoryType) + Q_ENUMS(HistoryType) +public: + enum HistoryType { + ShallowHistory, + DeepHistory + }; + + QHistoryState(QState *parent = 0); + QHistoryState(HistoryType type, QState *parent = 0); + ~QHistoryState(); + + QAbstractState *defaultState() const; + void setDefaultState(QAbstractState *state); + + HistoryType historyType() const; + void setHistoryType(HistoryType type); + +protected: + void onEntry(QEvent *event); + void onExit(QEvent *event); + + bool event(QEvent *e); + +private: + Q_DISABLE_COPY(QHistoryState) + Q_DECLARE_PRIVATE(QHistoryState) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qhistorystate_p.h b/src/corelib/statemachine/qhistorystate_p.h new file mode 100644 index 0000000..5aaa64c --- /dev/null +++ b/src/corelib/statemachine/qhistorystate_p.h @@ -0,0 +1,79 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QHISTORYSTATE_P_H +#define QHISTORYSTATE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qabstractstate_p.h" + +#include + +QT_BEGIN_NAMESPACE + +class QHistoryState; +class QHistoryStatePrivate : public QAbstractStatePrivate +{ + Q_DECLARE_PUBLIC(QHistoryState) + +public: + QHistoryStatePrivate(); + + static QHistoryStatePrivate *get(QHistoryState *q); + + QAbstractState *defaultState; + QHistoryState::HistoryType historyType; + QList configuration; +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/statemachine/qsignalevent.h b/src/corelib/statemachine/qsignalevent.h new file mode 100644 index 0000000..8221f68 --- /dev/null +++ b/src/corelib/statemachine/qsignalevent.h @@ -0,0 +1,77 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSIGNALEVENT_H +#define QSIGNALEVENT_H + +#include + +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class Q_CORE_EXPORT QSignalEvent : public QEvent +{ +public: + QSignalEvent(const QObject *sender, int signalIndex, + const QList &arguments); + ~QSignalEvent(); + + inline const QObject *sender() const { return m_sender; } + inline int signalIndex() const { return m_signalIndex; } + inline QList arguments() const { return m_arguments; } + +private: + const QObject *m_sender; + int m_signalIndex; + QList m_arguments; +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qsignaleventgenerator_p.h b/src/corelib/statemachine/qsignaleventgenerator_p.h new file mode 100644 index 0000000..cf0ea1e --- /dev/null +++ b/src/corelib/statemachine/qsignaleventgenerator_p.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSIGNALEVENTGENERATOR_P_H +#define QSIGNALEVENTGENERATOR_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +QT_BEGIN_NAMESPACE + +class QStateMachine; + +class QSignalEventGenerator : public QObject +{ +public: + QSignalEventGenerator(QStateMachine *parent); + + static const QMetaObject staticMetaObject; + virtual const QMetaObject *metaObject() const; + virtual void *qt_metacast(const char *); + virtual int qt_metacall(QMetaObject::Call, int, void **argv); + +private: + Q_DISABLE_COPY(QSignalEventGenerator) +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/statemachine/qsignaltransition.cpp b/src/corelib/statemachine/qsignaltransition.cpp new file mode 100644 index 0000000..4caa917 --- /dev/null +++ b/src/corelib/statemachine/qsignaltransition.cpp @@ -0,0 +1,257 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qsignaltransition.h" +#include "qsignaltransition_p.h" +#include "qsignalevent.h" +#include "qstate.h" +#include "qstate_p.h" +#include "qstatemachine.h" +#include "qstatemachine_p.h" +#include + +QT_BEGIN_NAMESPACE + +/*! + \class QSignalTransition + + \brief The QSignalTransition class provides a transition based on a Qt signal. + + \since 4.6 + \ingroup statemachine + + Typically you would use the overload of QState::addTransition() that takes a + sender and signal as arguments, rather than creating QSignalTransition + objects directly. QSignalTransition is part of \l{The State Machine + Framework}. + + You can subclass QSignalTransition and reimplement eventTest() to make a + signal transition conditional; the event object passed to eventTest() will + be a QSignalEvent object. Example: + + \code + class CheckedTransition : public QSignalTransition + { + public: + CheckedTransition(QCheckBox *check) + : QSignalTransition(check, SIGNAL(stateChanged(int))) {} + protected: + bool eventTest(QEvent *e) const { + if (!QSignalTransition::eventTest(e)) + return false; + QSignalEvent *se = static_cast(e); + return (se->arguments().at(0).toInt() == Qt::Checked); + } + }; + + ... + + QCheckBox *check = new QCheckBox(); + check->setTristate(true); + + QState *s1 = new QState(); + QState *s2 = new QState(); + CheckedTransition *t1 = new CheckedTransition(check); + t1->setTargetState(s2); + s1->addTransition(t1); + \endcode +*/ + +/*! + \property QSignalTransition::senderObject + + \brief the sender object that this signal transition is associated with +*/ + +/*! + \property QSignalTransition::signal + + \brief the signal that this signal transition is associated with +*/ + +QSignalTransitionPrivate::QSignalTransitionPrivate() +{ + sender = 0; + signalIndex = -1; +} + +QSignalTransitionPrivate *QSignalTransitionPrivate::get(QSignalTransition *q) +{ + return q->d_func(); +} + +void QSignalTransitionPrivate::invalidate() +{ + Q_Q(QSignalTransition); + if (signalIndex != -1) { + QState *source = sourceState(); + QStatePrivate *source_d = QStatePrivate::get(source); + QStateMachinePrivate *mach = QStateMachinePrivate::get(source_d->machine()); + if (mach) { + mach->unregisterSignalTransition(q); + if (mach->configuration.contains(source)) + mach->registerSignalTransition(q); + } + } +} + +/*! + Constructs a new signal transition with the given \a sourceState. +*/ +QSignalTransition::QSignalTransition(QState *sourceState) + : QAbstractTransition(*new QSignalTransitionPrivate, sourceState) +{ +} + +/*! + Constructs a new signal transition associated with the given \a signal of + the given \a sender, and with the given \a sourceState. +*/ +QSignalTransition::QSignalTransition(QObject *sender, const char *signal, + QState *sourceState) + : QAbstractTransition(*new QSignalTransitionPrivate, sourceState) +{ + Q_D(QSignalTransition); + d->sender = sender; + d->signal = signal; +} + +/*! + Constructs a new signal transition associated with the given \a signal of + the given \a sender. The transition has the given \a targets and \a + sourceState. +*/ +QSignalTransition::QSignalTransition(QObject *sender, const char *signal, + const QList &targets, + QState *sourceState) + : QAbstractTransition(*new QSignalTransitionPrivate, targets, sourceState) +{ + Q_D(QSignalTransition); + d->sender = sender; + d->signal = signal; +} + +/*! + Destroys this signal transition. +*/ +QSignalTransition::~QSignalTransition() +{ +} + +/*! + Returns the sender object associated with this signal transition. +*/ +QObject *QSignalTransition::senderObject() const +{ + Q_D(const QSignalTransition); + return d->sender; +} + +/*! + Sets the \a sender object associated with this signal transition. +*/ +void QSignalTransition::setSenderObject(QObject *sender) +{ + Q_D(QSignalTransition); + if (sender == d->sender) + return; + d->sender = sender; + d->invalidate(); +} + +/*! + Returns the signal associated with this signal transition. +*/ +QByteArray QSignalTransition::signal() const +{ + Q_D(const QSignalTransition); + return d->signal; +} + +/*! + Sets the \a signal associated with this signal transition. +*/ +void QSignalTransition::setSignal(const QByteArray &signal) +{ + Q_D(QSignalTransition); + if (signal == d->signal) + return; + d->signal = signal; + d->invalidate(); +} + +/*! + \reimp + + The \a event is a QSignalEvent object. The default implementation returns + true if the event's sender and signal index match this transition, and + returns false otherwise. +*/ +bool QSignalTransition::eventTest(QEvent *event) +{ + Q_D(const QSignalTransition); + if (event->type() == QEvent::Signal) { + if (d->signalIndex == -1) + return false; + QSignalEvent *se = static_cast(event); + return (se->sender() == d->sender) + && (se->signalIndex() == d->signalIndex); + } + return false; +} + +/*! + \reimp +*/ +void QSignalTransition::onTransition(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \reimp +*/ +bool QSignalTransition::event(QEvent *e) +{ + return QAbstractTransition::event(e); +} + +QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qsignaltransition.h b/src/corelib/statemachine/qsignaltransition.h new file mode 100644 index 0000000..b485785 --- /dev/null +++ b/src/corelib/statemachine/qsignaltransition.h @@ -0,0 +1,89 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSIGNALTRANSITION_H +#define QSIGNALTRANSITION_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QSignalTransitionPrivate; +class Q_CORE_EXPORT QSignalTransition : public QAbstractTransition +{ + Q_OBJECT + Q_PROPERTY(QObject* senderObject READ senderObject WRITE setSenderObject) + Q_PROPERTY(QByteArray signal READ signal WRITE setSignal) +public: + QSignalTransition(QState *sourceState = 0); + QSignalTransition(QObject *sender, const char *signal, + QState *sourceState = 0); + QSignalTransition(QObject *sender, const char *signal, + const QList &targets, + QState *sourceState = 0); + ~QSignalTransition(); + + QObject *senderObject() const; + void setSenderObject(QObject *sender); + + QByteArray signal() const; + void setSignal(const QByteArray &signal); + +protected: + bool eventTest(QEvent *event); + void onTransition(QEvent *event); + + bool event(QEvent *e); + +private: + Q_DISABLE_COPY(QSignalTransition) + Q_DECLARE_PRIVATE(QSignalTransition) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qsignaltransition_p.h b/src/corelib/statemachine/qsignaltransition_p.h new file mode 100644 index 0000000..a23e58c --- /dev/null +++ b/src/corelib/statemachine/qsignaltransition_p.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSIGNALTRANSITION_P_H +#define QSIGNALTRANSITION_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qabstracttransition_p.h" + +QT_BEGIN_NAMESPACE + +class QSignalTransition; +class QSignalTransitionPrivate : public QAbstractTransitionPrivate +{ + Q_DECLARE_PUBLIC(QSignalTransition) +public: + QSignalTransitionPrivate(); + + static QSignalTransitionPrivate *get(QSignalTransition *q); + + void invalidate(); + + QObject *sender; + QByteArray signal; + int signalIndex; +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/statemachine/qstate.cpp b/src/corelib/statemachine/qstate.cpp new file mode 100644 index 0000000..e42e463 --- /dev/null +++ b/src/corelib/statemachine/qstate.cpp @@ -0,0 +1,497 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qstate.h" +#include "qstate_p.h" +#include "qhistorystate.h" +#include "qhistorystate_p.h" +#include "qabstracttransition.h" +#include "qabstracttransition_p.h" +#include "qsignaltransition.h" +#include "qstatemachine.h" +#include "qstatemachine_p.h" + +QT_BEGIN_NAMESPACE + +/*! + \class QState + + \brief The QState class provides a general-purpose state for QStateMachine. + + \since 4.6 + \ingroup statemachine + + QState objects can have child states, and can have transitions to other + states. QState is part of \l{The State Machine Framework}. + + The addTransition() function adds a transition. The removeTransition() + function removes a transition. + + The assignProperty() function is used for defining property assignments that + should be performed when a state is entered. + + Top-level states must be passed QStateMachine::rootState() as their parent + state, or added to a state machine using QStateMachine::addState(). + + \section1 States with Child States + + The childMode property determines how child states are treated. For + non-parallel state groups, the setInitialState() function must be called to + set the initial state. The child states are mutually exclusive states, and + the state machine needs to know which child state to enter when the parent + state is the target of a transition. + + The state emits the QState::finished() signal when a final child state + (QFinalState) is entered. + + The setErrorState() sets the state's error state. The error state is the + state that the state machine will transition to if an error is detected when + attempting to enter the state (e.g. because no initial state has been set). + +*/ + +/*! + \property QState::initialState + + \brief the initial state of this state (one of its child states) +*/ + +/*! + \property QState::errorState + + \brief the error state of this state +*/ + +/*! + \property QState::childMode + + \brief the child mode of this state + + The default value of this property is QState::ExclusiveStates. +*/ + +/*! + \enum QState::ChildMode + + This enum specifies how a state's child states are treated. + + \value ExclusiveStates The child states are mutually exclusive and an + initial state must be set by calling QState::setInitialState(). + + \value ParallelStates The child states are parallel. When the parent state + is entered, all its child states are entered in parallel. +*/ + +QStatePrivate::QStatePrivate() + : errorState(0), initialState(0), childMode(QState::ExclusiveStates) +{ +} + +QStatePrivate::~QStatePrivate() +{ +} + +QStatePrivate *QStatePrivate::get(QState *q) +{ + if (!q) + return 0; + return q->d_func(); +} + +const QStatePrivate *QStatePrivate::get(const QState *q) +{ + if (!q) + return 0; + return q->d_func(); +} + +void QStatePrivate::emitFinished() +{ + Q_Q(QState); + emit q->finished(); +} + +void QStatePrivate::emitPolished() +{ + Q_Q(QState); + emit q->polished(); +} + +/*! + Constructs a new state with the given \a parent state. +*/ +QState::QState(QState *parent) + : QAbstractState(*new QStatePrivate, parent) +{ +} + +/*! + Constructs a new state with the given \a childMode and the given \a parent + state. +*/ +QState::QState(ChildMode childMode, QState *parent) + : QAbstractState(*new QStatePrivate, parent) +{ + Q_D(QState); + d->childMode = childMode; +} + +/*! + \internal +*/ +QState::QState(QStatePrivate &dd, QState *parent) + : QAbstractState(dd, parent) +{ +} + +/*! + Destroys this state. +*/ +QState::~QState() +{ +} + +QList QStatePrivate::childStates() const +{ + QList result; + QList::const_iterator it; + for (it = children.constBegin(); it != children.constEnd(); ++it) { + QAbstractState *s = qobject_cast(*it); + if (!s || qobject_cast(s)) + continue; + result.append(s); + } + return result; +} + +QList QStatePrivate::historyStates() const +{ + QList result; + QList::const_iterator it; + for (it = children.constBegin(); it != children.constEnd(); ++it) { + QHistoryState *h = qobject_cast(*it); + if (h) + result.append(h); + } + return result; +} + +QList QStatePrivate::transitions() const +{ + QList result; + QList::const_iterator it; + for (it = children.constBegin(); it != children.constEnd(); ++it) { + QAbstractTransition *t = qobject_cast(*it); + if (t) + result.append(t); + } + return result; +} + +/*! + Instructs this state to set the property with the given \a name of the given + \a object to the given \a value when the state is entered. + + \sa polished() +*/ +void QState::assignProperty(QObject *object, const char *name, + const QVariant &value) +{ + Q_D(QState); + if (!object) { + qWarning("QState::assignProperty: cannot assign property '%s' of null object", name); + return; + } + for (int i = 0; i < d->propertyAssignments.size(); ++i) { + QPropertyAssignment &assn = d->propertyAssignments[i]; + if ((assn.object == object) && (assn.propertyName == name)) { + assn.value = value; + return; + } + } + d->propertyAssignments.append(QPropertyAssignment(object, name, value)); +} + +/*! + Returns this state group's error state. + + \sa QStateMachine::errorState(), QStateMachine::setErrorState() +*/ +QAbstractState *QState::errorState() const +{ + Q_D(const QState); + return d->errorState; +} + +/*! + Sets this state's error state to be the given \a state. If the error state + is not set, or if it is set to 0, the state will inherit its parent's error + state recursively. + + \sa QStateMachine::setErrorState(), QStateMachine::errorState() +*/ +void QState::setErrorState(QAbstractState *state) +{ + Q_D(QState); + if (state != 0 && state->machine() != machine()) { + qWarning("QState::setErrorState: error state cannot belong " + "to a different state machine"); + return; + } + if (state != 0 && state->machine() != 0 && state->machine()->rootState() == state) { + qWarning("QStateMachine::setErrorState: root state cannot be error state"); + return; + } + + d->errorState = state; +} + +/*! + Adds the given \a transition. The transition has this state as the source. + This state takes ownership of the transition. If the transition is successfully + added, the function will return the \a transition pointer. Otherwise it will return null. +*/ +QAbstractTransition *QState::addTransition(QAbstractTransition *transition) +{ + Q_D(QState); + if (!transition) { + qWarning("QState::addTransition: cannot add null transition"); + return 0; + } + + // machine() will always be non-null for root state + if (machine() != 0 && machine()->rootState() == this) { + qWarning("QState::addTransition: cannot add transition from root state"); + return 0; + } + + const QList > &targets = QAbstractTransitionPrivate::get(transition)->targetStates; + for (int i = 0; i < targets.size(); ++i) { + QAbstractState *t = targets.at(i); + if (!t) { + qWarning("QState::addTransition: cannot add transition to null state"); + return 0; + } + if ((QAbstractStatePrivate::get(t)->machine() != d->machine()) + && QAbstractStatePrivate::get(t)->machine() && d->machine()) { + qWarning("QState::addTransition: cannot add transition " + "to a state in a different state machine"); + return 0; + } + } + transition->setParent(this); + if (machine() != 0 && machine()->configuration().contains(this)) + QStateMachinePrivate::get(machine())->registerTransitions(this); + return transition; +} + +/*! + Adds a transition associated with the given \a signal of the given \a sender + object, and returns the new QSignalTransition object. The transition has + this state as the source, and the given \a target as the target state. +*/ +QSignalTransition *QState::addTransition(QObject *sender, const char *signal, + QAbstractState *target) +{ + if (!sender) { + qWarning("QState::addTransition: sender cannot be null"); + return 0; + } + if (!signal) { + qWarning("QState::addTransition: signal cannot be null"); + return 0; + } + if (!target) { + qWarning("QState::addTransition: cannot add transition to null state"); + return 0; + } + if (*signal && sender->metaObject()->indexOfSignal(signal+1) == -1) { + qWarning("QState::addTransition: no such signal %s::%s", + sender->metaObject()->className(), signal+1); + return 0; + } + QSignalTransition *trans = new QSignalTransition(sender, signal, QList() << target); + addTransition(trans); + return trans; +} + +namespace { + +// ### Make public? +class UnconditionalTransition : public QAbstractTransition +{ +public: + UnconditionalTransition(QAbstractState *target) + : QAbstractTransition(QList() << target) {} +protected: + void onTransition(QEvent *) {} + bool eventTest(QEvent *) { return true; } +}; + +} // namespace + +/*! + Adds an unconditional transition from this state to the given \a target + state, and returns then new transition object. +*/ +QAbstractTransition *QState::addTransition(QAbstractState *target) +{ + if (!target) { + qWarning("QState::addTransition: cannot add transition to null state"); + return 0; + } + UnconditionalTransition *trans = new UnconditionalTransition(target); + return addTransition(trans); +} + +/*! + Removes the given \a transition from this state. The state releases + ownership of the transition. + + \sa addTransition() +*/ +void QState::removeTransition(QAbstractTransition *transition) +{ + Q_D(QState); + if (!transition) { + qWarning("QState::removeTransition: cannot remove null transition"); + return; + } + if (transition->sourceState() != this) { + qWarning("QState::removeTransition: transition %p's source state (%p)" + " is different from this state (%p)", + transition, transition->sourceState(), this); + return; + } + QStateMachinePrivate *mach = QStateMachinePrivate::get(d->machine()); + if (mach) + mach->unregisterTransition(transition); + transition->setParent(0); +} + +/*! + \reimp +*/ +void QState::onEntry(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \reimp +*/ +void QState::onExit(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + Returns this state's initial state, or 0 if the state has no initial state. +*/ +QAbstractState *QState::initialState() const +{ + Q_D(const QState); + return d->initialState; +} + +/*! + Sets this state's initial state to be the given \a state. + \a state has to be a child of this state. +*/ +void QState::setInitialState(QAbstractState *state) +{ + Q_D(QState); + if (d->childMode == QState::ParallelStates) { + qWarning("QState::setInitialState: ignoring attempt to set initial state " + "of parallel state group %p", this); + return; + } + if (state && (state->parentState() != this)) { + qWarning("QState::setInitialState: state %p is not a child of this state (%p)", + state, this); + return; + } + d->initialState = state; +} + +/*! + Returns the child mode of this state. +*/ +QState::ChildMode QState::childMode() const +{ + Q_D(const QState); + return d->childMode; +} + +/*! + Sets the child \a mode of this state. +*/ +void QState::setChildMode(ChildMode mode) +{ + Q_D(QState); + d->childMode = mode; +} + +/*! + \reimp +*/ +bool QState::event(QEvent *e) +{ + return QAbstractState::event(e); +} + +/*! + \fn QState::finished() + + This signal is emitted when a final child state of this state is entered. + + \sa QFinalState +*/ + +/*! + \fn QState::polished() + + This signal is emitted when all properties have been assigned their final value. + + \sa QState::assignProperty(), QAbstractTransition::addAnimation() +*/ + +QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qstate.h b/src/corelib/statemachine/qstate.h new file mode 100644 index 0000000..6729c69 --- /dev/null +++ b/src/corelib/statemachine/qstate.h @@ -0,0 +1,113 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSTATE_H +#define QSTATE_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QAbstractTransition; +class QSignalTransition; + +class QStatePrivate; +class Q_CORE_EXPORT QState : public QAbstractState +{ + Q_OBJECT + Q_PROPERTY(QAbstractState* initialState READ initialState WRITE setInitialState) + Q_PROPERTY(QAbstractState* errorState READ errorState WRITE setErrorState) + Q_PROPERTY(ChildMode childMode READ childMode WRITE setChildMode) + Q_ENUMS(ChildMode) +public: + enum ChildMode { + ExclusiveStates, + ParallelStates + }; + + QState(QState *parent = 0); + QState(ChildMode childMode, QState *parent = 0); + ~QState(); + + QAbstractState *errorState() const; + void setErrorState(QAbstractState *state); + + QAbstractTransition *addTransition(QAbstractTransition *transition); + QSignalTransition *addTransition(QObject *sender, const char *signal, QAbstractState *target); + QAbstractTransition *addTransition(QAbstractState *target); + void removeTransition(QAbstractTransition *transition); + + QAbstractState *initialState() const; + void setInitialState(QAbstractState *state); + + ChildMode childMode() const; + void setChildMode(ChildMode mode); + + void assignProperty(QObject *object, const char *name, + const QVariant &value); + +Q_SIGNALS: + void finished(); + void polished(); + +protected: + void onEntry(QEvent *event); + void onExit(QEvent *event); + + bool event(QEvent *e); + +protected: + QState(QStatePrivate &dd, QState *parent); + +private: + Q_DISABLE_COPY(QState) + Q_DECLARE_PRIVATE(QState) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qstate_p.h b/src/corelib/statemachine/qstate_p.h new file mode 100644 index 0000000..1f913b4 --- /dev/null +++ b/src/corelib/statemachine/qstate_p.h @@ -0,0 +1,108 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSTATE_P_H +#define QSTATE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qabstractstate_p.h" + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +struct QPropertyAssignment +{ + QPropertyAssignment() + : object(0) {} + QPropertyAssignment(QObject *o, const QByteArray &n, + const QVariant &v, bool es = true) + : object(o), propertyName(n), value(v), explicitlySet(es) + {} + QObject *object; + QByteArray propertyName; + QVariant value; + bool explicitlySet; +}; + +class QAbstractTransition; +class QHistoryState; + +class QState; +class Q_CORE_EXPORT QStatePrivate : public QAbstractStatePrivate +{ + Q_DECLARE_PUBLIC(QState) +public: + QStatePrivate(); + ~QStatePrivate(); + + static QStatePrivate *get(QState *q); + static const QStatePrivate *get(const QState *q); + + QList childStates() const; + QList historyStates() const; + QList transitions() const; + + void emitFinished(); + void emitPolished(); + + QAbstractState *errorState; + QAbstractState *initialState; + QState::ChildMode childMode; + + QList propertyAssignments; +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp new file mode 100644 index 0000000..744515b --- /dev/null +++ b/src/corelib/statemachine/qstatemachine.cpp @@ -0,0 +1,2216 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qstatemachine.h" +#include "qstate.h" +#include "qstate_p.h" +#include "qstatemachine_p.h" +#include "qabstracttransition.h" +#include "qabstracttransition_p.h" +#include "qsignaltransition.h" +#include "qsignaltransition_p.h" +#include "qsignalevent.h" +#include "qsignaleventgenerator_p.h" +#include "qabstractstate.h" +#include "qabstractstate_p.h" +#include "qfinalstate.h" +#include "qhistorystate.h" +#include "qhistorystate_p.h" +#include "private/qobject_p.h" +#include "private/qthread_p.h" + +#ifndef QT_NO_STATEMACHINE_EVENTFILTER +#include "qeventtransition.h" +#include "qeventtransition_p.h" +#include "qwrappedevent.h" +#endif + +#ifndef QT_NO_ANIMATION +#include "qpropertyanimation.h" +#include "qanimationgroup.h" +#include +#endif + +#include +#include + +QT_BEGIN_NAMESPACE + +/*! + \class QStateMachine + \reentrant + + \brief The QStateMachine class provides a hierarchical finite state machine. + + \since 4.6 + \ingroup statemachine + + QStateMachine is based on the concepts and notation of + \l{Statecharts: A visual formalism for complex + systems}{Statecharts}. QStateMachine is part of \l{The State + Machine Framework}. + + A state machine manages a set of states (classes that inherit from + QAbstractState) and transitions (descendants of + QAbstractTransition) between those states; these states and + transitions define a state graph. Once a state graph has been + built, the state machine can execute it. \l{QStateMachine}'s + execution algorithm is based on the \l{State Chart XML: State + Machine Notation for Control Abstraction}{State Chart XML (SCXML)} + algorithm. The framework's \l{The State Machine + Framework}{overview} gives several state graphs and the code to + build them. + + The rootState() is the parent of all top-level states in the + machine; it is used, for instance, when the state graph is + deleted. It is created by the machine. + + Use the addState() function to add a state to the state machine. + All top-level states are added to the root state. States are + removed with the removeState() function. Removing states while the + machine is running is discouraged. + + Before the machine can be started, the \l{initialState}{initial + state} must be set. The initial state is the state that the + machine enters when started. You can then start() the state + machine. The started() signal is emitted when the initial state is + entered. + + The machine is event driven and keeps its own event loop. Events + are posted to the machine through postEvent(). Note that this + means that it executes asynchronously, and that it will not + progress without a running event loop. You will normally not have + to post events to the machine directly as Qt's transitions, e.g., + QEventTransition and its subclasses, handle this. But for custom + transitions triggered by events, postEvent() is useful. + + The state machine processes events and takes transitions until a + top-level final state is entered; the state machine then emits the + finished() signal. You can also stop() the state machine + explicitly. The stopped() signal is emitted in this case. + + The following snippet shows a state machine that will finish when a button + is clicked: + + \code + QPushButton button; + + QStateMachine machine; + QState *s1 = new QState(); + s1->assignProperty(&button, "text", "Click me"); + + QFinalState *s2 = new QFinalState(); + s1->addTransition(&button, SIGNAL(clicked()), s2); + + machine.addState(s1); + machine.addState(s2); + machine.setInitialState(s1); + machine.start(); + \endcode + + This code example uses QState, which inherits QAbstractState. The + QState class provides a state that you can use to set properties + and invoke methods on \l{QObject}s when the state is entered or + exited. It also contains convenience functions for adding + transitions, e.g., \l{QSignalTransition}s as in this example. See + the QState class description for further details. + + If an error is encountered, the machine will enter the + \l{errorState}{error state}, which is a special state created by + the machine. The types of errors possible are described by the + \l{QStateMachine::}{Error} enum. After the error state is entered, + the type of the error can be retrieved with error(). The execution + of the state graph will not stop when the error state is entered. + So it is possible to handle the error, for instance, by connecting + to the \l{QAbstractState::}{entered()} signal of the error state. + It is also possible to set a custom error state with + setErrorState(). + + \omit This stuff will be moved elsewhere +This is + typically used in conjunction with \l{Signals and Slots}{signals}; the + signals determine the flow of the state graph, whereas the states' property + assignments and method invocations are the actions. + + The postEvent() function posts an event to the state machine. This is useful + when you are using custom events to trigger transitions. + \endomit + + \sa QAbstractState, QAbstractTransition, QState, {The State Machine Framework} +*/ + +/*! + \property QStateMachine::rootState + + \brief the root state of this state machine +*/ + +/*! + \property QStateMachine::initialState + + \brief the initial state of this state machine + + The initial state must be one of the rootState()'s child states. +*/ + +/*! + \property QStateMachine::errorState + + \brief the error state of this state machine +*/ + +/*! + \property QStateMachine::errorString + + \brief the error string of this state machine +*/ + +/*! + \property QStateMachine::globalRestorePolicy + + \brief the restore policy for states of this state machine. + + The default value of this property is + QStateMachine::DoNotRestoreProperties. +*/ + +#ifndef QT_NO_ANIMATION +/*! + \property QStateMachine::animationsEnabled + + \brief whether animations are enabled + + The default value of this property is true. + + \sa QAbstractTransition::addAnimation() +*/ +#endif + +// #define QSTATEMACHINE_DEBUG + +QStateMachinePrivate::QStateMachinePrivate() +{ + state = NotRunning; + processing = false; + processingScheduled = false; + stop = false; + error = QStateMachine::NoError; + globalRestorePolicy = QStateMachine::DoNotRestoreProperties; + rootState = 0; + initialErrorStateForRoot = 0; + signalEventGenerator = 0; +#ifndef QT_NO_ANIMATION + animationsEnabled = true; +#endif +} + +QStateMachinePrivate::~QStateMachinePrivate() +{ + qDeleteAll(internalEventQueue); + qDeleteAll(externalEventQueue); +} + +QStateMachinePrivate *QStateMachinePrivate::get(QStateMachine *q) +{ + if (q) + return q->d_func(); + return 0; +} + +static QEvent *cloneEvent(QEvent *e) +{ + switch (e->type()) { + case QEvent::None: + return new QEvent(*e); + case QEvent::Timer: + return new QTimerEvent(*static_cast(e)); + default: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + } + return 0; +} + +const QStateMachinePrivate::Handler qt_kernel_statemachine_handler = { + cloneEvent +}; + +const QStateMachinePrivate::Handler *QStateMachinePrivate::handler = &qt_kernel_statemachine_handler; + +Q_CORE_EXPORT const QStateMachinePrivate::Handler *qcoreStateMachineHandler() +{ + return &qt_kernel_statemachine_handler; +} + +static int indexOfDescendant(QState *s, QAbstractState *desc) +{ + QList childStates = QStatePrivate::get(s)->childStates(); + for (int i = 0; i < childStates.size(); ++i) { + QAbstractState *c = childStates.at(i); + if ((c == desc) || QStateMachinePrivate::isDescendantOf(desc, c)) { + return i; + } + } + return -1; +} + +bool QStateMachinePrivate::stateEntryLessThan(QAbstractState *s1, QAbstractState *s2) +{ + if (s1->parent() == s2->parent()) { + return s1->children().indexOf(s1) + < s2->children().indexOf(s2); + } else if (isDescendantOf(s1, s2)) { + return false; + } else if (isDescendantOf(s2, s1)) { + return true; + } else { + QState *lca = findLCA(QList() << s1 << s2); + Q_ASSERT(lca != 0); + return (indexOfDescendant(lca, s1) < indexOfDescendant(lca, s2)); + } +} + +bool QStateMachinePrivate::stateExitLessThan(QAbstractState *s1, QAbstractState *s2) +{ + if (s1->parent() == s2->parent()) { + return s1->children().indexOf(s1) + < s2->children().indexOf(s2); + } else if (isDescendantOf(s1, s2)) { + return true; + } else if (isDescendantOf(s2, s1)) { + return false; + } else { + QState *lca = findLCA(QList() << s1 << s2); + Q_ASSERT(lca != 0); + return (indexOfDescendant(lca, s1) < indexOfDescendant(lca, s2)); + } +} + +QState *QStateMachinePrivate::findLCA(const QList &states) +{ + if (states.isEmpty()) + return 0; + QList ancestors = properAncestors(states.at(0), 0); + for (int i = 0; i < ancestors.size(); ++i) { + QState *anc = ancestors.at(i); + bool ok = true; + for (int j = states.size() - 1; (j > 0) && ok; --j) { + const QAbstractState *s = states.at(j); + if (!isDescendantOf(s, anc)) + ok = false; + } + if (ok) + return anc; + } + return 0; +} + +bool QStateMachinePrivate::isPreempted(const QAbstractState *s, const QSet &transitions) const +{ + QSet::const_iterator it; + for (it = transitions.constBegin(); it != transitions.constEnd(); ++it) { + QAbstractTransition *t = *it; + QList lst = t->targetStates(); + if (!lst.isEmpty()) { + lst.prepend(t->sourceState()); + QAbstractState *lca = findLCA(lst); + if (isDescendantOf(s, lca)) { +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ":" << transitions << "preempts selection of a transition from" + << s << "because" << s << "is a descendant of" << lca; +#endif + return true; + } + } + } + return false; +} + +QSet QStateMachinePrivate::selectTransitions(QEvent *event) const +{ + Q_Q(const QStateMachine); + QSet enabledTransitions; + QSet::const_iterator it; + const_cast(q)->beginSelectTransitions(event); + for (it = configuration.constBegin(); it != configuration.constEnd(); ++it) { + QAbstractState *state = *it; + if (!isAtomic(state)) + continue; + if (isPreempted(state, enabledTransitions)) + continue; + QList lst = properAncestors(state, 0); + if (QState *grp = qobject_cast(state)) + lst.prepend(grp); + bool found = false; + for (int j = 0; (j < lst.size()) && !found; ++j) { + QState *s = lst.at(j); + QList transitions = QStatePrivate::get(s)->transitions(); + for (int k = 0; k < transitions.size(); ++k) { + QAbstractTransition *t = transitions.at(k); + if (QAbstractTransitionPrivate::get(t)->callEventTest(event)) { +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": selecting transition" << t; +#endif + enabledTransitions.insert(t); + found = true; + break; + } + } + } + } + const_cast(q)->endSelectTransitions(event); + return enabledTransitions; +} + +void QStateMachinePrivate::microstep(QEvent *event, const QList &enabledTransitions) +{ +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ": begin microstep( enabledTransitions:" << enabledTransitions << ")"; + qDebug() << q_func() << ": configuration before exiting states:" << configuration; +#endif + QList exitedStates = exitStates(event, enabledTransitions); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ": configuration after exiting states:" << configuration; +#endif + executeTransitionContent(event, enabledTransitions); + QList enteredStates = enterStates(event, enabledTransitions); + applyProperties(enabledTransitions, exitedStates, enteredStates); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ": configuration after entering states:" << configuration; + qDebug() << q_func() << ": end microstep"; +#endif +} + +QList QStateMachinePrivate::exitStates(QEvent *event, const QList &enabledTransitions) +{ +// qDebug() << "exitStates(" << enabledTransitions << ")"; + QSet statesToExit; +// QSet statesToSnapshot; + for (int i = 0; i < enabledTransitions.size(); ++i) { + QAbstractTransition *t = enabledTransitions.at(i); + QList lst = t->targetStates(); + if (lst.isEmpty()) + continue; + lst.prepend(t->sourceState()); + QAbstractState *lca = findLCA(lst); + if (lca == 0) { + setError(QStateMachine::NoCommonAncestorForTransitionError, t->sourceState()); + lst = pendingErrorStates.toList(); + lst.prepend(t->sourceState()); + + lca = findLCA(lst); + Q_ASSERT(lca != 0); + } + + { + QSet::const_iterator it; + for (it = configuration.constBegin(); it != configuration.constEnd(); ++it) { + QAbstractState *s = *it; + if (isDescendantOf(s, lca)) + statesToExit.insert(s); + } + } + } + QList statesToExit_sorted = statesToExit.toList(); + qSort(statesToExit_sorted.begin(), statesToExit_sorted.end(), stateExitLessThan); + for (int i = 0; i < statesToExit_sorted.size(); ++i) { + QAbstractState *s = statesToExit_sorted.at(i); + if (QState *grp = qobject_cast(s)) { + QList hlst = QStatePrivate::get(grp)->historyStates(); + for (int j = 0; j < hlst.size(); ++j) { + QHistoryState *h = hlst.at(j); + QHistoryStatePrivate::get(h)->configuration.clear(); + QSet::const_iterator it; + for (it = configuration.constBegin(); it != configuration.constEnd(); ++it) { + QAbstractState *s0 = *it; + if (QHistoryStatePrivate::get(h)->historyType == QHistoryState::DeepHistory) { + if (isAtomic(s0) && isDescendantOf(s0, s)) + QHistoryStatePrivate::get(h)->configuration.append(s0); + } else if (s0->parentState() == s) { + QHistoryStatePrivate::get(h)->configuration.append(s0); + } + } +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ": recorded" << ((QHistoryStatePrivate::get(h)->historyType == QHistoryState::DeepHistory) ? "deep" : "shallow") + << "history for" << s << "in" << h << ":" << QHistoryStatePrivate::get(h)->configuration; +#endif + } + } + } + for (int i = 0; i < statesToExit_sorted.size(); ++i) { + QAbstractState *s = statesToExit_sorted.at(i); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ": exiting" << s; +#endif + QAbstractStatePrivate::get(s)->callOnExit(event); + configuration.remove(s); + QAbstractStatePrivate::get(s)->emitExited(); + } + return statesToExit_sorted; +} + +void QStateMachinePrivate::executeTransitionContent(QEvent *event, const QList &enabledTransitions) +{ + for (int i = 0; i < enabledTransitions.size(); ++i) { + QAbstractTransition *t = enabledTransitions.at(i); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ": triggering" << t; +#endif + QAbstractTransitionPrivate::get(t)->callOnTransition(event); + } +} + +QList QStateMachinePrivate::enterStates(QEvent *event, const QList &enabledTransitions) +{ +#ifdef QSTATEMACHINE_DEBUG + Q_Q(QStateMachine); +#endif +// qDebug() << "enterStates(" << enabledTransitions << ")"; + QSet statesToEnter; + QSet statesForDefaultEntry; + + if (pendingErrorStates.isEmpty()) { + for (int i = 0; i < enabledTransitions.size(); ++i) { + QAbstractTransition *t = enabledTransitions.at(i); + QList lst = t->targetStates(); + if (lst.isEmpty()) + continue; + lst.prepend(t->sourceState()); + QState *lca = findLCA(lst); + for (int j = 1; j < lst.size(); ++j) { + QAbstractState *s = lst.at(j); + addStatesToEnter(s, lca, statesToEnter, statesForDefaultEntry); + if (isParallel(lca)) { + QList lcac = QStatePrivate::get(lca)->childStates(); + foreach (QAbstractState* child,lcac) { + if (!statesToEnter.contains(child)) + addStatesToEnter(child,lca,statesToEnter,statesForDefaultEntry); + } + } + } + } + } + + // Did an error occur while selecting transitions? Then we enter the error state. + if (!pendingErrorStates.isEmpty()) { + statesToEnter.clear(); + statesToEnter = pendingErrorStates; + statesForDefaultEntry = pendingErrorStatesForDefaultEntry; + pendingErrorStates.clear(); + pendingErrorStatesForDefaultEntry.clear(); + } + + QList statesToEnter_sorted = statesToEnter.toList(); + qSort(statesToEnter_sorted.begin(), statesToEnter_sorted.end(), stateEntryLessThan); + + for (int i = 0; i < statesToEnter_sorted.size(); ++i) { + QAbstractState *s = statesToEnter_sorted.at(i); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": entering" << s; +#endif + configuration.insert(s); + registerTransitions(s); + QAbstractStatePrivate::get(s)->callOnEntry(event); + QAbstractStatePrivate::get(s)->emitEntered(); + if (statesForDefaultEntry.contains(s)) { + // ### executeContent(s.initial.transition.children()) + } + if (isFinal(s)) { + QState *parent = s->parentState(); + if (parent) { + QState *grandparent = parent->parentState(); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": emitting finished signal for" << parent; +#endif + QStatePrivate::get(parent)->emitFinished(); + if (grandparent && isParallel(grandparent)) { + bool allChildStatesFinal = true; + QList childStates = QStatePrivate::get(grandparent)->childStates(); + for (int j = 0; j < childStates.size(); ++j) { + QAbstractState *cs = childStates.at(j); + if (!isInFinalState(cs)) { + allChildStatesFinal = false; + break; + } + } + if (allChildStatesFinal) { +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": emitting finished signal for" << grandparent; +#endif + QStatePrivate::get(grandparent)->emitFinished(); + } + } + } + } + } + { + QSet::const_iterator it; + for (it = configuration.constBegin(); it != configuration.constEnd(); ++it) { + if (isFinal(*it) && (*it)->parentState() == rootState) { + processing = false; + stopProcessingReason = Finished; + break; + } + } + } +// qDebug() << "configuration:" << configuration.toList(); + return statesToEnter_sorted; +} + +void QStateMachinePrivate::addStatesToEnter(QAbstractState *s, QState *root, + QSet &statesToEnter, + QSet &statesForDefaultEntry) +{ + if (QHistoryState *h = qobject_cast(s)) { + QList hconf = QHistoryStatePrivate::get(h)->configuration; + if (!hconf.isEmpty()) { + for (int k = 0; k < hconf.size(); ++k) { + QAbstractState *s0 = hconf.at(k); + addStatesToEnter(s0, root, statesToEnter, statesForDefaultEntry); + } + #ifdef QSTATEMACHINE_DEBUG + qDebug() <historyType == QHistoryState::DeepHistory) ? "deep" : "shallow") + << "history from" << s << ":" << hconf; + #endif + } else { + QList hlst; + if (QHistoryStatePrivate::get(h)->defaultState) + hlst.append(QHistoryStatePrivate::get(h)->defaultState); + + if (hlst.isEmpty()) { + setError(QStateMachine::NoDefaultStateInHistoryStateError, h); + } else { + for (int k = 0; k < hlst.size(); ++k) { + QAbstractState *s0 = hlst.at(k); + addStatesToEnter(s0, root, statesToEnter, statesForDefaultEntry); + } + #ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ": initial history targets for" << s << ":" << hlst; + #endif + } + } + } else { + statesToEnter.insert(s); + if (isParallel(s)) { + QState *grp = qobject_cast(s); + QList lst = QStatePrivate::get(grp)->childStates(); + for (int i = 0; i < lst.size(); ++i) { + QAbstractState *child = lst.at(i); + addStatesToEnter(child, grp, statesToEnter, statesForDefaultEntry); + } + } else if (isCompound(s)) { + statesForDefaultEntry.insert(s); + QState *grp = qobject_cast(s); + QAbstractState *initial = grp->initialState(); + if (initial != 0) { + addStatesToEnter(initial, grp, statesToEnter, statesForDefaultEntry); + } else { + setError(QStateMachine::NoInitialStateError, grp); + return; + } + } + QList ancs = properAncestors(s, root); + for (int i = 0; i < ancs.size(); ++i) { + QState *anc = ancs.at(i); + if (!anc->parentState()) + continue; + statesToEnter.insert(anc); + if (isParallel(anc)) { + QList lst = QStatePrivate::get(anc)->childStates(); + for (int j = 0; j < lst.size(); ++j) { + QAbstractState *child = lst.at(j); + bool hasDescendantInList = false; + QSet::const_iterator it; + for (it = statesToEnter.constBegin(); it != statesToEnter.constEnd(); ++it) { + if (isDescendantOf(*it, child)) { + hasDescendantInList = true; + break; + } + } + if (!hasDescendantInList) + addStatesToEnter(child, anc, statesToEnter, statesForDefaultEntry); + } + } + } + } +} + +void QStateMachinePrivate::applyProperties(const QList &transitionList, + const QList &exitedStates, + const QList &enteredStates) +{ + Q_Q(QStateMachine); +#ifdef QT_NO_ANIMATION + Q_UNUSED(transitionList); +#endif + // Process the property assignments of the entered states. + QHash > propertyAssignmentsForState; + QHash pendingRestorables = registeredRestorables; + for (int i = 0; i < enteredStates.size(); ++i) { + QState *s = qobject_cast(enteredStates.at(i)); + if (!s) + continue; + + QList assignments = QStatePrivate::get(s)->propertyAssignments; + for (int j = 0; j < assignments.size(); ++j) { + const QPropertyAssignment &assn = assignments.at(j); + if (globalRestorePolicy == QStateMachine::RestoreProperties) { + registerRestorable(assn.object, assn.propertyName); + } + pendingRestorables.remove(RestorableId(assn.object, assn.propertyName)); + propertyAssignmentsForState[s].append(assn); + } + + // Remove pending restorables for all parent states to avoid restoring properties + // before the state that assigned them is exited. If state does not explicitly + // assign a property which is assigned by the parent, it inherits the parent's assignment. + QState *parentState = s; + while ((parentState = parentState->parentState()) != 0) { + assignments = QStatePrivate::get(parentState)->propertyAssignments; + for (int j=0; j 0) + propertyAssignmentsForState[s].append(assn); + } + } + } + if (!pendingRestorables.isEmpty()) { + QAbstractState *s; + if (!enteredStates.isEmpty()) + s = enteredStates.last(); // ### handle if parallel + else + s = 0; + propertyAssignmentsForState[s] << restorablesToPropertyList(pendingRestorables); + } + +#ifndef QT_NO_ANIMATION + // Gracefully terminate playing animations for states that are exited. + for (int i = 0; i < exitedStates.size(); ++i) { + QAbstractState *s = exitedStates.at(i); + QList animations = animationsForState.take(s); + for (int j = 0; j < animations.size(); ++j) { + QAbstractAnimation *anim = animations.at(j); + QObject::disconnect(anim, SIGNAL(finished()), q, SLOT(_q_animationFinished())); + stateForAnimation.remove(anim); + + // Stop the (top-level) animation. + // ### Stopping nested animation has weird behavior. + QAbstractAnimation *topLevelAnim = anim; + while (QAnimationGroup *group = topLevelAnim->group()) + topLevelAnim = group; + topLevelAnim->stop(); + + if (resetAnimationEndValues.contains(anim)) { + qobject_cast(anim)->setEndValue(QVariant()); // ### generalize + resetAnimationEndValues.remove(anim); + } + QPropertyAssignment assn = propertyForAnimation.take(anim); + Q_ASSERT(assn.object != 0); + // If there is no property assignment that sets this property, + // set the property to its target value. + bool found = false; + QHash >::const_iterator it; + for (it = propertyAssignmentsForState.constBegin(); it != propertyAssignmentsForState.constEnd(); ++it) { + const QList &assignments = it.value(); + for (int k = 0; k < assignments.size(); ++k) { + if ((assignments.at(k).object == assn.object) + && (assignments.at(k).propertyName == assn.propertyName)) { + found = true; + break; + } + } + } + if (!found) { + assn.object->setProperty(assn.propertyName, assn.value); + } + } + } + + // Find the animations to use for the state change. + QList selectedAnimations; + if (animationsEnabled) { + for (int i = 0; i < transitionList.size(); ++i) { + QAbstractTransition *transition = transitionList.at(i); + + selectedAnimations << transition->animations(); + selectedAnimations << defaultAnimationsForSource.values(transition->sourceState()); + + QList targetStates = transition->targetStates(); + for (int j=0; j >::iterator it; + for (it = propertyAssignmentsForState.begin(); it != propertyAssignmentsForState.end(); ) { + QList::iterator it2; + QAbstractState *s = it.key(); + QList &assignments = it.value(); + for (it2 = assignments.begin(); it2 != assignments.end(); ) { + QPair, QList > ret; + ret = initializeAnimation(anim, *it2); + QList handlers = ret.first; + if (!handlers.isEmpty()) { + for (int j = 0; j < handlers.size(); ++j) { + QAbstractAnimation *a = handlers.at(j); + propertyForAnimation.insert(a, *it2); + stateForAnimation.insert(a, s); + animationsForState[s].append(a); + // ### connect to just the top-level animation? + QObject::disconnect(a, SIGNAL(finished()), q, SLOT(_q_animationFinished())); + QObject::connect(a, SIGNAL(finished()), q, SLOT(_q_animationFinished())); + } + it2 = assignments.erase(it2); + } else { + ++it2; + } + for (int j = 0; j < ret.second.size(); ++j) + resetAnimationEndValues.insert(ret.second.at(j)); + } + if (assignments.isEmpty()) + it = propertyAssignmentsForState.erase(it); + else + ++it; + } + // We require that at least one animation is valid. + // ### generalize + QList variantAnims = qFindChildren(anim); + if (QVariantAnimation *va = qobject_cast(anim)) + variantAnims.append(va); + + bool hasValidEndValue = false; + for (int j = 0; j < variantAnims.size(); ++j) { + if (variantAnims.at(j)->endValue().isValid()) { + hasValidEndValue = true; + break; + } + } + + if (hasValidEndValue) { + anim->start(); + } + } +#endif // !QT_NO_ANIMATION + + // Immediately set the properties that are not animated. + { + QHash >::const_iterator it; + for (it = propertyAssignmentsForState.constBegin(); it != propertyAssignmentsForState.constEnd(); ++it) { + const QList &assignments = it.value(); + for (int i = 0; i < assignments.size(); ++i) { + const QPropertyAssignment &assn = assignments.at(i); + assn.object->setProperty(assn.propertyName, assn.value); + } + } + } + + // Emit polished signal for entered states that have no animated properties. + for (int i = 0; i < enteredStates.size(); ++i) { + QState *s = qobject_cast(enteredStates.at(i)); + if (s && !animationsForState.contains(s)) + QStatePrivate::get(s)->emitPolished(); + } +} + +bool QStateMachinePrivate::isFinal(const QAbstractState *s) +{ + return qobject_cast(s) != 0; +} + +bool QStateMachinePrivate::isParallel(const QAbstractState *s) +{ + const QState *ss = qobject_cast(s); + return ss && (QStatePrivate::get(ss)->childMode == QState::ParallelStates); +} + +bool QStateMachinePrivate::isCompound(const QAbstractState *s) +{ + const QState *group = qobject_cast(s); + if (!group) + return false; + return (!isParallel(group) && !QStatePrivate::get(group)->childStates().isEmpty()) + || (qobject_cast(group->parent()) != 0); +} + +bool QStateMachinePrivate::isAtomic(const QAbstractState *s) +{ + const QState *ss = qobject_cast(s); + return (ss && QStatePrivate::get(ss)->childStates().isEmpty()) + || isFinal(s); +} + + +bool QStateMachinePrivate::isDescendantOf(const QAbstractState *state, const QAbstractState *other) +{ + Q_ASSERT(state != 0); + for (QAbstractState *s = state->parentState(); s != 0; s = s->parentState()) { + if (s == other) + return true; + } + return false; +} + +QList QStateMachinePrivate::properAncestors(const QAbstractState *state, const QState *upperBound) +{ + Q_ASSERT(state != 0); + QList result; + for (QState *s = state->parentState(); s && s != upperBound; s = s->parentState()) { + result.append(s); + } + return result; +} + +bool QStateMachinePrivate::isInFinalState(QAbstractState* s) const +{ + if (isCompound(s)) { + QState *grp = qobject_cast(s); + QList lst = QStatePrivate::get(grp)->childStates(); + for (int i = 0; i < lst.size(); ++i) { + QAbstractState *cs = lst.at(i); + if (isFinal(cs) && configuration.contains(cs)) + return true; + } + return false; + } else if (isParallel(s)) { + QState *grp = qobject_cast(s); + QList lst = QStatePrivate::get(grp)->childStates(); + for (int i = 0; i < lst.size(); ++i) { + QAbstractState *cs = lst.at(i); + if (!isInFinalState(cs)) + return false; + } + return true; + } + else + return false; +} + +void QStateMachinePrivate::registerRestorable(QObject *object, const QByteArray &propertyName) +{ + RestorableId id(object, propertyName); + if (!registeredRestorables.contains(id)) + registeredRestorables.insert(id, object->property(propertyName)); +} + +QList QStateMachinePrivate::restorablesToPropertyList(const QHash &restorables) const +{ + QList result; + QHash::const_iterator it; + for (it = restorables.constBegin(); it != restorables.constEnd(); ++it) { +// qDebug() << "restorable:" << it.key().first << it.key().second << it.value(); + result.append(QPropertyAssignment(it.key().first, it.key().second, it.value(), /*explicitlySet=*/false)); + } + return result; +} + +/*! + \internal + Returns true if the variable with the given \a id has been registered for restoration. +*/ +bool QStateMachinePrivate::hasRestorable(QObject *object, const QByteArray &propertyName) const +{ + return registeredRestorables.contains(RestorableId(object, propertyName)); +} + +QVariant QStateMachinePrivate::restorableValue(QObject *object, const QByteArray &propertyName) const +{ + return registeredRestorables.value(RestorableId(object, propertyName), QVariant()); +} + + +/*! + \internal + Unregisters the variable identified by \a id +*/ +void QStateMachinePrivate::unregisterRestorable(QObject *object, const QByteArray &propertyName) +{ +// qDebug() << "unregisterRestorable(" << object << propertyName << ")"; + RestorableId id(object, propertyName); + registeredRestorables.remove(id); +} + +QAbstractState *QStateMachinePrivate::findErrorState(QAbstractState *context) +{ + // If the user sets the root state's error state to 0, we return the initial error state + if (context == 0) + return initialErrorStateForRoot; + + // Find error state recursively in parent hierarchy if not set explicitly for context state + QAbstractState *errorState = 0; + + QState *s = qobject_cast(context); + if (s) + errorState = s->errorState(); + + if (!errorState) + errorState = findErrorState(context->parentState()); + + return errorState; +} + +void QStateMachinePrivate::setError(QStateMachine::Error errorCode, QAbstractState *currentContext) +{ + error = errorCode; + + switch (errorCode) { + case QStateMachine::NoInitialStateError: + Q_ASSERT(currentContext != 0); + + errorString = QStateMachine::tr("Missing initial state in compound state '%1'") + .arg(currentContext->objectName()); + + break; + case QStateMachine::NoDefaultStateInHistoryStateError: + Q_ASSERT(currentContext != 0); + + errorString = QStateMachine::tr("Missing default state in history state '%1'") + .arg(currentContext->objectName()); + break; + + case QStateMachine::NoCommonAncestorForTransitionError: + Q_ASSERT(currentContext != 0); + + errorString = QStateMachine::tr("No common ancestor for targets and source of transition from state '%1'") + .arg(currentContext->objectName()); + break; + default: + errorString = QStateMachine::tr("Unknown error"); + }; + + pendingErrorStates.clear(); + pendingErrorStatesForDefaultEntry.clear(); + + QAbstractState *currentErrorState = findErrorState(currentContext); + + // Avoid infinite loop if the error state itself has an error + if (currentContext == currentErrorState) { + Q_ASSERT(currentContext != initialErrorStateForRoot); // RootErrorState is broken + currentErrorState = initialErrorStateForRoot; + } + + Q_ASSERT(currentErrorState != 0); + Q_ASSERT(currentErrorState != rootState); + + QState *lca = findLCA(QList() << currentErrorState << currentContext); + addStatesToEnter(currentErrorState, lca, pendingErrorStates, pendingErrorStatesForDefaultEntry); +} + +#ifndef QT_NO_ANIMATION + +QPair, QList > +QStateMachinePrivate::initializeAnimation(QAbstractAnimation *abstractAnimation, + const QPropertyAssignment &prop) +{ + QList handledAnimations; + QList localResetEndValues; + QAnimationGroup *group = qobject_cast(abstractAnimation); + if (group) { + for (int i = 0; i < group->animationCount(); ++i) { + QAbstractAnimation *animationChild = group->animationAt(i); + QPair, QList > ret; + ret = initializeAnimation(animationChild, prop); + handledAnimations << ret.first; + localResetEndValues << ret.second; + } + } else { + QPropertyAnimation *animation = qobject_cast(abstractAnimation); + if (animation != 0 + && prop.object == animation->targetObject() + && prop.propertyName == animation->propertyName()) { + + // Only change end value if it is undefined + if (!animation->endValue().isValid()) { + animation->setEndValue(prop.value); + localResetEndValues.append(animation); + } + handledAnimations.append(animation); + } + } + return qMakePair(handledAnimations, localResetEndValues); +} + +void QStateMachinePrivate::_q_animationFinished() +{ + Q_Q(QStateMachine); + QAbstractAnimation *anim = qobject_cast(q->sender()); + Q_ASSERT(anim != 0); + QObject::disconnect(anim, SIGNAL(finished()), q, SLOT(_q_animationFinished())); + if (resetAnimationEndValues.contains(anim)) { + qobject_cast(anim)->setEndValue(QVariant()); // ### generalize + resetAnimationEndValues.remove(anim); + } + + // Set the final property value. + QPropertyAssignment assn = propertyForAnimation.take(anim); + Q_ASSERT(assn.object != 0); + assn.object->setProperty(assn.propertyName, assn.value); + if (!assn.explicitlySet) + unregisterRestorable(assn.object, assn.propertyName); + + QAbstractState *state = stateForAnimation.take(anim); + Q_ASSERT(state != 0); + QHash >::iterator it; + it = animationsForState.find(state); + Q_ASSERT(it != animationsForState.end()); + QList &animations = it.value(); + animations.removeOne(anim); + if (animations.isEmpty()) { + animationsForState.erase(it); + QStatePrivate::get(qobject_cast(state))->emitPolished(); + } +} + +#endif // !QT_NO_ANIMATION + +namespace { + +class StartState : public QState +{ +public: + StartState(QState *parent) + : QState(parent) {} +protected: + void onEntry(QEvent *) {} + void onExit(QEvent *) {} +}; + +class InitialTransition : public QAbstractTransition +{ +public: + InitialTransition(QAbstractState *target) + : QAbstractTransition(QList() << target) {} +protected: + virtual bool eventTest(QEvent *) { return true; } + virtual void onTransition(QEvent *) {} +}; + +} // namespace + +void QStateMachinePrivate::_q_start() +{ + Q_Q(QStateMachine); + Q_ASSERT(state == Starting); + if (!rootState) { + state = NotRunning; + return; + } + QAbstractState *initial = rootState->initialState(); + if (initial == 0) + setError(QStateMachine::NoInitialStateError, rootState); + + configuration.clear(); + qDeleteAll(internalEventQueue); + internalEventQueue.clear(); + qDeleteAll(externalEventQueue); + externalEventQueue.clear(); + +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": starting"; +#endif + state = Running; + processingScheduled = true; // we call _q_process() below + emit q->started(); + + StartState *start = new StartState(rootState); + QAbstractTransition *initialTransition = new InitialTransition(initial); + start->addTransition(initialTransition); + QList transitions; + transitions.append(initialTransition); + QEvent nullEvent(QEvent::None); + executeTransitionContent(&nullEvent, transitions); + enterStates(&nullEvent, transitions); + applyProperties(transitions, QList() << start, + QList() << initial); + delete start; + +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": initial configuration:" << configuration; +#endif + _q_process(); +} + +void QStateMachinePrivate::_q_process() +{ + Q_Q(QStateMachine); + Q_ASSERT(state == Running); + Q_ASSERT(!processing); + processing = true; + processingScheduled = false; +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": starting the event processing loop"; +#endif + while (processing) { + if (stop) { + stop = false; + processing = false; + stopProcessingReason = Stopped; + break; + } + QSet enabledTransitions; + QEvent *e = new QEvent(QEvent::None); + enabledTransitions = selectTransitions(e); + if (enabledTransitions.isEmpty()) { + delete e; + e = 0; + } + if (enabledTransitions.isEmpty() && !internalEventQueue.isEmpty()) { + e = internalEventQueue.takeFirst(); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": dequeued internal event" << e << "of type" << e->type(); +#endif + enabledTransitions = selectTransitions(e); + if (enabledTransitions.isEmpty()) { + delete e; + e = 0; + } + } + if (enabledTransitions.isEmpty()) { + if (externalEventQueue.isEmpty()) { + if (internalEventQueue.isEmpty()) { + processing = false; + stopProcessingReason = EventQueueEmpty; + } + } else { + e = externalEventQueue.takeFirst(); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": dequeued external event" << e << "of type" << e->type(); +#endif + enabledTransitions = selectTransitions(e); + if (enabledTransitions.isEmpty()) { + delete e; + e = 0; + } + } + } + if (!enabledTransitions.isEmpty()) { + q->beginMicrostep(e); + microstep(e, enabledTransitions.toList()); + q->endMicrostep(e); + } +#ifdef QSTATEMACHINE_DEBUG + else { + qDebug() << q << ": no transitions enabled"; + } +#endif + delete e; + } +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": finished the event processing loop"; +#endif + switch (stopProcessingReason) { + case EventQueueEmpty: + break; + case Finished: + state = NotRunning; + unregisterAllTransitions(); + emit q->finished(); + break; + case Stopped: + state = NotRunning; + unregisterAllTransitions(); + emit q->stopped(); + break; + } +} + +void QStateMachinePrivate::scheduleProcess() +{ + if ((state != Running) || processing || processingScheduled) + return; + processingScheduled = true; + QMetaObject::invokeMethod(q_func(), "_q_process", Qt::QueuedConnection); +} + +void QStateMachinePrivate::registerTransitions(QAbstractState *state) +{ + QState *group = qobject_cast(state); + if (!group) + return; + QList transitions = QStatePrivate::get(group)->transitions(); + for (int i = 0; i < transitions.size(); ++i) { + QAbstractTransition *t = transitions.at(i); + if (QSignalTransition *st = qobject_cast(t)) { + registerSignalTransition(st); + } +#ifndef QT_NO_STATEMACHINE_EVENTFILTER + else if (QEventTransition *oet = qobject_cast(t)) { + registerEventTransition(oet); + } +#endif + } +} + +void QStateMachinePrivate::unregisterTransition(QAbstractTransition *transition) +{ + if (QSignalTransition *st = qobject_cast(transition)) { + unregisterSignalTransition(st); + } +#ifndef QT_NO_STATEMACHINE_EVENTFILTER + else if (QEventTransition *oet = qobject_cast(transition)) { + unregisterEventTransition(oet); + } +#endif +} + +static int senderSignalIndex(const QObject *sender) +{ + QObjectPrivate *d = QObjectPrivate::get(const_cast(sender)); + QMutexLocker(&d->threadData->mutex); + if (!d->currentSender) + return -1; + + // Return -1 if d->currentSender isn't in d->senders + bool found = false; + for (int i = 0; !found && i < d->senders.count(); ++i) + found = (d->senders.at(i)->sender == d->currentSender->sender); + if (!found) + return -1; + return d->currentSender->signal; +} + +void QStateMachinePrivate::registerSignalTransition(QSignalTransition *transition) +{ + Q_Q(QStateMachine); + if (QSignalTransitionPrivate::get(transition)->signalIndex != -1) + return; // already registered + QObject *sender = QSignalTransitionPrivate::get(transition)->sender; + if (!sender) + return; + QByteArray signal = QSignalTransitionPrivate::get(transition)->signal; + if (signal.startsWith('0'+QSIGNAL_CODE)) + signal.remove(0, 1); + int signalIndex = sender->metaObject()->indexOfSignal(signal); + if (signalIndex == -1) { + qWarning("QSignalTransition: no such signal: %s::%s", + sender->metaObject()->className(), signal.constData()); + return; + } + QVector &connectedSignalIndexes = connections[sender]; + if (connectedSignalIndexes.size() <= signalIndex) + connectedSignalIndexes.resize(signalIndex+1); + if (connectedSignalIndexes.at(signalIndex) == 0) { + if (!signalEventGenerator) + signalEventGenerator = new QSignalEventGenerator(q); + bool ok = QMetaObject::connect(sender, signalIndex, signalEventGenerator, + signalEventGenerator->metaObject()->methodOffset()); + if (!ok) { +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": FAILED to add signal transition from" << transition->sourceState() + << ": ( sender =" << sender << ", signal =" << (signal.mid(1)) + << ", targets =" << transition->targetStates() << ")"; +#endif + return; + } + } + ++connectedSignalIndexes[signalIndex]; + QSignalTransitionPrivate::get(transition)->signalIndex = signalIndex; +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": added signal transition from" << transition->sourceState() + << ": ( sender =" << sender << ", signal =" << (signal.mid(1)) + << ", targets =" << transition->targetStates() << ")"; +#endif +} + +void QStateMachinePrivate::unregisterSignalTransition(QSignalTransition *transition) +{ + int signalIndex = QSignalTransitionPrivate::get(transition)->signalIndex; + if (signalIndex == -1) + return; // not registered + QSignalTransitionPrivate::get(transition)->signalIndex = -1; + const QObject *sender = QSignalTransitionPrivate::get(transition)->sender; + QVector &connectedSignalIndexes = connections[sender]; + Q_ASSERT(connectedSignalIndexes.size() > signalIndex); + Q_ASSERT(connectedSignalIndexes.at(signalIndex) != 0); + if (--connectedSignalIndexes[signalIndex] == 0) { + Q_ASSERT(signalEventGenerator != 0); + QMetaObject::disconnect(sender, signalIndex, signalEventGenerator, + signalEventGenerator->metaObject()->methodOffset()); + int sum = 0; + for (int i = 0; i < connectedSignalIndexes.size(); ++i) + sum += connectedSignalIndexes.at(i); + if (sum == 0) + connections.remove(sender); + } +} + +void QStateMachinePrivate::unregisterAllTransitions() +{ + { + QList transitions = qFindChildren(rootState); + for (int i = 0; i < transitions.size(); ++i) + unregisterSignalTransition(transitions.at(i)); + } + { + QList transitions = qFindChildren(rootState); + for (int i = 0; i < transitions.size(); ++i) + unregisterEventTransition(transitions.at(i)); + } +} + +#ifndef QT_NO_STATEMACHINE_EVENTFILTER +void QStateMachinePrivate::registerEventTransition(QEventTransition *transition) +{ + Q_Q(QStateMachine); + if (QEventTransitionPrivate::get(transition)->registered) + return; + if (transition->eventType() >= QEvent::User) { + qWarning("QObject event transitions are not supported for custom types"); + return; + } + QObject *object = QEventTransitionPrivate::get(transition)->object; + if (!object) + return; + QObjectPrivate *od = QObjectPrivate::get(object); + if (!od->eventFilters.contains(q)) + object->installEventFilter(q); + ++qobjectEvents[object][transition->eventType()]; + QEventTransitionPrivate::get(transition)->registered = true; +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q << ": added event transition from" << transition->sourceState() + << ": ( object =" << object << ", event =" << transition->eventType() + << ", targets =" << transition->targetStates() << ")"; +#endif +} + +void QStateMachinePrivate::unregisterEventTransition(QEventTransition *transition) +{ + Q_Q(QStateMachine); + if (!QEventTransitionPrivate::get(transition)->registered) + return; + QObject *object = QEventTransitionPrivate::get(transition)->object; + QHash &events = qobjectEvents[object]; + Q_ASSERT(events.value(transition->eventType()) > 0); + if (--events[transition->eventType()] == 0) { + events.remove(transition->eventType()); + int sum = 0; + QHash::const_iterator it; + for (it = events.constBegin(); it != events.constEnd(); ++it) + sum += it.value(); + if (sum == 0) { + qobjectEvents.remove(object); + object->removeEventFilter(q); + } + } + QEventTransitionPrivate::get(transition)->registered = false; +} +#endif + +void QStateMachinePrivate::handleTransitionSignal(const QObject *sender, int signalIndex, + void **argv) +{ + const QVector &connectedSignalIndexes = connections[sender]; + Q_ASSERT(connectedSignalIndexes.at(signalIndex) != 0); + const QMetaObject *meta = sender->metaObject(); + QMetaMethod method = meta->method(signalIndex); + QList parameterTypes = method.parameterTypes(); + int argc = parameterTypes.count(); + QList vargs; + for (int i = 0; i < argc; ++i) { + int type = QMetaType::type(parameterTypes.at(i)); + vargs.append(QVariant(type, argv[i+1])); + } + +#ifdef QSTATEMACHINE_DEBUG + qDebug() << q_func() << ": sending signal event ( sender =" << sender + << ", signal =" << sender->metaObject()->method(signalIndex).signature() << ")"; +#endif + internalEventQueue.append(new QSignalEvent(sender, signalIndex, vargs)); + scheduleProcess(); +} + +/*! + Constructs a new state machine with the given \a parent. +*/ +QStateMachine::QStateMachine(QObject *parent) + : QObject(*new QStateMachinePrivate, parent) +{ +} + +/*! + \internal +*/ +QStateMachine::QStateMachine(QStateMachinePrivate &dd, QObject *parent) + : QObject(dd, parent) +{ +} + +/*! + Destroys this state machine. +*/ +QStateMachine::~QStateMachine() +{ +} + +namespace { + +class RootErrorState : public QAbstractState +{ +public: + RootErrorState(QState *parent) + : QAbstractState(parent) + { + setObjectName(QString::fromLatin1("DefaultErrorState")); + } + + void onEntry(QEvent *) + { + QAbstractStatePrivate *d = QAbstractStatePrivate::get(this); + QStateMachine *machine = d->machine(); + + qWarning("Unrecoverable error detected in running state machine: %s", + qPrintable(machine->errorString())); + } + + void onExit(QEvent *) {} +}; + +class RootState : public QState +{ +public: + RootState(QState *parent) + : QState(parent) + { + } + + void onEntry(QEvent *) {} + void onExit(QEvent *) {} +}; + +} // namespace + +/*! + Returns this state machine's root state. +*/ +QState *QStateMachine::rootState() const +{ + Q_D(const QStateMachine); + if (!d->rootState) { + const_cast(d)->rootState = new RootState(0); + const_cast(d)->initialErrorStateForRoot = new RootErrorState(d->rootState); + d->rootState->setParent(const_cast(this)); + d->rootState->setErrorState(d->initialErrorStateForRoot); + } + return d->rootState; +} + +/*! + Returns the error state of the state machine's root state. + + \sa QState::errorState() +*/ +QAbstractState *QStateMachine::errorState() const +{ + return rootState()->errorState(); +} + +/*! + Sets the error state of this state machine's root state to be \a state. When a running state + machine encounters an error which puts it in an undefined state, it will enter an error state + based on the context of the error that occurred. It will enter this state regardless of what + is currently in the event queue. + + If the erroneous state has an error state set, this will be entered by the machine. If no error + state has been set, the state machine will search the parent hierarchy recursively for an + error state. The error state of the root state can thus be seen as a global error state that + applies for the states for which a more specific error state has not been set. + + Before entering the error state, the state machine will set the error code returned by error() and + error message returned by errorString(). + + The default error state will print a warning to the console containing the information returned by + errorString(). By setting a new error state on either the state machine itself, or on specific + states, you can fine tune error handling in the state machine. + + If the root state's error state is set to 0, or if the error state selected by the machine itself + contains an error, the default error state will be used. + + \sa QState::setErrorState(), rootState() +*/ +void QStateMachine::setErrorState(QAbstractState *state) +{ + rootState()->setErrorState(state); +} + +/*! \enum QStateMachine::Error + + This enum type defines errors that can occur in the state machine at run time. When the state + machine encounters an unrecoverable error at run time, it will set the error code returned + by error(), the error message returned by errorString(), and enter an error state based on + the context of the error. + + \value NoError No error has occurred. + \value NoInitialStateError The machine has entered a QState with children which does not have an + initial state set. The context of this error is the state which is missing an initial + state. + \value NoDefaultStateInHistoryStateError The machine has entered a QHistoryState which does not have + a default state set. The context of this error is the QHistoryState which is missing a + default state. + \value NoCommonAncestorForTransitionError The machine has selected a transition whose source + and targets are not part of the same tree of states, and thus are not part of the same + state machine. Commonly, this could mean that one of the states has not been given + any parent or added to any machine. The context of this error is the source state of + the transition. + + \sa setErrorState() +*/ + +/*! + \enum QStateMachine::RestorePolicy + + This enum specifies the restore policy type. The restore policy + takes effect when the machine enters a state which sets one or more + properties. If the restore policy is set to RestoreProperties, + the state machine will save the original value of the property before the + new value is set. + + Later, when the machine either enters a state which does not set + a value for the given property, the property will automatically be restored + to its initial value. + + Only one initial value will be saved for any given property. If a value for a property has + already been saved by the state machine, it will not be overwritten until the property has been + successfully restored. + + \value DoNotRestoreProperties The state machine should not save the initial values of properties + and restore them later. + \value RestoreProperties The state machine should save the initial values of properties + and restore them later. + + \sa QStateMachine::globalRestorePolicy QState::assignProperty() +*/ + + +/*! + Returns the error code of the last error that occurred in the state machine. +*/ +QStateMachine::Error QStateMachine::error() const +{ + Q_D(const QStateMachine); + return d->error; +} + +/*! + Returns the error string of the last error that occurred in the state machine. +*/ +QString QStateMachine::errorString() const +{ + Q_D(const QStateMachine); + return d->errorString; +} + +/*! + Clears the error string and error code of the state machine. +*/ +void QStateMachine::clearError() +{ + Q_D(QStateMachine); + d->errorString.clear(); + d->error = NoError; +} + +/*! + Returns the restore policy of the state machine. + + \sa setGlobalRestorePolicy() +*/ +QStateMachine::RestorePolicy QStateMachine::globalRestorePolicy() const +{ + Q_D(const QStateMachine); + return d->globalRestorePolicy; +} + +/*! + Sets the restore policy of the state machine to \a restorePolicy. The default + restore policy is QAbstractState::DoNotRestoreProperties. + + \sa globalRestorePolicy() +*/ +void QStateMachine::setGlobalRestorePolicy(QStateMachine::RestorePolicy restorePolicy) +{ + Q_D(QStateMachine); + d->globalRestorePolicy = restorePolicy; +} + +/*! + Returns this state machine's initial state, or 0 if no initial state has + been set. +*/ +QAbstractState *QStateMachine::initialState() const +{ + Q_D(const QStateMachine); + if (!d->rootState) + return 0; + return d->rootState->initialState(); +} + +/*! + Sets this state machine's initial \a state. +*/ +void QStateMachine::setInitialState(QAbstractState *state) +{ + Q_D(QStateMachine); + if (!d->rootState) { + if (!state) + return; + rootState()->setInitialState(state); + } + d->rootState->setInitialState(state); +} + +/*! + Adds the given \a state to this state machine. The state becomes a top-level + state (i.e. a child of the rootState()). + + If the state is already in a different machine, it will first be removed + from its old machine, and then added to this machine. + + \sa removeState(), rootState(), setInitialState() +*/ +void QStateMachine::addState(QAbstractState *state) +{ + if (!state) { + qWarning("QStateMachine::addState: cannot add null state"); + return; + } + if (QAbstractStatePrivate::get(state)->machine() == this) { + qWarning("QStateMachine::addState: state has already been added to this machine"); + return; + } + state->setParent(rootState()); +} + +/*! + Removes the given \a state from this state machine. The state machine + releases ownership of the state. + + \sa addState() +*/ +void QStateMachine::removeState(QAbstractState *state) +{ + if (!state) { + qWarning("QStateMachine::removeState: cannot remove null state"); + return; + } + if (QAbstractStatePrivate::get(state)->machine() != this) { + qWarning("QStateMachine::removeState: state %p's machine (%p)" + " is different from this machine (%p)", + state, QAbstractStatePrivate::get(state)->machine(), this); + return; + } + state->setParent(0); +} + +/*! + Returns whether this state machine is running. + + start(), stop() +*/ +bool QStateMachine::isRunning() const +{ + Q_D(const QStateMachine); + return (d->state == QStateMachinePrivate::Running); +} + +/*! + Starts this state machine. The machine will reset its configuration and + transition to the initial state. When a final top-level state (QFinalState) + is entered, the machine will emit the finished() signal. + + \sa started(), finished(), stop(), initialState() +*/ +void QStateMachine::start() +{ + Q_D(QStateMachine); + + if (rootState()->initialState() == 0) { + qWarning("QStateMachine::start: No initial state set for machine. Refusing to start."); + return; + } + + switch (d->state) { + case QStateMachinePrivate::NotRunning: + d->state = QStateMachinePrivate::Starting; + QMetaObject::invokeMethod(this, "_q_start", Qt::QueuedConnection); + break; + case QStateMachinePrivate::Starting: + break; + case QStateMachinePrivate::Running: + qWarning("QStateMachine::start(): already running"); + break; + } +} + +/*! + Stops this state machine. The state machine will stop processing events and + then emit the stopped() signal. + + \sa stopped(), start() +*/ +void QStateMachine::stop() +{ + Q_D(QStateMachine); + switch (d->state) { + case QStateMachinePrivate::NotRunning: + break; + case QStateMachinePrivate::Starting: + // the machine will exit as soon as it enters the event processing loop + d->stop = true; + break; + case QStateMachinePrivate::Running: + d->stop = true; + d->scheduleProcess(); + break; + } +} + +/*! + Posts the given \a event for processing by this state machine, with a delay + of \a delay milliseconds. + + This function returns immediately. The event is added to the state machine's + event queue. Events are processed in the order posted. The state machine + takes ownership of the event and deletes it once it has been processed. + + You can only post events when the state machine is running. +*/ +void QStateMachine::postEvent(QEvent *event, int delay) +{ + Q_D(QStateMachine); + if (d->state != QStateMachinePrivate::Running) { + qWarning("QStateMachine::postEvent: cannot post event when the state machine is not running"); + return; + } +#ifdef QSTATEMACHINE_DEBUG + qDebug() << this << ": posting external event" << event << "with delay" << delay; +#endif + if (delay) { + int tid = startTimer(delay); + d->delayedEvents[tid] = event; + } else { + d->externalEventQueue.append(event); + d->scheduleProcess(); + } +} + +/*! + \internal + + Posts the given internal \a event for processing by this state machine. +*/ +void QStateMachine::postInternalEvent(QEvent *event) +{ + Q_D(QStateMachine); +#ifdef QSTATEMACHINE_DEBUG + qDebug() << this << ": posting internal event" << event; +#endif + d->internalEventQueue.append(event); + d->scheduleProcess(); +} + +/*! + \internal + + Returns the maximal consistent set of states (including parallel and final + states) that this state machine is currently in. If a state \c s is in the + configuration, it is always the case that the parent of \c s is also in + c. Note, however, that the rootState() is not an explicit member of the + configuration. +*/ +QSet QStateMachine::configuration() const +{ + Q_D(const QStateMachine); + return d->configuration; +} + +/*! + \fn QStateMachine::started() + + This signal is emitted when the state machine has entered its initial state + (QStateMachine::initialState). + + \sa QStateMachine::finished(), QStateMachine::start() +*/ + +/*! + \fn QStateMachine::finished() + + This signal is emitted when the state machine has reached a top-level final + state (QFinalState). + + \sa QStateMachine::started() +*/ + +/*! + \fn QStateMachine::stopped() + + This signal is emitted when the state machine has stopped. + + \sa QStateMachine::stop(), QStateMachine::finished() +*/ + +/*! + \reimp +*/ +bool QStateMachine::event(QEvent *e) +{ + Q_D(QStateMachine); + if (e->type() == QEvent::Timer) { + QTimerEvent *te = static_cast(e); + int tid = te->timerId(); + if (d->delayedEvents.contains(tid)) { + killTimer(tid); + QEvent *ee = d->delayedEvents.take(tid); + d->externalEventQueue.append(ee); + d->scheduleProcess(); + return true; + } + } else if (e->type() == QEvent::ChildAdded) { + QChildEvent *ce = static_cast(e); + if (QAbstractState *state = qobject_cast(ce->child())) { + if (state != rootState()) { + state->setParent(rootState()); + return true; + } + } + } + return QObject::event(e); +} + +#ifndef QT_NO_STATEMACHINE_EVENTFILTER +/*! + \reimp +*/ +bool QStateMachine::eventFilter(QObject *watched, QEvent *event) +{ + Q_D(QStateMachine); + Q_ASSERT(d->qobjectEvents.contains(watched)); + if (d->qobjectEvents[watched].contains(event->type())) + postEvent(new QWrappedEvent(watched, d->handler->cloneEvent(event))); + return false; +} +#endif + +/*! + \internal + + This function is called when the state machine is about to select + transitions based on the given \a event. + + The default implementation does nothing. +*/ +void QStateMachine::beginSelectTransitions(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \internal + + This function is called when the state machine has finished selecting + transitions based on the given \a event. + + The default implementation does nothing. +*/ +void QStateMachine::endSelectTransitions(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \internal + + This function is called when the state machine is about to do a microstep. + + The default implementation does nothing. +*/ +void QStateMachine::beginMicrostep(QEvent *event) +{ + Q_UNUSED(event); +} + +/*! + \internal + + This function is called when the state machine has finished doing a + microstep. + + The default implementation does nothing. +*/ +void QStateMachine::endMicrostep(QEvent *event) +{ + Q_UNUSED(event); +} + +#ifndef QT_NO_ANIMATION + +/*! + Returns whether animations are enabled for this state machine. +*/ +bool QStateMachine::animationsEnabled() const +{ + Q_D(const QStateMachine); + return d->animationsEnabled; +} + +/*! + Sets whether animations are \a enabled for this state machine. +*/ +void QStateMachine::setAnimationsEnabled(bool enabled) +{ + Q_D(QStateMachine); + d->animationsEnabled = enabled; +} + +/*! + Adds a default \a animation to be considered for any transition. +*/ +void QStateMachine::addDefaultAnimation(QAbstractAnimation *animation) +{ + Q_D(QStateMachine); + d->defaultAnimations.append(animation); +} + +/*! + Returns the list of default animations that will be considered for any transition. +*/ +QList QStateMachine::defaultAnimations() const +{ + Q_D(const QStateMachine); + return d->defaultAnimations; +} + +/*! + Removes \a animation from the list of default animations. +*/ +void QStateMachine::removeDefaultAnimation(QAbstractAnimation *animation) +{ + Q_D(QStateMachine); + d->defaultAnimations.removeAll(animation); +} + +#endif // QT_NO_ANIMATION + + +static const uint qt_meta_data_QSignalEventGenerator[] = { + + // content: + 2, // revision + 0, // classname + 0, 0, // classinfo + 1, 12, // methods + 0, 0, // properties + 0, 0, // enums/sets + 0, 0, // constructors + + // slots: signature, parameters, type, tag, flags + 23, 22, 22, 22, 0x0a, + + 0 // eod +}; + +static const char qt_meta_stringdata_QSignalEventGenerator[] = { + "QSignalEventGenerator\0\0execute()\0" +}; + +const QMetaObject QSignalEventGenerator::staticMetaObject = { + { &QObject::staticMetaObject, qt_meta_stringdata_QSignalEventGenerator, + qt_meta_data_QSignalEventGenerator, 0 } +}; + +const QMetaObject *QSignalEventGenerator::metaObject() const +{ + return &staticMetaObject; +} + +void *QSignalEventGenerator::qt_metacast(const char *_clname) +{ + if (!_clname) return 0; + if (!strcmp(_clname, qt_meta_stringdata_QSignalEventGenerator)) + return static_cast(const_cast< QSignalEventGenerator*>(this)); + return QObject::qt_metacast(_clname); +} + +int QSignalEventGenerator::qt_metacall(QMetaObject::Call _c, int _id, void **_a) +{ + _id = QObject::qt_metacall(_c, _id, _a); + if (_id < 0) + return _id; + if (_c == QMetaObject::InvokeMetaMethod) { + switch (_id) { + case 0: { +// ### in Qt 4.6 we can use QObject::senderSignalIndex() + int signalIndex = senderSignalIndex(this); + Q_ASSERT(signalIndex != -1); + QStateMachine *machine = qobject_cast(parent()); + QStateMachinePrivate::get(machine)->handleTransitionSignal(sender(), signalIndex, _a); + break; + } + default: ; + } + _id -= 1; + } + return _id; +} + +QSignalEventGenerator::QSignalEventGenerator(QStateMachine *parent) + : QObject(parent) +{ +} + +/*! + \class QSignalEvent + + \brief The QSignalEvent class represents a Qt signal event. + + \since 4.6 + \ingroup statemachine + + A signal event is generated by a QStateMachine in response to a Qt + signal. The QSignalTransition class provides a transition associated with a + signal event. QSignalEvent is part of \l{The State Machine Framework}. + + The sender() function returns the object that generated the signal. The + signalIndex() function returns the index of the signal. The arguments() + function returns the arguments of the signal. + + \sa QSignalTransition +*/ + +/*! + \internal + + Constructs a new QSignalEvent object with the given \a sender, \a + signalIndex and \a arguments. +*/ +QSignalEvent::QSignalEvent(const QObject *sender, int signalIndex, + const QList &arguments) + : QEvent(QEvent::Signal), m_sender(sender), + m_signalIndex(signalIndex), m_arguments(arguments) +{ +} + +/*! + Destroys this QSignalEvent. +*/ +QSignalEvent::~QSignalEvent() +{ +} + +/*! + \fn QSignalEvent::sender() const + + Returns the object that emitted the signal. + + \sa QObject::sender() +*/ + +/*! + \fn QSignalEvent::signalIndex() const + + Returns the index of the signal. + + \sa QMetaObject::indexOfSignal(), QMetaObject::method() +*/ + +/*! + \fn QSignalEvent::arguments() const + + Returns the arguments of the signal. +*/ + + +/*! + \class QWrappedEvent + + \brief The QWrappedEvent class holds a clone of an event associated with a QObject. + + \since 4.6 + \ingroup statemachine + + A wrapped event is generated by a QStateMachine in response to a Qt + event. The QEventTransition class provides a transition associated with a + such an event. QWrappedEvent is part of \l{The State Machine Framework}. + + The object() function returns the object that generated the event. The + event() function returns a clone of the original event. + + \sa QEventTransition +*/ + +/*! + \internal + + Constructs a new QWrappedEvent object with the given \a object + and \a event. +*/ +QWrappedEvent::QWrappedEvent(QObject *object, QEvent *event) + : QEvent(QEvent::Wrapped), m_object(object), m_event(event) +{ +} + +/*! + Destroys this QWrappedEvent. +*/ +QWrappedEvent::~QWrappedEvent() +{ +} + +/*! + \fn QWrappedEvent::object() const + + Returns the object that the event is associated with. +*/ + +/*! + \fn QWrappedEvent::event() const + + Returns a clone of the original event. +*/ + +QT_END_NAMESPACE + +#include "moc_qstatemachine.cpp" diff --git a/src/corelib/statemachine/qstatemachine.h b/src/corelib/statemachine/qstatemachine.h new file mode 100644 index 0000000..2a98a9a --- /dev/null +++ b/src/corelib/statemachine/qstatemachine.h @@ -0,0 +1,166 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSTATEMACHINE_H +#define QSTATEMACHINE_H + +#include + +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QEvent; +class QAbstractState; +class QState; + +class QStateMachinePrivate; +class QAbstractAnimation; +class QAbstractState; +class Q_CORE_EXPORT QStateMachine : public QObject +{ + Q_OBJECT + Q_PROPERTY(QState* rootState READ rootState) + Q_PROPERTY(QAbstractState* initialState READ initialState WRITE setInitialState) + Q_PROPERTY(QAbstractState* errorState READ errorState WRITE setErrorState) + Q_PROPERTY(QString errorString READ errorString) + Q_PROPERTY(RestorePolicy globalRestorePolicy READ globalRestorePolicy WRITE setGlobalRestorePolicy) + Q_ENUMS(RestorePolicy) +#ifndef QT_NO_ANIMATION + Q_PROPERTY(bool animationsEnabled READ animationsEnabled WRITE setAnimationsEnabled) +#endif +public: + enum RestorePolicy { + DoNotRestoreProperties, + RestoreProperties + }; + + enum Error { + NoError, + NoInitialStateError, + NoDefaultStateInHistoryStateError, + NoCommonAncestorForTransitionError + }; + + QStateMachine(QObject *parent = 0); + ~QStateMachine(); + + void addState(QAbstractState *state); + void removeState(QAbstractState *state); + + QState *rootState() const; + + QAbstractState *initialState() const; + void setInitialState(QAbstractState *state); + + QAbstractState *errorState() const; + void setErrorState(QAbstractState *state); + + Error error() const; + QString errorString() const; + void clearError(); + + bool isRunning() const; + +#ifndef QT_NO_ANIMATION + bool animationsEnabled() const; + void setAnimationsEnabled(bool enabled); + + void addDefaultAnimation(QAbstractAnimation *animation); + QList defaultAnimations() const; + void removeDefaultAnimation(QAbstractAnimation *animation); +#endif // QT_NO_ANIMATION + + QStateMachine::RestorePolicy globalRestorePolicy() const; + void setGlobalRestorePolicy(QStateMachine::RestorePolicy restorePolicy); + + void postEvent(QEvent *event, int delay = 0); + + QSet configuration() const; + +#ifndef QT_NO_STATEMACHINE_EVENTFILTER + bool eventFilter(QObject *watched, QEvent *event); +#endif + +public Q_SLOTS: + void start(); + void stop(); + +Q_SIGNALS: + void started(); + void stopped(); + void finished(); + +protected: + void postInternalEvent(QEvent *event); + + virtual void beginSelectTransitions(QEvent *event); + virtual void endSelectTransitions(QEvent *event); + + virtual void beginMicrostep(QEvent *event); + virtual void endMicrostep(QEvent *event); + + bool event(QEvent *e); + +protected: + QStateMachine(QStateMachinePrivate &dd, QObject *parent); + +private: + Q_DISABLE_COPY(QStateMachine) + Q_DECLARE_PRIVATE(QStateMachine) + Q_PRIVATE_SLOT(d_func(), void _q_start()) + Q_PRIVATE_SLOT(d_func(), void _q_process()) +#ifndef QT_NO_ANIMATION + Q_PRIVATE_SLOT(d_func(), void _q_animationFinished()) +#endif +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/qstatemachine_p.h b/src/corelib/statemachine/qstatemachine_p.h new file mode 100644 index 0000000..dfa5575 --- /dev/null +++ b/src/corelib/statemachine/qstatemachine_p.h @@ -0,0 +1,217 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSTATEMACHINE_P_H +#define QSTATEMACHINE_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include +#include +#include +#include +#include + +#include "qstate.h" +#include "qstate_p.h" + +QT_BEGIN_NAMESPACE + +class QEvent; +#ifndef QT_NO_STATEMACHINE_EVENTFILTER +class QEventTransition; +#endif +class QSignalEventGenerator; +class QSignalTransition; +class QAbstractState; +class QAbstractTransition; +class QState; + +#ifndef QT_NO_ANIMATION +class QAbstractAnimation; +#endif + +class QStateMachine; +class Q_CORE_EXPORT QStateMachinePrivate + : public QObjectPrivate +{ + Q_DECLARE_PUBLIC(QStateMachine) +public: + enum State { + NotRunning, + Starting, + Running + }; + enum StopProcessingReason { + EventQueueEmpty, + Finished, + Stopped + }; + + QStateMachinePrivate(); + ~QStateMachinePrivate(); + + static QStateMachinePrivate *get(QStateMachine *q); + + static QState *findLCA(const QList &states); + + static bool stateEntryLessThan(QAbstractState *s1, QAbstractState *s2); + static bool stateExitLessThan(QAbstractState *s1, QAbstractState *s2); + + QAbstractState *findErrorState(QAbstractState *context); + void setError(QStateMachine::Error error, QAbstractState *currentContext); + + // private slots + void _q_start(); + void _q_process(); +#ifndef QT_NO_ANIMATION + void _q_animationFinished(); +#endif + + void microstep(QEvent *event, const QList &transitionList); + bool isPreempted(const QAbstractState *s, const QSet &transitions) const; + QSet selectTransitions(QEvent *event) const; + QList exitStates(QEvent *event, const QList &transitionList); + void executeTransitionContent(QEvent *event, const QList &transitionList); + QList enterStates(QEvent *event, const QList &enabledTransitions); + void addStatesToEnter(QAbstractState *s, QState *root, + QSet &statesToEnter, + QSet &statesForDefaultEntry); + + void applyProperties(const QList &transitionList, + const QList &exitedStates, + const QList &enteredStates); + + bool isInFinalState(QAbstractState *s) const; + static bool isFinal(const QAbstractState *s); + static bool isParallel(const QAbstractState *s); + static bool isCompound(const QAbstractState *s); + static bool isAtomic(const QAbstractState *s); + static bool isDescendantOf(const QAbstractState *s, const QAbstractState *other); + static QList properAncestors(const QAbstractState *s, const QState *upperBound); + + void registerTransitions(QAbstractState *state); + void registerSignalTransition(QSignalTransition *transition); + void unregisterSignalTransition(QSignalTransition *transition); +#ifndef QT_NO_STATEMACHINE_EVENTFILTER + void registerEventTransition(QEventTransition *transition); + void unregisterEventTransition(QEventTransition *transition); +#endif + void unregisterTransition(QAbstractTransition *transition); + void unregisterAllTransitions(); + void handleTransitionSignal(const QObject *sender, int signalIndex, + void **args); + void scheduleProcess(); + + typedef QPair RestorableId; + QHash registeredRestorables; + void registerRestorable(QObject *object, const QByteArray &propertyName); + void unregisterRestorable(QObject *object, const QByteArray &propertyName); + bool hasRestorable(QObject *object, const QByteArray &propertyName) const; + QVariant restorableValue(QObject *object, const QByteArray &propertyName) const; + QList restorablesToPropertyList(const QHash &restorables) const; + + State state; + bool processing; + bool processingScheduled; + bool stop; + StopProcessingReason stopProcessingReason; + QState *rootState; + QSet configuration; + QList internalEventQueue; + QList externalEventQueue; + + QStateMachine::Error error; + QStateMachine::RestorePolicy globalRestorePolicy; + + QString errorString; + QSet pendingErrorStates; + QSet pendingErrorStatesForDefaultEntry; + QAbstractState *initialErrorStateForRoot; + +#ifndef QT_NO_ANIMATION + bool animationsEnabled; + + QPair, QList > + initializeAnimation(QAbstractAnimation *abstractAnimation, + const QPropertyAssignment &prop); + + QHash > animationsForState; + QHash propertyForAnimation; + QHash stateForAnimation; + QSet resetAnimationEndValues; + + QList defaultAnimations; + QMultiHash defaultAnimationsForSource; + QMultiHash defaultAnimationsForTarget; + +#endif // QT_NO_ANIMATION + + QSignalEventGenerator *signalEventGenerator; + + QHash > connections; +#ifndef QT_NO_STATEMACHINE_EVENTFILTER + QHash > qobjectEvents; +#endif + QHash delayedEvents; + + typedef QEvent* (*f_cloneEvent)(QEvent*); + struct Handler { + f_cloneEvent cloneEvent; + }; + + static const Handler *handler; +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/corelib/statemachine/qwrappedevent.h b/src/corelib/statemachine/qwrappedevent.h new file mode 100644 index 0000000..b01c608 --- /dev/null +++ b/src/corelib/statemachine/qwrappedevent.h @@ -0,0 +1,76 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QWRAPPEDEVENT_H +#define QWRAPPEDEVENT_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QObject; + +class Q_CORE_EXPORT QWrappedEvent : public QEvent +{ +public: + QWrappedEvent(QObject *object, QEvent *event); + ~QWrappedEvent(); + + inline QObject *object() const { return m_object; } + inline QEvent *event() const { return m_event; } + +private: + QObject *m_object; + QEvent *m_event; + +private: + Q_DISABLE_COPY(QWrappedEvent) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/statemachine/statemachine.pri b/src/corelib/statemachine/statemachine.pri new file mode 100644 index 0000000..5b19bc1 --- /dev/null +++ b/src/corelib/statemachine/statemachine.pri @@ -0,0 +1,30 @@ +HEADERS += $$PWD/qstatemachine.h \ + $$PWD/qstatemachine_p.h \ + $$PWD/qsignaleventgenerator_p.h \ + $$PWD/qabstractstate.h \ + $$PWD/qabstractstate_p.h \ + $$PWD/qstate.h \ + $$PWD/qstate_p.h \ + $$PWD/qfinalstate.h \ + $$PWD/qhistorystate.h \ + $$PWD/qhistorystate_p.h \ + $$PWD/qabstracttransition.h \ + $$PWD/qabstracttransition_p.h \ + $$PWD/qsignalevent.h \ + $$PWD/qsignaltransition.h \ + $$PWD/qsignaltransition_p.h + +SOURCES += $$PWD/qstatemachine.cpp \ + $$PWD/qabstractstate.cpp \ + $$PWD/qstate.cpp \ + $$PWD/qfinalstate.cpp \ + $$PWD/qhistorystate.cpp \ + $$PWD/qabstracttransition.cpp \ + $$PWD/qsignaltransition.cpp + +!contains(DEFINES, QT_NO_STATEMACHINE_EVENTFILTER) { +HEADERS += $$PWD/qwrappedevent.h \ + $$PWD/qeventtransition.h \ + $$PWD/qeventtransition_p.h +SOURCES += $$PWD/qeventtransition.cpp +} diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp new file mode 100644 index 0000000..2b027fc --- /dev/null +++ b/src/corelib/tools/qeasingcurve.cpp @@ -0,0 +1,846 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +/* + +| *property* | *Used for type* | +| period | QEasingCurve::{In,Out,InOut,OutIn}Elastic | +| amplitude | QEasingCurve::{In,Out,InOut,OutIn}Bounce, QEasingCurve::{In,Out,InOut,OutIn}Elastic | +| overshoot | QEasingCurve::{In,Out,InOut,OutIn}Back | + +*/ + + + + +/*! + \class QEasingCurve + \since 4.6 + \ingroup animation + \brief The QEasingCurve class provides easing curves for controlling animation. + + Easing curves describe a function that controls how the speed of the interpolation + between 0 and 1 should be. Easing curves allow transitions from + one value to another to appear more natural than a simple constant speed would allow. + The QEasingCurve class is usually used in conjunction with the QAnimation class, + but can be used on its own. + + To calculate the speed of the interpolation, the easing curve provides the function + valueForProgress(), where the \a progress argument specifies the progress of the + interpolation: 0 is the start value of the interpolation, 1 is the end value of the + interpolation. The returned value is the effective progress of the interpolation. + If the returned value is the same as the input value for all input values the easing + curve is a linear curve. This is the default behaviour. + + For example, + \code + QEasingCurve easing(QEasingCurve::InOutQuad); + + for(qreal t = 0.0; t < 1.0; t+=0.1) + qWarning() << "Effective progress" << t << " is + << easing.valueForProgress(t); + \endcode + will print the effective progress of the interpolation between 0 and 1. + + When using a QAnimation, the easing curve will be used to control the + progress of the interpolation between startValue and endValue: + \code + QAnimation animation; + animation.setStartValue(0); + animation.setEndValue(1000); + animation.setDuration(1000); + animation.setEasingCurve(QEasingCurve::InOutQuad); + \endcode + */ + +/*! + \enum QEasingCurve::Type + + The type of easing curve. + + \value Linear \inlineimage qeasingcurve-linear.png + \br + Easing equation function for a simple linear tweening, + with no easing. + \value InQuad \inlineimage qeasingcurve-inquad.png + \br + Easing equation function for a quadratic (t^2) easing + in: accelerating from zero velocity. + \value OutQuad \inlineimage qeasingcurve-outquad.png + \br + Easing equation function for a quadratic (t^2) easing + out: decelerating to zero velocity. + \value InOutQuad \inlineimage qeasingcurve-inoutquad.png + \br + Easing equation function for a quadratic (t^2) easing + in/out: acceleration until halfway, then deceleration. + \value OutInQuad \inlineimage qeasingcurve-outinquad.png + \br + Easing equation function for a quadratic (t^2) easing + out/in: deceleration until halfway, then acceleration. + \value InCubic \inlineimage qeasingcurve-incubic.png + \br + Easing equation function for a cubic (t^3) easing + in: accelerating from zero velocity. + \value OutCubic \inlineimage qeasingcurve-outcubic.png + \br + Easing equation function for a cubic (t^3) easing + out: decelerating from zero velocity. + \value InOutCubic \inlineimage qeasingcurve-inoutcubic.png + \br + Easing equation function for a cubic (t^3) easing + in/out: acceleration until halfway, then deceleration. + \value OutInCubic \inlineimage qeasingcurve-outincubic.png + \br + Easing equation function for a cubic (t^3) easing + out/in: deceleration until halfway, then acceleration. + \value InQuart \inlineimage qeasingcurve-inquart.png + \br + Easing equation function for a quartic (t^4) easing + in: accelerating from zero velocity. + \value OutQuart \inlineimage qeasingcurve-outquart.png + \br + Easing equation function for a quartic (t^4) easing + out: decelerating from zero velocity. + \value InOutQuart \inlineimage qeasingcurve-inoutquart.png + \br + Easing equation function for a quartic (t^4) easing + in/out: acceleration until halfway, then deceleration. + \value OutInQuart \inlineimage qeasingcurve-outinquart.png + \br + Easing equation function for a quartic (t^4) easing + out/in: deceleration until halfway, then acceleration. + \value InQuint \inlineimage qeasingcurve-inquint.png + \br + Easing equation function for a quintic (t^5) easing + in: accelerating from zero velocity. + \value OutQuint \inlineimage qeasingcurve-outquint.png + \br + Easing equation function for a quintic (t^5) easing + out: decelerating from zero velocity. + \value InOutQuint \inlineimage qeasingcurve-inoutquint.png + \br + Easing equation function for a quintic (t^5) easing + in/out: acceleration until halfway, then deceleration. + \value OutInQuint \inlineimage qeasingcurve-outinquint.png + \br + Easing equation function for a quintic (t^5) easing + out/in: deceleration until halfway, then acceleration. + \value InSine \inlineimage qeasingcurve-insine.png + \br + Easing equation function for a sinusoidal (sin(t)) easing + in: accelerating from zero velocity. + \value OutSine \inlineimage qeasingcurve-outsine.png + \br + Easing equation function for a sinusoidal (sin(t)) easing + out: decelerating from zero velocity. + \value InOutSine \inlineimage qeasingcurve-inoutsine.png + \br + Easing equation function for a sinusoidal (sin(t)) easing + in/out: acceleration until halfway, then deceleration. + \value OutInSine \inlineimage qeasingcurve-outinsine.png + \br + Easing equation function for a sinusoidal (sin(t)) easing + out/in: deceleration until halfway, then acceleration. + \value InExpo \inlineimage qeasingcurve-inexpo.png + \br + Easing equation function for an exponential (2^t) easing + in: accelerating from zero velocity. + \value OutExpo \inlineimage qeasingcurve-outexpo.png + \br + Easing equation function for an exponential (2^t) easing + out: decelerating from zero velocity. + \value InOutExpo \inlineimage qeasingcurve-inoutexpo.png + \br + Easing equation function for an exponential (2^t) easing + in/out: acceleration until halfway, then deceleration. + \value OutInExpo \inlineimage qeasingcurve-outinexpo.png + \br + Easing equation function for an exponential (2^t) easing + out/in: deceleration until halfway, then acceleration. + \value InCirc \inlineimage qeasingcurve-incirc.png + \br + Easing equation function for a circular (sqrt(1-t^2)) easing + in: accelerating from zero velocity. + \value OutCirc \inlineimage qeasingcurve-outcirc.png + \br + Easing equation function for a circular (sqrt(1-t^2)) easing + out: decelerating from zero velocity. + \value InOutCirc \inlineimage qeasingcurve-inoutcirc.png + \br + Easing equation function for a circular (sqrt(1-t^2)) easing + in/out: acceleration until halfway, then deceleration. + \value OutInCirc \inlineimage qeasingcurve-outincirc.png + \br + Easing equation function for a circular (sqrt(1-t^2)) easing + out/in: deceleration until halfway, then acceleration. + \value InElastic \inlineimage qeasingcurve-inelastic.png + \br + Easing equation function for an elastic + (exponentially decaying sine wave) easing in: + accelerating from zero velocity. The peak amplitude + can be set with the \e amplitude parameter, and the + period of decay by the \e period parameter. + \value OutElastic \inlineimage qeasingcurve-outelastic.png + \br + Easing equation function for an elastic + (exponentially decaying sine wave) easing out: + decelerating from zero velocity. The peak amplitude + can be set with the \e amplitude parameter, and the + period of decay by the \e period parameter. + \value InOutElastic \inlineimage qeasingcurve-inoutelastic.png + \br + Easing equation function for an elastic + (exponentially decaying sine wave) easing in/out: + acceleration until halfway, then deceleration. + \value OutInElastic \inlineimage qeasingcurve-outinelastic.png + \br + Easing equation function for an elastic + (exponentially decaying sine wave) easing out/in: + deceleration until halfway, then acceleration. + \value InBack \inlineimage qeasingcurve-inback.png + \br + Easing equation function for a back (overshooting + cubic easing: (s+1)*t^3 - s*t^2) easing in: + accelerating from zero velocity. + \value OutBack \inlineimage qeasingcurve-outback.png + \br + Easing equation function for a back (overshooting + cubic easing: (s+1)*t^3 - s*t^2) easing out: + decelerating from zero velocity. + \value InOutBack \inlineimage qeasingcurve-inoutback.png + \br + Easing equation function for a back (overshooting + cubic easing: (s+1)*t^3 - s*t^2) easing in/out: + acceleration until halfway, then deceleration. + \value OutInBack \inlineimage qeasingcurve-outinback.png + \br + Easing equation function for a back (overshooting + cubic easing: (s+1)*t^3 - s*t^2) easing out/in: + deceleration until halfway, then acceleration. + \value InBounce \inlineimage qeasingcurve-inbounce.png + \br + Easing equation function for a bounce (exponentially + decaying parabolic bounce) easing in: accelerating + from zero velocity. + \value OutBounce \inlineimage qeasingcurve-outbounce.png + \br + Easing equation function for a bounce (exponentially + decaying parabolic bounce) easing out: decelerating + from zero velocity. + \value InOutBounce \inlineimage qeasingcurve-inoutbounce.png + \br + Easing equation function for a bounce (exponentially + decaying parabolic bounce) easing in/out: + acceleration until halfway, then deceleration. + \value OutInBounce \inlineimage qeasingcurve-outinbounce.png + \br + Easing equation function for a bounce (exponentially + decaying parabolic bounce) easing out/in: + deceleration until halfway, then acceleration. + \omitvalue InCurve + \omitvalue OutCurve + \omitvalue SineCurve + \omitvalue CosineCurve + \value Custom This is returned if the user have specified a custom curve type with setCustomType(). Note that you cannot call setType() with this value, but type() can return it. + \omitvalue NCurveTypes +*/ + +/*! + \typedef QEasingCurve::EasingFunction + + This is a typedef for a pointer to a function with the following + signature: + + \snippet doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp 0 +*/ + +#include "qeasingcurve.h" + +#ifndef QT_NO_DEBUG_STREAM +#include +#include +#endif + +QT_BEGIN_NAMESPACE + +static bool isConfigFunction(QEasingCurve::Type type) +{ + return type >= QEasingCurve::InElastic + && type <= QEasingCurve::OutInBounce; +} + +class QEasingCurveFunction +{ +public: + enum Type { In, Out, InOut, OutIn }; + + QEasingCurveFunction(QEasingCurveFunction::Type type = In, qreal period = 0.3, qreal amplitude = 1.0, + qreal overshoot = 1.70158f) + : _t(type), _p(period), _a(amplitude), _o(overshoot) + { } + virtual ~QEasingCurveFunction() {} + virtual qreal value(qreal t); + virtual QEasingCurveFunction *copy() const; + bool operator==(const QEasingCurveFunction& other); + + Type _t; + qreal _p; + qreal _a; + qreal _o; +}; + +qreal QEasingCurveFunction::value(qreal t) +{ + return t; +} + +QEasingCurveFunction *QEasingCurveFunction::copy() const +{ + return new QEasingCurveFunction(_t, _p, _a, _o); +} + +bool QEasingCurveFunction::operator==(const QEasingCurveFunction& other) +{ + return _t == other._t && + _p == other._p && + _a == other._a && + _o == other._o; +} + +QT_BEGIN_INCLUDE_NAMESPACE +#include "../../3rdparty/easing/easing.cpp" +QT_END_INCLUDE_NAMESPACE + +class QEasingCurvePrivate +{ +public: + QEasingCurvePrivate() + : type(QEasingCurve::Linear), + config(0), + func(&easeNone) + { } + ~QEasingCurvePrivate() { delete config; } + void setType_helper(QEasingCurve::Type); + + QEasingCurve::Type type; + QEasingCurveFunction *config; + QEasingCurve::EasingFunction func; +}; + +struct ElasticEase : public QEasingCurveFunction +{ + ElasticEase(Type type) + : QEasingCurveFunction(type, qreal(0.3), qreal(1.0)) + { } + + QEasingCurveFunction *copy() const + { + ElasticEase *rv = new ElasticEase(_t); + rv->_p = _p; + rv->_a = _a; + return rv; + } + + qreal value(qreal t) + { + qreal p = (_p < 0) ? 0.3f : _p; + qreal a = (_a < 0) ? 1.0f : _a; + switch(_t) { + case In: + return easeInElastic(t, a, p); + case Out: + return easeOutElastic(t, a, p); + case InOut: + return easeInOutElastic(t, a, p); + case OutIn: + return easeOutInElastic(t, a, p); + default: + return t; + } + } +}; + +struct BounceEase : public QEasingCurveFunction +{ + BounceEase(Type type) + : QEasingCurveFunction(type, 0.3f, 1.0f) + { } + + QEasingCurveFunction *copy() const + { + BounceEase *rv = new BounceEase(_t); + rv->_a = _a; + return rv; + } + + qreal value(qreal t) + { + qreal a = (_a < 0) ? 1.0f : _a; + switch(_t) { + case In: + return easeInBounce(t, a); + case Out: + return easeOutBounce(t, a); + case InOut: + return easeInOutBounce(t, a); + case OutIn: + return easeOutInBounce(t, a); + default: + return t; + } + } +}; + +struct BackEase : public QEasingCurveFunction +{ + BackEase(Type type) + : QEasingCurveFunction(type, 0.3f, 1.0f, 1.70158f) + { } + + QEasingCurveFunction *copy() const + { + BackEase *rv = new BackEase(_t); + rv->_o = _o; + return rv; + } + + qreal value(qreal t) + { + qreal o = (_o < 0) ? 1.70158f : _o; + switch(_t) { + case In: + return easeInBack(t, o); + case Out: + return easeOutBack(t, o); + case InOut: + return easeInOutBack(t, o); + case OutIn: + return easeOutInBack(t, o); + default: + return t; + } + } +}; + +static QEasingCurve::EasingFunction curveToFunc(QEasingCurve::Type curve) +{ + switch(curve) { + case QEasingCurve::Linear: + return &easeNone; + case QEasingCurve::InQuad: + return &easeInQuad; + case QEasingCurve::OutQuad: + return &easeOutQuad; + case QEasingCurve::InOutQuad: + return &easeInOutQuad; + case QEasingCurve::OutInQuad: + return &easeOutInQuad; + case QEasingCurve::InCubic: + return &easeInCubic; + case QEasingCurve::OutCubic: + return &easeOutCubic; + case QEasingCurve::InOutCubic: + return &easeInOutCubic; + case QEasingCurve::OutInCubic: + return &easeOutInCubic; + case QEasingCurve::InQuart: + return &easeInQuart; + case QEasingCurve::OutQuart: + return &easeOutQuart; + case QEasingCurve::InOutQuart: + return &easeInOutQuart; + case QEasingCurve::OutInQuart: + return &easeOutInQuart; + case QEasingCurve::InQuint: + return &easeInQuint; + case QEasingCurve::OutQuint: + return &easeOutQuint; + case QEasingCurve::InOutQuint: + return &easeInOutQuint; + case QEasingCurve::OutInQuint: + return &easeOutInQuint; + case QEasingCurve::InSine: + return &easeInSine; + case QEasingCurve::OutSine: + return &easeOutSine; + case QEasingCurve::InOutSine: + return &easeInOutSine; + case QEasingCurve::OutInSine: + return &easeOutInSine; + case QEasingCurve::InExpo: + return &easeInExpo; + case QEasingCurve::OutExpo: + return &easeOutExpo; + case QEasingCurve::InOutExpo: + return &easeInOutExpo; + case QEasingCurve::OutInExpo: + return &easeOutInExpo; + case QEasingCurve::InCirc: + return &easeInCirc; + case QEasingCurve::OutCirc: + return &easeOutCirc; + case QEasingCurve::InOutCirc: + return &easeInOutCirc; + case QEasingCurve::OutInCirc: + return &easeOutInCirc; + // Internal for, compatibility with QTimeLine only ?? + case QEasingCurve::InCurve: + return &easeInCurve; + case QEasingCurve::OutCurve: + return &easeOutCurve; + case QEasingCurve::SineCurve: + return &easeSineCurve; + case QEasingCurve::CosineCurve: + return &easeCosineCurve; + default: + return 0; + }; +} + +static QEasingCurveFunction *curveToFunctionObject(QEasingCurve::Type type) +{ + QEasingCurveFunction *curveFunc = 0; + switch(type) { + case QEasingCurve::InElastic: + curveFunc = new ElasticEase(ElasticEase::In); + break; + case QEasingCurve::OutElastic: + curveFunc = new ElasticEase(ElasticEase::Out); + break; + case QEasingCurve::InOutElastic: + curveFunc = new ElasticEase(ElasticEase::InOut); + break; + case QEasingCurve::OutInElastic: + curveFunc = new ElasticEase(ElasticEase::OutIn); + break; + case QEasingCurve::OutBounce: + curveFunc = new BounceEase(BounceEase::Out); + break; + case QEasingCurve::InBounce: + curveFunc = new BounceEase(BounceEase::In); + break; + case QEasingCurve::OutInBounce: + curveFunc = new BounceEase(BounceEase::OutIn); + break; + case QEasingCurve::InOutBounce: + curveFunc = new BounceEase(BounceEase::InOut); + break; + case QEasingCurve::InBack: + curveFunc = new BackEase(BackEase::In); + break; + case QEasingCurve::OutBack: + curveFunc = new BackEase(BackEase::Out); + break; + case QEasingCurve::InOutBack: + curveFunc = new BackEase(BackEase::InOut); + break; + case QEasingCurve::OutInBack: + curveFunc = new BackEase(BackEase::OutIn); + break; + default: + curveFunc = new QEasingCurveFunction(QEasingCurveFunction::In, 0.3f, 1.0f, 1.70158f); // ### + } + + return curveFunc; +} + +/*! + Constructs an easing curve of the given \a type. + */ +QEasingCurve::QEasingCurve(Type type) + : d_ptr(new QEasingCurvePrivate) +{ + setType(type); +} + +/*! + Construct a copy of \a other. + */ +QEasingCurve::QEasingCurve(const QEasingCurve &other) +: d_ptr(new QEasingCurvePrivate) +{ + // ### non-atomic, requires malloc on shallow copy + *d_ptr = *other.d_ptr; + if(other.d_ptr->config) + d_ptr->config = other.d_ptr->config->copy(); +} + +/*! + Destructor. + */ + +QEasingCurve::~QEasingCurve() +{ + delete d_ptr; +} + +/*! + Copy \a other. + */ +QEasingCurve &QEasingCurve::operator=(const QEasingCurve &other) +{ + // ### non-atomic, requires malloc on shallow copy + if (d_ptr->config) { + delete d_ptr->config; + d_ptr->config = 0; + } + + *d_ptr = *other.d_ptr; + if(other.d_ptr->config) + d_ptr->config = other.d_ptr->config->copy(); + + return *this; +} + +/*! + Compare this easing curve with \a other and returns true if they are + equal. It will also compare the properties of a curve. + */ +bool QEasingCurve::operator==(const QEasingCurve &other) const +{ + bool res = d_ptr->func == other.d_ptr->func + && d_ptr->type == other.d_ptr->type; + if (res && d_ptr->config && other.d_ptr->config) { + // catch the config content + res = d_ptr->config->operator==(*(other.d_ptr->config)); + } + return res; +} + +/*! + \fn bool QEasingCurve::operator!=(const QEasingCurve &other) const + Compare this easing curve with \a other and returns true if they are not equal. + It will also compare the properties of a curve. + + \sa operator==() +*/ + +/*! + Returns the amplitude. This is not applicable for all curve types. + It is only applicable for bounce and elastic curves (curves of type() + QEasingCurve::InBounce, QEasingCurve::OutBounce, QEasingCurve::InOutBounce, + QEasingCurve::OutInBounce, QEasingCurve::InElastic, QEasingCurve::OutElastic, + QEasingCurve::InOutElastic or QEasingCurve::OutInElastic). + */ +qreal QEasingCurve::amplitude() const +{ + return d_ptr->config ? d_ptr->config->_a : 1.0; +} + +/*! + Sets the amplitude to \a amplitude. + + This will set the amplitude of the bounce or the amplitude of the + elastic "spring" effect. The higher the number, the higher the amplitude. + \sa amplitude() +*/ +void QEasingCurve::setAmplitude(qreal amplitude) +{ + if (!d_ptr->config) + d_ptr->config = curveToFunctionObject(d_ptr->type); + d_ptr->config->_a = amplitude; +} + +/*! + Returns the period. This is not applicable for all curve types. + It is only applicable if type() is QEasingCurve::InElastic, QEasingCurve::OutElastic, + QEasingCurve::InOutElastic or QEasingCurve::OutInElastic. + */ +qreal QEasingCurve::period() const +{ + return d_ptr->config ? d_ptr->config->_p : 0.3; +} + +/*! + Sets the period to \a period. + Setting a small period value will give a high frequency of the curve. A + large period will give it a small frequency. + + \sa period() +*/ +void QEasingCurve::setPeriod(qreal period) +{ + if (!d_ptr->config) + d_ptr->config = curveToFunctionObject(d_ptr->type); + d_ptr->config->_p = period; +} + +/*! + Returns the overshoot. This is not applicable for all curve types. + It is only applicable if type() is QEasingCurve::InBack, QEasingCurve::OutBack, + QEasingCurve::InOutBack or QEasingCurve::OutInBack. + */ +qreal QEasingCurve::overshoot() const +{ + return d_ptr->config ? d_ptr->config->_o : 1.70158f; +} + +/*! + Sets the overshoot to \a overshoot. + + 0 produces no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent. + + \sa overshoot() +*/ +void QEasingCurve::setOvershoot(qreal overshoot) +{ + if (!d_ptr->config) + d_ptr->config = curveToFunctionObject(d_ptr->type); + d_ptr->config->_o = overshoot; +} + +/*! + Returns the type of the easing curve. +*/ +QEasingCurve::Type QEasingCurve::type() const +{ + return d_ptr->type; +} + +void QEasingCurvePrivate::setType_helper(QEasingCurve::Type newType) +{ + qreal amp = -1.0; + qreal period = -1.0; + qreal overshoot = -1.0; + + if (config) { + amp = config->_a; + period = config->_p; + overshoot = config->_o; + delete config; + config = 0; + } + + if (isConfigFunction(newType) || (amp != -1.0) || (period != -1.0) || (overshoot != -1.0)) { + config = curveToFunctionObject(newType); + if (amp != -1.0) + config->_a = amp; + if (period != -1.0) + config->_p = period; + if (overshoot != -1.0) + config->_o = overshoot; + func = 0; + } else if (newType != QEasingCurve::Custom) { + func = curveToFunc(newType); + } + Q_ASSERT((func == 0) == (config != 0)); + type = newType; +} + +/*! + Sets the type of the easing curve to \a type. +*/ +void QEasingCurve::setType(Type type) +{ + if (d_ptr->type == type) + return; + if (type < Linear || type >= NCurveTypes - 1) { + qWarning("QEasingCurve: Invalid curve type %d", type); + return; + } + + d_ptr->setType_helper(type); +} + +/*! + Sets a custom easing curve that is defined by the user in the function \a func. + The signature of the function is qreal myEasingFunction(qreal progress), + where \e progress and the return value is considered to be normalized between 0 and 1. + (In some cases the return value can be outside that range) + After calling this function type() will return QEasingCurve::Custom. + \a func cannot be zero. + + \sa customType() + \sa valueForProgress() +*/ +void QEasingCurve::setCustomType(EasingFunction func) +{ + if (!func) { + qWarning("Function pointer must not be null"); + return; + } + d_ptr->func = func; + d_ptr->setType_helper(Custom); +} + +/*! + Returns the function pointer to the custom easing curve. + If type() does not return QEasingCurve::Custom, this function + will return 0. +*/ +QEasingCurve::EasingFunction QEasingCurve::customType() const +{ + return d_ptr->type == Custom ? d_ptr->func : 0; +} + +/*! + Return the effective progress for the easing curve at \a progress. + While \a progress must be between 0 and 1, the returned effective progress + can be outside those bounds. For instance, QEasingCurve::InBack will + return negative values in the beginning of the function. + */ +qreal QEasingCurve::valueForProgress(qreal progress) const +{ + progress = qBound(0, progress, 1); + if (d_ptr->func) + return d_ptr->func(progress); + else if (d_ptr->config) + return d_ptr->config->value(progress); + else + return progress; +} + +#ifndef QT_NO_DEBUG_STREAM +QDebug operator<<(QDebug debug, const QEasingCurve &item) +{ + debug << "type:" << item.d_ptr->type + << "func:" << item.d_ptr->func; + if (item.d_ptr->config) { + debug << QString::fromAscii("period:%1").arg(item.d_ptr->config->_p, 0, 'f', 20) + << QString::fromAscii("amp:%1").arg(item.d_ptr->config->_a, 0, 'f', 20) + << QString::fromAscii("overshoot:%1").arg(item.d_ptr->config->_o, 0, 'f', 20); + } + return debug; +} +#endif + +QT_END_NAMESPACE diff --git a/src/corelib/tools/qeasingcurve.h b/src/corelib/tools/qeasingcurve.h new file mode 100644 index 0000000..a240bc0 --- /dev/null +++ b/src/corelib/tools/qeasingcurve.h @@ -0,0 +1,114 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QEASINGCURVE_H +#define QEASINGCURVE_H + +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QEasingCurvePrivate; +class Q_CORE_EXPORT QEasingCurve +{ + Q_GADGET + Q_ENUMS(Type) +public: + enum Type { + Linear, + InQuad, OutQuad, InOutQuad, OutInQuad, + InCubic, OutCubic, InOutCubic, OutInCubic, + InQuart, OutQuart, InOutQuart, OutInQuart, + InQuint, OutQuint, InOutQuint, OutInQuint, + InSine, OutSine, InOutSine, OutInSine, + InExpo, OutExpo, InOutExpo, OutInExpo, + InCirc, OutCirc, InOutCirc, OutInCirc, + InElastic, OutElastic, InOutElastic, OutInElastic, + InBack, OutBack, InOutBack, OutInBack, + InBounce, OutBounce, InOutBounce, OutInBounce, + InCurve, OutCurve, SineCurve, CosineCurve, + Custom, NCurveTypes + }; + + QEasingCurve(Type type = Linear); + QEasingCurve(const QEasingCurve &other); + ~QEasingCurve(); + + QEasingCurve &operator=(const QEasingCurve &other); + bool operator==(const QEasingCurve &other) const; + inline bool operator!=(const QEasingCurve &other) const + { return !(this->operator==(other)); } + + qreal amplitude() const; + void setAmplitude(qreal amplitude); + + qreal period() const; + void setPeriod(qreal period); + + qreal overshoot() const; + void setOvershoot(qreal overshoot); + + Type type() const; + void setType(Type type); + typedef qreal (*EasingFunction)(qreal progress); + void setCustomType(EasingFunction func); + EasingFunction customType() const; + + qreal valueForProgress(qreal progress) const; +private: + QEasingCurvePrivate *d_ptr; + friend Q_CORE_EXPORT QDebug operator<<(QDebug debug, const QEasingCurve &item); +}; + +#ifndef QT_NO_DEBUG_STREAM +Q_CORE_EXPORT QDebug operator<<(QDebug debug, const QEasingCurve &item); +#endif + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/corelib/tools/qtimeline.cpp b/src/corelib/tools/qtimeline.cpp index 3a03558..ee4f73c 100644 --- a/src/corelib/tools/qtimeline.cpp +++ b/src/corelib/tools/qtimeline.cpp @@ -48,20 +48,6 @@ QT_BEGIN_NAMESPACE -static const qreal pi = qreal(3.14159265359); -static const qreal halfPi = pi / qreal(2.0); - - -static inline qreal qt_sinProgress(qreal value) -{ - return qSin((value * pi) - halfPi) / 2 + qreal(0.5); -} - -static inline qreal qt_smoothBeginEndMixFactor(qreal value) -{ - return qMin(qMax(1 - value * 2 + qreal(0.3), qreal(0.0)), qreal(1.0)); -} - class QTimeLinePrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QTimeLine) @@ -70,7 +56,7 @@ public: : startTime(0), duration(1000), startFrame(0), endFrame(0), updateInterval(1000 / 25), totalLoopCount(1), currentLoopCount(0), currentTime(0), timerId(0), - direction(QTimeLine::Forward), curveShape(QTimeLine::EaseInOutCurve), + direction(QTimeLine::Forward), easingCurve(QEasingCurve::InOutSine), state(QTimeLine::NotRunning) { } @@ -88,7 +74,7 @@ public: QTime timer; QTimeLine::Direction direction; - QTimeLine::CurveShape curveShape; + QEasingCurve easingCurve; QTimeLine::State state; inline void setState(QTimeLine::State newState) { @@ -523,12 +509,68 @@ void QTimeLine::setUpdateInterval(int interval) QTimeLine::CurveShape QTimeLine::curveShape() const { Q_D(const QTimeLine); - return d->curveShape; + switch (d->easingCurve.type()) { + default: + case QEasingCurve::InOutSine: + return EaseInOutCurve; + case QEasingCurve::InCurve: + return EaseInCurve; + case QEasingCurve::OutCurve: + return EaseOutCurve; + case QEasingCurve::Linear: + return LinearCurve; + case QEasingCurve::SineCurve: + return SineCurve; + case QEasingCurve::CosineCurve: + return CosineCurve; + } + return EaseInOutCurve; } + void QTimeLine::setCurveShape(CurveShape shape) { + switch (shape) { + default: + case EaseInOutCurve: + setEasingCurve(QEasingCurve(QEasingCurve::InOutSine)); + break; + case EaseInCurve: + setEasingCurve(QEasingCurve(QEasingCurve::InCurve)); + break; + case EaseOutCurve: + setEasingCurve(QEasingCurve(QEasingCurve::OutCurve)); + break; + case LinearCurve: + setEasingCurve(QEasingCurve(QEasingCurve::Linear)); + break; + case SineCurve: + setEasingCurve(QEasingCurve(QEasingCurve::SineCurve)); + break; + case CosineCurve: + setEasingCurve(QEasingCurve(QEasingCurve::CosineCurve)); + break; + } +} + +/*! + \property QTimeLine::easingCurve + + Specifies the easing curve that the timeline will use. + If both easing curve and curveShape are set, the last set property will + override the previous one. (If valueForTime() is reimplemented it will + override both) +*/ + +QEasingCurve QTimeLine::easingCurve() const +{ + Q_D(const QTimeLine); + return d->easingCurve; +} + +void QTimeLine::setEasingCurve(const QEasingCurve& curve) +{ Q_D(QTimeLine); - d->curveShape = shape; + d->easingCurve = curve; } /*! @@ -608,42 +650,8 @@ qreal QTimeLine::valueForTime(int msec) const Q_D(const QTimeLine); msec = qMin(qMax(msec, 0), d->duration); - // Simple linear interpolation qreal value = msec / qreal(d->duration); - - switch (d->curveShape) { - case EaseInOutCurve: - value = qt_sinProgress(value); - break; - // SmoothBegin blends Smooth and Linear Interpolation. - // Progress 0 - 0.3 : Smooth only - // Progress 0.3 - ~ 0.5 : Mix of Smooth and Linear - // Progress ~ 0.5 - 1 : Linear only - case EaseInCurve: { - const qreal sinProgress = qt_sinProgress(value); - const qreal linearProgress = value; - const qreal mix = qt_smoothBeginEndMixFactor(value); - value = sinProgress * mix + linearProgress * (1 - mix); - break; - } - case EaseOutCurve: { - const qreal sinProgress = qt_sinProgress(value); - const qreal linearProgress = value; - const qreal mix = qt_smoothBeginEndMixFactor(1 - value); - value = sinProgress * mix + linearProgress * (1 - mix); - break; - } - case SineCurve: - value = (qSin(((msec * pi * 2) / d->duration) - pi/2) + 1) / 2; - break; - case CosineCurve: - value = (qCos(((msec * pi * 2) / d->duration) - pi/2) + 1) / 2; - break; - default: - break; - } - - return value; + return d->easingCurve.valueForProgress(value); } /*! diff --git a/src/corelib/tools/qtimeline.h b/src/corelib/tools/qtimeline.h index 18c3980..48c9232 100644 --- a/src/corelib/tools/qtimeline.h +++ b/src/corelib/tools/qtimeline.h @@ -42,6 +42,7 @@ #ifndef QTIMELINE_H #define QTIMELINE_H +#include #include QT_BEGIN_HEADER @@ -60,6 +61,7 @@ class Q_CORE_EXPORT QTimeLine : public QObject Q_PROPERTY(Direction direction READ direction WRITE setDirection) Q_PROPERTY(int loopCount READ loopCount WRITE setLoopCount) Q_PROPERTY(CurveShape curveShape READ curveShape WRITE setCurveShape) + Q_PROPERTY(QEasingCurve easingCurve READ easingCurve WRITE setEasingCurve) public: enum State { NotRunning, @@ -105,6 +107,9 @@ public: CurveShape curveShape() const; void setCurveShape(CurveShape shape); + QEasingCurve easingCurve() const; + void setEasingCurve(const QEasingCurve &curve); + int currentTime() const; int currentFrame() const; qreal currentValue() const; diff --git a/src/corelib/tools/tools.pri b/src/corelib/tools/tools.pri index a6fdac7..90287cb 100644 --- a/src/corelib/tools/tools.pri +++ b/src/corelib/tools/tools.pri @@ -11,6 +11,7 @@ HEADERS += \ tools/qcryptographichash.h \ tools/qdatetime.h \ tools/qdatetime_p.h \ + tools/qeasingcurve.h \ tools/qhash.h \ tools/qline.h \ tools/qlinkedlist.h \ @@ -46,6 +47,7 @@ SOURCES += \ tools/qbytearraymatcher.cpp \ tools/qcryptographichash.cpp \ tools/qdatetime.cpp \ + tools/qeasingcurve.cpp \ tools/qhash.cpp \ tools/qline.cpp \ tools/qlinkedlist.cpp \ diff --git a/src/gui/animation/animation.pri b/src/gui/animation/animation.pri new file mode 100644 index 0000000..27763ca --- /dev/null +++ b/src/gui/animation/animation.pri @@ -0,0 +1,3 @@ +# Qt gui animation module + +SOURCES += animation/qguivariantanimation.cpp diff --git a/src/gui/animation/qguivariantanimation.cpp b/src/gui/animation/qguivariantanimation.cpp new file mode 100644 index 0000000..37ca6a1 --- /dev/null +++ b/src/gui/animation/qguivariantanimation.cpp @@ -0,0 +1,75 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QT_NO_ANIMATION + +#include +#include + +#include + +QT_BEGIN_NAMESPACE + +template<> Q_INLINE_TEMPLATE QColor _q_interpolate(const QColor &f,const QColor &t, qreal progress) +{ + return QColor(_q_interpolate(f.red(), t.red(), progress), + _q_interpolate(f.green(), t.green(), progress), + _q_interpolate(f.blue(), t.blue(), progress), + _q_interpolate(f.alpha(), t.alpha(), progress)); +} + +static int qRegisterGuiGetInterpolator() +{ + qRegisterAnimationInterpolator(_q_interpolateVariant); + return 1; +} +Q_CONSTRUCTOR_FUNCTION(qRegisterGuiGetInterpolator) + +static int qUnregisterGuiGetInterpolator() +{ + qRegisterAnimationInterpolator(0); + return 1; +} +Q_DESTRUCTOR_FUNCTION(qUnregisterGuiGetInterpolator) + +QT_END_NAMESPACE + +#endif //QT_NO_ANIMATION diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index b2569c1..62e0411 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -95,6 +95,15 @@ class Q_AUTOTEST_EXPORT QGraphicsItemPrivate { Q_DECLARE_PUBLIC(QGraphicsItem) public: + struct TransformData + { + TransformData() : rotationX(0),rotationY(0),rotationZ(0),scaleX(1),scaleY(1), dirty(true) {} + QTransform baseTransform; + QTransform transform; + QPointF transformCenter; + qreal rotationX,rotationY,rotationZ,scaleX,scaleY; + bool dirty; + }; enum Extra { ExtraTransform, ExtraToolTip, @@ -239,7 +248,7 @@ public: } } } - + struct ExtraStruct { ExtraStruct(Extra type, QVariant value) : type(type), value(value) @@ -251,6 +260,7 @@ public: bool operator<(Extra extra) const { return type < extra; } }; + QList extras; QGraphicsItemCache *maybeExtraItemCache() const; diff --git a/src/gui/graphicsview/qgraphicsproxywidget.cpp b/src/gui/graphicsview/qgraphicsproxywidget.cpp index 01b7593..a5b11ff 100644 --- a/src/gui/graphicsview/qgraphicsproxywidget.cpp +++ b/src/gui/graphicsview/qgraphicsproxywidget.cpp @@ -976,6 +976,7 @@ void QGraphicsProxyWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent *even } #endif // QT_NO_CONTEXTMENU +#ifndef QT_NO_DRAGANDDROP /*! \reimp */ @@ -1096,6 +1097,7 @@ void QGraphicsProxyWidget::dropEvent(QGraphicsSceneDragDropEvent *event) } #endif } +#endif /*! \reimp diff --git a/src/gui/graphicsview/qgraphicsproxywidget.h b/src/gui/graphicsview/qgraphicsproxywidget.h index b2c3c8f..ab8c9da 100644 --- a/src/gui/graphicsview/qgraphicsproxywidget.h +++ b/src/gui/graphicsview/qgraphicsproxywidget.h @@ -90,10 +90,12 @@ protected: void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); #endif +#ifndef QT_NO_DRAGANDDROP void dragEnterEvent(QGraphicsSceneDragDropEvent *event); void dragLeaveEvent(QGraphicsSceneDragDropEvent *event); void dragMoveEvent(QGraphicsSceneDragDropEvent *event); void dropEvent(QGraphicsSceneDragDropEvent *event); +#endif void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); diff --git a/src/gui/gui.pro b/src/gui/gui.pro index 1aa6558..329fb01 100644 --- a/src/gui/gui.pro +++ b/src/gui/gui.pro @@ -19,6 +19,7 @@ win32:include(kernel/win.pri) embedded:include(embedded/embedded.pri) #modules +include(animation/animation.pri) include(kernel/kernel.pri) include(image/image.pri) include(painting/painting.pri) @@ -31,6 +32,7 @@ include(itemviews/itemviews.pri) include(inputmethod/inputmethod.pri) include(graphicsview/graphicsview.pri) include(util/util.pri) +include(statemachine/statemachine.pri) include(math3d/math3d.pri) embedded: QT += network diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp index 824d6f1..a9424db 100644 --- a/src/gui/kernel/qapplication.cpp +++ b/src/gui/kernel/qapplication.cpp @@ -838,6 +838,9 @@ void QApplicationPrivate::initialize() // trigger registering of QVariant's GUI types extern int qRegisterGuiVariant(); qRegisterGuiVariant(); + // trigger registering of QStateMachine's GUI types + extern int qRegisterGuiStateMachine(); + qRegisterGuiStateMachine(); is_app_running = true; // no longer starting up @@ -1059,6 +1062,9 @@ QApplication::~QApplication() QApplicationPrivate::fade_tooltip = false; QApplicationPrivate::widgetCount = false; + // trigger unregistering of QStateMachine's GUI types + extern int qUnregisterGuiStateMachine(); + qUnregisterGuiStateMachine(); // trigger unregistering of QVariant's GUI types extern int qUnregisterGuiVariant(); qUnregisterGuiVariant(); diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp index fdd0c21..bbe1a76 100644 --- a/src/gui/painting/qdrawhelper.cpp +++ b/src/gui/painting/qdrawhelper.cpp @@ -6930,7 +6930,7 @@ static void qt_alphamapblit_quint16(QRasterBuffer *rasterBuffer, } void qt_build_pow_tables() { - qreal smoothing = 1.7; + qreal smoothing = qreal(1.7); #ifdef Q_WS_MAC // decided by testing a few things on an iMac, should probably get this from the @@ -6952,15 +6952,15 @@ void qt_build_pow_tables() { } #else for (int i=0; i<256; ++i) { - qt_pow_rgb_gamma[i] = uchar(qRound(pow(i / 255.0, smoothing) * 255)); - qt_pow_rgb_invgamma[i] = uchar(qRound(pow(i / 255.0, 1 / smoothing) * 255)); + qt_pow_rgb_gamma[i] = uchar(qRound(pow(i / qreal(255.0), smoothing) * 255)); + qt_pow_rgb_invgamma[i] = uchar(qRound(pow(i / qreal(255.), 1 / smoothing) * 255)); } #endif #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) const qreal gray_gamma = 2.31; for (int i=0; i<256; ++i) - qt_pow_gamma[i] = uint(qRound(pow(i / 255.0, gray_gamma) * 2047)); + qt_pow_gamma[i] = uint(qRound(pow(i / qreal(255.), gray_gamma) * 2047)); for (int i=0; i<2048; ++i) qt_pow_invgamma[i] = uchar(qRound(pow(i / 2047.0, 1 / gray_gamma) * 255)); #endif diff --git a/src/gui/statemachine/qbasickeyeventtransition.cpp b/src/gui/statemachine/qbasickeyeventtransition.cpp new file mode 100644 index 0000000..f7f1eb6 --- /dev/null +++ b/src/gui/statemachine/qbasickeyeventtransition.cpp @@ -0,0 +1,203 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qbasickeyeventtransition_p.h" +#include +#include +#include + +QT_BEGIN_NAMESPACE + +/*! + \internal + \class QBasicKeyEventTransition + \since 4.6 + \ingroup statemachine + + \brief The QBasicKeyEventTransition class provides a transition for Qt key events. +*/ + +class QBasicKeyEventTransitionPrivate : public QAbstractTransitionPrivate +{ + Q_DECLARE_PUBLIC(QBasicKeyEventTransition) +public: + QBasicKeyEventTransitionPrivate(); + + static QBasicKeyEventTransitionPrivate *get(QBasicKeyEventTransition *q); + + QEvent::Type eventType; + int key; + Qt::KeyboardModifiers modifiersMask; +}; + +QBasicKeyEventTransitionPrivate::QBasicKeyEventTransitionPrivate() +{ + eventType = QEvent::None; + key = 0; + modifiersMask = Qt::NoModifier; +} + +QBasicKeyEventTransitionPrivate *QBasicKeyEventTransitionPrivate::get(QBasicKeyEventTransition *q) +{ + return q->d_func(); +} + +/*! + Constructs a new key event transition with the given \a sourceState. +*/ +QBasicKeyEventTransition::QBasicKeyEventTransition(QState *sourceState) + : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState) +{ +} + +/*! + Constructs a new event transition for events of the given \a type for the + given \a key, with the given \a sourceState. +*/ +QBasicKeyEventTransition::QBasicKeyEventTransition(QEvent::Type type, int key, + QState *sourceState) + : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState) +{ + Q_D(QBasicKeyEventTransition); + d->eventType = type; + d->key = key; +} + +/*! + Constructs a new event transition for events of the given \a type for the + given \a key, with the given \a modifiersMask and \a sourceState. +*/ +QBasicKeyEventTransition::QBasicKeyEventTransition(QEvent::Type type, int key, + Qt::KeyboardModifiers modifiersMask, + QState *sourceState) + : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState) +{ + Q_D(QBasicKeyEventTransition); + d->eventType = type; + d->key = key; + d->modifiersMask = modifiersMask; +} + +/*! + Destroys this event transition. +*/ +QBasicKeyEventTransition::~QBasicKeyEventTransition() +{ +} + +/*! + Returns the event type that this key event transition is associated with. +*/ +QEvent::Type QBasicKeyEventTransition::eventType() const +{ + Q_D(const QBasicKeyEventTransition); + return d->eventType; +} + +/*! + Sets the event \a type that this key event transition is associated with. +*/ +void QBasicKeyEventTransition::setEventType(QEvent::Type type) +{ + Q_D(QBasicKeyEventTransition); + d->eventType = type; +} + +/*! + Returns the key that this key event transition checks for. +*/ +int QBasicKeyEventTransition::key() const +{ + Q_D(const QBasicKeyEventTransition); + return d->key; +} + +/*! + Sets the key that this key event transition will check for. +*/ +void QBasicKeyEventTransition::setKey(int key) +{ + Q_D(QBasicKeyEventTransition); + d->key = key; +} + +/*! + Returns the keyboard modifiers mask that this key event transition checks + for. +*/ +Qt::KeyboardModifiers QBasicKeyEventTransition::modifiersMask() const +{ + Q_D(const QBasicKeyEventTransition); + return d->modifiersMask; +} + +/*! + Sets the keyboard modifiers mask that this key event transition will check + for. +*/ +void QBasicKeyEventTransition::setModifiersMask(Qt::KeyboardModifiers modifiersMask) +{ + Q_D(QBasicKeyEventTransition); + d->modifiersMask = modifiersMask; +} + +/*! + \reimp +*/ +bool QBasicKeyEventTransition::eventTest(QEvent *event) +{ + Q_D(const QBasicKeyEventTransition); + if (event->type() == d->eventType) { + QKeyEvent *ke = static_cast(event); + return (ke->key() == d->key) + && ((ke->modifiers() & d->modifiersMask) == d->modifiersMask); + } + return false; +} + +/*! + \reimp +*/ +void QBasicKeyEventTransition::onTransition(QEvent *) +{ +} + +QT_END_NAMESPACE diff --git a/src/gui/statemachine/qbasickeyeventtransition_p.h b/src/gui/statemachine/qbasickeyeventtransition_p.h new file mode 100644 index 0000000..39fa6ad --- /dev/null +++ b/src/gui/statemachine/qbasickeyeventtransition_p.h @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QBASICKEYEVENTTRANSITION_P_H +#define QBASICKEYEVENTTRANSITION_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +QT_BEGIN_NAMESPACE + +class QBasicKeyEventTransitionPrivate; +class Q_AUTOTEST_EXPORT QBasicKeyEventTransition : public QAbstractTransition +{ + Q_OBJECT +public: + QBasicKeyEventTransition(QState *sourceState = 0); + QBasicKeyEventTransition(QEvent::Type type, int key, QState *sourceState = 0); + QBasicKeyEventTransition(QEvent::Type type, int key, + Qt::KeyboardModifiers modifiersMask, + QState *sourceState = 0); + ~QBasicKeyEventTransition(); + + QEvent::Type eventType() const; + void setEventType(QEvent::Type type); + + int key() const; + void setKey(int key); + + Qt::KeyboardModifiers modifiersMask() const; + void setModifiersMask(Qt::KeyboardModifiers modifiers); + +protected: + bool eventTest(QEvent *event); + void onTransition(QEvent *); + +private: + Q_DISABLE_COPY(QBasicKeyEventTransition) + Q_DECLARE_PRIVATE(QBasicKeyEventTransition) +}; + +QT_END_NAMESPACE + +#endif diff --git a/src/gui/statemachine/qbasicmouseeventtransition.cpp b/src/gui/statemachine/qbasicmouseeventtransition.cpp new file mode 100644 index 0000000..20dd792 --- /dev/null +++ b/src/gui/statemachine/qbasicmouseeventtransition.cpp @@ -0,0 +1,208 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qbasicmouseeventtransition_p.h" +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +/*! + \internal + \class QBasicMouseEventTransition + \since 4.6 + \ingroup statemachine + + \brief The QBasicMouseEventTransition class provides a transition for Qt mouse events. +*/ + +class QBasicMouseEventTransitionPrivate : public QAbstractTransitionPrivate +{ + Q_DECLARE_PUBLIC(QBasicMouseEventTransition) +public: + QBasicMouseEventTransitionPrivate(); + + static QBasicMouseEventTransitionPrivate *get(QBasicMouseEventTransition *q); + + QEvent::Type eventType; + Qt::MouseButton button; + Qt::KeyboardModifiers modifiersMask; + QPainterPath path; +}; + +QBasicMouseEventTransitionPrivate::QBasicMouseEventTransitionPrivate() +{ + eventType = QEvent::None; + button = Qt::NoButton; +} + +QBasicMouseEventTransitionPrivate *QBasicMouseEventTransitionPrivate::get(QBasicMouseEventTransition *q) +{ + return q->d_func(); +} + +/*! + Constructs a new mouse event transition with the given \a sourceState. +*/ +QBasicMouseEventTransition::QBasicMouseEventTransition(QState *sourceState) + : QAbstractTransition(*new QBasicMouseEventTransitionPrivate, sourceState) +{ +} + +/*! + Constructs a new mouse event transition for events of the given \a type. +*/ +QBasicMouseEventTransition::QBasicMouseEventTransition(QEvent::Type type, + Qt::MouseButton button, + QState *sourceState) + : QAbstractTransition(*new QBasicMouseEventTransitionPrivate, sourceState) +{ + Q_D(QBasicMouseEventTransition); + d->eventType = type; + d->button = button; +} + +/*! + Destroys this mouse event transition. +*/ +QBasicMouseEventTransition::~QBasicMouseEventTransition() +{ +} + +/*! + Returns the event type that this mouse event transition is associated with. +*/ +QEvent::Type QBasicMouseEventTransition::eventType() const +{ + Q_D(const QBasicMouseEventTransition); + return d->eventType; +} + +/*! + Sets the event \a type that this mouse event transition is associated with. +*/ +void QBasicMouseEventTransition::setEventType(QEvent::Type type) +{ + Q_D(QBasicMouseEventTransition); + d->eventType = type; +} + +/*! + Returns the button that this mouse event transition checks for. +*/ +Qt::MouseButton QBasicMouseEventTransition::button() const +{ + Q_D(const QBasicMouseEventTransition); + return d->button; +} + +/*! + Sets the button that this mouse event transition will check for. +*/ +void QBasicMouseEventTransition::setButton(Qt::MouseButton button) +{ + Q_D(QBasicMouseEventTransition); + d->button = button; +} + +/*! + Returns the keyboard modifiers mask that this mouse event transition checks + for. +*/ +Qt::KeyboardModifiers QBasicMouseEventTransition::modifiersMask() const +{ + Q_D(const QBasicMouseEventTransition); + return d->modifiersMask; +} + +/*! + Sets the keyboard modifiers mask that this mouse event transition will check + for. +*/ +void QBasicMouseEventTransition::setModifiersMask(Qt::KeyboardModifiers modifiersMask) +{ + Q_D(QBasicMouseEventTransition); + d->modifiersMask = modifiersMask; +} + +/*! + Returns the path for this mouse event transition. +*/ +QPainterPath QBasicMouseEventTransition::path() const +{ + Q_D(const QBasicMouseEventTransition); + return d->path; +} + +/*! + Sets the path for this mouse event transition. +*/ +void QBasicMouseEventTransition::setPath(const QPainterPath &path) +{ + Q_D(QBasicMouseEventTransition); + d->path = path; +} + +/*! + \reimp +*/ +bool QBasicMouseEventTransition::eventTest(QEvent *event) +{ + Q_D(const QBasicMouseEventTransition); + if (event->type() == d->eventType) { + QMouseEvent *me = static_cast(event); + return (me->button() == d->button) + && ((me->modifiers() & d->modifiersMask) == d->modifiersMask) + && (d->path.isEmpty() || d->path.contains(me->pos())); + } + return false; +} + +/*! + \reimp +*/ +void QBasicMouseEventTransition::onTransition(QEvent *) +{ +} + +QT_END_NAMESPACE diff --git a/src/gui/statemachine/qbasicmouseeventtransition_p.h b/src/gui/statemachine/qbasicmouseeventtransition_p.h new file mode 100644 index 0000000..6c0afe4 --- /dev/null +++ b/src/gui/statemachine/qbasicmouseeventtransition_p.h @@ -0,0 +1,98 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QBASICMOUSEEVENTTRANSITION_P_H +#define QBASICMOUSEEVENTTRANSITION_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +QT_BEGIN_NAMESPACE + +class QPainterPath; + +class QBasicMouseEventTransitionPrivate; +class Q_AUTOTEST_EXPORT QBasicMouseEventTransition : public QAbstractTransition +{ + Q_OBJECT +public: + QBasicMouseEventTransition(QState *sourceState = 0); + QBasicMouseEventTransition(QEvent::Type type, Qt::MouseButton button, + QState *sourceState = 0); + ~QBasicMouseEventTransition(); + + QEvent::Type eventType() const; + void setEventType(QEvent::Type type); + + Qt::MouseButton button() const; + void setButton(Qt::MouseButton button); + + Qt::KeyboardModifiers modifiersMask() const; + void setModifiersMask(Qt::KeyboardModifiers modifiers); + + QPainterPath path() const; + void setPath(const QPainterPath &path); + +protected: + bool eventTest(QEvent *event); + void onTransition(QEvent *); + +private: + Q_DISABLE_COPY(QBasicMouseEventTransition) + Q_DECLARE_PRIVATE(QBasicMouseEventTransition) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/gui/statemachine/qguistatemachine.cpp b/src/gui/statemachine/qguistatemachine.cpp new file mode 100644 index 0000000..612e43e --- /dev/null +++ b/src/gui/statemachine/qguistatemachine.cpp @@ -0,0 +1,559 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +Q_CORE_EXPORT const QStateMachinePrivate::Handler *qcoreStateMachineHandler(); + +static QEvent *cloneEvent(QEvent *e) +{ + switch (e->type()) { + case QEvent::MouseButtonPress: + case QEvent::MouseButtonRelease: + case QEvent::MouseButtonDblClick: + case QEvent::MouseMove: + return new QMouseEvent(*static_cast(e)); + case QEvent::KeyPress: + case QEvent::KeyRelease: + return new QKeyEvent(*static_cast(e)); + case QEvent::FocusIn: + case QEvent::FocusOut: + return new QFocusEvent(*static_cast(e)); + case QEvent::Enter: + return new QEvent(*e); + case QEvent::Leave: + return new QEvent(*e); + break; + case QEvent::Paint: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::Move: + return new QMoveEvent(*static_cast(e)); + case QEvent::Resize: + return new QResizeEvent(*static_cast(e)); + case QEvent::Create: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::Destroy: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::Show: + return new QShowEvent(*static_cast(e)); + case QEvent::Hide: + return new QHideEvent(*static_cast(e)); + case QEvent::Close: + return new QCloseEvent(*static_cast(e)); + case QEvent::Quit: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ParentChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ParentAboutToChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ThreadChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::WindowActivate: + case QEvent::WindowDeactivate: + return new QEvent(*e); + + case QEvent::ShowToParent: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::HideToParent: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::Wheel: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::WindowTitleChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::WindowIconChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ApplicationWindowIconChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ApplicationFontChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ApplicationLayoutDirectionChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ApplicationPaletteChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::PaletteChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::Clipboard: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::Speech: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::MetaCall: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::SockAct: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::WinEventAct: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::DeferredDelete: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::DragEnter: + return new QDragEnterEvent(*static_cast(e)); + case QEvent::DragMove: + return new QDragMoveEvent(*static_cast(e)); + case QEvent::DragLeave: + return new QDragLeaveEvent(*static_cast(e)); + case QEvent::Drop: + return new QDropEvent(*static_cast(e)); + case QEvent::DragResponse: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ChildAdded: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ChildPolished: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; +#ifdef QT3_SUPPORT + case QEvent::ChildInsertedRequest: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ChildInserted: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::LayoutHint: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; +#endif + case QEvent::ChildRemoved: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ShowWindowRequest: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::PolishRequest: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::Polish: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::LayoutRequest: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::UpdateRequest: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::UpdateLater: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::EmbeddingControl: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ActivateControl: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::DeactivateControl: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ContextMenu: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::InputMethod: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::AccessibilityPrepare: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::TabletMove: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::LocaleChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::LanguageChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::LayoutDirectionChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::Style: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::TabletPress: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::TabletRelease: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::OkRequest: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::HelpRequest: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::IconDrag: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::FontChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::EnabledChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ActivationChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::StyleChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::IconTextChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ModifiedChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::MouseTrackingChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::WindowBlocked: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::WindowUnblocked: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::WindowStateChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::ToolTip: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::WhatsThis: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::StatusTip: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::ActionChanged: + case QEvent::ActionAdded: + case QEvent::ActionRemoved: + return new QActionEvent(*static_cast(e)); + + case QEvent::FileOpen: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::Shortcut: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ShortcutOverride: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + +#ifdef QT3_SUPPORT + case QEvent::Accel: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::AccelAvailable: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; +#endif + + case QEvent::WhatsThisClicked: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::ToolBarChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::ApplicationActivate: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ApplicationDeactivate: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::QueryWhatsThis: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::EnterWhatsThisMode: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::LeaveWhatsThisMode: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::ZOrderChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::HoverEnter: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::HoverLeave: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::HoverMove: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::AccessibilityHelp: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::AccessibilityDescription: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + +#ifdef QT_KEYPAD_NAVIGATION + case QEvent::EnterEditFocus: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::LeaveEditFocus: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; +#endif + case QEvent::AcceptDropsChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::MenubarUpdated: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::ZeroTimerEvent: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::GraphicsSceneMouseMove: + case QEvent::GraphicsSceneMousePress: + case QEvent::GraphicsSceneMouseRelease: + case QEvent::GraphicsSceneMouseDoubleClick: { + QGraphicsSceneMouseEvent *me = static_cast(e); + QGraphicsSceneMouseEvent *me2 = new QGraphicsSceneMouseEvent(me->type()); + me2->setWidget(me->widget()); + me2->setPos(me->pos()); + me2->setScenePos(me->scenePos()); + me2->setScreenPos(me->screenPos()); +// ### for all buttons + me2->setButtonDownPos(Qt::LeftButton, me->buttonDownPos(Qt::LeftButton)); + me2->setButtonDownPos(Qt::RightButton, me->buttonDownPos(Qt::RightButton)); + me2->setButtonDownScreenPos(Qt::LeftButton, me->buttonDownScreenPos(Qt::LeftButton)); + me2->setButtonDownScreenPos(Qt::RightButton, me->buttonDownScreenPos(Qt::RightButton)); + me2->setLastPos(me->lastPos()); + me2->setLastScenePos(me->lastScenePos()); + me2->setLastScreenPos(me->lastScreenPos()); + me2->setButtons(me->buttons()); + me2->setButton(me->button()); + me2->setModifiers(me->modifiers()); + return me2; + } + + case QEvent::GraphicsSceneContextMenu: { + QGraphicsSceneContextMenuEvent *me = static_cast(e); + QGraphicsSceneContextMenuEvent *me2 = new QGraphicsSceneContextMenuEvent(me->type()); + me2->setWidget(me->widget()); + me2->setPos(me->pos()); + me2->setScenePos(me->scenePos()); + me2->setScreenPos(me->screenPos()); + me2->setModifiers(me->modifiers()); + me2->setReason(me->reason()); + return me2; + } + + case QEvent::GraphicsSceneHoverEnter: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneHoverMove: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneHoverLeave: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneHelp: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneDragEnter: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneDragMove: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneDragLeave: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneDrop: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneWheel: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::KeyboardLayoutChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::DynamicPropertyChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::TabletEnterProximity: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::TabletLeaveProximity: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::NonClientAreaMouseMove: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::NonClientAreaMouseButtonPress: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::NonClientAreaMouseButtonRelease: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::NonClientAreaMouseButtonDblClick: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::MacSizeChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::ContentsRectChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::MacGLWindowChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::FutureCallOut: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::GraphicsSceneResize: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::GraphicsSceneMove: { + QGraphicsSceneMoveEvent *me = static_cast(e); + QGraphicsSceneMoveEvent *me2 = new QGraphicsSceneMoveEvent(); + me2->setWidget(me->widget()); + me2->setNewPos(me->newPos()); + me2->setOldPos(me->oldPos()); + return me2; + } + + case QEvent::CursorChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + case QEvent::ToolTipChange: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::NetworkReplyUpdated: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + + case QEvent::GrabMouse: + case QEvent::UngrabMouse: + case QEvent::GrabKeyboard: + case QEvent::UngrabKeyboard: + return new QEvent(*e); + +#ifdef QT_MAC_USE_COCOA + case QEvent::CocoaRequestModal: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; +#endif + case QEvent::User: + case QEvent::MaxUser: + Q_ASSERT_X(false, "cloneEvent()", "not implemented"); + break; + default: + ; + } + return qcoreStateMachineHandler()->cloneEvent(e); +} + +const QStateMachinePrivate::Handler qt_gui_statemachine_handler = { + cloneEvent +}; + +static const QStateMachinePrivate::Handler *qt_guistatemachine_last_handler = 0; +int qRegisterGuiStateMachine() +{ + qt_guistatemachine_last_handler = QStateMachinePrivate::handler; + QStateMachinePrivate::handler = &qt_gui_statemachine_handler; + return 1; +} +Q_CONSTRUCTOR_FUNCTION(qRegisterGuiStateMachine) + +int qUnregisterGuiStateMachine() +{ + QStateMachinePrivate::handler = qt_guistatemachine_last_handler; + return 1; +} +Q_DESTRUCTOR_FUNCTION(qUnregisterGuiStateMachine) + +QT_END_NAMESPACE diff --git a/src/gui/statemachine/qkeyeventtransition.cpp b/src/gui/statemachine/qkeyeventtransition.cpp new file mode 100644 index 0000000..f803711 --- /dev/null +++ b/src/gui/statemachine/qkeyeventtransition.cpp @@ -0,0 +1,186 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qkeyeventtransition.h" +#include "qbasickeyeventtransition_p.h" +#include +#include + +QT_BEGIN_NAMESPACE + +/*! + \class QKeyEventTransition + + \brief The QKeyEventTransition class provides a transition for key events. + + \since 4.6 + \ingroup statemachine + + QKeyEventTransition is part of \l{The State Machine Framework}. + + \sa QState::addTransition() +*/ + +/*! + \property QKeyEventTransition::key + + \brief the key that this key event transition is associated with +*/ + +/*! + \property QKeyEventTransition::modifiersMask + + \brief the keyboard modifiers mask that this key event transition checks for +*/ + +class QKeyEventTransitionPrivate : public QEventTransitionPrivate +{ + Q_DECLARE_PUBLIC(QKeyEventTransition) +public: + QKeyEventTransitionPrivate() {} + + QBasicKeyEventTransition *transition; +}; + +/*! + Constructs a new key event transition with the given \a sourceState. +*/ +QKeyEventTransition::QKeyEventTransition(QState *sourceState) + : QEventTransition(*new QKeyEventTransitionPrivate, sourceState) +{ + Q_D(QKeyEventTransition); + d->transition = new QBasicKeyEventTransition(); +} + +/*! + Constructs a new key event transition for events of the given \a type for + the given \a object, with the given \a key and \a sourceState. +*/ +QKeyEventTransition::QKeyEventTransition(QObject *object, QEvent::Type type, + int key, QState *sourceState) + : QEventTransition(*new QKeyEventTransitionPrivate, object, type, sourceState) +{ + Q_D(QKeyEventTransition); + d->transition = new QBasicKeyEventTransition(type, key); +} + +/*! + Constructs a new key event transition for events of the given \a type for + the given \a object, with the given \a key, \a targets and \a sourceState. +*/ +QKeyEventTransition::QKeyEventTransition(QObject *object, QEvent::Type type, + int key, const QList &targets, + QState *sourceState) + : QEventTransition(*new QKeyEventTransitionPrivate, object, type, targets, sourceState) +{ + Q_D(QKeyEventTransition); + d->transition = new QBasicKeyEventTransition(type, key); +} + +/*! + Destroys this key event transition. +*/ +QKeyEventTransition::~QKeyEventTransition() +{ + Q_D(QKeyEventTransition); + delete d->transition; +} + +/*! + Returns the key that this key event transition checks for. +*/ +int QKeyEventTransition::key() const +{ + Q_D(const QKeyEventTransition); + return d->transition->key(); +} + +/*! + Sets the key that this key event transition will check for. +*/ +void QKeyEventTransition::setKey(int key) +{ + Q_D(QKeyEventTransition); + d->transition->setKey(key); +} + +/*! + Returns the keyboard modifiers mask that this key event transition checks + for. +*/ +Qt::KeyboardModifiers QKeyEventTransition::modifiersMask() const +{ + Q_D(const QKeyEventTransition); + return d->transition->modifiersMask(); +} + +/*! + Sets the keyboard \a modifiers mask that this key event transition will + check for. +*/ +void QKeyEventTransition::setModifiersMask(Qt::KeyboardModifiers modifiersMask) +{ + Q_D(QKeyEventTransition); + d->transition->setModifiersMask(modifiersMask); +} + +/*! + \reimp +*/ +bool QKeyEventTransition::eventTest(QEvent *event) +{ + Q_D(const QKeyEventTransition); + if (!QEventTransition::eventTest(event)) + return false; + QWrappedEvent *we = static_cast(event); + d->transition->setEventType(we->event()->type()); + return QAbstractTransitionPrivate::get(d->transition)->callEventTest(we->event()); +} + +/*! + \reimp +*/ +void QKeyEventTransition::onTransition(QEvent *event) +{ + QEventTransition::onTransition(event); +} + +QT_END_NAMESPACE diff --git a/src/gui/statemachine/qkeyeventtransition.h b/src/gui/statemachine/qkeyeventtransition.h new file mode 100644 index 0000000..3c8295f --- /dev/null +++ b/src/gui/statemachine/qkeyeventtransition.h @@ -0,0 +1,87 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QKEYEVENTTRANSITION_H +#define QKEYEVENTTRANSITION_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QKeyEventTransitionPrivate; +class Q_GUI_EXPORT QKeyEventTransition : public QEventTransition +{ + Q_OBJECT + Q_PROPERTY(int key READ key WRITE setKey) + Q_PROPERTY(Qt::KeyboardModifiers modifiersMask READ modifiersMask WRITE setModifiersMask) +public: + QKeyEventTransition(QState *sourceState = 0); + QKeyEventTransition(QObject *object, QEvent::Type type, int key, + QState *sourceState = 0); + QKeyEventTransition(QObject *object, QEvent::Type type, int key, + const QList &targets, + QState *sourceState = 0); + ~QKeyEventTransition(); + + int key() const; + void setKey(int key); + + Qt::KeyboardModifiers modifiersMask() const; + void setModifiersMask(Qt::KeyboardModifiers modifiers); + +protected: + void onTransition(QEvent *event); + bool eventTest(QEvent *event); + +private: + Q_DISABLE_COPY(QKeyEventTransition) + Q_DECLARE_PRIVATE(QKeyEventTransition) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/gui/statemachine/qmouseeventtransition.cpp b/src/gui/statemachine/qmouseeventtransition.cpp new file mode 100644 index 0000000..e4e18eb --- /dev/null +++ b/src/gui/statemachine/qmouseeventtransition.cpp @@ -0,0 +1,216 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmouseeventtransition.h" +#include "qbasicmouseeventtransition_p.h" +#include +#include +#include + +QT_BEGIN_NAMESPACE + +/*! + \class QMouseEventTransition + + \brief The QMouseEventTransition class provides a transition for mouse events. + + \since 4.6 + \ingroup statemachine + + QMouseEventTransition is part of \l{The State Machine Framework}. + + \sa QState::addTransition() +*/ + +/*! + \property QMouseEventTransition::button + + \brief the button that this mouse event transition is associated with +*/ + +/*! + \property QMouseEventTransition::modifiersMask + + \brief the keyboard modifiers mask that this mouse event transition checks for +*/ + +class QMouseEventTransitionPrivate : public QEventTransitionPrivate +{ + Q_DECLARE_PUBLIC(QMouseEventTransition) +public: + QMouseEventTransitionPrivate(); + + QBasicMouseEventTransition *transition; +}; + +QMouseEventTransitionPrivate::QMouseEventTransitionPrivate() +{ +} + +/*! + Constructs a new mouse event transition with the given \a sourceState. +*/ +QMouseEventTransition::QMouseEventTransition(QState *sourceState) + : QEventTransition(*new QMouseEventTransitionPrivate, sourceState) +{ + Q_D(QMouseEventTransition); + d->transition = new QBasicMouseEventTransition(); +} + +/*! + Constructs a new mouse event transition for events of the given \a type for + the given \a object, with the given \a button and \a sourceState. +*/ +QMouseEventTransition::QMouseEventTransition(QObject *object, QEvent::Type type, + Qt::MouseButton button, + QState *sourceState) + : QEventTransition(*new QMouseEventTransitionPrivate, object, type, sourceState) +{ + Q_D(QMouseEventTransition); + d->transition = new QBasicMouseEventTransition(type, button); +} + +/*! + Constructs a new mouse event transition for events of the given \a type for + the given \a object, with the given \a button, \a targets and \a + sourceState. +*/ +QMouseEventTransition::QMouseEventTransition(QObject *object, QEvent::Type type, + Qt::MouseButton button, + const QList &targets, + QState *sourceState) + : QEventTransition(*new QMouseEventTransitionPrivate, object, type, targets, sourceState) +{ + Q_D(QMouseEventTransition); + d->transition = new QBasicMouseEventTransition(type, button); +} + +/*! + Destroys this mouse event transition. +*/ +QMouseEventTransition::~QMouseEventTransition() +{ + Q_D(QMouseEventTransition); + delete d->transition; +} + +/*! + Returns the button that this mouse event transition checks for. +*/ +Qt::MouseButton QMouseEventTransition::button() const +{ + Q_D(const QMouseEventTransition); + return d->transition->button(); +} + +/*! + Sets the \a button that this mouse event transition will check for. +*/ +void QMouseEventTransition::setButton(Qt::MouseButton button) +{ + Q_D(QMouseEventTransition); + d->transition->setButton(button); +} + +/*! + Returns the keyboard modifiers mask that this mouse event transition checks + for. +*/ +Qt::KeyboardModifiers QMouseEventTransition::modifiersMask() const +{ + Q_D(const QMouseEventTransition); + return d->transition->modifiersMask(); +} + +/*! + Sets the keyboard \a modifiers mask that this mouse event transition will + check for. +*/ +void QMouseEventTransition::setModifiersMask(Qt::KeyboardModifiers modifiersMask) +{ + Q_D(QMouseEventTransition); + d->transition->setModifiersMask(modifiersMask); +} + +/*! + Returns the path for this mouse event transition. +*/ +QPainterPath QMouseEventTransition::path() const +{ + Q_D(const QMouseEventTransition); + return d->transition->path(); +} + +/*! + Sets the \a path for this mouse event transition. + If a valid path has been set, the transition will only trigger if the mouse + event position (QMouseEvent::pos()) is inside the path. + + \sa QPainterPath::contains() +*/ +void QMouseEventTransition::setPath(const QPainterPath &path) +{ + Q_D(QMouseEventTransition); + d->transition->setPath(path); +} + +/*! + \reimp +*/ +bool QMouseEventTransition::eventTest(QEvent *event) +{ + Q_D(const QMouseEventTransition); + if (!QEventTransition::eventTest(event)) + return false; + QWrappedEvent *we = static_cast(event); + d->transition->setEventType(we->event()->type()); + return QAbstractTransitionPrivate::get(d->transition)->callEventTest(we->event()); +} + +/*! + \reimp +*/ +void QMouseEventTransition::onTransition(QEvent *event) +{ + QEventTransition::onTransition(event); +} + +QT_END_NAMESPACE diff --git a/src/gui/statemachine/qmouseeventtransition.h b/src/gui/statemachine/qmouseeventtransition.h new file mode 100644 index 0000000..3f5f3ac --- /dev/null +++ b/src/gui/statemachine/qmouseeventtransition.h @@ -0,0 +1,92 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtGui module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMOUSEEVENTTRANSITION_H +#define QMOUSEEVENTTRANSITION_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +class QMouseEventTransitionPrivate; +class QPainterPath; +class Q_GUI_EXPORT QMouseEventTransition : public QEventTransition +{ + Q_OBJECT + Q_PROPERTY(Qt::MouseButton button READ button WRITE setButton) + Q_PROPERTY(Qt::KeyboardModifiers modifiersMask READ modifiersMask WRITE setModifiersMask) +public: + QMouseEventTransition(QState *sourceState = 0); + QMouseEventTransition(QObject *object, QEvent::Type type, + Qt::MouseButton button, QState *sourceState = 0); + QMouseEventTransition(QObject *object, QEvent::Type type, + Qt::MouseButton button, + const QList &targets, + QState *sourceState = 0); + ~QMouseEventTransition(); + + Qt::MouseButton button() const; + void setButton(Qt::MouseButton button); + + Qt::KeyboardModifiers modifiersMask() const; + void setModifiersMask(Qt::KeyboardModifiers modifiers); + + QPainterPath path() const; + void setPath(const QPainterPath &path); + +protected: + void onTransition(QEvent *event); + bool eventTest(QEvent *event); + +private: + Q_DISABLE_COPY(QMouseEventTransition) + Q_DECLARE_PRIVATE(QMouseEventTransition) +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif diff --git a/src/gui/statemachine/statemachine.pri b/src/gui/statemachine/statemachine.pri new file mode 100644 index 0000000..2eb1e05 --- /dev/null +++ b/src/gui/statemachine/statemachine.pri @@ -0,0 +1,13 @@ +SOURCES += $$PWD/qguistatemachine.cpp +!contains(DEFINES, QT_NO_STATEMACHINE_EVENTFILTER) { + HEADERS += \ + $$PWD/qkeyeventtransition.h \ + $$PWD/qmouseeventtransition.h \ + $$PWD/qbasickeyeventtransition_p.h \ + $$PWD/qbasicmouseeventtransition_p.h + SOURCES += \ + $$PWD/qkeyeventtransition.cpp \ + $$PWD/qmouseeventtransition.cpp \ + $$PWD/qbasickeyeventtransition.cpp \ + $$PWD/qbasicmouseeventtransition.cpp +} diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro index 714e19d..316a695 100644 --- a/tests/auto/auto.pro +++ b/tests/auto/auto.pro @@ -75,6 +75,7 @@ SUBDIRS += bic \ qaction \ qactiongroup \ qalgorithms \ + qanimationgroup \ qapplication \ qatomicint \ qatomicpointer \ @@ -214,6 +215,7 @@ SUBDIRS += bic \ qpainter \ qpainterpath \ qpalette \ + qparallelanimationgroup \ qpathclipper \ qpen \ qpicture \ @@ -229,6 +231,7 @@ SUBDIRS += bic \ qprocess \ qprogressbar \ qprogressdialog \ + qpropertyanimation \ qpushbutton \ qqueue \ qradiobutton \ @@ -256,6 +259,7 @@ SUBDIRS += bic \ qscrollarea \ qsemaphore \ qsharedpointer \ + qsequentialanimationgroup \ qset \ qsettings \ qshortcut \ @@ -289,6 +293,7 @@ SUBDIRS += bic \ qstackedwidget \ qstandarditem \ qstandarditemmodel \ + qstate \ qstatusbar \ qstl \ qstring \ @@ -342,6 +347,7 @@ SUBDIRS += bic \ qtranslator \ qtransform \ qtransformedscreen \ + qtransition \ qtreeview \ qtreewidget \ qtreewidgetitemiterator \ diff --git a/tests/auto/qanimationgroup/qanimationgroup.pro b/tests/auto/qanimationgroup/qanimationgroup.pro new file mode 100644 index 0000000..97d33dd --- /dev/null +++ b/tests/auto/qanimationgroup/qanimationgroup.pro @@ -0,0 +1,5 @@ +load(qttest_p4) +QT = core gui +SOURCES += tst_qanimationgroup.cpp + + diff --git a/tests/auto/qanimationgroup/tst_qanimationgroup.cpp b/tests/auto/qanimationgroup/tst_qanimationgroup.cpp new file mode 100644 index 0000000..2952a39 --- /dev/null +++ b/tests/auto/qanimationgroup/tst_qanimationgroup.cpp @@ -0,0 +1,413 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include +#include +#include + +//TESTED_CLASS=QAnimationGroup +//TESTED_FILES= + +Q_DECLARE_METATYPE(QAbstractAnimation::State) + +class tst_QAnimationGroup : public QObject +{ + Q_OBJECT +public: + tst_QAnimationGroup(); + virtual ~tst_QAnimationGroup(); + +public Q_SLOTS: + void init(); + void cleanup(); + +private slots: + void construction(); + void emptyGroup(); + void setCurrentTime(); + void statesAndSignals(); + void setParentAutoAdd(); + void beginNestedGroup(); + void addChildTwice(); + void loopWithoutStartValue(); +}; + +tst_QAnimationGroup::tst_QAnimationGroup() +{ +} + +tst_QAnimationGroup::~tst_QAnimationGroup() +{ +} + +void tst_QAnimationGroup::init() +{ + qRegisterMetaType("QAbstractAnimation::State"); +} + +void tst_QAnimationGroup::cleanup() +{ +} + +void tst_QAnimationGroup::construction() +{ + QSequentialAnimationGroup animationgroup; +} + +class AnimationObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(int value READ value WRITE setValue) +public: + AnimationObject(int startValue = 0) + : v(startValue) + { } + + int value() const { return v; } + void setValue(int value) { v = value; } + + int v; +}; + +class TestAnimation : public QVariantAnimation +{ + Q_OBJECT +public: + virtual void updateCurrentValue(const QVariant &value) { Q_UNUSED(value)}; + virtual void updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) + { + Q_UNUSED(oldState) + Q_UNUSED(newState) + }; +}; + +class UncontrolledAnimation : public QPropertyAnimation +{ + Q_OBJECT +public: + UncontrolledAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0) + : QPropertyAnimation(target, propertyName, parent), id(0) + { + setDuration(250); + } + + int duration() const { return -1; /* not time driven */ } + +protected: + void timerEvent(QTimerEvent *event) + { + if (event->timerId() == id) + stop(); + } + + void updateRunning(bool running) + { + if (running) { + id = startTimer(500); + } else { + killTimer(id); + id = 0; + } + } + +private: + int id; +}; + +void tst_QAnimationGroup::emptyGroup() +{ + QSequentialAnimationGroup group; + QSignalSpy groupStateChangedSpy(&group, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + group.start(); + + QCOMPARE(groupStateChangedSpy.count(), 2); + + QCOMPARE(qVariantValue(groupStateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(groupStateChangedSpy.at(1).at(1)), + QAnimationGroup::Stopped); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + + QTest::ignoreMessage(QtWarningMsg, "QAbstractAnimation::pause: Cannot pause a stopped animation"); + group.pause(); + + QCOMPARE(groupStateChangedSpy.count(), 2); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + + group.start(); + + QCOMPARE(qVariantValue(groupStateChangedSpy.at(2).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(groupStateChangedSpy.at(3).at(1)), + QAnimationGroup::Stopped); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + + group.stop(); + + QCOMPARE(groupStateChangedSpy.count(), 4); + QCOMPARE(group.state(), QAnimationGroup::Stopped); +} + +void tst_QAnimationGroup::setCurrentTime() +{ + AnimationObject s_o1; + AnimationObject s_o2; + AnimationObject s_o3; + AnimationObject p_o1; + AnimationObject p_o2; + AnimationObject p_o3; + AnimationObject t_o1; + AnimationObject t_o2; + + // sequence operating on same object/property + QSequentialAnimationGroup *sequence = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); + a2_s_o1->setLoopCount(3); + sequence->addAnimation(a1_s_o1); + sequence->addAnimation(a2_s_o1); + sequence->addAnimation(a3_s_o1); + + // sequence operating on different object/properties + QAnimationGroup *sequence2 = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); + QVariantAnimation *a1_s_o3 = new QPropertyAnimation(&s_o3, "value"); + sequence2->addAnimation(a1_s_o2); + sequence2->addAnimation(a1_s_o3); + + // parallel operating on different object/properties + QAnimationGroup *parallel = new QParallelAnimationGroup(); + QVariantAnimation *a1_p_o1 = new QPropertyAnimation(&p_o1, "value"); + QVariantAnimation *a1_p_o2 = new QPropertyAnimation(&p_o2, "value"); + QVariantAnimation *a1_p_o3 = new QPropertyAnimation(&p_o3, "value"); + a1_p_o2->setLoopCount(3); + parallel->addAnimation(a1_p_o1); + parallel->addAnimation(a1_p_o2); + parallel->addAnimation(a1_p_o3); + + UncontrolledAnimation *notTimeDriven = new UncontrolledAnimation(&t_o1, "value"); + QCOMPARE(notTimeDriven->totalDuration(), -1); + + QVariantAnimation *loopsForever = new QPropertyAnimation(&t_o2, "value"); + loopsForever->setLoopCount(-1); + QCOMPARE(loopsForever->totalDuration(), -1); + + QParallelAnimationGroup group; + group.addAnimation(sequence); + group.addAnimation(sequence2); + group.addAnimation(parallel); + group.addAnimation(notTimeDriven); + group.addAnimation(loopsForever); + + // Current time = 1 + group.setCurrentTime(1); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(sequence->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(parallel->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_p_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_p_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_p_o3->state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); + + QCOMPARE(group.currentTime(), 1); + QCOMPARE(sequence->currentTime(), 1); + QCOMPARE(a1_s_o1->currentTime(), 1); + QCOMPARE(a2_s_o1->currentTime(), 0); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 1); + QCOMPARE(a1_s_o3->currentTime(), 0); + QCOMPARE(a1_p_o1->currentTime(), 1); + QCOMPARE(a1_p_o2->currentTime(), 1); + QCOMPARE(a1_p_o3->currentTime(), 1); + QCOMPARE(notTimeDriven->currentTime(), 1); + QCOMPARE(loopsForever->currentTime(), 1); + + // Current time = 250 + group.setCurrentTime(250); + QCOMPARE(group.currentTime(), 250); + QCOMPARE(sequence->currentTime(), 250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 0); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 0); + QCOMPARE(a1_p_o1->currentTime(), 250); + QCOMPARE(a1_p_o2->currentTime(), 0); + QCOMPARE(a1_p_o2->currentLoop(), 1); + QCOMPARE(a1_p_o3->currentTime(), 250); + QCOMPARE(notTimeDriven->currentTime(), 250); + QCOMPARE(loopsForever->currentTime(), 0); + QCOMPARE(loopsForever->currentLoop(), 1); + QCOMPARE(sequence->currentAnimation(), a2_s_o1); + + // Current time = 251 + group.setCurrentTime(251); + QCOMPARE(group.currentTime(), 251); + QCOMPARE(sequence->currentTime(), 251); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 1); + QCOMPARE(a2_s_o1->currentLoop(), 0); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(sequence2->currentTime(), 251); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 1); + QCOMPARE(a1_p_o1->currentTime(), 250); + QCOMPARE(a1_p_o2->currentTime(), 1); + QCOMPARE(a1_p_o2->currentLoop(), 1); + QCOMPARE(a1_p_o3->currentTime(), 250); + QCOMPARE(notTimeDriven->currentTime(), 251); + QCOMPARE(loopsForever->currentTime(), 1); + QCOMPARE(sequence->currentAnimation(), a2_s_o1); +} + +void tst_QAnimationGroup::statesAndSignals() +{ +} + +void tst_QAnimationGroup::setParentAutoAdd() +{ + QParallelAnimationGroup group; + QVariantAnimation *animation = new QPropertyAnimation(&group); + QCOMPARE(animation->group(), &group); +} + +void tst_QAnimationGroup::beginNestedGroup() +{ + QAnimationGroup *subGroup; + QAnimationGroup *parent = new QParallelAnimationGroup(); + + for (int i = 0; i < 10; ++i) { + if (i & 1) + subGroup = new QParallelAnimationGroup(parent); + else + subGroup = new QSequentialAnimationGroup(parent); + + QCOMPARE(parent->animationCount(), 1); + QAnimationGroup *child = static_cast(parent->animationAt(0)); + + QCOMPARE(child->parent(), static_cast(parent)); + if (i & 1) + QVERIFY(qobject_cast (child)); + else + QVERIFY(qobject_cast (child)); + + parent = child; + } +} + +void tst_QAnimationGroup::addChildTwice() +{ + QPropertyAnimation *subGroup; + QPropertyAnimation *subGroup2; + QAnimationGroup *parent = new QSequentialAnimationGroup(); + + subGroup = new QPropertyAnimation(); + subGroup->setParent(parent); + parent->addAnimation(subGroup); + QCOMPARE(parent->animationCount(), 1); + + parent->clearAnimations(); + + QCOMPARE(parent->animationCount(), 0); + + // adding the same item twice to a group will remove the item from its current position + // and append it to the end + subGroup = new QPropertyAnimation(parent); + subGroup2 = new QPropertyAnimation(parent); + + QCOMPARE(parent->animationCount(), 2); + QCOMPARE(parent->animationAt(0), subGroup); + QCOMPARE(parent->animationAt(1), subGroup2); + + parent->addAnimation(subGroup); + + QCOMPARE(parent->animationCount(), 2); + QCOMPARE(parent->animationAt(0), subGroup2); + QCOMPARE(parent->animationAt(1), subGroup); + + delete parent; +} + +void tst_QAnimationGroup::loopWithoutStartValue() +{ + QAnimationGroup *parent = new QSequentialAnimationGroup(); + QObject o; + o.setProperty("ole", 0); + QCOMPARE(o.property("ole").toInt(), 0); + + QPropertyAnimation anim1(&o, "ole"); + anim1.setEndValue(-50); + anim1.setDuration(100); + + QPropertyAnimation anim2(&o, "ole"); + anim2.setEndValue(50); + anim2.setDuration(100); + + parent->addAnimation(&anim1); + parent->addAnimation(&anim2); + + parent->setLoopCount(-1); + parent->start(); + + QVERIFY(anim1.startValue().isNull()); + QCOMPARE(anim1.currentValue().toInt(), 0); + QCOMPARE(parent->currentLoop(), 0); + + parent->setCurrentTime(200); + QCOMPARE(parent->currentLoop(), 1); + QCOMPARE(anim1.currentValue().toInt(), 50); + parent->stop(); +} + +QTEST_MAIN(tst_QAnimationGroup) +#include "tst_qanimationgroup.moc" diff --git a/tests/auto/qeasingcurve/qeasingcurve.pro b/tests/auto/qeasingcurve/qeasingcurve.pro new file mode 100644 index 0000000..2b66081 --- /dev/null +++ b/tests/auto/qeasingcurve/qeasingcurve.pro @@ -0,0 +1,3 @@ +load(qttest_p4) +QT = core +SOURCES += tst_qeasingcurve.cpp diff --git a/tests/auto/qeasingcurve/tst_qeasingcurve.cpp b/tests/auto/qeasingcurve/tst_qeasingcurve.cpp new file mode 100644 index 0000000..8d42e5e --- /dev/null +++ b/tests/auto/qeasingcurve/tst_qeasingcurve.cpp @@ -0,0 +1,487 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include + +#if QT_VERSION < 0x040200 +QTEST_NOOP_MAIN +#else + +#include + +//TESTED_CLASS= +//TESTED_FILES= + +class tst_QEasingCurve : public QObject { + Q_OBJECT + +public: + tst_QEasingCurve(); + virtual ~tst_QEasingCurve(); + +public Q_SLOTS: + void init(); + void cleanup(); + +private slots: + void type(); + void propertyDefaults(); + void valueForProgress_data(); + void valueForProgress(); + void setCustomType(); + void operators(); + +protected: +}; + +tst_QEasingCurve::tst_QEasingCurve() +{ +} + +tst_QEasingCurve::~tst_QEasingCurve() +{ +} + +void tst_QEasingCurve::init() +{ +} + +void tst_QEasingCurve::cleanup() +{ +} +#include + +void tst_QEasingCurve::type() +{ + { + QEasingCurve curve(QEasingCurve::Linear); + QCOMPARE(curve.period(), 0.3); + QCOMPARE(curve.amplitude(), 1.0); + + curve.setPeriod(5); + curve.setAmplitude(3); + QCOMPARE(curve.period(), 5.0); + QCOMPARE(curve.amplitude(), 3.0); + + curve.setType(QEasingCurve::InElastic); + QCOMPARE(curve.period(), 5.0); + QCOMPARE(curve.amplitude(), 3.0); + } + + { + QEasingCurve curve(QEasingCurve::InElastic); + QCOMPARE(curve.period(), 0.3); + QCOMPARE(curve.amplitude(), 1.0); + curve.setAmplitude(2); + QCOMPARE(curve.type(), QEasingCurve::InElastic); + curve.setType(QEasingCurve::Linear); + } + + { + // check bounaries + QEasingCurve curve(QEasingCurve::InCubic); + QTest::ignoreMessage(QtWarningMsg, "QEasingCurve: Invalid curve type 9999"); + curve.setType((QEasingCurve::Type)9999); + QCOMPARE(curve.type(), QEasingCurve::InCubic); + QTest::ignoreMessage(QtWarningMsg, "QEasingCurve: Invalid curve type -9999"); + curve.setType((QEasingCurve::Type)-9999); + QCOMPARE(curve.type(), QEasingCurve::InCubic); + QTest::ignoreMessage(QtWarningMsg, QString::fromAscii("QEasingCurve: Invalid curve type %1") + .arg(QEasingCurve::NCurveTypes).toLatin1().constData()); + curve.setType(QEasingCurve::NCurveTypes); + QCOMPARE(curve.type(), QEasingCurve::InCubic); + QTest::ignoreMessage(QtWarningMsg, QString::fromAscii("QEasingCurve: Invalid curve type %1") + .arg(QEasingCurve::Custom).toLatin1().constData()); + curve.setType(QEasingCurve::Custom); + QCOMPARE(curve.type(), QEasingCurve::InCubic); + QTest::ignoreMessage(QtWarningMsg, QString::fromAscii("QEasingCurve: Invalid curve type %1") + .arg(-1).toLatin1().constData()); + curve.setType((QEasingCurve::Type)-1); + QCOMPARE(curve.type(), QEasingCurve::InCubic); + curve.setType(QEasingCurve::Linear); + QCOMPARE(curve.type(), QEasingCurve::Linear); + curve.setType(QEasingCurve::CosineCurve); + QCOMPARE(curve.type(), QEasingCurve::CosineCurve); + } +} + +void tst_QEasingCurve::propertyDefaults() +{ + { + // checks if the defaults are correct, but also demonstrates a weakness with the API. + QEasingCurve curve(QEasingCurve::InElastic); + QCOMPARE(curve.period(), 0.3); + QCOMPARE(curve.amplitude(), 1.0); + QCOMPARE(curve.overshoot(), qreal(1.70158f)); + curve.setType(QEasingCurve::InBounce); + QCOMPARE(curve.period(), 0.3); + QCOMPARE(curve.amplitude(), 1.0); + QCOMPARE(curve.overshoot(), qreal(1.70158f)); + curve.setType(QEasingCurve::Linear); + QCOMPARE(curve.period(), 0.3); + QCOMPARE(curve.amplitude(), 1.0); + QCOMPARE(curve.overshoot(), qreal(1.70158f)); + curve.setType(QEasingCurve::InElastic); + QCOMPARE(curve.period(), 0.3); + QCOMPARE(curve.amplitude(), 1.0); + QCOMPARE(curve.overshoot(), qreal(1.70158f)); + curve.setPeriod(0.4); + curve.setAmplitude(0.6); + curve.setOvershoot(1.0); + curve.setType(QEasingCurve::Linear); + QCOMPARE(curve.period(), 0.4); + QCOMPARE(curve.amplitude(), 0.6); + QCOMPARE(curve.overshoot(), 1.0); + curve.setType(QEasingCurve::InElastic); + QCOMPARE(curve.period(), 0.4); + QCOMPARE(curve.amplitude(), 0.6); + QCOMPARE(curve.overshoot(), 1.0); + } +} + +typedef QList IntList; +Q_DECLARE_METATYPE(IntList) + +void tst_QEasingCurve::valueForProgress_data() +{ + QTest::addColumn("type"); + QTest::addColumn("at"); + QTest::addColumn("expected"); + // automatically generated. + // note that values are scaled from range [0,1] to range [0, 100] in order to store them as + // integer values and avoid fp inaccuracies + + QTest::newRow("Linear") << int(QEasingCurve::Linear) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100); + + QTest::newRow("InQuad") << int(QEasingCurve::InQuad) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 1 << 4 << 9 << 16 << 25 << 36 << 48 << 64 << 81 << 100); + + QTest::newRow("OutQuad") << int(QEasingCurve::OutQuad) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 19 << 36 << 51 << 64 << 75 << 84 << 90 << 96 << 99 << 100); + + QTest::newRow("InOutQuad") << int(QEasingCurve::InOutQuad) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 2 << 8 << 18 << 32 << 50 << 68 << 82 << 92 << 98 << 100); + + QTest::newRow("OutInQuad") << int(QEasingCurve::OutInQuad) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 18 << 32 << 42 << 48 << 50 << 52 << 57 << 68 << 82 << 100); + + QTest::newRow("InCubic") << int(QEasingCurve::InCubic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 0 << 2 << 6 << 12 << 21 << 34 << 51 << 72 << 100); + + QTest::newRow("OutCubic") << int(QEasingCurve::OutCubic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 27 << 48 << 65 << 78 << 87 << 93 << 97 << 99 << 99 << 100); + + QTest::newRow("InOutCubic") << int(QEasingCurve::InOutCubic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 3 << 10 << 25 << 50 << 74 << 89 << 96 << 99 << 100); + + QTest::newRow("OutInCubic") << int(QEasingCurve::OutInCubic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 24 << 39 << 46 << 49 << 50 << 50 << 53 << 60 << 75 << 100); + + QTest::newRow("InQuart") << int(QEasingCurve::InQuart) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 0 << 0 << 2 << 6 << 12 << 24 << 40 << 65 << 100); + + QTest::newRow("OutQuart") << int(QEasingCurve::OutQuart) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 34 << 59 << 75 << 87 << 93 << 97 << 99 << 99 << 99 << 100); + + QTest::newRow("InOutQuart") << int(QEasingCurve::InOutQuart) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 1 << 6 << 20 << 50 << 79 << 93 << 98 << 99 << 100); + + QTest::newRow("OutInQuart") << int(QEasingCurve::OutInQuart) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 29 << 43 << 48 << 49 << 50 << 50 << 51 << 56 << 70 << 100); + + QTest::newRow("InQuint") << int(QEasingCurve::InQuint) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 0 << 0 << 1 << 3 << 7 << 16 << 32 << 59 << 100); + + QTest::newRow("OutQuint") << int(QEasingCurve::OutQuint) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 40 << 67 << 83 << 92 << 96 << 98 << 99 << 99 << 99 << 100); + + QTest::newRow("InOutQuint") << int(QEasingCurve::InOutQuint) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 0 << 3 << 16 << 50 << 83 << 96 << 99 << 99 << 100); + + QTest::newRow("OutInQuint") << int(QEasingCurve::OutInQuint) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 33 << 46 << 49 << 49 << 50 << 50 << 50 << 53 << 66 << 100); + + QTest::newRow("InSine") << int(QEasingCurve::InSine) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 1 << 4 << 10 << 19 << 29 << 41 << 54 << 69 << 84 << 100); + + QTest::newRow("OutSine") << int(QEasingCurve::OutSine) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 15 << 30 << 45 << 58 << 70 << 80 << 89 << 95 << 98 << 100); + + QTest::newRow("InOutSine") << int(QEasingCurve::InOutSine) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 2 << 9 << 20 << 34 << 49 << 65 << 79 << 90 << 97 << 100); + + QTest::newRow("OutInSine") << int(QEasingCurve::OutInSine) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 15 << 29 << 40 << 47 << 50 << 52 << 59 << 70 << 84 << 100); + + QTest::newRow("InExpo") << int(QEasingCurve::InExpo) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 0 << 0 << 1 << 3 << 6 << 12 << 24 << 49 << 100); + + QTest::newRow("OutExpo") << int(QEasingCurve::OutExpo) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 50 << 75 << 87 << 93 << 96 << 98 << 99 << 99 << 99 << 100); + + QTest::newRow("InOutExpo") << int(QEasingCurve::InOutExpo) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 0 << 3 << 12 << 50 << 87 << 96 << 99 << 99 << 100); + + QTest::newRow("OutInExpo") << int(QEasingCurve::OutInExpo) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 37 << 46 << 49 << 49 << 50 << 50 << 50 << 53 << 62 << 100); + + QTest::newRow("InCirc") << int(QEasingCurve::InCirc) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 2 << 4 << 8 << 13 << 19 << 28 << 40 << 56 << 100); + + QTest::newRow("OutCirc") << int(QEasingCurve::OutCirc) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 43 << 59 << 71 << 80 << 86 << 91 << 95 << 97 << 99 << 100); + + QTest::newRow("InOutCirc") << int(QEasingCurve::InOutCirc) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 1 << 4 << 9 << 20 << 50 << 80 << 89 << 95 << 98 << 100); + + QTest::newRow("OutInCirc") << int(QEasingCurve::OutInCirc) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 29 << 40 << 45 << 48 << 50 << 51 << 54 << 60 << 70 << 100); + + QTest::newRow("InElastic") << int(QEasingCurve::InElastic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 0 << 0 << 1 << -1 << -3 << 12 << -12 << -25 << 100); + + QTest::newRow("OutElastic") << int(QEasingCurve::OutElastic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 125 << 112 << 87 << 103 << 101 << 98 << 100 << 100 << 99 << 100); + + QTest::newRow("InOutElastic") << int(QEasingCurve::InOutElastic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 0 << 0 << -1 << -6 << 50 << 106 << 101 << 99 << 100 << 100); + + QTest::newRow("OutInElastic") << int(QEasingCurve::OutInElastic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 37 << 56 << 49 << 49 << 50 << 49 << 50 << 53 << 24 << 100); + + QTest::newRow("InBack") << int(QEasingCurve::InBack) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << -1 << -4 << -8 << -9 << -8 << -2 << 9 << 29 << 59 << 100); + + QTest::newRow("OutBack") << int(QEasingCurve::OutBack) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 40 << 70 << 90 << 102 << 108 << 109 << 108 << 104 << 101 << 100); + + QTest::newRow("InOutBack") << int(QEasingCurve::InOutBack) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << -3 << -9 << -7 << 8 << 50 << 91 << 107 << 109 << 103 << 100); + + QTest::newRow("OutInBack") << int(QEasingCurve::OutInBack) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 35 << 51 << 54 << 52 << 50 << 47 << 45 << 48 << 64 << 100); + + QTest::newRow("InBounce") << int(QEasingCurve::InBounce) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 1 << 6 << 6 << 22 << 23 << 9 << 31 << 69 << 92 << 100); + + QTest::newRow("OutBounce") << int(QEasingCurve::OutBounce) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 7 << 30 << 68 << 90 << 76 << 77 << 93 << 94 << 98 << 100); + + QTest::newRow("InOutBounce") << int(QEasingCurve::InOutBounce) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 3 << 11 << 4 << 34 << 50 << 65 << 95 << 88 << 97 << 100); + + QTest::newRow("OutInBounce") << int(QEasingCurve::OutInBounce) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 15 << 40 << 27 << 43 << 50 << 56 << 72 << 58 << 84 << 100); + + QTest::newRow("InCurve") << int(QEasingCurve::InCurve) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 2 << 10 << 23 << 37 << 50 << 60 << 70 << 80 << 90 << 100); + + QTest::newRow("OutCurve") << int(QEasingCurve::OutCurve) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 10 << 20 << 30 << 39 << 50 << 62 << 76 << 89 << 97 << 100); + + QTest::newRow("SineCurve") << int(QEasingCurve::SineCurve) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 0 << 9 << 34 << 65 << 90 << 100 << 90 << 65 << 34 << 9 << 0); + + QTest::newRow("CosineCurve") << int(QEasingCurve::CosineCurve) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (IntList() << 50 << 79 << 97 << 97 << 79 << 50 << 20 << 2 << 2 << 20 << 49); + +} + + +void tst_QEasingCurve::valueForProgress() +{ +#if 0 + // used to generate data tables... + QFile out; + out.open(stdout, QIODevice::WriteOnly); + for (int c = QEasingCurve::Linear; c < QEasingCurve::NCurveTypes - 1; ++c) { + QEasingCurve curve((QEasingCurve::Type)c); + QMetaObject mo = QEasingCurve::staticMetaObject; + QString strCurve = QLatin1String(mo.enumerator(mo.indexOfEnumerator("Type")).key(c)); + QString strInputs; + QString strOutputs; + + for (int t = 0; t <= 100; t+= 10) { + qreal ease = curve.valueForProgress(t/qreal(100)); + strInputs += QString::fromAscii(" << %1").arg(t); + strOutputs += QString::fromAscii(" << %1").arg(int(100*ease)); + + } + QString str = QString::fromAscii(" QTest::newRow(\"%1\") << int(QEasingCurve::%2)\n" + "\t\t << (IntList() %3)\n" + "\t\t << (IntList() %4);\n\n") + .arg(strCurve) + .arg(strCurve) + .arg(strInputs) + .arg(strOutputs); + out.write(str.toLatin1().constData()); + } + out.close(); + exit(1); +#else + QFETCH(int, type); + QFETCH(IntList, at); + QFETCH(IntList, expected); + + QEasingCurve curve((QEasingCurve::Type)type); + for (int i = 0; i < at.count(); ++i) { + qreal ease = curve.valueForProgress(at.at(i)/qreal(100)); + int ex = expected.at(i); + QCOMPARE(int(100*ease), ex); + } +#endif +} + +static qreal discreteEase(qreal progress) +{ + return qFloor(progress * 10) / qreal(10.0); +} + +void tst_QEasingCurve::setCustomType() +{ + QEasingCurve curve; + curve.setCustomType(&discreteEase); + QCOMPARE(curve.type(), QEasingCurve::Custom); + QCOMPARE(curve.valueForProgress(0.0), 0.0); + QCOMPARE(curve.valueForProgress(0.05), 0.0); + QCOMPARE(curve.valueForProgress(0.10), 0.1); + QCOMPARE(curve.valueForProgress(0.15), 0.1); + QCOMPARE(curve.valueForProgress(0.20), 0.2); + QCOMPARE(curve.valueForProgress(0.25), 0.2); + QCOMPARE(curve.valueForProgress(0.30), 0.3); + QCOMPARE(curve.valueForProgress(0.35), 0.3); + QCOMPARE(curve.valueForProgress(0.999999), 0.9); + + curve.setType(QEasingCurve::Linear); + QCOMPARE(curve.type(), QEasingCurve::Linear); + QCOMPARE(curve.valueForProgress(0.0), 0.0); + QCOMPARE(curve.valueForProgress(0.1), 0.1); + QCOMPARE(curve.valueForProgress(0.5), 0.5); + QCOMPARE(curve.valueForProgress(0.99), 0.99); +} + +void tst_QEasingCurve::operators() +{ + // operator= + QEasingCurve curve; + QEasingCurve curve2; + curve.setCustomType(&discreteEase); + curve2 = curve; + QCOMPARE(curve2.type(), QEasingCurve::Custom); + QCOMPARE(curve2.valueForProgress(0.0), 0.0); + QCOMPARE(curve2.valueForProgress(0.05), 0.0); + QCOMPARE(curve2.valueForProgress(0.15), 0.1); + QCOMPARE(curve2.valueForProgress(0.25), 0.2); + QCOMPARE(curve2.valueForProgress(0.35), 0.3); + QCOMPARE(curve2.valueForProgress(0.999999), 0.9); + + // operator== + curve.setType(QEasingCurve::InBack); + curve2 = curve; + curve2.setOvershoot(qreal(1.70158f)); + QCOMPARE(curve.overshoot(), curve2.overshoot()); + QVERIFY(curve2 == curve); + + curve.setOvershoot(3.0); + QVERIFY(curve2 != curve); + curve2.setOvershoot(3.0); + QVERIFY(curve2 == curve); + + curve2.setType(QEasingCurve::Linear); + QCOMPARE(curve.overshoot(), curve2.overshoot()); + QVERIFY(curve2 != curve); + curve2.setType(QEasingCurve::InBack); + QCOMPARE(curve.overshoot(), curve2.overshoot()); + QVERIFY(curve2 == curve); +} + + +QTEST_MAIN(tst_QEasingCurve) +#include "tst_qeasingcurve.moc" + +#endif //QT_VERSION diff --git a/tests/auto/qmake/testdata/bundle-spaces/some-file b/tests/auto/qmake/testdata/bundle-spaces/some-file index e69de29..9975dba 100644 --- a/tests/auto/qmake/testdata/bundle-spaces/some-file +++ b/tests/auto/qmake/testdata/bundle-spaces/some-file @@ -0,0 +1,6 @@ +all: + C:\git\qt-kinetic-animations\bin\qmake qdir.pro -o Makefile -spec win32-msvc2008 + nmake -f Makefile +first: all +qmake: + C:\git\qt-kinetic-animations\bin\qmake qdir.pro -o Makefile -spec win32-msvc2008 diff --git a/tests/auto/qparallelanimationgroup/qparallelanimationgroup.pro b/tests/auto/qparallelanimationgroup/qparallelanimationgroup.pro new file mode 100644 index 0000000..f2cacd3 --- /dev/null +++ b/tests/auto/qparallelanimationgroup/qparallelanimationgroup.pro @@ -0,0 +1,5 @@ +load(qttest_p4) +QT = core gui +SOURCES += tst_qparallelanimationgroup.cpp + + diff --git a/tests/auto/qparallelanimationgroup/tst_qparallelanimationgroup.cpp b/tests/auto/qparallelanimationgroup/tst_qparallelanimationgroup.cpp new file mode 100644 index 0000000..f2ab57a --- /dev/null +++ b/tests/auto/qparallelanimationgroup/tst_qparallelanimationgroup.cpp @@ -0,0 +1,834 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include + +//TESTED_CLASS=QParallelAnimationGroup +//TESTED_FILES= + +Q_DECLARE_METATYPE(QAbstractAnimation::State) + +class tst_QParallelAnimationGroup : public QObject +{ + Q_OBJECT +public: + tst_QParallelAnimationGroup(); + virtual ~tst_QParallelAnimationGroup(); + +public Q_SLOTS: + void init(); + void cleanup(); + +private slots: + void construction(); + void setCurrentTime(); + void clearGroup(); + void propagateGroupUpdateToChildren(); + void updateChildrenWithRunningGroup(); + void deleteChildrenWithRunningGroup(); + void startChildrenWithStoppedGroup(); + void stopGroupWithRunningChild(); + void startGroupWithRunningChild(); + void zeroDurationAnimation(); + void stopUncontrolledAnimations(); + void loopCount_data(); + void loopCount(); + void autoAdd(); +}; + +tst_QParallelAnimationGroup::tst_QParallelAnimationGroup() +{ +} + +tst_QParallelAnimationGroup::~tst_QParallelAnimationGroup() +{ +} + +void tst_QParallelAnimationGroup::init() +{ + qRegisterMetaType("QAbstractAnimation::State"); +} + +void tst_QParallelAnimationGroup::cleanup() +{ +} + +void tst_QParallelAnimationGroup::construction() +{ + QParallelAnimationGroup animationgroup; +} + +class AnimationObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(int value READ value WRITE setValue) +public: + AnimationObject(int startValue = 0) + : v(startValue) + { } + + int value() const { return v; } + void setValue(int value) { v = value; } + + int v; +}; + +class TestAnimation : public QVariantAnimation +{ + Q_OBJECT +public: + virtual void updateCurrentValue(const QVariant &value) { Q_UNUSED(value)}; + virtual void updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) + { + Q_UNUSED(oldState) + Q_UNUSED(newState) + }; +}; + +class TestAnimation2 : public QVariantAnimation +{ + Q_OBJECT +public: + TestAnimation2(QAbstractAnimation *animation) : QVariantAnimation(animation) {} + TestAnimation2(int duration, QAbstractAnimation *animation) : QVariantAnimation(animation), m_duration(duration) {} + + virtual void updateCurrentValue(const QVariant &value) { Q_UNUSED(value)}; + virtual void updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) + { + Q_UNUSED(oldState) + Q_UNUSED(newState) + }; + + virtual int duration() const { + return m_duration; + } +private: + int m_duration; +}; + +class UncontrolledAnimation : public QPropertyAnimation +{ + Q_OBJECT +public: + UncontrolledAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0) + : QPropertyAnimation(target, propertyName, parent), id(0) + { + setDuration(250); + } + + int duration() const { return -1; /* not time driven */ } + +protected: + void timerEvent(QTimerEvent *event) + { + if (event->timerId() == id) + stop(); + } + + void updateRunning(bool running) + { + if (running) { + id = startTimer(500); + } else { + killTimer(id); + id = 0; + } + } + +private: + int id; +}; + +void tst_QParallelAnimationGroup::setCurrentTime() +{ + AnimationObject p_o1; + AnimationObject p_o2; + AnimationObject p_o3; + AnimationObject t_o1; + AnimationObject t_o2; + + // parallel operating on different object/properties + QAnimationGroup *parallel = new QParallelAnimationGroup(); + QVariantAnimation *a1_p_o1 = new QPropertyAnimation(&p_o1, "value"); + QVariantAnimation *a1_p_o2 = new QPropertyAnimation(&p_o2, "value"); + QVariantAnimation *a1_p_o3 = new QPropertyAnimation(&p_o3, "value"); + a1_p_o2->setLoopCount(3); + parallel->addAnimation(a1_p_o1); + parallel->addAnimation(a1_p_o2); + parallel->addAnimation(a1_p_o3); + + UncontrolledAnimation *notTimeDriven = new UncontrolledAnimation(&t_o1, "value"); + QCOMPARE(notTimeDriven->totalDuration(), -1); + + QVariantAnimation *loopsForever = new QPropertyAnimation(&t_o2, "value"); + loopsForever->setLoopCount(-1); + QCOMPARE(loopsForever->totalDuration(), -1); + + QParallelAnimationGroup group; + group.addAnimation(parallel); + group.addAnimation(notTimeDriven); + group.addAnimation(loopsForever); + + // Current time = 1 + group.setCurrentTime(1); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(parallel->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_p_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_p_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_p_o3->state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); + + QCOMPARE(group.currentTime(), 1); + QCOMPARE(a1_p_o1->currentTime(), 1); + QCOMPARE(a1_p_o2->currentTime(), 1); + QCOMPARE(a1_p_o3->currentTime(), 1); + QCOMPARE(notTimeDriven->currentTime(), 1); + QCOMPARE(loopsForever->currentTime(), 1); + + // Current time = 250 + group.setCurrentTime(250); + QCOMPARE(group.currentTime(), 250); + QCOMPARE(a1_p_o1->currentTime(), 250); + QCOMPARE(a1_p_o2->currentTime(), 0); + QCOMPARE(a1_p_o2->currentLoop(), 1); + QCOMPARE(a1_p_o3->currentTime(), 250); + QCOMPARE(notTimeDriven->currentTime(), 250); + QCOMPARE(loopsForever->currentTime(), 0); + QCOMPARE(loopsForever->currentLoop(), 1); + + // Current time = 251 + group.setCurrentTime(251); + QCOMPARE(group.currentTime(), 251); + QCOMPARE(a1_p_o1->currentTime(), 250); + QCOMPARE(a1_p_o2->currentTime(), 1); + QCOMPARE(a1_p_o2->currentLoop(), 1); + QCOMPARE(a1_p_o3->currentTime(), 250); + QCOMPARE(notTimeDriven->currentTime(), 251); + QCOMPARE(loopsForever->currentTime(), 1); +} + +void tst_QParallelAnimationGroup::clearGroup() +{ + QParallelAnimationGroup group; + + for (int i = 0; i < 10; ++i) { + new QParallelAnimationGroup(&group); + } + + QCOMPARE(group.animationCount(), 10); + + int count = group.animationCount(); + QPointer *children = new QPointer[count]; + for (int i = 0; i < count; ++i) { + QVERIFY(group.animationAt(i) != 0); + children[i] = group.animationAt(i); + } + + group.clearAnimations(); + QCOMPARE(group.animationCount(), 0); + QCOMPARE(group.currentTime(), 0); + for (int i = 0; i < count; ++i) + QCOMPARE(children[i], QPointer()); + + delete[] children; +} + +void tst_QParallelAnimationGroup::propagateGroupUpdateToChildren() +{ + // this test verifies if group state changes are updating its children correctly + QParallelAnimationGroup group; + + QObject o; + o.setProperty("ole", 42); + QCOMPARE(o.property("ole").toInt(), 42); + + QPropertyAnimation anim1(&o, "ole"); + anim1.setEndValue(43); + anim1.setDuration(100); + QVERIFY(!anim1.currentValue().isValid()); + QCOMPARE(anim1.currentValue().toInt(), 0); + QCOMPARE(o.property("ole").toInt(), 42); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(200); + + QVERIFY(anim2.currentValue().isValid()); + QCOMPARE(anim2.currentValue().toInt(), 0); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + + group.start(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Running); + + group.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Paused); + QCOMPARE(anim1.state(), QAnimationGroup::Paused); + QCOMPARE(anim2.state(), QAnimationGroup::Paused); + + group.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); +} + +void tst_QParallelAnimationGroup::updateChildrenWithRunningGroup() +{ + // assert that its possible to modify a child's state directly while their group is running + QParallelAnimationGroup group; + + TestAnimation anim; + anim.setStartValue(0); + anim.setEndValue(100); + anim.setDuration(200); + + QSignalSpy groupStateChangedSpy(&group, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy childStateChangedSpy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + QCOMPARE(groupStateChangedSpy.count(), 0); + QCOMPARE(childStateChangedSpy.count(), 0); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim); + + group.start(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim.state(), QAnimationGroup::Running); + + QCOMPARE(groupStateChangedSpy.count(), 1); + QCOMPARE(childStateChangedSpy.count(), 1); + + QCOMPARE(qVariantValue(groupStateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(childStateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + + // starting directly a running child will not have any effect + anim.start(); + + QCOMPARE(groupStateChangedSpy.count(), 1); + QCOMPARE(childStateChangedSpy.count(), 1); + + anim.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim.state(), QAnimationGroup::Paused); + + // in the animation stops directly, the group will still be running + anim.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim.state(), QAnimationGroup::Stopped); +} + +void tst_QParallelAnimationGroup::deleteChildrenWithRunningGroup() +{ + // test if children can be activated when their group is stopped + QParallelAnimationGroup group; + + QVariantAnimation *anim1 = new TestAnimation; + anim1->setStartValue(0); + anim1->setEndValue(100); + anim1->setDuration(200); + group.addAnimation(anim1); + + QCOMPARE(group.duration(), anim1->duration()); + + group.start(); + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim1->state(), QAnimationGroup::Running); + + QTest::qWait(50); + QVERIFY(group.currentTime() > 0); + + delete anim1; + QVERIFY(group.animationCount() == 0); + QCOMPARE(group.duration(), 0); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(group.currentTime(), 0); //that's the invariant +} + +void tst_QParallelAnimationGroup::startChildrenWithStoppedGroup() +{ + // test if children can be activated when their group is stopped + QParallelAnimationGroup group; + + TestAnimation anim1; + anim1.setStartValue(0); + anim1.setEndValue(100); + anim1.setDuration(200); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(200); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + + group.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + anim1.start(); + anim2.start(); + anim2.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Paused); +} + +void tst_QParallelAnimationGroup::stopGroupWithRunningChild() +{ + // children that started independently will not be affected by a group stop + QParallelAnimationGroup group; + + TestAnimation anim1; + anim1.setStartValue(0); + anim1.setEndValue(100); + anim1.setDuration(200); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(200); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + + anim1.start(); + anim2.start(); + anim2.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Paused); + + group.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Paused); + + anim1.stop(); + anim2.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); +} + +void tst_QParallelAnimationGroup::startGroupWithRunningChild() +{ + // as the group has precedence over its children, starting a group will restart all the children + QParallelAnimationGroup group; + + TestAnimation anim1; + anim1.setStartValue(0); + anim1.setEndValue(100); + anim1.setDuration(200); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(200); + + QSignalSpy stateChangedSpy1(&anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy stateChangedSpy2(&anim2, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + QCOMPARE(stateChangedSpy1.count(), 0); + QCOMPARE(stateChangedSpy2.count(), 0); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + + anim1.start(); + anim2.start(); + anim2.pause(); + + QCOMPARE(qVariantValue(stateChangedSpy1.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(stateChangedSpy2.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(stateChangedSpy2.at(1).at(1)), + QAnimationGroup::Paused); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Paused); + + group.start(); + + QCOMPARE(stateChangedSpy1.count(), 3); + QCOMPARE(qVariantValue(stateChangedSpy1.at(1).at(1)), + QAnimationGroup::Stopped); + QCOMPARE(qVariantValue(stateChangedSpy1.at(2).at(1)), + QAnimationGroup::Running); + + QCOMPARE(stateChangedSpy2.count(), 4); + QCOMPARE(qVariantValue(stateChangedSpy2.at(2).at(1)), + QAnimationGroup::Stopped); + QCOMPARE(qVariantValue(stateChangedSpy2.at(3).at(1)), + QAnimationGroup::Running); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Running); +} + +void tst_QParallelAnimationGroup::zeroDurationAnimation() +{ + QParallelAnimationGroup group; + + TestAnimation anim1; + anim1.setStartValue(0); + anim1.setEndValue(100); + anim1.setDuration(0); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(100); + + QSignalSpy stateChangedSpy1(&anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy finishedSpy1(&anim1, SIGNAL(finished())); + + QSignalSpy stateChangedSpy2(&anim2, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy finishedSpy2(&anim2, SIGNAL(finished())); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + QCOMPARE(stateChangedSpy1.count(), 0); + group.start(); + QCOMPARE(stateChangedSpy1.count(), 2); + QCOMPARE(finishedSpy1.count(), 1); + QCOMPARE(qVariantValue(stateChangedSpy1.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(stateChangedSpy1.at(1).at(1)), + QAnimationGroup::Stopped); + + QCOMPARE(stateChangedSpy2.count(), 1); + QCOMPARE(finishedSpy2.count(), 0); + QCOMPARE(qVariantValue(stateChangedSpy1.at(0).at(1)), + QAnimationGroup::Running); + + + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Running); + QCOMPARE(group.state(), QAnimationGroup::Running); + + + group.stop(); + group.setLoopCount(4); + stateChangedSpy1.clear(); + stateChangedSpy2.clear(); + + group.start(); + QCOMPARE(stateChangedSpy1.count(), 2); + QCOMPARE(stateChangedSpy2.count(), 1); + group.setCurrentTime(50); + QCOMPARE(stateChangedSpy1.count(), 2); + QCOMPARE(stateChangedSpy2.count(), 1); + group.setCurrentTime(150); + QCOMPARE(stateChangedSpy1.count(), 4); + QCOMPARE(stateChangedSpy2.count(), 3); + group.setCurrentTime(50); + QCOMPARE(stateChangedSpy1.count(), 6); + QCOMPARE(stateChangedSpy2.count(), 5); + +} + +void tst_QParallelAnimationGroup::stopUncontrolledAnimations() +{ + QParallelAnimationGroup group; + + TestAnimation anim1; + anim1.setStartValue(0); + anim1.setEndValue(100); + anim1.setDuration(0); + + AnimationObject o1; + UncontrolledAnimation notTimeDriven(&o1, "value"); + QCOMPARE(notTimeDriven.totalDuration(), -1); + + TestAnimation loopsForever; + loopsForever.setStartValue(0); + loopsForever.setEndValue(100); + loopsForever.setDuration(100); + loopsForever.setLoopCount(-1); + + QSignalSpy stateChangedSpy(&anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + group.addAnimation(&anim1); + group.addAnimation(¬TimeDriven); + group.addAnimation(&loopsForever); + + group.start(); + + QCOMPARE(stateChangedSpy.count(), 2); + QCOMPARE(qVariantValue(stateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(stateChangedSpy.at(1).at(1)), + QAnimationGroup::Stopped); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Running); + QCOMPARE(loopsForever.state(), QAnimationGroup::Running); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + + notTimeDriven.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever.state(), QAnimationGroup::Running); + + loopsForever.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever.state(), QAnimationGroup::Stopped); +} + +struct AnimState { + AnimState(int time = -1) : time(time), state(-1) {} + AnimState(int time, int state) : time(time), state(state) {} + int time; + int state; +}; + +#define Running QAbstractAnimation::Running +#define Stopped QAbstractAnimation::Stopped + +Q_DECLARE_METATYPE(AnimState) +void tst_QParallelAnimationGroup::loopCount_data() +{ + QTest::addColumn("directionBackward"); + QTest::addColumn("setLoopCount"); + QTest::addColumn("initialGroupTime"); + QTest::addColumn("currentGroupTime"); + QTest::addColumn("expected1"); + QTest::addColumn("expected2"); + QTest::addColumn("expected3"); + + // D U R A T I O N + // 100 60*2 0 + // direction = Forward + QTest::newRow("50") << false << 3 << 0 << 50 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("100") << false << 3 << 0 << 100 << AnimState(100 ) << AnimState( 40, Running) << AnimState( 0, Stopped); + QTest::newRow("110") << false << 3 << 0 << 110 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("120") << false << 3 << 0 << 120 << AnimState( 0, Running) << AnimState( 0, Running) << AnimState( 0, Stopped); + + QTest::newRow("170") << false << 3 << 0 << 170 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("220") << false << 3 << 0 << 220 << AnimState(100 ) << AnimState( 40, Running) << AnimState( 0, Stopped); + QTest::newRow("230") << false << 3 << 0 << 230 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("240") << false << 3 << 0 << 240 << AnimState( 0, Running) << AnimState( 0, Running) << AnimState( 0, Stopped); + + QTest::newRow("290") << false << 3 << 0 << 290 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("340") << false << 3 << 0 << 340 << AnimState(100 ) << AnimState( 40, Running) << AnimState( 0, Stopped); + QTest::newRow("350") << false << 3 << 0 << 350 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("360") << false << 3 << 0 << 360 << AnimState(100, Stopped) << AnimState( 60 ) << AnimState( 0, Stopped); + + QTest::newRow("410") << false << 3 << 0 << 410 << AnimState(100, Stopped) << AnimState( 60, Stopped) << AnimState( 0, Stopped); + QTest::newRow("460") << false << 3 << 0 << 460 << AnimState(100, Stopped) << AnimState( 60, Stopped) << AnimState( 0, Stopped); + QTest::newRow("470") << false << 3 << 0 << 470 << AnimState(100, Stopped) << AnimState( 60, Stopped) << AnimState( 0, Stopped); + QTest::newRow("480") << false << 3 << 0 << 480 << AnimState(100, Stopped) << AnimState( 60, Stopped) << AnimState( 0, Stopped); + + // direction = Forward, rewind + QTest::newRow("120-110") << false << 3 << 120 << 110 << AnimState( 0, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("120-50") << false << 3 << 120 << 50 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("120-0") << false << 3 << 120 << 0 << AnimState( 0, Running) << AnimState( 0, Running) << AnimState( 0, Stopped); + QTest::newRow("300-110") << false << 3 << 300 << 110 << AnimState( 0, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("300-50") << false << 3 << 300 << 50 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("300-0") << false << 3 << 300 << 0 << AnimState( 0, Running) << AnimState( 0, Running) << AnimState( 0, Stopped); + QTest::newRow("115-105") << false << 3 << 115 << 105 << AnimState( 42, Stopped) << AnimState( 45, Running) << AnimState( 0, Stopped); + + // direction = Backward + QTest::newRow("b120-120") << true << 3 << 120 << 120 << AnimState( 42, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); + QTest::newRow("b120-110") << true << 3 << 120 << 110 << AnimState( 42, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("b120-100") << true << 3 << 120 << 100 << AnimState(100, Running) << AnimState( 40, Running) << AnimState( 0, Stopped); + QTest::newRow("b120-50") << true << 3 << 120 << 50 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("b120-0") << true << 3 << 120 << 0 << AnimState( 0, Stopped) << AnimState( 0, Stopped) << AnimState( 0, Stopped); + QTest::newRow("b360-170") << true << 3 << 360 << 170 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("b360-220") << true << 3 << 360 << 220 << AnimState(100, Running) << AnimState( 40, Running) << AnimState( 0, Stopped); + QTest::newRow("b360-210") << true << 3 << 360 << 210 << AnimState( 90, Running) << AnimState( 30, Running) << AnimState( 0, Stopped); + QTest::newRow("b360-120") << true << 3 << 360 << 120 << AnimState( 0, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); + + // rewind, direction = Backward + QTest::newRow("b50-110") << true << 3 << 50 << 110 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + QTest::newRow("b50-120") << true << 3 << 50 << 120 << AnimState(100, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); + QTest::newRow("b50-140") << true << 3 << 50 << 140 << AnimState( 20, Running) << AnimState( 20, Running) << AnimState( 0, Stopped); + QTest::newRow("b50-240") << true << 3 << 50 << 240 << AnimState(100, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); + QTest::newRow("b50-260") << true << 3 << 50 << 260 << AnimState( 20, Running) << AnimState( 20, Running) << AnimState( 0, Stopped); + QTest::newRow("b50-350") << true << 3 << 50 << 350 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + + // infinite looping + QTest::newRow("inf1220") << false << -1 << 0 << 1220 << AnimState( 20, Running) << AnimState( 20, Running) << AnimState( 0, Stopped); + QTest::newRow("inf1310") << false << -1 << 0 << 1310 << AnimState( 100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + // infinite looping, direction = Backward (will only loop once) + QTest::newRow("b.inf120-120") << true << -1 << 120 << 120 << AnimState( 42, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); + QTest::newRow("b.inf120-20") << true << -1 << 120 << 20 << AnimState( 20, Running) << AnimState( 20, Running) << AnimState( 0, Stopped); + QTest::newRow("b.inf120-110") << true << -1 << 120 << 110 << AnimState( 42, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); + + +} + +void tst_QParallelAnimationGroup::loopCount() +{ + QFETCH(bool, directionBackward); + QFETCH(int, setLoopCount); + QFETCH(int, initialGroupTime); + QFETCH(int, currentGroupTime); + QFETCH(AnimState, expected1); + QFETCH(AnimState, expected2); + QFETCH(AnimState, expected3); + + QParallelAnimationGroup group; + + TestAnimation anim1; + anim1.setStartValue(0); + anim1.setEndValue(100); + anim1.setDuration(100); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(60); //total 120 + anim2.setLoopCount(2); + + TestAnimation anim3; + anim3.setStartValue(0); + anim3.setEndValue(100); + anim3.setDuration(0); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + group.addAnimation(&anim3); + + group.setLoopCount(setLoopCount); + if (initialGroupTime >= 0) + group.setCurrentTime(initialGroupTime); + if (directionBackward) + group.setDirection(QAbstractAnimation::Backward); + + group.start(); + if (initialGroupTime >= 0) + group.setCurrentTime(initialGroupTime); + + anim1.setCurrentTime(42); // 42 is "untouched" + anim2.setCurrentTime(42); + + group.setCurrentTime(currentGroupTime); + + QCOMPARE(anim1.currentTime(), expected1.time); + QCOMPARE(anim2.currentTime(), expected2.time); + QCOMPARE(anim3.currentTime(), expected3.time); + + if (expected1.state >=0) + QCOMPARE(int(anim1.state()), expected1.state); + if (expected2.state >=0) + QCOMPARE(int(anim2.state()), expected2.state); + if (expected3.state >=0) + QCOMPARE(int(anim3.state()), expected3.state); + +} + +void tst_QParallelAnimationGroup::autoAdd() +{ + QParallelAnimationGroup group; + QCOMPARE(group.duration(), 0); + TestAnimation2 *test = new TestAnimation2(250, &group); // 0, duration = 250; + QCOMPARE(test->group(), &group); + QCOMPARE(test->duration(), 250); + QCOMPARE(group.duration(), 250); + + test = new TestAnimation2(750, &group); // 1 + QCOMPARE(test->group(), &group); + QCOMPARE(group.duration(), 750); + test = new TestAnimation2(500, &group); // 2 + QCOMPARE(test->group(), &group); + QCOMPARE(group.duration(), 750); + + delete group.animationAt(1); // remove the one with duration = 750 + QCOMPARE(group.duration(), 500); + + delete group.animationAt(1); // remove the one with duration = 500 + QCOMPARE(group.duration(), 250); + + test = static_cast(group.animationAt(0)); + test->setParent(0); // remove the last one (with duration = 250) + QCOMPARE(test->group(), static_cast(0)); + QCOMPARE(group.duration(), 0); +} + +QTEST_MAIN(tst_QParallelAnimationGroup) +#include "tst_qparallelanimationgroup.moc" diff --git a/tests/auto/qpropertyanimation/qpropertyanimation.pro b/tests/auto/qpropertyanimation/qpropertyanimation.pro new file mode 100644 index 0000000..6d6ddbf --- /dev/null +++ b/tests/auto/qpropertyanimation/qpropertyanimation.pro @@ -0,0 +1,5 @@ +load(qttest_p4) +QT = core gui +SOURCES += tst_qpropertyanimation.cpp + + diff --git a/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp b/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp new file mode 100644 index 0000000..7e910d4 --- /dev/null +++ b/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp @@ -0,0 +1,919 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include +#include +#include + +//TESTED_CLASS=QPropertyAnimation +//TESTED_FILES= + +class UncontrolledAnimation : public QPropertyAnimation +{ + Q_OBJECT +public: + int duration() const { return -1; /* not time driven */ } + +protected: + void updateCurrentTime(int msecs) + { + QPropertyAnimation::updateCurrentTime(msecs); + if (msecs >= QPropertyAnimation::duration()) + stop(); + } +}; + +class tst_QPropertyAnimation : public QObject +{ + Q_OBJECT +public: + tst_QPropertyAnimation(); + virtual ~tst_QPropertyAnimation(); + +public Q_SLOTS: + void init(); + void cleanup(); + +private slots: + void construction(); + void setCurrentTime_data(); + void setCurrentTime(); + void statesAndSignals_data(); + void statesAndSignals(); + void deletion1(); + void deletion2(); + void deletion3(); + void duration0(); + void noStartValue(); + void noStartValueWithLoop(); + void startWhenAnotherIsRunning(); + void easingcurve_data(); + void easingcurve(); + void startWithoutStartValue(); + void playForwardBackward(); + void interpolated(); + void setStartEndValues(); + void zeroDurationStart(); + void operationsInStates_data(); + void operationsInStates(); + void oneKeyValue(); + void updateOnSetKeyValues(); +}; + +tst_QPropertyAnimation::tst_QPropertyAnimation() +{ +} + +tst_QPropertyAnimation::~tst_QPropertyAnimation() +{ +} + +void tst_QPropertyAnimation::init() +{ + qRegisterMetaType("QAbstractAnimation::State"); + qRegisterMetaType("QAbstractAnimation::DeletionPolicy"); +} + +void tst_QPropertyAnimation::cleanup() +{ +} + +class AnimationObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(int value READ value WRITE setValue) + Q_PROPERTY(qreal realValue READ realValue WRITE setRealValue) +public: + AnimationObject(int startValue = 0) + : v(startValue) + { } + + int value() const { return v; } + void setValue(int value) { v = value; } + + qreal realValue() const { return rv; } + void setRealValue(qreal value) { rv = value; } + + int v; + qreal rv; +}; + + +void tst_QPropertyAnimation::construction() +{ + QPropertyAnimation panimation; +} + +void tst_QPropertyAnimation::setCurrentTime_data() +{ + QTest::addColumn("duration"); + QTest::addColumn("loopCount"); + QTest::addColumn("currentTime"); + QTest::addColumn("testCurrentTime"); + QTest::addColumn("testCurrentLoop"); + + QTest::newRow("-1") << -1 << 1 << 0 << 0 << 0; + QTest::newRow("0") << 0 << 1 << 0 << 0 << 0; + QTest::newRow("1") << 0 << 1 << 1 << 0 << 0; + QTest::newRow("2") << 0 << 2 << 1 << 0 << 0; + QTest::newRow("3") << 1 << 1 << 0 << 0 << 0; + QTest::newRow("4") << 1 << 1 << 1 << 1 << 0; + QTest::newRow("5") << 1 << 2 << 1 << 0 << 1; + QTest::newRow("6") << 1 << 2 << 2 << 1 << 1; + QTest::newRow("7") << 1 << 2 << 3 << 1 << 1; + QTest::newRow("8") << 1 << 3 << 2 << 0 << 2; + QTest::newRow("9") << 1 << 3 << 3 << 1 << 2; + QTest::newRow("a") << 10 << 1 << 0 << 0 << 0; + QTest::newRow("b") << 10 << 1 << 1 << 1 << 0; + QTest::newRow("c") << 10 << 1 << 10 << 10 << 0; + QTest::newRow("d") << 10 << 2 << 10 << 0 << 1; + QTest::newRow("e") << 10 << 2 << 11 << 1 << 1; + QTest::newRow("f") << 10 << 2 << 20 << 10 << 1; + QTest::newRow("g") << 10 << 2 << 21 << 10 << 1; + QTest::newRow("negloop 0") << 10 << -1 << 0 << 0 << 0; + QTest::newRow("negloop 1") << 10 << -1 << 10 << 0 << 1; + QTest::newRow("negloop 2") << 10 << -1 << 15 << 5 << 1; + QTest::newRow("negloop 3") << 10 << -1 << 20 << 0 << 2; + QTest::newRow("negloop 4") << 10 << -1 << 30 << 0 << 3; +} + +void tst_QPropertyAnimation::setCurrentTime() +{ + QFETCH(int, duration); + QFETCH(int, loopCount); + QFETCH(int, currentTime); + QFETCH(int, testCurrentTime); + QFETCH(int, testCurrentLoop); + + QPropertyAnimation animation; + if (duration < 0) + QTest::ignoreMessage(QtWarningMsg, "QVariantAnimation::setDuration: cannot set a negative duration"); + animation.setDuration(duration); + animation.setLoopCount(loopCount); + animation.setCurrentTime(currentTime); + + QCOMPARE(animation.currentTime(), testCurrentTime); + QCOMPARE(animation.currentLoop(), testCurrentLoop); +} + +void tst_QPropertyAnimation::statesAndSignals_data() +{ + QTest::addColumn("uncontrolled"); + QTest::newRow("normal animation") << false; + QTest::newRow("animation with undefined duration") << true; +} + +void tst_QPropertyAnimation::statesAndSignals() +{ + QFETCH(bool, uncontrolled); + QPropertyAnimation *anim = uncontrolled ? new UncontrolledAnimation : new QPropertyAnimation; + anim->setDuration(100); + + QSignalSpy finishedSpy(anim, SIGNAL(finished())); + QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy currentLoopSpy(anim, SIGNAL(currentLoopChanged(int))); + + anim->setCurrentTime(1); + anim->setCurrentTime(100); + QCOMPARE(finishedSpy.count(), 0); + QCOMPARE(runningSpy.count(), 0); + QCOMPARE(currentLoopSpy.count(), 0); + QCOMPARE(anim->state(), QAnimationGroup::Stopped); + + anim->setLoopCount(3); + anim->setCurrentTime(101); + + if (uncontrolled) + QSKIP("Uncontrolled animations don't handle looping", SkipSingle); + + QCOMPARE(currentLoopSpy.count(), 1); + QCOMPARE(anim->currentLoop(), 1); + + anim->setCurrentTime(0); + QCOMPARE(currentLoopSpy.count(), 2); + QCOMPARE(anim->currentLoop(), 0); + + anim->start(); + QCOMPARE(anim->state(), QAnimationGroup::Running); + QCOMPARE(runningSpy.count(), 1); //anim must have started + QCOMPARE(anim->currentLoop(), 0); + runningSpy.clear(); + + anim->stop(); + QCOMPARE(anim->state(), QAnimationGroup::Stopped); + QCOMPARE(runningSpy.count(), 1); //anim must have stopped + QCOMPARE(finishedSpy.count(), 0); + QCOMPARE(anim->currentTime(), 0); + QCOMPARE(anim->currentLoop(), 0); + QCOMPARE(currentLoopSpy.count(), 2); + runningSpy.clear(); + + anim->start(); + QTest::qWait(1000); + QCOMPARE(anim->state(), QAnimationGroup::Stopped); + QCOMPARE(runningSpy.count(), 2); //started and stopped again + runningSpy.clear(); + QCOMPARE(finishedSpy.count(), 1); + QCOMPARE(anim->currentTime(), 100); + QCOMPARE(anim->currentLoop(), 2); + QCOMPARE(currentLoopSpy.count(), 4); + + anim->start(); // auto-rewinds + QCOMPARE(anim->state(), QAnimationGroup::Running); + QCOMPARE(anim->currentTime(), 0); + QCOMPARE(anim->currentLoop(), 0); + QCOMPARE(currentLoopSpy.count(), 5); + QCOMPARE(runningSpy.count(), 1); // anim has started + QCOMPARE(finishedSpy.count(), 1); + QCOMPARE(anim->currentLoop(), 0); + runningSpy.clear(); + + QTest::qWait(1000); + + QCOMPARE(currentLoopSpy.count(), 7); + QCOMPARE(anim->state(), QAnimationGroup::Stopped); + QCOMPARE(anim->currentLoop(), 2); + QCOMPARE(runningSpy.count(), 1); // anim has stopped + QCOMPARE(finishedSpy.count(), 2); + QCOMPARE(anim->currentTime(), 100); + + delete anim; +} + +void tst_QPropertyAnimation::deletion1() +{ + QObject *object = new QWidget; + QPointer anim = new QPropertyAnimation(object,"minimumWidth"); + + //test that the animation is deleted correctly depending of the deletion flag passed in start() + QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy finishedSpy(anim, SIGNAL(finished())); + anim->setStartValue(10); + anim->setEndValue(20); + anim->setDuration(200); + anim->start(); + QCOMPARE(runningSpy.count(), 1); + QCOMPARE(finishedSpy.count(), 0); + + QVERIFY(anim); + QCOMPARE(anim->state(), QAnimationGroup::Running); + QTest::qWait(100); + QVERIFY(anim); + QCOMPARE(anim->state(), QAnimationGroup::Running); + QTest::qWait(150); + QVERIFY(anim); //The animation should not have been deleted + QCOMPARE(anim->state(), QAnimationGroup::Stopped); + QCOMPARE(runningSpy.count(), 2); + QCOMPARE(finishedSpy.count(), 1); + + anim->start(QVariantAnimation::DeleteWhenStopped); + QVERIFY(anim); + QCOMPARE(anim->state(), QAnimationGroup::Running); + QTest::qWait(100); + QVERIFY(anim); + QCOMPARE(anim->state(), QAnimationGroup::Running); + QTest::qWait(150); + QVERIFY(!anim); //The animation must have been deleted + QCOMPARE(runningSpy.count(), 4); + QCOMPARE(finishedSpy.count(), 2); + delete object; +} + +void tst_QPropertyAnimation::deletion2() +{ + //test that the animation get deleted if the object is deleted + QObject *object = new QWidget; + QPointer anim = new QPropertyAnimation(object,"minimumWidth"); + anim->setStartValue(10); + anim->setEndValue(20); + anim->setDuration(200); + + QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy finishedSpy(anim, SIGNAL(finished())); + + anim->setStartValue(10); + anim->setEndValue(20); + anim->setDuration(200); + anim->start(); + + QTest::qWait(50); + QVERIFY(anim); + QCOMPARE(anim->state(), QAnimationGroup::Running); + + QCOMPARE(runningSpy.count(), 1); + QCOMPARE(finishedSpy.count(), 0); + + //we can't call deletaLater directly because the delete would only happen in the next loop of _this_ event loop + QTimer::singleShot(0, object, SLOT(deleteLater())); + QTest::qWait(50); + + QVERIFY(anim->targetObject() == 0); +} + +void tst_QPropertyAnimation::deletion3() +{ + //test that the stopped signal is emit when the animation is destroyed + QObject *object = new QWidget; + QPropertyAnimation *anim = new QPropertyAnimation(object,"minimumWidth"); + anim->setStartValue(10); + anim->setEndValue(20); + anim->setDuration(200); + + QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy finishedSpy(anim, SIGNAL(finished())); + anim->start(); + + QTest::qWait(50); + QCOMPARE(anim->state(), QAnimationGroup::Running); + QCOMPARE(runningSpy.count(), 1); + QCOMPARE(finishedSpy.count(), 0); + delete anim; + QCOMPARE(runningSpy.count(), 2); + QCOMPARE(finishedSpy.count(), 0); +} + +void tst_QPropertyAnimation::duration0() +{ + QObject o; + o.setProperty("ole", 42); + QCOMPARE(o.property("ole").toInt(), 42); + + QPropertyAnimation animation(&o, "ole"); + animation.setEndValue(43); + QVERIFY(!animation.currentValue().isValid()); + QCOMPARE(animation.currentValue().toInt(), 0); + QCOMPARE(o.property("ole").toInt(), 42); + animation.setDuration(0); + animation.start(); + QCOMPARE(animation.state(), QAnimationGroup::Stopped); + QCOMPARE(animation.currentTime(), 0); + QCOMPARE(o.property("ole").toInt(), 43); +} + +class StartValueTester : public QObject +{ + Q_OBJECT + Q_PROPERTY(int ole READ ole WRITE setOle) +public: + StartValueTester() : o(0) { } + int ole() const { return o; } + void setOle(int v) { o = v; values << v; } + + int o; + QList values; +}; + +void tst_QPropertyAnimation::noStartValue() +{ + StartValueTester o; + o.setProperty("ole", 42); + o.values.clear(); + + QPropertyAnimation a(&o, "ole"); + a.setEndValue(420); + a.setDuration(250); + a.start(); + + QTest::qWait(300); + + QCOMPARE(o.values.first(), 42); + QCOMPARE(o.values.last(), 420); +} + +void tst_QPropertyAnimation::noStartValueWithLoop() +{ + StartValueTester o; + o.setProperty("ole", 42); + o.values.clear(); + + QPropertyAnimation a(&o, "ole"); + a.setEndValue(420); + a.setDuration(250); + a.setLoopCount(2); + a.start(); + + a.setCurrentTime(250); + QCOMPARE(o.values.first(), 42); + QCOMPARE(a.currentValue().toInt(), 42); + QCOMPARE(o.values.last(), 42); + + a.setCurrentTime(500); + QCOMPARE(a.currentValue().toInt(), 420); +} + +void tst_QPropertyAnimation::startWhenAnotherIsRunning() +{ + StartValueTester o; + o.setProperty("ole", 42); + o.values.clear(); + + { + //normal case: the animation finishes and is deleted + QPointer anim = new QPropertyAnimation(&o, "ole"); + QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + anim->start(QVariantAnimation::DeleteWhenStopped); + QTest::qWait(anim->duration() + 50); + QCOMPARE(runningSpy.count(), 2); //started and then stopped + QVERIFY(!anim); + } + + { + QPointer anim = new QPropertyAnimation(&o, "ole"); + QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + anim->start(QVariantAnimation::DeleteWhenStopped); + QTest::qWait(anim->duration()/2); + QPointer anim2 = new QPropertyAnimation(&o, "ole"); + QCOMPARE(runningSpy.count(), 1); + QCOMPARE(anim->state(), QVariantAnimation::Running); + + //anim2 will interrupt anim1 + QMetaObject::invokeMethod(anim2, "start", Qt::QueuedConnection, Q_ARG(QAbstractAnimation::DeletionPolicy, QVariantAnimation::DeleteWhenStopped)); + QTest::qWait(50); + QVERIFY(!anim); //anim should have been deleted + QVERIFY(anim2); + QTest::qWait(anim2->duration()); + QVERIFY(!anim2); //anim2 is finished: it should have been deleted by now + QVERIFY(!anim); + } + +} + +// copy from easing.cpp in case that function changes definition +static qreal easeInOutBack(qreal t) +{ + qreal s = 1.70158; + qreal t_adj = 2.0f * (qreal)t; + if (t_adj < 1) { + s *= 1.525f; + return 1.0/2*(t_adj*t_adj*((s+1)*t_adj - s)); + } else { + t_adj -= 2; + s *= 1.525f; + return 1.0/2*(t_adj*t_adj*((s+1)*t_adj + s) + 2); + } +} + +void tst_QPropertyAnimation::easingcurve_data() +{ + QTest::addColumn("currentTime"); + QTest::addColumn("expectedvalue"); + + QTest::newRow("interpolation1") << 0 << 0; + QTest::newRow("interpolation2") << 1000 << 1000; + QTest::newRow("extrapolationbelow") << 250 << -99; + QTest::newRow("extrapolationabove") << 750 << 1099; +} + +void tst_QPropertyAnimation::easingcurve() +{ + QFETCH(int, currentTime); + QFETCH(int, expectedvalue); + QObject o; + o.setProperty("ole", 42); + QCOMPARE(o.property("ole").toInt(), 42); + + QPropertyAnimation pAnimation(&o, "ole"); + pAnimation.setStartValue(0); + pAnimation.setEndValue(1000); + pAnimation.setDuration(1000); + + // this easingcurve assumes that we extrapolate before startValue and after endValue + QEasingCurve easingCurve; + easingCurve.setCustomType(easeInOutBack); + pAnimation.setEasingCurve(easingCurve); + pAnimation.start(); + pAnimation.pause(); + pAnimation.setCurrentTime(currentTime); + QCOMPARE(o.property("ole").toInt(), expectedvalue); +} + +void tst_QPropertyAnimation::startWithoutStartValue() +{ + QObject o; + o.setProperty("ole", 42); + QCOMPARE(o.property("ole").toInt(), 42); + + QPropertyAnimation anim(&o, "ole"); + anim.setEndValue(100); + + anim.start(); + + QTest::qWait(100); + int current = anim.currentValue().toInt(); + //it is somewhere in the animation + QVERIFY(current > 42); + QVERIFY(current < 100); + + QTest::qWait(200); + QCOMPARE(anim.state(), QVariantAnimation::Stopped); + + anim.setEndValue(110); + anim.start(); + current = anim.currentValue().toInt(); + // the default start value will reevaluate the current property + // and set it to the end value of the last iteration + QCOMPARE(current, 100); + QTest::qWait(100); + current = anim.currentValue().toInt(); + //it is somewhere in the animation + QVERIFY(current >= 100); + QVERIFY(current <= 110); +} + +void tst_QPropertyAnimation::playForwardBackward() +{ + QObject o; + o.setProperty("ole", 0); + QCOMPARE(o.property("ole").toInt(), 0); + + QPropertyAnimation anim(&o, "ole"); + anim.setEndValue(100); + anim.start(); + QTest::qWait(anim.duration() + 50); + QCOMPARE(anim.state(), QAbstractAnimation::Stopped); + QCOMPARE(anim.currentTime(), anim.duration()); + + //the animation is at the end + anim.setDirection(QVariantAnimation::Backward); + anim.start(); + QCOMPARE(anim.state(), QAbstractAnimation::Running); + QTest::qWait(anim.duration() + 50); + QCOMPARE(anim.state(), QAbstractAnimation::Stopped); + QCOMPARE(anim.currentTime(), 0); + + //the direction is backward + //restarting should jump to the end + anim.start(); + QCOMPARE(anim.state(), QAbstractAnimation::Running); + QCOMPARE(anim.currentTime(), anim.duration()); + QTest::qWait(anim.duration() + 50); + QCOMPARE(anim.state(), QAbstractAnimation::Stopped); + QCOMPARE(anim.currentTime(), 0); +} + +struct Number +{ + Number() {} + Number(int n) + : n(n) {} + + Number(const Number &other) + : n(other.n){} + + Number &operator=(const Number &other) { + n = other.n; + return *this; + } + bool operator==(const Number &other) const { + return n == other.n; + } + + int n; +}; + +Q_DECLARE_METATYPE(Number) +Q_DECLARE_METATYPE(QAbstractAnimation::State) + +QVariant numberInterpolator(const Number &f, const Number &t, qreal progress) +{ + return qVariantFromValue(Number(f.n + (t.n - f.n)*progress)); +} + +QVariant xaxisQPointInterpolator(const QPointF &f, const QPointF &t, qreal progress) +{ + return QPointF(f.x() + (t.x() - f.x())*progress, f.y()); +} + +void tst_QPropertyAnimation::interpolated() +{ + QObject o; + o.setProperty("point", QPointF()); //this will avoid warnings + o.setProperty("number", qVariantFromValue(Number(42))); + QCOMPARE(qVariantValue(o.property("number")), Number(42)); + { + qRegisterAnimationInterpolator(numberInterpolator); + QPropertyAnimation anim(&o, "number"); + anim.setStartValue(qVariantFromValue(Number(0))); + anim.setEndValue(qVariantFromValue(Number(100))); + anim.setDuration(1000); + anim.start(); + anim.pause(); + anim.setCurrentTime(100); + Number t(qVariantValue(o.property("number"))); + QCOMPARE(t, Number(10)); + anim.setCurrentTime(500); + QCOMPARE(qVariantValue(o.property("number")), Number(50)); + } + { + qRegisterAnimationInterpolator(xaxisQPointInterpolator); + QPropertyAnimation anim(&o, "point"); + anim.setStartValue(QPointF(0,0)); + anim.setEndValue(QPointF(100, 100)); + anim.setDuration(1000); + anim.start(); + anim.pause(); + anim.setCurrentTime(100); + QCOMPARE(o.property("point"), QVariant(QPointF(10, 0))); + anim.setCurrentTime(500); + QCOMPARE(o.property("point"), QVariant(QPointF(50, 0))); + } + { + // unregister it and see if we get back the default behaviour + qRegisterAnimationInterpolator(0); + QPropertyAnimation anim(&o, "point"); + anim.setStartValue(QPointF(0,0)); + anim.setEndValue(QPointF(100, 100)); + anim.setDuration(1000); + anim.start(); + anim.pause(); + anim.setCurrentTime(100); + QCOMPARE(o.property("point").toPointF(), QPointF(10, 10)); + anim.setCurrentTime(500); + QCOMPARE(o.property("point").toPointF(), QPointF(50, 50)); + } + + { + // Interpolate a qreal property with a int interpolator + AnimationObject o1; + o1.setRealValue(42.42); + QPropertyAnimation anim(&o1, "realValue"); + anim.setStartValue(0); + anim.setEndValue(100); + anim.start(); + QCOMPARE(o1.realValue(), qreal(0)); + anim.setCurrentTime(250); + QCOMPARE(o1.realValue(), qreal(100)); + } +} + +void tst_QPropertyAnimation::setStartEndValues() +{ + //this tests the start value, end value and default start value + QObject o; + o.setProperty("ole", 42); + QPropertyAnimation anim(&o, "ole"); + QVariantAnimation::KeyValues values; + QCOMPARE(anim.keyValues(), values); + + //let's add a start value + anim.setStartValue(0); + values << QVariantAnimation::KeyValue(0, 0); + QCOMPARE(anim.keyValues(), values); + + anim.setEndValue(10); + values << QVariantAnimation::KeyValue(1, 10); + QCOMPARE(anim.keyValues(), values); + + //now we can play with objects + QCOMPARE(o.property("ole").toInt(), 42); + QCOMPARE(o.property("ole").toInt(), 42); + anim.start(); + QVERIFY(anim.startValue().isValid()); + QCOMPARE(o.property("ole"), anim.startValue()); + + //now we remove the explicit start value and test the implicit one + anim.stop(); + o.setProperty("ole", 42); + values.remove(0); + anim.setStartValue(QVariant()); //reset the start value + QCOMPARE(anim.keyValues(), values); + QVERIFY(!anim.startValue().isValid()); + anim.start(); + QCOMPARE(o.property("ole").toInt(), 42); + anim.setCurrentTime(anim.duration()/2); + QCOMPARE(o.property("ole").toInt(), 26); //just in the middle of the animation + anim.setCurrentTime(anim.duration()); + QCOMPARE(anim.state(), QAnimationGroup::Stopped); //it should have stopped + QVERIFY(anim.endValue().isValid()); + QCOMPARE(o.property("ole"), anim.endValue()); //end of the animations + + //now we set back the startValue + anim.setStartValue(5); + QVERIFY(anim.startValue().isValid()); + anim.start(); + QCOMPARE(o.property("ole").toInt(), 5); +} + +void tst_QPropertyAnimation::zeroDurationStart() +{ + QPropertyAnimation anim; + QSignalSpy spy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + anim.setDuration(0); + QCOMPARE(anim.state(), QAbstractAnimation::Stopped); + anim.start(); + //the animation stops immediately + QCOMPARE(anim.state(), QAbstractAnimation::Stopped); + QCOMPARE(spy.count(), 2); + + //let's check the first state change + const QVariantList firstChange = spy.first(); + //old state + QCOMPARE(qVariantValue(firstChange.first()), QAbstractAnimation::Stopped); + //new state + QCOMPARE(qVariantValue(firstChange.last()), QAbstractAnimation::Running); + + //let's check the first state change + const QVariantList secondChange = spy.last(); + //old state + QCOMPARE(qVariantValue(secondChange.first()), QAbstractAnimation::Running); + //new state + QCOMPARE(qVariantValue(secondChange.last()), QAbstractAnimation::Stopped); +} + +#define Pause 1 +#define Start 2 +#define Resume 3 +#define Stop 4 + +void tst_QPropertyAnimation::operationsInStates_data() +{ + QTest::addColumn("originState"); + QTest::addColumn("operation"); + QTest::addColumn("expectedWarning"); + QTest::addColumn("expectedState"); + + QString pauseWarn(QLatin1String("QAbstractAnimation::pause: Cannot pause a stopped animation")); + QString resumeWarn(QLatin1String("QAbstractAnimation::resume: Cannot resume an animation that is not paused")); + + QTest::newRow("S-pause") << QAbstractAnimation::Stopped << Pause << pauseWarn << QAbstractAnimation::Stopped; + QTest::newRow("S-start") << QAbstractAnimation::Stopped << Start << QString() << QAbstractAnimation::Running; + QTest::newRow("S-resume") << QAbstractAnimation::Stopped << Resume << resumeWarn << QAbstractAnimation::Stopped; + QTest::newRow("S-stop") << QAbstractAnimation::Stopped << Stop << QString() << QAbstractAnimation::Stopped; + + QTest::newRow("P-pause") << QAbstractAnimation::Paused << Pause << QString() << QAbstractAnimation::Paused; + QTest::newRow("P-start") << QAbstractAnimation::Paused << Start << QString() << QAbstractAnimation::Running; + QTest::newRow("P-resume") << QAbstractAnimation::Paused << Resume << QString() << QAbstractAnimation::Running; + QTest::newRow("P-stop") << QAbstractAnimation::Paused << Stop << QString() << QAbstractAnimation::Stopped; + + QTest::newRow("R-pause") << QAbstractAnimation::Running << Pause << QString() << QAbstractAnimation::Paused; + QTest::newRow("R-start") << QAbstractAnimation::Running << Start << QString() << QAbstractAnimation::Running; + QTest::newRow("R-resume") << QAbstractAnimation::Running << Resume << resumeWarn << QAbstractAnimation::Running; + QTest::newRow("R-stop") << QAbstractAnimation::Running << Stop << QString() << QAbstractAnimation::Stopped; +} + +void tst_QPropertyAnimation::operationsInStates() +{ +/** + * | pause() |start() |resume() |stop() + * ----------+------------+-----------+-----------+-------------------+ + * Stopped | Stopped |Running |Stopped |Stopped | + * _| qWarning |restart |qWarning | | + * Paused | Paused |Running |Running |Stopped | + * _| | | | | + * Running | Paused |Running |Running |Stopped | + * | |restart |qWarning | | + * ----------+------------+-----------+-----------+-------------------+ +**/ + + QFETCH(QAbstractAnimation::State, originState); + QFETCH(int, operation); + QFETCH(QString, expectedWarning); + QFETCH(QAbstractAnimation::State, expectedState); + + QObject o; + o.setProperty("ole", 42); + QPropertyAnimation anim(&o, "ole"); + QSignalSpy spy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + anim.stop(); + switch (originState) { + case QAbstractAnimation::Stopped: + break; + case QAbstractAnimation::Paused: + anim.start(); + anim.pause(); + break; + case QAbstractAnimation::Running: + anim.start(); + break; + } + if (!expectedWarning.isEmpty()) { + QTest::ignoreMessage(QtWarningMsg, qPrintable(expectedWarning)); + } + QCOMPARE(anim.state(), originState); + switch (operation) { + case Pause: + anim.pause(); + break; + case Start: + anim.start(); + break; + case Resume: + anim.resume(); + break; + case Stop: + anim.stop(); + break; + } + + QCOMPARE(anim.state(), expectedState); +} +#undef Pause +#undef Start +#undef Resume +#undef Stop + +void tst_QPropertyAnimation::oneKeyValue() +{ + QObject o; + o.setProperty("ole", 42); + QCOMPARE(o.property("ole").toInt(), 42); + + QPropertyAnimation animation(&o, "ole"); + animation.setStartValue(43); + animation.setEndValue(44); + animation.setDuration(100); + + animation.setCurrentTime(0); + + QVERIFY(animation.currentValue().isValid()); + QCOMPARE(animation.currentValue().toInt(), 43); + QCOMPARE(o.property("ole").toInt(), 42); + + // remove the last key value + animation.setKeyValueAt(1.0, QVariant()); + + // we will neither interpolate, nor update the current value + // since there is only one 1 key value defined + animation.setCurrentTime(100); + + // the animation should not have been modified + QVERIFY(animation.currentValue().isValid()); + QCOMPARE(animation.currentValue().toInt(), 43); + QCOMPARE(o.property("ole").toInt(), 42); +} + +void tst_QPropertyAnimation::updateOnSetKeyValues() +{ + QObject o; + o.setProperty("ole", 100); + QCOMPARE(o.property("ole").toInt(), 100); + + QPropertyAnimation animation(&o, "ole"); + animation.setStartValue(100); + animation.setEndValue(200); + animation.setDuration(100); + + animation.setCurrentTime(50); + QCOMPARE(animation.currentValue().toInt(), 150); + animation.setKeyValueAt(0.0, 300); + QCOMPARE(animation.currentValue().toInt(), 250); + + o.setProperty("ole", 100); + QPropertyAnimation animation2(&o, "ole"); + QVariantAnimation::KeyValues kValues; + kValues << QVariantAnimation::KeyValue(0.0, 100) << QVariantAnimation::KeyValue(1.0, 200); + animation2.setKeyValues(kValues); + animation2.setDuration(100); + animation2.setCurrentTime(50); + QCOMPARE(animation2.currentValue().toInt(), 150); + + kValues.clear(); + kValues << QVariantAnimation::KeyValue(0.0, 300) << QVariantAnimation::KeyValue(1.0, 200); + animation2.setKeyValues(kValues); + + QCOMPARE(animation2.currentValue().toInt(), animation.currentValue().toInt()); +} + +QTEST_MAIN(tst_QPropertyAnimation) +#include "tst_qpropertyanimation.moc" diff --git a/tests/auto/qsequentialanimationgroup/qsequentialanimationgroup.pro b/tests/auto/qsequentialanimationgroup/qsequentialanimationgroup.pro new file mode 100644 index 0000000..ad861c3 --- /dev/null +++ b/tests/auto/qsequentialanimationgroup/qsequentialanimationgroup.pro @@ -0,0 +1,5 @@ +load(qttest_p4) +QT = core gui +SOURCES += tst_qsequentialanimationgroup.cpp + + diff --git a/tests/auto/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp b/tests/auto/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp new file mode 100644 index 0000000..0631343 --- /dev/null +++ b/tests/auto/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp @@ -0,0 +1,1649 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include "../../shared/util.h" + +#include +#include + +//TESTED_CLASS=QSequentialAnimationGroup +//TESTED_FILES= + +Q_DECLARE_METATYPE(QAbstractAnimation::State) +Q_DECLARE_METATYPE(QAbstractAnimation*) + +class tst_QSequentialAnimationGroup : public QObject +{ + Q_OBJECT +public: + tst_QSequentialAnimationGroup(); + virtual ~tst_QSequentialAnimationGroup(); + +public Q_SLOTS: + void init(); + void cleanup(); + +private slots: + void construction(); + void setCurrentTime(); + void setCurrentTimeWithUncontrolledAnimation(); + void seekingForwards(); + void seekingBackwards(); + void pauseAndResume(); + void restart(); + void looping(); + void startDelay(); + void clearGroup(); + void groupWithZeroDurationAnimations(); + void propagateGroupUpdateToChildren(); + void updateChildrenWithRunningGroup(); + void deleteChildrenWithRunningGroup(); + void startChildrenWithStoppedGroup(); + void stopGroupWithRunningChild(); + void startGroupWithRunningChild(); + void zeroDurationAnimation(); + void stopUncontrolledAnimations(); + void finishWithUncontrolledAnimation(); + void addRemoveAnimation(); + void currentAnimation(); + void currentAnimationWithZeroDuration(); + void insertAnimation(); + void clearAnimations(); +}; + +tst_QSequentialAnimationGroup::tst_QSequentialAnimationGroup() +{ +} + +tst_QSequentialAnimationGroup::~tst_QSequentialAnimationGroup() +{ +} + +void tst_QSequentialAnimationGroup::init() +{ + qRegisterMetaType("QAbstractAnimation::State"); + qRegisterMetaType("QAbstractAnimation*"); +} + +void tst_QSequentialAnimationGroup::cleanup() +{ +} + +void tst_QSequentialAnimationGroup::construction() +{ + QSequentialAnimationGroup animationgroup; +} + +class AnimationObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(int value READ value WRITE setValue) +public: + AnimationObject(int startValue = 0) + : v(startValue) + { } + + int value() const { return v; } + void setValue(int value) { v = value; } + + int v; +}; + +class TestAnimation : public QVariantAnimation +{ + Q_OBJECT +public: + virtual void updateCurrentValue(const QVariant &value) { Q_UNUSED(value)}; + virtual void updateState(QAbstractAnimation::State oldState, + QAbstractAnimation::State newState) + { + Q_UNUSED(oldState) + Q_UNUSED(newState) + }; +}; + +class UncontrolledAnimation : public QPropertyAnimation +{ + Q_OBJECT +public: + UncontrolledAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0) + : QPropertyAnimation(target, propertyName, parent) + { + setDuration(250); + } + + int duration() const { return -1; /* not time driven */ } + +protected: + void updateCurrentTime(int msecs) + { + QPropertyAnimation::updateCurrentTime(msecs); + if (msecs >= QPropertyAnimation::duration()) + stop(); + } +}; + +void tst_QSequentialAnimationGroup::setCurrentTime() +{ + AnimationObject s_o1; + AnimationObject s_o2; + AnimationObject s_o3; + + // sequence operating on same object/property + QAnimationGroup *sequence = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); + a2_s_o1->setLoopCount(3); + sequence->addAnimation(a1_s_o1); + sequence->addAnimation(a2_s_o1); + sequence->addAnimation(a3_s_o1); + + // sequence operating on different object/properties + QAnimationGroup *sequence2 = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); + QVariantAnimation *a1_s_o3 = new QPropertyAnimation(&s_o3, "value"); + sequence2->addAnimation(a1_s_o2); + sequence2->addAnimation(a1_s_o3); + + QSequentialAnimationGroup group; + group.addAnimation(sequence); + group.addAnimation(sequence2); + + // Current time = 1 + group.setCurrentTime(1); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(sequence->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + + QCOMPARE(group.currentTime(), 1); + QCOMPARE(sequence->currentTime(), 1); + QCOMPARE(a1_s_o1->currentTime(), 1); + QCOMPARE(a2_s_o1->currentTime(), 0); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 250 + group.setCurrentTime(250); + QCOMPARE(group.currentTime(), 250); + QCOMPARE(sequence->currentTime(), 250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 0); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 251 + group.setCurrentTime(251); + QCOMPARE(group.currentTime(), 251); + QCOMPARE(sequence->currentTime(), 251); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 1); + QCOMPARE(a2_s_o1->currentLoop(), 0); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(sequence2->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 750 + group.setCurrentTime(750); + QCOMPARE(group.currentTime(), 750); + QCOMPARE(sequence->currentTime(), 750); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 0); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(sequence2->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 1000 + group.setCurrentTime(1000); + QCOMPARE(group.currentTime(), 1000); + QCOMPARE(sequence->currentTime(), 1000); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(sequence2->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 1010 + group.setCurrentTime(1010); + QCOMPARE(group.currentTime(), 1010); + QCOMPARE(sequence->currentTime(), 1010); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 10); + QCOMPARE(sequence2->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 1250 + group.setCurrentTime(1250); + QCOMPARE(group.currentTime(), 1250); + QCOMPARE(sequence->currentTime(), 1250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 250); + QCOMPARE(sequence2->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 1500 + group.setCurrentTime(1500); + QCOMPARE(group.currentTime(), 1500); + QCOMPARE(sequence->currentTime(), 1250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 250); + QCOMPARE(sequence2->currentTime(), 250); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 1750 + group.setCurrentTime(1750); + QCOMPARE(group.currentTime(), 1750); + QCOMPARE(sequence->currentTime(), 1250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 250); + QCOMPARE(sequence2->currentTime(), 500); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 250); + + // Current time = 2000 + group.setCurrentTime(2000); + QCOMPARE(group.currentTime(), 1750); + QCOMPARE(sequence->currentTime(), 1250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 250); + QCOMPARE(sequence2->currentTime(), 500); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 250); +} + +void tst_QSequentialAnimationGroup::setCurrentTimeWithUncontrolledAnimation() +{ + AnimationObject s_o1; + AnimationObject s_o2; + AnimationObject t_o1; + AnimationObject t_o2; + + // sequence operating on different object/properties + QAnimationGroup *sequence = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); + sequence->addAnimation(a1_s_o1); + sequence->addAnimation(a1_s_o2); + + UncontrolledAnimation *notTimeDriven = new UncontrolledAnimation(&t_o1, "value"); + QCOMPARE(notTimeDriven->totalDuration(), -1); + + QVariantAnimation *loopsForever = new QPropertyAnimation(&t_o2, "value"); + loopsForever->setLoopCount(-1); + QCOMPARE(loopsForever->totalDuration(), -1); + + QSequentialAnimationGroup group; + group.addAnimation(sequence); + group.addAnimation(notTimeDriven); + group.addAnimation(loopsForever); + group.start(); + group.pause(); // this allows the group to listen for the finish signal of its children + + // Current time = 1 + group.setCurrentTime(1); + QCOMPARE(group.state(), QAnimationGroup::Paused); + QCOMPARE(sequence->state(), QAnimationGroup::Paused); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Paused); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); + + QCOMPARE(group.currentTime(), 1); + QCOMPARE(sequence->currentTime(), 1); + QCOMPARE(a1_s_o1->currentTime(), 1); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(notTimeDriven->currentTime(), 0); + QCOMPARE(loopsForever->currentTime(), 0); + + // Current time = 250 + group.setCurrentTime(250); + QCOMPARE(group.currentTime(), 250); + QCOMPARE(sequence->currentTime(), 250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(notTimeDriven->currentTime(), 0); + QCOMPARE(loopsForever->currentTime(), 0); + + // Current time = 500 + group.setCurrentTime(500); + QCOMPARE(group.currentTime(), 500); + QCOMPARE(sequence->currentTime(), 500); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(notTimeDriven->currentTime(), 0); + QCOMPARE(loopsForever->currentTime(), 0); + QCOMPARE(group.currentAnimation(), notTimeDriven); + + // Current time = 505 + group.setCurrentTime(505); + QCOMPARE(group.currentTime(), 505); + QCOMPARE(sequence->currentTime(), 500); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(notTimeDriven->currentTime(), 5); + QCOMPARE(loopsForever->currentTime(), 0); + QCOMPARE(group.currentAnimation(), notTimeDriven); + QCOMPARE(sequence->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven->state(), QAnimationGroup::Paused); + QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); + + // Current time = 750 (end of notTimeDriven animation) + group.setCurrentTime(750); + QCOMPARE(group.currentTime(), 750); + QCOMPARE(sequence->currentTime(), 500); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(notTimeDriven->currentTime(), 250); + QCOMPARE(loopsForever->currentTime(), 0); + QCOMPARE(group.currentAnimation(), loopsForever); + QCOMPARE(sequence->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever->state(), QAnimationGroup::Paused); + + // Current time = 800 (as notTimeDriven was finished at 750, loopsforever should still run) + group.setCurrentTime(800); + QCOMPARE(group.currentTime(), 800); + QCOMPARE(group.currentAnimation(), loopsForever); + QCOMPARE(sequence->currentTime(), 500); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(notTimeDriven->currentTime(), 250); + QCOMPARE(loopsForever->currentTime(), 50); + + loopsForever->stop(); // this should stop the group + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(sequence->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); +} + +void tst_QSequentialAnimationGroup::seekingForwards() +{ + AnimationObject s_o1; + AnimationObject s_o2; + AnimationObject s_o3; + + // sequence operating on same object/property + QAnimationGroup *sequence = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); + a2_s_o1->setLoopCount(3); + sequence->addAnimation(a1_s_o1); + sequence->addAnimation(a2_s_o1); + sequence->addAnimation(a3_s_o1); + + // sequence operating on different object/properties + QAnimationGroup *sequence2 = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); + QVariantAnimation *a1_s_o3 = new QPropertyAnimation(&s_o3, "value"); + sequence2->addAnimation(a1_s_o2); + sequence2->addAnimation(a1_s_o3); + + QSequentialAnimationGroup group; + group.addAnimation(sequence); + group.addAnimation(sequence2); + + // Current time = 1 + group.setCurrentTime(1); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(sequence->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); + + QCOMPARE(group.currentTime(), 1); + QCOMPARE(sequence->currentTime(), 1); + QCOMPARE(a1_s_o1->currentTime(), 1); + QCOMPARE(a2_s_o1->currentTime(), 0); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(sequence2->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // Current time = 1500 + group.setCurrentTime(1500); + QCOMPARE(group.currentTime(), 1500); + QCOMPARE(sequence->currentTime(), 1250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 250); + QCOMPARE(sequence2->currentTime(), 250); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 0); + + // this will restart the group + group.start(); + group.pause(); + QCOMPARE(group.state(), QAnimationGroup::Paused); + QCOMPARE(sequence->state(), QAnimationGroup::Paused); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Paused); + QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); + + // Current time = 1750 + group.setCurrentTime(1750); + QCOMPARE(group.currentTime(), 1750); + QCOMPARE(sequence->currentTime(), 1250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 250); + QCOMPARE(sequence2->currentTime(), 500); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 250); +} + +void tst_QSequentialAnimationGroup::seekingBackwards() +{ + AnimationObject s_o1; + AnimationObject s_o2; + AnimationObject s_o3; + + // sequence operating on same object/property + QAnimationGroup *sequence = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); + a2_s_o1->setLoopCount(3); + sequence->addAnimation(a1_s_o1); + sequence->addAnimation(a2_s_o1); + sequence->addAnimation(a3_s_o1); + + // sequence operating on different object/properties + QAnimationGroup *sequence2 = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); + QVariantAnimation *a1_s_o3 = new QPropertyAnimation(&s_o3, "value"); + sequence2->addAnimation(a1_s_o2); + sequence2->addAnimation(a1_s_o3); + + QSequentialAnimationGroup group; + group.addAnimation(sequence); + group.addAnimation(sequence2); + + group.start(); + + // Current time = 1600 + group.setCurrentTime(1600); + QCOMPARE(group.currentTime(), 1600); + QCOMPARE(sequence->currentTime(), 1250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 250); + QCOMPARE(sequence2->currentTime(), 350); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 100); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(sequence->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(sequence2->state(), QAnimationGroup::Running); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o3->state(), QAnimationGroup::Running); + + // Seeking backwards, current time = 1 + group.setCurrentTime(1); + QCOMPARE(group.currentTime(), 1); + QCOMPARE(sequence->currentTime(), 1); + QCOMPARE(a1_s_o1->currentTime(), 1); + + QEXPECT_FAIL("", "rewinding in nested groups is considered as a restart from the children," + "hence they don't reset from their current animation", Continue); + QCOMPARE(a2_s_o1->currentTime(), 0); + QEXPECT_FAIL("", "rewinding in nested groups is considered as a restart from the children," + "hence they don't reset from their current animation", Continue); + QCOMPARE(a2_s_o1->currentLoop(), 0); + QEXPECT_FAIL("", "rewinding in nested groups is considered as a restart from the children," + "hence they don't reset from their current animation", Continue); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(sequence2->currentTime(), 0); + QCOMPARE(a1_s_o2->currentTime(), 0); + QCOMPARE(a1_s_o3->currentTime(), 0); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(sequence->state(), QAnimationGroup::Running); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Running); + QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); + + // Current time = 2000 + group.setCurrentTime(2000); + QCOMPARE(group.currentTime(), 1750); + QCOMPARE(sequence->currentTime(), 1250); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 2); + QCOMPARE(a3_s_o1->currentTime(), 250); + QCOMPARE(sequence2->currentTime(), 500); + QCOMPARE(a1_s_o2->currentTime(), 250); + QCOMPARE(a1_s_o3->currentTime(), 250); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(sequence->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); + QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); +} + +typedef QList StateList; + +static bool compareStates(const QSignalSpy& spy, const StateList &expectedStates) +{ + bool equals = true; + for (int i = 0; i < qMax(expectedStates.count(), spy.count()); ++i) { + if (i >= spy.count() || i >= expectedStates.count()) { + equals = false; + break; + } + QList args = spy.at(i); + QAbstractAnimation::State st = expectedStates.at(i); + QAbstractAnimation::State actual = qVariantValue(args.value(1)); + if (equals && actual != st) { + equals = false; + break; + } + } + if (!equals) { + const char *stateStrings[] = {"Stopped", "Paused", "Running"}; + QString e,a; + for (int i = 0; i < qMax(expectedStates.count(), spy.count()); ++i) { + if (i < expectedStates.count()) { + int exp = int(expectedStates.at(i)); + if (!e.isEmpty()) + e += QLatin1String(", "); + e += QLatin1String(stateStrings[exp]); + } + if (i < spy.count()) { + QList args = spy.at(i); + QAbstractAnimation::State actual = qVariantValue(args.value(1)); + if (!a.isEmpty()) + a += QLatin1String(", "); + if (int(actual) >= 0 && int(actual) <= 2) { + a += QLatin1String(stateStrings[int(actual)]); + } else { + a += QLatin1String("NaN"); + } + } + + } + qDebug("\n" + "expected (count == %d): %s\n" + "actual (count == %d): %s\n", expectedStates.count(), qPrintable(e), spy.count(), qPrintable(a)); + } + return equals; +} + +void tst_QSequentialAnimationGroup::pauseAndResume() +{ + AnimationObject s_o1; + + // sequence operating on same object/property + QAnimationGroup *sequence = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); + a2_s_o1->setLoopCount(2); + sequence->addAnimation(a1_s_o1); + sequence->addAnimation(a2_s_o1); + sequence->addAnimation(a3_s_o1); + sequence->setLoopCount(2); + + QSignalSpy a1StateChangedSpy(a1_s_o1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy seqStateChangedSpy(sequence, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + QSequentialAnimationGroup group; + group.addAnimation(sequence); + + group.start(); + group.pause(); + + // Current time = 1751 + group.setCurrentTime(1751); + QCOMPARE(group.currentTime(), 1751); + QCOMPARE(sequence->currentTime(), 751); + QCOMPARE(sequence->currentLoop(), 1); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 1); + QCOMPARE(a3_s_o1->currentLoop(), 0); + QCOMPARE(a3_s_o1->currentTime(), 1); + + QCOMPARE(group.state(), QAnimationGroup::Paused); + QCOMPARE(sequence->state(), QAnimationGroup::Paused); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a3_s_o1->state(), QAnimationGroup::Paused); + + QCOMPARE(a1StateChangedSpy.count(), 5); // Running,Paused,Stopped,Running,Stopped + QCOMPARE(seqStateChangedSpy.count(), 2); // Running,Paused + + QVERIFY(compareStates(a1StateChangedSpy, (StateList() << QAbstractAnimation::Running + << QAbstractAnimation::Paused + << QAbstractAnimation::Stopped + << QAbstractAnimation::Running + << QAbstractAnimation::Stopped))); + + QCOMPARE(qVariantValue(a1StateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(a1StateChangedSpy.at(1).at(1)), + QAnimationGroup::Paused); + QCOMPARE(qVariantValue(a1StateChangedSpy.at(2).at(1)), + QAnimationGroup::Stopped); + QCOMPARE(qVariantValue(a1StateChangedSpy.at(3).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(a1StateChangedSpy.at(4).at(1)), + QAnimationGroup::Stopped); + + QCOMPARE(qVariantValue(seqStateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(seqStateChangedSpy.at(1).at(1)), + QAnimationGroup::Paused); + + group.resume(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(sequence->state(), QAnimationGroup::Running); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a3_s_o1->state(), QAnimationGroup::Running); + + QVERIFY(group.currentTime() >= 1751); + QVERIFY(sequence->currentTime() >= 751); + QCOMPARE(sequence->currentLoop(), 1); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 1); + QCOMPARE(a3_s_o1->currentLoop(), 0); + QVERIFY(a3_s_o1->currentTime() >= 1); + + QCOMPARE(seqStateChangedSpy.count(), 3); // Running,Paused,Running + QCOMPARE(qVariantValue(seqStateChangedSpy.at(2).at(1)), + QAnimationGroup::Running); + + group.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Paused); + QCOMPARE(sequence->state(), QAnimationGroup::Paused); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a3_s_o1->state(), QAnimationGroup::Paused); + + QVERIFY(group.currentTime() >= 1751); + QVERIFY(sequence->currentTime() >= 751); + QCOMPARE(sequence->currentLoop(), 1); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 1); + QCOMPARE(a3_s_o1->currentLoop(), 0); + QVERIFY(a3_s_o1->currentTime() >= 1); + + QCOMPARE(seqStateChangedSpy.count(), 4); // Running,Paused,Running,Paused + QCOMPARE(qVariantValue(seqStateChangedSpy.at(3).at(1)), + QAnimationGroup::Paused); + + group.stop(); + + QCOMPARE(seqStateChangedSpy.count(), 5); // Running,Paused,Running,Paused,Stopped + QCOMPARE(qVariantValue(seqStateChangedSpy.at(4).at(1)), + QAnimationGroup::Stopped); +} + +void tst_QSequentialAnimationGroup::restart() +{ + AnimationObject s_o1; + + // sequence operating on same object/property + QAnimationGroup *sequence = new QSequentialAnimationGroup(); + QSignalSpy seqCurrentAnimChangedSpy(sequence, SIGNAL(currentAnimationChanged(QAbstractAnimation*))); + QSignalSpy seqStateChangedSpy(sequence, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + QVariantAnimation *anims[3]; + QSignalSpy *animsStateChanged[3]; + + for (int i = 0; i < 3; i++) { + anims[i] = new QPropertyAnimation(&s_o1, "value"); + anims[i]->setDuration(100); + animsStateChanged[i] = new QSignalSpy(anims[i], SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + } + + anims[1]->setLoopCount(2); + sequence->addAnimation(anims[0]); + sequence->addAnimation(anims[1]); + sequence->addAnimation(anims[2]); + sequence->setLoopCount(2); + + QSequentialAnimationGroup group; + group.addAnimation(sequence); + + group.start(); + + QTest::qWait(500); + + QCOMPARE(group.state(), QAnimationGroup::Running); + + QTest::qWait(300); + QTRY_COMPARE(group.state(), QAnimationGroup::Stopped); + + for (int i = 0; i < 3; i++) { + QCOMPARE(animsStateChanged[i]->count(), 4); + QCOMPARE(qVariantValue(animsStateChanged[i]->at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(animsStateChanged[i]->at(1).at(1)), + QAnimationGroup::Stopped); + QCOMPARE(qVariantValue(animsStateChanged[i]->at(2).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(animsStateChanged[i]->at(3).at(1)), + QAnimationGroup::Stopped); + } + + QCOMPARE(seqStateChangedSpy.count(), 2); + QCOMPARE(qVariantValue(seqStateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(seqStateChangedSpy.at(1).at(1)), + QAnimationGroup::Stopped); + + QCOMPARE(seqCurrentAnimChangedSpy.count(), 6); + for(int i=0; i(seqCurrentAnimChangedSpy.at(i).at(0))); + + group.start(); + + QCOMPARE(animsStateChanged[0]->count(), 5); + QCOMPARE(animsStateChanged[1]->count(), 4); + QCOMPARE(animsStateChanged[2]->count(), 4); + QCOMPARE(seqStateChangedSpy.count(), 3); +} + +void tst_QSequentialAnimationGroup::looping() +{ + AnimationObject s_o1; + AnimationObject s_o2; + AnimationObject s_o3; + + // sequence operating on same object/property + QSequentialAnimationGroup *sequence = new QSequentialAnimationGroup(); + QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); + QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); + + QSignalSpy a1Spy(a1_s_o1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy a2Spy(a2_s_o1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy a3Spy(a3_s_o1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy seqSpy(sequence, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + a2_s_o1->setLoopCount(2); + sequence->addAnimation(a1_s_o1); + sequence->addAnimation(a2_s_o1); + sequence->addAnimation(a3_s_o1); + sequence->setLoopCount(2); + + QSequentialAnimationGroup group; + QSignalSpy groupSpy(&group, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + group.addAnimation(sequence); + group.setLoopCount(2); + + group.start(); + group.pause(); + + // Current time = 1750 + group.setCurrentTime(1750); + QCOMPARE(group.currentTime(), 1750); + QCOMPARE(sequence->currentTime(), 750); + QCOMPARE(sequence->currentLoop(), 1); + QCOMPARE(a1_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 1); + // this animation is at the beginning because it is the current one inside sequence + QCOMPARE(a3_s_o1->currentLoop(), 0); + QCOMPARE(a3_s_o1->currentTime(), 0); + QCOMPARE(sequence->currentAnimation(), a3_s_o1); + + QCOMPARE(group.state(), QAnimationGroup::Paused); + QCOMPARE(sequence->state(), QAnimationGroup::Paused); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a3_s_o1->state(), QAnimationGroup::Paused); + + QCOMPARE(a1Spy.count(), 5); // Running,Paused,Stopped,Running,Stopped + QVERIFY(compareStates(a1Spy, (StateList() << QAbstractAnimation::Running + << QAbstractAnimation::Paused + << QAbstractAnimation::Stopped + << QAbstractAnimation::Running + << QAbstractAnimation::Stopped))); + + QCOMPARE(a2Spy.count(), 4); // Running,Stopped,Running,Stopped + QVERIFY(compareStates(a3Spy, (StateList() << QAbstractAnimation::Running + << QAbstractAnimation::Stopped + << QAbstractAnimation::Running + << QAbstractAnimation::Paused))); + + QCOMPARE(seqSpy.count(), 2); // Running,Paused + QCOMPARE(groupSpy.count(), 2); // Running,Paused + + // Looping, current time = duration + 1 + group.setCurrentTime(group.duration() + 1); + QCOMPARE(group.currentTime(), 1); + QCOMPARE(group.currentLoop(), 1); + QCOMPARE(sequence->currentTime(), 1); + QCOMPARE(sequence->currentLoop(), 0); + QCOMPARE(a1_s_o1->currentTime(), 1); + QCOMPARE(a2_s_o1->currentTime(), 250); + QCOMPARE(a2_s_o1->currentLoop(), 1); + // this animation is at the end because it was run on the previous loop + QCOMPARE(a3_s_o1->currentLoop(), 0); + QCOMPARE(a3_s_o1->currentTime(), 250); + + QCOMPARE(group.state(), QAnimationGroup::Paused); + QCOMPARE(sequence->state(), QAnimationGroup::Paused); + QCOMPARE(a1_s_o1->state(), QAnimationGroup::Paused); + QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); + QCOMPARE(a3_s_o1->state(), QAnimationGroup::Stopped); + + QCOMPARE(a1Spy.count(), 7); // Running,Paused,Stopped,Running,Stopped,Running,Stopped + QCOMPARE(a2Spy.count(), 4); // Running, Stopped, Running, Stopped + QVERIFY(compareStates(a3Spy, (StateList() << QAbstractAnimation::Running + << QAbstractAnimation::Stopped + << QAbstractAnimation::Running + << QAbstractAnimation::Paused + << QAbstractAnimation::Stopped))); + QVERIFY(compareStates(seqSpy, (StateList() << QAbstractAnimation::Running + << QAbstractAnimation::Paused + << QAbstractAnimation::Stopped + << QAbstractAnimation::Running + << QAbstractAnimation::Paused))); + QCOMPARE(groupSpy.count(), 2); +} + +void tst_QSequentialAnimationGroup::startDelay() +{ + QSequentialAnimationGroup group; + group.addPause(250); + group.addPause(125); + QCOMPARE(group.totalDuration(), 375); + + QEventLoop loop; + QObject::connect(&group, SIGNAL(finished()), &loop, SLOT(quit())); + + QTime time; + time.start(); + group.start(); + loop.exec(); + + QVERIFY(time.elapsed() >= 375); + QVERIFY(time.elapsed() < 1000); +} + +void tst_QSequentialAnimationGroup::clearGroup() +{ + QSequentialAnimationGroup group; + + for (int i = 0; i < 10; ++i) { + QSequentialAnimationGroup *subGroup = new QSequentialAnimationGroup(&group); + group.addPause(100); + subGroup->addPause(10); + } + + QCOMPARE(group.animationCount(), 20); + + int count = group.animationCount(); + QPointer *children = new QPointer[count]; + for (int i = 0; i < count; ++i) { + QVERIFY(group.animationAt(i) != 0); + children[i] = group.animationAt(i); + } + + group.clearAnimations(); + QCOMPARE(group.animationCount(), 0); + QCOMPARE(group.currentTime(), 0); + for (int i = 0; i < count; ++i) + QCOMPARE(children[i], QPointer()); + + delete[] children; +} + +void tst_QSequentialAnimationGroup::groupWithZeroDurationAnimations() +{ + QObject o; + QObject o2; + + o.setProperty("myProperty", 42); + o.setProperty("myOtherProperty", 13); + o2.setProperty("myProperty", 42); + o2.setProperty("myOtherProperty", 13); + + QSequentialAnimationGroup group; + + QVariantAnimation *a1 = new QPropertyAnimation(&o, "myProperty"); + a1->setDuration(0); + a1->setEndValue(43); + group.addAnimation(a1); + + //this should just run fine and change nothing + group.setCurrentTime(0); + QCOMPARE(group.currentAnimation(), a1); + + QVariantAnimation *a2 = new QPropertyAnimation(&o2, "myOtherProperty"); + a2->setDuration(500); + a2->setEndValue(31); + group.addAnimation(a2); + + QVariantAnimation *a3 = new QPropertyAnimation(&o, "myProperty"); + a3->setDuration(0); + a3->setEndValue(44); + group.addAnimation(a3); + + QVariantAnimation *a4 = new QPropertyAnimation(&o, "myOtherProperty"); + a4->setDuration(250); + a4->setEndValue(75); + group.addAnimation(a4); + + QVariantAnimation *a5 = new QPropertyAnimation(&o2, "myProperty"); + a5->setDuration(0); + a5->setEndValue(12); + group.addAnimation(a5); + + QCOMPARE(o.property("myProperty").toInt(), 42); + QCOMPARE(o.property("myOtherProperty").toInt(), 13); + QCOMPARE(o2.property("myProperty").toInt(), 42); + QCOMPARE(o2.property("myOtherProperty").toInt(), 13); + + + group.start(); + + QCOMPARE(o.property("myProperty").toInt(), 43); + QCOMPARE(o.property("myOtherProperty").toInt(), 13); + QCOMPARE(o2.property("myProperty").toInt(), 42); + QCOMPARE(o2.property("myOtherProperty").toInt(), 13); + + QTest::qWait(50); + + int o2val = o2.property("myOtherProperty").toInt(); + QVERIFY(o2val > 13); + QVERIFY(o2val < 31); + QCOMPARE(o.property("myProperty").toInt(), 43); + QCOMPARE(o.property("myOtherProperty").toInt(), 13); + + QTest::qWait(500); + + QCOMPARE(o.property("myProperty").toInt(), 44); + QCOMPARE(o2.property("myProperty").toInt(), 42); + QCOMPARE(o2.property("myOtherProperty").toInt(), 31); + QCOMPARE(a1->state(), QAnimationGroup::Stopped); + QCOMPARE(a2->state(), QAnimationGroup::Stopped); + QCOMPARE(a3->state(), QAnimationGroup::Stopped); + QCOMPARE(a4->state(), QAnimationGroup::Running); + QCOMPARE(a5->state(), QAnimationGroup::Stopped); + QCOMPARE(group.state(), QAnimationGroup::Running); + QTest::qWait(500); + + QTRY_COMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(o.property("myProperty").toInt(), 44); + QCOMPARE(o.property("myOtherProperty").toInt(), 75); + QCOMPARE(o2.property("myProperty").toInt(), 12); + QCOMPARE(o2.property("myOtherProperty").toInt(), 31); + QCOMPARE(a1->state(), QAnimationGroup::Stopped); + QCOMPARE(a2->state(), QAnimationGroup::Stopped); + QCOMPARE(a3->state(), QAnimationGroup::Stopped); + QCOMPARE(a4->state(), QAnimationGroup::Stopped); + QCOMPARE(a5->state(), QAnimationGroup::Stopped); +} + +void tst_QSequentialAnimationGroup::propagateGroupUpdateToChildren() +{ + // this test verifies if group state changes are updating its children correctly + QSequentialAnimationGroup group; + + QObject o; + o.setProperty("ole", 42); + QCOMPARE(o.property("ole").toInt(), 42); + + QPropertyAnimation anim1(&o, "ole"); + anim1.setEndValue(43); + anim1.setDuration(100); + QVERIFY(!anim1.currentValue().isValid()); + QCOMPARE(anim1.currentValue().toInt(), 0); + QCOMPARE(o.property("ole").toInt(), 42); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(200); + + QVERIFY(anim2.currentValue().isValid()); + QCOMPARE(anim2.currentValue().toInt(), 0); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + + group.start(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Paused); + QCOMPARE(anim1.state(), QAnimationGroup::Paused); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); +} + +void tst_QSequentialAnimationGroup::updateChildrenWithRunningGroup() +{ + // assert that its possible to modify a child's state directly while their group is running + QSequentialAnimationGroup group; + + TestAnimation anim; + anim.setStartValue(0); + anim.setEndValue(100); + anim.setDuration(200); + + QSignalSpy groupStateChangedSpy(&group, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy childStateChangedSpy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + QCOMPARE(groupStateChangedSpy.count(), 0); + QCOMPARE(childStateChangedSpy.count(), 0); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim); + + group.start(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim.state(), QAnimationGroup::Running); + + QCOMPARE(groupStateChangedSpy.count(), 1); + QCOMPARE(childStateChangedSpy.count(), 1); + + QCOMPARE(qVariantValue(groupStateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(childStateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + + // starting directly a running child will not have any effect + anim.start(); + + QCOMPARE(groupStateChangedSpy.count(), 1); + QCOMPARE(childStateChangedSpy.count(), 1); + + anim.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim.state(), QAnimationGroup::Paused); + + // in the animation stops directly, the group will still be running + anim.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim.state(), QAnimationGroup::Stopped); +} + +void tst_QSequentialAnimationGroup::deleteChildrenWithRunningGroup() +{ + // test if children can be activated when their group is stopped + QSequentialAnimationGroup group; + + QVariantAnimation *anim1 = new TestAnimation; + anim1->setStartValue(0); + anim1->setEndValue(100); + anim1->setDuration(200); + group.addAnimation(anim1); + + QCOMPARE(group.duration(), anim1->duration()); + + group.start(); + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim1->state(), QAnimationGroup::Running); + + QTest::qWait(50); + QVERIFY(group.currentTime() > 0); + + delete anim1; + QCOMPARE(group.animationCount(), 0); + QCOMPARE(group.duration(), 0); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(group.currentTime(), 0); //that's the invariant +} + +void tst_QSequentialAnimationGroup::startChildrenWithStoppedGroup() +{ + // test if children can be activated when their group is stopped + QSequentialAnimationGroup group; + + TestAnimation anim1; + anim1.setStartValue(0); + anim1.setEndValue(100); + anim1.setDuration(200); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(200); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + + group.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + anim1.start(); + anim2.start(); + anim2.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Paused); +} + +void tst_QSequentialAnimationGroup::stopGroupWithRunningChild() +{ + // children that started independently will not be affected by a group stop + QSequentialAnimationGroup group; + + TestAnimation anim1; + anim1.setStartValue(0); + anim1.setEndValue(100); + anim1.setDuration(200); + + TestAnimation anim2; + anim2.setStartValue(0); + anim2.setEndValue(100); + anim2.setDuration(200); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); + + group.addAnimation(&anim1); + group.addAnimation(&anim2); + + anim1.start(); + anim2.start(); + anim2.pause(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Paused); + + group.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Running); + QCOMPARE(anim2.state(), QAnimationGroup::Paused); + + anim1.stop(); + anim2.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1.state(), QAnimationGroup::Stopped); + QCOMPARE(anim2.state(), QAnimationGroup::Stopped); +} + +void tst_QSequentialAnimationGroup::startGroupWithRunningChild() +{ + // as the group has precedence over its children, starting a group will restart all the children + QSequentialAnimationGroup group; + + TestAnimation *anim1 = new TestAnimation(); + anim1->setStartValue(0); + anim1->setEndValue(100); + anim1->setDuration(200); + + TestAnimation *anim2 = new TestAnimation(); + anim2->setStartValue(0); + anim2->setEndValue(100); + anim2->setDuration(200); + + QSignalSpy stateChangedSpy1(anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + QSignalSpy stateChangedSpy2(anim2, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + QCOMPARE(stateChangedSpy1.count(), 0); + QCOMPARE(stateChangedSpy2.count(), 0); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1->state(), QAnimationGroup::Stopped); + QCOMPARE(anim2->state(), QAnimationGroup::Stopped); + + group.addAnimation(anim1); + group.addAnimation(anim2); + + anim1->start(); + anim2->start(); + anim2->pause(); + + QVERIFY(compareStates(stateChangedSpy1, (StateList() << QAbstractAnimation::Running))); + + QVERIFY(compareStates(stateChangedSpy2, (StateList() << QAbstractAnimation::Running + << QAbstractAnimation::Paused))); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1->state(), QAnimationGroup::Running); + QCOMPARE(anim2->state(), QAnimationGroup::Paused); + + group.start(); + + QVERIFY(compareStates(stateChangedSpy1, (StateList() << QAbstractAnimation::Running + << QAbstractAnimation::Stopped + << QAbstractAnimation::Running))); + QVERIFY(compareStates(stateChangedSpy2, (StateList() << QAbstractAnimation::Running + << QAbstractAnimation::Paused))); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim1->state(), QAnimationGroup::Running); + QCOMPARE(anim2->state(), QAnimationGroup::Paused); + + QTest::qWait(300); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim1->state(), QAnimationGroup::Stopped); + QCOMPARE(anim2->state(), QAnimationGroup::Running); + + QCOMPARE(stateChangedSpy2.count(), 4); + QCOMPARE(qVariantValue(stateChangedSpy2.at(2).at(1)), + QAnimationGroup::Stopped); + QCOMPARE(qVariantValue(stateChangedSpy2.at(3).at(1)), + QAnimationGroup::Running); + + group.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(anim1->state(), QAnimationGroup::Stopped); + QCOMPARE(anim2->state(), QAnimationGroup::Stopped); +} + +void tst_QSequentialAnimationGroup::zeroDurationAnimation() +{ + QSequentialAnimationGroup group; + + TestAnimation *anim1 = new TestAnimation(); + anim1->setStartValue(0); + anim1->setEndValue(100); + anim1->setDuration(0); + + TestAnimation *anim2 = new TestAnimation(); + anim2->setStartValue(0); + anim2->setEndValue(100); + anim2->setDuration(100); + + AnimationObject o1; + QPropertyAnimation *anim3 = new QPropertyAnimation(&o1, "value"); + anim3->setEndValue(100); + anim3->setDuration(0); + + QSignalSpy stateChangedSpy(anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + group.addAnimation(anim1); + group.addAnimation(anim2); + group.addAnimation(anim3); + group.setLoopCount(2); + group.start(); + + QCOMPARE(stateChangedSpy.count(), 2); + QCOMPARE(qVariantValue(stateChangedSpy.at(0).at(1)), + QAnimationGroup::Running); + QCOMPARE(qVariantValue(stateChangedSpy.at(1).at(1)), + QAnimationGroup::Stopped); + + QCOMPARE(anim1->state(), QAnimationGroup::Stopped); + QCOMPARE(anim2->state(), QAnimationGroup::Running); + QCOMPARE(group.state(), QAnimationGroup::Running); + + //now let's try to seek to the next loop + group.setCurrentTime(group.duration() + 1); + QCOMPARE(anim1->state(), QAnimationGroup::Stopped); + QCOMPARE(anim2->state(), QAnimationGroup::Running); + QCOMPARE(anim3->state(), QAnimationGroup::Stopped); + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(o1.value(), 100); //anim3 should have been run +} + +void tst_QSequentialAnimationGroup::stopUncontrolledAnimations() +{ + QSequentialAnimationGroup group; + + AnimationObject o1; + UncontrolledAnimation notTimeDriven(&o1, "value"); + QCOMPARE(notTimeDriven.totalDuration(), -1); + + TestAnimation loopsForever; + loopsForever.setStartValue(0); + loopsForever.setEndValue(100); + loopsForever.setDuration(100); + loopsForever.setLoopCount(-1); + + group.addAnimation(¬TimeDriven); + group.addAnimation(&loopsForever); + + group.start(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Running); + QCOMPARE(loopsForever.state(), QAnimationGroup::Stopped); + + notTimeDriven.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever.state(), QAnimationGroup::Running); + + loopsForever.stop(); + + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); + QCOMPARE(loopsForever.state(), QAnimationGroup::Stopped); +} + +void tst_QSequentialAnimationGroup::finishWithUncontrolledAnimation() +{ + AnimationObject o1; + + //1st case: + //first we test a group with one uncontrolled animation + QSequentialAnimationGroup group; + UncontrolledAnimation notTimeDriven(&o1, "value", &group); + QSignalSpy spy(&group, SIGNAL(finished())); + + group.start(); + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Running); + QCOMPARE(group.currentTime(), 0); + QCOMPARE(notTimeDriven.currentTime(), 0); + + QTest::qWait(300); //wait for the end of notTimeDriven + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); + const int actualDuration = notTimeDriven.currentTime(); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(group.currentTime(), actualDuration); + QCOMPARE(spy.count(), 1); + + //2nd case: + // lets make sure the seeking will work again + spy.clear(); + QPropertyAnimation anim(&group); + QSignalSpy animStateChangedSpy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); + + group.setCurrentTime(300); + QCOMPARE(group.state(), QAnimationGroup::Stopped); + QCOMPARE(notTimeDriven.currentTime(), actualDuration); + QCOMPARE(group.currentAnimation(), &anim); + + //3rd case: + //now let's add a perfectly defined animation at the end + QCOMPARE(animStateChangedSpy.count(), 0); + group.start(); + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Running); + QCOMPARE(group.currentTime(), 0); + QCOMPARE(notTimeDriven.currentTime(), 0); + + QCOMPARE(animStateChangedSpy.count(), 0); + + QTest::qWait(300); //wait for the end of notTimeDriven + QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); + QCOMPARE(group.state(), QAnimationGroup::Running); + QCOMPARE(anim.state(), QAnimationGroup::Running); + QCOMPARE(group.currentAnimation(), &anim); + QCOMPARE(animStateChangedSpy.count(), 1); + QTest::qWait(300); //wait for the end of anim + + QCOMPARE(anim.state(), QAnimationGroup::Stopped); + QCOMPARE(anim.currentTime(), anim.duration()); + + //we should simply be at the end + QCOMPARE(spy.count(), 1); + QCOMPARE(animStateChangedSpy.count(), 2); + QCOMPARE(group.currentTime(), notTimeDriven.currentTime() + anim.currentTime()); +} + +void tst_QSequentialAnimationGroup::addRemoveAnimation() +{ + //this test is specific to the sequential animation group + QSequentialAnimationGroup group; + + QCOMPARE(group.duration(), 0); + QCOMPARE(group.currentTime(), 0); + QVariantAnimation *anim1 = new QPropertyAnimation; + group.addAnimation(anim1); + QCOMPARE(group.duration(), 250); + QCOMPARE(group.currentTime(), 0); + QCOMPARE(group.currentAnimation(), anim1); + + //let's append an animation + QVariantAnimation *anim2 = new QPropertyAnimation; + group.addAnimation(anim2); + QCOMPARE(group.duration(), 500); + QCOMPARE(group.currentTime(), 0); + QCOMPARE(group.currentAnimation(), anim1); + + //let's prepend an animation + QVariantAnimation *anim0 = new QPropertyAnimation; + group.insertAnimationAt(0, anim0); + QCOMPARE(group.duration(), 750); + QCOMPARE(group.currentTime(), 0); + QCOMPARE(group.currentAnimation(), anim0); //anim0 has become the new currentAnimation + + group.setCurrentTime(300); //anim0 | anim1 | anim2 + QCOMPARE(group.currentTime(), 300); + QCOMPARE(group.currentAnimation(), anim1); + QCOMPARE(anim1->currentTime(), 50); + + group.removeAnimation(anim0); //anim1 | anim2 + QCOMPARE(group.currentTime(), 50); + QCOMPARE(group.currentAnimation(), anim1); + QCOMPARE(anim1->currentTime(), 50); + + group.setCurrentTime(0); + group.insertAnimationAt(0, anim0); //anim0 | anim1 | anim2 + group.setCurrentTime(300); + QCOMPARE(group.currentTime(), 300); + QCOMPARE(group.currentAnimation(), anim1); + QCOMPARE(anim1->currentTime(), 50); + + group.removeAnimation(anim1); //anim0 | anim2 + QCOMPARE(group.currentTime(), 250); + QCOMPARE(group.currentAnimation(), anim2); + QCOMPARE(anim0->currentTime(), 250); +} + +void tst_QSequentialAnimationGroup::currentAnimation() +{ + QSequentialAnimationGroup group; + QVERIFY(group.currentAnimation() == 0); + + QPropertyAnimation anim; + anim.setDuration(0); + group.addAnimation(&anim); + QCOMPARE(group.currentAnimation(), &anim); +} + +void tst_QSequentialAnimationGroup::currentAnimationWithZeroDuration() +{ + QSequentialAnimationGroup group; + QVERIFY(group.currentAnimation() == 0); + + QPropertyAnimation zero1; + zero1.setDuration(0); + QPropertyAnimation zero2; + zero2.setDuration(0); + + QPropertyAnimation anim; + + QPropertyAnimation zero3; + zero3.setDuration(0); + QPropertyAnimation zero4; + zero4.setDuration(0); + + + group.addAnimation(&zero1); + group.addAnimation(&zero2); + group.addAnimation(&anim); + group.addAnimation(&zero3); + group.addAnimation(&zero4); + + QCOMPARE(group.currentAnimation(), &zero1); + + group.setCurrentTime(0); + QCOMPARE(group.currentAnimation(), &anim); + + group.setCurrentTime(group.duration()); + QCOMPARE(group.currentAnimation(), &zero4); + + group.setDirection(QAbstractAnimation::Backward); + + group.setCurrentTime(0); + QCOMPARE(group.currentAnimation(), &zero1); + + group.setCurrentTime(group.duration()); + QCOMPARE(group.currentAnimation(), &anim); +} + +void tst_QSequentialAnimationGroup::insertAnimation() +{ + QSequentialAnimationGroup group; + group.setLoopCount(2); + QPropertyAnimation *anim = new QPropertyAnimation(&group); + QCOMPARE(group.duration(), anim->duration()); + group.setCurrentTime(300); + QCOMPARE(group.currentLoop(), 1); + + //this will crash if the sequential group calls duration on the created animation + new QPropertyAnimation(&group); +} + + +class SequentialAnimationGroup : public QSequentialAnimationGroup +{ + Q_OBJECT +public slots: + void clearAnimations() + { + QSequentialAnimationGroup::clearAnimations(); + } + + void refill() + { + stop(); + clearAnimations(); + new QPropertyAnimation(this); + start(); + } + +}; + + +void tst_QSequentialAnimationGroup::clearAnimations() +{ + SequentialAnimationGroup group; + QPointer anim1 = new QPropertyAnimation(&group); + group.connect(anim1, SIGNAL(finished()), SLOT(clearAnimations())); + new QPropertyAnimation(&group); + QCOMPARE(group.animationCount(), 2); + + group.start(); + QTest::qWait(anim1->duration() + 100); + QCOMPARE(group.animationCount(), 0); + QCOMPARE(group.state(), QAbstractAnimation::Stopped); + QCOMPARE(group.currentTime(), 0); + + anim1 = new QPropertyAnimation(&group); + group.connect(anim1, SIGNAL(finished()), SLOT(refill())); + group.start(); + QTest::qWait(anim1->duration() + 100); + QVERIFY(anim1 == 0); //anim1 should have been deleted + QCOMPARE(group.state(), QAbstractAnimation::Running); +} + +QTEST_MAIN(tst_QSequentialAnimationGroup) +#include "tst_qsequentialanimationgroup.moc" diff --git a/tests/auto/qstate/qstate.pro b/tests/auto/qstate/qstate.pro new file mode 100644 index 0000000..9131fa8 --- /dev/null +++ b/tests/auto/qstate/qstate.pro @@ -0,0 +1,5 @@ +load(qttest_p4) +QT = core +SOURCES += tst_qstate.cpp + + diff --git a/tests/auto/qstate/tst_qstate.cpp b/tests/auto/qstate/tst_qstate.cpp new file mode 100644 index 0000000..75b1905 --- /dev/null +++ b/tests/auto/qstate/tst_qstate.cpp @@ -0,0 +1,340 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +****************************************************************************/ + +#include + +#include "qstate.h" +#include "qstatemachine.h" +#include "qsignaltransition.h" + +// Will try to wait for the condition while allowing event processing +#define QTRY_COMPARE(__expr, __expected) \ + do { \ + const int __step = 50; \ + const int __timeout = 5000; \ + if ((__expr) != (__expected)) { \ + QTest::qWait(0); \ + } \ + for (int __i = 0; __i < __timeout && ((__expr) != (__expected)); __i+=__step) { \ + QTest::qWait(__step); \ + } \ + QCOMPARE(__expr, __expected); \ + } while(0) + +//TESTED_CLASS= +//TESTED_FILES= + +class tst_QState : public QObject +{ + Q_OBJECT + +public: + tst_QState(); + virtual ~tst_QState(); + +private slots: +#if 0 + void test(); +#endif + void assignProperty(); + void assignPropertyTwice(); + void historyInitialState(); + +private: + bool functionCalled; +}; + +tst_QState::tst_QState() : functionCalled(false) +{ +} + +tst_QState::~tst_QState() +{ +} + +#if 0 +void tst_QState::test() +{ + QStateMachine machine; + QState *s1 = new QState(machine.rootState()); + + QCOMPARE(s1->machine(), &machine); + QCOMPARE(s1->parentState(), machine.rootState()); + QCOMPARE(s1->initialState(), (QState*)0); + QVERIFY(s1->childStates().isEmpty()); + QVERIFY(s1->transitions().isEmpty()); + + QCOMPARE(s1->isFinal(), false); + s1->setFinal(true); + QCOMPARE(s1->isFinal(), true); + s1->setFinal(false); + QCOMPARE(s1->isFinal(), false); + + QCOMPARE(s1->isParallel(), false); + s1->setParallel(true); + QCOMPARE(s1->isParallel(), true); + s1->setParallel(false); + QCOMPARE(s1->isParallel(), false); + + QCOMPARE(s1->isAtomic(), true); + QCOMPARE(s1->isCompound(), false); + QCOMPARE(s1->isComplex(), false); + + QState *s11 = new QState(s1); + QCOMPARE(s11->parentState(), s1); + QCOMPARE(s11->isAtomic(), true); + QCOMPARE(s11->isCompound(), false); + QCOMPARE(s11->isComplex(), false); + QCOMPARE(s11->machine(), s1->machine()); + QVERIFY(s11->isDescendantOf(s1)); + + QCOMPARE(s1->initialState(), (QState*)0); + QCOMPARE(s1->childStates().size(), 1); + QCOMPARE(s1->childStates().at(0), s11); + + QCOMPARE(s1->isAtomic(), false); + QCOMPARE(s1->isCompound(), true); + QCOMPARE(s1->isComplex(), true); + + s1->setParallel(true); + QCOMPARE(s1->isAtomic(), false); + QCOMPARE(s1->isCompound(), false); + QCOMPARE(s1->isComplex(), true); + + QState *s12 = new QState(s1); + QCOMPARE(s12->parentState(), s1); + QCOMPARE(s12->isAtomic(), true); + QCOMPARE(s12->isCompound(), false); + QCOMPARE(s12->isComplex(), false); + QCOMPARE(s12->machine(), s1->machine()); + QVERIFY(s12->isDescendantOf(s1)); + QVERIFY(!s12->isDescendantOf(s11)); + + QCOMPARE(s1->initialState(), (QState*)0); + QCOMPARE(s1->childStates().size(), 2); + QCOMPARE(s1->childStates().at(0), s11); + QCOMPARE(s1->childStates().at(1), s12); + + QCOMPARE(s1->isAtomic(), false); + QCOMPARE(s1->isCompound(), false); + QCOMPARE(s1->isComplex(), true); + + s1->setParallel(false); + QCOMPARE(s1->isAtomic(), false); + QCOMPARE(s1->isCompound(), true); + QCOMPARE(s1->isComplex(), true); + + s1->setInitialState(s11); + QCOMPARE(s1->initialState(), s11); + + s1->setInitialState(0); + QCOMPARE(s1->initialState(), (QState*)0); + + s1->setInitialState(s12); + QCOMPARE(s1->initialState(), s12); + + QState *s13 = new QState(); + s1->setInitialState(s13); + QCOMPARE(s13->parentState(), s1); + QCOMPARE(s1->childStates().size(), 3); + QCOMPARE(s1->childStates().at(0), s11); + QCOMPARE(s1->childStates().at(1), s12); + QCOMPARE(s1->childStates().at(2), s13); + QVERIFY(s13->isDescendantOf(s1)); + + QVERIFY(s12->childStates().isEmpty()); + + QState *s121 = new QState(s12); + QCOMPARE(s121->parentState(), s12); + QCOMPARE(s121->isAtomic(), true); + QCOMPARE(s121->isCompound(), false); + QCOMPARE(s121->isComplex(), false); + QCOMPARE(s121->machine(), s12->machine()); + QVERIFY(s121->isDescendantOf(s12)); + QVERIFY(s121->isDescendantOf(s1)); + QVERIFY(!s121->isDescendantOf(s11)); + + QCOMPARE(s12->childStates().size(), 1); + QCOMPARE(s12->childStates().at(0), (QState*)s121); + + QCOMPARE(s1->childStates().size(), 3); + QCOMPARE(s1->childStates().at(0), s11); + QCOMPARE(s1->childStates().at(1), s12); + QCOMPARE(s1->childStates().at(2), s13); + + s11->addTransition(s12); + QCOMPARE(s11->transitions().size(), 1); + QCOMPARE(s11->transitions().at(0)->sourceState(), s11); + QCOMPARE(s11->transitions().at(0)->targetStates().size(), 1); + QCOMPARE(s11->transitions().at(0)->targetStates().at(0), s12); + QCOMPARE(s11->transitions().at(0)->eventType(), QEvent::None); + + QState *s14 = new QState(); + s12->addTransition(QList() << s13 << s14); + QCOMPARE(s12->transitions().size(), 1); + QCOMPARE(s12->transitions().at(0)->sourceState(), s12); + QCOMPARE(s12->transitions().at(0)->targetStates().size(), 2); + QCOMPARE(s12->transitions().at(0)->targetStates().at(0), s13); + QCOMPARE(s12->transitions().at(0)->targetStates().at(1), s14); + QCOMPARE(s12->transitions().at(0)->eventType(), QEvent::None); + + s13->addTransition(this, SIGNAL(destroyed()), s14); + QCOMPARE(s13->transitions().size(), 1); + QCOMPARE(s13->transitions().at(0)->sourceState(), s13); + QCOMPARE(s13->transitions().at(0)->targetStates().size(), 1); + QCOMPARE(s13->transitions().at(0)->targetStates().at(0), s14); + QCOMPARE(s13->transitions().at(0)->eventType(), QEvent::Signal); + QVERIFY(qobject_cast(s13->transitions().at(0)) != 0); + + delete s13->transitions().at(0); + QCOMPARE(s13->transitions().size(), 0); + + s12->addTransition(this, SIGNAL(destroyed()), s11); + QCOMPARE(s12->transitions().size(), 2); +} +#endif + +class TestClass: public QObject +{ + Q_OBJECT +public: + TestClass() : called(false) {} + bool called; + +public slots: + void slot() { called = true; } + + +}; + +void tst_QState::assignProperty() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("fooBar", 10); + + QState *s1 = new QState(machine.rootState()); + s1->assignProperty(object, "fooBar", 20); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(object->property("fooBar").toInt(), 20); +} + +void tst_QState::assignPropertyTwice() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("fooBar", 10); + + QState *s1 = new QState(machine.rootState()); + s1->assignProperty(object, "fooBar", 20); + s1->assignProperty(object, "fooBar", 30); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(object->property("fooBar").toInt(), 30); +} + +class EventTestTransition: public QAbstractTransition +{ +public: + EventTestTransition(QEvent::Type type, QState *targetState) + : QAbstractTransition(QList() << targetState), m_type(type) + { + } + +protected: + bool eventTest(QEvent *e) + { + return e->type() == m_type; + } + + void onTransition(QEvent *) {} + +private: + QEvent::Type m_type; + +}; + +void tst_QState::historyInitialState() +{ + QStateMachine machine; + + QState *s1 = new QState(machine.rootState()); + + QState *s2 = new QState(machine.rootState()); + QHistoryState *h1 = new QHistoryState(s2); + + s2->setInitialState(h1); + + QState *s3 = new QState(s2); + h1->setDefaultState(s3); + + QState *s4 = new QState(s2); + + s1->addTransition(new EventTestTransition(QEvent::User, s2)); + s2->addTransition(new EventTestTransition(QEvent::User, s1)); + s3->addTransition(new EventTestTransition(QEvent::Type(QEvent::User+1), s4)); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s3)); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s3)); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User+1))); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s4)); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s4)); +} + + +QTEST_MAIN(tst_QState) +#include "tst_qstate.moc" diff --git a/tests/auto/qstatemachine/qstatemachine.pro b/tests/auto/qstatemachine/qstatemachine.pro new file mode 100644 index 0000000..e5b32b5 --- /dev/null +++ b/tests/auto/qstatemachine/qstatemachine.pro @@ -0,0 +1,4 @@ +load(qttest_p4) +QT = core gui +SOURCES += tst_qstatemachine.cpp + diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp new file mode 100644 index 0000000..40c01bd --- /dev/null +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -0,0 +1,3548 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +#include "qstatemachine.h" +#include "qstate.h" +#include "qhistorystate.h" +#include "qkeyeventtransition.h" +#include "qmouseeventtransition.h" +#include "private/qstate_p.h" +#include "private/qstatemachine_p.h" + +// Will try to wait for the condition while allowing event processing +#define QTRY_COMPARE(__expr, __expected) \ + do { \ + const int __step = 50; \ + const int __timeout = 5000; \ + if ((__expr) != (__expected)) { \ + QTest::qWait(0); \ + } \ + for (int __i = 0; __i < __timeout && ((__expr) != (__expected)); __i+=__step) { \ + QTest::qWait(__step); \ + } \ + QCOMPARE(__expr, __expected); \ + } while(0) + +//TESTED_CLASS= +//TESTED_FILES= + +static int globalTick; + +// Run exec for a maximum of TIMEOUT msecs +#define QCOREAPPLICATION_EXEC(TIMEOUT) \ +{ \ + QTimer timer; \ + timer.setSingleShot(true); \ + timer.setInterval(TIMEOUT); \ + timer.start(); \ + connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit())); \ + QCoreApplication::exec(); \ +} + +class tst_QStateMachine : public QObject +{ + Q_OBJECT +public: + tst_QStateMachine(); + virtual ~tst_QStateMachine(); + +private slots: + void init(); + void cleanup(); + + void rootState(); + void addAndRemoveState(); + void stateEntryAndExit(); + void assignProperty(); + void assignPropertyWithAnimation(); + void postEvent(); + void stateFinished(); + void parallelStates(); + void allSourceToTargetConfigurations(); + void signalTransitions(); + void eventTransitions(); + void historyStates(); + void startAndStop(); + void targetStateWithNoParent(); + void targetStateDeleted(); + void transitionToRootState(); + void transitionEntersParent(); + + void defaultErrorState(); + void customGlobalErrorState(); + void customLocalErrorStateInBrokenState(); + void customLocalErrorStateInOtherState(); + void customLocalErrorStateInParentOfBrokenState(); + void customLocalErrorStateOverridesParent(); + void errorStateHasChildren(); + void errorStateHasErrors(); + void errorStateIsRootState(); + void errorStateEntersParentFirst(); + void customErrorStateIsNull(); + void clearError(); + void historyStateHasNowhereToGo(); + void historyStateAsInitialState(); + void brokenStateIsNeverEntered(); + void customErrorStateNotInGraph(); + void transitionToStateNotInGraph(); + void restoreProperties(); + + void defaultGlobalRestorePolicy(); + void globalRestorePolicySetToRestore(); + void globalRestorePolicySetToDoNotRestore(); + + //void restorePolicyNotInherited(); + //void mixedRestoreProperties(); + //void setRestorePolicyToDoNotRestore(); + //void setGlobalRestorePolicyToGlobalRestore(); + //void restorePolicyOnChildState(); + + void transitionWithParent(); + void transitionsFromParallelStateWithNoChildren(); + void parallelStateTransition(); + void parallelStateAssignmentsDone(); + void nestedRestoreProperties(); + void nestedRestoreProperties2(); + + void simpleAnimation(); + void twoAnimations(); + void twoAnimatedTransitions(); + void playAnimationTwice(); + void nestedTargetStateForAnimation(); + void animatedGlobalRestoreProperty(); + void specificTargetValueOfAnimation(); + + void addDefaultAnimation(); + void addDefaultAnimationWithUnusedAnimation(); + void removeDefaultAnimation(); + void overrideDefaultAnimationWithSpecific(); + +// void addDefaultAnimationForSource(); +// void addDefaultAnimationForTarget(); +// void removeDefaultAnimationForSource(); +// void removeDefaultAnimationForTarget(); +// void overrideDefaultAnimationWithSource(); +// void overrideDefaultAnimationWithTarget(); +// void overrideDefaultSourceAnimationWithSpecific(); +// void overrideDefaultTargetAnimationWithSpecific(); +// void overrideDefaultTargetAnimationWithSource(); +}; + +tst_QStateMachine::tst_QStateMachine() +{ +} + +tst_QStateMachine::~tst_QStateMachine() +{ +} + +class TestState : public QState +{ +public: + enum Event { + Entry, + Exit + }; + TestState(QState *parent) + : QState(parent) {} + QList > events; +protected: + virtual void onEntry(QEvent *) { + events.append(qMakePair(globalTick++, Entry)); + } + virtual void onExit(QEvent *) { + events.append(qMakePair(globalTick++, Exit)); + } +}; + +class TestTransition : public QAbstractTransition +{ +public: + TestTransition(QAbstractState *target) + : QAbstractTransition(QList() << target) {} + QList triggers; +protected: + virtual bool eventTest(QEvent *) { + return true; + } + virtual void onTransition(QEvent *) { + triggers.append(globalTick++); + } +}; + +void tst_QStateMachine::init() +{ +} + +void tst_QStateMachine::cleanup() +{ +} + +class EventTransition : public QAbstractTransition +{ +public: + EventTransition(QEvent::Type type, QAbstractState *target, QState *parent = 0) + : QAbstractTransition(QList() << target, parent), m_type(type) {} +protected: + virtual bool eventTest(QEvent *e) { + return (e->type() == m_type); + } + virtual void onTransition(QEvent *) {} +private: + QEvent::Type m_type; +}; + +void tst_QStateMachine::transitionToRootState() +{ + QStateMachine machine; + + QState *initialState = new QState(); + machine.addState(initialState); + machine.setInitialState(initialState); + + QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::setTargetStates: root state cannot be target of transition"); + initialState->addTransition(new EventTransition(QEvent::User, machine.rootState())); + + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(initialState)); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(initialState)); +} + +void tst_QStateMachine::transitionEntersParent() +{ + QStateMachine machine; + + QObject *entryController = new QObject(&machine); + entryController->setObjectName("entryController"); + entryController->setProperty("greatGrandParentEntered", false); + entryController->setProperty("grandParentEntered", false); + entryController->setProperty("parentEntered", false); + entryController->setProperty("stateEntered", false); + + QState *greatGrandParent = new QState(); + greatGrandParent->setObjectName("grandParent"); + greatGrandParent->assignProperty(entryController, "greatGrandParentEntered", true); + machine.addState(greatGrandParent); + machine.setInitialState(greatGrandParent); + + QState *grandParent = new QState(greatGrandParent); + grandParent->setObjectName("grandParent"); + grandParent->assignProperty(entryController, "grandParentEntered", true); + + QState *parent = new QState(grandParent); + parent->setObjectName("parent"); + parent->assignProperty(entryController, "parentEntered", true); + + QState *state = new QState(parent); + state->setObjectName("state"); + state->assignProperty(entryController, "stateEntered", true); + + QState *initialStateOfGreatGrandParent = new QState(greatGrandParent); + initialStateOfGreatGrandParent->setObjectName("initialStateOfGreatGrandParent"); + greatGrandParent->setInitialState(initialStateOfGreatGrandParent); + + initialStateOfGreatGrandParent->addTransition(new EventTransition(QEvent::User, state)); + + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(entryController->property("greatGrandParentEntered").toBool(), true); + QCOMPARE(entryController->property("grandParentEntered").toBool(), false); + QCOMPARE(entryController->property("parentEntered").toBool(), false); + QCOMPARE(entryController->property("stateEntered").toBool(), false); + QCOMPARE(machine.configuration().count(), 2); + QVERIFY(machine.configuration().contains(greatGrandParent)); + QVERIFY(machine.configuration().contains(initialStateOfGreatGrandParent)); + + entryController->setProperty("greatGrandParentEntered", false); + entryController->setProperty("grandParentEntered", false); + entryController->setProperty("parentEntered", false); + entryController->setProperty("stateEntered", false); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(entryController->property("greatGrandParentEntered").toBool(), false); + QCOMPARE(entryController->property("grandParentEntered").toBool(), true); + QCOMPARE(entryController->property("parentEntered").toBool(), true); + QCOMPARE(entryController->property("stateEntered").toBool(), true); + QCOMPARE(machine.configuration().count(), 4); + QVERIFY(machine.configuration().contains(greatGrandParent)); + QVERIFY(machine.configuration().contains(grandParent)); + QVERIFY(machine.configuration().contains(parent)); + QVERIFY(machine.configuration().contains(state)); +} + +void tst_QStateMachine::defaultErrorState() +{ + QStateMachine machine; + QVERIFY(machine.errorState() != 0); + + QState *brokenState = new QState(); + brokenState->setObjectName("MyInitialState"); + + machine.addState(brokenState); + machine.setInitialState(brokenState); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'MyInitialState'"); + + // initialState has no initial state + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); + QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'MyInitialState'")); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(machine.errorState())); +} + +class CustomErrorState: public QState +{ +public: + CustomErrorState(QStateMachine *machine, QState *parent = 0) + : QState(parent), error(QStateMachine::NoError), m_machine(machine) + { + } + + void onEntry(QEvent *) + { + error = m_machine->error(); + errorString = m_machine->errorString(); + } + + QStateMachine::Error error; + QString errorString; + +private: + QStateMachine *m_machine; +}; + +void tst_QStateMachine::customGlobalErrorState() +{ + QStateMachine machine; + + CustomErrorState *customErrorState = new CustomErrorState(&machine); + customErrorState->setObjectName("customErrorState"); + machine.addState(customErrorState); + machine.setErrorState(customErrorState); + + QState *initialState = new QState(); + initialState->setObjectName("initialState"); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *brokenState = new QState(); + brokenState->setObjectName("brokenState"); + machine.addState(brokenState); + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(machine.errorState(), customErrorState); + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(initialState)); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(initialState)); + + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(customErrorState)); + QCOMPARE(customErrorState->error, QStateMachine::NoInitialStateError); + QCOMPARE(customErrorState->errorString, QString::fromLatin1("Missing initial state in compound state 'brokenState'")); + QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); + QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'brokenState'")); +} + +void tst_QStateMachine::customLocalErrorStateInBrokenState() +{ + QStateMachine machine; + CustomErrorState *customErrorState = new CustomErrorState(&machine); + machine.addState(customErrorState); + + QState *initialState = new QState(); + initialState->setObjectName("initialState"); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *brokenState = new QState(); + brokenState->setObjectName("brokenState"); + machine.addState(brokenState); + brokenState->setErrorState(customErrorState); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(customErrorState)); + QCOMPARE(customErrorState->error, QStateMachine::NoInitialStateError); +} + +void tst_QStateMachine::customLocalErrorStateInOtherState() +{ + QStateMachine machine; + CustomErrorState *customErrorState = new CustomErrorState(&machine); + machine.addState(customErrorState); + + QState *initialState = new QState(); + initialState->setObjectName("initialState"); + QTest::ignoreMessage(QtWarningMsg, "QState::setErrorState: error state cannot belong to a different state machine"); + initialState->setErrorState(customErrorState); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *brokenState = new QState(); + brokenState->setObjectName("brokenState"); + + machine.addState(brokenState); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'brokenState'"); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(machine.errorState())); +} + +void tst_QStateMachine::customLocalErrorStateInParentOfBrokenState() +{ + QStateMachine machine; + CustomErrorState *customErrorState = new CustomErrorState(&machine); + machine.addState(customErrorState); + + QState *initialState = new QState(); + initialState->setObjectName("initialState"); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *parentOfBrokenState = new QState(); + machine.addState(parentOfBrokenState); + parentOfBrokenState->setObjectName("parentOfBrokenState"); + parentOfBrokenState->setErrorState(customErrorState); + + QState *brokenState = new QState(parentOfBrokenState); + brokenState->setObjectName("brokenState"); + parentOfBrokenState->setInitialState(brokenState); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(customErrorState)); +} + +void tst_QStateMachine::customLocalErrorStateOverridesParent() +{ + QStateMachine machine; + CustomErrorState *customErrorStateForParent = new CustomErrorState(&machine); + machine.addState(customErrorStateForParent); + + CustomErrorState *customErrorStateForBrokenState = new CustomErrorState(&machine); + machine.addState(customErrorStateForBrokenState); + + QState *initialState = new QState(); + initialState->setObjectName("initialState"); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *parentOfBrokenState = new QState(); + machine.addState(parentOfBrokenState); + parentOfBrokenState->setObjectName("parentOfBrokenState"); + parentOfBrokenState->setErrorState(customErrorStateForParent); + + QState *brokenState = new QState(parentOfBrokenState); + brokenState->setObjectName("brokenState"); + brokenState->setErrorState(customErrorStateForBrokenState); + parentOfBrokenState->setInitialState(brokenState); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(customErrorStateForBrokenState)); + QCOMPARE(customErrorStateForBrokenState->error, QStateMachine::NoInitialStateError); + QCOMPARE(customErrorStateForParent->error, QStateMachine::NoError); +} + +void tst_QStateMachine::errorStateHasChildren() +{ + QStateMachine machine; + CustomErrorState *customErrorState = new CustomErrorState(&machine); + customErrorState->setObjectName("customErrorState"); + machine.addState(customErrorState); + + machine.setErrorState(customErrorState); + + QState *childOfErrorState = new QState(customErrorState); + childOfErrorState->setObjectName("childOfErrorState"); + customErrorState->setInitialState(childOfErrorState); + + QState *initialState = new QState(); + initialState->setObjectName("initialState"); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *brokenState = new QState(); + brokenState->setObjectName("brokenState"); + machine.addState(brokenState); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 2); + QVERIFY(machine.configuration().contains(customErrorState)); + QVERIFY(machine.configuration().contains(childOfErrorState)); +} + + +void tst_QStateMachine::errorStateHasErrors() +{ + QStateMachine machine; + CustomErrorState *customErrorState = new CustomErrorState(&machine); + customErrorState->setObjectName("customErrorState"); + machine.addState(customErrorState); + + QAbstractState *oldErrorState = machine.errorState(); + machine.setErrorState(customErrorState); + + QState *childOfErrorState = new QState(customErrorState); + childOfErrorState->setObjectName("childOfErrorState"); + + QState *initialState = new QState(); + initialState->setObjectName("initialState"); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *brokenState = new QState(); + brokenState->setObjectName("brokenState"); + machine.addState(brokenState); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'customErrorState'"); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(oldErrorState)); // Fall back to default + QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); + QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'customErrorState'")); +} + +void tst_QStateMachine::errorStateIsRootState() +{ + QStateMachine machine; + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::setErrorState: root state cannot be error state"); + machine.setErrorState(machine.rootState()); + + QState *initialState = new QState(); + initialState->setObjectName("initialState"); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *brokenState = new QState(); + brokenState->setObjectName("brokenState"); + machine.addState(brokenState); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'brokenState'"); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(machine.errorState())); +} + +void tst_QStateMachine::errorStateEntersParentFirst() +{ + QStateMachine machine; + + QObject *entryController = new QObject(&machine); + entryController->setObjectName("entryController"); + entryController->setProperty("greatGrandParentEntered", false); + entryController->setProperty("grandParentEntered", false); + entryController->setProperty("parentEntered", false); + entryController->setProperty("errorStateEntered", false); + + QState *greatGrandParent = new QState(); + greatGrandParent->setObjectName("greatGrandParent"); + greatGrandParent->assignProperty(entryController, "greatGrandParentEntered", true); + machine.addState(greatGrandParent); + machine.setInitialState(greatGrandParent); + + QState *grandParent = new QState(greatGrandParent); + grandParent->setObjectName("grandParent"); + grandParent->assignProperty(entryController, "grandParentEntered", true); + + QState *parent = new QState(grandParent); + parent->setObjectName("parent"); + parent->assignProperty(entryController, "parentEntered", true); + + QState *errorState = new QState(parent); + errorState->setObjectName("errorState"); + errorState->assignProperty(entryController, "errorStateEntered", true); + machine.setErrorState(errorState); + + QState *initialStateOfGreatGrandParent = new QState(greatGrandParent); + initialStateOfGreatGrandParent->setObjectName("initialStateOfGreatGrandParent"); + greatGrandParent->setInitialState(initialStateOfGreatGrandParent); + + QState *brokenState = new QState(greatGrandParent); + brokenState->setObjectName("brokenState"); + + QState *childState = new QState(brokenState); + childState->setObjectName("childState"); + + initialStateOfGreatGrandParent->addTransition(new EventTransition(QEvent::User, brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(entryController->property("greatGrandParentEntered").toBool(), true); + QCOMPARE(entryController->property("grandParentEntered").toBool(), false); + QCOMPARE(entryController->property("parentEntered").toBool(), false); + QCOMPARE(entryController->property("errorStateEntered").toBool(), false); + QCOMPARE(machine.configuration().count(), 2); + QVERIFY(machine.configuration().contains(greatGrandParent)); + QVERIFY(machine.configuration().contains(initialStateOfGreatGrandParent)); + + entryController->setProperty("greatGrandParentEntered", false); + entryController->setProperty("grandParentEntered", false); + entryController->setProperty("parentEntered", false); + entryController->setProperty("errorStateEntered", false); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(entryController->property("greatGrandParentEntered").toBool(), false); + QCOMPARE(entryController->property("grandParentEntered").toBool(), true); + QCOMPARE(entryController->property("parentEntered").toBool(), true); + QCOMPARE(entryController->property("errorStateEntered").toBool(), true); + QCOMPARE(machine.configuration().count(), 4); + QVERIFY(machine.configuration().contains(greatGrandParent)); + QVERIFY(machine.configuration().contains(grandParent)); + QVERIFY(machine.configuration().contains(parent)); + QVERIFY(machine.configuration().contains(errorState)); +} + +void tst_QStateMachine::customErrorStateIsNull() +{ + QStateMachine machine; + QAbstractState *oldErrorState = machine.errorState(); + machine.rootState()->setErrorState(0); + + QState *initialState = new QState(); + machine.addState(initialState); + machine.setInitialState(initialState); + + QState *brokenState = new QState(); + machine.addState(brokenState); + + new QState(brokenState); + initialState->addTransition(new EventTransition(QEvent::User, brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state ''"); + QCoreApplication::processEvents(); + + QCOMPARE(machine.errorState(), reinterpret_cast(0)); + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(oldErrorState)); +} + +void tst_QStateMachine::clearError() +{ + QStateMachine machine; + machine.setErrorState(new QState(machine.rootState())); // avoid warnings + + QState *brokenState = new QState(machine.rootState()); + brokenState->setObjectName("brokenState"); + machine.setInitialState(brokenState); + new QState(brokenState); + + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); + QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'brokenState'")); + + machine.clearError(); + + QCOMPARE(machine.error(), QStateMachine::NoError); + QVERIFY(machine.errorString().isEmpty()); +} + +void tst_QStateMachine::historyStateAsInitialState() +{ + QStateMachine machine; + + QHistoryState *hs = new QHistoryState(machine.rootState()); + machine.setInitialState(hs); + + QState *s1 = new QState(machine.rootState()); + hs->setDefaultState(s1); + + QState *s2 = new QState(machine.rootState()); + + QHistoryState *s2h = new QHistoryState(s2); + s2->setInitialState(s2h); + + QState *s21 = new QState(s2); + s2h->setDefaultState(s21); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s21)); +} + +void tst_QStateMachine::historyStateHasNowhereToGo() +{ + QStateMachine machine; + + QState *initialState = new QState(machine.rootState()); + machine.setInitialState(initialState); + machine.setErrorState(new QState(machine.rootState())); // avoid warnings + + QState *brokenState = new QState(machine.rootState()); + brokenState->setObjectName("brokenState"); + brokenState->setInitialState(new QState(brokenState)); + + QHistoryState *historyState = new QHistoryState(brokenState); + historyState->setObjectName("historyState"); + initialState->addTransition(new EventTransition(QEvent::User, historyState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(machine.errorState())); + QCOMPARE(machine.error(), QStateMachine::NoDefaultStateInHistoryStateError); + QCOMPARE(machine.errorString(), QString::fromLatin1("Missing default state in history state 'historyState'")); +} + +void tst_QStateMachine::brokenStateIsNeverEntered() +{ + QStateMachine machine; + + QObject *entryController = new QObject(&machine); + entryController->setProperty("brokenStateEntered", false); + entryController->setProperty("childStateEntered", false); + entryController->setProperty("errorStateEntered", false); + + QState *initialState = new QState(machine.rootState()); + machine.setInitialState(initialState); + + QState *errorState = new QState(machine.rootState()); + errorState->assignProperty(entryController, "errorStateEntered", true); + machine.setErrorState(errorState); + + QState *brokenState = new QState(machine.rootState()); + brokenState->assignProperty(entryController, "brokenStateEntered", true); + brokenState->setObjectName("brokenState"); + + QState *childState = new QState(brokenState); + childState->assignProperty(entryController, "childStateEntered", true); + + initialState->addTransition(new EventTransition(QEvent::User, brokenState)); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(entryController->property("errorStateEntered").toBool(), true); + QCOMPARE(entryController->property("brokenStateEntered").toBool(), false); + QCOMPARE(entryController->property("childStateEntered").toBool(), false); +} + +void tst_QStateMachine::transitionToStateNotInGraph() +{ + QStateMachine machine; + + QState *initialState = new QState(machine.rootState()); + initialState->setObjectName("initialState"); + machine.setInitialState(initialState); + + QState independentState; + independentState.setObjectName("independentState"); + initialState->addTransition(&independentState); + + machine.start(); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: No common ancestor for targets and source of transition from state 'initialState'"); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(qobject_cast(machine.rootState())->errorState())); +} + +void tst_QStateMachine::customErrorStateNotInGraph() +{ + QStateMachine machine; + + QState errorState; + errorState.setObjectName("errorState"); + QTest::ignoreMessage(QtWarningMsg, "QState::setErrorState: error state cannot belong to a different state machine"); + machine.setErrorState(&errorState); + QVERIFY(&errorState != machine.errorState()); + + QState *initialBrokenState = new QState(machine.rootState()); + initialBrokenState->setObjectName("initialBrokenState"); + machine.setInitialState(initialBrokenState); + new QState(initialBrokenState); + + machine.start(); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'initialBrokenState'"); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(machine.errorState())); +} + +void tst_QStateMachine::restoreProperties() +{ + QStateMachine machine; + QCOMPARE(machine.globalRestorePolicy(), QStateMachine::DoNotRestoreProperties); + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + + QObject *object = new QObject(&machine); + object->setProperty("a", 1); + object->setProperty("b", 2); + + QState *S1 = new QState(); + S1->setObjectName("S1"); + S1->assignProperty(object, "a", 3); + machine.addState(S1); + + QState *S2 = new QState(); + S2->setObjectName("S2"); + S2->assignProperty(object, "b", 5); + machine.addState(S2); + + QState *S3 = new QState(); + S3->setObjectName("S3"); + machine.addState(S3); + + QFinalState *S4 = new QFinalState(); + machine.addState(S4); + + S1->addTransition(new EventTransition(QEvent::User, S2)); + S2->addTransition(new EventTransition(QEvent::User, S3)); + S3->addTransition(S4); + + machine.setInitialState(S1); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(object->property("a").toInt(), 3); + QCOMPARE(object->property("b").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(object->property("a").toInt(), 1); + QCOMPARE(object->property("b").toInt(), 5); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(object->property("a").toInt(), 1); + QCOMPARE(object->property("b").toInt(), 2); +} + +void tst_QStateMachine::rootState() +{ + QStateMachine machine; + QVERIFY(machine.rootState() != 0); + QVERIFY(qobject_cast(machine.rootState()) != 0); + QCOMPARE(qobject_cast(machine.rootState())->parentState(), (QState*)0); + QCOMPARE(machine.rootState()->parent(), (QObject*)&machine); + QCOMPARE(machine.rootState()->machine(), &machine); + + QState *s1 = new QState(machine.rootState()); + QCOMPARE(s1->parentState(), machine.rootState()); + + QState *s2 = new QState(); + s2->setParent(&machine); + QCOMPARE(s2->parentState(), machine.rootState()); +} + +void tst_QStateMachine::addAndRemoveState() +{ + QStateMachine machine; + QStatePrivate *root_d = QStatePrivate::get(machine.rootState()); + QCOMPARE(root_d->childStates().size(), 1); // the error state + QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); + + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::addState: cannot add null state"); + machine.addState(0); + + QState *s1 = new QState(); + QCOMPARE(s1->parentState(), (QState*)0); + QCOMPARE(s1->machine(), (QStateMachine*)0); + machine.addState(s1); + QCOMPARE(s1->machine(), &machine); + QCOMPARE(s1->parentState(), machine.rootState()); + QCOMPARE(root_d->childStates().size(), 2); + QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); + QCOMPARE(root_d->childStates().at(1), (QAbstractState*)s1); + + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::addState: state has already been added to this machine"); + machine.addState(s1); + + QState *s2 = new QState(); + QCOMPARE(s2->parentState(), (QState*)0); + machine.addState(s2); + QCOMPARE(s2->parentState(), machine.rootState()); + QCOMPARE(root_d->childStates().size(), 3); + QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); + QCOMPARE(root_d->childStates().at(1), (QAbstractState*)s1); + QCOMPARE(root_d->childStates().at(2), (QAbstractState*)s2); + + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::addState: state has already been added to this machine"); + machine.addState(s2); + + machine.removeState(s1); + QCOMPARE(s1->parentState(), (QState*)0); + QCOMPARE(root_d->childStates().size(), 2); + QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); + QCOMPARE(root_d->childStates().at(1), (QAbstractState*)s2); + + machine.removeState(s2); + QCOMPARE(s2->parentState(), (QState*)0); + QCOMPARE(root_d->childStates().size(), 1); + QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); + + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::removeState: cannot remove null state"); + machine.removeState(0); + + delete s1; + delete s2; + // ### how to deal with this? + // machine.removeState(machine.errorState()); +} + +void tst_QStateMachine::stateEntryAndExit() +{ + // Two top-level states + { + QStateMachine machine; + + TestState *s1 = new TestState(machine.rootState()); + QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: cannot add transition to null state"); + s1->addTransition((QAbstractState*)0); + QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: cannot add null transition"); + s1->addTransition((QAbstractTransition*)0); + QTest::ignoreMessage(QtWarningMsg, "QState::removeTransition: cannot remove null transition"); + s1->removeTransition((QAbstractTransition*)0); + + TestState *s2 = new TestState(machine.rootState()); + QFinalState *s3 = new QFinalState(machine.rootState()); + + TestTransition *t = new TestTransition(s2); + QCOMPARE(t->machine(), (QStateMachine*)0); + QCOMPARE(t->sourceState(), (QState*)0); + QCOMPARE(t->targetState(), s2); + QCOMPARE(t->targetStates().size(), 1); + QCOMPARE(t->targetStates().at(0), s2); + t->setTargetState(0); + QCOMPARE(t->targetState(), (QState*)0); + QVERIFY(t->targetStates().isEmpty()); + t->setTargetState(s2); + QCOMPARE(t->targetState(), s2); + QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::setTargetStates: target state(s) cannot be null"); + t->setTargetStates(QList() << 0); + QCOMPARE(t->targetState(), s2); + t->setTargetStates(QList() << s2); + QCOMPARE(t->targetState(), s2); + QCOMPARE(t->targetStates().size(), 1); + QCOMPARE(t->targetStates().at(0), s2); + QCOMPARE(s1->addTransition(t), (QAbstractTransition*)t); + QCOMPARE(t->sourceState(), s1); + QCOMPARE(t->machine(), &machine); + + { + QAbstractTransition *trans = s2->addTransition(s3); + QVERIFY(trans != 0); + QCOMPARE(trans->sourceState(), (QAbstractState*)s2); + QCOMPARE(trans->targetState(), (QAbstractState*)s3); + { + char warning[256]; + sprintf(warning, "QState::removeTransition: transition %p's source state (%p) is different from this state (%p)", trans, s2, s1); + QTest::ignoreMessage(QtWarningMsg, warning); + s1->removeTransition(trans); + } + s2->removeTransition(trans); + QCOMPARE(trans->sourceState(), (QAbstractState*)0); + QCOMPARE(trans->targetState(), (QAbstractState*)s3); + QCOMPARE(s2->addTransition(trans), trans); + QCOMPARE(trans->sourceState(), (QAbstractState*)s2); + } + + QSignalSpy startedSpy(&machine, SIGNAL(started())); + QSignalSpy stoppedSpy(&machine, SIGNAL(stopped())); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s1); + QCOMPARE(machine.initialState(), (QAbstractState*)s1); + { + char warning[256]; + sprintf(warning, "QState::setInitialState: state %p is not a child of this state (%p)", machine.rootState(), machine.rootState()); + QTest::ignoreMessage(QtWarningMsg, warning); + machine.setInitialState(machine.rootState()); + QCOMPARE(machine.initialState(), (QAbstractState*)s1); + } + QVERIFY(machine.configuration().isEmpty()); + globalTick = 0; + QVERIFY(!machine.isRunning()); + machine.start(); + + QTRY_COMPARE(startedSpy.count(), 1); + QTRY_COMPARE(finishedSpy.count(), 1); + QTRY_COMPARE(stoppedSpy.count(), 0); + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(s3)); + + // s1 is entered + QCOMPARE(s1->events.count(), 2); + QCOMPARE(s1->events.at(0).first, 0); + QCOMPARE(s1->events.at(0).second, TestState::Entry); + // s1 is exited + QCOMPARE(s1->events.at(1).first, 1); + QCOMPARE(s1->events.at(1).second, TestState::Exit); + // t is triggered + QCOMPARE(t->triggers.count(), 1); + QCOMPARE(t->triggers.at(0), 2); + // s2 is entered + QCOMPARE(s2->events.count(), 2); + QCOMPARE(s2->events.at(0).first, 3); + QCOMPARE(s2->events.at(0).second, TestState::Entry); + // s2 is exited + QCOMPARE(s2->events.at(1).first, 4); + QCOMPARE(s2->events.at(1).second, TestState::Exit); + } + // Two top-level states, one has two child states + { + QStateMachine machine; + + TestState *s1 = new TestState(machine.rootState()); + TestState *s11 = new TestState(s1); + TestState *s12 = new TestState(s1); + TestState *s2 = new TestState(machine.rootState()); + QFinalState *s3 = new QFinalState(machine.rootState()); + s1->setInitialState(s11); + TestTransition *t1 = new TestTransition(s12); + s11->addTransition(t1); + TestTransition *t2 = new TestTransition(s2); + s12->addTransition(t2); + s2->addTransition(s3); + + QSignalSpy startedSpy(&machine, SIGNAL(started())); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s1); + globalTick = 0; + machine.start(); + + QTRY_COMPARE(startedSpy.count(), 1); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(s3)); + + // s1 is entered + QCOMPARE(s1->events.count(), 2); + QCOMPARE(s1->events.at(0).first, 0); + QCOMPARE(s1->events.at(0).second, TestState::Entry); + // s11 is entered + QCOMPARE(s11->events.count(), 2); + QCOMPARE(s11->events.at(0).first, 1); + QCOMPARE(s11->events.at(0).second, TestState::Entry); + // s11 is exited + QCOMPARE(s11->events.at(1).first, 2); + QCOMPARE(s11->events.at(1).second, TestState::Exit); + // t1 is triggered + QCOMPARE(t1->triggers.count(), 1); + QCOMPARE(t1->triggers.at(0), 3); + // s12 is entered + QCOMPARE(s12->events.count(), 2); + QCOMPARE(s12->events.at(0).first, 4); + QCOMPARE(s12->events.at(0).second, TestState::Entry); + // s12 is exited + QCOMPARE(s12->events.at(1).first, 5); + QCOMPARE(s12->events.at(1).second, TestState::Exit); + // s1 is exited + QCOMPARE(s1->events.at(1).first, 6); + QCOMPARE(s1->events.at(1).second, TestState::Exit); + // t2 is triggered + QCOMPARE(t2->triggers.count(), 1); + QCOMPARE(t2->triggers.at(0), 7); + // s2 is entered + QCOMPARE(s2->events.count(), 2); + QCOMPARE(s2->events.at(0).first, 8); + QCOMPARE(s2->events.at(0).second, TestState::Entry); + // s2 is exited + QCOMPARE(s2->events.at(1).first, 9); + QCOMPARE(s2->events.at(1).second, TestState::Exit); + } +} + +void tst_QStateMachine::assignProperty() +{ + QStateMachine machine; + QState *s1 = new QState(machine.rootState()); + + QTest::ignoreMessage(QtWarningMsg, "QState::assignProperty: cannot assign property 'foo' of null object"); + s1->assignProperty(0, "foo", QVariant()); + + s1->assignProperty(s1, "objectName", "s1"); + QFinalState *s2 = new QFinalState(machine.rootState()); + s1->addTransition(s2); + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + QCOMPARE(s1->objectName(), QString::fromLatin1("s1")); + + s1->assignProperty(s1, "objectName", "foo"); + machine.start(); + QCoreApplication::processEvents(); + QCOMPARE(s1->objectName(), QString::fromLatin1("foo")); + + s1->assignProperty(s1, "noSuchProperty", 123); + machine.start(); + QCoreApplication::processEvents(); + QCOMPARE(s1->objectName(), QString::fromLatin1("foo")); + QCOMPARE(s1->dynamicPropertyNames().size(), 1); + QCOMPARE(s1->dynamicPropertyNames().at(0), QByteArray("noSuchProperty")); + + QSignalSpy polishedSpy(s1, SIGNAL(polished())); + machine.start(); + QCoreApplication::processEvents(); + QCOMPARE(polishedSpy.count(), 1); +} + +void tst_QStateMachine::assignPropertyWithAnimation() +{ + // Single animation + { + QStateMachine machine; + QVERIFY(machine.animationsEnabled()); + machine.setAnimationsEnabled(false); + QVERIFY(!machine.animationsEnabled()); + machine.setAnimationsEnabled(true); + QVERIFY(machine.animationsEnabled()); + QObject obj; + obj.setProperty("foo", 321); + obj.setProperty("bar", 654); + QState *s1 = new QState(machine.rootState()); + s1->assignProperty(&obj, "foo", 123); + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(&obj, "foo", 456); + s2->assignProperty(&obj, "bar", 789); + QAbstractTransition *trans = s1->addTransition(s2); + QVERIFY(trans->animations().isEmpty()); + QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::addAnimation: cannot add null animation"); + trans->addAnimation(0); + QPropertyAnimation anim(&obj, "foo"); + anim.setDuration(250); + trans->addAnimation(&anim); + QCOMPARE(trans->animations().size(), 1); + QCOMPARE(trans->animations().at(0), (QAbstractAnimation*)&anim); + QCOMPARE(anim.parent(), (QObject*)0); + QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::removeAnimation: cannot remove null animation"); + trans->removeAnimation(0); + trans->removeAnimation(&anim); + QVERIFY(trans->animations().isEmpty()); + trans->addAnimation(&anim); + QCOMPARE(trans->animations().size(), 1); + QCOMPARE(trans->animations().at(0), (QAbstractAnimation*)&anim); + QFinalState *s3 = new QFinalState(machine.rootState()); + s2->addTransition(s2, SIGNAL(polished()), s3); + + machine.setInitialState(s1); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(obj.property("foo").toInt(), 456); + QCOMPARE(obj.property("bar").toInt(), 789); + } + // Two animations + { + QStateMachine machine; + QObject obj; + obj.setProperty("foo", 321); + obj.setProperty("bar", 654); + QState *s1 = new QState(machine.rootState()); + s1->assignProperty(&obj, "foo", 123); + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(&obj, "foo", 456); + s2->assignProperty(&obj, "bar", 789); + QAbstractTransition *trans = s1->addTransition(s2); + QPropertyAnimation anim(&obj, "foo"); + anim.setDuration(150); + trans->addAnimation(&anim); + QPropertyAnimation anim2(&obj, "bar"); + anim2.setDuration(150); + trans->addAnimation(&anim2); + QFinalState *s3 = new QFinalState(machine.rootState()); + s2->addTransition(s2, SIGNAL(polished()), s3); + + machine.setInitialState(s1); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(obj.property("foo").toInt(), 456); + QCOMPARE(obj.property("bar").toInt(), 789); + } + // Animation group + { + QStateMachine machine; + QObject obj; + obj.setProperty("foo", 321); + obj.setProperty("bar", 654); + QState *s1 = new QState(machine.rootState()); + s1->assignProperty(&obj, "foo", 123); + s1->assignProperty(&obj, "bar", 321); + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(&obj, "foo", 456); + s2->assignProperty(&obj, "bar", 654); + s2->assignProperty(&obj, "baz", 789); + QAbstractTransition *trans = s1->addTransition(s2); + QSequentialAnimationGroup group; + group.addAnimation(new QPropertyAnimation(&obj, "foo")); + group.addAnimation(new QPropertyAnimation(&obj, "bar")); + trans->addAnimation(&group); + QFinalState *s3 = new QFinalState(machine.rootState()); + s2->addTransition(s2, SIGNAL(polished()), s3); + + machine.setInitialState(s1); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(obj.property("foo").toInt(), 456); + QCOMPARE(obj.property("bar").toInt(), 654); + QCOMPARE(obj.property("baz").toInt(), 789); + } + // Nested states + { + QStateMachine machine; + QObject obj; + obj.setProperty("foo", 321); + obj.setProperty("bar", 654); + QState *s1 = new QState(machine.rootState()); + QCOMPARE(s1->childMode(), QState::ExclusiveStates); + s1->setChildMode(QState::ParallelStates); + QCOMPARE(s1->childMode(), QState::ParallelStates); + s1->setChildMode(QState::ExclusiveStates); + QCOMPARE(s1->childMode(), QState::ExclusiveStates); + QCOMPARE(s1->initialState(), (QAbstractState*)0); + s1->setObjectName("s1"); + s1->assignProperty(&obj, "foo", 123); + s1->assignProperty(&obj, "bar", 456); + QState *s2 = new QState(machine.rootState()); + s2->setObjectName("s2"); + s2->assignProperty(&obj, "foo", 321); + QState *s21 = new QState(s2); + s21->setObjectName("s21"); + s21->assignProperty(&obj, "bar", 654); + QState *s22 = new QState(s2); + s22->setObjectName("s22"); + s22->assignProperty(&obj, "bar", 789); + s2->setInitialState(s21); + QCOMPARE(s2->initialState(), (QAbstractState*)s21); + + QAbstractTransition *trans = s1->addTransition(s2); + QPropertyAnimation anim(&obj, "foo"); + anim.setDuration(500); + trans->addAnimation(&anim); + QPropertyAnimation anim2(&obj, "bar"); + anim2.setDuration(250); + trans->addAnimation(&anim2); + + s21->addTransition(s21, SIGNAL(polished()), s22); + + QFinalState *s3 = new QFinalState(machine.rootState()); + s22->addTransition(s2, SIGNAL(polished()), s3); + + machine.setInitialState(s1); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(obj.property("foo").toInt(), 321); + QCOMPARE(obj.property("bar").toInt(), 789); + } +} + +struct StringEvent : public QEvent +{ +public: + StringEvent(const QString &val) + : QEvent(QEvent::Type(QEvent::User+2)), + value(val) {} + + QString value; +}; + +class StringTransition : public QAbstractTransition +{ +public: + StringTransition(const QString &value, QAbstractState *target) + : QAbstractTransition(QList() << target), m_value(value) {} + +protected: + virtual bool eventTest(QEvent *e) + { + if (e->type() != QEvent::Type(QEvent::User+2)) + return false; + StringEvent *se = static_cast(e); + return (m_value == se->value) && (!m_cond.isValid() || (m_cond.indexIn(m_value) != -1)); + } + virtual void onTransition(QEvent *) {} + +private: + QString m_value; + QRegExp m_cond; +}; + +class StringEventPoster : public QState +{ +public: + StringEventPoster(QStateMachine *machine, const QString &value, QState *parent = 0) + : QState(parent), m_machine(machine), m_value(value), m_delay(0) {} + + void setString(const QString &value) + { m_value = value; } + void setDelay(int delay) + { m_delay = delay; } + +protected: + virtual void onEntry(QEvent *) + { + m_machine->postEvent(new StringEvent(m_value), m_delay); + } + virtual void onExit(QEvent *) {} + +private: + QStateMachine *m_machine; + QString m_value; + int m_delay; +}; + +void tst_QStateMachine::postEvent() +{ + for (int x = 0; x < 2; ++x) { + QStateMachine machine; + { + QEvent e(QEvent::None); + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::postEvent: cannot post event when the state machine is not running"); + machine.postEvent(&e); + } + StringEventPoster *s1 = new StringEventPoster(&machine, "a"); + if (x == 1) + s1->setDelay(100); + QFinalState *s2 = new QFinalState; + s1->addTransition(new StringTransition("a", s2)); + machine.addState(s1); + machine.addState(s2); + machine.setInitialState(s1); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s2)); + + s1->setString("b"); + QFinalState *s3 = new QFinalState(); + machine.addState(s3); + s1->addTransition(new StringTransition("b", s3)); + finishedSpy.clear(); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s3)); + } +} + +void tst_QStateMachine::stateFinished() +{ + QStateMachine machine; + QState *s1 = new QState(machine.rootState()); + QState *s1_1 = new QState(s1); + QFinalState *s1_2 = new QFinalState(s1); + s1_1->addTransition(s1_2); + s1->setInitialState(s1_1); + QFinalState *s2 = new QFinalState(machine.rootState()); + s1->addTransition(s1, SIGNAL(finished()), s2); + machine.setInitialState(s1); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s2)); +} + +void tst_QStateMachine::parallelStates() +{ + QStateMachine machine; + + QState *s1 = new QState(QState::ParallelStates); + QCOMPARE(s1->childMode(), QState::ParallelStates); + QState *s1_1 = new QState(s1); + QState *s1_1_1 = new QState(s1_1); + QFinalState *s1_1_f = new QFinalState(s1_1); + s1_1_1->addTransition(s1_1_f); + s1_1->setInitialState(s1_1_1); + QState *s1_2 = new QState(s1); + QState *s1_2_1 = new QState(s1_2); + QFinalState *s1_2_f = new QFinalState(s1_2); + s1_2_1->addTransition(s1_2_f); + s1_2->setInitialState(s1_2_1); + { + char warning[256]; + sprintf(warning, "QState::setInitialState: ignoring attempt to set initial state of parallel state group %p", s1); + QTest::ignoreMessage(QtWarningMsg, warning); + s1->setInitialState(0); + } + machine.addState(s1); + + QFinalState *s2 = new QFinalState(); + machine.addState(s2); + + s1->addTransition(s1, SIGNAL(finished()), s2); + + machine.setInitialState(s1); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s2)); +} + +void tst_QStateMachine::allSourceToTargetConfigurations() +{ + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + s0->setObjectName("s0"); + QState *s1 = new QState(s0); + s1->setObjectName("s1"); + QState *s11 = new QState(s1); + s11->setObjectName("s11"); + QState *s2 = new QState(s0); + s2->setObjectName("s2"); + QState *s21 = new QState(s2); + s21->setObjectName("s21"); + QState *s211 = new QState(s21); + s211->setObjectName("s211"); + QFinalState *f = new QFinalState(machine.rootState()); + f->setObjectName("f"); + + s0->setInitialState(s1); + s1->setInitialState(s11); + s2->setInitialState(s21); + s21->setInitialState(s211); + + s11->addTransition(new StringTransition("g", s211)); + s1->addTransition(new StringTransition("a", s1)); + s1->addTransition(new StringTransition("b", s11)); + s1->addTransition(new StringTransition("c", s2)); + s1->addTransition(new StringTransition("d", s0)); + s1->addTransition(new StringTransition("f", s211)); + s211->addTransition(new StringTransition("d", s21)); + s211->addTransition(new StringTransition("g", s0)); + s211->addTransition(new StringTransition("h", f)); + s21->addTransition(new StringTransition("b", s211)); + s2->addTransition(new StringTransition("c", s1)); + s2->addTransition(new StringTransition("f", s11)); + s0->addTransition(new StringTransition("e", s211)); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new StringEvent("a")); + QCoreApplication::processEvents(); + machine.postEvent(new StringEvent("b")); + QCoreApplication::processEvents(); + machine.postEvent(new StringEvent("c")); + QCoreApplication::processEvents(); + machine.postEvent(new StringEvent("d")); + QCoreApplication::processEvents(); + machine.postEvent(new StringEvent("e")); + QCoreApplication::processEvents(); + machine.postEvent(new StringEvent("f")); + QCoreApplication::processEvents(); + machine.postEvent(new StringEvent("g")); + QCoreApplication::processEvents(); + machine.postEvent(new StringEvent("h")); + QCoreApplication::processEvents(); + + QTRY_COMPARE(finishedSpy.count(), 1); +} + +class SignalEmitter : public QObject +{ +Q_OBJECT + public: + SignalEmitter(QObject *parent = 0) + : QObject(parent) {} + void emitSignalWithNoArg() + { emit signalWithNoArg(); } + void emitSignalWithIntArg(int arg) + { emit signalWithIntArg(arg); } + void emitSignalWithStringArg(const QString &arg) + { emit signalWithStringArg(arg); } +Q_SIGNALS: + void signalWithNoArg(); + void signalWithIntArg(int); + void signalWithStringArg(const QString &); +}; + +class TestSignalTransition : public QSignalTransition +{ +public: + TestSignalTransition(QState *sourceState = 0) + : QSignalTransition(sourceState) {} + TestSignalTransition(QObject *sender, const char *signal, + QAbstractState *target) + : QSignalTransition(sender, signal, QList() << target) {} + QVariantList argumentsReceived() const { + return m_args; + } +protected: + bool eventTest(QEvent *e) { + if (!QSignalTransition::eventTest(e)) + return false; + QSignalEvent *se = static_cast(e); + const_cast(this)->m_args = se->arguments(); + return true; + } +private: + QVariantList m_args; +}; + +void tst_QStateMachine::signalTransitions() +{ + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: sender cannot be null"); + QCOMPARE(s0->addTransition(0, SIGNAL(noSuchSignal()), 0), (QObject*)0); + + SignalEmitter emitter; + QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: signal cannot be null"); + QCOMPARE(s0->addTransition(&emitter, 0, 0), (QObject*)0); + + QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: cannot add transition to null state"); + QCOMPARE(s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), 0), (QObject*)0); + + QFinalState *s1 = new QFinalState(machine.rootState()); + QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: no such signal SignalEmitter::noSuchSignal()"); + QCOMPARE(s0->addTransition(&emitter, SIGNAL(noSuchSignal()), s1), (QObject*)0); + + { + QSignalTransition *trans = s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), s1); + QVERIFY(trans != 0); + QCOMPARE(trans->sourceState(), s0); + QCOMPARE(trans->targetState(), (QAbstractState*)s1); + QCOMPARE(trans->senderObject(), (QObject*)&emitter); + QCOMPARE(trans->signal(), QByteArray(SIGNAL(signalWithNoArg()))); + } + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + emitter.emitSignalWithNoArg(); + + QTRY_COMPARE(finishedSpy.count(), 1); + + emitter.emitSignalWithNoArg(); + } + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + SignalEmitter emitter; + TestSignalTransition *trans = new TestSignalTransition(&emitter, SIGNAL(signalWithIntArg(int)), s1); + s0->addTransition(trans); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + emitter.emitSignalWithIntArg(123); + + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(trans->argumentsReceived().size(), 1); + QCOMPARE(trans->argumentsReceived().at(0).toInt(), 123); + } + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + SignalEmitter emitter; + TestSignalTransition *trans = new TestSignalTransition(&emitter, SIGNAL(signalWithStringArg(QString)), s1); + s0->addTransition(trans); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + QString testString = QString::fromLatin1("hello"); + emitter.emitSignalWithStringArg(testString); + + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(trans->argumentsReceived().size(), 1); + QCOMPARE(trans->argumentsReceived().at(0).toString(), testString); + } + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + + TestSignalTransition *trans = new TestSignalTransition(); + QCOMPARE(trans->senderObject(), (QObject*)0); + QCOMPARE(trans->signal(), QByteArray()); + + SignalEmitter emitter; + trans->setSenderObject(&emitter); + QCOMPARE(trans->senderObject(), (QObject*)&emitter); + trans->setSignal(SIGNAL(signalWithNoArg())); + QCOMPARE(trans->signal(), QByteArray(SIGNAL(signalWithNoArg()))); + trans->setTargetState(s1); + s0->addTransition(trans); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + emitter.emitSignalWithNoArg(); + + QTRY_COMPARE(finishedSpy.count(), 1); + } + // Multiple transitions for same (object,signal) + { + QStateMachine machine; + SignalEmitter emitter; + QState *s0 = new QState(machine.rootState()); + QState *s1 = new QState(machine.rootState()); + QSignalTransition *t0 = s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), s1); + QSignalTransition *t1 = s1->addTransition(&emitter, SIGNAL(signalWithNoArg()), s0); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s0)); + + emitter.emitSignalWithNoArg(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + s0->removeTransition(t0); + emitter.emitSignalWithNoArg(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s0)); + + emitter.emitSignalWithNoArg(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s0)); + + s1->removeTransition(t1); + emitter.emitSignalWithNoArg(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s0)); + + s0->addTransition(t0); + s1->addTransition(t1); + emitter.emitSignalWithNoArg(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + } +} + +void tst_QStateMachine::eventTransitions() +{ + QPushButton button; + for (int x = 0; x < 2; ++x) { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + + QMouseEventTransition *trans; + if (x == 0) { + trans = new QMouseEventTransition(&button, QEvent::MouseButtonPress, Qt::LeftButton); + QCOMPARE(trans->targetState(), (QAbstractState*)0); + trans->setTargetState(s1); + } else { + trans = new QMouseEventTransition(&button, QEvent::MouseButtonPress, + Qt::LeftButton, QList() << s1); + } + QCOMPARE(trans->eventType(), QEvent::MouseButtonPress); + QCOMPARE(trans->button(), Qt::LeftButton); + QCOMPARE(trans->targetState(), (QAbstractState*)s1); + s0->addTransition(trans); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + QTest::mousePress(&button, Qt::LeftButton); + QTRY_COMPARE(finishedSpy.count(), 1); + + QTest::mousePress(&button, Qt::LeftButton); + + trans->setEventType(QEvent::MouseButtonRelease); + QCOMPARE(trans->eventType(), QEvent::MouseButtonRelease); + machine.start(); + QCoreApplication::processEvents(); + QTest::mouseRelease(&button, Qt::LeftButton); + QTRY_COMPARE(finishedSpy.count(), 2); + } + for (int x = 0; x < 3; ++x) { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + + QEventTransition *trans; + if (x == 0) { + trans = new QEventTransition(); + QCOMPARE(trans->eventObject(), (QObject*)0); + QCOMPARE(trans->eventType(), QEvent::None); + trans->setEventObject(&button); + trans->setEventType(QEvent::MouseButtonPress); + trans->setTargetState(s1); + } else if (x == 1) { + trans = new QEventTransition(&button, QEvent::MouseButtonPress); + trans->setTargetState(s1); + } else { + trans = new QEventTransition(&button, QEvent::MouseButtonPress, + QList() << s1); + } + QCOMPARE(trans->eventObject(), (QObject*)&button); + QCOMPARE(trans->eventType(), QEvent::MouseButtonPress); + QCOMPARE(trans->targetState(), (QAbstractState*)s1); + s0->addTransition(trans); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + QTest::mousePress(&button, Qt::LeftButton); + QCoreApplication::processEvents(); + + QTRY_COMPARE(finishedSpy.count(), 1); + } + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + + QMouseEventTransition *trans = new QMouseEventTransition(); + QCOMPARE(trans->eventObject(), (QObject*)0); + QCOMPARE(trans->eventType(), QEvent::None); + QCOMPARE(trans->button(), Qt::NoButton); + trans->setEventObject(&button); + trans->setEventType(QEvent::MouseButtonPress); + trans->setButton(Qt::LeftButton); + trans->setTargetState(s1); + s0->addTransition(trans); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + QTest::mousePress(&button, Qt::LeftButton); + QCoreApplication::processEvents(); + + QTRY_COMPARE(finishedSpy.count(), 1); + } + + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + + QKeyEventTransition *trans = new QKeyEventTransition(&button, QEvent::KeyPress, Qt::Key_A); + QCOMPARE(trans->eventType(), QEvent::KeyPress); + QCOMPARE(trans->key(), (int)Qt::Key_A); + trans->setTargetState(s1); + s0->addTransition(trans); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + QTest::keyPress(&button, Qt::Key_A); + QCoreApplication::processEvents(); + + QTRY_COMPARE(finishedSpy.count(), 1); + } + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + + QKeyEventTransition *trans = new QKeyEventTransition(); + QCOMPARE(trans->eventObject(), (QObject*)0); + QCOMPARE(trans->eventType(), QEvent::None); + QCOMPARE(trans->key(), 0); + trans->setEventObject(&button); + trans->setEventType(QEvent::KeyPress); + trans->setKey(Qt::Key_A); + trans->setTargetState(s1); + s0->addTransition(trans); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + QTest::keyPress(&button, Qt::Key_A); + QCoreApplication::processEvents(); + + QTRY_COMPARE(finishedSpy.count(), 1); + } + // Multiple transitions for same (object,event) + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QState *s1 = new QState(machine.rootState()); + QEventTransition *t0 = new QEventTransition(&button, QEvent::MouseButtonPress); + t0->setTargetState(s1); + s0->addTransition(t0); + QEventTransition *t1 = new QEventTransition(&button, QEvent::MouseButtonPress); + t1->setTargetState(s0); + s1->addTransition(t1); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s0)); + + QTest::mousePress(&button, Qt::LeftButton); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + s0->removeTransition(t0); + QTest::mousePress(&button, Qt::LeftButton); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s0)); + + QTest::mousePress(&button, Qt::LeftButton); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s0)); + + s1->removeTransition(t1); + QTest::mousePress(&button, Qt::LeftButton); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s0)); + + s0->addTransition(t0); + s1->addTransition(t1); + QTest::mousePress(&button, Qt::LeftButton); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + } +} + +void tst_QStateMachine::historyStates() +{ + for (int x = 0; x < 2; ++x) { + QStateMachine machine; + QState *root = machine.rootState(); + QState *s0 = new QState(root); + QState *s00 = new QState(s0); + QState *s01 = new QState(s0); + QHistoryState *s0h; + if (x == 0) { + s0h = new QHistoryState(s0); + QCOMPARE(s0h->historyType(), QHistoryState::ShallowHistory); + s0h->setHistoryType(QHistoryState::DeepHistory); + } else { + s0h = new QHistoryState(QHistoryState::DeepHistory, s0); + } + QCOMPARE(s0h->historyType(), QHistoryState::DeepHistory); + s0h->setHistoryType(QHistoryState::ShallowHistory); + QCOMPARE(s0h->historyType(), QHistoryState::ShallowHistory); + QCOMPARE(s0h->defaultState(), (QAbstractState*)0); + s0h->setDefaultState(s00); + QCOMPARE(s0h->defaultState(), (QAbstractState*)s00); + char warning[256]; + sprintf(warning, "QHistoryState::setDefaultState: state %p does not belong to this history state's group (%p)", s0, s0); + QTest::ignoreMessage(QtWarningMsg, warning); + s0h->setDefaultState(s0); + QState *s1 = new QState(root); + QFinalState *s2 = new QFinalState(root); + + s00->addTransition(new StringTransition("a", s01)); + s0->addTransition(new StringTransition("b", s1)); + s1->addTransition(new StringTransition("c", s0h)); + s0->addTransition(new StringTransition("d", s2)); + + root->setInitialState(s0); + s0->setInitialState(s00); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s0)); + QVERIFY(machine.configuration().contains(s00)); + + machine.postEvent(new StringEvent("a")); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s0)); + QVERIFY(machine.configuration().contains(s01)); + + machine.postEvent(new StringEvent("b")); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + machine.postEvent(new StringEvent("c")); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s0)); + QVERIFY(machine.configuration().contains(s01)); + + machine.postEvent(new StringEvent("d")); + QCoreApplication::processEvents(); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s2)); + + QTRY_COMPARE(finishedSpy.count(), 1); + } +} + +void tst_QStateMachine::startAndStop() +{ + QStateMachine machine; + QSignalSpy startedSpy(&machine, SIGNAL(started())); + QSignalSpy stoppedSpy(&machine, SIGNAL(stopped())); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + QVERIFY(!machine.isRunning()); + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::start: No initial state set for machine. Refusing to start."); + machine.start(); + QCOMPARE(startedSpy.count(), 0); + QCOMPARE(stoppedSpy.count(), 0); + QCOMPARE(finishedSpy.count(), 0); + QVERIFY(!machine.isRunning()); + machine.stop(); + QCOMPARE(startedSpy.count(), 0); + QCOMPARE(stoppedSpy.count(), 0); + QCOMPARE(finishedSpy.count(), 0); + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + machine.start(); + QTRY_COMPARE(machine.isRunning(), true); + QTRY_COMPARE(startedSpy.count(), 1); + QCOMPARE(stoppedSpy.count(), 0); + QCOMPARE(finishedSpy.count(), 0); + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(s1)); + + machine.stop(); + QTRY_COMPARE(machine.isRunning(), false); + QTRY_COMPARE(stoppedSpy.count(), 1); + QCOMPARE(startedSpy.count(), 1); + QCOMPARE(finishedSpy.count(), 0); + + QCOMPARE(machine.configuration().count(), 1); + QVERIFY(machine.configuration().contains(s1)); +} + +void tst_QStateMachine::targetStateWithNoParent() +{ + QStateMachine machine; + QState *s1 = new QState(machine.rootState()); + s1->setObjectName("s1"); + QState s2; + s1->addTransition(&s2); + machine.setInitialState(s1); + QSignalSpy startedSpy(&machine, SIGNAL(started())); + QSignalSpy stoppedSpy(&machine, SIGNAL(stopped())); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.start(); + QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: No common ancestor for targets and source of transition from state 's1'"); + QTRY_COMPARE(machine.isRunning(), true); + QTRY_COMPARE(startedSpy.count(), 1); + QCOMPARE(stoppedSpy.count(), 0); + QCOMPARE(finishedSpy.count(), 0); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(machine.errorState())); + QCOMPARE(machine.error(), QStateMachine::NoCommonAncestorForTransitionError); +} + +void tst_QStateMachine::targetStateDeleted() +{ + QStateMachine machine; + QState *s1 = new QState(machine.rootState()); + s1->setObjectName("s1"); + QState *s2 = new QState(machine.rootState()); + QAbstractTransition *trans = s1->addTransition(s2); + delete s2; + QCOMPARE(trans->targetState(), (QAbstractState*)0); + QVERIFY(trans->targetStates().isEmpty()); +} + +void tst_QStateMachine::defaultGlobalRestorePolicy() +{ + QStateMachine machine; + + QObject *propertyHolder = new QObject(&machine); + propertyHolder->setProperty("a", 1); + propertyHolder->setProperty("b", 2); + + QState *s1 = new QState(machine.rootState()); + s1->assignProperty(propertyHolder, "a", 3); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(propertyHolder, "b", 4); + + QState *s3 = new QState(machine.rootState()); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + s2->addTransition(new EventTransition(QEvent::User, s3)); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 4); +} + +/* +void tst_QStateMachine::restorePolicyNotInherited() +{ + QStateMachine machine; + + QObject *propertyHolder = new QObject(); + propertyHolder->setProperty("a", 1); + propertyHolder->setProperty("b", 2); + + QState *parentState = new QState(machine.rootState()); + parentState->setObjectName("parentState"); + parentState->setRestorePolicy(QState::RestoreProperties); + + QState *s1 = new QState(parentState); + s1->setObjectName("s1"); + s1->assignProperty(propertyHolder, "a", 3); + parentState->setInitialState(s1); + + QState *s2 = new QState(parentState); + s2->setObjectName("s2"); + s2->assignProperty(propertyHolder, "b", 4); + + QState *s3 = new QState(parentState); + s3->setObjectName("s3"); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + s2->addTransition(new EventTransition(QEvent::User, s3)); + + machine.setInitialState(parentState); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 4); + +}*/ + +void tst_QStateMachine::globalRestorePolicySetToDoNotRestore() +{ + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::DoNotRestoreProperties); + + QObject *propertyHolder = new QObject(&machine); + propertyHolder->setProperty("a", 1); + propertyHolder->setProperty("b", 2); + + QState *s1 = new QState(machine.rootState()); + s1->assignProperty(propertyHolder, "a", 3); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(propertyHolder, "b", 4); + + QState *s3 = new QState(machine.rootState()); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + s2->addTransition(new EventTransition(QEvent::User, s3)); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 4); +} + +/* +void tst_QStateMachine::setRestorePolicyToDoNotRestore() +{ + QObject *object = new QObject(); + object->setProperty("a", 1); + object->setProperty("b", 2); + + QStateMachine machine; + + QState *S1 = new QState(); + S1->setObjectName("S1"); + S1->assignProperty(object, "a", 3); + S1->setRestorePolicy(QState::DoNotRestoreProperties); + machine.addState(S1); + + QState *S2 = new QState(); + S2->setObjectName("S2"); + S2->assignProperty(object, "b", 5); + S2->setRestorePolicy(QState::DoNotRestoreProperties); + machine.addState(S2); + + QState *S3 = new QState(); + S3->setObjectName("S3"); + S3->setRestorePolicy(QState::DoNotRestoreProperties); + machine.addState(S3); + + QFinalState *S4 = new QFinalState(); + machine.addState(S4); + + S1->addTransition(new EventTransition(QEvent::User, S2)); + S2->addTransition(new EventTransition(QEvent::User, S3)); + S3->addTransition(S4); + + machine.setInitialState(S1); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(object->property("a").toInt(), 3); + QCOMPARE(object->property("b").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(object->property("a").toInt(), 3); + QCOMPARE(object->property("b").toInt(), 5); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(object->property("a").toInt(), 3); + QCOMPARE(object->property("b").toInt(), 5); +} + +void tst_QStateMachine::setGlobalRestorePolicyToGlobalRestore() +{ + s_countWarnings = false; + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::GlobalRestorePolicy); + + QCOMPARE(machine.globalRestorePolicy(), QStateMachine::DoNotRestoreProperties); + QCOMPARE(s_msgType, QtWarningMsg); + + s_msgType = QtDebugMsg; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + machine.setGlobalRestorePolicy(QStateMachine::GlobalRestorePolicy); + + QCOMPARE(machine.globalRestorePolicy(), QStateMachine::RestoreProperties); + QCOMPARE(s_msgType, QtWarningMsg); +} + + +void tst_QStateMachine::restorePolicyOnChildState() +{ + QStateMachine machine; + + QObject *propertyHolder = new QObject(); + propertyHolder->setProperty("a", 1); + propertyHolder->setProperty("b", 2); + + QState *parentState = new QState(machine.rootState()); + parentState->setObjectName("parentState"); + + QState *s1 = new QState(parentState); + s1->setRestorePolicy(QState::RestoreProperties); + s1->setObjectName("s1"); + s1->assignProperty(propertyHolder, "a", 3); + parentState->setInitialState(s1); + + QState *s2 = new QState(parentState); + s2->setRestorePolicy(QState::RestoreProperties); + s2->setObjectName("s2"); + s2->assignProperty(propertyHolder, "b", 4); + + QState *s3 = new QState(parentState); + s3->setRestorePolicy(QState::RestoreProperties); + s3->setObjectName("s3"); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + s2->addTransition(new EventTransition(QEvent::User, s3)); + + machine.setInitialState(parentState); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 1); + QCOMPARE(propertyHolder->property("b").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 1); + QCOMPARE(propertyHolder->property("b").toInt(), 2); +} +*/ + +void tst_QStateMachine::globalRestorePolicySetToRestore() +{ + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + + QObject *propertyHolder = new QObject(&machine); + propertyHolder->setProperty("a", 1); + propertyHolder->setProperty("b", 2); + + QState *s1 = new QState(machine.rootState()); + s1->assignProperty(propertyHolder, "a", 3); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(propertyHolder, "b", 4); + + QState *s3 = new QState(machine.rootState()); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + s2->addTransition(new EventTransition(QEvent::User, s3)); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 3); + QCOMPARE(propertyHolder->property("b").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 1); + QCOMPARE(propertyHolder->property("b").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("a").toInt(), 1); + QCOMPARE(propertyHolder->property("b").toInt(), 2); +} + +/* +void tst_QStateMachine::mixedRestoreProperties() +{ + QStateMachine machine; + + QObject *propertyHolder = new QObject(); + propertyHolder->setProperty("a", 1); + + QState *s1 = new QState(machine.rootState()); + s1->setRestorePolicy(QState::RestoreProperties); + s1->assignProperty(propertyHolder, "a", 3); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(propertyHolder, "a", 4); + + QState *s3 = new QState(machine.rootState()); + + QState *s4 = new QState(machine.rootState()); + s4->assignProperty(propertyHolder, "a", 5); + + QState *s5 = new QState(machine.rootState()); + s5->setRestorePolicy(QState::RestoreProperties); + s5->assignProperty(propertyHolder, "a", 6); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + s2->addTransition(new EventTransition(QEvent::User, s3)); + s3->addTransition(new EventTransition(QEvent::User, s4)); + s4->addTransition(new EventTransition(QEvent::User, s5)); + s5->addTransition(new EventTransition(QEvent::User, s3)); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + // Enter s1, save current + QCOMPARE(propertyHolder->property("a").toInt(), 3); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + // Enter s2, restorePolicy == DoNotRestore, so restore all properties + QCOMPARE(propertyHolder->property("a").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + // Enter s3 + QCOMPARE(propertyHolder->property("a").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + // Enter s4 + QCOMPARE(propertyHolder->property("a").toInt(), 5); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + // Enter s5, save current + QCOMPARE(propertyHolder->property("a").toInt(), 6); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + // Enter s3, restore + QCOMPARE(propertyHolder->property("a").toInt(), 5); +} +*/ + +void tst_QStateMachine::transitionWithParent() +{ + QStateMachine machine; + QState *s1 = new QState(machine.rootState()); + QState *s2 = new QState(machine.rootState()); + EventTransition *trans = new EventTransition(QEvent::User, s2, s1); + QCOMPARE(trans->sourceState(), s1); + QCOMPARE(trans->targetState(), (QAbstractState*)s2); + QCOMPARE(trans->targetStates().size(), 1); + QCOMPARE(trans->targetStates().at(0), (QAbstractState*)s2); +} + +void tst_QStateMachine::simpleAnimation() +{ + QStateMachine machine; + + QObject *object = new QObject(&machine); + object->setProperty("fooBar", 1.0); + + QState *s1 = new QState(machine.rootState()); + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "fooBar", 2.0); + + EventTransition *et = new EventTransition(QEvent::User, s2); + QPropertyAnimation *animation = new QPropertyAnimation(object, "fooBar", s2); + et->addAnimation(animation); + s1->addTransition(et); + + QState *s3 = new QState(machine.rootState()); + s2->addTransition(animation, SIGNAL(finished()), s3); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("fooBar").toDouble(), 2.0); +} + +class SlotCalledCounter: public QObject +{ + Q_OBJECT +public: + SlotCalledCounter() : counter(0) {} + + int counter; + +public slots: + void slot() { counter++; } +}; + +void tst_QStateMachine::twoAnimations() +{ + QStateMachine machine; + + QObject *object = new QObject(&machine); + object->setProperty("foo", 1.0); + object->setProperty("bar", 3.0); + + QState *s1 = new QState(machine.rootState()); + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + s2->assignProperty(object, "bar", 10.0); + + QPropertyAnimation *animationFoo = new QPropertyAnimation(object, "foo", s2); + QPropertyAnimation *animationBar = new QPropertyAnimation(object, "bar", s2); + animationBar->setDuration(900); + + SlotCalledCounter counter; + connect(animationFoo, SIGNAL(finished()), &counter, SLOT(slot())); + connect(animationBar, SIGNAL(finished()), &counter, SLOT(slot())); + + EventTransition *et = new EventTransition(QEvent::User, s2); + et->addAnimation(animationFoo); + et->addAnimation(animationBar); + s1->addTransition(et); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + s2->addTransition(s2, SIGNAL(polished()), s3); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 2.0); + QCOMPARE(object->property("bar").toDouble(), 10.0); + + QCOMPARE(counter.counter, 2); +} + +void tst_QStateMachine::twoAnimatedTransitions() +{ + QStateMachine machine; + + QObject *object = new QObject(&machine); + object->setProperty("foo", 1.0); + + QState *s1 = new QState(machine.rootState()); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 5.0); + QPropertyAnimation *fooAnimation = new QPropertyAnimation(object, "foo", s2); + s1->addTransition(new EventTransition(QEvent::User, s2))->addAnimation(fooAnimation); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + s2->addTransition(fooAnimation, SIGNAL(finished()), s3); + + QState *s4 = new QState(machine.rootState()); + s4->assignProperty(object, "foo", 2.0); + QPropertyAnimation *fooAnimation2 = new QPropertyAnimation(object, "foo", s4); + s3->addTransition(new EventTransition(QEvent::User, s4))->addAnimation(fooAnimation2); + + QState *s5 = new QState(machine.rootState()); + QObject::connect(s5, SIGNAL(entered()), QApplication::instance(), SLOT(quit())); + s4->addTransition(fooAnimation2, SIGNAL(finished()), s5); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 5.0); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s5)); + QCOMPARE(object->property("foo").toDouble(), 2.0); +} + +void tst_QStateMachine::playAnimationTwice() +{ + QStateMachine machine; + + QObject *object = new QObject(&machine); + object->setProperty("foo", 1.0); + + QState *s1 = new QState(machine.rootState()); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 5.0); + QPropertyAnimation *fooAnimation = new QPropertyAnimation(object, "foo", s2); + s1->addTransition(new EventTransition(QEvent::User, s2))->addAnimation(fooAnimation); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + s2->addTransition(fooAnimation, SIGNAL(finished()), s3); + + QState *s4 = new QState(machine.rootState()); + s4->assignProperty(object, "foo", 2.0); + s3->addTransition(new EventTransition(QEvent::User, s4))->addAnimation(fooAnimation); + + QState *s5 = new QState(machine.rootState()); + QObject::connect(s5, SIGNAL(entered()), QApplication::instance(), SLOT(quit())); + s4->addTransition(fooAnimation, SIGNAL(finished()), s5); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 5.0); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s5)); + QCOMPARE(object->property("foo").toDouble(), 2.0); +} + +void tst_QStateMachine::nestedTargetStateForAnimation() +{ + QStateMachine machine; + + QObject *object = new QObject(&machine); + object->setProperty("foo", 1.0); + object->setProperty("bar", 3.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + QState *s2 = new QState(machine.rootState()); + + s2->assignProperty(object, "foo", 2.0); + + QState *s2Child = new QState(s2); + s2Child->assignProperty(object, "bar", 10.0); + s2->setInitialState(s2Child); + + QState *s2Child2 = new QState(s2); + s2Child2->assignProperty(object, "bar", 11.0); + QAbstractTransition *at = s2Child->addTransition(new EventTransition(QEvent::User, s2Child2)); + + QPropertyAnimation *animation = new QPropertyAnimation(object, "bar", s2); + animation->setDuration(2000); + connect(animation, SIGNAL(finished()), &counter, SLOT(slot())); + at->addAnimation(animation); + + at = s1->addTransition(new EventTransition(QEvent::User, s2)); + + animation = new QPropertyAnimation(object, "foo", s2); + connect(animation, SIGNAL(finished()), &counter, SLOT(slot())); + at->addAnimation(animation); + + animation = new QPropertyAnimation(object, "bar", s2); + connect(animation, SIGNAL(finished()), &counter, SLOT(slot())); + at->addAnimation(animation); + + QState *s3 = new QState(machine.rootState()); + s2->addTransition(s2Child, SIGNAL(polished()), s3); + + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + machine.postEvent(new QEvent(QEvent::User)); + + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 2.0); + QCOMPARE(object->property("bar").toDouble(), 10.0); + QCOMPARE(counter.counter, 2); +} + +void tst_QStateMachine::animatedGlobalRestoreProperty() +{ + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + + QObject *object = new QObject(&machine); + object->setProperty("foo", 1.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + + QState *s4 = new QState(machine.rootState()); + QObject::connect(s4, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + QAbstractTransition *at = s1->addTransition(new EventTransition(QEvent::User, s2)); + QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", s2); + connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); + at->addAnimation(pa); + + at = s2->addTransition(pa, SIGNAL(finished()), s3); + pa = new QPropertyAnimation(object, "foo", s3); + connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); + at->addAnimation(pa); + + at = s3->addTransition(pa, SIGNAL(finished()), s4); + pa = new QPropertyAnimation(object, "foo", s4); + connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); + at->addAnimation(pa); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s4)); + QCOMPARE(object->property("foo").toDouble(), 1.0); + QCOMPARE(counter.counter, 2); +} + +void tst_QStateMachine::specificTargetValueOfAnimation() +{ + QStateMachine machine; + + QObject *object = new QObject(&machine); + object->setProperty("foo", 1.0); + + QState *s1 = new QState(machine.rootState()); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QPropertyAnimation *anim = new QPropertyAnimation(object, "foo"); + anim->setEndValue(10.0); + s1->addTransition(new EventTransition(QEvent::User, s2))->addAnimation(anim); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + s2->addTransition(anim, SIGNAL(finished()), s3); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 2.0); + QCOMPARE(anim->endValue().toDouble(), 10.0); +} + +void tst_QStateMachine::addDefaultAnimation() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("foo", 1.0); + + QState *s1 = new QState(machine.rootState()); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", &machine); + machine.addDefaultAnimation(pa); + s2->addTransition(pa, SIGNAL(finished()), s3); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 2.0); +} + +void tst_QStateMachine::addDefaultAnimationWithUnusedAnimation() +{ + QStateMachine machine; + + QObject *object = new QObject(&machine); + object->setProperty("foo", 1.0); + object->setProperty("bar", 2.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", &machine); + connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); + machine.addDefaultAnimation(pa); + s2->addTransition(pa, SIGNAL(finished()), s3); + + pa = new QPropertyAnimation(object, "bar", &machine); + connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); + machine.addDefaultAnimation(pa); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 2.0); + QCOMPARE(counter.counter, 1); +} + +void tst_QStateMachine::removeDefaultAnimation() +{ + QStateMachine machine; + + QObject propertyHolder; + propertyHolder.setProperty("foo", 0); + + QCOMPARE(machine.defaultAnimations().size(), 0); + + QPropertyAnimation *anim = new QPropertyAnimation(&propertyHolder, "foo"); + + machine.addDefaultAnimation(anim); + + QCOMPARE(machine.defaultAnimations().size(), 1); + QVERIFY(machine.defaultAnimations().contains(anim)); + + machine.removeDefaultAnimation(anim); + + QCOMPARE(machine.defaultAnimations().size(), 0); + + machine.addDefaultAnimation(anim); + + QPropertyAnimation *anim2 = new QPropertyAnimation(&propertyHolder, "foo"); + machine.addDefaultAnimation(anim2); + + QCOMPARE(machine.defaultAnimations().size(), 2); + QVERIFY(machine.defaultAnimations().contains(anim)); + QVERIFY(machine.defaultAnimations().contains(anim2)); + + machine.removeDefaultAnimation(anim); + + QCOMPARE(machine.defaultAnimations().size(), 1); + QVERIFY(machine.defaultAnimations().contains(anim2)); + + machine.removeDefaultAnimation(anim2); + QCOMPARE(machine.defaultAnimations().size(), 0); +} + +void tst_QStateMachine::overrideDefaultAnimationWithSpecific() +{ + QStateMachine machine; + + QObject *object = new QObject(&machine); + object->setProperty("foo", 1.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + QAbstractTransition *at = s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); + connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); + s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); + connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + machine.addDefaultAnimation(defaultAnimation); + at->addAnimation(moreSpecificAnimation); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(counter.counter, 2); // specific animation started and stopped +} + +/* +void tst_QStateMachine::addDefaultAnimationForSource() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("foo", 1.0); + + QState *s1 = new QState(machine.rootState()); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", &machine); + machine.addDefaultAnimationForSourceState(s1, pa); + s2->addTransition(pa, SIGNAL(finished()), s3); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 2.0); +} + +void tst_QStateMachine::addDefaultAnimationForTarget() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("foo", 1.0); + + QState *s1 = new QState(machine.rootState()); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", &machine); + machine.addDefaultAnimationForTargetState(s2, pa); + s2->addTransition(pa, SIGNAL(finished()), s3); + + machine.setInitialState(s1); + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(object->property("foo").toDouble(), 2.0); +} + +void tst_QStateMachine::removeDefaultAnimationForSource() +{ + QStateMachine machine; + + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); + + QPropertyAnimation *anim = new QPropertyAnimation(this, "foo"); + + machine.addDefaultAnimationForSourceState(machine.rootState(), anim); + + QCOMPARE(machine.defaultAnimations().size(), 0); + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 1); + QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim)); + + machine.removeDefaultAnimationForTargetState(machine.rootState(), anim); + + QCOMPARE(machine.defaultAnimations().size(), 0); + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 1); + QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim)); + + machine.removeDefaultAnimationForSourceState(machine.rootState(), anim); + + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); + + machine.addDefaultAnimationForSourceState(machine.rootState(), anim); + + QPropertyAnimation *anim2 = new QPropertyAnimation(this, "foo"); + machine.addDefaultAnimationForSourceState(machine.rootState(), anim2); + + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 2); + QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim)); + QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim2)); + + machine.removeDefaultAnimationForSourceState(machine.rootState(), anim); + + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 1); + QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim2)); + + machine.removeDefaultAnimationForSourceState(machine.rootState(), anim2); + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); +} + +void tst_QStateMachine::removeDefaultAnimationForTarget() +{ + QStateMachine machine; + + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); + + QPropertyAnimation *anim = new QPropertyAnimation(this, "foo"); + + machine.addDefaultAnimationForTargetState(machine.rootState(), anim); + + QCOMPARE(machine.defaultAnimations().size(), 0); + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 1); + QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim)); + + machine.removeDefaultAnimationForSourceState(machine.rootState(), anim); + + QCOMPARE(machine.defaultAnimations().size(), 0); + QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 1); + QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim)); + + machine.removeDefaultAnimationForTargetState(machine.rootState(), anim); + + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); + + machine.addDefaultAnimationForTargetState(machine.rootState(), anim); + + QPropertyAnimation *anim2 = new QPropertyAnimation(this, "foo"); + machine.addDefaultAnimationForTargetState(machine.rootState(), anim2); + + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 2); + QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim)); + QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim2)); + + machine.removeDefaultAnimationForTargetState(machine.rootState(), anim); + + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 1); + QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim2)); + + machine.removeDefaultAnimationForTargetState(machine.rootState(), anim2); + QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); +} + +void tst_QStateMachine::overrideDefaultAnimationWithSource() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("foo", 1.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); + connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); + s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); + connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + machine.addDefaultAnimation(defaultAnimation); + machine.addDefaultAnimationForSourceState(s1, moreSpecificAnimation); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(counter.counter, 2); // specific animation started and stopped +} + +void tst_QStateMachine::overrideDefaultAnimationWithTarget() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("foo", 1.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); + connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); + s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); + connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + machine.addDefaultAnimation(defaultAnimation); + machine.addDefaultAnimationForTargetState(s2, moreSpecificAnimation); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(counter.counter, 2); // specific animation started and stopped + +} + +void tst_QStateMachine::overrideDefaultSourceAnimationWithSpecific() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("foo", 1.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + QAbstractTransition *at = s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); + connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); + s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); + connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + machine.addDefaultAnimationForSourceState(s1, defaultAnimation); + at->addAnimation(moreSpecificAnimation); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(counter.counter, 2); // specific animation started and stopped +} + +void tst_QStateMachine::overrideDefaultTargetAnimationWithSpecific() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("foo", 1.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + QAbstractTransition *at = s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); + connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); + s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); + connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + machine.addDefaultAnimationForTargetState(s2, defaultAnimation); + at->addAnimation(moreSpecificAnimation); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(counter.counter, 2); // specific animation started and stopped +} + +void tst_QStateMachine::overrideDefaultTargetAnimationWithSource() +{ + QStateMachine machine; + + QObject *object = new QObject(); + object->setProperty("foo", 1.0); + + SlotCalledCounter counter; + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(object, "foo", 2.0); + + QState *s3 = new QState(machine.rootState()); + QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + + QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); + connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); + s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); + connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); + + machine.addDefaultAnimationForTargetState(s2, defaultAnimation); + machine.addDefaultAnimationForSourceState(s1, moreSpecificAnimation); + + machine.start(); + QCoreApplication::processEvents(); + + machine.postEvent(new QEvent(QEvent::User)); + QCOREAPPLICATION_EXEC(5000); + + QVERIFY(machine.configuration().contains(s3)); + QCOMPARE(counter.counter, 2); // specific animation started and stopped +} + +*/ + +void tst_QStateMachine::parallelStateAssignmentsDone() +{ + QStateMachine machine; + + QObject *propertyHolder = new QObject(&machine); + propertyHolder->setProperty("foo", 123); + propertyHolder->setProperty("bar", 456); + propertyHolder->setProperty("zoot", 789); + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *parallelState = new QState(QState::ParallelStates, machine.rootState()); + parallelState->assignProperty(propertyHolder, "foo", 321); + + QState *s2 = new QState(parallelState); + s2->assignProperty(propertyHolder, "bar", 654); + + QState *s3 = new QState(parallelState); + s3->assignProperty(propertyHolder, "zoot", 987); + + s1->addTransition(new EventTransition(QEvent::User, parallelState)); + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("foo").toInt(), 123); + QCOMPARE(propertyHolder->property("bar").toInt(), 456); + QCOMPARE(propertyHolder->property("zoot").toInt(), 789); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(propertyHolder->property("foo").toInt(), 321); + QCOMPARE(propertyHolder->property("bar").toInt(), 654); + QCOMPARE(propertyHolder->property("zoot").toInt(), 987); +} + +void tst_QStateMachine::transitionsFromParallelStateWithNoChildren() +{ + QStateMachine machine; + + QState *parallelState = new QState(QState::ParallelStates, machine.rootState()); + machine.setInitialState(parallelState); + + QState *s1 = new QState(machine.rootState()); + parallelState->addTransition(new EventTransition(QEvent::User, s1)); + + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(1, machine.configuration().size()); + QVERIFY(machine.configuration().contains(parallelState)); + + machine.postEvent(new QEvent(QEvent::User)); + + QCoreApplication::processEvents(); + + QCOMPARE(1, machine.configuration().size()); + QVERIFY(machine.configuration().contains(s1)); +} + +void tst_QStateMachine::parallelStateTransition() +{ + QStateMachine machine; + + QState *parallelState = new QState(QState::ParallelStates, machine.rootState()); + machine.setInitialState(parallelState); + + QState *s1 = new QState(parallelState); + QState *s2 = new QState(parallelState); + + QState *s1InitialChild = new QState(s1); + s1->setInitialState(s1InitialChild); + + QState *s2InitialChild = new QState(s2); + s2->setInitialState(s2InitialChild); + + QState *s1OtherChild = new QState(s1); + + s1->addTransition(new EventTransition(QEvent::User, s1OtherChild)); + + machine.start(); + QCoreApplication::processEvents(); + + QVERIFY(machine.configuration().contains(parallelState)); + QVERIFY(machine.configuration().contains(s1)); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s1InitialChild)); + QVERIFY(machine.configuration().contains(s2InitialChild)); + QCOMPARE(machine.configuration().size(), 5); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QVERIFY(machine.configuration().contains(parallelState)); + + QVERIFY(machine.configuration().contains(s1)); + + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s1OtherChild)); + QVERIFY(machine.configuration().contains(s2InitialChild)); + QCOMPARE(machine.configuration().size(), 5); + +} + +void tst_QStateMachine::nestedRestoreProperties() +{ + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + + QObject *propertyHolder = new QObject(&machine); + propertyHolder->setProperty("foo", 1); + propertyHolder->setProperty("bar", 2); + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(propertyHolder, "foo", 3); + + QState *s21 = new QState(s2); + s21->assignProperty(propertyHolder, "bar", 4); + s2->setInitialState(s21); + + QState *s22 = new QState(s2); + s22->assignProperty(propertyHolder, "bar", 5); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + s21->addTransition(new EventTransition(QEvent::User, s22)); + + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + QCOMPARE(propertyHolder->property("foo").toInt(), 1); + QCOMPARE(propertyHolder->property("bar").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s21)); + QCOMPARE(propertyHolder->property("foo").toInt(), 3); + QCOMPARE(propertyHolder->property("bar").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s22)); + QCOMPARE(propertyHolder->property("foo").toInt(), 3); + QCOMPARE(propertyHolder->property("bar").toInt(), 5); +} + +void tst_QStateMachine::nestedRestoreProperties2() +{ + QStateMachine machine; + machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); + + QObject *propertyHolder = new QObject(&machine); + propertyHolder->setProperty("foo", 1); + propertyHolder->setProperty("bar", 2); + + QState *s1 = new QState(machine.rootState()); + machine.setInitialState(s1); + + QState *s2 = new QState(machine.rootState()); + s2->assignProperty(propertyHolder, "foo", 3); + + QState *s21 = new QState(s2); + s21->assignProperty(propertyHolder, "bar", 4); + s2->setInitialState(s21); + + QState *s22 = new QState(s2); + s22->assignProperty(propertyHolder, "foo", 6); + s22->assignProperty(propertyHolder, "bar", 5); + + s1->addTransition(new EventTransition(QEvent::User, s2)); + s21->addTransition(new EventTransition(QEvent::User, s22)); + s22->addTransition(new EventTransition(QEvent::User, s21)); + + machine.start(); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + QCOMPARE(propertyHolder->property("foo").toInt(), 1); + QCOMPARE(propertyHolder->property("bar").toInt(), 2); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s21)); + QCOMPARE(propertyHolder->property("foo").toInt(), 3); + QCOMPARE(propertyHolder->property("bar").toInt(), 4); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s22)); + QCOMPARE(propertyHolder->property("foo").toInt(), 6); + QCOMPARE(propertyHolder->property("bar").toInt(), 5); + + machine.postEvent(new QEvent(QEvent::User)); + QCoreApplication::processEvents(); + + QCOMPARE(machine.configuration().size(), 2); + QVERIFY(machine.configuration().contains(s2)); + QVERIFY(machine.configuration().contains(s21)); + QCOMPARE(propertyHolder->property("foo").toInt(), 3); + QCOMPARE(propertyHolder->property("bar").toInt(), 4); + +} + + +QTEST_MAIN(tst_QStateMachine) +#include "tst_qstatemachine.moc" diff --git a/tests/benchmarks/benchmarks.pro b/tests/benchmarks/benchmarks.pro index 8e2c243..4c39373 100644 --- a/tests/benchmarks/benchmarks.pro +++ b/tests/benchmarks/benchmarks.pro @@ -1,6 +1,7 @@ TEMPLATE = subdirs SUBDIRS = containers-associative \ containers-sequential \ + qanimation \ qbytearray \ qpainter \ qtestlib-simple events \ diff --git a/tests/benchmarks/qanimation/dummyanimation.cpp b/tests/benchmarks/qanimation/dummyanimation.cpp new file mode 100644 index 0000000..6fb1d0a --- /dev/null +++ b/tests/benchmarks/qanimation/dummyanimation.cpp @@ -0,0 +1,20 @@ +#include "dummyanimation.h" +#include "dummyobject.h" + + +DummyAnimation::DummyAnimation(DummyObject *d) : m_dummy(d) +{ +} + +void DummyAnimation::updateCurrentValue(const QVariant &value) +{ + if (state() == Stopped) + return; + if (m_dummy) + m_dummy->setRect(value.toRect()); +} + +void DummyAnimation::updateState(State state) +{ + Q_UNUSED(state); +} diff --git a/tests/benchmarks/qanimation/dummyanimation.h b/tests/benchmarks/qanimation/dummyanimation.h new file mode 100644 index 0000000..fe6592b --- /dev/null +++ b/tests/benchmarks/qanimation/dummyanimation.h @@ -0,0 +1,19 @@ +#include + +#ifndef _DUMMYANIMATION_H__ + +class DummyObject; + +class DummyAnimation : public QVariantAnimation +{ +public: + DummyAnimation(DummyObject *d); + + void updateCurrentValue(const QVariant &value); + void updateState(State state); + +private: + DummyObject *m_dummy; +}; + +#endif \ No newline at end of file diff --git a/tests/benchmarks/qanimation/dummyobject.cpp b/tests/benchmarks/qanimation/dummyobject.cpp new file mode 100644 index 0000000..bd76388 --- /dev/null +++ b/tests/benchmarks/qanimation/dummyobject.cpp @@ -0,0 +1,25 @@ +#include "dummyobject.h" + +DummyObject::DummyObject() +{ +} + +QRect DummyObject::rect() const +{ + return m_rect; +} + +void DummyObject::setRect(const QRect &r) +{ + m_rect = r; +} + +float DummyObject::opacity() const +{ + return m_opacity; +} + +void DummyObject::setOpacity(float o) +{ + m_opacity = o; +} diff --git a/tests/benchmarks/qanimation/dummyobject.h b/tests/benchmarks/qanimation/dummyobject.h new file mode 100644 index 0000000..c989662 --- /dev/null +++ b/tests/benchmarks/qanimation/dummyobject.h @@ -0,0 +1,23 @@ +#include + +#ifndef _DUMMYOBJECT_H__ + +class DummyObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(QRect rect READ rect WRITE setRect) + Q_PROPERTY(float opacity READ opacity WRITE setOpacity) +public: + DummyObject(); + QRect rect() const; + void setRect(const QRect &r); + float opacity() const; + void setOpacity(float); + +private: + QRect m_rect; + float m_opacity; +}; + + +#endif \ No newline at end of file diff --git a/tests/benchmarks/qanimation/main.cpp b/tests/benchmarks/qanimation/main.cpp new file mode 100644 index 0000000..7bb770f --- /dev/null +++ b/tests/benchmarks/qanimation/main.cpp @@ -0,0 +1,150 @@ +#include +#include + +#include "dummyobject.h" +#include "dummyanimation.h" +#include "rectanimation.h" + +#define ITERATION_COUNT 10e3 + +class tst_qanimation : public QObject +{ + Q_OBJECT +private slots: + void itemPropertyAnimation(); + void itemPropertyAnimation_data() { data();} + void dummyAnimation(); + void dummyAnimation_data() { data();} + void dummyPropertyAnimation(); + void dummyPropertyAnimation_data() { data();} + void rectAnimation(); + void rectAnimation_data() { data();} + + void floatAnimation_data() { data(); } + void floatAnimation(); + +private: + void data(); +}; + + +void tst_qanimation::data() +{ + QTest::addColumn("started"); + QTest::newRow("NotRunning") << false; + QTest::newRow("Running") << true; +} + +void tst_qanimation::itemPropertyAnimation() +{ + QFETCH(bool, started); + QGraphicsWidget item; + + //then the property animation + { + QPropertyAnimation anim(&item, "pos"); + anim.setDuration(ITERATION_COUNT); + anim.setStartValue(QPointF(0,0)); + anim.setEndValue(QPointF(ITERATION_COUNT,ITERATION_COUNT)); + if (started) + anim.start(); + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + anim.setCurrentTime(i); + } + } + } + +} + +void tst_qanimation::dummyAnimation() +{ + QFETCH(bool, started); + DummyObject dummy; + + //first the dummy animation + { + DummyAnimation anim(&dummy); + anim.setDuration(ITERATION_COUNT); + anim.setStartValue(QRect(0, 0, 0, 0)); + anim.setEndValue(QRect(0, 0, ITERATION_COUNT,ITERATION_COUNT)); + if (started) + anim.start(); + QBENCHMARK { + for(int i = 0; i < anim.duration(); ++i) { + anim.setCurrentTime(i); + } + } + } +} + +void tst_qanimation::dummyPropertyAnimation() +{ + QFETCH(bool, started); + DummyObject dummy; + + //then the property animation + { + QPropertyAnimation anim(&dummy, "rect"); + anim.setDuration(ITERATION_COUNT); + anim.setStartValue(QRect(0, 0, 0, 0)); + anim.setEndValue(QRect(0, 0, ITERATION_COUNT,ITERATION_COUNT)); + if (started) + anim.start(); + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + anim.setCurrentTime(i); + } + } + } +} + +void tst_qanimation::rectAnimation() +{ + //this is the simplest animation you can do + QFETCH(bool, started); + DummyObject dummy; + + //then the property animation + { + RectAnimation anim(&dummy); + anim.setDuration(ITERATION_COUNT); + anim.setStartValue(QRect(0, 0, 0, 0)); + anim.setEndValue(QRect(0, 0, ITERATION_COUNT,ITERATION_COUNT)); + if (started) + anim.start(); + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + anim.setCurrentTime(i); + } + } + } +} + +void tst_qanimation::floatAnimation() +{ + //this is the simplest animation you can do + QFETCH(bool, started); + DummyObject dummy; + + //then the property animation + { + QPropertyAnimation anim(&dummy, "opacity"); + anim.setDuration(ITERATION_COUNT); + anim.setStartValue(0.f); + anim.setEndValue(1.f); + if (started) + anim.start(); + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + anim.setCurrentTime(i); + } + } + } +} + + + +QTEST_MAIN(tst_qanimation) + +#include "main.moc" diff --git a/tests/benchmarks/qanimation/qanimation.pro b/tests/benchmarks/qanimation/qanimation.pro new file mode 100644 index 0000000..55cd75e --- /dev/null +++ b/tests/benchmarks/qanimation/qanimation.pro @@ -0,0 +1,18 @@ +load(qttest_p4) +TEMPLATE = app +TARGET = tst_qanimation +DEPENDPATH += . +INCLUDEPATH += . + +CONFIG += release +#CONFIG += debug + + +SOURCES += main.cpp \ + dummyobject.cpp \ + dummyanimation.cpp \ + rectanimation.cpp + +HEADERS += dummyobject.h \ + dummyanimation.h \ + rectanimation.h diff --git a/tests/benchmarks/qanimation/rectanimation.cpp b/tests/benchmarks/qanimation/rectanimation.cpp new file mode 100644 index 0000000..d60a943 --- /dev/null +++ b/tests/benchmarks/qanimation/rectanimation.cpp @@ -0,0 +1,58 @@ +#include "rectanimation.h" +#include "dummyobject.h" + +static inline int interpolateInteger(int from, int to, qreal progress) +{ + return from + (to - from) * progress; +} + + +RectAnimation::RectAnimation(DummyObject *obj) : m_object(obj), m_dura(250) +{ +} + +void RectAnimation::setEndValue(const QRect &rect) +{ + m_end = rect; +} + +void RectAnimation::setStartValue(const QRect &rect) +{ + m_start = rect; +} + +void RectAnimation::setDuration(int d) +{ + m_dura = d; +} + +int RectAnimation::duration() const +{ + return m_dura; +} + + +void RectAnimation::updateCurrentTime(int msecs) +{ + qreal progress = m_easing.valueForProgress( qreal(msecs) / qreal(m_dura) ); + QRect now; + now.setCoords(interpolateInteger(m_start.left(), m_end.left(), progress), + interpolateInteger(m_start.top(), m_end.top(), progress), + interpolateInteger(m_start.right(), m_end.right(), progress), + interpolateInteger(m_start.bottom(), m_end.bottom(), progress)); + + bool changed = (now != m_current); + if (changed) + m_current = now; + + if (state() == Stopped) + return; + + if (m_object) + m_object->setRect(m_current); +} + +void RectAnimation::updateState(QAbstractAnimation::State state) +{ + Q_UNUSED(state); +} diff --git a/tests/benchmarks/qanimation/rectanimation.h b/tests/benchmarks/qanimation/rectanimation.h new file mode 100644 index 0000000..99b82b4 --- /dev/null +++ b/tests/benchmarks/qanimation/rectanimation.h @@ -0,0 +1,30 @@ +#include + +#ifndef _RECTANIMATION_H__ + +class DummyObject; + +//this class is even simpler than the dummy +//and uses no QVariant at all +class RectAnimation : public QAbstractAnimation +{ +public: + RectAnimation(DummyObject *obj); + + void setEndValue(const QRect &rect); + void setStartValue(const QRect &rect); + + void setDuration(int d); + int duration() const; + + virtual void updateCurrentTime(int msecs); + virtual void updateState(QAbstractAnimation::State state); + +private: + DummyObject *m_object; + QEasingCurve m_easing; + QRect m_start, m_end, m_current; + int m_dura; +}; + +#endif diff --git a/tests/benchmarks/qvariant/qvariant.pro b/tests/benchmarks/qvariant/qvariant.pro index 68b4a97..63b5442 100644 --- a/tests/benchmarks/qvariant/qvariant.pro +++ b/tests/benchmarks/qvariant/qvariant.pro @@ -3,7 +3,6 @@ TEMPLATE = app TARGET = tst_qvariant DEPENDPATH += . INCLUDEPATH += . -QT -= gui CONFIG += release #CONFIG += debug diff --git a/tests/benchmarks/qvariant/tst_qvariant.cpp b/tests/benchmarks/qvariant/tst_qvariant.cpp index 4a7ad02..0eb1ae2 100644 --- a/tests/benchmarks/qvariant/tst_qvariant.cpp +++ b/tests/benchmarks/qvariant/tst_qvariant.cpp @@ -38,7 +38,9 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ + #include +#include #include #define ITERATION_COUNT 1e5 @@ -47,64 +49,73 @@ class tst_qvariant : public QObject { Q_OBJECT private slots: + void testBound(); + void doubleVariantCreation(); void floatVariantCreation(); void rectVariantCreation(); void stringVariantCreation(); + void pixmapVariantCreation(); + void doubleVariantSetValue(); void floatVariantSetValue(); void rectVariantSetValue(); void stringVariantSetValue(); + void doubleVariantAssignment(); void floatVariantAssignment(); void rectVariantAssignment(); void stringVariantAssignment(); }; - -void tst_qvariant::doubleVariantCreation() +void tst_qvariant::testBound() { - double d = 0; + qreal d = qreal(.5); QBENCHMARK { for(int i = 0; i < ITERATION_COUNT; ++i) { - QVariant v(d); + d = qBound(0, d, 1); } } } -void tst_qvariant::floatVariantCreation() +template +static void variantCreation(T val) { - float f = 0; QBENCHMARK { for(int i = 0; i < ITERATION_COUNT; ++i) { - QVariant v(f); + QVariant v(val); } } } +void tst_qvariant::doubleVariantCreation() +{ + variantCreation(0.0); +} + +void tst_qvariant::floatVariantCreation() +{ + variantCreation(0.0f); +} + void tst_qvariant::rectVariantCreation() { - QRect r(1,2,3,4); - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - QVariant v(r); - } - } + variantCreation(QRect(1, 2, 3, 4)); } void tst_qvariant::stringVariantCreation() { - QString s; - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - QVariant v(s); - } - } + variantCreation(QString()); } -void tst_qvariant::doubleVariantSetValue() +void tst_qvariant::pixmapVariantCreation() +{ + variantCreation(QPixmap()); +} + +template +static void variantSetValue(T d) { - double d = 0; QVariant v; QBENCHMARK { for(int i = 0; i < ITERATION_COUNT; ++i) { @@ -113,42 +124,29 @@ void tst_qvariant::doubleVariantSetValue() } } +void tst_qvariant::doubleVariantSetValue() +{ + variantSetValue(0.0); +} + void tst_qvariant::floatVariantSetValue() { - float f = 0; - QVariant v; - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - qVariantSetValue(v, f); - } - } + variantSetValue(0.0f); } void tst_qvariant::rectVariantSetValue() { - QRect r; - QVariant v; - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - qVariantSetValue(v, r); - } - } + variantSetValue(QRect()); } void tst_qvariant::stringVariantSetValue() { - QString s; - QVariant v; - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - qVariantSetValue(v, s); - } - } + variantSetValue(QString()); } -void tst_qvariant::doubleVariantAssignment() +template +static void variantAssignment(T d) { - double d = 0; QVariant v; QBENCHMARK { for(int i = 0; i < ITERATION_COUNT; ++i) { @@ -157,37 +155,24 @@ void tst_qvariant::doubleVariantAssignment() } } +void tst_qvariant::doubleVariantAssignment() +{ + variantAssignment(0.0); +} + void tst_qvariant::floatVariantAssignment() { - float f = 0; - QVariant v; - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - v = f; - } - } + variantAssignment(0.0f); } void tst_qvariant::rectVariantAssignment() { - QRect r; - QVariant v; - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - v = r; - } - } + variantAssignment(QRect()); } void tst_qvariant::stringVariantAssignment() { - QString s; - QVariant v; - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - v = s; - } - } + variantAssignment(QString()); } QTEST_MAIN(tst_qvariant) -- cgit v0.12 From 7c00cc50fc41a7c7b9c04e258a9eb03ff187c574 Mon Sep 17 00:00:00 2001 From: jasplin Date: Fri, 22 May 2009 13:23:39 +0200 Subject: Clarified doc for QGraphicsTextItem::setTextInteractionFlags(). Reviewed-by: TrustMe Task-number: 253559 --- src/gui/graphicsview/qgraphicsitem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 828dd4f..bd764b5 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -8837,9 +8837,9 @@ bool QGraphicsTextItemPrivate::_q_mouseOnEdge(QGraphicsSceneMouseEvent *event) Sets the flags \a flags to specify how the text item should react to user input. - The default for a QGraphicsTextItem is Qt::NoTextInteraction. Setting a - value different to Qt::NoTextInteraction will also set the ItemIsFocusable - QGraphicsItem flag. + The default for a QGraphicsTextItem is Qt::NoTextInteraction. This function + also affects the ItemIsFocusable QGraphicsItem flag by setting it if \a flags + is different from Qt::NoTextInteraction and clearing it otherwise. By default, the text is read-only. To transform the item into an editor, set the Qt::TextEditable flag. -- cgit v0.12 From bc498cd027dff6ff16032868c6bb00e634749cd6 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Fri, 22 May 2009 13:52:47 +0200 Subject: Fix Qt does not compile when glibc < 2.3.2 on linux Rather than try to resolve functions or impose configure time limitations we simply remove the dependancy entirely and rely on the fallbac for all platforms. Task-number: 250731 Reviewed-by: thiago --- src/gui/styles/gtksymbols.cpp | 27 +++++---------------------- 1 file changed, 5 insertions(+), 22 deletions(-) diff --git a/src/gui/styles/gtksymbols.cpp b/src/gui/styles/gtksymbols.cpp index 0842ec7..d8a67c2 100644 --- a/src/gui/styles/gtksymbols.cpp +++ b/src/gui/styles/gtksymbols.cpp @@ -633,31 +633,14 @@ GtkStyle* QGtk::gtkStyle(const QString &path) return 0; } -#ifdef Q_OS_LINUX -QT_END_NAMESPACE - -int getresuid(uid_t *ruid, uid_t *euid, uid_t *suid); -int getresgid(gid_t *rgid, gid_t *egid, gid_t *sgid); - -QT_BEGIN_NAMESPACE -#endif - void QGtk::initGtkWidgets() { // From gtkmain.c - - uid_t ruid, rgid, euid, egid, suid, sgid; - -#ifdef Q_OS_LINUX - if (getresuid (&ruid, &euid, &suid) != 0 || getresgid (&rgid, &egid, &sgid) != 0) -#endif - { - suid = ruid = getuid (); - sgid = rgid = getgid (); - euid = geteuid (); - egid = getegid (); - } - if (ruid != euid || ruid != suid || rgid != egid || rgid != sgid) { + uid_t ruid = getuid (); + uid_t rgid = getgid (); + uid_t euid = geteuid (); + uid_t egid = getegid (); + if (ruid != euid || rgid != egid) { qWarning("\nThis process is currently running setuid or setgid.\nGTK+ does not allow this " "therefore Qt cannot use the GTK+ integration.\nTry launching your app using \'gksudo\', " "\'kdesudo\' or a similar tool.\n\n" -- cgit v0.12 From b89efc8e7f3289ff85a5076297e4357283dd24a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 22 May 2009 12:27:48 +0200 Subject: Fixed text shaping bugs with ligatures and multiple font engines. If Harfbuzz shaping adds or merges glyphs we need to move the remaining glyphs in the glyph layout to compensate. Task-number: 253783 Reviewed-by: Simon Hausmann --- src/gui/text/qtextengine.cpp | 40 ++++++++++++++++++++++++++-------------- 1 file changed, 26 insertions(+), 14 deletions(-) diff --git a/src/gui/text/qtextengine.cpp b/src/gui/text/qtextengine.cpp index 80a5425..da1ab25 100644 --- a/src/gui/text/qtextengine.cpp +++ b/src/gui/text/qtextengine.cpp @@ -1099,6 +1099,16 @@ void QTextEngine::shapeTextWithCE(int item) const } #endif +static inline void moveGlyphData(const QGlyphLayout &destination, const QGlyphLayout &source, int num) +{ + if (num > 0 && destination.glyphs != source.glyphs) { + memmove(destination.glyphs, source.glyphs, num * sizeof(HB_Glyph)); + memmove(destination.attributes, source.attributes, num * sizeof(HB_GlyphAttributes)); + memmove(destination.advances_x, source.advances_x, num * sizeof(HB_Fixed)); + memmove(destination.offsets, source.offsets, num * sizeof(HB_FixedPoint)); + } +} + /// take the item from layoutData->items and void QTextEngine::shapeTextWithHarfbuzz(int item) const { @@ -1189,7 +1199,7 @@ void QTextEngine::shapeTextWithHarfbuzz(int item) const - int initial_glyph_pos = 0; + int remaining_glyphs = entire_shaper_item.num_glyphs; int glyph_pos = 0; // for each item shape using harfbuzz and store the results in our layoutData's glyphs array. for (int k = 0; k < itemBoundaries.size(); k += 2) { // for the +2, see the comment at the definition of itemBoundaries @@ -1209,7 +1219,7 @@ void QTextEngine::shapeTextWithHarfbuzz(int item) const QFontEngine *actualFontEngine = font; uint engineIdx = 0; if (font->type() == QFontEngine::Multi) { - engineIdx = uint(initialGlyphs.glyphs[itemBoundaries[k + 1]] >> 24); + engineIdx = uint(initialGlyphs.glyphs[glyph_pos] >> 24); actualFontEngine = static_cast(font)->engine(engineIdx); } @@ -1219,16 +1229,18 @@ void QTextEngine::shapeTextWithHarfbuzz(int item) const shaper_item.glyphIndicesPresent = true; + remaining_glyphs -= shaper_item.initialGlyphCount; + do { - ensureSpace(glyph_pos + shaper_item.num_glyphs); - initialGlyphs = availableGlyphs(&si).mid(0, entire_shaper_item.num_glyphs); - shaper_item.num_glyphs = layoutData->glyphLayout.numGlyphs - layoutData->used - glyph_pos; + ensureSpace(glyph_pos + shaper_item.num_glyphs + remaining_glyphs); - const QGlyphLayout g = availableGlyphs(&si); - shaper_item.glyphs = g.glyphs + glyph_pos; - shaper_item.attributes = g.attributes + glyph_pos; - shaper_item.advances = reinterpret_cast(g.advances_x + glyph_pos); - shaper_item.offsets = reinterpret_cast(g.offsets + glyph_pos); + const QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos); + moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs); + + shaper_item.glyphs = g.glyphs; + shaper_item.attributes = g.attributes; + shaper_item.advances = reinterpret_cast(g.advances_x); + shaper_item.offsets = reinterpret_cast(g.offsets); if (shaper_item.glyphIndicesPresent) { for (hb_uint32 i = 0; i < shaper_item.initialGlyphCount; ++i) @@ -1241,18 +1253,18 @@ void QTextEngine::shapeTextWithHarfbuzz(int item) const } while (!qShapeItem(&shaper_item)); // this does the actual shaping via harfbuzz. QGlyphLayout g = availableGlyphs(&si).mid(glyph_pos, shaper_item.num_glyphs); + moveGlyphData(g.mid(shaper_item.num_glyphs), g.mid(shaper_item.initialGlyphCount), remaining_glyphs); - for (hb_uint32 i = 0; i < shaper_item.item.length; ++i) { + for (hb_uint32 i = 0; i < shaper_item.num_glyphs; ++i) g.glyphs[i] = g.glyphs[i] | (engineIdx << 24); + + for (hb_uint32 i = 0; i < shaper_item.item.length; ++i) shaper_item.log_clusters[i] += glyph_pos; - } if (kerningEnabled && !shaper_item.kerning_applied) font->doKerning(&g, option.useDesignMetrics() ? QFlag(QTextEngine::DesignMetrics) : QFlag(0)); glyph_pos += shaper_item.num_glyphs; - - initial_glyph_pos += shaper_item.initialGlyphCount; } // qDebug(" -> item: script=%d num_glyphs=%d", shaper_item.script, shaper_item.num_glyphs); -- cgit v0.12 From 64cc2368d230c6f0996a6311767bd1704b4cf322 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 14:09:21 +0200 Subject: Revert "Say hello to animation API & state machine API" This reverts commit 1a709fbe25a2446a9b311ded88aec5565258f3ac. --- demos/qtdemo/xml/examples.xml | 15 - doc/src/animation.qdoc | 368 -- doc/src/diagrams/animations-architecture.svg | 351 -- .../diagrams/programs/easingcurve/easingcurve.pro | 13 - doc/src/diagrams/programs/easingcurve/main.cpp | 90 - doc/src/examples-overview.qdoc | 8 - doc/src/examples.qdoc | 17 - doc/src/examples/eventtransitions.qdoc | 86 - doc/src/examples/factorial.qdoc | 102 - doc/src/examples/pingpong.qdoc | 107 - doc/src/examples/stickman.qdoc | 115 - doc/src/examples/tankgame.qdoc | 117 - doc/src/examples/trafficlight.qdoc | 99 - doc/src/examples/twowaybutton.qdoc | 82 - doc/src/external-resources.qdoc | 10 - doc/src/groups.qdoc | 23 - doc/src/images/animations-architecture.png | Bin 27619 -> 0 bytes doc/src/images/factorial-example.png | Bin 4032 -> 0 bytes doc/src/images/pingpong-example.png | Bin 7843 -> 0 bytes doc/src/images/qeasingcurve-cosinecurve.png | Bin 2544 -> 0 bytes doc/src/images/qeasingcurve-inback.png | Bin 2225 -> 0 bytes doc/src/images/qeasingcurve-inbounce.png | Bin 2378 -> 0 bytes doc/src/images/qeasingcurve-incirc.png | Bin 2138 -> 0 bytes doc/src/images/qeasingcurve-incubic.png | Bin 2230 -> 0 bytes doc/src/images/qeasingcurve-incurve.png | Bin 2325 -> 0 bytes doc/src/images/qeasingcurve-inelastic.png | Bin 2314 -> 0 bytes doc/src/images/qeasingcurve-inexpo.png | Bin 2183 -> 0 bytes doc/src/images/qeasingcurve-inoutback.png | Bin 2460 -> 0 bytes doc/src/images/qeasingcurve-inoutbounce.png | Bin 2522 -> 0 bytes doc/src/images/qeasingcurve-inoutcirc.png | Bin 2352 -> 0 bytes doc/src/images/qeasingcurve-inoutcubic.png | Bin 2410 -> 0 bytes doc/src/images/qeasingcurve-inoutelastic.png | Bin 2485 -> 0 bytes doc/src/images/qeasingcurve-inoutexpo.png | Bin 2383 -> 0 bytes doc/src/images/qeasingcurve-inoutquad.png | Bin 2392 -> 0 bytes doc/src/images/qeasingcurve-inoutquart.png | Bin 2331 -> 0 bytes doc/src/images/qeasingcurve-inoutquint.png | Bin 2244 -> 0 bytes doc/src/images/qeasingcurve-inoutsine.png | Bin 2405 -> 0 bytes doc/src/images/qeasingcurve-inquad.png | Bin 2283 -> 0 bytes doc/src/images/qeasingcurve-inquart.png | Bin 2261 -> 0 bytes doc/src/images/qeasingcurve-inquint.png | Bin 2178 -> 0 bytes doc/src/images/qeasingcurve-insine.png | Bin 2167 -> 0 bytes doc/src/images/qeasingcurve-linear.png | Bin 2165 -> 0 bytes doc/src/images/qeasingcurve-outback.png | Bin 2371 -> 0 bytes doc/src/images/qeasingcurve-outbounce.png | Bin 2481 -> 0 bytes doc/src/images/qeasingcurve-outcirc.png | Bin 2269 -> 0 bytes doc/src/images/qeasingcurve-outcubic.png | Bin 2336 -> 0 bytes doc/src/images/qeasingcurve-outcurve.png | Bin 2389 -> 0 bytes doc/src/images/qeasingcurve-outelastic.png | Bin 2402 -> 0 bytes doc/src/images/qeasingcurve-outexpo.png | Bin 2299 -> 0 bytes doc/src/images/qeasingcurve-outinback.png | Bin 2400 -> 0 bytes doc/src/images/qeasingcurve-outinbounce.png | Bin 2568 -> 0 bytes doc/src/images/qeasingcurve-outincirc.png | Bin 2339 -> 0 bytes doc/src/images/qeasingcurve-outincubic.png | Bin 2393 -> 0 bytes doc/src/images/qeasingcurve-outinelastic.png | Bin 2517 -> 0 bytes doc/src/images/qeasingcurve-outinexpo.png | Bin 2377 -> 0 bytes doc/src/images/qeasingcurve-outinquad.png | Bin 2380 -> 0 bytes doc/src/images/qeasingcurve-outinquart.png | Bin 2319 -> 0 bytes doc/src/images/qeasingcurve-outinquint.png | Bin 2248 -> 0 bytes doc/src/images/qeasingcurve-outinsine.png | Bin 2388 -> 0 bytes doc/src/images/qeasingcurve-outquad.png | Bin 2324 -> 0 bytes doc/src/images/qeasingcurve-outquart.png | Bin 2304 -> 0 bytes doc/src/images/qeasingcurve-outquint.png | Bin 2242 -> 0 bytes doc/src/images/qeasingcurve-outsine.png | Bin 2364 -> 0 bytes doc/src/images/qeasingcurve-sinecurve.png | Bin 2470 -> 0 bytes doc/src/images/statemachine-button-history.png | Bin 8493 -> 0 bytes doc/src/images/statemachine-button-nested.png | Bin 7051 -> 0 bytes doc/src/images/statemachine-button.png | Bin 4233 -> 0 bytes doc/src/images/statemachine-customevents.png | Bin 2544 -> 0 bytes doc/src/images/statemachine-customevents2.png | Bin 6713 -> 0 bytes doc/src/images/statemachine-finished.png | Bin 5518 -> 0 bytes doc/src/images/statemachine-nonparallel.png | Bin 5350 -> 0 bytes doc/src/images/statemachine-parallel.png | Bin 8631 -> 0 bytes doc/src/images/stickman-example.png | Bin 18867 -> 0 bytes doc/src/images/stickman-example1.png | Bin 64543 -> 0 bytes doc/src/images/stickman-example2.png | Bin 37412 -> 0 bytes doc/src/images/stickman-example3.png | Bin 23591 -> 0 bytes doc/src/images/tankgame-example.png | Bin 16089 -> 0 bytes doc/src/images/trafficlight-example.png | Bin 5325 -> 0 bytes doc/src/images/trafficlight-example1.png | Bin 3694 -> 0 bytes doc/src/images/trafficlight-example2.png | Bin 7257 -> 0 bytes doc/src/snippets/animation/sequential/icons.qrc | 6 - .../snippets/animation/sequential/icons/left.png | Bin 413 -> 0 bytes .../snippets/animation/sequential/icons/right.png | Bin 414 -> 0 bytes doc/src/snippets/animation/sequential/main.cpp | 50 - .../snippets/animation/sequential/sequential.pro | 4 - doc/src/snippets/animation/sequential/tracer.cpp | 25 - doc/src/snippets/animation/sequential/tracer.h | 23 - .../code/src_corelib_tools_qeasingcurve.cpp | 4 - doc/src/statemachine.qdoc | 645 ---- examples/animation/README | 38 - examples/animation/animatedtiles/animatedtiles.pro | 8 - examples/animation/animatedtiles/animatedtiles.qrc | 11 - .../animatedtiles/images/Time-For-Lunch-2.jpg | Bin 32471 -> 0 bytes .../animation/animatedtiles/images/centered.png | Bin 892 -> 0 bytes .../animation/animatedtiles/images/ellipse.png | Bin 10767 -> 0 bytes .../animation/animatedtiles/images/figure8.png | Bin 14050 -> 0 bytes .../animation/animatedtiles/images/kinetic.png | Bin 6776 -> 0 bytes examples/animation/animatedtiles/images/random.png | Bin 14969 -> 0 bytes examples/animation/animatedtiles/images/tile.png | Bin 16337 -> 0 bytes examples/animation/animatedtiles/main.cpp | 280 -- examples/animation/animation.pro | 16 - .../appchooser/accessories-dictionary.png | Bin 5396 -> 0 bytes examples/animation/appchooser/akregator.png | Bin 4873 -> 0 bytes examples/animation/appchooser/appchooser.pro | 8 - examples/animation/appchooser/appchooser.qrc | 8 - examples/animation/appchooser/digikam.png | Bin 3334 -> 0 bytes examples/animation/appchooser/k3b.png | Bin 8220 -> 0 bytes examples/animation/appchooser/main.cpp | 158 - examples/animation/easing/animation.h | 101 - examples/animation/easing/easing.pro | 14 - examples/animation/easing/easing.qrc | 5 - examples/animation/easing/form.ui | 201 -- examples/animation/easing/images/qt-logo.png | Bin 5149 -> 0 bytes examples/animation/easing/main.cpp | 53 - examples/animation/easing/window.cpp | 163 - examples/animation/easing/window.h | 79 - examples/animation/moveblocks/main.cpp | 296 -- examples/animation/moveblocks/moveblocks.pro | 7 - .../animation/states/accessories-dictionary.png | Bin 5396 -> 0 bytes examples/animation/states/akregator.png | Bin 4873 -> 0 bytes examples/animation/states/digikam.png | Bin 3334 -> 0 bytes examples/animation/states/help-browser.png | Bin 6984 -> 0 bytes examples/animation/states/k3b.png | Bin 8220 -> 0 bytes examples/animation/states/kchart.png | Bin 4887 -> 0 bytes examples/animation/states/main.cpp | 284 -- examples/animation/states/states.pro | 8 - examples/animation/states/states.qrc | 10 - examples/animation/stickman/animation.cpp | 193 -- examples/animation/stickman/animation.h | 83 - examples/animation/stickman/animations/chilling | Bin 6508 -> 0 bytes examples/animation/stickman/animations/dancing | Bin 2348 -> 0 bytes examples/animation/stickman/animations/dead | Bin 268 -> 0 bytes examples/animation/stickman/animations/jumping | Bin 1308 -> 0 bytes .../animation/stickman/editor/animationdialog.cpp | 192 -- .../animation/stickman/editor/animationdialog.h | 84 - examples/animation/stickman/editor/editor.pri | 2 - examples/animation/stickman/editor/mainwindow.cpp | 76 - examples/animation/stickman/editor/mainwindow.h | 58 - examples/animation/stickman/graphicsview.cpp | 81 - examples/animation/stickman/graphicsview.h | 64 - examples/animation/stickman/lifecycle.cpp | 212 -- examples/animation/stickman/lifecycle.h | 80 - examples/animation/stickman/main.cpp | 97 - examples/animation/stickman/node.cpp | 92 - examples/animation/stickman/node.h | 72 - examples/animation/stickman/stickman.cpp | 339 -- examples/animation/stickman/stickman.h | 103 - examples/animation/stickman/stickman.pro | 19 - examples/animation/sub-attaq/animationmanager.cpp | 93 - examples/animation/sub-attaq/animationmanager.h | 70 - examples/animation/sub-attaq/boat.cpp | 318 -- examples/animation/sub-attaq/boat.h | 102 - examples/animation/sub-attaq/boat_p.h | 256 -- examples/animation/sub-attaq/bomb.cpp | 124 - examples/animation/sub-attaq/bomb.h | 76 - .../sub-attaq/custompropertyanimation.cpp | 108 - .../animation/sub-attaq/custompropertyanimation.h | 114 - examples/animation/sub-attaq/data.xml | 15 - examples/animation/sub-attaq/graphicsscene.cpp | 374 --- examples/animation/sub-attaq/graphicsscene.h | 131 - examples/animation/sub-attaq/main.cpp | 57 - examples/animation/sub-attaq/mainwindow.cpp | 92 - examples/animation/sub-attaq/mainwindow.h | 64 - .../animation/sub-attaq/pics/big/background.png | Bin 48858 -> 0 bytes examples/animation/sub-attaq/pics/big/boat.png | Bin 5198 -> 0 bytes examples/animation/sub-attaq/pics/big/bomb.png | Bin 760 -> 0 bytes .../sub-attaq/pics/big/explosion/boat/step1.png | Bin 5760 -> 0 bytes .../sub-attaq/pics/big/explosion/boat/step2.png | Bin 9976 -> 0 bytes .../sub-attaq/pics/big/explosion/boat/step3.png | Bin 12411 -> 0 bytes .../sub-attaq/pics/big/explosion/boat/step4.png | Bin 15438 -> 0 bytes .../pics/big/explosion/submarine/step1.png | Bin 3354 -> 0 bytes .../pics/big/explosion/submarine/step2.png | Bin 6205 -> 0 bytes .../pics/big/explosion/submarine/step3.png | Bin 6678 -> 0 bytes .../pics/big/explosion/submarine/step4.png | Bin 6666 -> 0 bytes .../animation/sub-attaq/pics/big/submarine.png | Bin 3202 -> 0 bytes examples/animation/sub-attaq/pics/big/surface.png | Bin 575 -> 0 bytes examples/animation/sub-attaq/pics/big/torpedo.png | Bin 951 -> 0 bytes .../sub-attaq/pics/scalable/background-n810.svg | 171 - .../sub-attaq/pics/scalable/background.svg | 171 - .../animation/sub-attaq/pics/scalable/boat.svg | 279 -- .../animation/sub-attaq/pics/scalable/bomb.svg | 138 - .../animation/sub-attaq/pics/scalable/sand.svg | 103 - examples/animation/sub-attaq/pics/scalable/see.svg | 44 - examples/animation/sub-attaq/pics/scalable/sky.svg | 45 - .../sub-attaq/pics/scalable/sub-attaq.svg | 1473 -------- .../sub-attaq/pics/scalable/submarine.svg | 214 -- .../animation/sub-attaq/pics/scalable/surface.svg | 49 - .../animation/sub-attaq/pics/scalable/torpedo.svg | 127 - .../animation/sub-attaq/pics/small/background.png | Bin 34634 -> 0 bytes examples/animation/sub-attaq/pics/small/boat.png | Bin 2394 -> 0 bytes examples/animation/sub-attaq/pics/small/bomb.png | Bin 760 -> 0 bytes .../animation/sub-attaq/pics/small/submarine.png | Bin 1338 -> 0 bytes .../animation/sub-attaq/pics/small/surface.png | Bin 502 -> 0 bytes .../animation/sub-attaq/pics/small/torpedo.png | Bin 951 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-a.png | Bin 5972 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-a2.png | Bin 5969 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-b.png | Bin 6869 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-dash.png | Bin 2255 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-excl.png | Bin 2740 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-q.png | Bin 7016 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-s.png | Bin 5817 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-t.png | Bin 3717 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-t2.png | Bin 3688 -> 0 bytes .../animation/sub-attaq/pics/welcome/logo-u.png | Bin 5374 -> 0 bytes examples/animation/sub-attaq/pixmapitem.cpp | 59 - examples/animation/sub-attaq/pixmapitem.h | 63 - examples/animation/sub-attaq/progressitem.cpp | 67 - examples/animation/sub-attaq/progressitem.h | 61 - examples/animation/sub-attaq/qanimationstate.cpp | 171 - examples/animation/sub-attaq/qanimationstate.h | 92 - examples/animation/sub-attaq/states.cpp | 325 -- examples/animation/sub-attaq/states.h | 180 - examples/animation/sub-attaq/sub-attaq.pro | 36 - examples/animation/sub-attaq/subattaq.qrc | 38 - examples/animation/sub-attaq/submarine.cpp | 211 -- examples/animation/sub-attaq/submarine.h | 92 - examples/animation/sub-attaq/submarine_p.h | 139 - examples/animation/sub-attaq/torpedo.cpp | 120 - examples/animation/sub-attaq/torpedo.h | 76 - examples/examples.pro | 2 - examples/statemachine/README | 36 - .../eventtransitions/eventtransitions.pro | 7 - examples/statemachine/eventtransitions/main.cpp | 116 - examples/statemachine/factorial/factorial.pro | 11 - examples/statemachine/factorial/main.cpp | 182 - examples/statemachine/pingpong/main.cpp | 145 - examples/statemachine/pingpong/pingpong.pro | 11 - examples/statemachine/statemachine.pro | 15 - examples/statemachine/tankgame/gameitem.cpp | 129 - examples/statemachine/tankgame/gameitem.h | 66 - .../statemachine/tankgame/gameovertransition.cpp | 80 - .../statemachine/tankgame/gameovertransition.h | 63 - examples/statemachine/tankgame/main.cpp | 53 - examples/statemachine/tankgame/mainwindow.cpp | 342 -- examples/statemachine/tankgame/mainwindow.h | 93 - examples/statemachine/tankgame/plugin.h | 62 - examples/statemachine/tankgame/rocketitem.cpp | 101 - examples/statemachine/tankgame/rocketitem.h | 66 - examples/statemachine/tankgame/tankgame.pro | 19 - examples/statemachine/tankgame/tankitem.cpp | 302 -- examples/statemachine/tankgame/tankitem.h | 109 - .../tankgameplugins/random_ai/random_ai.pro | 13 - .../tankgameplugins/random_ai/random_ai_plugin.cpp | 79 - .../tankgameplugins/random_ai/random_ai_plugin.h | 105 - .../tankgameplugins/seek_ai/seek_ai.cpp | 89 - .../statemachine/tankgameplugins/seek_ai/seek_ai.h | 249 -- .../tankgameplugins/seek_ai/seek_ai.pro | 13 - .../tankgameplugins/spin_ai/spin_ai.cpp | 70 - .../statemachine/tankgameplugins/spin_ai/spin_ai.h | 92 - .../tankgameplugins/spin_ai/spin_ai.pro | 13 - .../spin_ai_with_error/spin_ai_with_error.cpp | 70 - .../spin_ai_with_error/spin_ai_with_error.h | 92 - .../spin_ai_with_error/spin_ai_with_error.pro | 13 - .../tankgameplugins/tankgameplugins.pro | 11 - examples/statemachine/trafficlight/main.cpp | 190 -- .../statemachine/trafficlight/trafficlight.pro | 7 - examples/statemachine/twowaybutton/main.cpp | 86 - .../statemachine/twowaybutton/twowaybutton.pro | 7 - mkspecs/win32-icc/qmake.conf | 2 +- src/3rdparty/easing/easing.cpp | 670 ---- src/3rdparty/easing/legal.qdoc | 35 - src/corelib/animation/animation.pri | 25 - src/corelib/animation/qabstractanimation.cpp | 759 ----- src/corelib/animation/qabstractanimation.h | 137 - src/corelib/animation/qabstractanimation_p.h | 136 - src/corelib/animation/qanimationgroup.cpp | 309 -- src/corelib/animation/qanimationgroup.h | 88 - src/corelib/animation/qanimationgroup_p.h | 79 - src/corelib/animation/qparallelanimationgroup.cpp | 316 -- src/corelib/animation/qparallelanimationgroup.h | 86 - src/corelib/animation/qparallelanimationgroup_p.h | 85 - src/corelib/animation/qpauseanimation.cpp | 154 - src/corelib/animation/qpauseanimation.h | 84 - src/corelib/animation/qpropertyanimation.cpp | 316 -- src/corelib/animation/qpropertyanimation.h | 90 - src/corelib/animation/qpropertyanimation_p.h | 89 - .../animation/qsequentialanimationgroup.cpp | 594 ---- src/corelib/animation/qsequentialanimationgroup.h | 96 - .../animation/qsequentialanimationgroup_p.h | 111 - src/corelib/animation/qvariantanimation.cpp | 644 ---- src/corelib/animation/qvariantanimation.h | 130 - src/corelib/animation/qvariantanimation_p.h | 130 - src/corelib/corelib.pro | 2 - src/corelib/kernel/kernel.pri | 8 +- src/corelib/kernel/qcoreevent.cpp | 2 - src/corelib/kernel/qcoreevent.h | 8 +- src/corelib/statemachine/qabstractstate.cpp | 202 -- src/corelib/statemachine/qabstractstate.h | 90 - src/corelib/statemachine/qabstractstate_p.h | 84 - src/corelib/statemachine/qabstracttransition.cpp | 342 -- src/corelib/statemachine/qabstracttransition.h | 111 - src/corelib/statemachine/qabstracttransition_p.h | 91 - src/corelib/statemachine/qeventtransition.cpp | 282 -- src/corelib/statemachine/qeventtransition.h | 96 - src/corelib/statemachine/qeventtransition_p.h | 78 - src/corelib/statemachine/qfinalstate.cpp | 134 - src/corelib/statemachine/qfinalstate.h | 76 - src/corelib/statemachine/qhistorystate.cpp | 223 -- src/corelib/statemachine/qhistorystate.h | 91 - src/corelib/statemachine/qhistorystate_p.h | 79 - src/corelib/statemachine/qsignalevent.h | 77 - src/corelib/statemachine/qsignaleventgenerator_p.h | 78 - src/corelib/statemachine/qsignaltransition.cpp | 257 -- src/corelib/statemachine/qsignaltransition.h | 89 - src/corelib/statemachine/qsignaltransition_p.h | 78 - src/corelib/statemachine/qstate.cpp | 497 --- src/corelib/statemachine/qstate.h | 113 - src/corelib/statemachine/qstate_p.h | 108 - src/corelib/statemachine/qstatemachine.cpp | 2216 ------------ src/corelib/statemachine/qstatemachine.h | 166 - src/corelib/statemachine/qstatemachine_p.h | 217 -- src/corelib/statemachine/qwrappedevent.h | 76 - src/corelib/statemachine/statemachine.pri | 30 - src/corelib/tools/qeasingcurve.cpp | 846 ----- src/corelib/tools/qeasingcurve.h | 114 - src/corelib/tools/qtimeline.cpp | 114 +- src/corelib/tools/qtimeline.h | 5 - src/corelib/tools/tools.pri | 2 - src/gui/animation/animation.pri | 3 - src/gui/animation/qguivariantanimation.cpp | 75 - src/gui/graphicsview/qgraphicsitem_p.h | 12 +- src/gui/graphicsview/qgraphicsproxywidget.cpp | 2 - src/gui/graphicsview/qgraphicsproxywidget.h | 2 - src/gui/gui.pro | 2 - src/gui/kernel/qapplication.cpp | 6 - src/gui/painting/qdrawhelper.cpp | 8 +- src/gui/statemachine/qbasickeyeventtransition.cpp | 203 -- src/gui/statemachine/qbasickeyeventtransition_p.h | 93 - .../statemachine/qbasicmouseeventtransition.cpp | 208 -- .../statemachine/qbasicmouseeventtransition_p.h | 98 - src/gui/statemachine/qguistatemachine.cpp | 559 --- src/gui/statemachine/qkeyeventtransition.cpp | 186 - src/gui/statemachine/qkeyeventtransition.h | 87 - src/gui/statemachine/qmouseeventtransition.cpp | 216 -- src/gui/statemachine/qmouseeventtransition.h | 92 - src/gui/statemachine/statemachine.pri | 13 - tests/auto/auto.pro | 6 - tests/auto/qanimationgroup/qanimationgroup.pro | 5 - tests/auto/qanimationgroup/tst_qanimationgroup.cpp | 413 --- tests/auto/qeasingcurve/qeasingcurve.pro | 3 - tests/auto/qeasingcurve/tst_qeasingcurve.cpp | 487 --- tests/auto/qmake/testdata/bundle-spaces/some-file | 6 - .../qparallelanimationgroup.pro | 5 - .../tst_qparallelanimationgroup.cpp | 834 ----- .../auto/qpropertyanimation/qpropertyanimation.pro | 5 - .../qpropertyanimation/tst_qpropertyanimation.cpp | 919 ----- .../qsequentialanimationgroup.pro | 5 - .../tst_qsequentialanimationgroup.cpp | 1649 --------- tests/auto/qstate/qstate.pro | 5 - tests/auto/qstate/tst_qstate.cpp | 340 -- tests/auto/qstatemachine/qstatemachine.pro | 4 - tests/auto/qstatemachine/tst_qstatemachine.cpp | 3548 -------------------- tests/benchmarks/benchmarks.pro | 1 - tests/benchmarks/qanimation/dummyanimation.cpp | 20 - tests/benchmarks/qanimation/dummyanimation.h | 19 - tests/benchmarks/qanimation/dummyobject.cpp | 25 - tests/benchmarks/qanimation/dummyobject.h | 23 - tests/benchmarks/qanimation/main.cpp | 150 - tests/benchmarks/qanimation/qanimation.pro | 18 - tests/benchmarks/qanimation/rectanimation.cpp | 58 - tests/benchmarks/qanimation/rectanimation.h | 30 - tests/benchmarks/qvariant/qvariant.pro | 1 + tests/benchmarks/qvariant/tst_qvariant.cpp | 115 +- 363 files changed, 130 insertions(+), 38378 deletions(-) delete mode 100644 doc/src/animation.qdoc delete mode 100644 doc/src/diagrams/animations-architecture.svg delete mode 100644 doc/src/diagrams/programs/easingcurve/easingcurve.pro delete mode 100644 doc/src/diagrams/programs/easingcurve/main.cpp delete mode 100644 doc/src/examples/eventtransitions.qdoc delete mode 100644 doc/src/examples/factorial.qdoc delete mode 100644 doc/src/examples/pingpong.qdoc delete mode 100644 doc/src/examples/stickman.qdoc delete mode 100644 doc/src/examples/tankgame.qdoc delete mode 100644 doc/src/examples/trafficlight.qdoc delete mode 100644 doc/src/examples/twowaybutton.qdoc delete mode 100644 doc/src/images/animations-architecture.png delete mode 100644 doc/src/images/factorial-example.png delete mode 100644 doc/src/images/pingpong-example.png delete mode 100644 doc/src/images/qeasingcurve-cosinecurve.png delete mode 100644 doc/src/images/qeasingcurve-inback.png delete mode 100644 doc/src/images/qeasingcurve-inbounce.png delete mode 100644 doc/src/images/qeasingcurve-incirc.png delete mode 100644 doc/src/images/qeasingcurve-incubic.png delete mode 100644 doc/src/images/qeasingcurve-incurve.png delete mode 100644 doc/src/images/qeasingcurve-inelastic.png delete mode 100644 doc/src/images/qeasingcurve-inexpo.png delete mode 100644 doc/src/images/qeasingcurve-inoutback.png delete mode 100644 doc/src/images/qeasingcurve-inoutbounce.png delete mode 100644 doc/src/images/qeasingcurve-inoutcirc.png delete mode 100644 doc/src/images/qeasingcurve-inoutcubic.png delete mode 100644 doc/src/images/qeasingcurve-inoutelastic.png delete mode 100644 doc/src/images/qeasingcurve-inoutexpo.png delete mode 100644 doc/src/images/qeasingcurve-inoutquad.png delete mode 100644 doc/src/images/qeasingcurve-inoutquart.png delete mode 100644 doc/src/images/qeasingcurve-inoutquint.png delete mode 100644 doc/src/images/qeasingcurve-inoutsine.png delete mode 100644 doc/src/images/qeasingcurve-inquad.png delete mode 100644 doc/src/images/qeasingcurve-inquart.png delete mode 100644 doc/src/images/qeasingcurve-inquint.png delete mode 100644 doc/src/images/qeasingcurve-insine.png delete mode 100644 doc/src/images/qeasingcurve-linear.png delete mode 100644 doc/src/images/qeasingcurve-outback.png delete mode 100644 doc/src/images/qeasingcurve-outbounce.png delete mode 100644 doc/src/images/qeasingcurve-outcirc.png delete mode 100644 doc/src/images/qeasingcurve-outcubic.png delete mode 100644 doc/src/images/qeasingcurve-outcurve.png delete mode 100644 doc/src/images/qeasingcurve-outelastic.png delete mode 100644 doc/src/images/qeasingcurve-outexpo.png delete mode 100644 doc/src/images/qeasingcurve-outinback.png delete mode 100644 doc/src/images/qeasingcurve-outinbounce.png delete mode 100644 doc/src/images/qeasingcurve-outincirc.png delete mode 100644 doc/src/images/qeasingcurve-outincubic.png delete mode 100644 doc/src/images/qeasingcurve-outinelastic.png delete mode 100644 doc/src/images/qeasingcurve-outinexpo.png delete mode 100644 doc/src/images/qeasingcurve-outinquad.png delete mode 100644 doc/src/images/qeasingcurve-outinquart.png delete mode 100644 doc/src/images/qeasingcurve-outinquint.png delete mode 100644 doc/src/images/qeasingcurve-outinsine.png delete mode 100644 doc/src/images/qeasingcurve-outquad.png delete mode 100644 doc/src/images/qeasingcurve-outquart.png delete mode 100644 doc/src/images/qeasingcurve-outquint.png delete mode 100644 doc/src/images/qeasingcurve-outsine.png delete mode 100644 doc/src/images/qeasingcurve-sinecurve.png delete mode 100644 doc/src/images/statemachine-button-history.png delete mode 100644 doc/src/images/statemachine-button-nested.png delete mode 100644 doc/src/images/statemachine-button.png delete mode 100644 doc/src/images/statemachine-customevents.png delete mode 100644 doc/src/images/statemachine-customevents2.png delete mode 100644 doc/src/images/statemachine-finished.png delete mode 100644 doc/src/images/statemachine-nonparallel.png delete mode 100644 doc/src/images/statemachine-parallel.png delete mode 100644 doc/src/images/stickman-example.png delete mode 100644 doc/src/images/stickman-example1.png delete mode 100644 doc/src/images/stickman-example2.png delete mode 100644 doc/src/images/stickman-example3.png delete mode 100644 doc/src/images/tankgame-example.png delete mode 100644 doc/src/images/trafficlight-example.png delete mode 100644 doc/src/images/trafficlight-example1.png delete mode 100644 doc/src/images/trafficlight-example2.png delete mode 100644 doc/src/snippets/animation/sequential/icons.qrc delete mode 100644 doc/src/snippets/animation/sequential/icons/left.png delete mode 100644 doc/src/snippets/animation/sequential/icons/right.png delete mode 100644 doc/src/snippets/animation/sequential/main.cpp delete mode 100644 doc/src/snippets/animation/sequential/sequential.pro delete mode 100644 doc/src/snippets/animation/sequential/tracer.cpp delete mode 100644 doc/src/snippets/animation/sequential/tracer.h delete mode 100644 doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp delete mode 100644 doc/src/statemachine.qdoc delete mode 100644 examples/animation/README delete mode 100644 examples/animation/animatedtiles/animatedtiles.pro delete mode 100644 examples/animation/animatedtiles/animatedtiles.qrc delete mode 100644 examples/animation/animatedtiles/images/Time-For-Lunch-2.jpg delete mode 100644 examples/animation/animatedtiles/images/centered.png delete mode 100644 examples/animation/animatedtiles/images/ellipse.png delete mode 100644 examples/animation/animatedtiles/images/figure8.png delete mode 100644 examples/animation/animatedtiles/images/kinetic.png delete mode 100644 examples/animation/animatedtiles/images/random.png delete mode 100644 examples/animation/animatedtiles/images/tile.png delete mode 100644 examples/animation/animatedtiles/main.cpp delete mode 100644 examples/animation/animation.pro delete mode 100644 examples/animation/appchooser/accessories-dictionary.png delete mode 100644 examples/animation/appchooser/akregator.png delete mode 100644 examples/animation/appchooser/appchooser.pro delete mode 100644 examples/animation/appchooser/appchooser.qrc delete mode 100644 examples/animation/appchooser/digikam.png delete mode 100644 examples/animation/appchooser/k3b.png delete mode 100644 examples/animation/appchooser/main.cpp delete mode 100644 examples/animation/easing/animation.h delete mode 100644 examples/animation/easing/easing.pro delete mode 100644 examples/animation/easing/easing.qrc delete mode 100644 examples/animation/easing/form.ui delete mode 100644 examples/animation/easing/images/qt-logo.png delete mode 100644 examples/animation/easing/main.cpp delete mode 100644 examples/animation/easing/window.cpp delete mode 100644 examples/animation/easing/window.h delete mode 100644 examples/animation/moveblocks/main.cpp delete mode 100644 examples/animation/moveblocks/moveblocks.pro delete mode 100644 examples/animation/states/accessories-dictionary.png delete mode 100644 examples/animation/states/akregator.png delete mode 100644 examples/animation/states/digikam.png delete mode 100644 examples/animation/states/help-browser.png delete mode 100644 examples/animation/states/k3b.png delete mode 100644 examples/animation/states/kchart.png delete mode 100644 examples/animation/states/main.cpp delete mode 100644 examples/animation/states/states.pro delete mode 100644 examples/animation/states/states.qrc delete mode 100644 examples/animation/stickman/animation.cpp delete mode 100644 examples/animation/stickman/animation.h delete mode 100644 examples/animation/stickman/animations/chilling delete mode 100644 examples/animation/stickman/animations/dancing delete mode 100644 examples/animation/stickman/animations/dead delete mode 100644 examples/animation/stickman/animations/jumping delete mode 100644 examples/animation/stickman/editor/animationdialog.cpp delete mode 100644 examples/animation/stickman/editor/animationdialog.h delete mode 100644 examples/animation/stickman/editor/editor.pri delete mode 100644 examples/animation/stickman/editor/mainwindow.cpp delete mode 100644 examples/animation/stickman/editor/mainwindow.h delete mode 100644 examples/animation/stickman/graphicsview.cpp delete mode 100644 examples/animation/stickman/graphicsview.h delete mode 100644 examples/animation/stickman/lifecycle.cpp delete mode 100644 examples/animation/stickman/lifecycle.h delete mode 100644 examples/animation/stickman/main.cpp delete mode 100644 examples/animation/stickman/node.cpp delete mode 100644 examples/animation/stickman/node.h delete mode 100644 examples/animation/stickman/stickman.cpp delete mode 100644 examples/animation/stickman/stickman.h delete mode 100644 examples/animation/stickman/stickman.pro delete mode 100644 examples/animation/sub-attaq/animationmanager.cpp delete mode 100644 examples/animation/sub-attaq/animationmanager.h delete mode 100644 examples/animation/sub-attaq/boat.cpp delete mode 100644 examples/animation/sub-attaq/boat.h delete mode 100644 examples/animation/sub-attaq/boat_p.h delete mode 100644 examples/animation/sub-attaq/bomb.cpp delete mode 100644 examples/animation/sub-attaq/bomb.h delete mode 100644 examples/animation/sub-attaq/custompropertyanimation.cpp delete mode 100644 examples/animation/sub-attaq/custompropertyanimation.h delete mode 100644 examples/animation/sub-attaq/data.xml delete mode 100644 examples/animation/sub-attaq/graphicsscene.cpp delete mode 100644 examples/animation/sub-attaq/graphicsscene.h delete mode 100644 examples/animation/sub-attaq/main.cpp delete mode 100644 examples/animation/sub-attaq/mainwindow.cpp delete mode 100644 examples/animation/sub-attaq/mainwindow.h delete mode 100644 examples/animation/sub-attaq/pics/big/background.png delete mode 100644 examples/animation/sub-attaq/pics/big/boat.png delete mode 100644 examples/animation/sub-attaq/pics/big/bomb.png delete mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step1.png delete mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step2.png delete mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step3.png delete mode 100644 examples/animation/sub-attaq/pics/big/explosion/boat/step4.png delete mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png delete mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png delete mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png delete mode 100644 examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png delete mode 100644 examples/animation/sub-attaq/pics/big/submarine.png delete mode 100644 examples/animation/sub-attaq/pics/big/surface.png delete mode 100644 examples/animation/sub-attaq/pics/big/torpedo.png delete mode 100644 examples/animation/sub-attaq/pics/scalable/background-n810.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/background.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/boat.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/bomb.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/sand.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/see.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/sky.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/sub-attaq.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/submarine.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/surface.svg delete mode 100644 examples/animation/sub-attaq/pics/scalable/torpedo.svg delete mode 100644 examples/animation/sub-attaq/pics/small/background.png delete mode 100644 examples/animation/sub-attaq/pics/small/boat.png delete mode 100644 examples/animation/sub-attaq/pics/small/bomb.png delete mode 100644 examples/animation/sub-attaq/pics/small/submarine.png delete mode 100644 examples/animation/sub-attaq/pics/small/surface.png delete mode 100644 examples/animation/sub-attaq/pics/small/torpedo.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-a.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-a2.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-b.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-dash.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-excl.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-q.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-s.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-t.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-t2.png delete mode 100644 examples/animation/sub-attaq/pics/welcome/logo-u.png delete mode 100644 examples/animation/sub-attaq/pixmapitem.cpp delete mode 100644 examples/animation/sub-attaq/pixmapitem.h delete mode 100644 examples/animation/sub-attaq/progressitem.cpp delete mode 100644 examples/animation/sub-attaq/progressitem.h delete mode 100644 examples/animation/sub-attaq/qanimationstate.cpp delete mode 100644 examples/animation/sub-attaq/qanimationstate.h delete mode 100644 examples/animation/sub-attaq/states.cpp delete mode 100644 examples/animation/sub-attaq/states.h delete mode 100644 examples/animation/sub-attaq/sub-attaq.pro delete mode 100644 examples/animation/sub-attaq/subattaq.qrc delete mode 100644 examples/animation/sub-attaq/submarine.cpp delete mode 100644 examples/animation/sub-attaq/submarine.h delete mode 100644 examples/animation/sub-attaq/submarine_p.h delete mode 100644 examples/animation/sub-attaq/torpedo.cpp delete mode 100644 examples/animation/sub-attaq/torpedo.h delete mode 100644 examples/statemachine/README delete mode 100644 examples/statemachine/eventtransitions/eventtransitions.pro delete mode 100644 examples/statemachine/eventtransitions/main.cpp delete mode 100644 examples/statemachine/factorial/factorial.pro delete mode 100644 examples/statemachine/factorial/main.cpp delete mode 100644 examples/statemachine/pingpong/main.cpp delete mode 100644 examples/statemachine/pingpong/pingpong.pro delete mode 100644 examples/statemachine/statemachine.pro delete mode 100644 examples/statemachine/tankgame/gameitem.cpp delete mode 100644 examples/statemachine/tankgame/gameitem.h delete mode 100644 examples/statemachine/tankgame/gameovertransition.cpp delete mode 100644 examples/statemachine/tankgame/gameovertransition.h delete mode 100644 examples/statemachine/tankgame/main.cpp delete mode 100644 examples/statemachine/tankgame/mainwindow.cpp delete mode 100644 examples/statemachine/tankgame/mainwindow.h delete mode 100644 examples/statemachine/tankgame/plugin.h delete mode 100644 examples/statemachine/tankgame/rocketitem.cpp delete mode 100644 examples/statemachine/tankgame/rocketitem.h delete mode 100644 examples/statemachine/tankgame/tankgame.pro delete mode 100644 examples/statemachine/tankgame/tankitem.cpp delete mode 100644 examples/statemachine/tankgame/tankitem.h delete mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai.pro delete mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp delete mode 100644 examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h delete mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp delete mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.h delete mode 100644 examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro delete mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp delete mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.h delete mode 100644 examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro delete mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp delete mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h delete mode 100644 examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro delete mode 100644 examples/statemachine/tankgameplugins/tankgameplugins.pro delete mode 100644 examples/statemachine/trafficlight/main.cpp delete mode 100644 examples/statemachine/trafficlight/trafficlight.pro delete mode 100644 examples/statemachine/twowaybutton/main.cpp delete mode 100644 examples/statemachine/twowaybutton/twowaybutton.pro delete mode 100644 src/3rdparty/easing/easing.cpp delete mode 100644 src/3rdparty/easing/legal.qdoc delete mode 100644 src/corelib/animation/animation.pri delete mode 100644 src/corelib/animation/qabstractanimation.cpp delete mode 100644 src/corelib/animation/qabstractanimation.h delete mode 100644 src/corelib/animation/qabstractanimation_p.h delete mode 100644 src/corelib/animation/qanimationgroup.cpp delete mode 100644 src/corelib/animation/qanimationgroup.h delete mode 100644 src/corelib/animation/qanimationgroup_p.h delete mode 100644 src/corelib/animation/qparallelanimationgroup.cpp delete mode 100644 src/corelib/animation/qparallelanimationgroup.h delete mode 100644 src/corelib/animation/qparallelanimationgroup_p.h delete mode 100644 src/corelib/animation/qpauseanimation.cpp delete mode 100644 src/corelib/animation/qpauseanimation.h delete mode 100644 src/corelib/animation/qpropertyanimation.cpp delete mode 100644 src/corelib/animation/qpropertyanimation.h delete mode 100644 src/corelib/animation/qpropertyanimation_p.h delete mode 100644 src/corelib/animation/qsequentialanimationgroup.cpp delete mode 100644 src/corelib/animation/qsequentialanimationgroup.h delete mode 100644 src/corelib/animation/qsequentialanimationgroup_p.h delete mode 100644 src/corelib/animation/qvariantanimation.cpp delete mode 100644 src/corelib/animation/qvariantanimation.h delete mode 100644 src/corelib/animation/qvariantanimation_p.h delete mode 100644 src/corelib/statemachine/qabstractstate.cpp delete mode 100644 src/corelib/statemachine/qabstractstate.h delete mode 100644 src/corelib/statemachine/qabstractstate_p.h delete mode 100644 src/corelib/statemachine/qabstracttransition.cpp delete mode 100644 src/corelib/statemachine/qabstracttransition.h delete mode 100644 src/corelib/statemachine/qabstracttransition_p.h delete mode 100644 src/corelib/statemachine/qeventtransition.cpp delete mode 100644 src/corelib/statemachine/qeventtransition.h delete mode 100644 src/corelib/statemachine/qeventtransition_p.h delete mode 100644 src/corelib/statemachine/qfinalstate.cpp delete mode 100644 src/corelib/statemachine/qfinalstate.h delete mode 100644 src/corelib/statemachine/qhistorystate.cpp delete mode 100644 src/corelib/statemachine/qhistorystate.h delete mode 100644 src/corelib/statemachine/qhistorystate_p.h delete mode 100644 src/corelib/statemachine/qsignalevent.h delete mode 100644 src/corelib/statemachine/qsignaleventgenerator_p.h delete mode 100644 src/corelib/statemachine/qsignaltransition.cpp delete mode 100644 src/corelib/statemachine/qsignaltransition.h delete mode 100644 src/corelib/statemachine/qsignaltransition_p.h delete mode 100644 src/corelib/statemachine/qstate.cpp delete mode 100644 src/corelib/statemachine/qstate.h delete mode 100644 src/corelib/statemachine/qstate_p.h delete mode 100644 src/corelib/statemachine/qstatemachine.cpp delete mode 100644 src/corelib/statemachine/qstatemachine.h delete mode 100644 src/corelib/statemachine/qstatemachine_p.h delete mode 100644 src/corelib/statemachine/qwrappedevent.h delete mode 100644 src/corelib/statemachine/statemachine.pri delete mode 100644 src/corelib/tools/qeasingcurve.cpp delete mode 100644 src/corelib/tools/qeasingcurve.h delete mode 100644 src/gui/animation/animation.pri delete mode 100644 src/gui/animation/qguivariantanimation.cpp delete mode 100644 src/gui/statemachine/qbasickeyeventtransition.cpp delete mode 100644 src/gui/statemachine/qbasickeyeventtransition_p.h delete mode 100644 src/gui/statemachine/qbasicmouseeventtransition.cpp delete mode 100644 src/gui/statemachine/qbasicmouseeventtransition_p.h delete mode 100644 src/gui/statemachine/qguistatemachine.cpp delete mode 100644 src/gui/statemachine/qkeyeventtransition.cpp delete mode 100644 src/gui/statemachine/qkeyeventtransition.h delete mode 100644 src/gui/statemachine/qmouseeventtransition.cpp delete mode 100644 src/gui/statemachine/qmouseeventtransition.h delete mode 100644 src/gui/statemachine/statemachine.pri delete mode 100644 tests/auto/qanimationgroup/qanimationgroup.pro delete mode 100644 tests/auto/qanimationgroup/tst_qanimationgroup.cpp delete mode 100644 tests/auto/qeasingcurve/qeasingcurve.pro delete mode 100644 tests/auto/qeasingcurve/tst_qeasingcurve.cpp delete mode 100644 tests/auto/qparallelanimationgroup/qparallelanimationgroup.pro delete mode 100644 tests/auto/qparallelanimationgroup/tst_qparallelanimationgroup.cpp delete mode 100644 tests/auto/qpropertyanimation/qpropertyanimation.pro delete mode 100644 tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp delete mode 100644 tests/auto/qsequentialanimationgroup/qsequentialanimationgroup.pro delete mode 100644 tests/auto/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp delete mode 100644 tests/auto/qstate/qstate.pro delete mode 100644 tests/auto/qstate/tst_qstate.cpp delete mode 100644 tests/auto/qstatemachine/qstatemachine.pro delete mode 100644 tests/auto/qstatemachine/tst_qstatemachine.cpp delete mode 100644 tests/benchmarks/qanimation/dummyanimation.cpp delete mode 100644 tests/benchmarks/qanimation/dummyanimation.h delete mode 100644 tests/benchmarks/qanimation/dummyobject.cpp delete mode 100644 tests/benchmarks/qanimation/dummyobject.h delete mode 100644 tests/benchmarks/qanimation/main.cpp delete mode 100644 tests/benchmarks/qanimation/qanimation.pro delete mode 100644 tests/benchmarks/qanimation/rectanimation.cpp delete mode 100644 tests/benchmarks/qanimation/rectanimation.h diff --git a/demos/qtdemo/xml/examples.xml b/demos/qtdemo/xml/examples.xml index 2560848..96a3e80 100644 --- a/demos/qtdemo/xml/examples.xml +++ b/demos/qtdemo/xml/examples.xml @@ -19,15 +19,6 @@ - - - - - - - - - @@ -176,12 +167,6 @@ - - - - - - diff --git a/doc/src/animation.qdoc b/doc/src/animation.qdoc deleted file mode 100644 index b4e603c..0000000 --- a/doc/src/animation.qdoc +++ /dev/null @@ -1,368 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page animation-overview.html - \title The Animation Framework - \ingroup architecture - \ingroup animation - \brief An overview of the Animation Framework - - \keyword Animation - - The animation framework is part of the Kinetic project, and aims - to provide an easy way for creating animated and smooth GUI's. By - animating Qt properties, the framework provides great freedom for - animating widgets and other \l{QObject}s. The framework can also - be used with the Graphics View framework. - - In this overview, we explain the basics of its architecture. We - also show examples of the most common techniques that the - framework allows for animating QObjects and graphics items. - - \tableofcontents - - \section1 The Animation Architecture - - We will in this section take a high-level look at the animation - framework's architecture and how it is used to animate Qt - properties. The following diagram shows the most important classes - in the animation framework. - - \image animations-architecture.png - - The animation framework foundation consists of the base class - QAbstractAnimation, and its two subclasses QVariantAnimation and - QAnimationGroup. QAbstractAnimation is the ancestor of all - animations. It represents basic properties that are common for all - animations in the framework; notably, the ability to start, stop, - and pause an animation. It is also receives the time change - notifications. - - The animation framework further provides the QPropertyAnimation - class, which inherits QVariantAnimation and performs animation of - a Qt property, which is part of Qt's \l{Meta-Object - System}{meta-object system}. The class performs an interpolation - over the property using an easing curve. So when you want to - animate a value, you can declare it as a property and make your - class a QObject. Note that this gives us great freedom in - animating already existing widgets and other \l{QObject}s. - - Complex animations can be constructed by building a tree structure - of \l{QAbstractAnimation}s. The tree is built by using - \l{QAnimationGroup}s, which function as containers for other - animations. Note also that the groups are subclasses of - QAbstractAnimation, so groups can themselves contain other groups. - - The animation framework can be used on its own, but is also - designed to be part of the state machine framework (See the - \l{The State Machine Framework}{state machine framework} for an - introduction to the Qt state machine). The state machine provides - a special state that can play an animation. A QState can also set - properties when the state is entered or exited, and this special - animation state will interpolate between these values when given a - QPropertyAnimation. We will look more closely at this later. - - Behind the scenes, the animations are controlled by a global - timer, which sends \l{QAbstractAnimation::updateCurrentTime()}{updates} to - all animations that are playing. - - For detailed descriptions of the classes' function and roles in - the framework, please look up their class descriptions. - - \section1 Animating Qt Properties - - As mentioned in the previous section, the QPropertyAnimation class - can interpolate over Qt properties. It is this class that should - be used for animation of values; in fact, its superclass, - QVariantAnimation, is an abstract class, and cannot be used - directly. - - A major reason we chose to animate Qt properties is that it - presents us with freedom to animate already existing classes in - the Qt API. Notably, the QWidget class (which we can also embed in - a QGraphicsView) has properties for its bounds, colors, etc. - Let's look at a small example: - - \code - QPushButton button("Animated Button"); - button.show(); - - QPropertyAnimation animation(&button, "geometry"); - animation.setDuration(10000); - animation.setStartValue(QRect(0, 0, 100, 30)); - animation.setEndValue(QRect(250, 250, 100, 30)); - - animation.start(); - \endcode - - This code will move \c button from the top left corner of the - screen to the position (250, 250) in 10 seconds (10000 milliseconds). - - The example above will do a linear interpolation between the - start and end value. It is also possible to set values - situated between the start and end value. The interpolation - will then go by these points. - - \code - QPushButton button("Animated Button"); - button.show(); - - QPropertyAnimation animation(&button, "geometry"); - animation.setDuration(10000); - - animation.setKeyValueAt(0, QRect(0, 0, 100, 30)); - animation.setKeyValueAt(0.8, QRect(250, 250, 100, 30)); - animation.setKeyValueAt(1, QRect(0, 0, 100, 30)); - - animation.start(); - \endcode - - In this example, the animation will take the button to (250, 250) - in 8 seconds, and then move it back to its original position in - the remaining 2 seconds. The movement will be linearly - interpolated between these points. - - You also have the possibility to animate values of a QObject - that is not declared as a Qt property. The only requirement is - that this value has a setter. You can then subclass the class - containing the value and declare a property that uses this setter. - Note that each Qt property requires a getter, so you will need to - provide a getter yourself if this is not defined. - - \code - class MyGraphicsRectItem : public QObject, public QGraphicsRectItem - { - Q_OBJECT - Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry) - }; - \endcode - - In the above code example, we subclass QGraphicsRectItem and - define a geometry property. We can now animate the widgets - geometry even if QGraphicsRectItem does not provide the geometry - property. - - For a general introduction to the Qt property system, see its - \l{Qt's Property System}{overview}. - - \section1 Animations and the Graphics View Framework - - When you want to animate \l{QGraphicsItem}s, you also use - QPropertyAnimation. However, QGraphicsItem does not inherit QObject. - A good solution is to subclass the graphics item you wish to animate. - This class will then also inherit QObject. - This way, QPropertyAnimation can be used for \l{QGraphicsItem}s. - The example below shows how this is done. Another possibility is - to inherit QGraphicsWidget, which already is a QObject. - - \code - class Pixmap : public QObject, public QGraphicsPixmapItem - { - Q_OBJECT - Q_PROPERTY(QPointF pos READ pos WRITE setPos) - ... - \endcode - - As described in the previous section, we need to define - properties that we wish to animate. - - Note that QObject must be the first class inherited as the - meta-object system demands this. - - \warning The QItemAnimation class, which was initially intended - for animating \l{QGraphicsItem}s may be deprecated or removed from - the animation framework. - - \omit (need something about the list of animations). \endomit - - \section1 Easing Curves - - As mentioned, QPropertyAnimation performs an interpolation between - the start and end property value. In addition to adding more key - values to the animation, you can also use an easing curve. Easing - curves describe a function that controls how the speed of the - interpolation between 0 and 1 should be, and are useful if you - want to control the speed of an animation without changing the - path of the interpolation. - - \code - QPushButton button("Animated Button"); - button.show(); - - QPropertyAnimation animation(&button, "geometry"); - animation.setDuration(3000); - animation.setStartValue(QRect(0, 0, 100, 30)); - animation.setEndValue(QRect(250, 250, 100, 30)); - - animation.setEasingCurve(QEasingCurve::OutBounce); - - animation.start(); - \endcode - - Here the animation will follow a curve that makes it bounce like a - ball as if it was dropped from the start to the end position. - QEasingCurve has a large collection of curves for you to choose - from. These are defined by the QEasingCurve::Type enum. If you are - in need of another curve, you can also implement one yourself, and - register it with QEasingCurve. - - \omit Drop this for the first Lab release - (Example of custom easing curve (without the actual impl of - the function I expect) - \endomit - - \section1 Putting Animations Together - - An application will often contain more than one animation. For - instance, you might want to move more than one graphics item - simultaneously or move them in sequence after each other. - - The subclasses of QAnimationGroup (QSequentialAnimationGroup and - QParallelAnimationGroup) are containers for other animations so - that these animations can be animated either in sequence or - parallel. The QAnimationGroup is an example of an animation that - does not animate properties, but it gets notified of time changes - periodically. This enables it to forward those time changes to its - contained animations, and thereby controlling when its animations - are played. - - Let's look at code examples that use both - QSequentialAnimationGroup and QParallelAnimationGroup, starting - off with the latter. - - \code - QPushButton *bonnie = new QPushButton("Bonnie"); - bonnie->show(); - - QPushButton *clyde = new QPushButton("Clyde"); - clyde->show(); - - QPropertyAnimation *anim1 = new QPropertyAnimation(bonnie, "geometry"); - // Set up anim1 - - QPropertyAnimation *anim2 = new QPropertyAnimation(clyde, "geometry"); - // Set up anim2 - - QParallelAnimationGroup *group = new QParallelAnimationGroup; - group->addAnimation(anim1); - group->addAnimation(anim2); - - group->start(); - \endcode - - A parallel group plays more than one animation at the same time. - Calling its \l{QAbstractAnimation::}{start()} function will start - all animations it governs. - - \code - QPushButton button("Animated Button"); - button.show(); - - QPropertyAnimation anim1(&button, "geometry"); - anim1.setDuration(3000); - anim1.setStartValue(QRect(0, 0, 100, 30)); - anim1.setEndValue(QRect(500, 500, 100, 30)); - - QPropertyAnimation anim2(&button, "geometry"); - anim2.setDuration(3000); - anim2.setStartValue(QRect(500, 500, 100, 30)); - anim2.setEndValue(QRect(1000, 500, 100, 30)); - - QSequentialAnimationGroup group; - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - - group.start(); - \endcode - - As you no doubt have guessed, QSequentialAnimationGroup plays - its animations in sequence. It starts the next animation in - the list after the previous is finished. - - Since an animation group is an animation itself, you can add - it to another group. This way, you can build a tree structure - of animations which specifies when the animations are played - in relation to each other. - - \section1 Animations and States - - When using a \l{The State Machine Framework}{state machine}, we - have a special state, QAnimationState, that will play one or more - animations. - - The QState::addAnimatedTransition() convenience function lets you - associate an animation to a state transition. The function will - create the QAnimationState for you, and insert it into the state - machine. We also have the possibility to associate properties with - the states rather than setting the start and end values ourselves. - Below is a complete code example that animates the geometry of a - QPushButton. - - \code - QPushButton *button = new QPushButton("Animated Button"); - button->show(); - - QStateMachine *machine = new QStateMachine; - - QState *state1 = new QState(machine->rootState()); - state1->setPropertyOnEntry(button, "geometry", - QRect(0, 0, 100, 30)); - machine->setInitialState(state1); - - QState *state2 = new QState(machine->rootState()); - state2->setPropertyOnEntry(button, "geometry", - QRect(250, 250, 100, 30)); - - state1->addAnimatedTransition(button, SIGNAL(clicked()), state2, - new QPropertyAnimation(button, "geometry")); - state2->addAnimatedTransition(button, SIGNAL(clicked()), state1, - new QPropertyAnimation(button, "geometry")); - - machine->start(); - \endcode - - For a more comprehensive example of how to use the state machine - framework for animations, see the states example (it lives in the - \c{examples/animation/states} directory). -*/ - diff --git a/doc/src/diagrams/animations-architecture.svg b/doc/src/diagrams/animations-architecture.svg deleted file mode 100644 index 0246510..0000000 --- a/doc/src/diagrams/animations-architecture.svg +++ /dev/null @@ -1,351 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - QAbstractAnimation - - QVariantAnimation - - QAnimationGroup - - - - QPropertyAnimation - - - QSequentialAnimationGroup - - QParallelAnimationGroup - - - - diff --git a/doc/src/diagrams/programs/easingcurve/easingcurve.pro b/doc/src/diagrams/programs/easingcurve/easingcurve.pro deleted file mode 100644 index 0b80127..0000000 --- a/doc/src/diagrams/programs/easingcurve/easingcurve.pro +++ /dev/null @@ -1,13 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) fr 13. feb 13:26:38 2009 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -# Input -SOURCES += main.cpp - -CONFIG += console \ No newline at end of file diff --git a/doc/src/diagrams/programs/easingcurve/main.cpp b/doc/src/diagrams/programs/easingcurve/main.cpp deleted file mode 100644 index 98e9d37..0000000 --- a/doc/src/diagrams/programs/easingcurve/main.cpp +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the $MODULE$ of the Qt Toolkit. -** -** $TROLLTECH_DUAL_LICENSE$ -** -****************************************************************************/ - -#include - -void createCurveIcons(); - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - createCurveIcons(); - return app.exit(); -} - -void createCurveIcons() -{ - QDir dir(QDir::current()); - if (dir.dirName() == QLatin1String("debug") || dir.dirName() == QLatin1String("release")) { - dir.cdUp(); - } - dir.cdUp(); - dir.cdUp(); - dir.cdUp(); - QSize iconSize(128, 128); - QPixmap pix(iconSize); - QPainter painter(&pix); - QLinearGradient gradient(0,0, 0, iconSize.height()); - gradient.setColorAt(0.0, QColor(240, 240, 240)); - gradient.setColorAt(1.0, QColor(224, 224, 224)); - QBrush brush(gradient); - const QMetaObject &mo = QEasingCurve::staticMetaObject; - QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type")); - QFont oldFont = painter.font(); - // Skip QEasingCurve::Custom - QString output(QString::fromAscii("%1/images").arg(dir.absolutePath())); - printf("Generating images to %s\n", qPrintable(output)); - for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) { - painter.setFont(oldFont); - QString name(QLatin1String(metaEnum.key(i))); - painter.fillRect(QRect(QPoint(0, 0), iconSize), brush); - QEasingCurve curve((QEasingCurve::Type)i); - painter.setPen(QColor(0, 0, 255, 64)); - qreal xAxis = iconSize.height()/1.5; - qreal yAxis = iconSize.width()/3; - painter.drawLine(0, xAxis, iconSize.width(), xAxis); // hor - painter.drawLine(yAxis, 0, yAxis, iconSize.height()); // ver - - qreal curveScale = iconSize.height()/2; - - painter.drawLine(yAxis - 2, xAxis - curveScale, yAxis + 2, xAxis - curveScale); // hor - painter.drawLine(yAxis + curveScale, xAxis + 2, yAxis + curveScale, xAxis - 2); // ver - painter.drawText(yAxis + curveScale - 8, xAxis - curveScale - 4, QLatin1String("(1,1)")); - - painter.drawText(yAxis + 42, xAxis + 10, QLatin1String("progress")); - painter.drawText(15, xAxis - curveScale - 10, QLatin1String("ease")); - - painter.setPen(QPen(Qt::red, 1, Qt::DotLine)); - painter.drawLine(yAxis, xAxis - curveScale, yAxis + curveScale, xAxis - curveScale); // hor - painter.drawLine(yAxis + curveScale, xAxis, yAxis + curveScale, xAxis - curveScale); // ver - - QPoint currentPos(yAxis, xAxis); - - painter.setPen(Qt::black); - QFont font = oldFont; - font.setPixelSize(oldFont.pixelSize() + 15); - painter.setFont(font); - painter.drawText(0, iconSize.height() - 20, iconSize.width(), 20, Qt::AlignHCenter, name); - - for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { - QPoint to; - to.setX(yAxis + curveScale * t); - to.setY(xAxis - curveScale * curve.valueForProgress(t)); - painter.drawLine(currentPos, to); - currentPos = to; - } - QString fileName(QString::fromAscii("qeasingcurve-%1.png").arg(name.toLower())); - printf("%s\n", qPrintable(fileName)); - pix.save(QString::fromAscii("%1/%2").arg(output).arg(fileName), "PNG"); - } -} - - diff --git a/doc/src/examples-overview.qdoc b/doc/src/examples-overview.qdoc index 92ccd4e..549574d 100644 --- a/doc/src/examples-overview.qdoc +++ b/doc/src/examples-overview.qdoc @@ -319,14 +319,6 @@ from displaying Web pages within a Qt user interface to an implementation of a basic function Web browser. - \section1 \l{Qt Examples#State Machine}{State Machine} - - Qt provides a powerful hierchical finite state machine through the Qt State - Machine classes. - - These examples demonstrate the fundamental aspects of implementing - Statecharts with Qt. - \section1 \l{Qt Examples#Qt for Embedded Linux}{Qt for Embedded Linux} \l{Qt Examples#Qt for Embedded Linux}{\inlineimage qt-embedded-examples.png diff --git a/doc/src/examples.qdoc b/doc/src/examples.qdoc index c55d29f..29c6c0b 100644 --- a/doc/src/examples.qdoc +++ b/doc/src/examples.qdoc @@ -86,12 +86,6 @@ \o \l{activeqt/webbrowser}{Web Browser}\raisedaster \o \l{activeqt/wrapper}{Wrapper}\raisedaster \endlist - - \section1 Animation - - \list - \o \l{animation/stickman}{Stick man}\raisedaster - \endlist \section1 Concurrent Programming @@ -314,17 +308,6 @@ \o \l{sql/sqlwidgetmapper}{SQL Widget Mapper}\raisedaster \endlist - \section1 State Machine - - \list - \o \l{statemachine/eventtransitions}{Event Transitions}\raisedaster - \o \l{statemachine/factorial}{Factorial States}\raisedaster - \o \l{statemachine/pingpong}{Ping Pong States}\raisedaster - \o \l{statemachine/trafficlight}{Traffic Light}\raisedaster - \o \l{statemachine/twowaybutton}{Two-way Button}\raisedaster - \o \l{statemachine/tankgame}{Tank Game}\raisedaster - \endlist - \section1 Threads \list diff --git a/doc/src/examples/eventtransitions.qdoc b/doc/src/examples/eventtransitions.qdoc deleted file mode 100644 index 3b956bb..0000000 --- a/doc/src/examples/eventtransitions.qdoc +++ /dev/null @@ -1,86 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example statemachine/eventtransitions - \title Event Transitions Example - - The Event Transitions example shows how to use event transitions, a - feature of \l{The State Machine Framework}. - - \snippet examples/statemachine/eventtransitions/main.cpp 0 - - The \c Window class's constructors begins by creating a button. - - \snippet examples/statemachine/eventtransitions/main.cpp 1 - - Two states, \c s1 and \c s2, are created; upon entry they will assign - "Outside" and "Inside" to the button's text, respectively. - - \snippet examples/statemachine/eventtransitions/main.cpp 2 - - When the button receives an event of type QEvent::Enter and the state - machine is in state \c s1, the machine will transition to state \c s2. - - \snippet examples/statemachine/eventtransitions/main.cpp 3 - - When the button receives an event of type QEvent::Leave and the state - machine is in state \c s2, the machine will transition back to state \c - s1. - - \snippet examples/statemachine/eventtransitions/main.cpp 4 - - Next, the state \c s3 is created. \c s3 will be entered when the button - receives an event of type QEvent::MouseButtonPress and the state machine - is in state \c s2. When the button receives an event of type - QEvent::MouseButtonRelease and the state machine is in state \c s3, the - machine will transition back to state \c s2. - - \snippet examples/statemachine/eventtransitions/main.cpp 5 - - Finally, the states are added to the machine as top-level states, the - initial state is set to be \c s1 ("Outside"), and the machine is started. - - \snippet examples/statemachine/eventtransitions/main.cpp 6 - - The main() function constructs a Window object and shows it. - -*/ diff --git a/doc/src/examples/factorial.qdoc b/doc/src/examples/factorial.qdoc deleted file mode 100644 index 2a72e0a..0000000 --- a/doc/src/examples/factorial.qdoc +++ /dev/null @@ -1,102 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example statemachine/factorial - \title Factorial States Example - - The Factorial States example shows how to use \l{The State Machine - Framework} to calculate the factorial of an integer. - - The statechart for calculating the factorial looks as follows: - - \img factorial-example.png - \omit - \caption This is a caption - \endomit - - In other words, the state machine calculates the factorial of 6 and prints - the result. - - \snippet examples/statemachine/factorial/main.cpp 0 - - The Factorial class is used to hold the data of the computation, \c x and - \c fac. It also provides a signal that's emitted whenever the value of \c - x changes. - - \snippet examples/statemachine/factorial/main.cpp 1 - - The FactorialLoopTransition class implements the guard (\c x > 1) and - calculations (\c fac = \c x * \c fac; \c x = \c x - 1) of the factorial - loop. - - \snippet examples/statemachine/factorial/main.cpp 2 - - The FactorialDoneTransition class implements the guard (\c x <= 1) that - terminates the factorial computation. It also prints the final result to - standard output. - - \snippet examples/statemachine/factorial/main.cpp 3 - - The application's main() function first creates the application object, a - Factorial object and a state machine. - - \snippet examples/statemachine/factorial/main.cpp 4 - - The \c compute state is created, and the initial values of \c x and \c fac - are defined. A FactorialLoopTransition object is created and added to the - state. - - \snippet examples/statemachine/factorial/main.cpp 5 - - A final state, \c done, is created, and a FactorialDoneTransition object - is created with \c done as its target state. The transition is then added - to the \c compute state. - - \snippet examples/statemachine/factorial/main.cpp 6 - - The machine's initial state is set to be the \c compute state. We connect - the QStateMachine::finished() signal to the QCoreApplication::quit() slot, - so the application will quit when the state machine's work is - done. Finally, the state machine is started, and the application's event - loop is entered. - - */ diff --git a/doc/src/examples/pingpong.qdoc b/doc/src/examples/pingpong.qdoc deleted file mode 100644 index 040e429..0000000 --- a/doc/src/examples/pingpong.qdoc +++ /dev/null @@ -1,107 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example statemachine/pingpong - \title Ping Pong States Example - - The Ping Pong States example shows how to use parallel states together - with custom events and transitions in \l{The State Machine Framework}. - - This example implements a statechart where two states communicate by - posting events to the state machine. The state chart looks as follows: - - \img pingpong-example.png - \omit - \caption This is a caption - \endomit - - The \c pinger and \c ponger states are parallel states, i.e. they are - entered simultaneously and will take transitions independently of - eachother. - - The \c pinger state will post the first \c ping event upon entry; the \c - ponger state will respond by posting a \c pong event; this will cause the - \c pinger state to post a new \c ping event; and so on. - - \snippet examples/statemachine/pingpong/main.cpp 0 - - Two custom events are defined, \c PingEvent and \c PongEvent. - - \snippet examples/statemachine/pingpong/main.cpp 1 - - The \c Pinger class defines a state that posts a \c PingEvent to the state - machine when the state is entered. - - \snippet examples/statemachine/pingpong/main.cpp 2 - - The \c PingTransition class defines a transition that is triggered by - events of type \c PingEvent, and that posts a \c PongEvent (with a delay - of 500 milliseconds) to the state machine when the transition is - triggered. - - \snippet examples/statemachine/pingpong/main.cpp 3 - - The \c PongTransition class defines a transition that is triggered by - events of type \c PongEvent, and that posts a \c PingEvent (with a delay - of 500 milliseconds) to the state machine when the transition is - triggered. - - \snippet examples/statemachine/pingpong/main.cpp 4 - - The main() function begins by creating a state machine and a parallel - state group. - - \snippet examples/statemachine/pingpong/main.cpp 5 - - Next, the \c pinger and \c ponger states are created, with the parallel - state group as their parent state. Note that the transitions are \e - targetless. When such a transition is triggered, the source state won't be - exited and re-entered; only the transition's onTransition() function will - be called, and the state machine's configuration will remain the same, - which is precisely what we want in this case. - - \snippet examples/statemachine/pingpong/main.cpp 6 - - Finally, the group is added to the state machine, the machine is started, - and the application event loop is entered. - - */ diff --git a/doc/src/examples/stickman.qdoc b/doc/src/examples/stickman.qdoc deleted file mode 100644 index 49f4953..0000000 --- a/doc/src/examples/stickman.qdoc +++ /dev/null @@ -1,115 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example animation/stickman - \title Stickman Example - - The Stickman example shows how to animate transitions in a state machine to implement key frame - animations. - - \image stickman-example.png - - In this example, we will write a small application which animates the joints in a skeleton and - projects a stickman figure on top. The stickman can be either "alive" or "dead", and when in the - "alive" state, he can be performing different actions defined by key frame animations. - - Animations are implemented as composite states. Each child state of the animation state - represents a frame in the animation by setting the position of each joint in the stickman's - skeleton to the positions defined for the particular frame. The frames are then bound together - with animated transitions that trigger on the source state's polished() signal. Thus, the - machine will enter the state representing the next frame in the animation immediately after it - has finished animating into the previous frame. - - \image stickman-example1.png - - The states for an animation is constructed by reading a custom animation file format and - creating states that assign values to the the "position" properties of each of the nodes in the - skeleton graph. - - \snippet examples/animation/stickman/lifecycle.cpp 1 - - The states are then bound together with signal transitions that listen to the polished() signal. - - \snippet examples/animation/stickman/lifecycle.cpp 2 - - The last frame state is given a transition to the first one, so that the animation will loop - until it is interrupted when a transition out from the animation state is taken. To get smooth - animations between the different key frames, we set a default animation on the state machine. - This is a parallel animation group which contains animations for all the "position" properties - and will be selected by default when taking any transition that leads into a state that assigns - values to these properties. - - \snippet examples/animation/stickman/lifecycle.cpp 3 - - Several such animation states are constructed, and are placed together as children of a top - level "alive" state which represents the stickman life cycle. Transitions go from the parent - state to the child state to ensure that each of the child states inherit them. - - \image stickman-example2.png - - This saves us the effort of connect every state to every state with identical transitions. The - state machine makes sure that transitions between the key frame animations are also smooth by - applying the default animation when interrupting one and starting another. - - Finally, there is a transition out from the "alive" state and into the "dead" state. This is - a custom transition type called LightningSrikesTransition which samples every second and - triggers at random (one out of fifty times on average.) - - \snippet examples/animation/stickman/lifecycle.cpp 4 - - When it triggers, the machine will first enter a "lightningBlink" state which uses a timer to - pause for a brief period of time while the background color of the scene is white. This gives us - a flash effect when the lightning strikes. - - \snippet examples/animation/stickman/lifecycle.cpp 5 - - We start and stop a QTimer object when entering and exiting the state. Then we transition into - the "dead" state when the timer times out. - - \snippet examples/animation/stickman/lifecycle.cpp 0 - - When the machine is in the "dead" state, it will be unresponsive. This is because the "dead" - state has no transitions leading out. - - \image stickman-example3.png - -*/ diff --git a/doc/src/examples/tankgame.qdoc b/doc/src/examples/tankgame.qdoc deleted file mode 100644 index ab3e0f4..0000000 --- a/doc/src/examples/tankgame.qdoc +++ /dev/null @@ -1,117 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example statemachine/tankgame - \title Tank Game Example - - The Tank Game example is part of the in \l{The State Machine Framework}. It shows how to use - parallel states to implement artificial intelligence controllers that run in parallel, and error - states to handle run-time errors in parts of the state graph created by external plugins. - - \image tankgame-example.png - - In this example we write a simple game. The application runs a state machine with two main - states: A "stopped" state and a "running" state. The user can load plugins from the disk by - selecting the "Add tank" menu item. - - When the "Add tank" menu item is selected, the "plugins" subdirectory in the example's - directory is searched for compatible plugins. If any are found, they will be listed in a - dialog box created using QInputDialog::getItem(). - - \snippet examples/statemachine/tankgame/mainwindow.cpp 1 - - If the user selects a plugin, the application will construct a TankItem object, which inherits - from QGraphicsItem and QObject, and which implements an agreed-upon interface using the - meta-object mechanism. - - \snippet examples/statemachine/tankgame/tankitem.h 0 - - The tank item will be passed to the plugin's create() function. This will in turn return a - QState object which is expected to implement an artificial intelligence which controls the - tank and attempts to destroy other tanks it detects. - - \snippet examples/statemachine/tankgame/mainwindow.cpp 2 - - Each returned QState object becomes a descendant of a \c region in the "running" state, which is - defined as a parallel state. This means that entering the "running" state will cause each of the - plugged-in QState objects to be entered simultaneously, allowing the tanks to run independently - of each other. - - \snippet examples/statemachine/tankgame/mainwindow.cpp 0 - - The maximum number of tanks on the map is four, and when this number is reached, the - "Add tank" menu item should be disabled. This is implemented by giving the "stopped" state two - children which define whether the map is full or not. - - \snippet examples/statemachine/tankgame/mainwindow.cpp 5 - - To make sure that we go into the correct child state when returning from the "running" state - (if the "Stop game" menu item is selected while the game is running) we also give the "stopped" - state a history state which we make the initial state of "stopped" state. - - \snippet examples/statemachine/tankgame/mainwindow.cpp 3 - - Since part of the state graph is defined by external plugins, we have no way of controlling - whether they contain errors. By default, run-time errors are handled in the state machine by - entering a top level state which prints out an error message and never exits. If we were to - use this default behavior, a run-time error in any of the plugins would cause the "running" - state to exit, and thus all the other tanks to stop running as well. A better solution would - be if the broken plugin was disabled and the rest of the tanks allowed to continue as before. - - This is done by setting the error state of the plugin's top-most state to a special error state - defined specifically for the plugin in question. - - \snippet examples/statemachine/tankgame/mainwindow.cpp 4 - - If a run-time error occurs in \c pluginState or any of its descendants, the state machine will - search the hierarchy of ancestors until it finds a state whose error state is different from - \c null. (Note that if we are worried that a plugin could inadvertedly be overriding our - error state, we could search the descendants of \c pluginState and verify that their error - states are set to \c null before accepting the plugin.) - - The specialized \c errorState sets the "enabled" property of the tank item in question to false, - causing it to be painted with a red cross over it to indicate that it is no longer running. - Since the error state is a child of the same region in the parallel "running" state as - \c pluginState, it will not exit the "running" state, and the other tanks will continue running - without disruption. - -*/ diff --git a/doc/src/examples/trafficlight.qdoc b/doc/src/examples/trafficlight.qdoc deleted file mode 100644 index ae62127..0000000 --- a/doc/src/examples/trafficlight.qdoc +++ /dev/null @@ -1,99 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example statemachine/trafficlight - \title Traffic Light Example - - The Traffic Light example shows how to use \l{The State Machine Framework} - to implement the control flow of a traffic light. - - \image trafficlight-example.png - - In this example we write a TrafficLightWidget class. The traffic light has - three lights: Red, yellow and green. The traffic light transitions from - one light to another (red to yellow to green to yellow to red again) at - certain intervals. - - \snippet examples/statemachine/trafficlight/main.cpp 0 - - The LightWidget class represents a single light of the traffic light. It - provides an \c on property and two slots, turnOn() and turnOff(), to turn - the light on and off, respectively. The widget paints itself in the color - that's passed to the constructor. - - \snippet examples/statemachine/trafficlight/main.cpp 1 - - The TrafficLightWidget class represents the visual part of the traffic - light; it's a widget that contains three lights arranged vertically, and - provides accessor functions for these. - - \snippet examples/statemachine/trafficlight/main.cpp 2 - - The createLightState() function creates a state that turns a light on when - the state is entered, and off when the state is exited. The state uses a - timer, and as we shall see the timeout is used to transition from one - LightState to another. Here is the statechart for the light state: - - \img trafficlight-example1.png - \omit - \caption This is a caption - \endomit - - \snippet examples/statemachine/trafficlight/main.cpp 3 - - The TrafficLight class combines the TrafficLightWidget with a state - machine. The state graph has four states: red-to-yellow, yellow-to-green, - green-to-yellow and yellow-to-red. The initial state is red-to-yellow; - when the state's timer times out, the state machine transitions to - yellow-to-green. The same process repeats through the other states. - This is what the statechart looks like: - - \img trafficlight-example2.png - \omit - \caption This is a caption - \endomit - - \snippet examples/statemachine/trafficlight/main.cpp 4 - - The main() function constructs a TrafficLight and shows it. - -*/ diff --git a/doc/src/examples/twowaybutton.qdoc b/doc/src/examples/twowaybutton.qdoc deleted file mode 100644 index 87de2e8..0000000 --- a/doc/src/examples/twowaybutton.qdoc +++ /dev/null @@ -1,82 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \example statemachine/twowaybutton - \title Two-way Button Example - - The Two-way button example shows how to use \l{The State Machine - Framework} to implement a simple state machine that toggles the current - state when a button is clicked. - - \snippet examples/statemachine/twowaybutton/main.cpp 0 - - The application's main() function begins by constructing the application - object, a button and a state machine. - - \snippet examples/statemachine/twowaybutton/main.cpp 1 - - The state machine has two states; \c on and \c off. When either state is - entered, the text of the button will be set accordingly. - - \snippet examples/statemachine/twowaybutton/main.cpp 2 - - When the state machine is in the \c off state and the button is clicked, - it will transition to the \c on state; when the state machine is in the \c - on state and the button is clicked, it will transition to the \c off - state. - - \snippet examples/statemachine/twowaybutton/main.cpp 3 - - The states are added to the state machine; they become top-level (sibling) - states. - - \snippet examples/statemachine/twowaybutton/main.cpp 4 - - The initial state is \c off; this is the state the state machine will - immediately transition to once the state machine is started. - - \snippet examples/statemachine/twowaybutton/main.cpp 5 - - Finally, the button is resized and made visible, and the application event - loop is entered. - -*/ diff --git a/doc/src/external-resources.qdoc b/doc/src/external-resources.qdoc index 3bfb5af..f48c3d7 100644 --- a/doc/src/external-resources.qdoc +++ b/doc/src/external-resources.qdoc @@ -334,16 +334,6 @@ */ /*! - \externalpage http://www.w3.org/TR/scxml/ - \title State Chart XML: State Machine Notation for Control Abstraction -*/ - -/*! - \externalpage http://www.wisdom.weizmann.ac.il/~dharel/SCANNED.PAPERS/Statecharts.pdf - \title Statecharts: A visual formalism for complex systems -*/ - -/*! \externalpage http://www.gnu.org/licenses/gpl.html \title GNU General Public License */ diff --git a/doc/src/groups.qdoc b/doc/src/groups.qdoc index 3c4da53..c9cedc4 100644 --- a/doc/src/groups.qdoc +++ b/doc/src/groups.qdoc @@ -69,18 +69,6 @@ */ /*! - \group animation - \ingroup groups - - \title Animation Framework - \brief Classes for animations, states and transitions. - - These classes provide a framework for creating both simple and complex - animations. \l{The Animation Framework} also provides states and animated - transitions, making it easy to create animated stateful forms. -*/ - -/*! \group abstractwidgets \title Abstract Widget Classes \ingroup groups @@ -609,14 +597,3 @@ These classes are relevant to developers who are working with Qt Script's debugging features. */ - -/*! - \group statemachine - \ingroup groups - - \title State Machine Classes - \brief Classes for constructing and executing state graphs. - - These classes are provided by \l{The State Machine Framework} for creating - event-driven state machines. -*/ diff --git a/doc/src/images/animations-architecture.png b/doc/src/images/animations-architecture.png deleted file mode 100644 index 9b581af..0000000 Binary files a/doc/src/images/animations-architecture.png and /dev/null differ diff --git a/doc/src/images/factorial-example.png b/doc/src/images/factorial-example.png deleted file mode 100644 index 8fb1cc6..0000000 Binary files a/doc/src/images/factorial-example.png and /dev/null differ diff --git a/doc/src/images/pingpong-example.png b/doc/src/images/pingpong-example.png deleted file mode 100644 index af707e4..0000000 Binary files a/doc/src/images/pingpong-example.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-cosinecurve.png b/doc/src/images/qeasingcurve-cosinecurve.png deleted file mode 100644 index b27e763..0000000 Binary files a/doc/src/images/qeasingcurve-cosinecurve.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inback.png b/doc/src/images/qeasingcurve-inback.png deleted file mode 100644 index 8506c0f..0000000 Binary files a/doc/src/images/qeasingcurve-inback.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inbounce.png b/doc/src/images/qeasingcurve-inbounce.png deleted file mode 100644 index 275b38c..0000000 Binary files a/doc/src/images/qeasingcurve-inbounce.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-incirc.png b/doc/src/images/qeasingcurve-incirc.png deleted file mode 100644 index b985e9c..0000000 Binary files a/doc/src/images/qeasingcurve-incirc.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-incubic.png b/doc/src/images/qeasingcurve-incubic.png deleted file mode 100644 index e417ee1..0000000 Binary files a/doc/src/images/qeasingcurve-incubic.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-incurve.png b/doc/src/images/qeasingcurve-incurve.png deleted file mode 100644 index d9a9340..0000000 Binary files a/doc/src/images/qeasingcurve-incurve.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inelastic.png b/doc/src/images/qeasingcurve-inelastic.png deleted file mode 100644 index b242fd3..0000000 Binary files a/doc/src/images/qeasingcurve-inelastic.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inexpo.png b/doc/src/images/qeasingcurve-inexpo.png deleted file mode 100644 index f06316c..0000000 Binary files a/doc/src/images/qeasingcurve-inexpo.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutback.png b/doc/src/images/qeasingcurve-inoutback.png deleted file mode 100644 index 9fd1446..0000000 Binary files a/doc/src/images/qeasingcurve-inoutback.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutbounce.png b/doc/src/images/qeasingcurve-inoutbounce.png deleted file mode 100644 index fb65f31..0000000 Binary files a/doc/src/images/qeasingcurve-inoutbounce.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutcirc.png b/doc/src/images/qeasingcurve-inoutcirc.png deleted file mode 100644 index 123cc54..0000000 Binary files a/doc/src/images/qeasingcurve-inoutcirc.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutcubic.png b/doc/src/images/qeasingcurve-inoutcubic.png deleted file mode 100644 index b07695c..0000000 Binary files a/doc/src/images/qeasingcurve-inoutcubic.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutelastic.png b/doc/src/images/qeasingcurve-inoutelastic.png deleted file mode 100644 index 65851e1..0000000 Binary files a/doc/src/images/qeasingcurve-inoutelastic.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutexpo.png b/doc/src/images/qeasingcurve-inoutexpo.png deleted file mode 100644 index 7cbfb13..0000000 Binary files a/doc/src/images/qeasingcurve-inoutexpo.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutquad.png b/doc/src/images/qeasingcurve-inoutquad.png deleted file mode 100644 index c5eed06..0000000 Binary files a/doc/src/images/qeasingcurve-inoutquad.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutquart.png b/doc/src/images/qeasingcurve-inoutquart.png deleted file mode 100644 index 3b66c0d..0000000 Binary files a/doc/src/images/qeasingcurve-inoutquart.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutquint.png b/doc/src/images/qeasingcurve-inoutquint.png deleted file mode 100644 index c74efe9..0000000 Binary files a/doc/src/images/qeasingcurve-inoutquint.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inoutsine.png b/doc/src/images/qeasingcurve-inoutsine.png deleted file mode 100644 index 5964f31..0000000 Binary files a/doc/src/images/qeasingcurve-inoutsine.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inquad.png b/doc/src/images/qeasingcurve-inquad.png deleted file mode 100644 index 3373310..0000000 Binary files a/doc/src/images/qeasingcurve-inquad.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inquart.png b/doc/src/images/qeasingcurve-inquart.png deleted file mode 100644 index 28086d8..0000000 Binary files a/doc/src/images/qeasingcurve-inquart.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-inquint.png b/doc/src/images/qeasingcurve-inquint.png deleted file mode 100644 index 330aa85..0000000 Binary files a/doc/src/images/qeasingcurve-inquint.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-insine.png b/doc/src/images/qeasingcurve-insine.png deleted file mode 100644 index 63d9238..0000000 Binary files a/doc/src/images/qeasingcurve-insine.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-linear.png b/doc/src/images/qeasingcurve-linear.png deleted file mode 100644 index 2a05885..0000000 Binary files a/doc/src/images/qeasingcurve-linear.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outback.png b/doc/src/images/qeasingcurve-outback.png deleted file mode 100644 index 7cb34c6..0000000 Binary files a/doc/src/images/qeasingcurve-outback.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outbounce.png b/doc/src/images/qeasingcurve-outbounce.png deleted file mode 100644 index 932fc16..0000000 Binary files a/doc/src/images/qeasingcurve-outbounce.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outcirc.png b/doc/src/images/qeasingcurve-outcirc.png deleted file mode 100644 index a1a6cb6..0000000 Binary files a/doc/src/images/qeasingcurve-outcirc.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outcubic.png b/doc/src/images/qeasingcurve-outcubic.png deleted file mode 100644 index aa1d604..0000000 Binary files a/doc/src/images/qeasingcurve-outcubic.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outcurve.png b/doc/src/images/qeasingcurve-outcurve.png deleted file mode 100644 index a949ae4..0000000 Binary files a/doc/src/images/qeasingcurve-outcurve.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outelastic.png b/doc/src/images/qeasingcurve-outelastic.png deleted file mode 100644 index 2a9ba39..0000000 Binary files a/doc/src/images/qeasingcurve-outelastic.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outexpo.png b/doc/src/images/qeasingcurve-outexpo.png deleted file mode 100644 index e771c2e..0000000 Binary files a/doc/src/images/qeasingcurve-outexpo.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outinback.png b/doc/src/images/qeasingcurve-outinback.png deleted file mode 100644 index 7523727..0000000 Binary files a/doc/src/images/qeasingcurve-outinback.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outinbounce.png b/doc/src/images/qeasingcurve-outinbounce.png deleted file mode 100644 index ab73d02..0000000 Binary files a/doc/src/images/qeasingcurve-outinbounce.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outincirc.png b/doc/src/images/qeasingcurve-outincirc.png deleted file mode 100644 index ec4b8d3..0000000 Binary files a/doc/src/images/qeasingcurve-outincirc.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outincubic.png b/doc/src/images/qeasingcurve-outincubic.png deleted file mode 100644 index 8b8ae68..0000000 Binary files a/doc/src/images/qeasingcurve-outincubic.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outinelastic.png b/doc/src/images/qeasingcurve-outinelastic.png deleted file mode 100644 index 89dde2c..0000000 Binary files a/doc/src/images/qeasingcurve-outinelastic.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outinexpo.png b/doc/src/images/qeasingcurve-outinexpo.png deleted file mode 100644 index 5909901..0000000 Binary files a/doc/src/images/qeasingcurve-outinexpo.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outinquad.png b/doc/src/images/qeasingcurve-outinquad.png deleted file mode 100644 index 7ddefee..0000000 Binary files a/doc/src/images/qeasingcurve-outinquad.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outinquart.png b/doc/src/images/qeasingcurve-outinquart.png deleted file mode 100644 index 00ef597..0000000 Binary files a/doc/src/images/qeasingcurve-outinquart.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outinquint.png b/doc/src/images/qeasingcurve-outinquint.png deleted file mode 100644 index 361bfaa4..0000000 Binary files a/doc/src/images/qeasingcurve-outinquint.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outinsine.png b/doc/src/images/qeasingcurve-outinsine.png deleted file mode 100644 index 1737041..0000000 Binary files a/doc/src/images/qeasingcurve-outinsine.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outquad.png b/doc/src/images/qeasingcurve-outquad.png deleted file mode 100644 index 6f27cbd..0000000 Binary files a/doc/src/images/qeasingcurve-outquad.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outquart.png b/doc/src/images/qeasingcurve-outquart.png deleted file mode 100644 index d45a0b8..0000000 Binary files a/doc/src/images/qeasingcurve-outquart.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outquint.png b/doc/src/images/qeasingcurve-outquint.png deleted file mode 100644 index 6e7df0e..0000000 Binary files a/doc/src/images/qeasingcurve-outquint.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-outsine.png b/doc/src/images/qeasingcurve-outsine.png deleted file mode 100644 index 7546a0d..0000000 Binary files a/doc/src/images/qeasingcurve-outsine.png and /dev/null differ diff --git a/doc/src/images/qeasingcurve-sinecurve.png b/doc/src/images/qeasingcurve-sinecurve.png deleted file mode 100644 index ca67d44..0000000 Binary files a/doc/src/images/qeasingcurve-sinecurve.png and /dev/null differ diff --git a/doc/src/images/statemachine-button-history.png b/doc/src/images/statemachine-button-history.png deleted file mode 100644 index 7f51cae..0000000 Binary files a/doc/src/images/statemachine-button-history.png and /dev/null differ diff --git a/doc/src/images/statemachine-button-nested.png b/doc/src/images/statemachine-button-nested.png deleted file mode 100644 index 762ac14..0000000 Binary files a/doc/src/images/statemachine-button-nested.png and /dev/null differ diff --git a/doc/src/images/statemachine-button.png b/doc/src/images/statemachine-button.png deleted file mode 100644 index 10102bd..0000000 Binary files a/doc/src/images/statemachine-button.png and /dev/null differ diff --git a/doc/src/images/statemachine-customevents.png b/doc/src/images/statemachine-customevents.png deleted file mode 100644 index 62a4222..0000000 Binary files a/doc/src/images/statemachine-customevents.png and /dev/null differ diff --git a/doc/src/images/statemachine-customevents2.png b/doc/src/images/statemachine-customevents2.png deleted file mode 100644 index 57b37ef..0000000 Binary files a/doc/src/images/statemachine-customevents2.png and /dev/null differ diff --git a/doc/src/images/statemachine-finished.png b/doc/src/images/statemachine-finished.png deleted file mode 100644 index 0ac081d..0000000 Binary files a/doc/src/images/statemachine-finished.png and /dev/null differ diff --git a/doc/src/images/statemachine-nonparallel.png b/doc/src/images/statemachine-nonparallel.png deleted file mode 100644 index f9850a7..0000000 Binary files a/doc/src/images/statemachine-nonparallel.png and /dev/null differ diff --git a/doc/src/images/statemachine-parallel.png b/doc/src/images/statemachine-parallel.png deleted file mode 100644 index a65c297..0000000 Binary files a/doc/src/images/statemachine-parallel.png and /dev/null differ diff --git a/doc/src/images/stickman-example.png b/doc/src/images/stickman-example.png deleted file mode 100644 index a40f37b..0000000 Binary files a/doc/src/images/stickman-example.png and /dev/null differ diff --git a/doc/src/images/stickman-example1.png b/doc/src/images/stickman-example1.png deleted file mode 100644 index 1596a68..0000000 Binary files a/doc/src/images/stickman-example1.png and /dev/null differ diff --git a/doc/src/images/stickman-example2.png b/doc/src/images/stickman-example2.png deleted file mode 100644 index 980276a..0000000 Binary files a/doc/src/images/stickman-example2.png and /dev/null differ diff --git a/doc/src/images/stickman-example3.png b/doc/src/images/stickman-example3.png deleted file mode 100644 index 3635ff7..0000000 Binary files a/doc/src/images/stickman-example3.png and /dev/null differ diff --git a/doc/src/images/tankgame-example.png b/doc/src/images/tankgame-example.png deleted file mode 100644 index 9e17e30..0000000 Binary files a/doc/src/images/tankgame-example.png and /dev/null differ diff --git a/doc/src/images/trafficlight-example.png b/doc/src/images/trafficlight-example.png deleted file mode 100644 index 3431542..0000000 Binary files a/doc/src/images/trafficlight-example.png and /dev/null differ diff --git a/doc/src/images/trafficlight-example1.png b/doc/src/images/trafficlight-example1.png deleted file mode 100644 index ec8c7ff..0000000 Binary files a/doc/src/images/trafficlight-example1.png and /dev/null differ diff --git a/doc/src/images/trafficlight-example2.png b/doc/src/images/trafficlight-example2.png deleted file mode 100644 index a12e4db..0000000 Binary files a/doc/src/images/trafficlight-example2.png and /dev/null differ diff --git a/doc/src/snippets/animation/sequential/icons.qrc b/doc/src/snippets/animation/sequential/icons.qrc deleted file mode 100644 index d55f797..0000000 --- a/doc/src/snippets/animation/sequential/icons.qrc +++ /dev/null @@ -1,6 +0,0 @@ - - - icons/left.png - icons/right.png - - diff --git a/doc/src/snippets/animation/sequential/icons/left.png b/doc/src/snippets/animation/sequential/icons/left.png deleted file mode 100644 index 5dd8da0..0000000 Binary files a/doc/src/snippets/animation/sequential/icons/left.png and /dev/null differ diff --git a/doc/src/snippets/animation/sequential/icons/right.png b/doc/src/snippets/animation/sequential/icons/right.png deleted file mode 100644 index ac61326..0000000 Binary files a/doc/src/snippets/animation/sequential/icons/right.png and /dev/null differ diff --git a/doc/src/snippets/animation/sequential/main.cpp b/doc/src/snippets/animation/sequential/main.cpp deleted file mode 100644 index aff8f29..0000000 --- a/doc/src/snippets/animation/sequential/main.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include -#include -#include -#include -#include "tracer.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - - QWidget window; - window.resize(720, 96); - window.show(); - - QLabel *label1 = new QLabel(&window); - label1->setPixmap(QPixmap(":/icons/left.png")); - label1->move(16, 16); - label1->show(); - - QLabel *label2 = new QLabel(&window); - label2->setPixmap(QPixmap(":/icons/right.png")); - label2->move(320, 16); - label2->show(); - - QPropertyAnimation *anim1 = new QPropertyAnimation(label1, "pos"); - anim1->setDuration(2500); - anim1->setStartValue(QPoint(16, 16)); - anim1->setEndValue(QPoint(320, 16)); - - QPropertyAnimation *anim2 = new QPropertyAnimation(label2, "pos"); - anim2->setDuration(2500); - anim2->setStartValue(QPoint(320, 16)); - anim2->setEndValue(QPoint(640, 16)); - - QSequentialAnimationGroup group; - group.addAnimation(anim1); - group.addAnimation(anim2); - - Tracer tracer(&window); - - QObject::connect(anim1, SIGNAL(valueChanged(QVariant)), - &tracer, SLOT(recordValue(QVariant))); - QObject::connect(anim2, SIGNAL(valueChanged(QVariant)), - &tracer, SLOT(recordValue(QVariant))); - QObject::connect(anim1, SIGNAL(finished()), &tracer, SLOT(checkValue())); - QObject::connect(anim2, SIGNAL(finished()), &tracer, SLOT(checkValue())); - - group.start(); - return app.exec(); -} diff --git a/doc/src/snippets/animation/sequential/sequential.pro b/doc/src/snippets/animation/sequential/sequential.pro deleted file mode 100644 index fcf017f..0000000 --- a/doc/src/snippets/animation/sequential/sequential.pro +++ /dev/null @@ -1,4 +0,0 @@ -HEADERS = tracer.h -RESOURCES = icons.qrc -SOURCES = main.cpp \ - tracer.cpp diff --git a/doc/src/snippets/animation/sequential/tracer.cpp b/doc/src/snippets/animation/sequential/tracer.cpp deleted file mode 100644 index 49bd51e..0000000 --- a/doc/src/snippets/animation/sequential/tracer.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include -#include -#include -#include "tracer.h" - -Tracer::Tracer(QObject *parent) - : QObject(parent) -{ -} - -void Tracer::checkValue() -{ - QAbstractAnimation *animation = static_cast(sender()); - if (time != animation->duration()) { - qDebug() << "Animation's last recorded time" << time; - qDebug() << "Expected" << animation->duration(); - } -} - -void Tracer::recordValue(const QVariant &value) -{ - QAbstractAnimation *animation = static_cast(sender()); - this->value = value; - time = animation->currentTime(); -} diff --git a/doc/src/snippets/animation/sequential/tracer.h b/doc/src/snippets/animation/sequential/tracer.h deleted file mode 100644 index 1adb018..0000000 --- a/doc/src/snippets/animation/sequential/tracer.h +++ /dev/null @@ -1,23 +0,0 @@ -#ifndef TRACER_H -#define TRACER_H - -#include -#include - -class Tracer : public QObject -{ - Q_OBJECT - -public: - Tracer(QObject *parent = 0); - -public slots: - void checkValue(); - void recordValue(const QVariant &value); - -private: - QVariant value; - int time; -}; - -#endif diff --git a/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp b/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp deleted file mode 100644 index 65358ea..0000000 --- a/doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp +++ /dev/null @@ -1,4 +0,0 @@ -//! [0] -qreal myEasingFunction(qreal progress); -//! [0] - diff --git a/doc/src/statemachine.qdoc b/doc/src/statemachine.qdoc deleted file mode 100644 index 5a89f4d..0000000 --- a/doc/src/statemachine.qdoc +++ /dev/null @@ -1,645 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the documentation of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \page statemachine-api.html - \title The State Machine Framework - \brief An overview of the State Machine framework for constructing and executing state graphs. - \ingroup architecture - - \tableofcontents - - The State Machine framework provides classes for creating and executing - state graphs. The concepts and notation are based on those from Harel's - \l{Statecharts: A visual formalism for complex systems}{Statecharts}, which - is also the basis of UML state diagrams. The semantics of state machine - execution are based on \l{State Chart XML: State Machine Notation for - Control Abstraction}{State Chart XML (SCXML)}. - - Statecharts provide a graphical way of modeling how a system reacts to - stimuli. This is done by defining the possible \e states that the system can - be in, and how the system can move from one state to another (\e transitions - between states). A key characteristic of event-driven systems (such as Qt - applications) is that behavior often depends not only on the last or current - event, but also the events that preceded it. With statecharts, this - information is easy to express. - - The State Machine framework provides an API and execution model that can be - used to effectively embed the elements and semantics of statecharts in Qt - applications. The framework integrates tightly with Qt's meta-object system; - for example, transitions between states can be triggered by signals, and - states can be configured to set properties and invoke methods on QObjects. - Qt's event system is used to drive the state machines. - - \section1 A Simple State Machine - - To demonstrate the core functionality of the State Machine API, let's look - at a small example: A state machine with three states, \c s1, \c s2 and \c - s3. The state machine is controlled by a single QPushButton; when the button - is clicked, the machine transitions to another state. Initially, the state - machine is in state \c s1. The statechart for this machine is as follows: - - \img statemachine-button.png - \omit - \caption This is a caption - \endomit - - The following snippet shows the code needed to create such a state machine. - First, we create the state machine and states: - - \code - QStateMachine machine; - QState *s1 = new QState(); - QState *s2 = new QState(); - QState *s3 = new QState(); - \endcode - - Then, we create the transitions by using the QState::addTransition() - function: - - \code - s1->addTransition(button, SIGNAL(clicked()), s2); - s2->addTransition(button, SIGNAL(clicked()), s3); - s3->addTransition(button, SIGNAL(clicked()), s1); - \endcode - - Next, we add the states to the machine and set the machine's initial state: - - \code - machine.addState(s1); - machine.addState(s2); - machine.addState(s3); - machine.setInitialState(s1); - \endcode - - Finally, we start the state machine: - - \code - machine.start(); - \endcode - - The state machine executes asynchronously, i.e. it becomes part of your - application's event loop. - - \section1 Doing Useful Work on State Entry and Exit - - The above state machine merely transitions from one state to another, it - doesn't perform any operations. The QState::assignProperty() function can be - used to have a state set a property of a QObject when the state is - entered. In the following snippet, the value that should be assigned to a - QLabel's text property is specified for each state: - - \code - s1->assignProperty(label, "text", "In state s1"); - s2->assignProperty(label, "text", "In state s2"); - s3->assignProperty(label, "text", "In state s3"); - \endcode - - When any of the states is entered, the label's text will be changed - accordingly. - - The QState::entered() signal is emitted when the state is entered, and the - QState::exited() signal is emitted when the state is exited. In the - following snippet, the button's showMaximized() slot will be called when - state \c s3 is entered, and the button's showMinimized() slot will be called - when \c s3 is exited: - - \code - QObject::connect(s3, SIGNAL(entered()), button, SLOT(showMaximized())); - QObject::connect(s3, SIGNAL(exited()), button, SLOT(showMinimized())); - \endcode - - Custom states can reimplement QAbstractState::onEntry() and - QAbstractState::onExit(). - - \section1 State Machines That Finish - - The state machine defined in the previous section never finishes. In order - for a state machine to be able to finish, it needs to have a top-level \e - final state (QFinalState object). When the state machine enters a top-level - final state, the machine will emit the QStateMachine::finished() signal and - halt. - - All you need to do to introduce a final state in the graph is create a - QFinalState object and use it as the target of one or more transitions. - - \section1 Sharing Transitions By Grouping States - - Assume we wanted the user to be able to quit the application at any time by - clicking a Quit button. In order to achieve this, we need to create a final - state and make it the target of a transition associated with the Quit - button's clicked() signal. We could add a transition from each of \c s1, \c - s2 and \c s3; however, this seems redundant, and one would also have to - remember to add such a transition from every new state that is added in the - future. - - We can achieve the same behavior (namely that clicking the Quit button quits - the state machine, regardless of which state the state machine is in) by - grouping states \c s1, \c s2 and \c s3. This is done by creating a new - top-level state and making the three original states children of the new - state. The following diagram shows the new state machine. - - \img statemachine-button-nested.png - \omit - \caption This is a caption - \endomit - - The three original states have been renamed \c s11, \c s12 and \c s13 to - reflect that they are now children of the new top-level state, \c s1. Child - states implicitly inherit the transitions of their parent state. This means - it is now sufficient to add a single transition from \c s1 to the final - state \c s2. New states added to \c s1 will also automatically inherit this - transition. - - All that's needed to group states is to specify the proper parent when the - state is created. You also need to specify which of the child states is the - initial one (i.e. which child state the state machine should enter when the - parent state is the target of a transition). - - \code - QState *s1 = new QState(); - QState *s11 = new QState(s1); - QState *s12 = new QState(s1); - QState *s13 = new QState(s1); - s1->setInitialState(s11); - machine.addState(s1); - \endcode - - \code - QFinalState *s2 = new QFinalState(); - s1->addTransition(quitButton, SIGNAL(clicked()), s2); - machine.addState(s2); - - QObject::connect(&machine, SIGNAL(finished()), QApplication::instance(), SLOT(quit())); - \endcode - - In this case we want the application to quit when the state machine is - finished, so the machine's finished() signal is connected to the - application's quit() slot. - - A child state can override an inherited transition. For example, the - following code adds a transition that effectively causes the Quit button to - be ignored when the state machine is in state \c s12. - - \code - s12>addTransition(quitButton, SIGNAL(clicked()), s12); - \endcode - - A transition can have any state as its target, i.e. the target state does - not have to be on the same level in the state hierarchy as the source state. - - \section1 Using History States to Save and Restore the Current State - - Imagine that we wanted to add an "interrupt" mechanism to the example - discussed in the previous section; the user should be able to click a button - to have the state machine perform some non-related task, after which the - state machine should resume whatever it was doing before (i.e. return to the - old state, which is one of \c s11, \c s12 and \c s13 in this case). - - Such behavior can easily be modeled using \e{history states}. A history - state (QHistoryState object) is a pseudo-state that represents the child - state that the parent state was in the last time the parent state was - exited. - - A history state is created as a child of the state for which we wish to - record the current child state; when the state machine detects the presence - of such a state at runtime, it automatically records the current (real) - child state when the parent state is exited. A transition to the history - state is in fact a transition to the child state that the state machine had - previously saved; the state machine automatically "forwards" the transition - to the real child state. - - The following diagram shows the state machine after the interrupt mechanism - has been added. - - \img statemachine-button-history.png - \omit - \caption This is a caption - \endomit - - The following code shows how it can be implemented; in this example we - simply display a message box when \c s3 is entered, then immediately return - to the previous child state of \c s1 via the history state. - - \code - QHistoryState *s1h = s1->addHistoryState(); - - QState *s3 = new QState(); - s3->assignProperty(label, "text", "In s3"); - QMessageBox mbox; - mbox.addButton(QMessageBox::Ok); - mbox.setText("Interrupted!"); - mbox.setIcon(QMessageBox::Information); - QObject::connect(s3, SIGNAL(entered()), &mbox, SLOT(exec())); - s3->addTransition(s1h); - machine.addState(s3); - - s1->addTransition(interruptButton, SIGNAL(clicked()), s3); - \endcode - - \section1 Using Parallel States to Avoid a Combinatorial Explosion of States - - Assume that you wanted to model a set of mutually exclusive properties of a - car in a single state machine. Let's say the properties we are interested in - are Clean vs Dirty, and Moving vs Not moving. It would take four mutually - exclusive states and eight transitions to be able to represent and freely - move between all possible combinations. - - \img statemachine-nonparallel.png - \omit - \caption This is a caption - \endomit - - If we added a third property (say, Red vs Blue), the total number of states - would double, to eight; and if we added a fourth property (say, Enclosed vs - Convertible), the total number of states would double again, to 16. - - Using parallel states, the total number of states and transitions grows - linearly as we add more properties, instead of exponentially. Furthermore, - states can be added to or removed from the parallel state without affecting - any of their sibling states. - - \img statemachine-parallel.png - \omit - \caption This is a caption - \endomit - - To create a parallel state group, pass QState::ParallelStates to the QState - constructor. - - \code - QState *s1 = new QState(QState::ParallelStates); - // s11 and s12 will be entered in parallel - QState *s11 = new QState(s1); - QState *s12 = new QState(s1); - \endcode - - When a parallel state group is entered, all its child states will be - simultaneously entered. Transitions within the individual child states - operate normally. However, any of the child states may take a transition - outside the parent state. When this happens, the parent state and all of its - child states are exited. - - \section1 Detecting that a Composite State has Finished - - A child state can be final (a QFinalState object); when a final child state - is entered, the parent state emits the QState::finished() signal. The - following diagram shows a composite state \c s1 which does some processing - before entering a final state: - - \img statemachine-finished.png - \omit - \caption This is a caption - \endomit - - When \c s1 's final state is entered, \c s1 will automatically emit - finished(). We use a signal transition to cause this event to trigger a - state change: - - \code - s1->addTransition(s1, SIGNAL(finished()), s2); - \endcode - - Using final states in composite states is useful when you want to hide the - internal details of a composite state; i.e. the only thing the outside world - should be able to do is enter the state, and get a notification when the - state has completed its work. This is a very powerful abstraction and - encapsulation mechanism when building complex (deeply nested) state - machines. (In the above example, you could of course create a transition - directly from \c s1 's \c done state rather than relying on \c s1 's - finished() signal, but with the consequence that implementation details of - \c s1 are exposed and depended on). - - For parallel state groups, the QState::finished() signal is emitted when \e - all the child states have entered final states. - - \section1 Events, Transitions and Guards - - A QStateMachine runs its own event loop. For signal transitions - (QSignalTransition objects), QStateMachine automatically posts a - QSignalEvent to itself when it intercepts the corresponding signal; - similarly, for QObject event transitions (QEventTransition objects) a - QWrappedEvent is posted. - - You can post your own events to the state machine using - QStateMachine::postEvent(). - - When posting a custom event to the state machine, you typically also have - one or more custom transitions that can be triggered from events of that - type. To create such a transition, you subclass QAbstractTransition and - reimplement QAbstractTransition::eventTest(), where you check if an event - matches your event type (and optionally other criteria, e.g. attributes of - the event object). - - Here we define our own custom event type, \c StringEvent, for posting - strings to the state machine: - - \code - struct StringEvent : public QEvent - { - StringEvent(const QString &val) - : QEvent(QEvent::Type(QEvent::User+1)), - value(val) {} - - QString value; - }; - \endcode - - Next, we define a transition that only triggers when the event's string - matches a particular string (a \e guarded transition): - - \code - class StringTransition : public QAbstractTransition - { - public: - StringTransition(const QString &value) - : m_value(value) {} - - protected: - virtual bool eventTest(QEvent *e) const - { - if (e->type() != QEvent::Type(QEvent::User+1)) // StringEvent - return false; - StringEvent *se = static_cast(e); - return (m_value == se->value); - } - - virtual void onTransition(QEvent *) {} - - private: - QString m_value; - }; - \endcode - - In the eventTest() reimplementation, we first check if the event type is the - desired one; if so, we cast the event to a StringEvent and perform the - string comparison. - - The following is a statechart that uses the custom event and transition: - - \img statemachine-customevents.png - \omit - \caption This is a caption - \endomit - - Here's what the implementation of the statechart looks like: - - \code - QStateMachine machine; - QState *s1 = new QState(); - QState *s2 = new QState(); - QFinalState *done = new QFinalState(); - - StringTransition *t1 = new StringTransition("Hello"); - t1->setTargetState(s2); - s1->addTransition(t1); - StringTransition *t2 = new StringTransition("world"); - t2->setTargetState(done); - s2->addTransition(t2); - - machine.addState(s1); - machine.addState(s2); - machine.addState(done); - machine.setInitialState(s1); - \endcode - - Once the machine is started, we can post events to it. - - \code - machine.postEvent(new StringEvent("Hello")); - machine.postEvent(new StringEvent("world")); - \endcode - - An event that is not handled by any relevant transition will be silently - consumed by the state machine. It can be useful to group states and provide - a default handling of such events; for example, as illustrated in the - following statechart: - - \img statemachine-customevents2.png - \omit - \caption This is a caption - \endomit - - For deeply nested statecharts, you can add such "fallback" transitions at - the level of granularity that's most appropriate. - - \section1 Using Restore Policy To Automatically Restore Properties - - In some state machines it can be useful to focus the attention on assigning properties in states, - not on restoring them when the state is no longer active. If you know that a property should - always be restored to its initial value when the machine enters a state that does not explicitly - give the property a value, you can set the global restore policy to - QStateMachine::RestoreProperties. - - \code - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - \endcode - - When this restore policy is set, the machine will automatically restore all properties. If it - enters a state where a given property is not set, it will first search the hierarchy of ancestors - to see if the property is defined there. If it is, the property will be restored to the value - defined by the closest ancestor. If not, it will be restored to its initial value (i.e. the - value of the property before any property assignments in states were executed.) - - Take the following code: - \code - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - - QState *s1 = new QState(); - s1->assignProperty(object, "fooBar", 1.0); - machine.addState(s1); - machine.setInitialState(s1); - - QState *s2 = new QState(); - machine.addState(s2); - \endcode - - Lets say the property \c fooBar is 0.0 when the machine starts. When the machine is in state - \c s1, the property will be 1.0, since the state explicitly assigns this value to it. When the - machine is in state \c s2, no value is explicitly defined for the property, so it will implicitly - be restored to 0.0. - - If we are using nested states, the parent defines a value for the property which is inherited by - all descendants that do not explicitly assign a value to the property. - \code - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - - QState *s1 = new QState(); - s1->assignProperty(object, "fooBar", 1.0); - machine.addState(s1); - machine.setInitialState(s1); - - QState *s2 = new QState(s1); - s2->assignProperty(object, "fooBar", 2.0); - s1->setInitialState(s2); - - QState *s3 = new QState(s1); - \endcode - - Here \c s1 has two children: \c s2 and \c s3. When \c s2 is entered, the property \c fooBar - will have the value 2.0, since this is explicitly defined for the state. When the machine is in - state \c s3, no value is defined for the state, but \c s1 defines the property to be 1.0, so this - is the value that will be assigned to \c fooBar. - - \section1 Animating Property Assignments - - The State Machine API connects with the Animation API in Qt to allow automatically animating - properties as they are assigned in states. - - Say we have the following code: - \code - QState *s1 = new QState(); - QState *s2 = new QState(); - - s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); - s2->assignProperty(button, "geometry", QRectF(0, 0, 100, 100)); - - s1->addTransition(button, SIGNAL(clicked()), s2); - \endcode - - Here we define two states of a user interface. In \c s1 the \c button is small, and in \c s2 - it is bigger. If we click the button to transition from \c s1 to \c s2, the geometry of the button - will be set immediately when a given state has been entered. If we want the transition to be - smooth, however, all we need to do is make a QPropertyAnimation and add this to the transition - object. - - \code - QState *s1 = new QState(); - QState *s2 = new QState(); - - s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); - s2->assignProperty(button, "geometry", QRectF(0, 0, 100, 100)); - - QSignalTransition *transition = s1->addTransition(button, SIGNAL(clicked()), s2); - transition->addAnimation(new QPropertyAnimation(button, "geometry")); - \endcode - - Adding an animation for the property in question means that the property assignment will no - longer take immediate effect when the state has been entered. Instead, the animation will start - playing when the state has been entered and smoothly animate the property assignment. Since we - do not set the start value or end value of the animation, these will be set implicitly. The - start value of the animation will be the property's current value when the animation starts, and - the end value will be set based on the property assignments defined for the state. - - If the global restore policy of the state machine is set to QStateMachine::RestoreProperties, - it is possible to also add animations for the property restorations. - - \section1 Detecting That All Properties Have Been Set In A State - - When animations are used to assign properties, a state no longer defines the exact values that a - property will have when the machine is in the given state. While the animation is running, the - property can potentially have any value, depending on the animation. - - In some cases, it can be useful to be able to detect when the property has actually been assigned - the value defined by a state. For this, we can use the state's polished() signal. - \code - QState *s1 = new QState(); - s1->assignProperty(button, "geometry", QRectF(0, 0, 50, 50)); - - QState *s2 = new QState(); - - s1->addTransition(s1, SIGNAL(polished()), s2); - \endcode - - The machine will be in state \c s1 until the \c geometry property has been set. Then it will - immediately transition into \c s2. If the transition into \c s1 has an animation for the \c - geometry property, then the machine will stay in \c s1 until the animation has finished. If there - is no animation, it will simply set the property and immediately enter state \c s2. - - Either way, when the machine is in state \c s2, the property \c geometry has been assigned the - defined value. - - If the global restore policy is set to QStateMachine::RestoreProperties, the state will not emit - the polished() signal until these have been executed as well. - - \section1 What happens if a state is exited before the animation has finished - - If a state has property assignments, and the transition into the state has animations for the - properties, the state can potentially be exited before the properties have been assigned to the - values defines by the state. This is true in particular when there are transitions out from the - state that do not depend on the state being polished, as described in the previous section. - - The State Machine API guarantees that a property assigned by the state machine either: - \list - \o Has a value explicitly assigned to the property. - \o Is currently being animated into a value explicitly assigned to the property. - \endlist - - When a state is exited prior to the animation finishing, the behavior of the state machine depends - on the target state of the transition. If the target state explicitly assigns a value to the - property, no additional action will be taken. The property will be assigned the value defined by - the target state. - - If the target state does not assign any value to the property, there are two - options: By default, the property will be assigned the value defined by the state it is leaving - (the value it would have been assigned if the animation had been permitted to finish playing.) If - a global restore policy is set, however, this will take precedence, and the property will be - restored as usual. - - \section1 Default Animations - - As described earlier, you can add animations to transitions to make sure property assignments - in the target state are animated. If you want a specific animation to be used for a given property - regardless of which transition is taken, you can add it as a default animation to the state - machine. This is in particular useful when the properties assigned (or restored) by specific - states is not known when the machine is constructed. - - \code - QState *s1 = new QState(); - QState *s2 = new QState(); - - s2->assignProperty(object, "fooBar", 2.0); - s1->addTransition(s2); - - QStateMachine machine; - machine.setInitialState(s1); - machine.addDefaultAnimation(new QPropertyAnimation(object, "fooBar")); - \endcode - - When the machine is in state \c s2, the machine will play the default animation for the - property \c fooBar since this property is assigned by \c s2. - - Note that animations explicitly set on transitions will take precedence over any default - animation for the given property. -*/ diff --git a/examples/animation/README b/examples/animation/README deleted file mode 100644 index 6a892f8..0000000 --- a/examples/animation/README +++ /dev/null @@ -1,38 +0,0 @@ -The animation framework aims to provide an easy way for creating animated and -smooth GUI's. By animating Qt properties, the framework provides great freedom -for animating widgets and other QObjects. The framework can also be used with -the Graphics View framework. - -The example launcher provided with Qt can be used to explore each of the -examples in this directory. - -Documentation for these examples can be found via the Tutorial and Examples -link in the main Qt documentation. - - -Finding the Qt Examples and Demos launcher -========================================== - -On Windows: - -The launcher can be accessed via the Windows Start menu. Select the menu -entry entitled "Qt Examples and Demos" entry in the submenu containing -the Qt tools. - -On Mac OS X: - -For the binary distribution, the qtdemo executable is installed in the -/Developer/Applications/Qt directory. For the source distribution, it is -installed alongside the other Qt tools on the path specified when Qt is -configured. - -On Unix/Linux: - -The qtdemo executable is installed alongside the other Qt tools on the path -specified when Qt is configured. - -On all platforms: - -The source code for the launcher can be found in the demos/qtdemo directory -in the Qt package. This example is built at the same time as the Qt libraries, -tools, examples, and demonstrations. diff --git a/examples/animation/animatedtiles/animatedtiles.pro b/examples/animation/animatedtiles/animatedtiles.pro deleted file mode 100644 index 1840b17..0000000 --- a/examples/animation/animatedtiles/animatedtiles.pro +++ /dev/null @@ -1,8 +0,0 @@ -SOURCES = main.cpp -RESOURCES = animatedtiles.qrc - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation/animatedtiles -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS animatedtiles.pro images -sources.path = $$[QT_INSTALL_EXAMPLES]/animation/animatedtiles -INSTALLS += target sources diff --git a/examples/animation/animatedtiles/animatedtiles.qrc b/examples/animation/animatedtiles/animatedtiles.qrc deleted file mode 100644 index c43a979..0000000 --- a/examples/animation/animatedtiles/animatedtiles.qrc +++ /dev/null @@ -1,11 +0,0 @@ - - - images/Time-For-Lunch-2.jpg - images/centered.png - images/ellipse.png - images/figure8.png - images/kinetic.png - images/random.png - images/tile.png - - diff --git a/examples/animation/animatedtiles/images/Time-For-Lunch-2.jpg b/examples/animation/animatedtiles/images/Time-For-Lunch-2.jpg deleted file mode 100644 index c57a555..0000000 Binary files a/examples/animation/animatedtiles/images/Time-For-Lunch-2.jpg and /dev/null differ diff --git a/examples/animation/animatedtiles/images/centered.png b/examples/animation/animatedtiles/images/centered.png deleted file mode 100644 index e416156..0000000 Binary files a/examples/animation/animatedtiles/images/centered.png and /dev/null differ diff --git a/examples/animation/animatedtiles/images/ellipse.png b/examples/animation/animatedtiles/images/ellipse.png deleted file mode 100644 index 2c3ba88..0000000 Binary files a/examples/animation/animatedtiles/images/ellipse.png and /dev/null differ diff --git a/examples/animation/animatedtiles/images/figure8.png b/examples/animation/animatedtiles/images/figure8.png deleted file mode 100644 index 6b05804..0000000 Binary files a/examples/animation/animatedtiles/images/figure8.png and /dev/null differ diff --git a/examples/animation/animatedtiles/images/kinetic.png b/examples/animation/animatedtiles/images/kinetic.png deleted file mode 100644 index 55cfa55..0000000 Binary files a/examples/animation/animatedtiles/images/kinetic.png and /dev/null differ diff --git a/examples/animation/animatedtiles/images/random.png b/examples/animation/animatedtiles/images/random.png deleted file mode 100644 index 415d96f..0000000 Binary files a/examples/animation/animatedtiles/images/random.png and /dev/null differ diff --git a/examples/animation/animatedtiles/images/tile.png b/examples/animation/animatedtiles/images/tile.png deleted file mode 100644 index c8f39d8..0000000 Binary files a/examples/animation/animatedtiles/images/tile.png and /dev/null differ diff --git a/examples/animation/animatedtiles/main.cpp b/examples/animation/animatedtiles/main.cpp deleted file mode 100644 index 4b1d99d..0000000 --- a/examples/animation/animatedtiles/main.cpp +++ /dev/null @@ -1,280 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include - -class Pixmap : public QObject, public QGraphicsPixmapItem -{ - Q_OBJECT - Q_PROPERTY(QPointF pos READ pos WRITE setPos) -public: - Pixmap(const QPixmap &pix) - : QObject(), QGraphicsPixmapItem(pix) - { - setCacheMode(DeviceCoordinateCache); - } -}; - -class Button : public QGraphicsWidget -{ - Q_OBJECT -public: - Button(const QPixmap &pixmap, QGraphicsItem *parent = 0) - : QGraphicsWidget(parent), _pix(pixmap) - { - setAcceptHoverEvents(true); - setCacheMode(DeviceCoordinateCache); - } - - QRectF boundingRect() const - { - return QRectF(-65, -65, 130, 130); - } - - QPainterPath shape() const - { - QPainterPath path; - path.addEllipse(boundingRect()); - return path; - } - - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *) - { - bool down = option->state & QStyle::State_Sunken; - QRectF r = boundingRect(); - QLinearGradient grad(r.topLeft(), r.bottomRight()); - grad.setColorAt(down ? 1 : 0, option->state & QStyle::State_MouseOver ? Qt::white : Qt::lightGray); - grad.setColorAt(down ? 0 : 1, Qt::darkGray); - painter->setPen(Qt::darkGray); - painter->setBrush(grad); - painter->drawEllipse(r); - QLinearGradient grad2(r.topLeft(), r.bottomRight()); - grad.setColorAt(down ? 1 : 0, Qt::darkGray); - grad.setColorAt(down ? 0 : 1, Qt::lightGray); - painter->setPen(Qt::NoPen); - painter->setBrush(grad); - if (down) - painter->translate(2, 2); - painter->drawEllipse(r.adjusted(5, 5, -5, -5)); - painter->drawPixmap(-_pix.width()/2, -_pix.height()/2, _pix); - } - -signals: - void pressed(); - -protected: - void mousePressEvent(QGraphicsSceneMouseEvent *) - { - emit pressed(); - update(); - } - - void mouseReleaseEvent(QGraphicsSceneMouseEvent *) - { - update(); - } - -private: - QPixmap _pix; -}; - -class View : public QGraphicsView -{ -public: - View(QGraphicsScene *scene) : QGraphicsView(scene) { } - -protected: - void resizeEvent(QResizeEvent *event) - { - QGraphicsView::resizeEvent(event); - fitInView(sceneRect(), Qt::KeepAspectRatio); - } -}; - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(animatedtiles); - - QApplication app(argc, argv); - - QPixmap kineticPix(":/images/kinetic.png"); - QPixmap bgPix(":/images/Time-For-Lunch-2.jpg"); - - QGraphicsScene scene(-350, -350, 700, 700); - - QList items; - for (int i = 0; i < 64; ++i) { - Pixmap *item = new Pixmap(kineticPix); - item->setOffset(-kineticPix.width()/2, -kineticPix.height()/2); - item->setZValue(i); - items << item; - scene.addItem(item); - } - - // Buttons - QGraphicsItem *buttonParent = new QGraphicsRectItem; - Button *ellipseButton = new Button(QPixmap(":/images/ellipse.png"), buttonParent); - Button *figure8Button = new Button(QPixmap(":/images/figure8.png"), buttonParent); - Button *randomButton = new Button(QPixmap(":/images/random.png"), buttonParent); - Button *tiledButton = new Button(QPixmap(":/images/tile.png"), buttonParent); - Button *centeredButton = new Button(QPixmap(":/images/centered.png"), buttonParent); - - ellipseButton->setPos(-100, -100); - figure8Button->setPos(100, -100); - randomButton->setPos(0, 0); - tiledButton->setPos(-100, 100); - centeredButton->setPos(100, 100); - - scene.addItem(buttonParent); - buttonParent->scale(0.75, 0.75); - buttonParent->setPos(200, 200); - buttonParent->setZValue(65); - - // States - QState *rootState = new QState; - QState *ellipseState = new QState(rootState); - QState *figure8State = new QState(rootState); - QState *randomState = new QState(rootState); - QState *tiledState = new QState(rootState); - QState *centeredState = new QState(rootState); - - // Values - for (int i = 0; i < 64; ++i) { - Pixmap *item = items.at(i); - // Ellipse - ellipseState->assignProperty(item, "pos", - QPointF(cos((i / 63.0) * 6.28) * 250, - sin((i / 63.0) * 6.28) * 250)); - - // Figure 8 - figure8State->assignProperty(item, "pos", - QPointF(sin((i / 63.0) * 6.28) * 250, - sin(((i * 2)/63.0) * 6.28) * 250)); - - // Random - randomState->assignProperty(item, "pos", - QPointF(-250 + qrand() % 500, - -250 + qrand() % 500)); - - // Tiled - tiledState->assignProperty(item, "pos", - QPointF(((i % 8) - 4) * kineticPix.width() + kineticPix.width() / 2, - ((i / 8) - 4) * kineticPix.height() + kineticPix.height() / 2)); - - // Centered - centeredState->assignProperty(item, "pos", QPointF()); - } - - // Ui - View *view = new View(&scene); - view->setWindowTitle(QT_TRANSLATE_NOOP(QGraphicsView, "Animated Tiles")); - view->setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); - view->setBackgroundBrush(bgPix); - view->setCacheMode(QGraphicsView::CacheBackground); - view->setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform); - view->show(); - - QStateMachine states; - states.addState(rootState); - states.setInitialState(rootState); - rootState->setInitialState(centeredState); - - QParallelAnimationGroup *group = new QParallelAnimationGroup; - for (int i = 0; i < 64; ++i) { - QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); - anim->setDuration(750 + i * 25); - anim->setEasingCurve(QEasingCurve::InOutBack); - group->addAnimation(anim); - } - QAbstractTransition *trans = rootState->addTransition(ellipseButton, SIGNAL(pressed()), ellipseState); - trans->addAnimation(group); - - group = new QParallelAnimationGroup; - for (int i = 0; i < 64; ++i) { - QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); - anim->setDuration(750 + i * 25); - anim->setEasingCurve(QEasingCurve::InOutBack); - group->addAnimation(anim); - } - trans = rootState->addTransition(figure8Button, SIGNAL(pressed()), figure8State); - trans->addAnimation(group); - - group = new QParallelAnimationGroup; - for (int i = 0; i < 64; ++i) { - QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); - anim->setDuration(750 + i * 25); - anim->setEasingCurve(QEasingCurve::InOutBack); - group->addAnimation(anim); - } - trans = rootState->addTransition(randomButton, SIGNAL(pressed()), randomState); - trans->addAnimation(group); - - group = new QParallelAnimationGroup; - for (int i = 0; i < 64; ++i) { - QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); - anim->setDuration(750 + i * 25); - anim->setEasingCurve(QEasingCurve::InOutBack); - group->addAnimation(anim); - } - trans = rootState->addTransition(tiledButton, SIGNAL(pressed()), tiledState); - trans->addAnimation(group); - - group = new QParallelAnimationGroup; - for (int i = 0; i < 64; ++i) { - QPropertyAnimation *anim = new QPropertyAnimation(items[i], "pos"); - anim->setDuration(750 + i * 25); - anim->setEasingCurve(QEasingCurve::InOutBack); - group->addAnimation(anim); - } - trans = rootState->addTransition(centeredButton, SIGNAL(pressed()), centeredState); - trans->addAnimation(group); - - states.start(); - QTimer timer; - timer.start(125); - timer.setSingleShot(true); - rootState->addTransition(&timer, SIGNAL(timeout()), ellipseState); - - return app.exec(); -} - -#include "main.moc" diff --git a/examples/animation/animation.pro b/examples/animation/animation.pro deleted file mode 100644 index 9a2874b..0000000 --- a/examples/animation/animation.pro +++ /dev/null @@ -1,16 +0,0 @@ -TEMPLATE = \ - subdirs -SUBDIRS += \ - animatedtiles \ - appchooser \ - easing \ - moveblocks \ - states \ - stickman \ - sub-attaq - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS animation.pro README -sources.path = $$[QT_INSTALL_EXAMPLES]/animation -INSTALLS += target sources diff --git a/examples/animation/appchooser/accessories-dictionary.png b/examples/animation/appchooser/accessories-dictionary.png deleted file mode 100644 index e9bd55d..0000000 Binary files a/examples/animation/appchooser/accessories-dictionary.png and /dev/null differ diff --git a/examples/animation/appchooser/akregator.png b/examples/animation/appchooser/akregator.png deleted file mode 100644 index a086f45..0000000 Binary files a/examples/animation/appchooser/akregator.png and /dev/null differ diff --git a/examples/animation/appchooser/appchooser.pro b/examples/animation/appchooser/appchooser.pro deleted file mode 100644 index 847b60a..0000000 --- a/examples/animation/appchooser/appchooser.pro +++ /dev/null @@ -1,8 +0,0 @@ -SOURCES = main.cpp -RESOURCES = appchooser.qrc - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation/appchooser -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS appchooser.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/animation/appchooser -INSTALLS += target sources diff --git a/examples/animation/appchooser/appchooser.qrc b/examples/animation/appchooser/appchooser.qrc deleted file mode 100644 index 28a3e1c..0000000 --- a/examples/animation/appchooser/appchooser.qrc +++ /dev/null @@ -1,8 +0,0 @@ - - - accessories-dictionary.png - akregator.png - digikam.png - k3b.png - - diff --git a/examples/animation/appchooser/digikam.png b/examples/animation/appchooser/digikam.png deleted file mode 100644 index 9de9fb2..0000000 Binary files a/examples/animation/appchooser/digikam.png and /dev/null differ diff --git a/examples/animation/appchooser/k3b.png b/examples/animation/appchooser/k3b.png deleted file mode 100644 index bbcafcf..0000000 Binary files a/examples/animation/appchooser/k3b.png and /dev/null differ diff --git a/examples/animation/appchooser/main.cpp b/examples/animation/appchooser/main.cpp deleted file mode 100644 index 44457f7..0000000 --- a/examples/animation/appchooser/main.cpp +++ /dev/null @@ -1,158 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include - - -class Pixmap : public QGraphicsWidget -{ - Q_OBJECT - -public: - Pixmap(const QPixmap &pix, QGraphicsItem *parent = 0) - : QGraphicsWidget(parent), orig(pix), p(pix) - { - } - - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) - { - painter->drawPixmap(QPointF(), p); - } - - virtual void mousePressEvent(QGraphicsSceneMouseEvent * ) - { - emit clicked(); - } - - virtual void setGeometry(const QRectF &rect) - { - QGraphicsWidget::setGeometry(rect); - - if (rect.size().width() > orig.size().width()) - p = orig.scaled(rect.size().toSize()); - else - p = orig; - } - -Q_SIGNALS: - void clicked(); - -private: - QPixmap orig; - QPixmap p; -}; - -void createStates(const QObjectList &objects, - const QRect &selectedRect, QState *parent) -{ - for (int i = 0; i < objects.size(); ++i) { - QState *state = new QState(parent); - state->assignProperty(objects.at(i), "geometry", selectedRect); - parent->addTransition(objects.at(i), SIGNAL(clicked()), state); - } -} - -void createAnimations(const QObjectList &objects, QStateMachine *machine) -{ - for (int i=0; iaddDefaultAnimation(new QPropertyAnimation(objects.at(i), "geometry")); -} - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(appchooser); - - QApplication app(argc, argv); - - Pixmap *p1 = new Pixmap(QPixmap(":/digikam.png")); - Pixmap *p2 = new Pixmap(QPixmap(":/akregator.png")); - Pixmap *p3 = new Pixmap(QPixmap(":/accessories-dictionary.png")); - Pixmap *p4 = new Pixmap(QPixmap(":/k3b.png")); - - p1->setObjectName("p1"); - p2->setObjectName("p2"); - p3->setObjectName("p3"); - p4->setObjectName("p4"); - - p1->setGeometry(QRectF(0.0, 0.0, 64.0, 64.0)); - p2->setGeometry(QRectF(236.0, 0.0, 64.0, 64.0)); - p3->setGeometry(QRectF(236.0, 236.0, 64.0, 64.0)); - p4->setGeometry(QRectF(0.0, 236.0, 64.0, 64.0)); - - QGraphicsScene scene(0, 0, 300, 300); - scene.setBackgroundBrush(Qt::white); - scene.addItem(p1); - scene.addItem(p2); - scene.addItem(p3); - scene.addItem(p4); - - QGraphicsView window(&scene); - window.setFrameStyle(0); - window.setAlignment(Qt::AlignLeft | Qt::AlignTop); - window.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - window.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - - QState *group = new QState(machine.rootState()); - group->setObjectName("group"); - QRect selectedRect(86, 86, 128, 128); - - QState *idleState = new QState(group); - group->setInitialState(idleState); - - QObjectList objects; - objects << p1 << p2 << p3 << p4; - createStates(objects, selectedRect, group); - createAnimations(objects, &machine); - - machine.setInitialState(group); - machine.start(); - - window.resize(300, 300); - window.show(); - - return app.exec(); -} - -#include "main.moc" diff --git a/examples/animation/easing/animation.h b/examples/animation/easing/animation.h deleted file mode 100644 index d4d699d..0000000 --- a/examples/animation/easing/animation.h +++ /dev/null @@ -1,101 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ANIMATION_H -#define ANIMATION_H - -#include - -#include - -class Animation : public QPropertyAnimation { -public: - enum PathType { - LinearPath, - CirclePath, - NPathTypes - }; - Animation(QObject *target, const QByteArray &prop) - : QPropertyAnimation(target, prop) - { - setPathType(LinearPath); - } - - void setPathType(PathType pathType) - { - if (pathType >= NPathTypes) - qWarning("Unknown pathType %d", pathType); - - m_pathType = pathType; - m_path = QPainterPath(); - } - - void updateCurrentTime(int msecs) - { - if (m_pathType == CirclePath) { - if (m_path.isEmpty()) { - QPointF to = endValue().toPointF(); - QPointF from = startValue().toPointF(); - m_path.moveTo(from); - m_path.addEllipse(QRectF(from, to)); - } - int dura = duration(); - const qreal progress = ((dura == 0) ? 1 : ((((currentTime() - 1) % dura) + 1) / qreal(dura))); - - qreal easedProgress = easingCurve().valueForProgress(progress); - if (easedProgress > 1.0) { - easedProgress -= 1.0; - } else if (easedProgress < 0) { - easedProgress += 1.0; - } - QPointF pt = m_path.pointAtPercent(easedProgress); - updateCurrentValue(pt); - emit valueChanged(pt); - } else { - QPropertyAnimation::updateCurrentTime(msecs); - } - } - - QPainterPath m_path; - PathType m_pathType; -}; - -#endif // ANIMATION_H diff --git a/examples/animation/easing/easing.pro b/examples/animation/easing/easing.pro deleted file mode 100644 index 8e8a35f..0000000 --- a/examples/animation/easing/easing.pro +++ /dev/null @@ -1,14 +0,0 @@ -HEADERS = window.h \ - animation.h -SOURCES = main.cpp \ - window.cpp - -FORMS = form.ui - -RESOURCES = easing.qrc - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation/easing -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS easing.pro images -sources.path = $$[QT_INSTALL_EXAMPLES]/animation/easing -INSTALLS += target sources diff --git a/examples/animation/easing/easing.qrc b/examples/animation/easing/easing.qrc deleted file mode 100644 index 7e112d3..0000000 --- a/examples/animation/easing/easing.qrc +++ /dev/null @@ -1,5 +0,0 @@ - - - images/qt-logo.png - - \ No newline at end of file diff --git a/examples/animation/easing/form.ui b/examples/animation/easing/form.ui deleted file mode 100644 index b60ade8..0000000 --- a/examples/animation/easing/form.ui +++ /dev/null @@ -1,201 +0,0 @@ - - - Form - - - - 0 - 0 - 545 - 471 - - - - Easing curves - - - - - - - 0 - 0 - - - - - 16777215 - 120 - - - - Qt::ScrollBarAlwaysOff - - - QListView::Static - - - false - - - QListView::IconMode - - - false - - - - - - - - - Path type - - - - - - Line - - - true - - - buttonGroup - - - - - - - Circle - - - buttonGroup - - - - - - - - - - - 0 - 0 - - - - Properties - - - - QFormLayout::AllNonFixedFieldsGrow - - - - - Period - - - - - - - false - - - -1.000000000000000 - - - 0.100000000000000 - - - -1.000000000000000 - - - - - - - Amplitude - - - - - - - false - - - -1.000000000000000 - - - 0.100000000000000 - - - -1.000000000000000 - - - - - - - Overshoot - - - - - - - false - - - -1.000000000000000 - - - 0.100000000000000 - - - -1.000000000000000 - - - - - - - - - - Qt::Vertical - - - - 20 - 40 - - - - - - - - - - - 0 - 0 - - - - - - - - - - - - diff --git a/examples/animation/easing/images/qt-logo.png b/examples/animation/easing/images/qt-logo.png deleted file mode 100644 index 14ddf2a..0000000 Binary files a/examples/animation/easing/images/qt-logo.png and /dev/null differ diff --git a/examples/animation/easing/main.cpp b/examples/animation/easing/main.cpp deleted file mode 100644 index bd10df2..0000000 --- a/examples/animation/easing/main.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "window.h" - -int main(int argc, char **argv) -{ - Q_INIT_RESOURCE(easing); - QApplication app(argc, argv); - Window w; - w.resize(400, 400); - w.show(); - return app.exec(); -} diff --git a/examples/animation/easing/window.cpp b/examples/animation/easing/window.cpp deleted file mode 100644 index cf4be15..0000000 --- a/examples/animation/easing/window.cpp +++ /dev/null @@ -1,163 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "window.h" - -Window::Window(QWidget *parent) - : QWidget(parent), m_iconSize(64, 64) -{ - m_ui.setupUi(this); - QButtonGroup *buttonGroup = qFindChild(this); // ### workaround for uic in 4.4 - m_ui.easingCurvePicker->setIconSize(m_iconSize); - m_ui.easingCurvePicker->setMinimumHeight(m_iconSize.height() + 50); - buttonGroup->setId(m_ui.lineRadio, 0); - buttonGroup->setId(m_ui.circleRadio, 1); - - QEasingCurve dummy; - m_ui.periodSpinBox->setValue(dummy.period()); - m_ui.amplitudeSpinBox->setValue(dummy.amplitude()); - m_ui.overshootSpinBox->setValue(dummy.overshoot()); - - connect(m_ui.easingCurvePicker, SIGNAL(currentRowChanged(int)), this, SLOT(curveChanged(int))); - connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(pathChanged(int))); - connect(m_ui.periodSpinBox, SIGNAL(valueChanged(double)), this, SLOT(periodChanged(double))); - connect(m_ui.amplitudeSpinBox, SIGNAL(valueChanged(double)), this, SLOT(amplitudeChanged(double))); - connect(m_ui.overshootSpinBox, SIGNAL(valueChanged(double)), this, SLOT(overshootChanged(double))); - createCurveIcons(); - - QPixmap pix(QLatin1String(":/images/qt-logo.png")); - m_item = new PixmapItem(pix); - m_scene.addItem(m_item); - m_ui.graphicsView->setScene(&m_scene); - - m_anim = new Animation(m_item, "pos"); - m_anim->setEasingCurve(QEasingCurve::OutBounce); - m_ui.easingCurvePicker->setCurrentRow(int(QEasingCurve::OutBounce)); - - startAnimation(); -} - -void Window::createCurveIcons() -{ - QPixmap pix(m_iconSize); - QPainter painter(&pix); - QLinearGradient gradient(0,0, 0, m_iconSize.height()); - gradient.setColorAt(0.0, QColor(240, 240, 240)); - gradient.setColorAt(1.0, QColor(224, 224, 224)); - QBrush brush(gradient); - const QMetaObject &mo = QEasingCurve::staticMetaObject; - QMetaEnum metaEnum = mo.enumerator(mo.indexOfEnumerator("Type")); - // Skip QEasingCurve::Custom - for (int i = 0; i < QEasingCurve::NCurveTypes - 1; ++i) { - painter.fillRect(QRect(QPoint(0, 0), m_iconSize), brush); - QEasingCurve curve((QEasingCurve::Type)i); - painter.setPen(QColor(0, 0, 255, 64)); - qreal xAxis = m_iconSize.height()/1.5; - qreal yAxis = m_iconSize.width()/3; - painter.drawLine(0, xAxis, m_iconSize.width(), xAxis); - painter.drawLine(yAxis, 0, yAxis, m_iconSize.height()); - painter.setPen(Qt::black); - - qreal curveScale = m_iconSize.height()/2; - QPoint currentPos(yAxis, xAxis); - - for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { - QPoint to; - to.setX(yAxis + curveScale * t); - to.setY(xAxis - curveScale * curve.valueForProgress(t)); - painter.drawLine(currentPos, to); - currentPos = to; - } - QListWidgetItem *item = new QListWidgetItem; - item->setIcon(QIcon(pix)); - item->setText(metaEnum.key(i)); - m_ui.easingCurvePicker->addItem(item); - } -} - -void Window::startAnimation() -{ - m_anim->setStartValue(QPointF(0, 0)); - m_anim->setEndValue(QPointF(100, 100)); - m_anim->setDuration(2000); - m_anim->setLoopCount(-1); // forever - m_anim->start(); -} - -void Window::curveChanged(int row) -{ - QEasingCurve::Type curveType = (QEasingCurve::Type)row; - m_anim->setEasingCurve(curveType); - m_anim->setCurrentTime(0); - - bool isElastic = curveType >= QEasingCurve::InElastic && curveType <= QEasingCurve::OutInElastic; - bool isBounce = curveType >= QEasingCurve::InBounce && curveType <= QEasingCurve::OutInBounce; - m_ui.periodSpinBox->setEnabled(isElastic); - m_ui.amplitudeSpinBox->setEnabled(isElastic || isBounce); - m_ui.overshootSpinBox->setEnabled(curveType >= QEasingCurve::InBack && curveType <= QEasingCurve::OutInBack); -} - -void Window::pathChanged(int index) -{ - m_anim->setPathType((Animation::PathType)index); -} - -void Window::periodChanged(double value) -{ - QEasingCurve curve = m_anim->easingCurve(); - curve.setPeriod(value); - m_anim->setEasingCurve(curve); -} - -void Window::amplitudeChanged(double value) -{ - QEasingCurve curve = m_anim->easingCurve(); - curve.setAmplitude(value); - m_anim->setEasingCurve(curve); -} - -void Window::overshootChanged(double value) -{ - QEasingCurve curve = m_anim->easingCurve(); - curve.setOvershoot(value); - m_anim->setEasingCurve(curve); -} - diff --git a/examples/animation/easing/window.h b/examples/animation/easing/window.h deleted file mode 100644 index f3a8cb3..0000000 --- a/examples/animation/easing/window.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include "ui_form.h" -#include "animation.h" - -class PixmapItem : public QObject, public QGraphicsPixmapItem -{ - Q_OBJECT - Q_PROPERTY(QPointF pos READ pos WRITE setPos) -public: - PixmapItem(const QPixmap &pix) : QGraphicsPixmapItem(pix) - { - } -}; - -class Window : public QWidget { - Q_OBJECT -public: - Window(QWidget *parent = 0); -private slots: - void curveChanged(int row); - void pathChanged(int index); - void periodChanged(double); - void amplitudeChanged(double); - void overshootChanged(double); - -private: - void createCurveIcons(); - void startAnimation(); - - Ui::Form m_ui; - QGraphicsScene m_scene; - PixmapItem *m_item; - Animation *m_anim; - QSize m_iconSize; - - -}; diff --git a/examples/animation/moveblocks/main.cpp b/examples/animation/moveblocks/main.cpp deleted file mode 100644 index b00485e..0000000 --- a/examples/animation/moveblocks/main.cpp +++ /dev/null @@ -1,296 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include - -class StateSwitchEvent: public QEvent -{ -public: - StateSwitchEvent() - : QEvent(Type(StateSwitchType)) - { - } - - StateSwitchEvent(int rand) - : QEvent(Type(StateSwitchType)), - m_rand(rand) - { - } - - enum { StateSwitchType = QEvent::User + 256 }; - - int rand() const { return m_rand; } - -private: - int m_rand; -}; - - -class QGraphicsRectWidget : public QGraphicsWidget -{ -public: - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, - QWidget *) - { - painter->fillRect(rect(), Qt::blue); - } -}; - -class StateSwitchTransition: public QAbstractTransition -{ -public: - StateSwitchTransition(int rand) - : QAbstractTransition(), - m_rand(rand) - { - } - -protected: - virtual bool eventTest(QEvent *event) - { - return (event->type() == QEvent::Type(StateSwitchEvent::StateSwitchType)) - && (static_cast(event)->rand() == m_rand); - } - - virtual void onTransition(QEvent *) {} - -private: - int m_rand; -}; - -class StateSwitcher : public QState -{ - Q_OBJECT -public: - StateSwitcher(QStateMachine *machine) - : QState(machine->rootState()), m_machine(machine), - m_stateCount(0), m_lastIndex(0) - { } - - virtual void onEntry(QEvent *) - { - int n; - while ((n = (qrand() % m_stateCount + 1)) == m_lastIndex) - { } - m_lastIndex = n; - m_machine->postEvent(new StateSwitchEvent(n)); - } - virtual void onExit(QEvent *) {} - - void addState(QState *state, QAbstractAnimation *animation) { - StateSwitchTransition *trans = new StateSwitchTransition(++m_stateCount); - trans->setTargetState(state); - addTransition(trans); - trans->addAnimation(animation); - } - - -private: - QStateMachine *m_machine; - int m_stateCount; - int m_lastIndex; -}; - -QState *createGeometryState(QObject *w1, const QRect &rect1, - QObject *w2, const QRect &rect2, - QObject *w3, const QRect &rect3, - QObject *w4, const QRect &rect4, - QState *parent) -{ - QState *result = new QState(parent); - result->assignProperty(w1, "geometry", rect1); - result->assignProperty(w1, "geometry", rect1); - result->assignProperty(w2, "geometry", rect2); - result->assignProperty(w3, "geometry", rect3); - result->assignProperty(w4, "geometry", rect4); - - return result; -} - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - -#if 0 - QWidget window; - QPalette palette; - palette.setBrush(QPalette::Window, Qt::black); - window.setPalette(palette); - QPushButton *button1 = new QPushButton("A", &window); - QPushButton *button2 = new QPushButton("B", &window); - QPushButton *button3 = new QPushButton("C", &window); - QPushButton *button4 = new QPushButton("D", &window); - - button1->setObjectName("button1"); - button2->setObjectName("button2"); - button3->setObjectName("button3"); - button4->setObjectName("button4"); -#else - QGraphicsRectWidget *button1 = new QGraphicsRectWidget; - QGraphicsRectWidget *button2 = new QGraphicsRectWidget; - QGraphicsRectWidget *button3 = new QGraphicsRectWidget; - QGraphicsRectWidget *button4 = new QGraphicsRectWidget; - button2->setZValue(1); - button3->setZValue(2); - button4->setZValue(3); - QGraphicsScene scene(0, 0, 300, 300); - scene.setBackgroundBrush(Qt::black); - scene.addItem(button1); - scene.addItem(button2); - scene.addItem(button3); - scene.addItem(button4); - - QGraphicsView window(&scene); - window.setFrameStyle(0); - window.setAlignment(Qt::AlignLeft | Qt::AlignTop); - window.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - window.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); -#endif - QStateMachine machine; - - QState *group = new QState(); - group->setObjectName("group"); - QTimer timer; - timer.setInterval(1250); - timer.setSingleShot(true); - QObject::connect(group, SIGNAL(entered()), &timer, SLOT(start())); - - QState *state1; - QState *state2; - QState *state3; - QState *state4; - QState *state5; - QState *state6; - QState *state7; - - state1 = createGeometryState(button1, QRect(100, 0, 50, 50), - button2, QRect(150, 0, 50, 50), - button3, QRect(200, 0, 50, 50), - button4, QRect(250, 0, 50, 50), - group); - state2 = createGeometryState(button1, QRect(250, 100, 50, 50), - button2, QRect(250, 150, 50, 50), - button3, QRect(250, 200, 50, 50), - button4, QRect(250, 250, 50, 50), - group); - state3 = createGeometryState(button1, QRect(150, 250, 50, 50), - button2, QRect(100, 250, 50, 50), - button3, QRect(50, 250, 50, 50), - button4, QRect(0, 250, 50, 50), - group); - state4 = createGeometryState(button1, QRect(0, 150, 50, 50), - button2, QRect(0, 100, 50, 50), - button3, QRect(0, 50, 50, 50), - button4, QRect(0, 0, 50, 50), - group); - state5 = createGeometryState(button1, QRect(100, 100, 50, 50), - button2, QRect(150, 100, 50, 50), - button3, QRect(100, 150, 50, 50), - button4, QRect(150, 150, 50, 50), - group); - state6 = createGeometryState(button1, QRect(50, 50, 50, 50), - button2, QRect(200, 50, 50, 50), - button3, QRect(50, 200, 50, 50), - button4, QRect(200, 200, 50, 50), - group); - state7 = createGeometryState(button1, QRect(0, 0, 50, 50), - button2, QRect(250, 0, 50, 50), - button3, QRect(0, 250, 50, 50), - button4, QRect(250, 250, 50, 50), - group); - group->setInitialState(state1); - - QParallelAnimationGroup animationGroup; - QSequentialAnimationGroup *subGroup; - - QPropertyAnimation *anim = new QPropertyAnimation(button4, "geometry"); - anim->setDuration(1000); - anim->setEasingCurve(QEasingCurve::OutElastic); - animationGroup.addAnimation(anim); - - subGroup = new QSequentialAnimationGroup(&animationGroup); - subGroup->addPause(100); - anim = new QPropertyAnimation(button3, "geometry"); - anim->setDuration(1000); - anim->setEasingCurve(QEasingCurve::OutElastic); - subGroup->addAnimation(anim); - - subGroup = new QSequentialAnimationGroup(&animationGroup); - subGroup->addPause(150); - anim = new QPropertyAnimation(button2, "geometry"); - anim->setDuration(1000); - anim->setEasingCurve(QEasingCurve::OutElastic); - subGroup->addAnimation(anim); - - subGroup = new QSequentialAnimationGroup(&animationGroup); - subGroup->addPause(200); - anim = new QPropertyAnimation(button1, "geometry"); - anim->setDuration(1000); - anim->setEasingCurve(QEasingCurve::OutElastic); - subGroup->addAnimation(anim); - - StateSwitcher *stateSwitcher = new StateSwitcher(&machine); - stateSwitcher->setObjectName("stateSwitcher"); - group->addTransition(&timer, SIGNAL(timeout()), stateSwitcher); - stateSwitcher->addState(state1, &animationGroup); - stateSwitcher->addState(state2, &animationGroup); - stateSwitcher->addState(state3, &animationGroup); - stateSwitcher->addState(state4, &animationGroup); - stateSwitcher->addState(state5, &animationGroup); - stateSwitcher->addState(state6, &animationGroup); - stateSwitcher->addState(state7, &animationGroup); - - machine.addState(group); - machine.setInitialState(group); - machine.start(); - - - window.resize(300, 300); - window.show(); - - qsrand(time(0)); - - return app.exec(); -} - -#include "main.moc" diff --git a/examples/animation/moveblocks/moveblocks.pro b/examples/animation/moveblocks/moveblocks.pro deleted file mode 100644 index b8e88b2..0000000 --- a/examples/animation/moveblocks/moveblocks.pro +++ /dev/null @@ -1,7 +0,0 @@ -SOURCES = main.cpp - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation/moveblocks -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS moveblocks.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/animation/moveblocks -INSTALLS += target sources diff --git a/examples/animation/states/accessories-dictionary.png b/examples/animation/states/accessories-dictionary.png deleted file mode 100644 index e9bd55d..0000000 Binary files a/examples/animation/states/accessories-dictionary.png and /dev/null differ diff --git a/examples/animation/states/akregator.png b/examples/animation/states/akregator.png deleted file mode 100644 index a086f45..0000000 Binary files a/examples/animation/states/akregator.png and /dev/null differ diff --git a/examples/animation/states/digikam.png b/examples/animation/states/digikam.png deleted file mode 100644 index 9de9fb2..0000000 Binary files a/examples/animation/states/digikam.png and /dev/null differ diff --git a/examples/animation/states/help-browser.png b/examples/animation/states/help-browser.png deleted file mode 100644 index db92faa..0000000 Binary files a/examples/animation/states/help-browser.png and /dev/null differ diff --git a/examples/animation/states/k3b.png b/examples/animation/states/k3b.png deleted file mode 100644 index bbcafcf..0000000 Binary files a/examples/animation/states/k3b.png and /dev/null differ diff --git a/examples/animation/states/kchart.png b/examples/animation/states/kchart.png deleted file mode 100644 index 1dd115b..0000000 Binary files a/examples/animation/states/kchart.png and /dev/null differ diff --git a/examples/animation/states/main.cpp b/examples/animation/states/main.cpp deleted file mode 100644 index 17a7a8e..0000000 --- a/examples/animation/states/main.cpp +++ /dev/null @@ -1,284 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -class Pixmap : public QGraphicsWidget -{ - Q_OBJECT -public: - Pixmap(const QPixmap &pix) : QGraphicsWidget(), p(pix) - { - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - } - - void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) - { - painter->drawPixmap(QPointF(), p); - } - -protected: - QSizeF sizeHint(Qt::SizeHint, const QSizeF & = QSizeF()) - { - return QSizeF(p.width(), p.height()); - } - -private: - QPixmap p; -}; - -int main(int argc, char *argv[]) -{ - Q_INIT_RESOURCE(states); - - QApplication app(argc, argv); - - // Text edit and button - QTextEdit *edit = new QTextEdit; - edit->setText("asdf lkjha yuoiqwe asd iuaysd u iasyd uiy " - "asdf lkjha yuoiqwe asd iuaysd u iasyd uiy " - "asdf lkjha yuoiqwe asd iuaysd u iasyd uiy " - "asdf lkjha yuoiqwe asd iuaysd u iasyd uiy!"); - - QPushButton *button = new QPushButton; - QGraphicsProxyWidget *buttonProxy = new QGraphicsProxyWidget; - buttonProxy->setWidget(button); - QGraphicsProxyWidget *editProxy = new QGraphicsProxyWidget; - editProxy->setWidget(edit); - - QGroupBox *box = new QGroupBox; - box->setFlat(true); - box->setTitle("Options"); - - QVBoxLayout *layout2 = new QVBoxLayout; - box->setLayout(layout2); - layout2->addWidget(new QRadioButton("Herring")); - layout2->addWidget(new QRadioButton("Blue Parrot")); - layout2->addWidget(new QRadioButton("Petunias")); - layout2->addStretch(); - - QGraphicsProxyWidget *boxProxy = new QGraphicsProxyWidget; - boxProxy->setWidget(box); - - // Parent widget - QGraphicsWidget *widget = new QGraphicsWidget; - QGraphicsLinearLayout *layout = new QGraphicsLinearLayout(Qt::Vertical, widget); - layout->addItem(editProxy); - layout->addItem(buttonProxy); - widget->setLayout(layout); - - Pixmap *p1 = new Pixmap(QPixmap(":/digikam.png")); - Pixmap *p2 = new Pixmap(QPixmap(":/akregator.png")); - Pixmap *p3 = new Pixmap(QPixmap(":/accessories-dictionary.png")); - Pixmap *p4 = new Pixmap(QPixmap(":/k3b.png")); - Pixmap *p5 = new Pixmap(QPixmap(":/help-browser.png")); - Pixmap *p6 = new Pixmap(QPixmap(":/kchart.png")); - - QGraphicsScene scene(0, 0, 400, 300); - scene.setBackgroundBrush(scene.palette().window()); - scene.addItem(widget); - scene.addItem(boxProxy); - scene.addItem(p1); - scene.addItem(p2); - scene.addItem(p3); - scene.addItem(p4); - scene.addItem(p5); - scene.addItem(p6); - - QStateMachine machine; - QState *root = machine.rootState(); - QState *state1 = new QState(root); - QState *state2 = new QState(root); - QState *state3 = new QState(root); - machine.setInitialState(state1); - - // State 1 - state1->assignProperty(button, "text", "Switch to state 2"); - state1->assignProperty(widget, "geometry", QRectF(0, 0, 400, 150)); - state1->assignProperty(box, "geometry", QRect(-200, 150, 200, 150)); - state1->assignProperty(p1, "geometry", QRectF(68, 185, 64, 64)); - state1->assignProperty(p2, "geometry", QRectF(168, 185, 64, 64)); - state1->assignProperty(p3, "geometry", QRectF(268, 185, 64, 64)); - state1->assignProperty(p4, "geometry", QRectF(68-150, 48-150, 64, 64)); - state1->assignProperty(p5, "geometry", QRectF(168, 48-150, 64, 64)); - state1->assignProperty(p6, "geometry", QRectF(268+150, 48-150, 64, 64)); - state1->assignProperty(p1, "zRotation", qreal(0)); - state1->assignProperty(p2, "zRotation", qreal(0)); - state1->assignProperty(p3, "zRotation", qreal(0)); - state1->assignProperty(p4, "zRotation", qreal(-270)); - state1->assignProperty(p5, "zRotation", qreal(-90)); - state1->assignProperty(p6, "zRotation", qreal(270)); - state1->assignProperty(boxProxy, "opacity", qreal(0)); - state1->assignProperty(p1, "opacity", qreal(1)); - state1->assignProperty(p2, "opacity", qreal(1)); - state1->assignProperty(p3, "opacity", qreal(1)); - state1->assignProperty(p4, "opacity", qreal(0)); - state1->assignProperty(p5, "opacity", qreal(0)); - state1->assignProperty(p6, "opacity", qreal(0)); - - // State 2 - state2->assignProperty(button, "text", "Switch to state 3"); - state2->assignProperty(widget, "geometry", QRectF(200, 150, 200, 150)); - state2->assignProperty(box, "geometry", QRect(9, 150, 190, 150)); - state2->assignProperty(p1, "geometry", QRectF(68-150, 185+150, 64, 64)); - state2->assignProperty(p2, "geometry", QRectF(168, 185+150, 64, 64)); - state2->assignProperty(p3, "geometry", QRectF(268+150, 185+150, 64, 64)); - state2->assignProperty(p4, "geometry", QRectF(64, 48, 64, 64)); - state2->assignProperty(p5, "geometry", QRectF(168, 48, 64, 64)); - state2->assignProperty(p6, "geometry", QRectF(268, 48, 64, 64)); - state2->assignProperty(p1, "zRotation", qreal(-270)); - state2->assignProperty(p2, "zRotation", qreal(90)); - state2->assignProperty(p3, "zRotation", qreal(270)); - state2->assignProperty(p4, "zRotation", qreal(0)); - state2->assignProperty(p5, "zRotation", qreal(0)); - state2->assignProperty(p6, "zRotation", qreal(0)); - state2->assignProperty(boxProxy, "opacity", qreal(1)); - state2->assignProperty(p1, "opacity", qreal(0)); - state2->assignProperty(p2, "opacity", qreal(0)); - state2->assignProperty(p3, "opacity", qreal(0)); - state2->assignProperty(p4, "opacity", qreal(1)); - state2->assignProperty(p5, "opacity", qreal(1)); - state2->assignProperty(p6, "opacity", qreal(1)); - - // State 3 - state3->assignProperty(button, "text", "Switch to state 1"); - state3->assignProperty(p1, "geometry", QRectF(5, 5, 64, 64)); - state3->assignProperty(p2, "geometry", QRectF(5, 5 + 64 + 5, 64, 64)); - state3->assignProperty(p3, "geometry", QRectF(5, 5 + (64 + 5) + 64, 64, 64)); - state3->assignProperty(p4, "geometry", QRectF(5 + 64 + 5, 5, 64, 64)); - state3->assignProperty(p5, "geometry", QRectF(5 + 64 + 5, 5 + 64 + 5, 64, 64)); - state3->assignProperty(p6, "geometry", QRectF(5 + 64 + 5, 5 + (64 + 5) + 64, 64, 64)); - state3->assignProperty(widget, "geometry", QRectF(138, 5, 400 - 138, 200)); - state3->assignProperty(box, "geometry", QRect(5, 205, 400, 90)); - state3->assignProperty(p1, "opacity", qreal(1)); - state3->assignProperty(p2, "opacity", qreal(1)); - state3->assignProperty(p3, "opacity", qreal(1)); - state3->assignProperty(p4, "opacity", qreal(1)); - state3->assignProperty(p5, "opacity", qreal(1)); - state3->assignProperty(p6, "opacity", qreal(1)); - - QParallelAnimationGroup animation1; - - QSequentialAnimationGroup *animation1SubGroup; - animation1SubGroup = new QSequentialAnimationGroup(&animation1); - animation1SubGroup->addPause(250); - animation1SubGroup->addAnimation(new QPropertyAnimation(box, "geometry")); - - animation1.addAnimation(new QPropertyAnimation(widget, "geometry")); - animation1.addAnimation(new QPropertyAnimation(p1, "geometry")); - animation1.addAnimation(new QPropertyAnimation(p2, "geometry")); - animation1.addAnimation(new QPropertyAnimation(p3, "geometry")); - animation1.addAnimation(new QPropertyAnimation(p4, "geometry")); - animation1.addAnimation(new QPropertyAnimation(p5, "geometry")); - animation1.addAnimation(new QPropertyAnimation(p6, "geometry")); - animation1.addAnimation(new QPropertyAnimation(p1, "zRotation")); - animation1.addAnimation(new QPropertyAnimation(p2, "zRotation")); - animation1.addAnimation(new QPropertyAnimation(p3, "zRotation")); - animation1.addAnimation(new QPropertyAnimation(p4, "zRotation")); - animation1.addAnimation(new QPropertyAnimation(p5, "zRotation")); - animation1.addAnimation(new QPropertyAnimation(p6, "zRotation")); - animation1.addAnimation(new QPropertyAnimation(p1, "opacity")); - animation1.addAnimation(new QPropertyAnimation(p2, "opacity")); - animation1.addAnimation(new QPropertyAnimation(p3, "opacity")); - animation1.addAnimation(new QPropertyAnimation(p4, "opacity")); - animation1.addAnimation(new QPropertyAnimation(p5, "opacity")); - animation1.addAnimation(new QPropertyAnimation(p6, "opacity")); - - QParallelAnimationGroup animation2; - animation2.addAnimation(new QPropertyAnimation(box, "geometry")); - animation2.addAnimation(new QPropertyAnimation(widget, "geometry")); - animation2.addAnimation(new QPropertyAnimation(p1, "geometry")); - animation2.addAnimation(new QPropertyAnimation(p2, "geometry")); - animation2.addAnimation(new QPropertyAnimation(p3, "geometry")); - animation2.addAnimation(new QPropertyAnimation(p4, "geometry")); - animation2.addAnimation(new QPropertyAnimation(p5, "geometry")); - animation2.addAnimation(new QPropertyAnimation(p6, "geometry")); - animation2.addAnimation(new QPropertyAnimation(p1, "zRotation")); - animation2.addAnimation(new QPropertyAnimation(p2, "zRotation")); - animation2.addAnimation(new QPropertyAnimation(p3, "zRotation")); - animation2.addAnimation(new QPropertyAnimation(p4, "zRotation")); - animation2.addAnimation(new QPropertyAnimation(p5, "zRotation")); - animation2.addAnimation(new QPropertyAnimation(p6, "zRotation")); - animation2.addAnimation(new QPropertyAnimation(p1, "opacity")); - animation2.addAnimation(new QPropertyAnimation(p2, "opacity")); - animation2.addAnimation(new QPropertyAnimation(p3, "opacity")); - animation2.addAnimation(new QPropertyAnimation(p4, "opacity")); - animation2.addAnimation(new QPropertyAnimation(p5, "opacity")); - animation2.addAnimation(new QPropertyAnimation(p6, "opacity")); - - QParallelAnimationGroup animation3; - animation3.addAnimation(new QPropertyAnimation(box, "geometry")); - animation3.addAnimation(new QPropertyAnimation(widget, "geometry")); - animation3.addAnimation(new QPropertyAnimation(p1, "geometry")); - animation3.addAnimation(new QPropertyAnimation(p2, "geometry")); - animation3.addAnimation(new QPropertyAnimation(p3, "geometry")); - animation3.addAnimation(new QPropertyAnimation(p4, "geometry")); - animation3.addAnimation(new QPropertyAnimation(p5, "geometry")); - animation3.addAnimation(new QPropertyAnimation(p6, "geometry")); - animation3.addAnimation(new QPropertyAnimation(p1, "zRotation")); - animation3.addAnimation(new QPropertyAnimation(p2, "zRotation")); - animation3.addAnimation(new QPropertyAnimation(p3, "zRotation")); - animation3.addAnimation(new QPropertyAnimation(p4, "zRotation")); - animation3.addAnimation(new QPropertyAnimation(p5, "zRotation")); - animation3.addAnimation(new QPropertyAnimation(p6, "zRotation")); - animation3.addAnimation(new QPropertyAnimation(p1, "opacity")); - animation3.addAnimation(new QPropertyAnimation(p2, "opacity")); - animation3.addAnimation(new QPropertyAnimation(p3, "opacity")); - animation3.addAnimation(new QPropertyAnimation(p4, "opacity")); - animation3.addAnimation(new QPropertyAnimation(p5, "opacity")); - animation3.addAnimation(new QPropertyAnimation(p6, "opacity")); - - QAbstractTransition *t1 = state1->addTransition(button, SIGNAL(clicked()), state2); - t1->addAnimation(&animation1); - QAbstractTransition *t2 = state2->addTransition(button, SIGNAL(clicked()), state3); - t2->addAnimation(&animation2); - QAbstractTransition *t3 = state3->addTransition(button, SIGNAL(clicked()), state1); - t3->addAnimation(&animation3); - - machine.start(); - - QGraphicsView view(&scene); - view.show(); - - return app.exec(); -} - -#include "main.moc" diff --git a/examples/animation/states/states.pro b/examples/animation/states/states.pro deleted file mode 100644 index f4d1e0b..0000000 --- a/examples/animation/states/states.pro +++ /dev/null @@ -1,8 +0,0 @@ -SOURCES += main.cpp -RESOURCES += states.qrc - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation/states -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS states.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/animation/states -INSTALLS += target sources diff --git a/examples/animation/states/states.qrc b/examples/animation/states/states.qrc deleted file mode 100644 index 60ab3f7..0000000 --- a/examples/animation/states/states.qrc +++ /dev/null @@ -1,10 +0,0 @@ - - - accessories-dictionary.png - akregator.png - digikam.png - help-browser.png - k3b.png - kchart.png - - diff --git a/examples/animation/stickman/animation.cpp b/examples/animation/stickman/animation.cpp deleted file mode 100644 index c2c6bd1..0000000 --- a/examples/animation/stickman/animation.cpp +++ /dev/null @@ -1,193 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "animation.h" - -#include -#include -#include - -class Frame -{ -public: - Frame() { - } - - int nodeCount() const - { - return m_nodePositions.size(); - } - - void setNodeCount(int nodeCount) - { - while (nodeCount > m_nodePositions.size()) - m_nodePositions.append(QPointF()); - - while (nodeCount < m_nodePositions.size()) - m_nodePositions.removeLast(); - } - - QPointF nodePos(int idx) const - { - return m_nodePositions.at(idx); - } - - void setNodePos(int idx, const QPointF &pos) - { - m_nodePositions[idx] = pos; - } - -private: - QList m_nodePositions; -}; - -Animation::Animation() -{ - m_currentFrame = 0; - m_frames.append(new Frame); -} - -Animation::~Animation() -{ - qDeleteAll(m_frames); -} - -void Animation::setTotalFrames(int totalFrames) -{ - while (m_frames.size() < totalFrames) - m_frames.append(new Frame); - - while (totalFrames < m_frames.size()) - delete m_frames.takeLast(); -} - -int Animation::totalFrames() const -{ - return m_frames.size(); -} - -void Animation::setCurrentFrame(int currentFrame) -{ - m_currentFrame = qMax(qMin(currentFrame, totalFrames()-1), 0); -} - -int Animation::currentFrame() const -{ - return m_currentFrame; -} - -void Animation::setNodeCount(int nodeCount) -{ - Frame *frame = m_frames.at(m_currentFrame); - frame->setNodeCount(nodeCount); -} - -int Animation::nodeCount() const -{ - Frame *frame = m_frames.at(m_currentFrame); - return frame->nodeCount(); -} - -void Animation::setNodePos(int idx, const QPointF &pos) -{ - Frame *frame = m_frames.at(m_currentFrame); - frame->setNodePos(idx, pos); -} - -QPointF Animation::nodePos(int idx) const -{ - Frame *frame = m_frames.at(m_currentFrame); - return frame->nodePos(idx); -} - -QString Animation::name() const -{ - return m_name; -} - -void Animation::setName(const QString &name) -{ - m_name = name; -} - -void Animation::save(QIODevice *device) const -{ - QDataStream stream(device); - stream << m_name; - stream << m_frames.size(); - foreach (Frame *frame, m_frames) { - stream << frame->nodeCount(); - for (int i=0; inodeCount(); ++i) - stream << frame->nodePos(i); - } -} - -void Animation::load(QIODevice *device) -{ - if (!m_frames.isEmpty()) - qDeleteAll(m_frames); - - m_frames.clear(); - - QDataStream stream(device); - stream >> m_name; - - int frameCount; - stream >> frameCount; - - for (int i=0; i> nodeCount; - - Frame *frame = new Frame; - frame->setNodeCount(nodeCount); - - for (int j=0; j> pos; - - frame->setNodePos(j, pos); - } - - m_frames.append(frame); - } -} diff --git a/examples/animation/stickman/animation.h b/examples/animation/stickman/animation.h deleted file mode 100644 index b0b39c9..0000000 --- a/examples/animation/stickman/animation.h +++ /dev/null @@ -1,83 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ANIMATION_H -#define ANIMATION_H - -#include -#include -#include - -class Frame; -QT_BEGIN_NAMESPACE -class QIODevice; -QT_END_NAMESPACE -class Animation -{ -public: - Animation(); - ~Animation(); - - void setTotalFrames(int totalFrames); - int totalFrames() const; - - void setCurrentFrame(int currentFrame); - int currentFrame() const; - - void setNodeCount(int nodeCount); - int nodeCount() const; - - void setNodePos(int idx, const QPointF &pos); - QPointF nodePos(int idx) const; - - QString name() const; - void setName(const QString &name); - - void save(QIODevice *device) const; - void load(QIODevice *device); - -private: - QString m_name; - QList m_frames; - int m_currentFrame; -}; - -#endif diff --git a/examples/animation/stickman/animations/chilling b/examples/animation/stickman/animations/chilling deleted file mode 100644 index a81fc7a..0000000 Binary files a/examples/animation/stickman/animations/chilling and /dev/null differ diff --git a/examples/animation/stickman/animations/dancing b/examples/animation/stickman/animations/dancing deleted file mode 100644 index 462f66f..0000000 Binary files a/examples/animation/stickman/animations/dancing and /dev/null differ diff --git a/examples/animation/stickman/animations/dead b/examples/animation/stickman/animations/dead deleted file mode 100644 index 9859b4b..0000000 Binary files a/examples/animation/stickman/animations/dead and /dev/null differ diff --git a/examples/animation/stickman/animations/jumping b/examples/animation/stickman/animations/jumping deleted file mode 100644 index 12661a1..0000000 Binary files a/examples/animation/stickman/animations/jumping and /dev/null differ diff --git a/examples/animation/stickman/editor/animationdialog.cpp b/examples/animation/stickman/editor/animationdialog.cpp deleted file mode 100644 index 441517d..0000000 --- a/examples/animation/stickman/editor/animationdialog.cpp +++ /dev/null @@ -1,192 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "animationdialog.h" -#include "stickman.h" -#include "animation.h" -#include "node.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -AnimationDialog::AnimationDialog(StickMan *stickman, QWidget *parent) - : QDialog(parent), m_animation(0), m_stickman(stickman) -{ - initUi(); -} - -AnimationDialog::~AnimationDialog() -{ - delete m_animation; -} - -void AnimationDialog::initUi() -{ - setWindowTitle("Animation"); - setEnabled(false); - - // Second page - m_currentFrame = new QSpinBox(); - m_totalFrames = new QSpinBox(); - m_name = new QLineEdit(); - - connect(m_currentFrame, SIGNAL(valueChanged(int)), this, SLOT(currentFrameChanged(int))); - connect(m_totalFrames, SIGNAL(valueChanged(int)), this, SLOT(totalFramesChanged(int))); - connect(m_name, SIGNAL(textChanged(QString)), this, SLOT(setCurrentAnimationName(QString))); - - QGridLayout *gridLayout = new QGridLayout(this); - gridLayout->addWidget(new QLabel("Name:"), 0, 0, 1, 2); - gridLayout->addWidget(m_name, 0, 2, 1, 2); - gridLayout->addWidget(new QLabel("Frame:"), 1, 0); - gridLayout->addWidget(m_currentFrame, 1, 1); - gridLayout->addWidget(new QLabel("of total # of frames: "), 1, 2); - gridLayout->addWidget(m_totalFrames, 1, 3); -} - -void AnimationDialog::initFromAnimation() -{ - m_currentFrame->setRange(0, m_animation->totalFrames()-1); - m_currentFrame->setValue(m_animation->currentFrame()); - - m_totalFrames->setRange(1, 1000); - m_totalFrames->setValue(m_animation->totalFrames()); - - m_name->setText(m_animation->name()); -} - -void AnimationDialog::saveAnimation() -{ - saveCurrentFrame(); - - QString fileName = QFileDialog::getSaveFileName(this, "Save animation"); - - QFile file(fileName); - if (file.open(QIODevice::WriteOnly)) - m_animation->save(&file); -} - -void AnimationDialog::loadAnimation() -{ - if (maybeSave() != QMessageBox::Cancel) { - QString fileName = QFileDialog::getOpenFileName(this, "Open animation"); - - QFile file(fileName); - if (file.open(QIODevice::ReadOnly)) { - if (m_animation == 0) - newAnimation(); - - m_animation->load(&file); - stickManFromCurrentFrame(); - initFromAnimation(); - } - } -} - -QMessageBox::StandardButton AnimationDialog::maybeSave() -{ - if (m_animation == 0) - return QMessageBox::No; - - QMessageBox::StandardButton button = QMessageBox::question(this, "Save?", "Do you want to save your changes?", - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); - if (button == QMessageBox::Save) - saveAnimation(); - - return button; -} - -void AnimationDialog::newAnimation() -{ - if (maybeSave() != QMessageBox::Cancel) { - setEnabled(true); - delete m_animation; - m_animation = new Animation(); - initFromAnimation(); - } -} - -// Gets the data from the stickman and stores it in current frame -void AnimationDialog::saveCurrentFrame() -{ - int count = m_stickman->nodeCount(); - m_animation->setNodeCount(count); - for (int i=0; inode(i); - m_animation->setNodePos(i, node->pos()); - } -} - -// Gets the data from the current frame and sets the stickman -void AnimationDialog::stickManFromCurrentFrame() -{ - int count = m_animation->nodeCount(); - for (int i=0;inode(i); - node->setPos(m_animation->nodePos(i)); - } -} - -void AnimationDialog::currentFrameChanged(int currentFrame) -{ - saveCurrentFrame(); - qDebug("currentFrame: %d", currentFrame); - m_animation->setCurrentFrame(currentFrame); - stickManFromCurrentFrame(); - initFromAnimation(); -} - -void AnimationDialog::totalFramesChanged(int totalFrames) -{ - m_animation->setTotalFrames(totalFrames); - stickManFromCurrentFrame(); - initFromAnimation(); -} - -void AnimationDialog::setCurrentAnimationName(const QString &name) -{ - m_animation->setName(name); -} diff --git a/examples/animation/stickman/editor/animationdialog.h b/examples/animation/stickman/editor/animationdialog.h deleted file mode 100644 index 6025088..0000000 --- a/examples/animation/stickman/editor/animationdialog.h +++ /dev/null @@ -1,84 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ANIMATIONDIALOG_H -#define ANIMATIONDIALOG_H - -#include -#include - -QT_BEGIN_NAMESPACE -class QSpinBox; -class QLineEdit; -QT_END_NAMESPACE -class StickMan; -class Animation; -class AnimationDialog: public QDialog -{ - Q_OBJECT -public: - AnimationDialog(StickMan *stickMan, QWidget *parent = 0); - ~AnimationDialog(); - -public slots: - void currentFrameChanged(int currentFrame); - void totalFramesChanged(int totalFrames); - void setCurrentAnimationName(const QString &name); - - void newAnimation(); - void saveAnimation(); - void loadAnimation(); - -private: - void saveCurrentFrame(); - void stickManFromCurrentFrame(); - void initFromAnimation(); - void initUi(); - QMessageBox::StandardButton maybeSave(); - - QSpinBox *m_currentFrame; - QSpinBox *m_totalFrames; - QLineEdit *m_name; - Animation *m_animation; - StickMan *m_stickman; -}; - -#endif diff --git a/examples/animation/stickman/editor/editor.pri b/examples/animation/stickman/editor/editor.pri deleted file mode 100644 index 7ad9edb..0000000 --- a/examples/animation/stickman/editor/editor.pri +++ /dev/null @@ -1,2 +0,0 @@ -SOURCES += $$PWD/animationdialog.cpp $$PWD/mainwindow.cpp -HEADERS += $$PWD/animationdialog.h $$PWD/mainwindow.h diff --git a/examples/animation/stickman/editor/mainwindow.cpp b/examples/animation/stickman/editor/mainwindow.cpp deleted file mode 100644 index c6464c6..0000000 --- a/examples/animation/stickman/editor/mainwindow.cpp +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "mainwindow.h" -#include "animationdialog.h" -#include "stickman.h" - -#include -#include - -MainWindow::MainWindow(StickMan *stickMan) -{ - initActions(stickMan); -} - -MainWindow::~MainWindow() -{ -} - -void MainWindow::initActions(StickMan *stickMan) -{ - AnimationDialog *dialog = new AnimationDialog(stickMan, this); - dialog->show(); - - QMenu *fileMenu = menuBar()->addMenu("&File"); - QAction *loadAction = fileMenu->addAction("&Open"); - QAction *saveAction = fileMenu->addAction("&Save"); - QAction *exitAction = fileMenu->addAction("E&xit"); - - QMenu *animationMenu = menuBar()->addMenu("&Animation"); - QAction *newAnimationAction = animationMenu->addAction("&New animation"); - - connect(loadAction, SIGNAL(triggered()), dialog, SLOT(loadAnimation())); - connect(saveAction, SIGNAL(triggered()), dialog, SLOT(saveAnimation())); - connect(exitAction, SIGNAL(triggered()), QApplication::instance(), SLOT(quit())); - connect(newAnimationAction, SIGNAL(triggered()), dialog, SLOT(newAnimation())); - -} diff --git a/examples/animation/stickman/editor/mainwindow.h b/examples/animation/stickman/editor/mainwindow.h deleted file mode 100644 index 4c2b949..0000000 --- a/examples/animation/stickman/editor/mainwindow.h +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include - -class StickMan; -class MainWindow: public QMainWindow -{ -public: - MainWindow(StickMan *stickMan); - ~MainWindow(); - -private: - void initActions(StickMan *stickMan); -}; - -#endif diff --git a/examples/animation/stickman/graphicsview.cpp b/examples/animation/stickman/graphicsview.cpp deleted file mode 100644 index 754f3bc..0000000 --- a/examples/animation/stickman/graphicsview.cpp +++ /dev/null @@ -1,81 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "graphicsview.h" -#include "editor/mainwindow.h" -#include "stickman.h" - -#include -#include -#include - -GraphicsView::GraphicsView(QWidget *parent) : QGraphicsView(parent), m_editor(0) {} - -void GraphicsView::keyPressEvent(QKeyEvent *e) -{ - if (e->key() == Qt::Key_Escape) - close(); - -#if 0 - if (e->key() == Qt::Key_F1) { - if (m_editor == 0) { - QGraphicsScene *scene = new QGraphicsScene; - StickMan *stickMan = new StickMan; - stickMan->setDrawSticks(true); - scene->addItem(stickMan); - - QGraphicsView *view = new QGraphicsView; - view->setBackgroundBrush(Qt::black); - view->setRenderHints(QPainter::Antialiasing); - view->setScene(scene); - - m_editor = new MainWindow(stickMan); - m_editor->setCentralWidget(view); - } - - m_editor->showMaximized(); - } -#endif - - emit keyPressed(Qt::Key(e->key())); -} - - diff --git a/examples/animation/stickman/graphicsview.h b/examples/animation/stickman/graphicsview.h deleted file mode 100644 index 2515418..0000000 --- a/examples/animation/stickman/graphicsview.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GRAPHICSVIEW_H -#define GRAPHICSVIEW - -#include - -class MainWindow; -class GraphicsView: public QGraphicsView -{ - Q_OBJECT -public: - GraphicsView(QWidget *parent = 0); - -protected: - void keyPressEvent(QKeyEvent *); - -signals: - void keyPressed(int key); - -private: - MainWindow *m_editor; -}; - -#endif diff --git a/examples/animation/stickman/lifecycle.cpp b/examples/animation/stickman/lifecycle.cpp deleted file mode 100644 index eb4ed11..0000000 --- a/examples/animation/stickman/lifecycle.cpp +++ /dev/null @@ -1,212 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "lifecycle.h" -#include "stickman.h" -#include "node.h" -#include "animation.h" -#include "graphicsview.h" - -#include -#include - -class KeyPressTransition: public QSignalTransition -{ -public: - KeyPressTransition(GraphicsView *receiver, Qt::Key key) - : QSignalTransition(receiver, SIGNAL(keyPressed(int))), m_key(key) - { - } - KeyPressTransition(GraphicsView *receiver, Qt::Key key, QAbstractState *target) - : QSignalTransition(receiver, SIGNAL(keyPressed(int)), QList() << target), m_key(key) - { - } - - virtual bool eventTest(QEvent *e) - { - if (QSignalTransition::eventTest(e)) { - QVariant key = static_cast(e)->arguments().at(0); - return (key.toInt() == int(m_key)); - } - - return false; - } -private: - Qt::Key m_key; -}; - -//! [4] -class LightningStrikesTransition: public QEventTransition -{ -public: - LightningStrikesTransition(QAbstractState *target) - : QEventTransition(this, QEvent::Timer, QList() << target) - { - qsrand((uint)QDateTime::currentDateTime().toTime_t()); - startTimer(1000); - } - - virtual bool eventTest(QEvent *e) - { - return QEventTransition::eventTest(e) && ((qrand() % 50) == 0); - } -}; -//! [4] - -LifeCycle::LifeCycle(StickMan *stickMan, GraphicsView *keyReceiver) - : m_stickMan(stickMan), m_keyReceiver(keyReceiver) -{ - // Create animation group to be used for all transitions - m_animationGroup = new QParallelAnimationGroup(); - const int stickManNodeCount = m_stickMan->nodeCount(); - for (int i=0; inode(i), "position"); - m_animationGroup->addAnimation(pa); - } - - // Set up intial state graph -//! [3] - m_machine = new QStateMachine(); - m_machine->addDefaultAnimation(m_animationGroup); -//! [3] - - m_alive = new QState(m_machine->rootState()); - m_alive->setObjectName("alive"); - - // Make it blink when lightning strikes before entering dead animation - QState *lightningBlink = new QState(m_machine->rootState()); - lightningBlink->assignProperty(m_stickMan->scene(), "backgroundBrush", Qt::white); - lightningBlink->assignProperty(m_stickMan, "penColor", Qt::black); - lightningBlink->assignProperty(m_stickMan, "fillColor", Qt::white); - lightningBlink->assignProperty(m_stickMan, "isDead", true); - -//! [5] - QTimer *timer = new QTimer(lightningBlink); - timer->setSingleShot(true); - timer->setInterval(100); - QObject::connect(lightningBlink, SIGNAL(entered()), timer, SLOT(start())); - QObject::connect(lightningBlink, SIGNAL(exited()), timer, SLOT(stop())); -//! [5] - - m_dead = new QState(m_machine->rootState()); - m_dead->assignProperty(m_stickMan->scene(), "backgroundBrush", Qt::black); - m_dead->assignProperty(m_stickMan, "penColor", Qt::white); - m_dead->assignProperty(m_stickMan, "fillColor", Qt::black); - m_dead->setObjectName("dead"); - - // Idle state (sets no properties) - m_idle = new QState(m_alive); - m_idle->setObjectName("idle"); - - m_alive->setInitialState(m_idle); - - // Lightning strikes at random - m_alive->addTransition(new LightningStrikesTransition(lightningBlink)); -//! [0] - lightningBlink->addTransition(timer, SIGNAL(timeout()), m_dead); -//! [0] - - m_machine->setInitialState(m_alive); -} - -void LifeCycle::setDeathAnimation(const QString &fileName) -{ - QState *deathAnimation = makeState(m_dead, fileName); - m_dead->setInitialState(deathAnimation); -} - -void LifeCycle::start() -{ - m_machine->start(); -} - -void LifeCycle::addActivity(const QString &fileName, Qt::Key key) -{ - QState *state = makeState(m_alive, fileName); - m_alive->addTransition(new KeyPressTransition(m_keyReceiver, key, state)); -} - -QState *LifeCycle::makeState(QState *parentState, const QString &animationFileName) -{ - QState *topLevel = new QState(parentState); - - Animation animation; - { - QFile file(animationFileName); - if (file.open(QIODevice::ReadOnly)) - animation.load(&file); - } - - const int frameCount = animation.totalFrames(); - QState *previousState = 0; - for (int i=0; iassignProperty(m_stickMan->node(j), "position", animation.nodePos(j)); -//! [1] - - frameState->setObjectName(QString::fromLatin1("frame %0").arg(i)); - if (previousState == 0) - topLevel->setInitialState(frameState); - else -//! [2] - previousState->addTransition(previousState, SIGNAL(polished()), frameState); -//! [2] - - previousState = frameState; - } - - // Loop - previousState->addTransition(previousState, SIGNAL(polished()), topLevel->initialState()); - - return topLevel; - -} - -LifeCycle::~LifeCycle() -{ - delete m_machine; - delete m_animationGroup; -} diff --git a/examples/animation/stickman/lifecycle.h b/examples/animation/stickman/lifecycle.h deleted file mode 100644 index 2be4762..0000000 --- a/examples/animation/stickman/lifecycle.h +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef LIFECYCLE_H -#define LIFECYCLE_H - -#include - -class StickMan; -QT_BEGIN_NAMESPACE -class QStateMachine; -class QAnimationGroup; -class QState; -class QAbstractState; -class QAbstractTransition; -QT_END_NAMESPACE -class GraphicsView; -class LifeCycle -{ -public: - LifeCycle(StickMan *stickMan, GraphicsView *keyEventReceiver); - ~LifeCycle(); - - void setDeathAnimation(const QString &fileName); - void addActivity(const QString &fileName, Qt::Key key); - - void start(); - -private: - QState *makeState(QState *parentState, const QString &animationFileName); - - StickMan *m_stickMan; - QStateMachine *m_machine; - QAnimationGroup *m_animationGroup; - GraphicsView *m_keyReceiver; - - QState *m_alive; - QState *m_dead; - QState *m_idle; -}; - -#endif diff --git a/examples/animation/stickman/main.cpp b/examples/animation/stickman/main.cpp deleted file mode 100644 index 62d8252..0000000 --- a/examples/animation/stickman/main.cpp +++ /dev/null @@ -1,97 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "animation.h" -#include "node.h" -#include "lifecycle.h" -#include "stickman.h" -#include "graphicsview.h" - -#include -#include - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - StickMan *stickMan = new StickMan; - stickMan->setDrawSticks(false); - - QGraphicsTextItem *textItem = new QGraphicsTextItem(); - textItem->setHtml("Stickman" - "

    " - "Tell the stickman what to do!" - "

    " - "

    " - "

  • Press J to make the stickman jump.
  • " - "
  • Press D to make the stickman dance.
  • " - "
  • Press C to make him chill out.
  • " - "
  • When you are done, press Escape.
  • " - "

    " - "

    If he is unlucky, the stickman will get struck by lightning, and never jump, dance or chill out again." - "

    "); - qreal w = textItem->boundingRect().width(); - QRectF stickManBoundingRect = stickMan->mapToScene(stickMan->boundingRect()).boundingRect(); - textItem->setPos(-w / 2.0, stickManBoundingRect.bottom() + 25.0); - - QGraphicsScene *scene = new QGraphicsScene(); - scene->addItem(stickMan); - scene->addItem(textItem); - scene->setBackgroundBrush(Qt::black); - - GraphicsView *view = new GraphicsView(); - view->setRenderHints(QPainter::Antialiasing); - view->setTransformationAnchor(QGraphicsView::NoAnchor); - view->setScene(scene); - view->showFullScreen(); - view->setFocus(); - view->setSceneRect(scene->sceneRect()); - - LifeCycle *cycle = new LifeCycle(stickMan, view); - cycle->setDeathAnimation("animations/dead"); - - cycle->addActivity("animations/jumping", Qt::Key_J); - cycle->addActivity("animations/dancing", Qt::Key_D); - cycle->addActivity("animations/chilling", Qt::Key_C); - cycle->start(); - - return app.exec(); -} diff --git a/examples/animation/stickman/node.cpp b/examples/animation/stickman/node.cpp deleted file mode 100644 index 9c485d9..0000000 --- a/examples/animation/stickman/node.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "node.h" -#include "stickman.h" - -#include -#include -#include - -Node::Node(const QPointF &pos, QGraphicsItem *parent) - : QGraphicsItem(parent), m_dragging(false) -{ - setPos(pos); -} - -Node::~Node() -{ -} - -QRectF Node::boundingRect() const -{ - return QRectF(-6.0, -6.0, 12.0, 12.0); -} - -void Node::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - painter->setPen(Qt::white); - painter->drawEllipse(QPointF(0.0, 0.0), 5.0, 5.0); -} - -QVariant Node::itemChange(GraphicsItemChange change, const QVariant &value) -{ - if (change == QGraphicsItem::ItemPositionChange) - emit positionChanged(); - - return QGraphicsItem::itemChange(change, value); -} - -void Node::mousePressEvent(QGraphicsSceneMouseEvent *) -{ - m_dragging = true; -} - -void Node::mouseMoveEvent(QGraphicsSceneMouseEvent *event) -{ - if (m_dragging) - setPos(mapToParent(event->pos())); -} - -void Node::mouseReleaseEvent(QGraphicsSceneMouseEvent *) -{ - m_dragging = false; -} diff --git a/examples/animation/stickman/node.h b/examples/animation/stickman/node.h deleted file mode 100644 index 72eae87..0000000 --- a/examples/animation/stickman/node.h +++ /dev/null @@ -1,72 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef NODE_H -#define NODE_H - -#include - -class Node: public QObject, public QGraphicsItem -{ - Q_OBJECT - Q_PROPERTY(QPointF position READ pos WRITE setPos); -public: - Node(const QPointF &pos, QGraphicsItem *parent = 0); - ~Node(); - - QRectF boundingRect() const; - void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - -signals: - void positionChanged(); - -protected: - QVariant itemChange(GraphicsItemChange change, const QVariant &value); - - void mousePressEvent(QGraphicsSceneMouseEvent *); - void mouseMoveEvent(QGraphicsSceneMouseEvent *); - void mouseReleaseEvent(QGraphicsSceneMouseEvent *); - -private: - bool m_dragging; -}; - -#endif diff --git a/examples/animation/stickman/stickman.cpp b/examples/animation/stickman/stickman.cpp deleted file mode 100644 index e00ea41..0000000 --- a/examples/animation/stickman/stickman.cpp +++ /dev/null @@ -1,339 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "stickman.h" -#include "node.h" - -#include -#include - -#define _USE_MATH_DEFINES -#include - -static const int NodeCount = 16; -static const qreal Coords[NodeCount * 2] = { - 0.0, -150.0, // head, #0 - - 0.0, -100.0, // body pentagon, top->bottom, left->right, #1 - 5 - -50.0, -50.0, - 50.0, -50.0, - -25.0, 50.0, - 25.0, 50.0, - - -100.0, 0.0, // right arm, #6 - 7 - -125.0, 50.0, - - 100.0, 0.0, // left arm, #8 - 9 - 125.0, 50.0, - - -35.0, 75.0, // lower body, #10 - 11 - 35.0, 75.0, - - -25.0, 200.0, // right leg, #12 - 13 - -30.0, 300.0, - - 25.0, 200.0, // left leg, #14 - 15 - 30.0, 300.0 - -}; - -static const int BoneCount = 24; -static const int Bones[BoneCount * 2] = { - 0, 1, // neck - - 1, 2, // body - 1, 3, - 1, 4, - 1, 5, - 2, 3, - 2, 4, - 2, 5, - 3, 4, - 3, 5, - 4, 5, - - 2, 6, // right arm - 6, 7, - - 3, 8, // left arm - 8, 9, - - 4, 10, // lower body - 4, 11, - 5, 10, - 5, 11, - 10, 11, - - 10, 12, // right leg - 12, 13, - - 11, 14, // left leg - 14, 15 - -}; - -StickMan::StickMan() -{ - m_nodes = new Node*[NodeCount]; - m_sticks = true; - m_isDead = false; - m_pixmap = QPixmap("images/head.png"); - m_penColor = Qt::white; - m_fillColor = Qt::black; - - // Set up start position of limbs - for (int i=0; ipos() - node2->pos(); - m_perfectBoneLengths[i] = sqrt(pow(dist.x(),2) + pow(dist.y(),2)); - } - - startTimer(10); -} - -StickMan::~StickMan() -{ - delete m_nodes; -} - -void StickMan::childPositionChanged() -{ - prepareGeometryChange(); -} - -void StickMan::setDrawSticks(bool on) -{ - m_sticks = on; - for (int i=0;isetVisible(on); - } -} - -QRectF StickMan::boundingRect() const -{ - // account for head radius=50.0 plus pen which is 5.0 - return childrenBoundingRect().adjusted(-55.0, -55.0, 55.0, 55.0); -} - -int StickMan::nodeCount() const -{ - return NodeCount; -} - -Node *StickMan::node(int idx) const -{ - if (idx >= 0 && idx < NodeCount) - return m_nodes[idx]; - else - return 0; -} - -void StickMan::timerEvent(QTimerEvent *) -{ - update(); -} - -void StickMan::stabilize() -{ - static const qreal threshold = 0.001; - - for (int i=0; ipos(); - QPointF pos2 = node2->pos(); - - QPointF dist = pos1 - pos2; - qreal length = sqrt(pow(dist.x(),2) + pow(dist.y(),2)); - qreal diff = (length - m_perfectBoneLengths[i]) / length; - - QPointF p = dist * (0.5 * diff); - if (p.x() > threshold && p.y() > threshold) { - pos1 -= p; - pos2 += p; - - node1->setPos(pos1); - node2->setPos(pos2); - } - } -} - -QPointF StickMan::posFor(int idx) const -{ - return m_nodes[idx]->pos(); -} - -//#include -void StickMan::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - /* static int frames = 0; - static QTime time; - if (frames++ % 100 == 0) { - frames = 1; - time.restart(); - } - - if (time.elapsed() > 0) { - painter->setPen(Qt::white); - painter->drawText(0, 0, QString::number(frames / (time.elapsed() / 1000.0))); - }*/ - - stabilize(); - if (m_sticks) { - painter->setPen(Qt::white); - for (int i=0; idrawLine(node1->pos(), node2->pos()); - } - } else { - // first bone is neck and will be used for head - - QPainterPath path; - path.moveTo(posFor(0)); - path.lineTo(posFor(1)); - - // right arm - path.lineTo(posFor(2)); - path.lineTo(posFor(6)); - path.lineTo(posFor(7)); - - // left arm - path.moveTo(posFor(3)); - path.lineTo(posFor(8)); - path.lineTo(posFor(9)); - - // body - path.moveTo(posFor(2)); - path.lineTo(posFor(4)); - path.lineTo(posFor(10)); - path.lineTo(posFor(11)); - path.lineTo(posFor(5)); - path.lineTo(posFor(3)); - path.lineTo(posFor(1)); - - // right leg - path.moveTo(posFor(10)); - path.lineTo(posFor(12)); - path.lineTo(posFor(13)); - - // left leg - path.moveTo(posFor(11)); - path.lineTo(posFor(14)); - path.lineTo(posFor(15)); - - painter->setPen(QPen(m_penColor, 5.0, Qt::SolidLine, Qt::RoundCap)); - painter->drawPath(path); - - { - int n1 = Bones[0]; - int n2 = Bones[1]; - Node *node1 = m_nodes[n1]; - Node *node2 = m_nodes[n2]; - - QPointF dist = node2->pos() - node1->pos(); - - qreal sinAngle = dist.x() / sqrt(pow(dist.x(), 2) + pow(dist.y(), 2)); - qreal angle = asin(sinAngle) * 180.0 / M_PI; - - QPointF headPos = node1->pos(); - painter->translate(headPos); - painter->rotate(-angle); - - painter->setBrush(m_fillColor); - painter->drawEllipse(QPointF(0,0), 50.0, 50.0); - - painter->setBrush(m_penColor); - painter->setPen(QPen(m_penColor, 2.5, Qt::SolidLine, Qt::RoundCap)); - - // eyes - if (m_isDead) { - painter->drawLine(-30.0, -30.0, -20.0, -20.0); - painter->drawLine(-20.0, -30.0, -30.0, -20.0); - - painter->drawLine(20.0, -30.0, 30.0, -20.0); - painter->drawLine(30.0, -30.0, 20.0, -20.0); - } else { - painter->drawChord(QRectF(-30.0, -30.0, 25.0, 70.0), 30.0*16, 120.0*16); - painter->drawChord(QRectF(5.0, -30.0, 25.0, 70.0), 30.0*16, 120.0*16); - } - - // mouth - if (m_isDead) { - painter->drawLine(-28.0, 2.0, 29.0, 2.0); - } else { - painter->setBrush(QColor(128, 0, 64 )); - painter->drawChord(QRectF(-28.0, 2.0-55.0/2.0, 57.0, 55.0), 0.0, -180.0*16); - } - - // pupils - if (!m_isDead) { - painter->setPen(QPen(m_fillColor, 1.0, Qt::SolidLine, Qt::RoundCap)); - painter->setBrush(m_fillColor); - painter->drawEllipse(QPointF(-12.0, -25.0), 5.0, 5.0); - painter->drawEllipse(QPointF(22.0, -25.0), 5.0, 5.0); - } - } - } -} - - - diff --git a/examples/animation/stickman/stickman.h b/examples/animation/stickman/stickman.h deleted file mode 100644 index 6395272..0000000 --- a/examples/animation/stickman/stickman.h +++ /dev/null @@ -1,103 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef STICKMAN_H -#define STICKMAN_H - -#include - -const int LimbCount = 16; - -class Node; -QT_BEGIN_NAMESPACE -class QTimer; -QT_END_NAMESPACE -class StickMan: public QObject, public QGraphicsItem -{ - Q_OBJECT - Q_PROPERTY(QColor penColor WRITE setPenColor READ penColor) - Q_PROPERTY(QColor fillColor WRITE setFillColor READ fillColor) - Q_PROPERTY(bool isDead WRITE setIsDead READ isDead) -public: - StickMan(); - ~StickMan(); - - virtual QRectF boundingRect() const; - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - - int nodeCount() const; - Node *node(int idx) const; - - void setDrawSticks(bool on); - bool drawSticks() const { return m_sticks; } - - QColor penColor() const { return m_penColor; } - void setPenColor(const QColor &color) { m_penColor = color; } - - QColor fillColor() const { return m_fillColor; } - void setFillColor(const QColor &color) { m_fillColor = color; } - - bool isDead() const { return m_isDead; } - void setIsDead(bool isDead) { m_isDead = isDead; } - -public slots: - void stabilize(); - void childPositionChanged(); - -protected: - void timerEvent(QTimerEvent *e); - -private: - QPointF posFor(int idx) const; - - Node **m_nodes; - qreal *m_perfectBoneLengths; - - uint m_sticks : 1; - uint m_isDead : 1; - uint m_reserved : 30; - - QPixmap m_pixmap; - QColor m_penColor; - QColor m_fillColor; -}; - -#endif // STICKMAN_H diff --git a/examples/animation/stickman/stickman.pro b/examples/animation/stickman/stickman.pro deleted file mode 100644 index 956b49c..0000000 --- a/examples/animation/stickman/stickman.pro +++ /dev/null @@ -1,19 +0,0 @@ -HEADERS += stickman.h \ - animation.h \ - node.h \ - lifecycle.h \ - graphicsview.h -SOURCES += main.cpp \ - stickman.cpp \ - animation.cpp \ - node.cpp \ - lifecycle.cpp \ - graphicsview.cpp - -include(editor/editor.pri) - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation/stickman -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS stickman.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/animation/stickman -INSTALLS += target sources diff --git a/examples/animation/sub-attaq/animationmanager.cpp b/examples/animation/sub-attaq/animationmanager.cpp deleted file mode 100644 index 477d3bd..0000000 --- a/examples/animation/sub-attaq/animationmanager.cpp +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "animationmanager.h" - -//Qt -#include -#include - -// the universe's only animation manager -AnimationManager *AnimationManager::instance = 0; - -AnimationManager::AnimationManager() -{ -} - -AnimationManager *AnimationManager::self() -{ - if (!instance) - instance = new AnimationManager; - return instance; -} - -void AnimationManager::registerAnimation(QAbstractAnimation *anim) -{ - animations.append(anim); -} - -void AnimationManager::unregisterAnimation(QAbstractAnimation *anim) -{ - animations.removeAll(anim); -} - -void AnimationManager::unregisterAllAnimations() -{ - animations.clear(); -} - -void AnimationManager::pauseAll() -{ - foreach (QAbstractAnimation* animation, animations) - { - if (animation->state() == QAbstractAnimation::Running) - animation->pause(); - } -} -void AnimationManager::resumeAll() -{ - foreach (QAbstractAnimation* animation, animations) - { - if (animation->state() == QAbstractAnimation::Paused) - animation->resume(); - } -} diff --git a/examples/animation/sub-attaq/animationmanager.h b/examples/animation/sub-attaq/animationmanager.h deleted file mode 100644 index a563c96..0000000 --- a/examples/animation/sub-attaq/animationmanager.h +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ANIMATIONMANAGER_H -#define ANIMATIONMANAGER_H - -#include - -QT_BEGIN_NAMESPACE -class QAbstractAnimation; -QT_END_NAMESPACE - -class AnimationManager : public QObject -{ -Q_OBJECT -public: - AnimationManager(); - void registerAnimation(QAbstractAnimation *anim); - void unregisterAnimation(QAbstractAnimation *anim); - void unregisterAllAnimations(); - static AnimationManager *self(); - -public slots: - void pauseAll(); - void resumeAll(); - -private: - static AnimationManager *instance; - QList animations; -}; - -#endif // ANIMATIONMANAGER_H diff --git a/examples/animation/sub-attaq/boat.cpp b/examples/animation/sub-attaq/boat.cpp deleted file mode 100644 index 63d12bb..0000000 --- a/examples/animation/sub-attaq/boat.cpp +++ /dev/null @@ -1,318 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "boat.h" -#include "boat_p.h" -#include "bomb.h" -#include "pixmapitem.h" -#include "graphicsscene.h" -#include "animationmanager.h" -#include "custompropertyanimation.h" -#include "qanimationstate.h" - -//Qt -#include -#include -#include -#include -#include -#include - -static QAbstractAnimation *setupDestroyAnimation(Boat *boat) -{ - QSequentialAnimationGroup *group = new QSequentialAnimationGroup(boat); -#if QT_VERSION >=0x040500 - PixmapItem *step1 = new PixmapItem(QString("explosion/boat/step1"),GraphicsScene::Big, boat); - step1->setZValue(6); - PixmapItem *step2 = new PixmapItem(QString("explosion/boat/step2"),GraphicsScene::Big, boat); - step2->setZValue(6); - PixmapItem *step3 = new PixmapItem(QString("explosion/boat/step3"),GraphicsScene::Big, boat); - step3->setZValue(6); - PixmapItem *step4 = new PixmapItem(QString("explosion/boat/step4"),GraphicsScene::Big, boat); - step4->setZValue(6); - step1->setOpacity(0); - step2->setOpacity(0); - step3->setOpacity(0); - step4->setOpacity(0); - CustomPropertyAnimation *anim1 = new CustomPropertyAnimation(boat); - anim1->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim1->setDuration(100); - anim1->setEndValue(1); - CustomPropertyAnimation *anim2 = new CustomPropertyAnimation(boat); - anim2->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim2->setDuration(100); - anim2->setEndValue(1); - CustomPropertyAnimation *anim3 = new CustomPropertyAnimation(boat); - anim3->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim3->setDuration(100); - anim3->setEndValue(1); - CustomPropertyAnimation *anim4 = new CustomPropertyAnimation(boat); - anim4->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim4->setDuration(100); - anim4->setEndValue(1); - CustomPropertyAnimation *anim5 = new CustomPropertyAnimation(boat); - anim5->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim5->setDuration(100); - anim5->setEndValue(0); - CustomPropertyAnimation *anim6 = new CustomPropertyAnimation(boat); - anim6->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim6->setDuration(100); - anim6->setEndValue(0); - CustomPropertyAnimation *anim7 = new CustomPropertyAnimation(boat); - anim7->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim7->setDuration(100); - anim7->setEndValue(0); - CustomPropertyAnimation *anim8 = new CustomPropertyAnimation(boat); - anim8->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim8->setDuration(100); - anim8->setEndValue(0); - group->addAnimation(anim1); - group->addAnimation(anim2); - group->addAnimation(anim3); - group->addAnimation(anim4); - group->addAnimation(anim5); - group->addAnimation(anim6); - group->addAnimation(anim7); - group->addAnimation(anim8); -#else - // work around for a bug where we don't transition if the duration is zero. - QtPauseAnimation *anim = new QtPauseAnimation(group); - anim->setDuration(1); - group->addAnimation(anim); -#endif - AnimationManager::self()->registerAnimation(group); - return group; -} - - - -Boat::Boat(QGraphicsItem * parent, Qt::WindowFlags wFlags) - : QGraphicsWidget(parent,wFlags), speed(0), bombsAlreadyLaunched(0), direction(Boat::None), movementAnimation(0) -{ - pixmapItem = new PixmapItem(QString("boat"),GraphicsScene::Big, this); - setZValue(4); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable); - resize(pixmapItem->boundingRect().size()); - - //The movement animation used to animate the boat - movementAnimation = new QPropertyAnimation(this, "pos"); - - //The movement animation used to animate the boat - destroyAnimation = setupDestroyAnimation(this); - - //We setup the state machien of the boat - machine = new QStateMachine(this); - QState *moving = new QState(machine->rootState()); - StopState *stopState = new StopState(this, moving); - machine->setInitialState(moving); - moving->setInitialState(stopState); - MoveStateRight *moveStateRight = new MoveStateRight(this, moving); - MoveStateLeft *moveStateLeft = new MoveStateLeft(this, moving); - LaunchStateRight *launchStateRight = new LaunchStateRight(this, machine->rootState()); - LaunchStateLeft *launchStateLeft = new LaunchStateLeft(this, machine->rootState()); - - //then setup the transitions for the rightMove state - KeyStopTransition *leftStopRight = new KeyStopTransition(this, QEvent::KeyPress, Qt::Key_Left); - leftStopRight->setTargetState(stopState); - KeyMoveTransition *leftMoveRight = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Left); - leftMoveRight->setTargetState(moveStateRight); - KeyMoveTransition *rightMoveRight = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); - rightMoveRight->setTargetState(moveStateRight); - KeyMoveTransition *rightMoveStop = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); - rightMoveStop->setTargetState(moveStateRight); - - //then setup the transitions for the leftMove state - KeyStopTransition *rightStopLeft = new KeyStopTransition(this, QEvent::KeyPress, Qt::Key_Right); - rightStopLeft->setTargetState(stopState); - KeyMoveTransition *rightMoveLeft = new KeyMoveTransition(this, QEvent::KeyPress, Qt::Key_Right); - rightMoveLeft->setTargetState(moveStateLeft); - KeyMoveTransition *leftMoveLeft = new KeyMoveTransition(this, QEvent::KeyPress,Qt::Key_Left); - leftMoveLeft->setTargetState(moveStateLeft); - KeyMoveTransition *leftMoveStop = new KeyMoveTransition(this, QEvent::KeyPress,Qt::Key_Left); - leftMoveStop->setTargetState(moveStateLeft); - - //We set up the right move state - moveStateRight->addTransition(leftStopRight); - moveStateRight->addTransition(leftMoveRight); - moveStateRight->addTransition(rightMoveRight); - stopState->addTransition(rightMoveStop); - - //We set up the left move state - moveStateLeft->addTransition(rightStopLeft); - moveStateLeft->addTransition(leftMoveLeft); - moveStateLeft->addTransition(rightMoveLeft); - stopState->addTransition(leftMoveStop); - - //The animation is finished, it means we reached the border of the screen, the boat is stopped so we move to the stop state - moveStateLeft->addTransition(movementAnimation, SIGNAL(finished()), stopState); - moveStateRight->addTransition(movementAnimation, SIGNAL(finished()), stopState); - - //We set up the keys for dropping bombs - KeyLaunchTransition *upFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); - upFireLeft->setTargetState(launchStateRight); - KeyLaunchTransition *upFireRight = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); - upFireRight->setTargetState(launchStateRight); - KeyLaunchTransition *upFireStop = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Up); - upFireStop->setTargetState(launchStateRight); - KeyLaunchTransition *downFireLeft = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); - downFireLeft->setTargetState(launchStateLeft); - KeyLaunchTransition *downFireRight = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); - downFireRight->setTargetState(launchStateLeft); - KeyLaunchTransition *downFireMove = new KeyLaunchTransition(this, QEvent::KeyPress, Qt::Key_Down); - downFireMove->setTargetState(launchStateLeft); - - //We set up transitions for fire up - moveStateRight->addTransition(upFireRight); - moveStateLeft->addTransition(upFireLeft); - stopState->addTransition(upFireStop); - - //We set up transitions for fire down - moveStateRight->addTransition(downFireRight); - moveStateLeft->addTransition(downFireLeft); - stopState->addTransition(downFireMove); - - //Finally the launch state should come back to its original state - QHistoryState *historyState = new QHistoryState(moving); - launchStateLeft->addTransition(historyState); - launchStateRight->addTransition(historyState); - - QFinalState *final = new QFinalState(machine->rootState()); - - //This state play the destroyed animation - QAnimationState *destroyedState = new QAnimationState(machine->rootState()); - destroyedState->setAnimation(destroyAnimation); - - //Play a nice animation when the boat is destroyed - moving->addTransition(this, SIGNAL(boatDestroyed()),destroyedState); - - //Transition to final state when the destroyed animation is finished - destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); - - //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(boatExecutionFinished())); - -} - -void Boat::run() -{ - //We register animations - AnimationManager::self()->registerAnimation(movementAnimation); - AnimationManager::self()->registerAnimation(destroyAnimation); - machine->start(); -} - -void Boat::stop() -{ - movementAnimation->stop(); - machine->stop(); -} - -void Boat::updateBoatMovement() -{ - if (speed == 0 || direction == Boat::None) { - movementAnimation->stop(); - return; - } - - movementAnimation->stop(); - movementAnimation->setStartValue(pos()); - - if (direction == Boat::Left) { - movementAnimation->setEndValue(QPointF(0,y())); - movementAnimation->setDuration(x()/speed*15); - } - else /*if (direction == Boat::Right)*/ { - movementAnimation->setEndValue(QPointF(scene()->width()-size().width(),y())); - movementAnimation->setDuration((scene()->width()-size().width()-x())/speed*15); - } - movementAnimation->start(); -} - -void Boat::destroy() -{ - movementAnimation->stop(); - emit boatDestroyed(); -} - -int Boat::bombsLaunched() const -{ - return bombsAlreadyLaunched; -} - -void Boat::setBombsLaunched(int number) -{ - if (number > MAX_BOMB) { - qWarning("Boat::setBombsLaunched : It impossible to launch that number of bombs"); - return; - } - bombsAlreadyLaunched = number; -} - -int Boat::currentSpeed() const -{ - return speed; -} - -void Boat::setCurrentSpeed(int speed) -{ - if (speed > 3 || speed < 0) { - qWarning("Boat::setCurrentSpeed: The boat can't run on that speed"); - return; - } - this->speed = speed; -} - -enum Boat::Movement Boat::currentDirection() const -{ - return direction; -} - -void Boat::setCurrentDirection(Movement direction) -{ - this->direction = direction; -} - -int Boat::type() const -{ - return Type; -} diff --git a/examples/animation/sub-attaq/boat.h b/examples/animation/sub-attaq/boat.h deleted file mode 100644 index 08a9fa2..0000000 --- a/examples/animation/sub-attaq/boat.h +++ /dev/null @@ -1,102 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __BOAT__H__ -#define __BOAT__H__ - -//Qt -#include -#include - -#include - -class PixmapItem; -class Bomb; -QT_BEGIN_NAMESPACE -class QVariantAnimation; -class QAbstractAnimation; -class QStateMachine; -QT_END_NAMESPACE - -class Boat : public QGraphicsWidget -{ -Q_OBJECT -Q_PROPERTY(QPointF pos READ pos WRITE setPos) -public: - enum Movement { - None = 0, - Left, - Right - }; - enum { Type = UserType + 2 }; - Boat(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); - void destroy(); - void run(); - void stop(); - - int bombsLaunched() const; - void setBombsLaunched(int number); - - int currentSpeed() const; - void setCurrentSpeed(int speed); - - enum Movement currentDirection() const; - void setCurrentDirection(Movement direction); - - void updateBoatMovement(); - - virtual int type() const; - -Q_SIGNALS: - void boatDestroyed(); - void boatExecutionFinished(); - -private: - int speed; - int bombsAlreadyLaunched; - Movement direction; - QVariantAnimation *movementAnimation; - QAbstractAnimation *destroyAnimation; - QStateMachine *machine; - PixmapItem *pixmapItem; -}; - -#endif //__BOAT__H__ diff --git a/examples/animation/sub-attaq/boat_p.h b/examples/animation/sub-attaq/boat_p.h deleted file mode 100644 index a8a24a6..0000000 --- a/examples/animation/sub-attaq/boat_p.h +++ /dev/null @@ -1,256 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef BOAT_P_H -#define BOAT_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -//Own -#include "bomb.h" -#include "graphicsscene.h" - -// Qt -#include - -static const int MAX_BOMB = 5; - - -//These transtion test if we have to stop the boat (i.e current speed is 1) -class KeyStopTransition : public QKeyEventTransition -{ -public: - KeyStopTransition(Boat *boat, QEvent::Type type, int key) - : QKeyEventTransition(boat, type, key) - { - this->boat = boat; - this->key = key; - } -protected: - virtual bool eventTest(QEvent *event) - { - Q_UNUSED(event); - if (!QKeyEventTransition::eventTest(event)) - return false; - if (boat->currentSpeed() == 1) - return true; - else - return false; - } -private: - Boat * boat; - int key; -}; - -//These transtion test if we have to move the boat (i.e current speed was 0 or another value) - class KeyMoveTransition : public QKeyEventTransition -{ -public: - KeyMoveTransition(Boat *boat, QEvent::Type type, int key) - : QKeyEventTransition(boat, type, key) - { - this->boat = boat; - this->key = key; - } -protected: - virtual bool eventTest(QEvent *event) - { - Q_UNUSED(event); - if (!QKeyEventTransition::eventTest(event)) - return false; - if (boat->currentSpeed() >= 0) - return true; - else - return false; - - } - void onTransition(QEvent *) - { - //We decrease the speed if needed - if (key == Qt::Key_Left && boat->currentDirection() == Boat::Right) - boat->setCurrentSpeed(boat->currentSpeed() - 1); - else if (key == Qt::Key_Right && boat->currentDirection() == Boat::Left) - boat->setCurrentSpeed(boat->currentSpeed() - 1); - else if (boat->currentSpeed() < 3) - boat->setCurrentSpeed(boat->currentSpeed() + 1); - boat->updateBoatMovement(); - } -private: - Boat * boat; - int key; -}; - -//This transition trigger the bombs launch - class KeyLaunchTransition : public QKeyEventTransition -{ -public: - KeyLaunchTransition(Boat *boat, QEvent::Type type, int key) - : QKeyEventTransition(boat, type, key) - { - this->boat = boat; - this->key = key; - } -protected: - virtual bool eventTest(QEvent *event) - { - Q_UNUSED(event); - if (!QKeyEventTransition::eventTest(event)) - return false; - //We have enough bomb? - if (boat->bombsLaunched() < MAX_BOMB) - return true; - else - return false; - } -private: - Boat * boat; - int key; -}; - -//This state is describing when the boat is moving right -class MoveStateRight : public QState -{ -public: - MoveStateRight(Boat *boat,QState *parent = 0) : QState(parent) - { - this->boat = boat; - } -protected: - void onEntry(QEvent *) - { - boat->setCurrentDirection(Boat::Right); - boat->updateBoatMovement(); - } -private: - Boat * boat; -}; - - //This state is describing when the boat is moving left -class MoveStateLeft : public QState -{ -public: - MoveStateLeft(Boat *boat,QState *parent = 0) : QState(parent) - { - this->boat = boat; - } -protected: - void onEntry(QEvent *) - { - boat->setCurrentDirection(Boat::Left); - boat->updateBoatMovement(); - } -private: - Boat * boat; -}; - -//This state is describing when the boat is in a stand by position -class StopState : public QState -{ -public: - StopState(Boat *boat,QState *parent = 0) : QState(parent) - { - this->boat = boat; - } -protected: - void onEntry(QEvent *) - { - boat->setCurrentSpeed(0); - boat->setCurrentDirection(Boat::None); - boat->updateBoatMovement(); - } -private: - Boat * boat; -}; - -//This state is describing the launch of the torpedo on the right -class LaunchStateRight : public QState -{ -public: - LaunchStateRight(Boat *boat,QState *parent = 0) : QState(parent) - { - this->boat = boat; - } -protected: - void onEntry(QEvent *) - { - Bomb *b = new Bomb(); - b->setPos(boat->x()+boat->size().width(),boat->y()); - GraphicsScene *scene = static_cast(boat->scene()); - scene->addItem(b); - b->launch(Bomb::Right); - boat->setBombsLaunched(boat->bombsLaunched() + 1); - } -private: - Boat * boat; -}; - -//This state is describing the launch of the torpedo on the left -class LaunchStateLeft : public QState -{ -public: - LaunchStateLeft(Boat *boat,QState *parent = 0) : QState(parent) - { - this->boat = boat; - } -protected: - void onEntry(QEvent *) - { - Bomb *b = new Bomb(); - b->setPos(boat->x() - b->size().width(), boat->y()); - GraphicsScene *scene = static_cast(boat->scene()); - scene->addItem(b); - b->launch(Bomb::Left); - boat->setBombsLaunched(boat->bombsLaunched() + 1); - } -private: - Boat * boat; -}; - -#endif // BOAT_P_H diff --git a/examples/animation/sub-attaq/bomb.cpp b/examples/animation/sub-attaq/bomb.cpp deleted file mode 100644 index f1f5324..0000000 --- a/examples/animation/sub-attaq/bomb.cpp +++ /dev/null @@ -1,124 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "bomb.h" -#include "submarine.h" -#include "pixmapitem.h" -#include "animationmanager.h" -#include "qanimationstate.h" - -//Qt -#include -#include -#include -#include - -Bomb::Bomb(QGraphicsItem * parent, Qt::WindowFlags wFlags) - : QGraphicsWidget(parent,wFlags), launchAnimation(0) -{ - pixmapItem = new PixmapItem(QString("bomb"),GraphicsScene::Big, this); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - setFlags(QGraphicsItem::ItemIsMovable); - setZValue(2); - resize(pixmapItem->boundingRect().size()); -} - -void Bomb::launch(Bomb::Direction direction) -{ - launchAnimation = new QSequentialAnimationGroup(); - AnimationManager::self()->registerAnimation(launchAnimation); - qreal delta = direction == Right ? 20 : - 20; - QPropertyAnimation *anim = new QPropertyAnimation(this, "pos"); - anim->setEndValue(QPointF(x() + delta,y() - 20)); - anim->setDuration(150); - launchAnimation->addAnimation(anim); - anim = new QPropertyAnimation(this, "pos"); - anim->setEndValue(QPointF(x() + delta*2, y() )); - anim->setDuration(150); - launchAnimation->addAnimation(anim); - anim = new QPropertyAnimation(this, "pos"); - anim->setEndValue(QPointF(x() + delta*2,scene()->height())); - anim->setDuration(y()/2*60); - launchAnimation->addAnimation(anim); - connect(anim,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationLaunchValueChanged(const QVariant &))); - - //We setup the state machine of the bomb - QStateMachine *machine = new QStateMachine(this); - - //This state is when the launch animation is playing - QAnimationState *launched = new QAnimationState(machine->rootState()); - launched->setAnimation(launchAnimation); - - //End - QFinalState *final = new QFinalState(machine->rootState()); - - machine->setInitialState(launched); - - //### Add a nice animation when the bomb is destroyed - launched->addTransition(this, SIGNAL(bombExplosed()),final); - - //If the animation is finished, then we move to the final state - launched->addTransition(launched, SIGNAL(animationFinished()), final); - - //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(bombExecutionFinished())); - - machine->start(); - -} - -void Bomb::onAnimationLaunchValueChanged(const QVariant &) -{ - foreach (QGraphicsItem * item , collidingItems(Qt::IntersectsItemBoundingRect)) { - if (item->type() == SubMarine::Type) { - SubMarine *s = static_cast(item); - destroy(); - s->destroy(); - } - } -} - -void Bomb::destroy() -{ - launchAnimation->stop(); - emit bombExplosed(); -} diff --git a/examples/animation/sub-attaq/bomb.h b/examples/animation/sub-attaq/bomb.h deleted file mode 100644 index 226d056..0000000 --- a/examples/animation/sub-attaq/bomb.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __BOMB__H__ -#define __BOMB__H__ - -//Qt -#include -#include - -class PixmapItem; - -class Bomb : public QGraphicsWidget -{ -Q_OBJECT -Q_PROPERTY(QPointF pos READ pos WRITE setPos) -public: - enum Direction { - Left = 0, - Right - }; - Bomb(QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0); - void launch(Direction direction); - void destroy(); - -Q_SIGNALS: - void bombExplosed(); - void bombExecutionFinished(); - -private slots: - void onAnimationLaunchValueChanged(const QVariant &); - -private: - QAnimationGroup *launchAnimation; - PixmapItem *pixmapItem; -}; - -#endif //__BOMB__H__ diff --git a/examples/animation/sub-attaq/custompropertyanimation.cpp b/examples/animation/sub-attaq/custompropertyanimation.cpp deleted file mode 100644 index 8226cca..0000000 --- a/examples/animation/sub-attaq/custompropertyanimation.cpp +++ /dev/null @@ -1,108 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "custompropertyanimation.h" - -// Qt -#include - -CustomPropertyAnimation::CustomPropertyAnimation(QObject *parent) : - QVariantAnimation(parent), animProp(0) -{ -} - -CustomPropertyAnimation::~CustomPropertyAnimation() -{ -} - -void CustomPropertyAnimation::setProperty(AbstractProperty *_animProp) -{ - if (animProp == _animProp) - return; - delete animProp; - animProp = _animProp; -} - -/*! - \reimp - */ -void CustomPropertyAnimation::updateCurrentValue(const QVariant &value) -{ - if (!animProp || state() == QAbstractAnimation::Stopped) - return; - - animProp->write(value); -} - - -/*! - \reimp -*/ -void CustomPropertyAnimation::updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState) -{ - // Initialize start value - if (oldState == QAbstractAnimation::Stopped) { - if (!animProp) - return; - QVariant def = animProp->read(); - if (def.isValid()) { - const int t = def.userType(); - KeyValues values = keyValues(); - //this ensures that all the keyValues are of type t - for (int i = 0; i < values.count(); ++i) { - QVariantAnimation::KeyValue &pair = values[i]; - if (pair.second.userType() != t) - pair.second.convert(static_cast(t)); - } - //let's now update the key values - setKeyValues(values); - } - - if (animProp && !startValue().isValid() && currentTime() == 0 - || (currentTime() == duration() && currentLoop() == (loopCount() - 1))) { - setStartValue(def); - } - } - - QVariantAnimation::updateState(oldState, newState); -} - -#include "moc_custompropertyanimation.cpp" diff --git a/examples/animation/sub-attaq/custompropertyanimation.h b/examples/animation/sub-attaq/custompropertyanimation.h deleted file mode 100644 index 8654aeb..0000000 --- a/examples/animation/sub-attaq/custompropertyanimation.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef CUSTOMPROPERTYANIMATION_H -#define CUSTOMPROPERTYANIMATION_H - -#include - -QT_BEGIN_NAMESPACE -class QGraphicsItem; -QT_END_NAMESPACE - -struct AbstractProperty -{ - virtual QVariant read() const = 0; - virtual void write(const QVariant &value) = 0; -}; - - -class CustomPropertyAnimation : public QVariantAnimation -{ - Q_OBJECT - - template - class MemberFunctionProperty : public AbstractProperty - { - public: - typedef T (Target::*Getter)(void) const; - typedef void (Target::*Setter)(T2); - - MemberFunctionProperty(Target* target, Getter getter, Setter setter) - : m_target(target), m_getter(getter), m_setter(setter) {} - - virtual void write(const QVariant &value) - { - if (m_setter) (m_target->*m_setter)(qVariantValue(value)); - } - - virtual QVariant read() const - { - if (m_getter) return qVariantFromValue((m_target->*m_getter)()); - return QVariant(); - } - - private: - Target *m_target; - Getter m_getter; - Setter m_setter; - }; - -public: - CustomPropertyAnimation(QObject *parent = 0); - ~CustomPropertyAnimation(); - - template - void setMemberFunctions(Target* target, T (Target::*getter)() const, void (Target::*setter)(const T& )) - { - setProperty(new MemberFunctionProperty(target, getter, setter)); - } - - template - void setMemberFunctions(Target* target, T (Target::*getter)() const, void (Target::*setter)(T)) - { - setProperty(new MemberFunctionProperty(target, getter, setter)); - } - - void updateCurrentValue(const QVariant &value); - void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - void setProperty(AbstractProperty *animProp); - -private: - Q_DISABLE_COPY(CustomPropertyAnimation); - AbstractProperty *animProp; -}; - -#endif // CUSTOMPROPERTYANIMATION_H diff --git a/examples/animation/sub-attaq/data.xml b/examples/animation/sub-attaq/data.xml deleted file mode 100644 index 41d4754..0000000 --- a/examples/animation/sub-attaq/data.xml +++ /dev/null @@ -1,15 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/graphicsscene.cpp b/examples/animation/sub-attaq/graphicsscene.cpp deleted file mode 100644 index f2d41bc..0000000 --- a/examples/animation/sub-attaq/graphicsscene.cpp +++ /dev/null @@ -1,374 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "graphicsscene.h" -#include "states.h" -#include "boat.h" -#include "submarine.h" -#include "torpedo.h" -#include "bomb.h" -#include "pixmapitem.h" -#include "custompropertyanimation.h" -#include "animationmanager.h" -#include "qanimationstate.h" -#include "progressitem.h" - -//Qt -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -//helper function that creates an animation for position and inserts it into group -static CustomPropertyAnimation *addGraphicsItemPosAnimation(QSequentialAnimationGroup *group, - QGraphicsItem *item, const QPointF &endPos) -{ - CustomPropertyAnimation *ret = new CustomPropertyAnimation(group); - ret->setMemberFunctions(item, &QGraphicsItem::pos, &QGraphicsItem::setPos); - ret->setEndValue(endPos); - ret->setDuration(200); - ret->setEasingCurve(QEasingCurve::OutElastic); - group->addPause(50); - return ret; -} - -//helper function that creates an animation for opacity and inserts it into group -static void addGraphicsItemFadeoutAnimation(QAnimationGroup *group, QGraphicsItem *item) -{ -#if QT_VERSION >=0x040500 - CustomPropertyAnimation *anim = new CustomPropertyAnimation(group); - anim->setMemberFunctions(item, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim->setDuration(800); - anim->setEndValue(0); - anim->setEasingCurve(QEasingCurve::OutQuad); -#else - // work around for a bug where we don't transition if the duration is zero. - QtPauseAnimation *anim = new QtPauseAnimation(group); - anim->setDuration(1); -#endif -} - -GraphicsScene::GraphicsScene(int x, int y, int width, int height, Mode mode) - : QGraphicsScene(x,y,width,height), mode(mode), newAction(0), quitAction(0), boat(0) -{ - backgroundItem = new PixmapItem(QString("background"),mode); - backgroundItem->setZValue(1); - backgroundItem->setPos(0,0); - addItem(backgroundItem); - - PixmapItem *surfaceItem = new PixmapItem(QString("surface"),mode); - surfaceItem->setZValue(3); - surfaceItem->setPos(0,sealLevel() - surfaceItem->boundingRect().height()/2); - addItem(surfaceItem); - - //The item that display score and level - progressItem = new ProgressItem(backgroundItem); - - //We create the boat - boat = new Boat(); - addItem(boat); - boat->setPos(this->width()/2, sealLevel() - boat->size().height()); - boat->hide(); - - //parse the xml that contain all data of the game - QXmlStreamReader reader; - QFile file(QDir::currentPath() + "/data.xml"); - file.open(QIODevice::ReadOnly); - reader.setDevice(&file); - LevelDescription currentLevel; - while (!reader.atEnd()) { - reader.readNext(); - if (reader.tokenType() == QXmlStreamReader::StartElement) { - if (reader.name() == "submarine") - { - SubmarineDescription desc; - desc.name = reader.attributes().value("name").toString(); - desc.points = reader.attributes().value("points").toString().toInt(); - desc.type = reader.attributes().value("type").toString().toInt(); - submarinesData.append(desc); - } - if (reader.name() == "level") - { - currentLevel.id = reader.attributes().value("id").toString().toInt(); - currentLevel.name = reader.attributes().value("name").toString(); - } - if (reader.name() == "subinstance") - { - currentLevel.submarines.append(qMakePair(reader.attributes().value("type").toString().toInt(),reader.attributes().value("nb").toString().toInt())); - } - } - if (reader.tokenType() == QXmlStreamReader::EndElement) { - if (reader.name() == "level") - { - levelsData.insert(currentLevel.id,currentLevel); - currentLevel.submarines.clear(); - } - } - } -} - -qreal GraphicsScene::sealLevel() const -{ - if (mode == Big) - return 220; - else - return 160; -} - -void GraphicsScene::setupScene(const QList &actions) -{ - newAction = actions.at(0); - quitAction = actions.at(1); - - QGraphicsItem *logo_s = addWelcomeItem(QPixmap(":/logo-s")); - QGraphicsItem *logo_u = addWelcomeItem(QPixmap(":/logo-u")); - QGraphicsItem *logo_b = addWelcomeItem(QPixmap(":/logo-b")); - QGraphicsItem *logo_dash = addWelcomeItem(QPixmap(":/logo-dash")); - QGraphicsItem *logo_a = addWelcomeItem(QPixmap(":/logo-a")); - QGraphicsItem *logo_t = addWelcomeItem(QPixmap(":/logo-t")); - QGraphicsItem *logo_t2 = addWelcomeItem(QPixmap(":/logo-t2")); - QGraphicsItem *logo_a2 = addWelcomeItem(QPixmap(":/logo-a2")); - QGraphicsItem *logo_q = addWelcomeItem(QPixmap(":/logo-q")); - QGraphicsItem *logo_excl = addWelcomeItem(QPixmap(":/logo-excl")); - logo_s->setZValue(3); - logo_u->setZValue(4); - logo_b->setZValue(5); - logo_dash->setZValue(6); - logo_a->setZValue(7); - logo_t->setZValue(8); - logo_t2->setZValue(9); - logo_a2->setZValue(10); - logo_q->setZValue(11); - logo_excl->setZValue(12); - logo_s->setPos(QPointF(-1000, -1000)); - logo_u->setPos(QPointF(-800, -1000)); - logo_b->setPos(QPointF(-600, -1000)); - logo_dash->setPos(QPointF(-400, -1000)); - logo_a->setPos(QPointF(1000, 2000)); - logo_t->setPos(QPointF(800, 2000)); - logo_t2->setPos(QPointF(600, 2000)); - logo_a2->setPos(QPointF(400, 2000)); - logo_q->setPos(QPointF(200, 2000)); - logo_excl->setPos(QPointF(0, 2000)); - - QSequentialAnimationGroup * lettersGroupMoving = new QSequentialAnimationGroup(this); - QParallelAnimationGroup * lettersGroupFading = new QParallelAnimationGroup(this); - - //creation of the animations for moving letters - addGraphicsItemPosAnimation(lettersGroupMoving, logo_s, QPointF(300, 150)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_u, QPointF(350, 150)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_b, QPointF(400, 120)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_dash, QPointF(460, 150)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_a, QPointF(350, 250)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_t, QPointF(400, 250)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_t2, QPointF(430, 250)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_a2, QPointF(465, 250)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_q, QPointF(510, 250)); - addGraphicsItemPosAnimation(lettersGroupMoving, logo_excl, QPointF(570, 220)); - - //creation of the animations for fading out the letters - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_s); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_u); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_b); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_dash); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_a); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_t); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_t2); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_a2); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_q); - addGraphicsItemFadeoutAnimation(lettersGroupFading, logo_excl); - connect(lettersGroupFading, SIGNAL(finished()), this, SLOT(onIntroAnimationFinished())); - - QStateMachine *machine = new QStateMachine(this); - - //This state is when the player is playing - PlayState *gameState = new PlayState(this,machine->rootState()); - - //Final state - QFinalState *final = new QFinalState(machine->rootState()); - - //Animation when the player enter in the game - QAnimationState *lettersMovingState = new QAnimationState(machine->rootState()); - lettersMovingState->setAnimation(lettersGroupMoving); - - //Animation when the welcome screen disappear - QAnimationState *lettersFadingState = new QAnimationState(machine->rootState()); - lettersFadingState->setAnimation(lettersGroupFading); - - //if new game then we fade out the welcome screen and start playing - lettersMovingState->addTransition(newAction, SIGNAL(triggered()),lettersFadingState); - lettersFadingState->addTransition(lettersFadingState, SIGNAL(animationFinished()),gameState); - - //New Game is triggered then player start playing - gameState->addTransition(newAction, SIGNAL(triggered()),gameState); - - //Wanna quit, then connect to CTRL+Q - gameState->addTransition(quitAction, SIGNAL(triggered()),final); - lettersMovingState->addTransition(quitAction, SIGNAL(triggered()),final); - - //Welcome screen is the initial state - machine->setInitialState(lettersMovingState); - - machine->start(); - - //We reach the final state, then we quit - connect(machine,SIGNAL(finished()),this, SLOT(onQuitGameTriggered())); -} - -void GraphicsScene::addItem(Bomb *bomb) -{ - bombs.insert(bomb); - connect(bomb,SIGNAL(bombExecutionFinished()),this, SLOT(onBombExecutionFinished())); - QGraphicsScene::addItem(bomb); -} - -void GraphicsScene::addItem(Torpedo *torpedo) -{ - torpedos.insert(torpedo); - connect(torpedo,SIGNAL(torpedoExecutionFinished()),this, SLOT(onTorpedoExecutionFinished())); - QGraphicsScene::addItem(torpedo); -} - -void GraphicsScene::addItem(SubMarine *submarine) -{ - submarines.insert(submarine); - connect(submarine,SIGNAL(subMarineExecutionFinished()),this, SLOT(onSubMarineExecutionFinished())); - QGraphicsScene::addItem(submarine); -} - -void GraphicsScene::addItem(QGraphicsItem *item) -{ - QGraphicsScene::addItem(item); -} - -void GraphicsScene::mousePressEvent (QGraphicsSceneMouseEvent * event) -{ - event->ignore(); -} - -void GraphicsScene::onQuitGameTriggered() -{ - qApp->closeAllWindows(); -} - -void GraphicsScene::onBombExecutionFinished() -{ - Bomb *bomb = qobject_cast(sender()); - bombs.remove(bomb); - bomb->deleteLater(); - if (boat) - boat->setBombsLaunched(boat->bombsLaunched() - 1); -} - -void GraphicsScene::onTorpedoExecutionFinished() -{ - Torpedo *torpedo = qobject_cast(sender()); - torpedos.remove(torpedo); - torpedo->deleteLater(); -} - -void GraphicsScene::onSubMarineExecutionFinished() -{ - SubMarine *submarine = qobject_cast(sender()); - submarines.remove(submarine); - if (submarines.count() == 0) { - emit allSubMarineDestroyed(submarine->points()); - } else { - emit subMarineDestroyed(submarine->points()); - } - submarine->deleteLater(); -} - -int GraphicsScene::remainingSubMarines() const -{ - return submarines.count(); -} - -void GraphicsScene::clearScene() -{ - foreach (SubMarine *sub,submarines) { - sub->destroy(); - sub->deleteLater(); - } - - foreach (Torpedo *torpedo,torpedos) { - torpedo->destroy(); - torpedo->deleteLater(); - } - - foreach (Bomb *bomb,bombs) { - bomb->destroy(); - bomb->deleteLater(); - } - - submarines.clear(); - bombs.clear(); - torpedos.clear(); - - AnimationManager::self()->unregisterAllAnimations(); - - boat->stop(); - boat->hide(); -} - -QGraphicsPixmapItem *GraphicsScene::addWelcomeItem(const QPixmap &pm) -{ - QGraphicsPixmapItem *item = addPixmap(pm); - welcomeItems << item; - return item; -} - -void GraphicsScene::onIntroAnimationFinished() -{ - qDeleteAll(welcomeItems); - welcomeItems.clear(); -} - diff --git a/examples/animation/sub-attaq/graphicsscene.h b/examples/animation/sub-attaq/graphicsscene.h deleted file mode 100644 index 8b0ea96..0000000 --- a/examples/animation/sub-attaq/graphicsscene.h +++ /dev/null @@ -1,131 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __GRAPHICSSCENE__H__ -#define __GRAPHICSSCENE__H__ - -//Qt -#include -#include -#include - - -class Boat; -class SubMarine; -class Torpedo; -class Bomb; -class PixmapItem; -class ProgressItem; -QT_BEGIN_NAMESPACE -class QAction; -QT_END_NAMESPACE - -class GraphicsScene : public QGraphicsScene -{ -Q_OBJECT -public: - enum Mode { - Big = 0, - Small - }; - - struct SubmarineDescription { - int type; - int points; - QString name; - }; - - struct LevelDescription { - int id; - QString name; - QList > submarines; - }; - - GraphicsScene(int x, int y, int width, int height, Mode mode = Big); - qreal sealLevel() const; - void setupScene(const QList &actions); - void addItem(Bomb *bomb); - void addItem(Torpedo *torpedo); - void addItem(SubMarine *submarine); - void addItem(QGraphicsItem *item); - int remainingSubMarines() const; - void clearScene(); - QGraphicsPixmapItem *addWelcomeItem(const QPixmap &pm); - -Q_SIGNALS: - void subMarineDestroyed(int); - void allSubMarineDestroyed(int); - -protected: - void mousePressEvent (QGraphicsSceneMouseEvent * event); - -private slots: - void onQuitGameTriggered(); - void onBombExecutionFinished(); - void onTorpedoExecutionFinished(); - void onSubMarineExecutionFinished(); - void onIntroAnimationFinished(); - -private: - Mode mode; - PixmapItem *backgroundItem; - ProgressItem *progressItem; - QAction * newAction; - QAction * quitAction; - Boat *boat; - QSet submarines; - QSet bombs; - QSet torpedos; - QVector welcomeItems; - QVector submarinesData; - QHash levelsData; - - friend class PauseState; - friend class PlayState; - friend class LevelState; - friend class LostState; - friend class WinState; - friend class WinTransition; - friend class UpdateScoreTransition; -}; - -#endif //__GRAPHICSSCENE__H__ - diff --git a/examples/animation/sub-attaq/main.cpp b/examples/animation/sub-attaq/main.cpp deleted file mode 100644 index ffaa86f..0000000 --- a/examples/animation/sub-attaq/main.cpp +++ /dev/null @@ -1,57 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include "mainwindow.h" - -int main(int argc, char *argv[]) -{ - QApplication app(argc, argv); - Q_INIT_RESOURCE(subattaq); - - qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); - - MainWindow w; - w.show(); - - return app.exec(); -} diff --git a/examples/animation/sub-attaq/mainwindow.cpp b/examples/animation/sub-attaq/mainwindow.cpp deleted file mode 100644 index a166241..0000000 --- a/examples/animation/sub-attaq/mainwindow.cpp +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "mainwindow.h" -#include "graphicsscene.h" - -#ifndef QT_NO_OPENGL - #include -#endif -//Qt -#include - -MainWindow::MainWindow() : QMainWindow(0) -{ - QMenuBar *menuBar = new QMenuBar; - QMenu *file = new QMenu(tr("&File"),menuBar); - - QAction *newAction = new QAction(tr("New Game"),file); - newAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_N)); - file->addAction(newAction); - QAction *quitAction = new QAction(tr("Quit"),file); - quitAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_Q)); - file->addAction(quitAction); - - menuBar->addMenu(file); - setMenuBar(menuBar); - - QStringList list = QApplication::arguments(); - if (list.contains("-fullscreen")) { - scene = new GraphicsScene(0, 0, 750, 400,GraphicsScene::Small); - setWindowState(Qt::WindowFullScreen); - } else { - scene = new GraphicsScene(0, 0, 880, 630); - layout()->setSizeConstraint(QLayout::SetFixedSize); - } - - view = new QGraphicsView(scene,this); - view->setAlignment(Qt::AlignLeft | Qt::AlignTop); - QList actions; - actions << newAction << quitAction; - scene->setupScene(actions); -#ifndef QT_NO_OPENGL - view->setViewport(new QGLWidget(QGLFormat(QGL::SampleBuffers))); -#endif - - setCentralWidget(view); - -} - -MainWindow::~MainWindow() -{ -} - diff --git a/examples/animation/sub-attaq/mainwindow.h b/examples/animation/sub-attaq/mainwindow.h deleted file mode 100644 index 87f194a..0000000 --- a/examples/animation/sub-attaq/mainwindow.h +++ /dev/null @@ -1,64 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __MAINWINDOW__H__ -#define __MAINWINDOW__H__ - -//Qt -#include -class GraphicsScene; -QT_BEGIN_NAMESPACE -class QGraphicsView; -QT_END_NAMESPACE - -class MainWindow : public QMainWindow -{ -Q_OBJECT -public: - MainWindow(); - ~MainWindow(); - -private: - GraphicsScene *scene; - QGraphicsView *view; -}; - -#endif //__MAINWINDOW__H__ diff --git a/examples/animation/sub-attaq/pics/big/background.png b/examples/animation/sub-attaq/pics/big/background.png deleted file mode 100644 index 9f58157..0000000 Binary files a/examples/animation/sub-attaq/pics/big/background.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/boat.png b/examples/animation/sub-attaq/pics/big/boat.png deleted file mode 100644 index be82dff..0000000 Binary files a/examples/animation/sub-attaq/pics/big/boat.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/bomb.png b/examples/animation/sub-attaq/pics/big/bomb.png deleted file mode 100644 index 3af5f2f..0000000 Binary files a/examples/animation/sub-attaq/pics/big/bomb.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png deleted file mode 100644 index c9fd8b0..0000000 Binary files a/examples/animation/sub-attaq/pics/big/explosion/boat/step1.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png deleted file mode 100644 index 7528f2d..0000000 Binary files a/examples/animation/sub-attaq/pics/big/explosion/boat/step2.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png deleted file mode 100644 index aae9c9c..0000000 Binary files a/examples/animation/sub-attaq/pics/big/explosion/boat/step3.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png b/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png deleted file mode 100644 index d697c1b..0000000 Binary files a/examples/animation/sub-attaq/pics/big/explosion/boat/step4.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png deleted file mode 100644 index 88ca514..0000000 Binary files a/examples/animation/sub-attaq/pics/big/explosion/submarine/step1.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png deleted file mode 100644 index 524f589..0000000 Binary files a/examples/animation/sub-attaq/pics/big/explosion/submarine/step2.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png deleted file mode 100644 index 2cca1e8..0000000 Binary files a/examples/animation/sub-attaq/pics/big/explosion/submarine/step3.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png b/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png deleted file mode 100644 index 82100a8..0000000 Binary files a/examples/animation/sub-attaq/pics/big/explosion/submarine/step4.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/submarine.png b/examples/animation/sub-attaq/pics/big/submarine.png deleted file mode 100644 index df435dc..0000000 Binary files a/examples/animation/sub-attaq/pics/big/submarine.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/surface.png b/examples/animation/sub-attaq/pics/big/surface.png deleted file mode 100644 index 4eba29e..0000000 Binary files a/examples/animation/sub-attaq/pics/big/surface.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/big/torpedo.png b/examples/animation/sub-attaq/pics/big/torpedo.png deleted file mode 100644 index f9c2687..0000000 Binary files a/examples/animation/sub-attaq/pics/big/torpedo.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/scalable/background-n810.svg b/examples/animation/sub-attaq/pics/scalable/background-n810.svg deleted file mode 100644 index ece9f7a..0000000 --- a/examples/animation/sub-attaq/pics/scalable/background-n810.svg +++ /dev/null @@ -1,171 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/background.svg b/examples/animation/sub-attaq/pics/scalable/background.svg deleted file mode 100644 index 0be2680..0000000 --- a/examples/animation/sub-attaq/pics/scalable/background.svg +++ /dev/null @@ -1,171 +0,0 @@ - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/boat.svg b/examples/animation/sub-attaq/pics/scalable/boat.svg deleted file mode 100644 index 5298821b..0000000 --- a/examples/animation/sub-attaq/pics/scalable/boat.svg +++ /dev/null @@ -1,279 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/bomb.svg b/examples/animation/sub-attaq/pics/scalable/bomb.svg deleted file mode 100644 index 294771a..0000000 --- a/examples/animation/sub-attaq/pics/scalable/bomb.svg +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/sand.svg b/examples/animation/sub-attaq/pics/scalable/sand.svg deleted file mode 100644 index 8af11b7..0000000 --- a/examples/animation/sub-attaq/pics/scalable/sand.svg +++ /dev/null @@ -1,103 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/see.svg b/examples/animation/sub-attaq/pics/scalable/see.svg deleted file mode 100644 index 0666691..0000000 --- a/examples/animation/sub-attaq/pics/scalable/see.svg +++ /dev/null @@ -1,44 +0,0 @@ - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/sky.svg b/examples/animation/sub-attaq/pics/scalable/sky.svg deleted file mode 100644 index 1546c08..0000000 --- a/examples/animation/sub-attaq/pics/scalable/sky.svg +++ /dev/null @@ -1,45 +0,0 @@ - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg b/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg deleted file mode 100644 index b075179..0000000 --- a/examples/animation/sub-attaq/pics/scalable/sub-attaq.svg +++ /dev/null @@ -1,1473 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - image/svg+xml - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/submarine.svg b/examples/animation/sub-attaq/pics/scalable/submarine.svg deleted file mode 100644 index 8a0ffdd..0000000 --- a/examples/animation/sub-attaq/pics/scalable/submarine.svg +++ /dev/null @@ -1,214 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/surface.svg b/examples/animation/sub-attaq/pics/scalable/surface.svg deleted file mode 100644 index 40ed239..0000000 --- a/examples/animation/sub-attaq/pics/scalable/surface.svg +++ /dev/null @@ -1,49 +0,0 @@ - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/scalable/torpedo.svg b/examples/animation/sub-attaq/pics/scalable/torpedo.svg deleted file mode 100644 index 48e429d..0000000 --- a/examples/animation/sub-attaq/pics/scalable/torpedo.svg +++ /dev/null @@ -1,127 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/examples/animation/sub-attaq/pics/small/background.png b/examples/animation/sub-attaq/pics/small/background.png deleted file mode 100644 index 5ad3db6..0000000 Binary files a/examples/animation/sub-attaq/pics/small/background.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/small/boat.png b/examples/animation/sub-attaq/pics/small/boat.png deleted file mode 100644 index 114ccc3..0000000 Binary files a/examples/animation/sub-attaq/pics/small/boat.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/small/bomb.png b/examples/animation/sub-attaq/pics/small/bomb.png deleted file mode 100644 index 3af5f2f..0000000 Binary files a/examples/animation/sub-attaq/pics/small/bomb.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/small/submarine.png b/examples/animation/sub-attaq/pics/small/submarine.png deleted file mode 100644 index 0c0c350..0000000 Binary files a/examples/animation/sub-attaq/pics/small/submarine.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/small/surface.png b/examples/animation/sub-attaq/pics/small/surface.png deleted file mode 100644 index 06d0e47..0000000 Binary files a/examples/animation/sub-attaq/pics/small/surface.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/small/torpedo.png b/examples/animation/sub-attaq/pics/small/torpedo.png deleted file mode 100644 index f9c2687..0000000 Binary files a/examples/animation/sub-attaq/pics/small/torpedo.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-a.png b/examples/animation/sub-attaq/pics/welcome/logo-a.png deleted file mode 100644 index 67dd76d..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-a.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-a2.png b/examples/animation/sub-attaq/pics/welcome/logo-a2.png deleted file mode 100644 index 17668b0..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-a2.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-b.png b/examples/animation/sub-attaq/pics/welcome/logo-b.png deleted file mode 100644 index cf6c045..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-b.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-dash.png b/examples/animation/sub-attaq/pics/welcome/logo-dash.png deleted file mode 100644 index 219233c..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-dash.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-excl.png b/examples/animation/sub-attaq/pics/welcome/logo-excl.png deleted file mode 100644 index 8dd0a2e..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-excl.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-q.png b/examples/animation/sub-attaq/pics/welcome/logo-q.png deleted file mode 100644 index 86e588d..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-q.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-s.png b/examples/animation/sub-attaq/pics/welcome/logo-s.png deleted file mode 100644 index 7b6a36e..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-s.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-t.png b/examples/animation/sub-attaq/pics/welcome/logo-t.png deleted file mode 100644 index b2e3526..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-t.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-t2.png b/examples/animation/sub-attaq/pics/welcome/logo-t2.png deleted file mode 100644 index b11a778..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-t2.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pics/welcome/logo-u.png b/examples/animation/sub-attaq/pics/welcome/logo-u.png deleted file mode 100644 index 24eede8..0000000 Binary files a/examples/animation/sub-attaq/pics/welcome/logo-u.png and /dev/null differ diff --git a/examples/animation/sub-attaq/pixmapitem.cpp b/examples/animation/sub-attaq/pixmapitem.cpp deleted file mode 100644 index 22a363f..0000000 --- a/examples/animation/sub-attaq/pixmapitem.cpp +++ /dev/null @@ -1,59 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "pixmapitem.h" - -//Qt -#include - -PixmapItem::PixmapItem(const QString &fileName,GraphicsScene::Mode mode, QGraphicsItem * parent) : QGraphicsPixmapItem(parent),name(fileName) -{ - loadPixmap(mode); -} - -void PixmapItem::loadPixmap(GraphicsScene::Mode mode) -{ - if (mode == GraphicsScene::Big) - setPixmap(":/big/" + name); - else - setPixmap(":/small/" + name); -} diff --git a/examples/animation/sub-attaq/pixmapitem.h b/examples/animation/sub-attaq/pixmapitem.h deleted file mode 100644 index 31022c1..0000000 --- a/examples/animation/sub-attaq/pixmapitem.h +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __PIXMAPITEM__H__ -#define __PIXMAPITEM__H__ - -//Own -#include "graphicsscene.h" - -//Qt -#include - -class PixmapItem : public QGraphicsPixmapItem -{ -public: - PixmapItem(const QString &fileName, GraphicsScene::Mode mode, QGraphicsItem * parent = 0); - -private: - void loadPixmap(GraphicsScene::Mode mode); - - QString name; - QPixmap pixmap; -}; - -#endif //__PIXMAPITEM__H__ diff --git a/examples/animation/sub-attaq/progressitem.cpp b/examples/animation/sub-attaq/progressitem.cpp deleted file mode 100644 index 59ccb9a..0000000 --- a/examples/animation/sub-attaq/progressitem.cpp +++ /dev/null @@ -1,67 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "progressitem.h" -#include "pixmapitem.h" - -ProgressItem::ProgressItem (QGraphicsItem * parent) - : QGraphicsTextItem(parent), currentLevel(1), currentScore(0) -{ - setFont(QFont("Comic Sans MS")); - setPos(parentItem()->boundingRect().topRight() - QPointF(180, -5)); -} - -void ProgressItem::setLevel(int level) -{ - currentLevel = level; - updateProgress(); -} - -void ProgressItem::setScore(int score) -{ - currentScore = score; - updateProgress(); -} - -void ProgressItem::updateProgress() -{ - setHtml(QString("Level : %1 Score : %2").arg(currentLevel).arg(currentScore)); -} diff --git a/examples/animation/sub-attaq/progressitem.h b/examples/animation/sub-attaq/progressitem.h deleted file mode 100644 index 7b8db4d..0000000 --- a/examples/animation/sub-attaq/progressitem.h +++ /dev/null @@ -1,61 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef PROGRESSITEM_H -#define PROGRESSITEM_H - -//Qt -#include - -class ProgressItem : public QGraphicsTextItem -{ -public: - ProgressItem(QGraphicsItem * parent = 0); - void setLevel(int level); - void setScore(int score); - -private: - void updateProgress(); - int currentLevel; - int currentScore; -}; - -#endif // PROGRESSITEM_H diff --git a/examples/animation/sub-attaq/qanimationstate.cpp b/examples/animation/sub-attaq/qanimationstate.cpp deleted file mode 100644 index 26e0ef3..0000000 --- a/examples/animation/sub-attaq/qanimationstate.cpp +++ /dev/null @@ -1,171 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qanimationstate.h" - -#include -#include - - -QT_BEGIN_NAMESPACE - -/*! -\class QAnimationState - -\brief The QAnimationState class provides state that handle an animation and emit -a signal when this animation is finished. - -\ingroup statemachine - -QAnimationState provides a state that handle an animation. It will start this animation -when the state is entered and stop it when it is leaved. When the animation has finished the -state emit animationFinished signal. -QAnimationState is part of \l{The State Machine Framework}. - -\code -QStateMachine machine; -QAnimationState *s = new QAnimationState(machine->rootState()); -QPropertyAnimation *animation = new QPropertyAnimation(obj, "pos"); -s->setAnimation(animation); -QState *s2 = new QState(machine->rootState()); -s->addTransition(s, SIGNAL(animationFinished()), s2); -machine.start(); -\endcode - -\sa QState, {The Animation Framework} -*/ - - -#ifndef QT_NO_ANIMATION - -class QAnimationStatePrivate : public QStatePrivate -{ - Q_DECLARE_PUBLIC(QAnimationState) -public: - QAnimationStatePrivate() - : animation(0) - { - - } - ~QAnimationStatePrivate() {} - - QAbstractAnimation *animation; -}; - -/*! - Constructs a new state with the given \a parent state. -*/ -QAnimationState::QAnimationState(QState *parent) - : QState(*new QAnimationStatePrivate, parent) -{ -} - -/*! - Destroys the animation state. -*/ -QAnimationState::~QAnimationState() -{ -} - -/*! - Set an \a animation for this QAnimationState. If an animation was previously handle by this - state then it won't emit animationFinished for the old animation. The QAnimationState doesn't - take the ownership of the animation. -*/ -void QAnimationState::setAnimation(QAbstractAnimation *animation) -{ - Q_D(QAnimationState); - - if (animation == d->animation) - return; - - //Disconnect from the previous animation if exist - if(d->animation) - disconnect(d->animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); - - d->animation = animation; - - if (d->animation) { - //connect the new animation - connect(d->animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); - } -} - -/*! - Returns the animation handle by this animation state, or 0 if there is no animation. -*/ -QAbstractAnimation* QAnimationState::animation() const -{ - Q_D(const QAnimationState); - return d->animation; -} - -/*! - \reimp -*/ -void QAnimationState::onEntry(QEvent *) -{ - Q_D(QAnimationState); - if (d->animation) - d->animation->start(); -} - -/*! - \reimp -*/ -void QAnimationState::onExit(QEvent *) -{ - Q_D(QAnimationState); - if (d->animation) - d->animation->stop(); -} - -/*! - \reimp -*/ -bool QAnimationState::event(QEvent *e) -{ - return QState::event(e); -} - -QT_END_NAMESPACE - -#endif diff --git a/examples/animation/sub-attaq/qanimationstate.h b/examples/animation/sub-attaq/qanimationstate.h deleted file mode 100644 index 88c0a6d..0000000 --- a/examples/animation/sub-attaq/qanimationstate.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QANIMATIONSTATE_H -#define QANIMATIONSTATE_H - -#ifndef QT_STATEMACHINE_SOLUTION -# include -# include -#else -# include "qstate.h" -# include "qabstractanimation.h" -#endif - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Gui) - -#ifndef QT_NO_ANIMATION - -class QAnimationStatePrivate; - -class QAnimationState : public QState -{ - Q_OBJECT -public: - QAnimationState(QState *parent = 0); - ~QAnimationState(); - - void setAnimation(QAbstractAnimation *animation); - QAbstractAnimation* animation() const; - -Q_SIGNALS: - void animationFinished(); - -protected: - void onEntry(QEvent *); - void onExit(QEvent *); - bool event(QEvent *e); - -private: - Q_DISABLE_COPY(QAnimationState) - Q_DECLARE_PRIVATE(QAnimationState) -}; - -#endif - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QANIMATIONSTATE_H diff --git a/examples/animation/sub-attaq/states.cpp b/examples/animation/sub-attaq/states.cpp deleted file mode 100644 index adc8bd0..0000000 --- a/examples/animation/sub-attaq/states.cpp +++ /dev/null @@ -1,325 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "states.h" -#include "graphicsscene.h" -#include "boat.h" -#include "submarine.h" -#include "torpedo.h" -#include "animationmanager.h" -#include "progressitem.h" - -//Qt -#include -#include -#include -#include -#include -#include - -PlayState::PlayState(GraphicsScene *scene, QState *parent) - : QState(parent), - scene(scene), - machine(0), - currentLevel(0), - score(0) -{ -} - -PlayState::~PlayState() -{ -} - -void PlayState::onEntry(QEvent *) -{ - //We are now playing? - if (machine) { - machine->stop(); - scene->clearScene(); - currentLevel = 0; - score = 0; - delete machine; - } - - machine = new QStateMachine(this); - - //This state is when player is playing - LevelState *levelState = new LevelState(scene, this, machine->rootState()); - - //This state is when the player is actually playing but the game is not paused - QState *playingState = new QState(levelState); - levelState->setInitialState(playingState); - - //This state is when the game is paused - PauseState *pauseState = new PauseState(scene, levelState); - - //We have one view, it receive the key press event - QKeyEventTransition *pressPplay = new QKeyEventTransition(scene->views().at(0), QEvent::KeyPress, Qt::Key_P); - pressPplay->setTargetState(pauseState); - QKeyEventTransition *pressPpause = new QKeyEventTransition(scene->views().at(0), QEvent::KeyPress, Qt::Key_P); - pressPpause->setTargetState(playingState); - - //Pause "P" is triggered, the player pause the game - playingState->addTransition(pressPplay); - - //To get back playing when the game has been paused - pauseState->addTransition(pressPpause); - - //This state is when player have lost - LostState *lostState = new LostState(scene, this, machine->rootState()); - - //This state is when player have won - WinState *winState = new WinState(scene, this, machine->rootState()); - - //The boat has been destroyed then the game is finished - levelState->addTransition(scene->boat, SIGNAL(boatExecutionFinished()),lostState); - - //This transition check if we won or not - WinTransition *winTransition = new WinTransition(scene, this, winState); - - //The boat has been destroyed then the game is finished - levelState->addTransition(winTransition); - - //This state is an animation when the score changed - UpdateScoreState *scoreState = new UpdateScoreState(this, levelState); - - //This transition update the score when a submarine die - UpdateScoreTransition *scoreTransition = new UpdateScoreTransition(scene, this, levelState); - scoreTransition->setTargetState(scoreState); - - //The boat has been destroyed then the game is finished - playingState->addTransition(scoreTransition); - - //We go back to play state - scoreState->addTransition(playingState); - - //We start playing!!! - machine->setInitialState(levelState); - - //Final state - QFinalState *final = new QFinalState(machine->rootState()); - - //This transition is triggered when the player press space after completing a level - CustomSpaceTransition *spaceTransition = new CustomSpaceTransition(scene->views().at(0), this, QEvent::KeyPress, Qt::Key_Space); - spaceTransition->setTargetState(levelState); - winState->addTransition(spaceTransition); - - //We lost we should reach the final state - lostState->addTransition(lostState, SIGNAL(finished()), final); - - machine->start(); -} - -LevelState::LevelState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) -{ -} -void LevelState::onEntry(QEvent *) -{ - initializeLevel(); -} - -void LevelState::initializeLevel() -{ - //we re-init the boat - scene->boat->setPos(scene->width()/2, scene->sealLevel() - scene->boat->size().height()); - scene->boat->setCurrentSpeed(0); - scene->boat->setCurrentDirection(Boat::None); - scene->boat->setBombsLaunched(0); - scene->boat->show(); - scene->setFocusItem(scene->boat,Qt::OtherFocusReason); - scene->boat->run(); - - scene->progressItem->setScore(game->score); - scene->progressItem->setLevel(game->currentLevel + 1); - - GraphicsScene::LevelDescription currentLevelDescription = scene->levelsData.value(game->currentLevel); - - for (int i = 0; i < currentLevelDescription.submarines.size(); ++i ) { - - QPair subContent = currentLevelDescription.submarines.at(i); - GraphicsScene::SubmarineDescription submarineDesc = scene->submarinesData.at(subContent.first); - - for (int j = 0; j < subContent.second; ++j ) { - SubMarine *sub = new SubMarine(submarineDesc.type, submarineDesc.name, submarineDesc.points); - scene->addItem(sub); - int random = (qrand() % 15 + 1); - qreal x = random == 13 || random == 5 ? 0 : scene->width() - sub->size().width(); - qreal y = scene->height() -(qrand() % 150 + 1) - sub->size().height(); - sub->setPos(x,y); - sub->setCurrentDirection(x == 0 ? SubMarine::Right : SubMarine::Left); - sub->setCurrentSpeed(qrand() % 3 + 1); - } - } -} - -/** Pause State */ -PauseState::PauseState(GraphicsScene *scene, QState *parent) : QState(parent),scene(scene) -{ -} -void PauseState::onEntry(QEvent *) -{ - AnimationManager::self()->pauseAll(); - scene->boat->setEnabled(false); -} -void PauseState::onExit(QEvent *) -{ - AnimationManager::self()->resumeAll(); - scene->boat->setEnabled(true); - scene->boat->setFocus(); -} - -/** Lost State */ -LostState::LostState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) -{ -} - -void LostState::onEntry(QEvent *) -{ - //The message to display - QString message = QString("You lose on level %1. Your score is %2.").arg(game->currentLevel+1).arg(game->score); - - //We set the level back to 0 - game->currentLevel = 0; - - //We set the score back to 0 - game->score = 0; - - //We clear the scene - scene->clearScene(); - - //we have only one view - QMessageBox::information(scene->views().at(0),"You lose",message); -} - -/** Win State */ -WinState::WinState(GraphicsScene *scene, PlayState *game, QState *parent) : QState(parent), scene(scene), game(game) -{ -} - -void WinState::onEntry(QEvent *) -{ - //We clear the scene - scene->clearScene(); - - QString message; - if (scene->levelsData.size() - 1 != game->currentLevel) { - message = QString("You win the level %1. Your score is %2.\nPress Space to continue after closing this dialog.").arg(game->currentLevel+1).arg(game->score); - //We increment the level number - game->currentLevel++; - } else { - message = QString("You finish the game on level %1. Your score is %2.").arg(game->currentLevel+1).arg(game->score); - //We set the level back to 0 - game->currentLevel = 0; - //We set the score back to 0 - game->score = 0; - } - - //we have only one view - QMessageBox::information(scene->views().at(0),"You win",message); -} - -/** UpdateScore State */ -UpdateScoreState::UpdateScoreState(PlayState *game, QState *parent) : QState(parent) -{ - this->game = game; -} -void UpdateScoreState::onEntry(QEvent *e) -{ - QState::onEntry(e); -} - -/** Win transition */ -UpdateScoreTransition::UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) - : QSignalTransition(scene,SIGNAL(subMarineDestroyed(int)), QList() << target), - game(game), scene(scene) -{ -} - -bool UpdateScoreTransition::eventTest(QEvent *event) -{ - if (!QSignalTransition::eventTest(event)) - return false; - else { - QSignalEvent *se = static_cast(event); - game->score += se->arguments().at(0).toInt(); - scene->progressItem->setScore(game->score); - return true; - } -} - -/** Win transition */ -WinTransition::WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target) - : QSignalTransition(scene,SIGNAL(allSubMarineDestroyed(int)), QList() << target), - game(game), scene(scene) -{ -} - -bool WinTransition::eventTest(QEvent *event) -{ - if (!QSignalTransition::eventTest(event)) - return false; - else { - QSignalEvent *se = static_cast(event); - game->score += se->arguments().at(0).toInt(); - scene->progressItem->setScore(game->score); - return true; - } -} - -/** Space transition */ -CustomSpaceTransition::CustomSpaceTransition(QWidget *widget, PlayState *game, QEvent::Type type, int key) - : QKeyEventTransition(widget, type, key), - game(game) -{ -} - -bool CustomSpaceTransition::eventTest(QEvent *event) -{ - Q_UNUSED(event); - if (!QKeyEventTransition::eventTest(event)) - return false; - if (game->currentLevel != 0) - return true; - else - return false; - -} diff --git a/examples/animation/sub-attaq/states.h b/examples/animation/sub-attaq/states.h deleted file mode 100644 index 71375e0..0000000 --- a/examples/animation/sub-attaq/states.h +++ /dev/null @@ -1,180 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef STATES_H -#define STATES_H - -//Qt -#include -#include -#include -#include -#include - -class GraphicsScene; -class Boat; -class SubMarine; -QT_BEGIN_NAMESPACE -class QStateMachine; -QT_END_NAMESPACE - -class PlayState : public QState -{ -public: - PlayState(GraphicsScene *scene, QState *parent = 0); - ~PlayState(); - - protected: - void onEntry(QEvent *); - -private : - GraphicsScene *scene; - QStateMachine *machine; - int currentLevel; - int score; - QState *parallelChild; - - friend class UpdateScoreState; - friend class UpdateScoreTransition; - friend class WinTransition; - friend class CustomSpaceTransition; - friend class WinState; - friend class LostState; - friend class LevelState; -}; - -class LevelState : public QState -{ -public: - LevelState(GraphicsScene *scene, PlayState *game, QState *parent = 0); -protected: - void onEntry(QEvent *); -private : - void initializeLevel(); - GraphicsScene *scene; - PlayState *game; -}; - -class PauseState : public QState -{ -public: - PauseState(GraphicsScene *scene, QState *parent = 0); - -protected: - void onEntry(QEvent *); - void onExit(QEvent *); -private : - GraphicsScene *scene; - Boat *boat; -}; - -class LostState : public QState -{ -public: - LostState(GraphicsScene *scene, PlayState *game, QState *parent = 0); - -protected: - void onEntry(QEvent *); -private : - GraphicsScene *scene; - PlayState *game; -}; - -class WinState : public QState -{ -public: - WinState(GraphicsScene *scene, PlayState *game, QState *parent = 0); - -protected: - void onEntry(QEvent *); -private : - GraphicsScene *scene; - PlayState *game; -}; - -class UpdateScoreState : public QState -{ -public: - UpdateScoreState(PlayState *game, QState *parent); -protected: - void onEntry(QEvent *); -private: - QPropertyAnimation *scoreAnimation; - PlayState *game; -}; - -//These transtion is used to update the score -class UpdateScoreTransition : public QSignalTransition -{ -public: - UpdateScoreTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target); -protected: - virtual bool eventTest(QEvent *event); -private: - PlayState * game; - GraphicsScene *scene; -}; - -//These transtion test if we have won the game -class WinTransition : public QSignalTransition -{ -public: - WinTransition(GraphicsScene *scene, PlayState *game, QAbstractState *target); -protected: - virtual bool eventTest(QEvent *event); -private: - PlayState * game; - GraphicsScene *scene; -}; - -//These transtion is true if one level has been completed and the player want to continue - class CustomSpaceTransition : public QKeyEventTransition -{ -public: - CustomSpaceTransition(QWidget *widget, PlayState *game, QEvent::Type type, int key); -protected: - virtual bool eventTest(QEvent *event); -private: - PlayState *game; - int key; -}; - -#endif // STATES_H diff --git a/examples/animation/sub-attaq/sub-attaq.pro b/examples/animation/sub-attaq/sub-attaq.pro deleted file mode 100644 index d13a099..0000000 --- a/examples/animation/sub-attaq/sub-attaq.pro +++ /dev/null @@ -1,36 +0,0 @@ -contains(QT_CONFIG, opengl):QT += opengl - -HEADERS += boat.h \ - bomb.h \ - mainwindow.h \ - submarine.h \ - torpedo.h \ - pixmapitem.h \ - graphicsscene.h \ - animationmanager.h \ - states.h \ - boat_p.h \ - submarine_p.h \ - custompropertyanimation.h \ - qanimationstate.h \ - progressitem.h -SOURCES += boat.cpp \ - bomb.cpp \ - main.cpp \ - mainwindow.cpp \ - submarine.cpp \ - torpedo.cpp \ - pixmapitem.cpp \ - graphicsscene.cpp \ - animationmanager.cpp \ - states.cpp \ - custompropertyanimation.cpp \ - qanimationstate.cpp \ - progressitem.cpp -RESOURCES += subattaq.qrc - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/animation/sub-attaq -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS sub-attaq.pro pics -sources.path = $$[QT_INSTALL_EXAMPLES]/animation/sub-attaq -INSTALLS += target sources diff --git a/examples/animation/sub-attaq/subattaq.qrc b/examples/animation/sub-attaq/subattaq.qrc deleted file mode 100644 index c76f8ef..0000000 --- a/examples/animation/sub-attaq/subattaq.qrc +++ /dev/null @@ -1,38 +0,0 @@ - - - pics/scalable/sub-attaq.svg - pics/scalable/submarine.svg - pics/scalable/boat.svg - pics/scalable/torpedo.svg - pics/welcome/logo-s.png - pics/welcome/logo-u.png - pics/welcome/logo-b.png - pics/welcome/logo-dash.png - pics/welcome/logo-a.png - pics/welcome/logo-t.png - pics/welcome/logo-t2.png - pics/welcome/logo-a2.png - pics/welcome/logo-q.png - pics/welcome/logo-excl.png - pics/big/background.png - pics/big/boat.png - pics/big/bomb.png - pics/big/submarine.png - pics/big/surface.png - pics/big/torpedo.png - pics/small/background.png - pics/small/boat.png - pics/small/bomb.png - pics/small/submarine.png - pics/small/surface.png - pics/small/torpedo.png - pics/big/explosion/boat/step1.png - pics/big/explosion/boat/step2.png - pics/big/explosion/boat/step3.png - pics/big/explosion/boat/step4.png - pics/big/explosion/submarine/step1.png - pics/big/explosion/submarine/step2.png - pics/big/explosion/submarine/step3.png - pics/big/explosion/submarine/step4.png - - diff --git a/examples/animation/sub-attaq/submarine.cpp b/examples/animation/sub-attaq/submarine.cpp deleted file mode 100644 index d8cf1da..0000000 --- a/examples/animation/sub-attaq/submarine.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "submarine.h" -#include "submarine_p.h" -#include "torpedo.h" -#include "pixmapitem.h" -#include "graphicsscene.h" -#include "animationmanager.h" -#include "custompropertyanimation.h" -#include "qanimationstate.h" - -#include -#include -#include -#include - -static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub) -{ - QSequentialAnimationGroup *group = new QSequentialAnimationGroup(sub); -#if QT_VERSION >=0x040500 - PixmapItem *step1 = new PixmapItem(QString("explosion/submarine/step1"),GraphicsScene::Big, sub); - step1->setZValue(6); - PixmapItem *step2 = new PixmapItem(QString("explosion/submarine/step2"),GraphicsScene::Big, sub); - step2->setZValue(6); - PixmapItem *step3 = new PixmapItem(QString("explosion/submarine/step3"),GraphicsScene::Big, sub); - step3->setZValue(6); - PixmapItem *step4 = new PixmapItem(QString("explosion/submarine/step4"),GraphicsScene::Big, sub); - step4->setZValue(6); - step1->setOpacity(0); - step2->setOpacity(0); - step3->setOpacity(0); - step4->setOpacity(0); - CustomPropertyAnimation *anim1 = new CustomPropertyAnimation(sub); - anim1->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim1->setDuration(100); - anim1->setEndValue(1); - CustomPropertyAnimation *anim2 = new CustomPropertyAnimation(sub); - anim2->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim2->setDuration(100); - anim2->setEndValue(1); - CustomPropertyAnimation *anim3 = new CustomPropertyAnimation(sub); - anim3->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim3->setDuration(100); - anim3->setEndValue(1); - CustomPropertyAnimation *anim4 = new CustomPropertyAnimation(sub); - anim4->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); - anim4->setDuration(100); - anim4->setEndValue(1); - group->addAnimation(anim1); - group->addAnimation(anim2); - group->addAnimation(anim3); - group->addAnimation(anim4); -#else - // work around for a bug where we don't transition if the duration is zero. - QtPauseAnimation *anim = new QtPauseAnimation(group); - anim->setDuration(1); - group->addAnimation(anim); -#endif - AnimationManager::self()->registerAnimation(group); - return group; -} - - -SubMarine::SubMarine(int type, const QString &name, int points, QGraphicsItem * parent, Qt::WindowFlags wFlags) - : QGraphicsWidget(parent,wFlags), subType(type), subName(name), subPoints(points), speed(0), direction(SubMarine::None) -{ - pixmapItem = new PixmapItem(QString("submarine"),GraphicsScene::Big, this); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - setZValue(5); - setFlags(QGraphicsItem::ItemIsMovable); - resize(pixmapItem->boundingRect().width(),pixmapItem->boundingRect().height()); - setTransformOrigin(boundingRect().center()); - - //We setup the state machine of the submarine - QStateMachine *machine = new QStateMachine(this); - - //This state is when the boat is moving/rotating - QState *moving = new QState(machine->rootState()); - - //This state is when the boat is moving from left to right - MovementState *movement = new MovementState(this, moving); - - //This state is when the boat is moving from left to right - ReturnState *rotation = new ReturnState(this, moving); - - //This is the initial state of the moving root state - moving->setInitialState(movement); - - movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving); - - //This is the initial state of the machine - machine->setInitialState(moving); - - //End - QFinalState *final = new QFinalState(machine->rootState()); - - //If the moving animation is finished we move to the return state - movement->addTransition(movement, SIGNAL(animationFinished()), rotation); - - //If the return animation is finished we move to the moving state - rotation->addTransition(rotation, SIGNAL(animationFinished()), movement); - - //This state play the destroyed animation - QAnimationState *destroyedState = new QAnimationState(machine->rootState()); - destroyedState->setAnimation(setupDestroyAnimation(this)); - - //Play a nice animation when the submarine is destroyed - moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState); - - //Transition to final state when the destroyed animation is finished - destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); - - //The machine has finished to be executed, then the submarine is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished())); - - machine->start(); -} - -int SubMarine::points() -{ - return subPoints; -} - -void SubMarine::setCurrentDirection(SubMarine::Movement direction) -{ - if (this->direction == direction) - return; - if (direction == SubMarine::Right && this->direction == SubMarine::None) { - setYRotation(180); - } - this->direction = direction; -} - -enum SubMarine::Movement SubMarine::currentDirection() const -{ - return direction; -} - -void SubMarine::setCurrentSpeed(int speed) -{ - if (speed < 0 || speed > 3) { - qWarning("SubMarine::setCurrentSpeed : The speed is invalid"); - } - this->speed = speed; - emit subMarineStateChanged(); -} - -int SubMarine::currentSpeed() const -{ - return speed; -} - -void SubMarine::launchTorpedo(int speed) -{ - Torpedo * torp = new Torpedo(); - GraphicsScene *scene = static_cast(this->scene()); - scene->addItem(torp); - torp->setPos(x(), y()); - torp->setCurrentSpeed(speed); - torp->launch(); -} - -void SubMarine::destroy() -{ - emit subMarineDestroyed(); -} - -int SubMarine::type() const -{ - return Type; -} diff --git a/examples/animation/sub-attaq/submarine.h b/examples/animation/sub-attaq/submarine.h deleted file mode 100644 index 4001603..0000000 --- a/examples/animation/sub-attaq/submarine.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __SUBMARINE__H__ -#define __SUBMARINE__H__ - -//Qt -#include -#include - -class PixmapItem; - -class Torpedo; - -class SubMarine : public QGraphicsWidget -{ -Q_OBJECT -public: - enum Movement { - None = 0, - Left, - Right - }; - enum { Type = UserType + 1 }; - SubMarine(int type, const QString &name, int points, QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0); - - int points(); - - void setCurrentDirection(Movement direction); - enum Movement currentDirection() const; - - void setCurrentSpeed(int speed); - int currentSpeed() const; - - void launchTorpedo(int speed); - void destroy(); - - virtual int type() const; - -Q_SIGNALS: - void subMarineDestroyed(); - void subMarineExecutionFinished(); - void subMarineStateChanged(); - -private: - int subType; - QString subName; - int subPoints; - int speed; - Movement direction; - PixmapItem *pixmapItem; -}; - -#endif //__SUBMARINE__H__ diff --git a/examples/animation/sub-attaq/submarine_p.h b/examples/animation/sub-attaq/submarine_p.h deleted file mode 100644 index 8c31eb7..0000000 --- a/examples/animation/sub-attaq/submarine_p.h +++ /dev/null @@ -1,139 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SUBMARINE_P_H -#define SUBMARINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -//Own -#include "animationmanager.h" -#include "submarine.h" -#include "qanimationstate.h" - -//Qt -#include -#include - -//This state is describing when the boat is moving right -class MovementState : public QAnimationState -{ -Q_OBJECT -public: - MovementState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) - { - movementAnimation = new QPropertyAnimation(submarine, "pos"); - connect(movementAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationMovementValueChanged(const QVariant &))); - setAnimation(movementAnimation); - AnimationManager::self()->registerAnimation(movementAnimation); - this->submarine = submarine; - } - -protected slots: - void onAnimationMovementValueChanged(const QVariant &) - { - if (qrand() % 200 + 1 == 3) - submarine->launchTorpedo(qrand() % 3 + 1); - } - -protected: - void onEntry(QEvent *e) - { - if (submarine->currentDirection() == SubMarine::Left) { - movementAnimation->setEndValue(QPointF(0,submarine->y())); - movementAnimation->setDuration(submarine->x()/submarine->currentSpeed()*12); - } - else /*if (submarine->currentDirection() == SubMarine::Right)*/ { - movementAnimation->setEndValue(QPointF(submarine->scene()->width()-submarine->size().width(),submarine->y())); - movementAnimation->setDuration((submarine->scene()->width()-submarine->size().width()-submarine->x())/submarine->currentSpeed()*12); - } - movementAnimation->setStartValue(submarine->pos()); - QAnimationState::onEntry(e); - } - -private: - SubMarine *submarine; - QPropertyAnimation *movementAnimation; -}; - -//This state is describing when the boat is moving right -class ReturnState : public QAnimationState -{ -public: - ReturnState(SubMarine *submarine, QState *parent = 0) : QAnimationState(parent) - { - returnAnimation = new QPropertyAnimation(submarine, "yRotation"); - AnimationManager::self()->registerAnimation(returnAnimation); - setAnimation(returnAnimation); - this->submarine = submarine; - } - -protected: - void onEntry(QEvent *e) - { - returnAnimation->stop(); - returnAnimation->setStartValue(submarine->yRotation()); - returnAnimation->setEndValue(submarine->currentDirection() == SubMarine::Right ? 360. : 180.); - returnAnimation->setDuration(500); - QAnimationState::onEntry(e); - } - - void onExit(QEvent *e) - { - submarine->currentDirection() == SubMarine::Right ? submarine->setCurrentDirection(SubMarine::Left) : submarine->setCurrentDirection(SubMarine::Right); - QAnimationState::onExit(e); - } - -private: - SubMarine *submarine; - QPropertyAnimation *returnAnimation; -}; - -#endif // SUBMARINE_P_H diff --git a/examples/animation/sub-attaq/torpedo.cpp b/examples/animation/sub-attaq/torpedo.cpp deleted file mode 100644 index 02a54fc..0000000 --- a/examples/animation/sub-attaq/torpedo.cpp +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -//Own -#include "torpedo.h" -#include "pixmapitem.h" -#include "boat.h" -#include "graphicsscene.h" -#include "animationmanager.h" -#include "qanimationstate.h" - -#include -#include -#include - -Torpedo::Torpedo(QGraphicsItem * parent, Qt::WindowFlags wFlags) - : QGraphicsWidget(parent,wFlags), currentSpeed(0), launchAnimation(0) -{ - pixmapItem = new PixmapItem(QString::fromLatin1("torpedo"),GraphicsScene::Big, this); - setZValue(2); - setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - setFlags(QGraphicsItem::ItemIsMovable); - resize(pixmapItem->boundingRect().size()); -} - -void Torpedo::launch() -{ - launchAnimation = new QPropertyAnimation(this, "pos"); - AnimationManager::self()->registerAnimation(launchAnimation); - launchAnimation->setEndValue(QPointF(x(),qobject_cast(scene())->sealLevel() - 15)); - launchAnimation->setEasingCurve(QEasingCurve::InQuad); - launchAnimation->setDuration(y()/currentSpeed*10); - connect(launchAnimation,SIGNAL(valueChanged(const QVariant &)),this,SLOT(onAnimationLaunchValueChanged(const QVariant &))); - - //We setup the state machine of the torpedo - QStateMachine *machine = new QStateMachine(this); - - //This state is when the launch animation is playing - QAnimationState *launched = new QAnimationState(machine->rootState()); - launched->setAnimation(launchAnimation); - - //End - QFinalState *final = new QFinalState(machine->rootState()); - - machine->setInitialState(launched); - - //### Add a nice animation when the torpedo is destroyed - launched->addTransition(this, SIGNAL(torpedoExplosed()),final); - - //If the animation is finished, then we move to the final state - launched->addTransition(launched, SIGNAL(animationFinished()), final); - - //The machine has finished to be executed, then the boat is dead - connect(machine,SIGNAL(finished()),this, SIGNAL(torpedoExecutionFinished())); - - machine->start(); -} - -void Torpedo::setCurrentSpeed(int speed) -{ - if (speed < 0) { - qWarning("Torpedo::setCurrentSpeed : The speed is invalid"); - return; - } - currentSpeed = speed; -} - -void Torpedo::onAnimationLaunchValueChanged(const QVariant &) -{ - foreach (QGraphicsItem *item , collidingItems(Qt::IntersectsItemBoundingRect)) { - if (item->type() == Boat::Type) { - Boat *b = static_cast(item); - b->destroy(); - } - } -} - -void Torpedo::destroy() -{ - launchAnimation->stop(); - emit torpedoExplosed(); -} diff --git a/examples/animation/sub-attaq/torpedo.h b/examples/animation/sub-attaq/torpedo.h deleted file mode 100644 index 4a0f457..0000000 --- a/examples/animation/sub-attaq/torpedo.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef __TORPEDO__H__ -#define __TORPEDO__H__ - -//Qt -#include - -#include -#include - -class PixmapItem; - -class Torpedo : public QGraphicsWidget -{ -Q_OBJECT -Q_PROPERTY(QPointF pos READ pos WRITE setPos) -public: - Torpedo(QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0); - void launch(); - void setCurrentSpeed(int speed); - void destroy(); - -Q_SIGNALS: - void torpedoExplosed(); - void torpedoExecutionFinished(); - -private slots: - void onAnimationLaunchValueChanged(const QVariant &); - -private: - int currentSpeed; - PixmapItem *pixmapItem; - QVariantAnimation *launchAnimation; -}; - -#endif //__TORPEDO__H__ diff --git a/examples/examples.pro b/examples/examples.pro index bfcf9b4..41501a0 100644 --- a/examples/examples.pro +++ b/examples/examples.pro @@ -1,6 +1,5 @@ TEMPLATE = subdirs SUBDIRS = \ - animation \ desktop \ dialogs \ draganddrop \ @@ -15,7 +14,6 @@ SUBDIRS = \ qtconcurrent \ richtext \ sql \ - statemachine \ threads \ tools \ tutorials \ diff --git a/examples/statemachine/README b/examples/statemachine/README deleted file mode 100644 index 2879e67..0000000 --- a/examples/statemachine/README +++ /dev/null @@ -1,36 +0,0 @@ -Qt is provided with a powerful hierchical finite state machine through -the Qt State Machine classes. - -The example launcher provided with Qt can be used to explore each of the -examples in this directory. - -Documentation for these examples can be found via the Tutorial and Examples -link in the main Qt documentation. - - -Finding the Qt Examples and Demos launcher -========================================== - -On Windows: - -The launcher can be accessed via the Windows Start menu. Select the menu -entry entitled "Qt Examples and Demos" entry in the submenu containing -the Qt tools. - -On Mac OS X: - -For the binary distribution, the qtdemo executable is installed in the -/Developer/Applications/Qt directory. For the source distribution, it is -installed alongside the other Qt tools on the path specified when Qt is -configured. - -On Unix/Linux: - -The qtdemo executable is installed alongside the other Qt tools on the path -specified when Qt is configured. - -On all platforms: - -The source code for the launcher can be found in the demos/qtdemo directory -in the Qt package. This example is built at the same time as the Qt libraries, -tools, examples, and demonstrations. diff --git a/examples/statemachine/eventtransitions/eventtransitions.pro b/examples/statemachine/eventtransitions/eventtransitions.pro deleted file mode 100644 index 7e92cf2..0000000 --- a/examples/statemachine/eventtransitions/eventtransitions.pro +++ /dev/null @@ -1,7 +0,0 @@ -SOURCES = main.cpp - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/eventtransitions -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS eventtransitions.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/eventtransitions -INSTALLS += target sources diff --git a/examples/statemachine/eventtransitions/main.cpp b/examples/statemachine/eventtransitions/main.cpp deleted file mode 100644 index aba0c73..0000000 --- a/examples/statemachine/eventtransitions/main.cpp +++ /dev/null @@ -1,116 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#include -#endif - -//! [0] -class Window : public QWidget -{ -public: - Window(QWidget *parent = 0) - : QWidget(parent) - { - QPushButton *button = new QPushButton(this); - button->setGeometry(QRect(100, 100, 100, 100)); -//! [0] - -//! [1] - QStateMachine *machine = new QStateMachine(this); - - QState *s1 = new QState(); - s1->assignProperty(button, "text", "Outside"); - - QState *s2 = new QState(); - s2->assignProperty(button, "text", "Inside"); -//! [1] - -//! [2] - QEventTransition *enterTransition = new QEventTransition(button, QEvent::Enter); - enterTransition->setTargetState(s2); - s1->addTransition(enterTransition); -//! [2] - -//! [3] - QEventTransition *leaveTransition = new QEventTransition(button, QEvent::Leave); - leaveTransition->setTargetState(s1); - s2->addTransition(leaveTransition); -//! [3] - -//! [4] - QState *s3 = new QState(); - s3->assignProperty(button, "text", "Pressing..."); - - QEventTransition *pressTransition = new QEventTransition(button, QEvent::MouseButtonPress); - pressTransition->setTargetState(s3); - s2->addTransition(pressTransition); - - QEventTransition *releaseTransition = new QEventTransition(button, QEvent::MouseButtonRelease); - releaseTransition->setTargetState(s2); - s3->addTransition(releaseTransition); -//! [4] - -//! [5] - machine->addState(s1); - machine->addState(s2); - machine->addState(s3); - - machine->setInitialState(s1); - machine->start(); - } -}; -//! [5] - -//! [6] -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - Window window; - window.resize(300, 300); - window.show(); - - return app.exec(); -} -//! [6] diff --git a/examples/statemachine/factorial/factorial.pro b/examples/statemachine/factorial/factorial.pro deleted file mode 100644 index 14a6833..0000000 --- a/examples/statemachine/factorial/factorial.pro +++ /dev/null @@ -1,11 +0,0 @@ -QT = core -win32: CONFIG += console -mac:CONFIG -= app_bundle - -SOURCES += main.cpp - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/factorial -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS factorial.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/factorial -INSTALLS += target sources diff --git a/examples/statemachine/factorial/main.cpp b/examples/statemachine/factorial/main.cpp deleted file mode 100644 index 1065eb8..0000000 --- a/examples/statemachine/factorial/main.cpp +++ /dev/null @@ -1,182 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#include -#include -#endif - -//! [0] -class Factorial : public QObject -{ - Q_OBJECT - Q_PROPERTY(int x READ x WRITE setX) - Q_PROPERTY(int fac READ fac WRITE setFac) -public: - Factorial(QObject *parent = 0) - : QObject(parent), m_x(-1), m_fac(1) - { - } - - int x() const - { - return m_x; - } - - void setX(int x) - { - if (x == m_x) - return; - m_x = x; - emit xChanged(x); - } - - int fac() const - { - return m_fac; - } - - void setFac(int fac) - { - m_fac = fac; - } - -Q_SIGNALS: - void xChanged(int value); - -private: - int m_x; - int m_fac; -}; -//! [0] - -//! [1] -class FactorialLoopTransition : public QSignalTransition -{ -public: - FactorialLoopTransition(Factorial *fact) - : QSignalTransition(fact, SIGNAL(xChanged(int))), m_fact(fact) - {} - - virtual bool eventTest(QEvent *e) - { - if (!QSignalTransition::eventTest(e)) - return false; - QSignalEvent *se = static_cast(e); - return se->arguments().at(0).toInt() > 1; - } - - virtual void onTransition(QEvent *e) - { - QSignalEvent *se = static_cast(e); - int x = se->arguments().at(0).toInt(); - int fac = m_fact->property("fac").toInt(); - m_fact->setProperty("fac", x * fac); - m_fact->setProperty("x", x - 1); - } - -private: - Factorial *m_fact; -}; -//! [1] - -//! [2] -class FactorialDoneTransition : public QSignalTransition -{ -public: - FactorialDoneTransition(Factorial *fact) - : QSignalTransition(fact, SIGNAL(xChanged(int))), m_fact(fact) - {} - - virtual bool eventTest(QEvent *e) - { - if (!QSignalTransition::eventTest(e)) - return false; - QSignalEvent *se = static_cast(e); - return se->arguments().at(0).toInt() <= 1; - } - - virtual void onTransition(QEvent *) - { - fprintf(stdout, "%d\n", m_fact->property("fac").toInt()); - } - -private: - Factorial *m_fact; -}; -//! [2] - -//! [3] -int main(int argc, char **argv) -{ - QCoreApplication app(argc, argv); - Factorial factorial; - QStateMachine machine; -//! [3] - -//! [4] - QState *compute = new QState(machine.rootState()); - compute->assignProperty(&factorial, "fac", 1); - compute->assignProperty(&factorial, "x", 6); - compute->addTransition(new FactorialLoopTransition(&factorial)); -//! [4] - -//! [5] - QFinalState *done = new QFinalState(machine.rootState()); - FactorialDoneTransition *doneTransition = new FactorialDoneTransition(&factorial); - doneTransition->setTargetState(done); - compute->addTransition(doneTransition); -//! [5] - -//! [6] - machine.setInitialState(compute); - QObject::connect(&machine, SIGNAL(finished()), &app, SLOT(quit())); - machine.start(); - - return app.exec(); -} -//! [6] - -#include "main.moc" diff --git a/examples/statemachine/pingpong/main.cpp b/examples/statemachine/pingpong/main.cpp deleted file mode 100644 index 331627e..0000000 --- a/examples/statemachine/pingpong/main.cpp +++ /dev/null @@ -1,145 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#include -#endif - -//! [0] -class PingEvent : public QEvent -{ -public: - PingEvent() : QEvent(QEvent::Type(QEvent::User+2)) - {} -}; - -class PongEvent : public QEvent -{ -public: - PongEvent() : QEvent(QEvent::Type(QEvent::User+3)) - {} -}; -//! [0] - -//! [1] -class Pinger : public QState -{ -public: - Pinger(QState *parent) - : QState(parent) {} - -protected: - virtual void onEntry(QEvent *) - { - machine()->postEvent(new PingEvent()); - fprintf(stdout, "ping?\n"); - } -}; -//! [1] - -//! [3] -class PongTransition : public QAbstractTransition -{ -public: - PongTransition() {} - -protected: - virtual bool eventTest(QEvent *e) { - return (e->type() == QEvent::User+3); - } - virtual void onTransition(QEvent *) - { - machine()->postEvent(new PingEvent(), 500); - fprintf(stdout, "ping?\n"); - } -}; -//! [3] - -//! [2] -class PingTransition : public QAbstractTransition -{ -public: - PingTransition() {} - -protected: - virtual bool eventTest(QEvent *e) { - return (e->type() == QEvent::User+2); - } - virtual void onTransition(QEvent *) - { - machine()->postEvent(new PongEvent(), 500); - fprintf(stdout, "pong!\n"); - } -}; -//! [2] - -//! [4] -int main(int argc, char **argv) -{ - QCoreApplication app(argc, argv); - - QStateMachine machine; - QState *group = new QState(QState::ParallelStates); - group->setObjectName("group"); -//! [4] - -//! [5] - Pinger *pinger = new Pinger(group); - pinger->setObjectName("pinger"); - pinger->addTransition(new PongTransition()); - - QState *ponger = new QState(group); - ponger->setObjectName("ponger"); - ponger->addTransition(new PingTransition()); -//! [5] - -//! [6] - machine.addState(group); - machine.setInitialState(group); - machine.start(); - - return app.exec(); -} -//! [6] diff --git a/examples/statemachine/pingpong/pingpong.pro b/examples/statemachine/pingpong/pingpong.pro deleted file mode 100644 index 42eab6c..0000000 --- a/examples/statemachine/pingpong/pingpong.pro +++ /dev/null @@ -1,11 +0,0 @@ -QT = core -win32: CONFIG += console -mac:CONFIG -= app_bundle - -SOURCES = main.cpp - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/pingpong -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS pingpong.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/pingpong -INSTALLS += target sources diff --git a/examples/statemachine/statemachine.pro b/examples/statemachine/statemachine.pro deleted file mode 100644 index 5074a3c..0000000 --- a/examples/statemachine/statemachine.pro +++ /dev/null @@ -1,15 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = \ - eventtransitions \ - factorial \ - pingpong \ - trafficlight \ - twowaybutton \ - tankgame \ - tankgameplugins - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS statemachine.pro README -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine -INSTALLS += target sources diff --git a/examples/statemachine/tankgame/gameitem.cpp b/examples/statemachine/tankgame/gameitem.cpp deleted file mode 100644 index ad8b37c..0000000 --- a/examples/statemachine/tankgame/gameitem.cpp +++ /dev/null @@ -1,129 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "gameitem.h" - -#include -#include - -GameItem::GameItem(QObject *parent) : QObject(parent) -{ -} - -QPointF GameItem::tryMove(const QPointF &requestedPosition, QLineF *collidedLine, - QGraphicsItem **collidedItem) const -{ - QLineF movementPath(pos(), requestedPosition); - - qreal cannonLength = 0.0; - { - QPointF p1 = boundingRect().center(); - QPointF p2 = QPointF(boundingRect().right() + 10.0, p1.y()); - - cannonLength = QLineF(mapToScene(p1), mapToScene(p2)).length(); - } - - movementPath.setLength(movementPath.length() + cannonLength); - - QRectF boundingRectPath(QPointF(qMin(movementPath.x1(), movementPath.x2()), qMin(movementPath.y1(), movementPath.y2())), - QPointF(qMax(movementPath.x1(), movementPath.x2()), qMax(movementPath.y1(), movementPath.y2()))); - - QList itemsInRect = scene()->items(boundingRectPath, Qt::IntersectsItemBoundingRect); - - QPointF nextPoint = requestedPosition; - QRectF sceneRect = scene()->sceneRect(); - - foreach (QGraphicsItem *item, itemsInRect) { - if (item == static_cast(this)) - continue; - - QPolygonF mappedBoundingRect = item->mapToScene(item->boundingRect()); - for (int i=0; isceneRect().topLeft(), scene()->sceneRect().bottomLeft()); - } - - if (nextPoint.x() > sceneRect.right()) { - nextPoint.rx() = sceneRect.right(); - if (collidedLine != 0) - *collidedLine = QLineF(scene()->sceneRect().topRight(), scene()->sceneRect().bottomRight()); - } - - if (nextPoint.y() < sceneRect.top()) { - nextPoint.ry() = sceneRect.top(); - if (collidedLine != 0) - *collidedLine = QLineF(scene()->sceneRect().topLeft(), scene()->sceneRect().topRight()); - } - - if (nextPoint.y() > sceneRect.bottom()) { - nextPoint.ry() = sceneRect.bottom(); - if (collidedLine != 0) - *collidedLine = QLineF(scene()->sceneRect().bottomLeft(), scene()->sceneRect().bottomRight()); - } - - return nextPoint; -} - diff --git a/examples/statemachine/tankgame/gameitem.h b/examples/statemachine/tankgame/gameitem.h deleted file mode 100644 index 90b0a6c..0000000 --- a/examples/statemachine/tankgame/gameitem.h +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GAMEITEM_H -#define GAMEITEM_H - -#include - -QT_BEGIN_NAMESPACE -class QLineF; -QT_END_NAMESPACE -class GameItem: public QObject, public QGraphicsItem -{ - Q_OBJECT -public: - enum { Type = UserType + 1 }; - int type() const { return Type; } - - GameItem(QObject *parent = 0); - - virtual void idle(qreal elapsed) = 0; - -protected: - QPointF tryMove(const QPointF &requestedPosition, QLineF *collidedLine = 0, - QGraphicsItem **collidedItem = 0) const; -}; - -#endif diff --git a/examples/statemachine/tankgame/gameovertransition.cpp b/examples/statemachine/tankgame/gameovertransition.cpp deleted file mode 100644 index 360e902..0000000 --- a/examples/statemachine/tankgame/gameovertransition.cpp +++ /dev/null @@ -1,80 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "gameovertransition.h" -#include "tankitem.h" - -#include -#include - -GameOverTransition::GameOverTransition(QAbstractState *targetState) - : QSignalTransition(new QSignalMapper(), SIGNAL(mapped(QObject*))) -{ - setTargetState(targetState); - - QSignalMapper *mapper = qobject_cast(senderObject()); - mapper->setParent(this); -} - -void GameOverTransition::addTankItem(TankItem *tankItem) -{ - m_tankItems.append(tankItem); - - QSignalMapper *mapper = qobject_cast(senderObject()); - mapper->setMapping(tankItem, tankItem); - connect(tankItem, SIGNAL(aboutToBeDestroyed()), mapper, SLOT(map())); -} - -bool GameOverTransition::eventTest(QEvent *e) -{ - bool ret = QSignalTransition::eventTest(e); - - if (ret) { - QSignalEvent *signalEvent = static_cast(e); - QObject *sender = qvariant_cast(signalEvent->arguments().at(0)); - TankItem *tankItem = qobject_cast(sender); - m_tankItems.removeAll(tankItem); - - return m_tankItems.size() <= 1; - } else { - return false; - } -} diff --git a/examples/statemachine/tankgame/gameovertransition.h b/examples/statemachine/tankgame/gameovertransition.h deleted file mode 100644 index 5e99a75..0000000 --- a/examples/statemachine/tankgame/gameovertransition.h +++ /dev/null @@ -1,63 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef GAMEOVERTRANSITION_H -#define GAMEOVERTRANSITION_H - -#include - -class TankItem; -class GameOverTransition: public QSignalTransition -{ - Q_OBJECT -public: - GameOverTransition(QAbstractState *targetState); - - void addTankItem(TankItem *tankItem); - -protected: - bool eventTest(QEvent *event); - -private: - QList m_tankItems; -}; - -#endif diff --git a/examples/statemachine/tankgame/main.cpp b/examples/statemachine/tankgame/main.cpp deleted file mode 100644 index 185ad68..0000000 --- a/examples/statemachine/tankgame/main.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "mainwindow.h" - -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - MainWindow mainWindow; - mainWindow.show(); - - return app.exec(); -} diff --git a/examples/statemachine/tankgame/mainwindow.cpp b/examples/statemachine/tankgame/mainwindow.cpp deleted file mode 100644 index 46e0db3..0000000 --- a/examples/statemachine/tankgame/mainwindow.cpp +++ /dev/null @@ -1,342 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "mainwindow.h" -#include "tankitem.h" -#include "rocketitem.h" -#include "plugin.h" -#include "gameovertransition.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -MainWindow::MainWindow(QWidget *parent) - : QMainWindow(parent), m_scene(0), m_machine(0), m_runningState(0), m_started(false) -{ - init(); -} - -MainWindow::~MainWindow() -{ -} - -void MainWindow::addWall(const QRectF &wall) -{ - QGraphicsRectItem *item = new QGraphicsRectItem; - item->setRect(wall); - item->setBrush(Qt::darkGreen); - item->setPen(QPen(Qt::black, 0)); - - m_scene->addItem(item); -} - -void MainWindow::init() -{ - setWindowTitle("Pluggable Tank Game"); - - QGraphicsView *view = new QGraphicsView(this); - view->setRenderHints(QPainter::Antialiasing); - setCentralWidget(view); - - m_scene = new QGraphicsScene(this); - view->setScene(m_scene); - - QRectF sceneRect = QRectF(-200.0, -200.0, 400.0, 400.0); - m_scene->setSceneRect(sceneRect); - - { - TankItem *item = new TankItem(this); - - item->setPos(m_scene->sceneRect().topLeft() + QPointF(30.0, 30.0)); - item->setDirection(45.0); - item->setColor(Qt::red); - - m_spawns.append(item); - } - - { - TankItem *item = new TankItem(this); - - item->setPos(m_scene->sceneRect().topRight() + QPointF(-30.0, 30.0)); - item->setDirection(135.0); - item->setColor(Qt::green); - - m_spawns.append(item); - } - - { - TankItem *item = new TankItem(this); - - item->setPos(m_scene->sceneRect().bottomRight() + QPointF(-30.0, -30.0)); - item->setDirection(225.0); - item->setColor(Qt::blue); - - m_spawns.append(item); - } - - { - TankItem *item = new TankItem(this); - - item->setPos(m_scene->sceneRect().bottomLeft() + QPointF(30.0, -30.0)); - item->setDirection(315.0); - item->setColor(Qt::yellow); - - m_spawns.append(item); - } - - QPointF centerOfMap = sceneRect.center(); - - addWall(QRectF(centerOfMap + QPointF(-50.0, -60.0), centerOfMap + QPointF(50.0, -50.0))); - addWall(QRectF(centerOfMap - QPointF(-50.0, -60.0), centerOfMap - QPointF(50.0, -50.0))); - addWall(QRectF(centerOfMap + QPointF(-50.0, -50.0), centerOfMap + QPointF(-40.0, 50.0))); - addWall(QRectF(centerOfMap - QPointF(-50.0, -50.0), centerOfMap - QPointF(-40.0, 50.0))); - - addWall(QRectF(sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, -10.0), - sceneRect.topLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, 100.0))); - addWall(QRectF(sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 - 5.0, 10.0), - sceneRect.bottomLeft() + QPointF(sceneRect.width() / 2.0 + 5.0, -100.0))); - addWall(QRectF(sceneRect.topLeft() + QPointF(-10.0, sceneRect.height() / 2.0 - 5.0), - sceneRect.topLeft() + QPointF(100.0, sceneRect.height() / 2.0 + 5.0))); - addWall(QRectF(sceneRect.topRight() + QPointF(10.0, sceneRect.height() / 2.0 - 5.0), - sceneRect.topRight() + QPointF(-100.0, sceneRect.height() / 2.0 + 5.0))); - - - QAction *addTankAction = menuBar()->addAction("&Add tank"); - QAction *runGameAction = menuBar()->addAction("&Run game"); - runGameAction->setObjectName("runGameAction"); - QAction *stopGameAction = menuBar()->addAction("&Stop game"); - menuBar()->addSeparator(); - QAction *quitAction = menuBar()->addAction("&Quit"); - - connect(addTankAction, SIGNAL(triggered()), this, SLOT(addTank())); - connect(quitAction, SIGNAL(triggered()), this, SLOT(close())); - - m_machine = new QStateMachine(this); - QState *stoppedState = new QState(m_machine->rootState()); - stoppedState->setObjectName("stoppedState"); - stoppedState->assignProperty(runGameAction, "enabled", true); - stoppedState->assignProperty(stopGameAction, "enabled", false); - stoppedState->assignProperty(this, "started", false); - m_machine->setInitialState(stoppedState); - -//! [5] - QState *spawnsAvailable = new QState(stoppedState); - spawnsAvailable->assignProperty(addTankAction, "enabled", true); - - QState *noSpawnsAvailable = new QState(stoppedState); - noSpawnsAvailable->assignProperty(addTankAction, "enabled", false); -//! [5] - spawnsAvailable->setObjectName("spawnsAvailable"); - noSpawnsAvailable->setObjectName("noSpawnsAvailable"); - - spawnsAvailable->addTransition(this, SIGNAL(mapFull()), noSpawnsAvailable); - -//! [3] - QHistoryState *hs = new QHistoryState(stoppedState); - hs->setDefaultState(spawnsAvailable); -//! [3] - hs->setObjectName("hs"); - - stoppedState->setInitialState(hs); - -//! [0] - m_runningState = new QState(QState::ParallelStates, m_machine->rootState()); -//! [0] - m_runningState->setObjectName("runningState"); - m_runningState->assignProperty(addTankAction, "enabled", false); - m_runningState->assignProperty(runGameAction, "enabled", false); - m_runningState->assignProperty(stopGameAction, "enabled", true); - - QState *gameOverState = new QState(m_machine->rootState()); - gameOverState->setObjectName("gameOverState"); - gameOverState->assignProperty(stopGameAction, "enabled", false); - connect(gameOverState, SIGNAL(entered()), this, SLOT(gameOver())); - - stoppedState->addTransition(runGameAction, SIGNAL(triggered()), m_runningState); - m_runningState->addTransition(stopGameAction, SIGNAL(triggered()), stoppedState); - - m_gameOverTransition = new GameOverTransition(gameOverState); - m_runningState->addTransition(m_gameOverTransition); - - QTimer *timer = new QTimer(this); - timer->setInterval(100); - connect(timer, SIGNAL(timeout()), this, SLOT(runStep())); - connect(m_runningState, SIGNAL(entered()), timer, SLOT(start())); - connect(m_runningState, SIGNAL(exited()), timer, SLOT(stop())); - - m_machine->start(); - m_time.start(); -} - -void MainWindow::runStep() -{ - if (!m_started) { - m_time.restart(); - m_started = true; - } else { - int elapsed = m_time.elapsed(); - if (elapsed > 0) { - m_time.restart(); - qreal elapsedSecs = elapsed / 1000.0; - QList items = m_scene->items(); - foreach (QGraphicsItem *item, items) { - if (GameItem *gameItem = qgraphicsitem_cast(item)) - gameItem->idle(elapsedSecs); - } - } - } -} - -void MainWindow::gameOver() -{ - QList items = m_scene->items(); - - TankItem *lastTankStanding = 0; - foreach (QGraphicsItem *item, items) { - if (GameItem *gameItem = qgraphicsitem_cast(item)) { - if ((lastTankStanding = qobject_cast(gameItem)) != 0) - break; - } - } - - QMessageBox::information(this, "Game over!", - QString::fromLatin1("The tank played by '%1' has won!").arg(lastTankStanding->objectName())); -} - -void MainWindow::addRocket() -{ - TankItem *tankItem = qobject_cast(sender()); - if (tankItem != 0) { - RocketItem *rocketItem = new RocketItem; - - QPointF s = tankItem->mapToScene(QPointF(tankItem->boundingRect().right() + 10.0, - tankItem->boundingRect().center().y())); - rocketItem->setPos(s); - rocketItem->setDirection(tankItem->direction()); - m_scene->addItem(rocketItem); - } -} - -void MainWindow::addTank() -{ - Q_ASSERT(!m_spawns.isEmpty()); - - QDir pluginsDir(qApp->applicationDirPath()); -#if defined(Q_OS_WIN) - if (pluginsDir.dirName().toLower() == "debug" || pluginsDir.dirName().toLower() == "release") - pluginsDir.cdUp(); -#elif defined(Q_OS_MAC) - if (pluginsDir.dirName() == "MacOS") { - pluginsDir.cdUp(); - pluginsDir.cdUp(); - pluginsDir.cdUp(); - } -#endif - - pluginsDir.cd("plugins"); - - QStringList itemNames; - QList items; - foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { - QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); - QObject *possiblePlugin = loader.instance(); - if (Plugin *plugin = qobject_cast(possiblePlugin)) { - QString objectName = possiblePlugin->objectName(); - if (objectName.isEmpty()) - objectName = fileName; - - itemNames.append(objectName); - items.append(plugin); - } - } - - if (items.isEmpty()) { - QMessageBox::information(this, "No tank types found", "Please build the errorstateplugins directory"); - return; - } - - bool ok; -//! [1] - QString selectedName = QInputDialog::getItem(this, "Select a tank type", "Tank types", - itemNames, 0, false, &ok); -//! [1] - - if (ok && !selectedName.isEmpty()) { - int idx = itemNames.indexOf(selectedName); - if (Plugin *plugin = idx >= 0 ? items.at(idx) : 0) { - TankItem *tankItem = m_spawns.takeLast(); - tankItem->setObjectName(selectedName); - tankItem->setToolTip(selectedName); - m_scene->addItem(tankItem); - connect(tankItem, SIGNAL(cannonFired()), this, SLOT(addRocket())); - if (m_spawns.isEmpty()) - emit mapFull(); - - m_gameOverTransition->addTankItem(tankItem); - - QState *region = new QState(m_runningState); - region->setObjectName(QString::fromLatin1("region%1").arg(m_spawns.size())); -//! [2] - QState *pluginState = plugin->create(region, tankItem); -//! [2] - region->setInitialState(pluginState); - - // If the plugin has an error it is disabled -//! [4] - QState *errorState = new QState(region); - errorState->setObjectName(QString::fromLatin1("errorState%1").arg(m_spawns.size())); - errorState->assignProperty(tankItem, "enabled", false); - pluginState->setErrorState(errorState); -//! [4] - } - } -} - diff --git a/examples/statemachine/tankgame/mainwindow.h b/examples/statemachine/tankgame/mainwindow.h deleted file mode 100644 index 4ae8f7a..0000000 --- a/examples/statemachine/tankgame/mainwindow.h +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef MAINWINDOW_H -#define MAINWINDOW_H - -#include -#include - -QT_BEGIN_NAMESPACE -class QGraphicsScene; -class QStateMachine; -class QState; -QT_END_NAMESPACE -class GameOverTransition; -class TankItem; - -class MainWindow: public QMainWindow -{ - Q_OBJECT - Q_PROPERTY(bool started READ started WRITE setStarted) -public: - MainWindow(QWidget *parent = 0); - ~MainWindow(); - - void setStarted(bool b) { m_started = b; } - bool started() const { return m_started; } - -public slots: - void addTank(); - void addRocket(); - void runStep(); - void gameOver(); - -signals: - void mapFull(); - -private: - void init(); - void addWall(const QRectF &wall); - - QGraphicsScene *m_scene; - - QStateMachine *m_machine; - QState *m_runningState; - GameOverTransition *m_gameOverTransition; - - QList m_spawns; - QTime m_time; - - bool m_started : 1; -}; - -#endif - diff --git a/examples/statemachine/tankgame/plugin.h b/examples/statemachine/tankgame/plugin.h deleted file mode 100644 index ddd10b7..0000000 --- a/examples/statemachine/tankgame/plugin.h +++ /dev/null @@ -1,62 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef PLUGIN_H -#define PLUGIN_H - -#include - -QT_BEGIN_NAMESPACE -class QState; -QT_END_NAMESPACE -class Plugin -{ -public: - virtual ~Plugin() {} - - virtual QState *create(QState *parentState, QObject *tank) = 0; -}; - -QT_BEGIN_NAMESPACE -Q_DECLARE_INTERFACE(Plugin, "TankPlugin") -QT_END_NAMESPACE - -#endif diff --git a/examples/statemachine/tankgame/rocketitem.cpp b/examples/statemachine/tankgame/rocketitem.cpp deleted file mode 100644 index 3ace8e8..0000000 --- a/examples/statemachine/tankgame/rocketitem.cpp +++ /dev/null @@ -1,101 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "rocketitem.h" -#include "tankitem.h" - -#include -#include - -#include - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -RocketItem::RocketItem(QObject *parent) - : GameItem(parent), m_direction(0.0), m_distance(300.0) -{ -} - -QRectF RocketItem::boundingRect() const -{ - return QRectF(-1.0, -1.0, 2.0, 2.0); -} - -void RocketItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - painter->setBrush(Qt::black); - painter->drawEllipse(boundingRect()); -} - -void RocketItem::idle(qreal elapsed) -{ - qreal dist = elapsed * speed(); - - m_distance -= dist; - if (m_distance < 0.0) { - scene()->removeItem(this); - delete this; - return; - } - - qreal a = m_direction * M_PI / 180.0; - - qreal yd = dist * sin(a); - qreal xd = dist * sin(M_PI / 2.0 - a); - - QPointF requestedPosition = pos() + QPointF(xd, yd); - QGraphicsItem *collidedItem = 0; - QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); - if (requestedPosition == nextPosition) { - setPos(nextPosition); - } else { - if (GameItem *gameItem = qgraphicsitem_cast(collidedItem)) { - TankItem *tankItem = qobject_cast(gameItem); - if (tankItem != 0) - tankItem->hitByRocket(); - } - - scene()->removeItem(this); - delete this; - } -} diff --git a/examples/statemachine/tankgame/rocketitem.h b/examples/statemachine/tankgame/rocketitem.h deleted file mode 100644 index 31146a6..0000000 --- a/examples/statemachine/tankgame/rocketitem.h +++ /dev/null @@ -1,66 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef ROCKETITEM_H -#define ROCKETITEM_H - -#include "gameitem.h" - -class RocketItem: public GameItem -{ - Q_OBJECT -public: - RocketItem(QObject *parent = 0); - - virtual void idle(qreal elapsed); - qreal speed() const { return 100.0; } - void setDirection(qreal direction) { m_direction = direction; } - -protected: - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - QRectF boundingRect() const; - -private: - qreal m_direction; - qreal m_distance; -}; - -#endif diff --git a/examples/statemachine/tankgame/tankgame.pro b/examples/statemachine/tankgame/tankgame.pro deleted file mode 100644 index 59415be..0000000 --- a/examples/statemachine/tankgame/tankgame.pro +++ /dev/null @@ -1,19 +0,0 @@ -HEADERS += mainwindow.h \ - plugin.h \ - tankitem.h \ - rocketitem.h \ - gameitem.h \ - gameovertransition.h -SOURCES += main.cpp \ - mainwindow.cpp \ - tankitem.cpp \ - rocketitem.cpp \ - gameitem.cpp \ - gameovertransition.cpp -CONFIG += console - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS tankgame.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame -INSTALLS += target sources diff --git a/examples/statemachine/tankgame/tankitem.cpp b/examples/statemachine/tankgame/tankitem.cpp deleted file mode 100644 index 393d65f..0000000 --- a/examples/statemachine/tankgame/tankitem.cpp +++ /dev/null @@ -1,302 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "tankitem.h" - -#include -#include -#include - -#include - -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif - -class Action -{ -public: - Action(TankItem *item) : m_item(item) - { - } - - TankItem *item() const { return m_item; } - void setItem(TankItem *item) { m_item = item; } - - virtual bool apply(qreal timeDelta) = 0; - -private: - TankItem *m_item; -}; - -class MoveAction: public Action -{ -public: - MoveAction(TankItem *item, qreal distance) - : Action(item), m_distance(distance) - { - m_reverse = m_distance < 0.0; - } - - bool apply(qreal timeDelta) - { - qreal dist = timeDelta * item()->speed() * (m_reverse ? -1.0 : 1.0); - - bool done = false; - if (qAbs(m_distance) < qAbs(dist)) { - done = true; - dist = m_distance; - } - m_distance -= dist; - - qreal a = item()->direction() * M_PI / 180.0; - - qreal yd = dist * sin(a); - qreal xd = dist * sin(M_PI / 2.0 - a); - - item()->setPos(item()->pos() + QPointF(xd, yd)); - return !done; - } - -private: - qreal m_distance; - bool m_reverse; -}; - -class TurnAction: public Action -{ -public: - TurnAction(TankItem *item, qreal distance) - : Action(item), m_distance(distance) - { - m_reverse = m_distance < 0.0; - } - - bool apply(qreal timeDelta) - { - qreal dist = timeDelta * item()->angularSpeed() * (m_reverse ? -1.0 : 1.0); - bool done = false; - if (qAbs(m_distance) < qAbs(dist)) { - done = true; - dist = m_distance; - } - m_distance -= dist; - - item()->setDirection(item()->direction() + dist); - return !done; - } - -private: - qreal m_distance; - bool m_reverse; -}; - -TankItem::TankItem(QObject *parent) - : GameItem(parent), m_currentAction(0), m_currentDirection(0.0), m_enabled(true) -{ - connect(this, SIGNAL(cannonFired()), this, SIGNAL(actionCompleted())); -} - -void TankItem::idle(qreal elapsed) -{ - if (m_enabled) { - if (m_currentAction != 0) { - if (!m_currentAction->apply(elapsed)) { - setAction(0); - emit actionCompleted(); - } - - QGraphicsItem *item = 0; - qreal distance = distanceToObstacle(&item); - if (TankItem *tankItem = qgraphicsitem_cast(item)) - emit tankSpotted(tankItem->direction(), distance); - } - } -} - -void TankItem::hitByRocket() -{ - emit aboutToBeDestroyed(); - deleteLater(); -} - -void TankItem::setAction(Action *newAction) -{ - if (m_currentAction != 0) - delete m_currentAction; - - m_currentAction = newAction; -} - -void TankItem::fireCannon() -{ - emit cannonFired(); -} - -void TankItem::moveForwards(qreal length) -{ - setAction(new MoveAction(this, length)); -} - -void TankItem::moveBackwards(qreal length) -{ - setAction(new MoveAction(this, -length)); -} - -void TankItem::turn(qreal degrees) -{ - setAction(new TurnAction(this, degrees)); -} - -void TankItem::turnTo(qreal degrees) -{ - setAction(new TurnAction(this, degrees - direction())); -} - -void TankItem::stop() -{ - setAction(0); -} - -QVariant TankItem::itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value) -{ - if (change == ItemPositionChange && scene()) { - QPointF requestedPosition = value.toPointF(); - QLineF collidedLine; - QPointF nextPoint = tryMove(requestedPosition, &collidedLine); - if (nextPoint != requestedPosition) - emit collision(collidedLine); - return nextPoint; - } else { - return QGraphicsItem::itemChange(change, value); - } -} - - -void TankItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) -{ - QRectF brect = boundingRect(); - - painter->setBrush(m_color); - painter->setPen(Qt::black); - - // body - painter->drawRect(brect.adjusted(0.0, 4.0, -2.0, -4.0)); - - // cannon - QRectF cannonBase = brect.adjusted(10.0, 6.0, -12.0, -6.0); - painter->drawEllipse(cannonBase); - - painter->drawRect(QRectF(QPointF(cannonBase.center().x(), cannonBase.center().y() - 2.0), - QPointF(brect.right(), cannonBase.center().y() + 2.0))); - - // left track - painter->setBrush(QBrush(Qt::black, Qt::VerPattern)); - QRectF leftTrackRect = QRectF(brect.topLeft(), QPointF(brect.right() - 2.0, brect.top() + 4.0)); - painter->fillRect(leftTrackRect, Qt::darkYellow); - painter->drawRect(leftTrackRect); - - // right track - QRectF rightTrackRect = QRectF(QPointF(brect.left(), brect.bottom() - 4.0), - QPointF(brect.right() - 2.0, brect.bottom())); - painter->fillRect(rightTrackRect, Qt::darkYellow); - painter->drawRect(rightTrackRect); - - if (!m_enabled) { - painter->setPen(QPen(Qt::red, 5)); - - painter->drawEllipse(brect); - - QPainterPath path; - path.addEllipse(brect); - painter->setClipPath(path); - painter->drawLine(brect.topRight(), brect.bottomLeft()); - } -} - -QRectF TankItem::boundingRect() const -{ - return QRectF(-20.0, -10.0, 40.0, 20.0); -} - -qreal TankItem::direction() const -{ - return m_currentDirection; -} - -void TankItem::setDirection(qreal newDirection) -{ - int fullRotations = int(newDirection) / 360; - newDirection -= fullRotations * 360.0; - - qreal diff = newDirection - m_currentDirection; - m_currentDirection = newDirection; - rotate(diff); -} - -qreal TankItem::distanceToObstacle(QGraphicsItem **obstacle) const -{ - qreal dist = sqrt(pow(scene()->sceneRect().width(), 2) + pow(scene()->sceneRect().height(), 2)); - - qreal a = m_currentDirection * M_PI / 180.0; - - qreal yd = dist * sin(a); - qreal xd = dist * sin(M_PI / 2.0 - a); - - QPointF requestedPosition = pos() + QPointF(xd, yd); - QGraphicsItem *collidedItem = 0; - QPointF nextPosition = tryMove(requestedPosition, 0, &collidedItem); - if (collidedItem != 0) { - if (obstacle != 0) - *obstacle = collidedItem; - - QPointF d = nextPosition - pos(); - return sqrt(pow(d.x(), 2) + pow(d.y(), 2)); - } else { - return 0.0; - } -} - -qreal TankItem::distanceToObstacle() const -{ - return distanceToObstacle(0); -} - diff --git a/examples/statemachine/tankgame/tankitem.h b/examples/statemachine/tankgame/tankitem.h deleted file mode 100644 index 942fca8..0000000 --- a/examples/statemachine/tankgame/tankitem.h +++ /dev/null @@ -1,109 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef TANKITEM_H -#define TANKITEM_H - -#include "gameitem.h" - -#include - -class Action; -class TankItem: public GameItem -{ - Q_OBJECT - Q_PROPERTY(bool enabled READ enabled WRITE setEnabled) - Q_PROPERTY(qreal direction READ direction WRITE turnTo) - Q_PROPERTY(qreal distanceToObstacle READ distanceToObstacle) -public: - TankItem(QObject *parent = 0); - - void setColor(const QColor &color) { m_color = color; } - QColor color() const { return m_color; } - - void idle(qreal elapsed); - void setDirection(qreal newDirection); - - qreal speed() const { return 90.0; } - qreal angularSpeed() const { return 90.0; } - - QRectF boundingRect() const; - - void hitByRocket(); - - void setEnabled(bool b) { m_enabled = b; } - bool enabled() const { return m_enabled; } - - qreal direction() const; - qreal distanceToObstacle() const; - qreal distanceToObstacle(QGraphicsItem **item) const; - -//! [0] -signals: - void tankSpotted(qreal direction, qreal distance); - void collision(const QLineF &collidedLine); - void actionCompleted(); - void cannonFired(); - void aboutToBeDestroyed(); - -public slots: - void moveForwards(qreal length = 10.0); - void moveBackwards(qreal length = 10.0); - void turn(qreal degrees = 30.0); - void turnTo(qreal degrees = 0.0); - void stop(); - void fireCannon(); -//! [0] - -protected: - virtual void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); - QVariant itemChange(QGraphicsItem::GraphicsItemChange change, const QVariant &value); - -private: - void setAction(Action *newAction); - - Action *m_currentAction; - qreal m_currentDirection; - QColor m_color; - bool m_enabled; -}; - -#endif diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai.pro b/examples/statemachine/tankgameplugins/random_ai/random_ai.pro deleted file mode 100644 index 5bc0b26..0000000 --- a/examples/statemachine/tankgameplugins/random_ai/random_ai.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = lib -CONFIG += plugin -INCLUDEPATH += ../.. -HEADERS = random_ai_plugin.h -SOURCES = random_ai_plugin.cpp -TARGET = $$qtLibraryTarget(random_ai) -DESTDIR = ../../tankgame/plugins - -#! [0] -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS random_ai.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/random_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp deleted file mode 100644 index d360de9..0000000 --- a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "random_ai_plugin.h" - -#include -#include - -#include - -QState *RandomAiPlugin::create(QState *parentState, QObject *tank) -{ - qsrand(uint(time(NULL))); - - QState *topLevel = new QState(parentState); - - QState *selectNextActionState = new SelectActionState(topLevel); - topLevel->setInitialState(selectNextActionState); - - QState *fireState = new RandomDistanceState(topLevel); - connect(fireState, SIGNAL(distanceComputed(qreal)), tank, SLOT(fireCannon())); - selectNextActionState->addTransition(selectNextActionState, SIGNAL(fireSelected()), fireState); - - QState *moveForwardsState = new RandomDistanceState(topLevel); - connect(moveForwardsState, SIGNAL(distanceComputed(qreal)), tank, SLOT(moveForwards(qreal))); - selectNextActionState->addTransition(selectNextActionState, SIGNAL(moveForwardsSelected()), moveForwardsState); - - QState *moveBackwardsState = new RandomDistanceState(topLevel); - connect(moveBackwardsState, SIGNAL(distanceComputed(qreal)), tank, SLOT(moveBackwards(qreal))); - selectNextActionState->addTransition(selectNextActionState, SIGNAL(moveBackwardsSelected()), moveBackwardsState); - - QState *turnState = new RandomDistanceState(topLevel); - connect(turnState, SIGNAL(distanceComputed(qreal)), tank, SLOT(turn(qreal))); - selectNextActionState->addTransition(selectNextActionState, SIGNAL(turnSelected()), turnState); - - topLevel->addTransition(tank, SIGNAL(actionCompleted()), selectNextActionState); - - return topLevel; -} - -Q_EXPORT_PLUGIN2(random_ai, RandomAiPlugin) diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h deleted file mode 100644 index 9faeeac..0000000 --- a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.h +++ /dev/null @@ -1,105 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef RANDOM_AI_PLUGIN_H -#define RANDOM_AI_PLUGIN_H - -#include -#include - -#include - -class SelectActionState: public QState -{ - Q_OBJECT -public: - SelectActionState(QState *parent = 0) : QState(parent) - { - } - -signals: - void fireSelected(); - void moveForwardsSelected(); - void moveBackwardsSelected(); - void turnSelected(); - -protected: - void onEntry(QEvent *) - { - int rand = qrand() % 4; - switch (rand) { - case 0: emit fireSelected(); break; - case 1: emit moveForwardsSelected(); break; - case 2: emit moveBackwardsSelected(); break; - case 3: emit turnSelected(); break; - }; - } -}; - -class RandomDistanceState: public QState -{ - Q_OBJECT -public: - RandomDistanceState(QState *parent = 0) : QState(parent) - { - } - -signals: - void distanceComputed(qreal distance); - -protected: - void onEntry(QEvent *) - { - emit distanceComputed(qreal(qrand() % 180)); - } -}; - -class RandomAiPlugin: public QObject, public Plugin -{ - Q_OBJECT - Q_INTERFACES(Plugin) -public: - RandomAiPlugin() { setObjectName("Random"); } - - virtual QState *create(QState *parentState, QObject *tank); -}; - -#endif // RANDOM_AI_PLUGIN_H diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp deleted file mode 100644 index 6aae015..0000000 --- a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.cpp +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "seek_ai.h" - -QState *SeekAi::create(QState *parentState, QObject *tank) -{ - QState *topLevel = new QState(parentState); - topLevel->setObjectName("topLevel"); - - QState *seek = new QState(topLevel); - seek->setObjectName("seek"); - topLevel->setInitialState(seek); - - QState *lookForNearestWall = new SearchState(tank, seek); - lookForNearestWall->setObjectName("lookForNearestWall"); - seek->setInitialState(lookForNearestWall); - - QState *driveToFirstObstacle = new QState(seek); - driveToFirstObstacle->setObjectName("driveToFirstObstacle"); - lookForNearestWall->addTransition(lookForNearestWall, SIGNAL(nearestObstacleStraightAhead()), - driveToFirstObstacle); - - QState *drive = new QState(driveToFirstObstacle); - drive->setObjectName("drive"); - driveToFirstObstacle->setInitialState(drive); - connect(drive, SIGNAL(entered()), tank, SLOT(moveForwards())); - connect(drive, SIGNAL(exited()), tank, SLOT(stop())); - - // Go in loop - QState *finishedDriving = new QState(driveToFirstObstacle); - finishedDriving->setObjectName("finishedDriving"); - drive->addTransition(tank, SIGNAL(actionCompleted()), finishedDriving); - finishedDriving->addTransition(drive); - - QState *turnTo = new QState(seek); - turnTo->setObjectName("turnTo"); - driveToFirstObstacle->addTransition(new CollisionTransition(tank, turnTo)); - - turnTo->addTransition(tank, SIGNAL(actionCompleted()), driveToFirstObstacle); - - ChaseState *chase = new ChaseState(tank, topLevel); - chase->setObjectName("chase"); - seek->addTransition(new TankSpottedTransition(tank, chase)); - chase->addTransition(chase, SIGNAL(finished()), driveToFirstObstacle); - chase->addTransition(new TankSpottedTransition(tank, chase)); - - return topLevel; -} - -Q_EXPORT_PLUGIN2(seek_ai, SeekAi) diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h deleted file mode 100644 index e44ad07..0000000 --- a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.h +++ /dev/null @@ -1,249 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SEEK_AI_H -#define SEEK_AI_H - -#include - -#include -#include -#include -#include -#include -#include -#include - -class SearchState: public QState -{ - Q_OBJECT -public: - SearchState(QObject *tank, QState *parentState = 0) - : QState(parentState), - m_tank(tank), - m_distanceToTurn(360.0), - m_nearestDistance(-1.0), - m_directionOfNearestObstacle(0.0) - { - } - -public slots: - void turnAlittle() - { - qreal dist = m_tank->property("distanceToObstacle").toDouble(); - - if (m_nearestDistance < 0.0 || dist < m_nearestDistance) { - m_nearestDistance = dist; - m_directionOfNearestObstacle = m_tank->property("direction").toDouble(); - } - - m_distanceToTurn -= 10.0; - if (m_distanceToTurn < 0.0) { - disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); - connect(m_tank, SIGNAL(actionCompleted()), this, SIGNAL(nearestObstacleStraightAhead())); - m_tank->setProperty("direction", m_directionOfNearestObstacle); - } - - qreal currentDirection = m_tank->property("direction").toDouble(); - m_tank->setProperty("direction", currentDirection + 10.0); - } - -signals: - void nearestObstacleStraightAhead(); - -protected: - void onEntry(QEvent *) - { - connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); - turnAlittle(); - } - - void onExit(QEvent *) - { - disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(turnAlittle())); - disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(nearestObstacleStraightAhead())); - } - -private: - QObject *m_tank; - - qreal m_distanceToTurn; - qreal m_nearestDistance; - qreal m_directionOfNearestObstacle; -}; - -class CollisionTransition: public QSignalTransition -{ -public: - CollisionTransition(QObject *tank, QState *turnTo) - : QSignalTransition(tank, SIGNAL(collision(QLineF))), - m_tank(tank), - m_turnTo(turnTo) - { - setTargetState(turnTo); - } - -protected: - bool eventTest(QEvent *event) - { - bool b = QSignalTransition::eventTest(event); - if (b) { - QSignalEvent *se = static_cast(event); - m_lastLine = se->arguments().at(0).toLineF(); - } - return b; - } - - void onTransition(QEvent *) - { - qreal angleOfWall = m_lastLine.angle(); - - qreal newDirection; - if (qrand() % 2 == 0) - newDirection = angleOfWall; - else - newDirection = angleOfWall - 180.0; - - m_turnTo->assignProperty(m_tank, "direction", newDirection); - } - -private: - QLineF m_lastLine; - QObject *m_tank; - QState *m_turnTo; -}; - -class ChaseState: public QState -{ - class GoToLocationState: public QState - { - public: - GoToLocationState(QObject *tank, QState *parentState = 0) - : QState(parentState), m_tank(tank), m_distance(0.0) - { - } - - void setDistance(qreal distance) { m_distance = distance; } - - protected: - void onEntry() - { - QMetaObject::invokeMethod(m_tank, "moveForwards", Q_ARG(qreal, m_distance)); - } - - private: - QObject *m_tank; - qreal m_distance; - }; - -public: - ChaseState(QObject *tank, QState *parentState = 0) : QState(parentState), m_tank(tank) - { - QState *fireCannon = new QState(this); - fireCannon->setObjectName("fireCannon"); - connect(fireCannon, SIGNAL(entered()), tank, SLOT(fireCannon())); - setInitialState(fireCannon); - - m_goToLocation = new GoToLocationState(tank, this); - m_goToLocation->setObjectName("goToLocation"); - fireCannon->addTransition(tank, SIGNAL(actionCompleted()), m_goToLocation); - - m_turnToDirection = new QState(this); - m_turnToDirection->setObjectName("turnToDirection"); - m_goToLocation->addTransition(tank, SIGNAL(actionCompleted()), m_turnToDirection); - - QFinalState *finalState = new QFinalState(this); - finalState->setObjectName("finalState"); - m_turnToDirection->addTransition(tank, SIGNAL(actionCompleted()), finalState); - } - - void setDirection(qreal direction) - { - m_turnToDirection->assignProperty(m_tank, "direction", direction); - } - - void setDistance(qreal distance) - { - m_goToLocation->setDistance(distance); - } - -private: - QObject *m_tank; - GoToLocationState *m_goToLocation; - QState *m_turnToDirection; - -}; - -class TankSpottedTransition: public QSignalTransition -{ -public: - TankSpottedTransition(QObject *tank, ChaseState *target) : QSignalTransition(tank, SIGNAL(tankSpotted(qreal,qreal))), m_chase(target) - { - setTargetState(target); - } - -protected: - bool eventTest(QEvent *event) - { - bool b = QSignalTransition::eventTest(event); - if (b) { - QSignalEvent *se = static_cast(event); - m_chase->setDirection(se->arguments().at(0).toDouble()); - m_chase->setDistance(se->arguments().at(1).toDouble()); - } - return b; - } - -private: - ChaseState *m_chase; -}; - -class SeekAi: public QObject, public Plugin -{ - Q_OBJECT - Q_INTERFACES(Plugin) -public: - SeekAi() { setObjectName("Seek and destroy"); } - - virtual QState *create(QState *parentState, QObject *tank); -}; - -#endif diff --git a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro b/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro deleted file mode 100644 index 0d8bf2e..0000000 --- a/examples/statemachine/tankgameplugins/seek_ai/seek_ai.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = lib -CONFIG += plugin -INCLUDEPATH += ../.. -HEADERS = seek_ai.h -SOURCES = seek_ai.cpp -TARGET = $$qtLibraryTarget(seek_ai) -DESTDIR = ../../tankgame/plugins - -#! [0] -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS seek_ai.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/seek_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp deleted file mode 100644 index 581a6b2..0000000 --- a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "spin_ai.h" - -#include - -QState *SpinAi::create(QState *parentState, QObject *tank) -{ - QState *topLevel = new QState(parentState); - QState *spinState = new SpinState(tank, topLevel); - topLevel->setInitialState(spinState); - - // When tank is spotted, fire two times and go back to spin state - QState *fireState = new QState(topLevel); - - QState *fireOnce = new QState(fireState); - fireState->setInitialState(fireOnce); - connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); - - QState *fireTwice = new QState(fireState); - connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); - - fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); - fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); - - spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); - - return topLevel; -} - -Q_EXPORT_PLUGIN2(spin_ai, SpinAi) diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h deleted file mode 100644 index 652e8b8..0000000 --- a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SPIN_AI_H -#define SPIN_AI_H - -#include - -#include -#include -#include - -class SpinState: public QState -{ - Q_OBJECT -public: - SpinState(QObject *tank, QState *parent) : QState(parent), m_tank(tank) - { - } - -public slots: - void spin() - { - m_tank->setProperty("direction", m_tank->property("direction").toDouble() + 90.0); - } - -protected: - void onEntry(QEvent *) - { - connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); - spin(); - } - - void onExit(QEvent *) - { - disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); - } - -private: - QObject *m_tank; - -}; - -class SpinAi: public QObject, public Plugin -{ - Q_OBJECT - Q_INTERFACES(Plugin) -public: - SpinAi() { setObjectName("Spin and destroy"); } - - virtual QState *create(QState *parentState, QObject *tank); -}; - -#endif diff --git a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro b/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro deleted file mode 100644 index 8ab4da0..0000000 --- a/examples/statemachine/tankgameplugins/spin_ai/spin_ai.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = lib -CONFIG += plugin -INCLUDEPATH += ../.. -HEADERS = spin_ai.h -SOURCES = spin_ai.cpp -TARGET = $$qtLibraryTarget(spin_ai) -DESTDIR = ../../tankgame/plugins - -#! [0] -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS spin_ai.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/spin_ai \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp deleted file mode 100644 index 19137b2..0000000 --- a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.cpp +++ /dev/null @@ -1,70 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "spin_ai_with_error.h" - -#include - -QState *SpinAiWithError::create(QState *parentState, QObject *tank) -{ - QState *topLevel = new QState(parentState); - QState *spinState = new SpinState(tank, topLevel); - topLevel->setInitialState(spinState); - - // When tank is spotted, fire two times and go back to spin state - // (no initial state set for fireState will lead to run-time error in machine) - QState *fireState = new QState(topLevel); - - QState *fireOnce = new QState(fireState); - connect(fireOnce, SIGNAL(entered()), tank, SLOT(fireCannon())); - - QState *fireTwice = new QState(fireState); - connect(fireTwice, SIGNAL(entered()), tank, SLOT(fireCannon())); - - fireOnce->addTransition(tank, SIGNAL(actionCompleted()), fireTwice); - fireTwice->addTransition(tank, SIGNAL(actionCompleted()), spinState); - - spinState->addTransition(tank, SIGNAL(tankSpotted(qreal,qreal)), fireState); - - return topLevel; -} - -Q_EXPORT_PLUGIN2(spin_ai_with_error, SpinAiWithError) diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h deleted file mode 100644 index e040bf2..0000000 --- a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the examples of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef SPIN_AI_WITH_ERROR_H -#define SPIN_AI_WITH_ERROR_H - -#include - -#include -#include -#include - -class SpinState: public QState -{ - Q_OBJECT -public: - SpinState(QObject *tank, QState *parent) : QState(parent), m_tank(tank) - { - } - -public slots: - void spin() - { - m_tank->setProperty("direction", m_tank->property("direction").toDouble() + 90.0); - } - -protected: - void onEntry(QEvent *) - { - connect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); - spin(); - } - - void onExit(QEvent *) - { - disconnect(m_tank, SIGNAL(actionCompleted()), this, SLOT(spin())); - } - -private: - QObject *m_tank; - -}; - -class SpinAiWithError: public QObject, public Plugin -{ - Q_OBJECT - Q_INTERFACES(Plugin) -public: - SpinAiWithError() { setObjectName("Spin and destroy with runtime error in state machine"); } - - virtual QState *create(QState *parentState, QObject *tank); -}; - -#endif diff --git a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro b/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro deleted file mode 100644 index 124cf98..0000000 --- a/examples/statemachine/tankgameplugins/spin_ai_with_error/spin_ai_with_error.pro +++ /dev/null @@ -1,13 +0,0 @@ -TEMPLATE = lib -CONFIG += plugin -INCLUDEPATH += ../.. -HEADERS = spin_ai_with_error.h -SOURCES = spin_ai_with_error.cpp -TARGET = $$qtLibraryTarget(spin_ai_with_error) -DESTDIR = ../../tankgame/plugins - -#! [0] -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgame/plugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS spin_ai_with_error.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins/spin_ai_with_error \ No newline at end of file diff --git a/examples/statemachine/tankgameplugins/tankgameplugins.pro b/examples/statemachine/tankgameplugins/tankgameplugins.pro deleted file mode 100644 index a098e03..0000000 --- a/examples/statemachine/tankgameplugins/tankgameplugins.pro +++ /dev/null @@ -1,11 +0,0 @@ -TEMPLATE = subdirs -SUBDIRS = random_ai \ - spin_ai_with_error \ - spin_ai \ - seek_ai - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS tankgameplugins.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/tankgameplugins -INSTALLS += target sources diff --git a/examples/statemachine/trafficlight/main.cpp b/examples/statemachine/trafficlight/main.cpp deleted file mode 100644 index 8a46fff..0000000 --- a/examples/statemachine/trafficlight/main.cpp +++ /dev/null @@ -1,190 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#include -#endif - -//! [0] -class LightWidget : public QWidget -{ - Q_OBJECT - Q_PROPERTY(bool on READ isOn WRITE setOn) -public: - LightWidget(const QColor &color, QWidget *parent = 0) - : QWidget(parent), m_color(color), m_on(false) {} - - bool isOn() const - { return m_on; } - void setOn(bool on) - { - if (on == m_on) - return; - m_on = on; - update(); - } - -public slots: - void turnOff() { setOn(false); } - void turnOn() { setOn(true); } - -protected: - virtual void paintEvent(QPaintEvent *) - { - if (!m_on) - return; - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.setBrush(m_color); - painter.drawEllipse(0, 0, width(), height()); - } - -private: - QColor m_color; - bool m_on; -}; -//! [0] - -//! [1] -class TrafficLightWidget : public QWidget -{ -public: - TrafficLightWidget(QWidget *parent = 0) - : QWidget(parent) - { - QVBoxLayout *vbox = new QVBoxLayout(this); - m_red = new LightWidget(Qt::red); - vbox->addWidget(m_red); - m_yellow = new LightWidget(Qt::yellow); - vbox->addWidget(m_yellow); - m_green = new LightWidget(Qt::green); - vbox->addWidget(m_green); - QPalette pal = palette(); - pal.setColor(QPalette::Background, Qt::black); - setPalette(pal); - setAutoFillBackground(true); - } - - LightWidget *redLight() const - { return m_red; } - LightWidget *yellowLight() const - { return m_yellow; } - LightWidget *greenLight() const - { return m_green; } - -private: - LightWidget *m_red; - LightWidget *m_yellow; - LightWidget *m_green; -}; -//! [1] - -//! [2] -QState *createLightState(LightWidget *light, int duration, QState *parent = 0) -{ - QState *lightState = new QState(parent); - QTimer *timer = new QTimer(lightState); - timer->setInterval(duration); - timer->setSingleShot(true); - QState *timing = new QState(lightState); - QObject::connect(timing, SIGNAL(entered()), light, SLOT(turnOn())); - QObject::connect(timing, SIGNAL(entered()), timer, SLOT(start())); - QObject::connect(timing, SIGNAL(exited()), light, SLOT(turnOff())); - QFinalState *done = new QFinalState(lightState); - timing->addTransition(timer, SIGNAL(timeout()), done); - lightState->setInitialState(timing); - return lightState; -} -//! [2] - -//! [3] -class TrafficLight : public QWidget -{ -public: - TrafficLight(QWidget *parent = 0) - : QWidget(parent) - { - QVBoxLayout *vbox = new QVBoxLayout(this); - TrafficLightWidget *widget = new TrafficLightWidget(); - vbox->addWidget(widget); - vbox->setMargin(0); - - QStateMachine *machine = new QStateMachine(this); - QState *redGoingYellow = createLightState(widget->redLight(), 3000); - redGoingYellow->setObjectName("redGoingYellow"); - QState *yellowGoingGreen = createLightState(widget->yellowLight(), 1000); - yellowGoingGreen->setObjectName("yellowGoingGreen"); - redGoingYellow->addTransition(redGoingYellow, SIGNAL(finished()), yellowGoingGreen); - QState *greenGoingYellow = createLightState(widget->greenLight(), 3000); - greenGoingYellow->setObjectName("greenGoingYellow"); - yellowGoingGreen->addTransition(yellowGoingGreen, SIGNAL(finished()), greenGoingYellow); - QState *yellowGoingRed = createLightState(widget->yellowLight(), 1000); - yellowGoingRed->setObjectName("yellowGoingRed"); - greenGoingYellow->addTransition(greenGoingYellow, SIGNAL(finished()), yellowGoingRed); - yellowGoingRed->addTransition(yellowGoingRed, SIGNAL(finished()), redGoingYellow); - - machine->addState(redGoingYellow); - machine->addState(yellowGoingGreen); - machine->addState(greenGoingYellow); - machine->addState(yellowGoingRed); - machine->setInitialState(redGoingYellow); - machine->start(); - } -}; -//! [3] - -//! [4] -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - - TrafficLight widget; - widget.resize(110, 300); - widget.show(); - - return app.exec(); -} -//! [4] - -#include "main.moc" diff --git a/examples/statemachine/trafficlight/trafficlight.pro b/examples/statemachine/trafficlight/trafficlight.pro deleted file mode 100644 index 684575a..0000000 --- a/examples/statemachine/trafficlight/trafficlight.pro +++ /dev/null @@ -1,7 +0,0 @@ -SOURCES = main.cpp - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/trafficlight -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS trafficlight.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/trafficlight -INSTALLS += target sources diff --git a/examples/statemachine/twowaybutton/main.cpp b/examples/statemachine/twowaybutton/main.cpp deleted file mode 100644 index a2c6e45..0000000 --- a/examples/statemachine/twowaybutton/main.cpp +++ /dev/null @@ -1,86 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#endif - -//! [0] -int main(int argc, char **argv) -{ - QApplication app(argc, argv); - QPushButton button; - QStateMachine machine; -//! [0] - -//! [1] - QState *off = new QState(); - off->assignProperty(&button, "text", "Off"); - off->setObjectName("off"); - - QState *on = new QState(); - on->setObjectName("on"); - on->assignProperty(&button, "text", "On"); -//! [1] - -//! [2] - off->addTransition(&button, SIGNAL(clicked()), on); - on->addTransition(&button, SIGNAL(clicked()), off); -//! [2] - -//! [3] - machine.addState(off); - machine.addState(on); -//! [3] - -//! [4] - machine.setInitialState(off); - machine.start(); -//! [4] - -//! [5] - button.resize(100, 50); - button.show(); - return app.exec(); -} -//! [5] diff --git a/examples/statemachine/twowaybutton/twowaybutton.pro b/examples/statemachine/twowaybutton/twowaybutton.pro deleted file mode 100644 index f6cbc57..0000000 --- a/examples/statemachine/twowaybutton/twowaybutton.pro +++ /dev/null @@ -1,7 +0,0 @@ -SOURCES = main.cpp - -# install -target.path = $$[QT_INSTALL_EXAMPLES]/statemachine/twowaybutton -sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS twowaybutton.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/statemachine/twowaybutton -INSTALLS += target sources diff --git a/mkspecs/win32-icc/qmake.conf b/mkspecs/win32-icc/qmake.conf index 78c947d..03582fc 100644 --- a/mkspecs/win32-icc/qmake.conf +++ b/mkspecs/win32-icc/qmake.conf @@ -16,7 +16,7 @@ QMAKE_LEX = flex QMAKE_LEXFLAGS = QMAKE_YACC = byacc QMAKE_YACCFLAGS = -d -QMAKE_CFLAGS = -nologo -Zm200 /Qprec /Qwd1744,1738 +QMAKE_CFLAGS = -nologo -Zm200 /Qprec QMAKE_CFLAGS_WARN_ON = -W3 /Qwd673 QMAKE_CFLAGS_WARN_OFF = -W0 /Qwd673 QMAKE_CFLAGS_RELEASE = -O2 -MD diff --git a/src/3rdparty/easing/easing.cpp b/src/3rdparty/easing/easing.cpp deleted file mode 100644 index 81af40f..0000000 --- a/src/3rdparty/easing/easing.cpp +++ /dev/null @@ -1,670 +0,0 @@ -/* -Disclaimer for Robert Penner's Easing Equations license: - -TERMS OF USE - EASING EQUATIONS - -Open source under the BSD License. - -Copyright © 2001 Robert Penner -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - * Neither the name of the author nor the names of contributors may be used to endorse or promote products derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -*/ - -#include -#include -#ifndef M_PI -#define M_PI 3.14159265358979323846 -#endif -#ifndef M_PI_2 -#define M_PI_2 (M_PI / 2) -#endif - -QT_USE_NAMESPACE - -/** - * Easing equation function for a simple linear tweening, with no easing. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeNone(qreal progress) -{ - return progress; -} - -/** - * Easing equation function for a quadratic (t^2) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInQuad(qreal t) -{ - return t*t; -} - -/** -* Easing equation function for a quadratic (t^2) easing out: decelerating to zero velocity. -* -* @param t Current time (in frames or seconds). -* @return The correct value. -*/ -static qreal easeOutQuad(qreal t) -{ - return -t*(t-2); -} - -/** - * Easing equation function for a quadratic (t^2) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInOutQuad(qreal t) -{ - t*=2.0; - if (t < 1) { - return t*t/qreal(2); - } else { - --t; - return -0.5 * (t*(t-2) - 1); - } -} - -/** - * Easing equation function for a quadratic (t^2) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutInQuad(qreal t) -{ - if (t < 0.5) return easeOutQuad (t*2)/2; - return easeInQuad((2*t)-1)/2 + 0.5; -} - -/** - * Easing equation function for a cubic (t^3) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInCubic(qreal t) -{ - return t*t*t; -} - -/** - * Easing equation function for a cubic (t^3) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutCubic(qreal t) -{ - t-=1.0; - return t*t*t + 1; -} - -/** - * Easing equation function for a cubic (t^3) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInOutCubic(qreal t) -{ - t*=2.0; - if(t < 1) { - return 0.5*t*t*t; - } else { - t -= qreal(2.0); - return 0.5*(t*t*t + 2); - } -} - -/** - * Easing equation function for a cubic (t^3) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutInCubic(qreal t) -{ - if (t < 0.5) return easeOutCubic (2*t)/2; - return easeInCubic(2*t - 1)/2 + 0.5; -} - -/** - * Easing equation function for a quartic (t^4) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInQuart(qreal t) -{ - return t*t*t*t; -} - -/** - * Easing equation function for a quartic (t^4) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutQuart(qreal t) -{ - t-= qreal(1.0); - return - (t*t*t*t- 1); -} - -/** - * Easing equation function for a quartic (t^4) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInOutQuart(qreal t) -{ - t*=2; - if (t < 1) return 0.5*t*t*t*t; - else { - t -= 2.0f; - return -0.5 * (t*t*t*t- 2); - } -} - -/** - * Easing equation function for a quartic (t^4) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutInQuart(qreal t) -{ - if (t < 0.5) return easeOutQuart (2*t)/2; - return easeInQuart(2*t-1)/2 + 0.5; -} - -/** - * Easing equation function for a quintic (t^5) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInQuint(qreal t) -{ - return t*t*t*t*t; -} - -/** - * Easing equation function for a quintic (t^5) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutQuint(qreal t) -{ - t-=1.0; - return t*t*t*t*t + 1; -} - -/** - * Easing equation function for a quintic (t^5) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInOutQuint(qreal t) -{ - t*=2.0; - if (t < 1) return 0.5*t*t*t*t*t; - else { - t -= 2.0; - return 0.5*(t*t*t*t*t + 2); - } -} - -/** - * Easing equation function for a quintic (t^5) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutInQuint(qreal t) -{ - if (t < 0.5) return easeOutQuint (2*t)/2; - return easeInQuint(2*t - 1)/2 + 0.5; -} - -/** - * Easing equation function for a sinusoidal (sin(t)) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInSine(qreal t) -{ - return (t == 1.0) ? 1.0 : -::cos(t * M_PI_2) + 1.0; -} - -/** - * Easing equation function for a sinusoidal (sin(t)) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutSine(qreal t) -{ - return ::sin(t* M_PI_2); -} - -/** - * Easing equation function for a sinusoidal (sin(t)) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInOutSine(qreal t) -{ - return -0.5 * (::cos(M_PI*t) - 1); -} - -/** - * Easing equation function for a sinusoidal (sin(t)) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutInSine(qreal t) -{ - if (t < 0.5) return easeOutSine (2*t)/2; - return easeInSine(2*t - 1)/2 + 0.5; -} - -/** - * Easing equation function for an exponential (2^t) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInExpo(qreal t) -{ - return (t==0 || t == 1.0) ? t : ::qPow(2.0, 10 * (t - 1)) - qreal(0.001); -} - -/** - * Easing equation function for an exponential (2^t) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutExpo(qreal t) -{ - return (t==1.0) ? 1.0 : 1.001 * (-::qPow(2.0f, -10 * t) + 1); -} - -/** - * Easing equation function for an exponential (2^t) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInOutExpo(qreal t) -{ - if (t==0.0) return qreal(0.0); - if (t==1.0) return qreal(1.0); - t*=2.0; - if (t < 1) return 0.5 * ::qPow(qreal(2.0), 10 * (t - 1)) - 0.0005; - return 0.5 * 1.0005 * (-::qPow(qreal(2.0), -10 * (t - 1)) + 2); -} - -/** - * Easing equation function for an exponential (2^t) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutInExpo(qreal t) -{ - if (t < 0.5) return easeOutExpo (2*t)/2; - return easeInExpo(2*t - 1)/2 + 0.5; -} - -/** - * Easing equation function for a circular (sqrt(1-t^2)) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInCirc(qreal t) -{ - return -(::sqrt(1 - t*t) - 1); -} - -/** - * Easing equation function for a circular (sqrt(1-t^2)) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutCirc(qreal t) -{ - t-= qreal(1.0); - return ::sqrt(1 - t* t); -} - -/** - * Easing equation function for a circular (sqrt(1-t^2)) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeInOutCirc(qreal t) -{ - t*=qreal(2.0); - if (t < 1) { - return -0.5 * (::sqrt(1 - t*t) - 1); - } else { - t -= qreal(2.0); - return 0.5 * (::sqrt(1 - t*t) + 1); - } -} - -/** - * Easing equation function for a circular (sqrt(1-t^2)) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @return The correct value. - */ -static qreal easeOutInCirc(qreal t) -{ - if (t < 0.5) return easeOutCirc (2*t)/2; - return easeInCirc(2*t - 1)/2 + 0.5; -} - -static qreal easeInElastic_helper(qreal t, qreal b, qreal c, qreal d, qreal a, qreal p) -{ - if (t==0) return b; - qreal t_adj = (qreal)t / (qreal)d; - if (t_adj==1) return b+c; - - qreal s; - if(a < ::fabs(c)) { - a = c; - s = p / 4.0f; - } else { - s = p / (2 * M_PI) * ::asin(c / a); - } - - t_adj -= 1.0f; - return -(a*::qPow(2.0f,10*t_adj) * ::sin( (t_adj*d-s)*(2*M_PI)/p )) + b; -} - -/** - * Easing equation function for an elastic (exponentially decaying sine wave) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param a Amplitude. - * @param p Period. - * @return The correct value. - */ -static qreal easeInElastic(qreal t, qreal a, qreal p) -{ - return easeInElastic_helper(t, 0, 1, 1, a, p); -} - -static qreal easeOutElastic_helper(qreal t, qreal /*b*/, qreal c, qreal /*d*/, qreal a, qreal p) -{ - if (t==0) return 0; - if (t==1) return c; - - qreal s; - if(a < c) { - a = c; - s = p / 4.0f; - } else { - s = p / (2 * M_PI) * ::asin(c / a); - } - - return (a*::qPow(2.0f,-10*t) * ::sin( (t-s)*(2*M_PI)/p ) + c); -} - -/** - * Easing equation function for an elastic (exponentially decaying sine wave) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param a Amplitude. - * @param p Period. - * @return The correct value. - */ -static qreal easeOutElastic(qreal t, qreal a, qreal p) -{ - return easeOutElastic_helper(t, 0, 1, 1, a, p); -} - -/** - * Easing equation function for an elastic (exponentially decaying sine wave) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param a Amplitude. - * @param p Period. - * @return The correct value. - */ -static qreal easeInOutElastic(qreal t, qreal a, qreal p) -{ - if (t==0) return 0.0; - t*=2.0; - if (t==2) return 1.0; - - qreal s; - if(a < 1.0) { - a = 1.0; - s = p / 4.0f; - } else { - s = p / (2 * M_PI) * ::asin(1.0 / a); - } - - if (t < 1) return -.5*(a*::qPow(2.0f,10*(t-1)) * ::sin( (t-1-s)*(2*M_PI)/p )); - return a*::qPow(2.0f,-10*(t-1)) * ::sin( (t-1-s)*(2*M_PI)/p )*.5 + 1.0; -} - -/** - * Easing equation function for an elastic (exponentially decaying sine wave) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param a Amplitude. - * @param p Period. - * @return The correct value. - */ -static qreal easeOutInElastic(qreal t, qreal a, qreal p) -{ - if (t < 0.5) return easeOutElastic_helper(t*2, 0, 0.5, 1.0, a, p); - return easeInElastic_helper(2*t - 1.0, 0.5, 0.5, 1.0, a, p); -} - -/** - * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). - * @return The correct value. - */ -static qreal easeInBack(qreal t, qreal s) -{ - return t*t*((s+1)*t - s); -} - -/** - * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). - * @return The correct value. - */ -static qreal easeOutBack(qreal t, qreal s) -{ - t-= qreal(1.0); - return t*t*((s+1)*t+ s) + 1; -} - -/** - * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). - * @return The correct value. - */ -static qreal easeInOutBack(qreal t, qreal s) -{ - t *= 2.0; - if (t < 1) { - s *= 1.525f; - return 0.5*(t*t*((s+1)*t - s)); - } else { - t -= 2; - s *= 1.525f; - return 0.5*(t*t*((s+1)*t+ s) + 2); - } -} - -/** - * Easing equation function for a back (overshooting cubic easing: (s+1)*t^3 - s*t^2) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param s Overshoot ammount: higher s means greater overshoot (0 produces cubic easing with no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent). - * @return The correct value. - */ -static qreal easeOutInBack(qreal t, qreal s) -{ - if (t < 0.5) return easeOutBack (2*t, s)/2; - return easeInBack(2*t - 1, s)/2 + 0.5; -} - -static qreal easeOutBounce_helper(qreal t, qreal c, qreal a) -{ - if (t == 1.0) return c; - if (t < (4/11.0)) { - return c*(7.5625*t*t); - } else if (t < (8/11.0)) { - t -= (6/11.0); - return -a * (1. - (7.5625*t*t + .75)) + c; - } else if (t < (10/11.0)) { - t -= (9/11.0); - return -a * (1. - (7.5625*t*t + .9375)) + c; - } else { - t -= (21/22.0); - return -a * (1. - (7.5625*t*t + .984375)) + c; - } -} - -/** - * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out: decelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param a Amplitude. - * @return The correct value. - */ -static qreal easeOutBounce(qreal t, qreal a) -{ - return easeOutBounce_helper(t, 1, a); -} - -/** - * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in: accelerating from zero velocity. - * - * @param t Current time (in frames or seconds). - * @param a Amplitude. - * @return The correct value. - */ -static qreal easeInBounce(qreal t, qreal a) -{ - return 1.0 - easeOutBounce_helper(1.0-t, 1.0, a); -} - - -/** - * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing in/out: acceleration until halfway, then deceleration. - * - * @param t Current time (in frames or seconds). - * @param a Amplitude. - * @return The correct value. - */ -static qreal easeInOutBounce(qreal t, qreal a) -{ - if (t < 0.5) return easeInBounce (2*t, a)/2; - else return (t == 1.0) ? 1.0 : easeOutBounce (2*t - 1, a)/2 + 0.5; -} - -/** - * Easing equation function for a bounce (exponentially decaying parabolic bounce) easing out/in: deceleration until halfway, then acceleration. - * - * @param t Current time (in frames or seconds). - * @param a Amplitude. - * @return The correct value. - */ -static qreal easeOutInBounce(qreal t, qreal a) -{ - if (t < 0.5) return easeOutBounce_helper(t*2, 0.5, a); - return 1.0 - easeOutBounce_helper (2.0-2*t, 0.5, a); -} - -static inline qreal qt_sinProgress(qreal value) -{ - return qSin((value * M_PI) - M_PI_2) / 2 + qreal(0.5); -} - -static inline qreal qt_smoothBeginEndMixFactor(qreal value) -{ - return qMin(qMax(1 - value * 2 + qreal(0.3), qreal(0.0)), qreal(1.0)); -} - -// SmoothBegin blends Smooth and Linear Interpolation. -// Progress 0 - 0.3 : Smooth only -// Progress 0.3 - ~ 0.5 : Mix of Smooth and Linear -// Progress ~ 0.5 - 1 : Linear only - -/** - * Easing function that starts growing slowly, then increases in speed. At the end of the curve the speed will be constant. - */ -static qreal easeInCurve(qreal t) -{ - const qreal sinProgress = qt_sinProgress(t); - const qreal mix = qt_smoothBeginEndMixFactor(t); - return sinProgress * mix + t * (1 - mix); -} - -/** - * Easing function that starts growing steadily, then ends slowly. The speed will be constant at the beginning of the curve. - */ -static qreal easeOutCurve(qreal t) -{ - const qreal sinProgress = qt_sinProgress(t); - const qreal mix = qt_smoothBeginEndMixFactor(1 - t); - return sinProgress * mix + t * (1 - mix); -} - -/** - * Easing function where the value grows sinusoidally. Note that the calculated end value will be 0 rather than 1. - */ -static qreal easeSineCurve(qreal t) -{ - return (qSin(((t * M_PI * 2)) - M_PI_2) + 1) / 2; -} - -/** - * Easing function where the value grows cosinusoidally. Note that the calculated start value will be 0.5 and the end value will be 0.5 - * contrary to the usual 0 to 1 easing curve. - */ -static qreal easeCosineCurve(qreal t) -{ - return (qCos(((t * M_PI * 2)) - M_PI_2) + 1) / 2; -} - diff --git a/src/3rdparty/easing/legal.qdoc b/src/3rdparty/easing/legal.qdoc deleted file mode 100644 index 25f67e1..0000000 --- a/src/3rdparty/easing/legal.qdoc +++ /dev/null @@ -1,35 +0,0 @@ -/*! -\page legal-easing.html -\title Easing Equations by Robert Penner -\ingroup animation - -\legalese -\code -Copyright (c) 2001 Robert Penner -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - * Neither the name of the author nor the names of contributors may be used - to endorse or promote products derived from this software without specific - prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR -ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -\endcode -\endlegalese -*/ diff --git a/src/corelib/animation/animation.pri b/src/corelib/animation/animation.pri deleted file mode 100644 index cb7850c..0000000 --- a/src/corelib/animation/animation.pri +++ /dev/null @@ -1,25 +0,0 @@ -# Qt core animation module - -HEADERS += \ - animation/qabstractanimation.h \ - animation/qabstractanimation_p.h \ - animation/qvariantanimation.h \ - animation/qvariantanimation_p.h \ - animation/qpropertyanimation.h \ - animation/qpropertyanimation_p.h \ - animation/qanimationgroup.h \ - animation/qanimationgroup_p.h \ - animation/qsequentialanimationgroup.h \ - animation/qsequentialanimationgroup_p.h \ - animation/qparallelanimationgroup.h \ - animation/qparallelanimationgroup_p.h \ - animation/qpauseanimation.h - -SOURCES += \ - animation/qabstractanimation.cpp \ - animation/qvariantanimation.cpp \ - animation/qpropertyanimation.cpp \ - animation/qanimationgroup.cpp \ - animation/qsequentialanimationgroup.cpp \ - animation/qparallelanimationgroup.cpp \ - animation/qpauseanimation.cpp diff --git a/src/corelib/animation/qabstractanimation.cpp b/src/corelib/animation/qabstractanimation.cpp deleted file mode 100644 index 94a94d1..0000000 --- a/src/corelib/animation/qabstractanimation.cpp +++ /dev/null @@ -1,759 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \class QAbstractAnimation - \ingroup animation - \brief The QAbstractAnimation class is the base of all animations. - \since 4.6 - - The class defines the functions for the functionality shared by - all animations. By inheriting this class, you can create custom - animations that plug into the rest of the animation framework. - - The progress of an animation is given by its current time - (currentTime()), which is measured in milliseconds from the start - of the animation (0) to its end (duration()). The value is updated - automatically while the animation is running. It can also be set - directly with setCurrentTime(). - - At any point an animation is in one of three states: - \l{QAbstractAnimation::}{Running}, - \l{QAbstractAnimation::}{Stopped}, or - \l{QAbstractAnimation::}{Paused}--as defined by the - \l{QAbstractAnimation::}{State} enum. The current state can be - changed by calling start(), stop(), pause(), or resume(). An - animation will always reset its \l{currentTime()}{current time} - when it is started. If paused, it will continue with the same - current time when resumed. When an animation is stopped, it cannot - be resumed, but will keep its current time (until started again). - QAbstractAnimation will emit stateChanged() whenever its state - changes. - - An animation can loop any number of times by setting the loopCount - property. When an animation's current time reaches its duration(), - it will reset the current time and keep running. A loop count of 1 - (the default value) means that the animation will run one time. - Note that a duration of -1 means that the animation will run until - stopped; the current time will increase indefinitely. When the - current time equals duration() and the animation is in its - final loop, the \l{QAbstractAnimation::}{Stopped} state is - entered, and the finished() signal is emitted. - - QAbstractAnimation provides pure virtual functions used by - subclasses to track the progress of the animation: duration() and - updateCurrentTime(). The duration() function lets you report a - duration for the animation (as discussed above). The current time - is delivered by the animation framework through calls to - updateCurrentTime(). By reimplementing this function, you can - track the animation progress. Note that neither the interval - between calls nor the number of calls to this function are - defined; though, it will normally be 60 updates per second. - - By reimplementing updateState(), you can track the animation's - state changes, which is particularly useful for animations that - are not driven by time. - - \sa QVariantAnimation, QPropertyAnimation, QAnimationGroup, {The Animation Framework} -*/ - -/*! - \enum QAbstractAnimation::DeletionPolicy - - \value KeepWhenStopped The animation will not be deleted when stopped. - \value DeleteWhenStopped The animation will be automatically deleted when - stopped. -*/ - -/*! - \fn QAbstractAnimation::finished() - - QAbstractAnimation emits this signal after the animation has stopped and - has reached the end. - - This signal is emitted after stateChanged(). - - \sa stateChanged() -*/ - -/*! - \fn QAbstractAnimation::stateChanged(QAbstractAnimation::State oldState, QAbstractAnimation::State newState) - - QAbstractAnimation emits this signal whenever the state of the animation has - changed from \a oldState to \a newState. This signal is emitted after the virtual - updateState() function is called. - - \sa updateState() -*/ - -/*! - \fn QAbstractAnimation::currentLoopChanged(int currentLoop) - - QAbstractAnimation emits this signal whenever the current loop - changes. \a currentLoop is the current loop. - - \sa currentLoop(), loopCount() -*/ - -/*! - \fn QAbstractAnimation::directionChanged(QAbstractAnimation::Direction newDirection); - - QAbstractAnimation emits this signal whenever the direction has been - changed. \a newDirection is the new direction. - - \sa direction -*/ - -#ifndef QT_NO_ANIMATION - -#include "qabstractanimation.h" -#include "qanimationgroup.h" -#include - -#include "qabstractanimation_p.h" - -#include -#include -#include -#include - -#define DEFAULT_TIMER_INTERVAL 16 - -QT_BEGIN_NAMESPACE - -Q_GLOBAL_STATIC(QThreadStorage, unifiedTimer); - -QUnifiedTimer::QUnifiedTimer() : QObject(), lastTick(0), timingInterval(DEFAULT_TIMER_INTERVAL), consistentTiming(false) -{ -} - -QUnifiedTimer *QUnifiedTimer::instance() -{ - QUnifiedTimer *inst; - if (!unifiedTimer()->hasLocalData()) { - inst = new QUnifiedTimer; - unifiedTimer()->setLocalData(inst); - } else { - inst = unifiedTimer()->localData(); - } - return inst; -} - -void QUnifiedTimer::updateRecentlyStartedAnimations() -{ - if (animationsToStart.isEmpty()) - return; - - animations += animationsToStart; - updateTimer(); //we make sure we start the timer there - - animationsToStart.clear(); -} - -/* - defines the timing interval. Default is DEFAULT_TIMER_INTERVAL -*/ -void QUnifiedTimer::setTimingInterval(int interval) -{ - timingInterval = interval; - if (animationTimer.isActive()) { - //we changed the timing interval - animationTimer.start(timingInterval, this); - } -} - -/* - this allows to have a consistent timer interval at each tick from the timer - not taking the real time that passed into account. -*/ -void QUnifiedTimer::setConsistentTiming(bool b) -{ - consistentTiming = b; -} - -int QUnifiedTimer::elapsedTime() const -{ - return lastTick; -} - -void QUnifiedTimer::timerEvent(QTimerEvent *event) -{ - //this is simply the time we last received a tick - const int oldLastTick = lastTick; - if (time.isValid()) - lastTick = consistentTiming ? oldLastTick + timingInterval : time.elapsed(); - - //we transfer the waiting animations into the "really running" state - updateRecentlyStartedAnimations(); - - if (event->timerId() == startStopAnimationTimer.timerId()) { - startStopAnimationTimer.stop(); - if (animations.isEmpty()) { - animationTimer.stop(); - time = QTime(); - } else { - animationTimer.start(timingInterval, this); - lastTick = 0; - time.start(); - } - } else if (event->timerId() == animationTimer.timerId()) { - const int delta = lastTick - oldLastTick; - for (int i = 0; i < animations.count(); ++i) { - QAbstractAnimation *animation = animations.at(i); - int elapsed = QAbstractAnimationPrivate::get(animation)->totalCurrentTime - + (animation->direction() == QAbstractAnimation::Forward ? delta : -delta); - animation->setCurrentTime(elapsed); - } - } -} - -void QUnifiedTimer::updateTimer() -{ - //we delay the call to start and stop for the animation timer so that if you - //stop and start animations in batch you don't stop/start the timer too often. - if (!startStopAnimationTimer.isActive()) - startStopAnimationTimer.start(0, this); // we delay the actual start of the animation -} - -void QUnifiedTimer::registerAnimation(QAbstractAnimation *animation) -{ - if (animations.contains(animation) ||animationsToStart.contains(animation)) - return; - animationsToStart << animation; - updateTimer(); -} - -void QUnifiedTimer::unregisterAnimation(QAbstractAnimation *animation) -{ - animations.removeAll(animation); - animationsToStart.removeAll(animation); - updateTimer(); -} - - -void QAbstractAnimationPrivate::setState(QAbstractAnimation::State newState) -{ - Q_Q(QAbstractAnimation); - if (state == newState) - return; - - QAbstractAnimation::State oldState = state; - int oldCurrentTime = currentTime; - int oldCurrentLoop = currentLoop; - QAbstractAnimation::Direction oldDirection = direction; - - state = newState; - - QPointer guard(q); - - guard->updateState(oldState, newState); - - //this is to be safe if updateState changes the state - if (state == oldState) - return; - - // Notify state change - if (guard) - emit guard->stateChanged(oldState, newState); - - // Enter running state. - switch (state) - { - case QAbstractAnimation::Paused: - case QAbstractAnimation::Running: - { - // Rewind - if (oldState == QAbstractAnimation::Stopped) { - if (guard) { - if (direction == QAbstractAnimation::Forward) - q->setCurrentTime(0); - else - q->setCurrentTime(loopCount == -1 ? q->duration() : q->totalDuration()); - } - - // Check if the setCurrentTime() function called stop(). - // This can happen for a 0-duration animation - if (state == QAbstractAnimation::Stopped) - return; - } - - // Register timer if our parent is not running. - if (state == QAbstractAnimation::Running && guard) { - if (!group || group->state() == QAbstractAnimation::Stopped) { - QUnifiedTimer::instance()->registerAnimation(q); - } - } else { - //new state is paused - QUnifiedTimer::instance()->unregisterAnimation(q); - } - } - break; - case QAbstractAnimation::Stopped: - // Leave running state. - int dura = q->duration(); - if (deleteWhenStopped && guard) - q->deleteLater(); - - QUnifiedTimer::instance()->unregisterAnimation(q); - - if (dura == -1 || loopCount < 0 - || (oldDirection == QAbstractAnimation::Forward && (oldCurrentTime * (oldCurrentLoop + 1)) == (dura * loopCount)) - || (oldDirection == QAbstractAnimation::Backward && oldCurrentTime == 0)) { - if (guard) - emit q->finished(); - } - break; - } - -} - -/*! - Constructs the QAbstractAnimation base class, and passes \a parent to - QObject's constructor. - - \sa QVariantAnimation, QAnimationGroup -*/ -QAbstractAnimation::QAbstractAnimation(QObject *parent) - : QObject(*new QAbstractAnimationPrivate, 0) -{ - // Allow auto-add on reparent - setParent(parent); -} - -/*! - \internal -*/ -QAbstractAnimation::QAbstractAnimation(QAbstractAnimationPrivate &dd, QObject *parent) - : QObject(dd, 0) -{ - // Allow auto-add on reparent - setParent(parent); -} - -/*! - Stops the animation if it's running, then destroys the - QAbstractAnimation. If the animation is part of a QAnimationGroup, it is - automatically removed before it's destroyed. -*/ -QAbstractAnimation::~QAbstractAnimation() -{ - Q_D(QAbstractAnimation); - //we can't call stop here. Otherwise we get pure virtual calls - if (d->state != Stopped) { - QAbstractAnimation::State oldState = d->state; - d->state = Stopped; - emit stateChanged(oldState, d->state); - QUnifiedTimer::instance()->unregisterAnimation(this); - } -} - -/*! - \property QAbstractAnimation::state - \brief state of the animation. - - This property describes the current state of the animation. When the - animation state changes, QAbstractAnimation emits the stateChanged() - signal. -*/ -QAbstractAnimation::State QAbstractAnimation::state() const -{ - Q_D(const QAbstractAnimation); - return d->state; -} - -/*! - If this animation is part of a QAnimationGroup, this function returns a - pointer to the group; otherwise, it returns 0. - - \sa QAnimationGroup::addAnimation() -*/ -QAnimationGroup *QAbstractAnimation::group() const -{ - Q_D(const QAbstractAnimation); - return d->group; -} - -/*! - \enum QAbstractAnimation::State - - This enum describes the state of the animation. - - \value Stopped The animation is not running. This is the initial state - of QAbstractAnimation, and the state QAbstractAnimation reenters when finished. The current - time remain unchanged until either setCurrentTime() is - called, or the animation is started by calling start(). - - \value Paused The animation is paused (i.e., temporarily - suspended). Calling resume() will resume animation activity. - - \value Running The animation is running. While control is in the event - loop, QAbstractAnimation will update its current time at regular intervals, - calling updateCurrentTime() when appropriate. - - \sa state(), stateChanged() -*/ - -/*! - \enum QAbstractAnimation::Direction - - This enum describes the direction of the animation when in \l Running state. - - \value Forward The current time of the animation increases with time (i.e., - moves from 0 and towards the end / duration). - - \value Backward The current time of the animation decreases with time (i.e., - moves from the end / duration and towards 0). - - \sa direction -*/ - -/*! - \property QAbstractAnimation::direction - \brief the direction of the animation when it is in \l Running - state. - - This direction indicates whether the time moves from 0 towards the - animation duration, or from the value of the duration and towards 0 after - start() has been called. - - By default, this property is set to \l Forward. -*/ -QAbstractAnimation::Direction QAbstractAnimation::direction() const -{ - Q_D(const QAbstractAnimation); - return d->direction; -} -void QAbstractAnimation::setDirection(Direction direction) -{ - Q_D(QAbstractAnimation); - if (d->direction == direction) - return; - - d->direction = direction; - if (state() == Stopped) { - if (direction == Backward) { - d->currentTime = duration(); - d->currentLoop = d->loopCount - 1; - } else { - d->currentTime = 0; - d->currentLoop = 0; - } - } - updateDirection(direction); - emit directionChanged(direction); -} - -/*! - \property QAbstractAnimation::duration - \brief the duration of the animation. - - If the duration is -1, it means that the duration is undefined. - In this case, loopCount is ignored. -*/ - -/*! - \property QAbstractAnimation::loopCount - \brief the loop count of the animation - - This property describes the loop count of the animation as an integer. - By default this value is 1, indicating that the animation - should run once only, and then stop. By changing it you can let the - animation loop several times. With a value of 0, the animation will not - run at all, and with a value of -1, the animation will loop forever - until stopped. - It is not supported to have loop on an animation that has an undefined - duration. It will only run once. -*/ -int QAbstractAnimation::loopCount() const -{ - Q_D(const QAbstractAnimation); - return d->loopCount; -} -void QAbstractAnimation::setLoopCount(int loopCount) -{ - Q_D(QAbstractAnimation); - d->loopCount = loopCount; -} - -/*! - \property QAbstractAnimation::currentLoop - \brief the current loop of the animation - - This property describes the current loop of the animation. By default, - the animation's loop count is 1, and so the current loop will - always be 0. If the loop count is 2 and the animation runs past its - duration, it will automatically rewind and restart at current time 0, and - current loop 1, and so on. - - When the current loop changes, QAbstractAnimation emits the - currentLoopChanged() signal. -*/ -int QAbstractAnimation::currentLoop() const -{ - Q_D(const QAbstractAnimation); - return d->currentLoop; -} - -/*! - \fn virtual int QAbstractAnimation::duration() const = 0 - - This pure virtual function returns the duration of the animation, and - defines for how long QAbstractAnimation should update the current - time. This duration is local, and does not include the loop count. - - A return value of -1 indicates that the animation has no defined duration; - the animation should run forever until stopped. This is useful for - animations that are not time driven, or where you cannot easily predict - its duration (e.g., event driven audio playback in a game). - - If the animation is a parallel QAnimationGroup, the duration will be the longest - duration of all its animations. If the animation is a sequential QAnimationGroup, - the duration will be the sum of the duration of all its animations. - \sa loopCount -*/ - -/*! - Returns the total and effective duration of the animation, including the - loop count. - - \sa duration(), currentTime -*/ -int QAbstractAnimation::totalDuration() const -{ - Q_D(const QAbstractAnimation); - if (d->loopCount < 0) - return -1; - int dura = duration(); - if (dura == -1) - return -1; - return dura * d->loopCount; -} - -/*! - \property QAbstractAnimation::currentTime - \brief the current time and progress of the animation - - This property describes the animation's current time. You can change the - current time by calling setCurrentTime, or you can call start() and let - the animation run, setting the current time automatically as the animation - progresses. - - The animation's current time starts at 0, and ends at duration(). If the - animation's loopCount is larger than 1, the current time will rewind and - start at 0 again for the consecutive loops. If the animation has a pause. - currentTime will also include the duration of the pause. - - \sa loopCount - */ -int QAbstractAnimation::currentTime() const -{ - Q_D(const QAbstractAnimation); - return d->currentTime; -} -void QAbstractAnimation::setCurrentTime(int msecs) -{ - Q_D(QAbstractAnimation); - msecs = qMax(msecs, 0); - - // Calculate new time and loop. - int dura = duration(); - int totalDura = (d->loopCount < 0 || dura == -1) ? -1 : dura * d->loopCount; - if (totalDura != -1) - msecs = qMin(totalDura, msecs); - d->totalCurrentTime = msecs; - - // Update new values. - int oldLoop = d->currentLoop; - d->currentLoop = ((dura <= 0) ? 0 : (msecs / dura)); - if (d->currentLoop == d->loopCount) { - //we're at the end - d->currentTime = qMax(0, dura); - d->currentLoop = qMax(0, d->loopCount - 1); - } else { - if (d->direction == Forward) { - d->currentTime = (dura <= 0) ? msecs : (msecs % dura); - } else { - d->currentTime = (dura <= 0) ? msecs : ((msecs - 1) % dura) + 1; - if (d->currentTime == dura) - --d->currentLoop; - } - } - - updateCurrentTime(msecs); - if (d->currentLoop != oldLoop) - emit currentLoopChanged(d->currentLoop); - - // All animations are responsible for stopping the animation when their - // own end state is reached; in this case the animation is time driven, - // and has reached the end. - if ((d->direction == Forward && d->totalCurrentTime == totalDura) - || (d->direction == Backward && d->totalCurrentTime == 0)) { - stop(); - } -} - -/*! - Starts the animation. The \a policy argument says whether or not the - animation should be deleted when it's done. When the animation starts, the - stateChanged() signal is emitted, and state() returns Running. When control - reaches the event loop, the animation will run by itself, periodically - calling updateCurrentTime() as the animation progresses. - - If the animation is currently stopped or has already reached the end, - calling start() will rewind the animation and start again from the beginning. - When the animation reaches the end, the animation will either stop, or - if the loop level is more than 1, it will rewind and continue from the beginning. - - If the animation is already running, this function does nothing. - - \sa stop(), state() -*/ -void QAbstractAnimation::start(DeletionPolicy policy) -{ - Q_D(QAbstractAnimation); - if (d->state == Running) - return; - d->setState(Running); - d->deleteWhenStopped = policy; -} - -/*! - Stops the animation. When the animation is stopped, it emits the stateChanged() - signal, and state() returns Stopped. The current time is not changed. - - If the animation stops by itself after reaching the end (i.e., - currentTime() == duration() and currentLoop() > loopCount() - 1), the - finished() signal is emitted. - - \sa start(), state() - */ -void QAbstractAnimation::stop() -{ - Q_D(QAbstractAnimation); - - d->setState(Stopped); -} - -/*! - Pauses the animation. When the animation is paused, state() returns Paused. - The currenttime will remain unchanged until resume() or start() is called. - If you want to continue from the current time, call resume(). - - - \sa start(), state(), resume() - */ -void QAbstractAnimation::pause() -{ - Q_D(QAbstractAnimation); - if (d->state == Stopped) { - qWarning("QAbstractAnimation::pause: Cannot pause a stopped animation"); - return; - } - - d->setState(Paused); -} - -/*! - Resumes the animation after it was paused. When the animation is resumed, - it emits the resumed() and stateChanged() signals. The currenttime is not - changed. - - \sa start(), pause(), state() - */ -void QAbstractAnimation::resume() -{ - Q_D(QAbstractAnimation); - if (d->state != Paused) { - qWarning("QAbstractAnimation::resume: " - "Cannot resume an animation that is not paused"); - return; - } - - d->setState(Running); -} - -/*! - \reimp -*/ -bool QAbstractAnimation::event(QEvent *event) -{ - return QObject::event(event); -} - -/*! - \fn virtual void QAbstractAnimation::updateCurrentTime(int msecs) = 0; - - This pure virtual function is called every time the animation's current - time changes. The \a msecs argument is the current time. - - \sa updateState() -*/ - -/*! - This virtual function is called by QAbstractAnimation when the state - of the animation is changed from \a oldState to \a newState. - - \sa start(), stop(), pause(), resume() -*/ -void QAbstractAnimation::updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) -{ - Q_UNUSED(oldState); - Q_UNUSED(newState); -} - -/*! - This virtual function is called by QAbstractAnimation when the direction - of the animation is changed. The \a direction argument is the new direction. - - \sa setDirection(), direction() -*/ -void QAbstractAnimation::updateDirection(QAbstractAnimation::Direction direction) -{ - Q_UNUSED(direction); -} - - -QT_END_NAMESPACE - -#include "moc_qabstractanimation.cpp" - -#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qabstractanimation.h b/src/corelib/animation/qabstractanimation.h deleted file mode 100644 index d6d50dc..0000000 --- a/src/corelib/animation/qabstractanimation.h +++ /dev/null @@ -1,137 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QABSTRACTANIMATION_H -#define QABSTRACTANIMATION_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -#ifndef QT_NO_ANIMATION - -class QAnimationGroup; -class QSequentialAnimationGroup; - -class QAbstractAnimationPrivate; -class Q_CORE_EXPORT QAbstractAnimation : public QObject -{ - Q_OBJECT - Q_PROPERTY(State state READ state NOTIFY stateChanged) - Q_PROPERTY(int loopCount READ loopCount WRITE setLoopCount) - Q_PROPERTY(int currentTime READ currentTime WRITE setCurrentTime) - Q_PROPERTY(int currentLoop READ currentLoop NOTIFY currentLoopChanged) - Q_PROPERTY(Direction direction READ direction WRITE setDirection NOTIFY directionChanged) - Q_PROPERTY(int duration READ duration) - -public: - enum Direction { - Forward, - Backward - }; - - enum State { - Stopped, - Paused, - Running - }; - - enum DeletionPolicy { - KeepWhenStopped = 0, - DeleteWhenStopped - }; - - QAbstractAnimation(QObject *parent = 0); - virtual ~QAbstractAnimation(); - - State state() const; - - QAnimationGroup *group() const; - - Direction direction() const; - void setDirection(Direction direction); - - int loopCount() const; - void setLoopCount(int loopCount); - int currentLoop() const; - - virtual int duration() const = 0; - int totalDuration() const; - - int currentTime() const; - -Q_SIGNALS: - void finished(); - void stateChanged(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - void currentLoopChanged(int currentLoop); - void directionChanged(QAbstractAnimation::Direction); - -public Q_SLOTS: - void start(QAbstractAnimation::DeletionPolicy policy = KeepWhenStopped); - void pause(); - void resume(); - void stop(); - void setCurrentTime(int msecs); - -protected: - QAbstractAnimation(QAbstractAnimationPrivate &dd, QObject *parent = 0); - bool event(QEvent *event); - - virtual void updateCurrentTime(int msecs) = 0; - virtual void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - virtual void updateDirection(QAbstractAnimation::Direction direction); - -private: - Q_DISABLE_COPY(QAbstractAnimation) - Q_DECLARE_PRIVATE(QAbstractAnimation) -}; - -#endif //QT_NO_ANIMATION - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QABSTRACTANIMATION_H diff --git a/src/corelib/animation/qabstractanimation_p.h b/src/corelib/animation/qabstractanimation_p.h deleted file mode 100644 index e64554c..0000000 --- a/src/corelib/animation/qabstractanimation_p.h +++ /dev/null @@ -1,136 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QABSTRACTANIMATION_P_H -#define QABSTRACTANIMATION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of QIODevice. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -class QAnimationGroup; -class QAbstractAnimation; -class QAbstractAnimationPrivate : public QObjectPrivate -{ -public: - QAbstractAnimationPrivate() - : state(QAbstractAnimation::Stopped), - direction(QAbstractAnimation::Forward), - deleteWhenStopped(false), - totalCurrentTime(0), - currentTime(0), - loopCount(1), - currentLoop(0), - group(0) - { - } - - virtual ~QAbstractAnimationPrivate() {} - - static QAbstractAnimationPrivate *get(QAbstractAnimation *q) - { - return q->d_func(); - } - - QAbstractAnimation::State state; - QAbstractAnimation::Direction direction; - bool deleteWhenStopped; - void setState(QAbstractAnimation::State state); - - int totalCurrentTime; - int currentTime; - int loopCount; - int currentLoop; - - QAnimationGroup *group; - -private: - Q_DECLARE_PUBLIC(QAbstractAnimation) -}; - - -class Q_CORE_EXPORT QUnifiedTimer : public QObject -{ -private: - QUnifiedTimer(); - -public: - static QUnifiedTimer *instance(); - - void registerAnimation(QAbstractAnimation *animation); - void unregisterAnimation(QAbstractAnimation *animation); - - void setTimingInterval(int interval); - void setConsistentTiming(bool consistent); - - int elapsedTime() const; - -protected: - void timerEvent(QTimerEvent *); - void updateTimer(); - -private: - void updateRecentlyStartedAnimations(); - - QBasicTimer animationTimer, startStopAnimationTimer; - QTime time; - int lastTick; - int timingInterval; - bool consistentTiming; - QList animations, animationsToStart; -}; - -QT_END_NAMESPACE -#endif diff --git a/src/corelib/animation/qanimationgroup.cpp b/src/corelib/animation/qanimationgroup.cpp deleted file mode 100644 index ed06eff..0000000 --- a/src/corelib/animation/qanimationgroup.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \class QAnimationGroup - \brief The QAnimationGroup class is an abstract base class for groups of animations. - \since 4.6 - \ingroup animation - - An animation group is a container for animations (subclasses of - QAbstractAnimation). A group is usually responsible for managing - the \l{QAbstractAnimation::State}{state} of its animations, i.e., - it decides when to start, stop, resume, and pause them. Currently, - Qt provides two such groups: QParallelAnimationGroup and - QSequentialAnimationGroup. Look up their class descriptions for - details. - - Since QAnimationGroup inherits from QAbstractAnimation, you can - combine groups, and easily construct complex animation graphs. - You can query QAbstractAnimation for the group it belongs to - (using the \l{QAbstractAnimation::}{group()} function). - - To start a top-level animation group, you simply use the - \l{QAbstractAnimation::}{start()} function from - QAbstractAnimation. By a top-level animation group, we think of a - group that itself is not contained within another group. Starting - sub groups directly is not supported, and may lead to unexpected - behavior. - - \omit OK, we'll put in a snippet on this here \endomit - - QAnimationGroup provides methods for adding and retrieving - animations. Besides that, you can remove animations by calling - remove(), and clear the animation group by calling - clearAnimations(). You may keep track of changes in the group's - animations by listening to QEvent::ChildAdded and - QEvent::ChildRemoved events. - - \omit OK, let's find a snippet here as well. \endomit - - QAnimationGroup takes ownership of the animations it manages, and - ensures that they are deleted when the animation group is deleted. - - You can also use a \l{The State Machine Framework}{state machine} - to create complex animations. The framework provides a special - state, QAnimationState, that plays an animation upon entry and - transitions to a new state when the animation has finished - playing. This technique can also be combined with using animation - groups. - - \sa QAbstractAnimation, QVariantAnimation, {The Animation Framework} -*/ - -#ifndef QT_NO_ANIMATION - -#include "qanimationgroup.h" -#include -#include -#include "qanimationgroup_p.h" - -QT_BEGIN_NAMESPACE - - -/*! - Constructs a QAnimationGroup. - \a parent is passed to QObject's constructor. -*/ -QAnimationGroup::QAnimationGroup(QObject *parent) - : QAbstractAnimation(*new QAnimationGroupPrivate, parent) -{ -} - -/*! - \internal -*/ -QAnimationGroup::QAnimationGroup(QAnimationGroupPrivate &dd, QObject *parent) - : QAbstractAnimation(dd, parent) -{ -} - -/*! - Destroys the animation group. It will also destroy all its animations. -*/ -QAnimationGroup::~QAnimationGroup() -{ -} - -/*! - Returns a pointer to the animation at \a index in this group. This - function is useful when you need access to a particular animation. \a - index is between 0 and animationCount() - 1. - - \sa animationCount(), indexOfAnimation() -*/ -QAbstractAnimation *QAnimationGroup::animationAt(int index) const -{ - Q_D(const QAnimationGroup); - - if (index < 0 || index >= d->animations.size()) { - qWarning("QAnimationGroup::animationAt: index is out of bounds"); - return 0; - } - - return d->animations.at(index); -} - - -/*! - Returns the number of animations managed by this group. - - \sa indexOfAnimation(), addAnimation(), animationAt() -*/ -int QAnimationGroup::animationCount() const -{ - Q_D(const QAnimationGroup); - return d->animations.size(); -} - -/*! - Returns the index of \a animation. The returned index can be passed - to the other functions that take an index as an argument. - - \sa insertAnimationAt(), animationAt(), takeAnimationAt() -*/ -int QAnimationGroup::indexOfAnimation(QAbstractAnimation *animation) const -{ - Q_D(const QAnimationGroup); - return d->animations.indexOf(animation); -} - -/*! - Adds \a animation to this group. This will call insertAnimationAt with - index equals to animationCount(). - - \note The group takes ownership of the animation. - - \sa removeAnimation() -*/ -void QAnimationGroup::addAnimation(QAbstractAnimation *animation) -{ - Q_D(QAnimationGroup); - insertAnimationAt(d->animations.count(), animation); -} - -/*! - Inserts \a animation into this animation group at \a index. - If \a index is 0 the animation is inserted at the beginning. - If \a index is animationCount(), the animation is inserted at the end. - - \note The group takes ownership of the animation. - - \sa takeAnimationAt(), addAnimation(), indexOfAnimation(), removeAnimation() -*/ -void QAnimationGroup::insertAnimationAt(int index, QAbstractAnimation *animation) -{ - Q_D(QAnimationGroup); - - if (index < 0 || index > d->animations.size()) { - qWarning("QAnimationGroup::insertAnimationAt: index is out of bounds"); - return; - } - - if (QAnimationGroup *oldGroup = animation->group()) - oldGroup->removeAnimation(animation); - - d->animations.insert(index, animation); - QAbstractAnimationPrivate::get(animation)->group = this; - // this will make sure that ChildAdded event is sent to 'this' - animation->setParent(this); - d->animationInsertedAt(index); -} - -/*! - Removes \a animation from this group. The ownership of \a animation is - transferred to the caller. - - \sa takeAnimationAt(), insertAnimationAt(), addAnimation() -*/ -void QAnimationGroup::removeAnimation(QAbstractAnimation *animation) -{ - Q_D(QAnimationGroup); - - if (!animation) { - qWarning("QAnimationGroup::remove: cannot remove null animation"); - return; - } - int index = d->animations.indexOf(animation); - if (index == -1) { - qWarning("QAnimationGroup::remove: animation is not part of this group"); - return; - } - - takeAnimationAt(index); -} - -/*! - Returns the animation at \a index and removes it from the animation group. - - \note The ownership of the animation is transferred to the caller. - - \sa removeAnimation(), addAnimation(), insertAnimation(), indexOfAnimation() -*/ -QAbstractAnimation *QAnimationGroup::takeAnimationAt(int index) -{ - Q_D(QAnimationGroup); - if (index < 0 || index >= d->animations.size()) { - qWarning("QAnimationGroup::takeAnimationAt: no animation at index %d", index); - return 0; - } - QAbstractAnimation *animation = d->animations.at(index); - QAbstractAnimationPrivate::get(animation)->group = 0; - // ### removing from list before doing setParent to avoid inifinite recursion - // in ChildRemoved event - d->animations.removeAt(index); - animation->setParent(0); - d->animationRemovedAt(index); - return animation; -} - -/*! - Removes and deletes all animations in this animation group, and resets the current - time to 0. - - \sa addAnimation(), removeAnimation() -*/ -void QAnimationGroup::clearAnimations() -{ - Q_D(QAnimationGroup); - qDeleteAll(d->animations); -} - -/*! - \reimp -*/ -bool QAnimationGroup::event(QEvent *event) -{ - Q_D(QAnimationGroup); - if (event->type() == QEvent::ChildAdded) { - QChildEvent *childEvent = static_cast(event); - if (QAbstractAnimation *a = qobject_cast(childEvent->child())) { - if (a->group() != this) - addAnimation(a); - } - } else if (event->type() == QEvent::ChildRemoved) { - QChildEvent *childEvent = static_cast(event); - QAbstractAnimation *a = static_cast(childEvent->child()); - // You can only rely on the child being a QObject because in the QEvent::ChildRemoved - // case it might be called from the destructor. - int index = d->animations.indexOf(a); - if (index != -1) - takeAnimationAt(index); - } - return QAbstractAnimation::event(event); -} - - -void QAnimationGroupPrivate::animationRemovedAt(int index) -{ - Q_Q(QAnimationGroup); - Q_UNUSED(index); - if (animations.isEmpty()) { - currentTime = 0; - q->stop(); - } -} - -QT_END_NAMESPACE - -#include "moc_qanimationgroup.cpp" - -#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qanimationgroup.h b/src/corelib/animation/qanimationgroup.h deleted file mode 100644 index 263bc38..0000000 --- a/src/corelib/animation/qanimationgroup.h +++ /dev/null @@ -1,88 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QANIMATIONGROUP_H -#define QANIMATIONGROUP_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -#ifndef QT_NO_ANIMATION - -class QAnimationGroupPrivate; -class Q_CORE_EXPORT QAnimationGroup : public QAbstractAnimation -{ - Q_OBJECT - -public: - QAnimationGroup(QObject *parent = 0); - ~QAnimationGroup(); - - QAbstractAnimation *animationAt(int index) const; - int animationCount() const; - int indexOfAnimation(QAbstractAnimation *animation) const; - void addAnimation(QAbstractAnimation *animation); - void insertAnimationAt(int index, QAbstractAnimation *animation); - void removeAnimation(QAbstractAnimation *animation); - QAbstractAnimation *takeAnimationAt(int index); - void clearAnimations(); - -protected: - QAnimationGroup(QAnimationGroupPrivate &dd, QObject *parent); - bool event(QEvent *event); - -private: - Q_DISABLE_COPY(QAnimationGroup) - Q_DECLARE_PRIVATE(QAnimationGroup) -}; - -#endif //QT_NO_ANIMATION - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif //QANIMATIONGROUP_H diff --git a/src/corelib/animation/qanimationgroup_p.h b/src/corelib/animation/qanimationgroup_p.h deleted file mode 100644 index a7bd0fa..0000000 --- a/src/corelib/animation/qanimationgroup_p.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QANIMATIONGROUP_P_H -#define QANIMATIONGROUP_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of QIODevice. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qanimationgroup.h" - -#include - -#include "qabstractanimation_p.h" - -QT_BEGIN_NAMESPACE - -class QAnimationGroupPrivate : public QAbstractAnimationPrivate -{ - Q_DECLARE_PUBLIC(QAnimationGroup) -public: - QAnimationGroupPrivate() - { } - - virtual void animationInsertedAt(int index) { Q_UNUSED(index) }; - virtual void animationRemovedAt(int index); - - QList animations; -}; - -QT_END_NAMESPACE - -#endif //QANIMATIONGROUP_P_H diff --git a/src/corelib/animation/qparallelanimationgroup.cpp b/src/corelib/animation/qparallelanimationgroup.cpp deleted file mode 100644 index 13f6073..0000000 --- a/src/corelib/animation/qparallelanimationgroup.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \class QParallelAnimationGroup - \brief The QParallelAnimationGroup class provides a parallel group of animations. - \since 4.6 - \ingroup animation - - QParallelAnimationGroup--a \l{QAnimationGroup}{container for - animations}--starts all its animations when it is - \l{QAbstractAnimation::start()}{started} itself, i.e., runs all - animations in parallel. The animation group finishes when the - longest lasting animation has finished. - - You can treat QParallelAnimation as any other QAbstractAnimation, - e.g., pause, resume, or add it to other animation groups. - - \code - QParallelAnimationGroup *group = new QParallelAnimationGroup; - group->addAnimation(anim1); - group->addAnimation(anim2); - - group->start(); - \endcode - - In this example, \c anim1 and \c anim2 are two - \l{QPropertyAnimation}s that have already been set up. - - \sa QAnimationGroup, QPropertyAnimation, {The Animation Framework} -*/ - -#ifndef QT_NO_ANIMATION - -#include "qparallelanimationgroup.h" -#include "qparallelanimationgroup_p.h" -//#define QANIMATION_DEBUG -QT_BEGIN_NAMESPACE - -/*! - Constructs a QParallelAnimationGroup. - \a parent is passed to QObject's constructor. -*/ -QParallelAnimationGroup::QParallelAnimationGroup(QObject *parent) - : QAnimationGroup(*new QParallelAnimationGroupPrivate, parent) -{ -} - -/*! - \internal -*/ -QParallelAnimationGroup::QParallelAnimationGroup(QParallelAnimationGroupPrivate &dd, - QObject *parent) - : QAnimationGroup(dd, parent) -{ -} - -/*! - Destroys the animation group. It will also destroy all its animations. -*/ -QParallelAnimationGroup::~QParallelAnimationGroup() -{ -} - -/*! - \reimp -*/ -int QParallelAnimationGroup::duration() const -{ - Q_D(const QParallelAnimationGroup); - int ret = 0; - - for (int i = 0; i < d->animations.size(); ++i) { - QAbstractAnimation *animation = d->animations.at(i); - const int currentDuration = animation->totalDuration(); - if (currentDuration == -1) - return -1; // Undetermined length - - ret = qMax(ret, currentDuration); - } - - return ret; -} - -/*! - \reimp -*/ -void QParallelAnimationGroup::updateCurrentTime(int) -{ - Q_D(QParallelAnimationGroup); - if (d->animations.isEmpty()) - return; - - if (d->currentLoop > d->lastLoop) { - // simulate completion of the loop - int dura = duration(); - if (dura > 0) { - foreach (QAbstractAnimation *animation, d->animations) { - animation->setCurrentTime(dura); // will stop - } - } - } else if (d->currentLoop < d->lastLoop) { - // simulate completion of the loop seeking backwards - foreach (QAbstractAnimation *animation, d->animations) { - animation->setCurrentTime(0); - animation->stop(); - } - } - - bool timeFwd = ((d->currentLoop == d->lastLoop && d->currentTime >= d->lastCurrentTime) - || d->currentLoop > d->lastLoop); -#ifdef QANIMATION_DEBUG - qDebug("QParallellAnimationGroup %5d: setCurrentTime(%d), loop:%d, last:%d, timeFwd:%d, lastcurrent:%d, %d", - __LINE__, d->currentTime, d->currentLoop, d->lastLoop, timeFwd, d->lastCurrentTime, state()); -#endif - // finally move into the actual time of the current loop - foreach (QAbstractAnimation *animation, d->animations) { - const int dura = animation->totalDuration(); - if (dura == -1 && d->isUncontrolledAnimationFinished(animation)) - continue; - if (dura == -1 || (d->currentTime <= dura && dura != 0) - || (dura == 0 && d->currentLoop != d->lastLoop)) { - switch (state()) { - case Running: - animation->start(); - break; - case Paused: - animation->pause(); - break; - case Stopped: - default: - break; - } - } - - if (dura <= 0) { - if (dura == -1) - animation->setCurrentTime(d->currentTime); - continue; - } - - if ((timeFwd && d->lastCurrentTime <= dura) - || (!timeFwd && d->currentTime <= dura)) - animation->setCurrentTime(d->currentTime); - if (d->currentTime > dura) - animation->stop(); - } - d->lastLoop = d->currentLoop; - d->lastCurrentTime = d->currentTime; -} - -/*! - \reimp -*/ -void QParallelAnimationGroup::updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) -{ - Q_D(QParallelAnimationGroup); - QAnimationGroup::updateState(oldState, newState); - - switch (newState) { - case Stopped: - foreach (QAbstractAnimation *animation, d->animations) - animation->stop(); - d->disconnectUncontrolledAnimations(); - break; - case Paused: - foreach (QAbstractAnimation *animation, d->animations) - animation->pause(); - break; - case Running: - d->connectUncontrolledAnimations(); - foreach (QAbstractAnimation *animation, d->animations) { - animation->stop(); - animation->setDirection(d->direction); - animation->start(); - } - break; - } -} - -void QParallelAnimationGroupPrivate::_q_uncontrolledAnimationFinished() -{ - Q_Q(QParallelAnimationGroup); - - QAbstractAnimation *animation = qobject_cast(q->sender()); - Q_ASSERT(animation); - - int uncontrolledRunningCount = 0; - if (animation->duration() == -1 || animation->loopCount() < 0) { - QHash::iterator it = uncontrolledFinishTime.begin(); - while (it != uncontrolledFinishTime.end()) { - if (it.key() == animation) { - *it = animation->currentTime(); - } - if (it.value() == -1) - ++uncontrolledRunningCount; - ++it; - } - } - - if (uncontrolledRunningCount > 0) - return; - - int maxDuration = 0; - foreach (QAbstractAnimation *a, animations) - maxDuration = qMax(maxDuration, a->totalDuration()); - - if (currentTime >= maxDuration) - q->stop(); -} - -void QParallelAnimationGroupPrivate::disconnectUncontrolledAnimations() -{ - Q_Q(QParallelAnimationGroup); - - QHash::iterator it = uncontrolledFinishTime.begin(); - while (it != uncontrolledFinishTime.end()) { - QObject::disconnect(it.key(), SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); - ++it; - } - - uncontrolledFinishTime.clear(); -} - -void QParallelAnimationGroupPrivate::connectUncontrolledAnimations() -{ - Q_Q(QParallelAnimationGroup); - - foreach (QAbstractAnimation *animation, animations) { - if (animation->duration() == -1 || animation->loopCount() < 0) { - uncontrolledFinishTime[animation] = -1; - QObject::connect(animation, SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); - } - } -} - -bool QParallelAnimationGroupPrivate::isUncontrolledAnimationFinished(QAbstractAnimation *anim) const -{ - return uncontrolledFinishTime.value(anim, -1) >= 0; -} - -/*! - \reimp -*/ -void QParallelAnimationGroup::updateDirection(QAbstractAnimation::Direction direction) -{ - Q_D(QParallelAnimationGroup); - //we need to update the direction of the current animation - if (state() != Stopped) { - foreach(QAbstractAnimation *anim, d->animations) { - anim->setDirection(direction); - } - } else { - if (direction == Forward) { - d->lastLoop = 0; - d->lastCurrentTime = 0; - } else { - // Looping backwards with loopCount == -1 does not really work well... - d->lastLoop = (d->loopCount == -1 ? 0 : d->loopCount - 1); - d->lastCurrentTime = duration(); - } - } -} - -/*! - \reimp -*/ -bool QParallelAnimationGroup::event(QEvent *event) -{ - return QAnimationGroup::event(event); -} - -QT_END_NAMESPACE - -#include "moc_qparallelanimationgroup.cpp" - -#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qparallelanimationgroup.h b/src/corelib/animation/qparallelanimationgroup.h deleted file mode 100644 index 57a8146..0000000 --- a/src/corelib/animation/qparallelanimationgroup.h +++ /dev/null @@ -1,86 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QPARALLELANIMATIONGROUP_H -#define QPARALLELANIMATIONGROUP_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -#ifndef QT_NO_ANIMATION - -class QParallelAnimationGroupPrivate; -class Q_CORE_EXPORT QParallelAnimationGroup : public QAnimationGroup -{ - Q_OBJECT - -public: - QParallelAnimationGroup(QObject *parent = 0); - ~QParallelAnimationGroup(); - - int duration() const; - -protected: - QParallelAnimationGroup(QParallelAnimationGroupPrivate &dd, QObject *parent); - bool event(QEvent *event); - - void updateCurrentTime(int msecs); - void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - void updateDirection(QAbstractAnimation::Direction direction); - -private: - Q_DISABLE_COPY(QParallelAnimationGroup) - Q_DECLARE_PRIVATE(QParallelAnimationGroup) - Q_PRIVATE_SLOT(d_func(), void _q_uncontrolledAnimationFinished()) -}; - -#endif //QT_NO_ANIMATION - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QPARALLELANIMATIONGROUP diff --git a/src/corelib/animation/qparallelanimationgroup_p.h b/src/corelib/animation/qparallelanimationgroup_p.h deleted file mode 100644 index f36d972..0000000 --- a/src/corelib/animation/qparallelanimationgroup_p.h +++ /dev/null @@ -1,85 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QPARALLELANIMATIONGROUP_P_H -#define QPARALLELANIMATIONGROUP_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of QIODevice. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qparallelanimationgroup.h" -#include "qanimationgroup_p.h" -#include - -QT_BEGIN_NAMESPACE - -class QParallelAnimationGroupPrivate : public QAnimationGroupPrivate -{ - Q_DECLARE_PUBLIC(QParallelAnimationGroup) -public: - QParallelAnimationGroupPrivate() - : lastLoop(0), lastCurrentTime(0) - { - } - - QHash uncontrolledFinishTime; - int lastLoop; - int lastCurrentTime; - - bool isUncontrolledAnimationFinished(QAbstractAnimation *anim) const; - void connectUncontrolledAnimations(); - void disconnectUncontrolledAnimations(); - - // private slot - void _q_uncontrolledAnimationFinished(); -}; - -QT_END_NAMESPACE - -#endif //QPARALLELANIMATIONGROUP_P_H diff --git a/src/corelib/animation/qpauseanimation.cpp b/src/corelib/animation/qpauseanimation.cpp deleted file mode 100644 index b175f0c..0000000 --- a/src/corelib/animation/qpauseanimation.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \class QPauseAnimation - \brief The QPauseAnimation class provides a pause for QSequentialAnimationGroup. - \since 4.6 - \ingroup animation - - If you wish to introduce a delay between animations in a - QSequentialAnimationGroup, you can insert a QPauseAnimation. This - class does not animate anything, but does not - \l{QAbstractAnimation::finished()}{finish} before a specified - number of milliseconds have elapsed from when it was started. You - specify the duration of the pause in the constructor. It can also - be set directly with setDuration(). - - It is not necessary to construct a QPauseAnimation yourself. - QSequentialAnimationGroup provides the convenience functions - \l{QSequentialAnimationGroup::}{addPause()} and - \l{QSequentialAnimationGroup::}{insertPauseAt()}. These functions - simply take the number of milliseconds the pause should last. - - \sa QSequentialAnimationGroup -*/ - -#ifndef QT_NO_ANIMATION - -#include "qpauseanimation.h" -#include "qabstractanimation_p.h" - - -QT_BEGIN_NAMESPACE - -class QPauseAnimationPrivate : public QAbstractAnimationPrivate -{ -public: - QPauseAnimationPrivate() : QAbstractAnimationPrivate(), duration(0) - { - } - - int duration; -}; - -/*! - Constructs a QPauseAnimation. - \a parent is passed to QObject's constructor. - The default duration is 0. -*/ - -QPauseAnimation::QPauseAnimation(QObject *parent) : QAbstractAnimation(*new QPauseAnimationPrivate, parent) -{ -} - -/*! - Constructs a QPauseAnimation. - \a msecs is the duration of the pause. - \a parent is passed to QObject's constructor. -*/ - -QPauseAnimation::QPauseAnimation(int msecs, QObject *parent) : QAbstractAnimation(*new QPauseAnimationPrivate, parent) -{ - setDuration(msecs); -} - -/*! - Destroys the pause animation. -*/ -QPauseAnimation::~QPauseAnimation() -{ -} - -/*! - \property QPauseAnimation::duration - \brief the duration of the pause. - - The duration of the pause. The duration should not be negative. -*/ -int QPauseAnimation::duration() const -{ - Q_D(const QPauseAnimation); - return d->duration; -} - -void QPauseAnimation::setDuration(int msecs) -{ - if (msecs < 0) { - qWarning("QPauseAnimation::setDuration: cannot set a negative duration"); - return; - } - Q_D(QPauseAnimation); - d->duration = msecs; -} - -/*! - \reimp - */ -bool QPauseAnimation::event(QEvent *e) -{ - return QAbstractAnimation::event(e); -} - -/*! - \reimp - */ -void QPauseAnimation::updateCurrentTime(int msecs) -{ - Q_UNUSED(msecs); -} - - -QT_END_NAMESPACE - -#include "moc_qpauseanimation.cpp" - -#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qpauseanimation.h b/src/corelib/animation/qpauseanimation.h deleted file mode 100644 index cb6e041..0000000 --- a/src/corelib/animation/qpauseanimation.h +++ /dev/null @@ -1,84 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QPAUSEANIMATION_P_H -#define QPAUSEANIMATION_P_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -#ifndef QT_NO_ANIMATION - -class QPauseAnimationPrivate; - -class Q_CORE_EXPORT QPauseAnimation : public QAbstractAnimation -{ - Q_OBJECT - Q_PROPERTY(int duration READ duration WRITE setDuration) -public: - QPauseAnimation(QObject *parent = 0); - QPauseAnimation(int msecs, QObject *parent = 0); - ~QPauseAnimation(); - - int duration() const; - void setDuration(int msecs); - -protected: - bool event(QEvent *e); - void updateCurrentTime(int msecs); - -private: - Q_DISABLE_COPY(QPauseAnimation) - Q_DECLARE_PRIVATE(QPauseAnimation) -}; - -#endif //QT_NO_ANIMATION - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QPAUSEANIMATION_P_H diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp deleted file mode 100644 index 9a17049..0000000 --- a/src/corelib/animation/qpropertyanimation.cpp +++ /dev/null @@ -1,316 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \class QPropertyAnimation - \brief The QPropertyAnimation class animates Qt properties - \since 4.6 - \ingroup animation - - QPropertyAnimation interpolates over \l{Qt's Property System}{Qt - properties}. As property values are stored in \l{QVariant}s, the - class inherits QVariantAnimation, and supports animation of the - same \l{QVariant::Type}{variant types} as its super class. - - A class declaring properties must be a QObject. To make it - possible to animate a property, it must provide a setter (so that - QPropertyAnimation can set the property's value). Note that this - makes it possible to animate many of Qt's widgets. Let's look at - an example: - - \code - QPropertyAnimation animation(myWidget, "geometry"); - animation.setDuration(10000); - animation.setStartValue(QRect(0, 0, 100, 30)); - animation.setEndValue(QRect(250, 250, 100, 30)); - - animation.start(); - \endcode - - The property name and the QObject instance of which property - should be animated are passed to the constructor. You can then - specify the start and end value of the property. The procedure is - equal for properties in classes you have implemented - yourself--just check with QVariantAnimation that your QVariant - type is supported. - - The QVariantAnimation class description explains how to set up the - animation in detail. Note, however, that if a start value is not - set, the property will start at the value it had when the - QPropertyAnimation instance was created. - - QPropertyAnimation works like a charm on its own. For complex - animations that, for instance, contain several objects, - QAnimationGroup is provided. An animation group is an animation - that can contain other animations, and that can manage when its - animations are played. Look at QParallelAnimationGroup for an - example. - - \sa QVariantAnimation, QAnimationGroup, {The Animation Framework} -*/ - -#ifndef QT_NO_ANIMATION - -#include "qpropertyanimation.h" -#include "qanimationgroup.h" -#include - -#include "qpropertyanimation_p.h" - -#include -#include - -QT_BEGIN_NAMESPACE - -typedef QPair QPropertyAnimationPair; -typedef QHash QPropertyAnimationHash; -Q_GLOBAL_STATIC(QPropertyAnimationHash, _q_runningAnimations); -Q_GLOBAL_STATIC_WITH_ARGS(QMutex, guardHashLock, (QMutex::Recursive) ) - -void QPropertyAnimationPrivate::updateMetaProperty() -{ - if (!target || propertyName.isEmpty()) - return; - - if (hasMetaProperty == 0 && !property.isValid()) { - const QMetaObject *mo = target->metaObject(); - propertyIndex = mo->indexOfProperty(propertyName); - if (propertyIndex != -1) { - hasMetaProperty = 1; - property = mo->property(propertyIndex); - propertyType = property.userType(); - } else { - if (!target->dynamicPropertyNames().contains(propertyName)) - qWarning("QPropertyAnimation: you're trying to animate a non-existing property %s of your QObject", propertyName.constData()); - hasMetaProperty = 2; - } - } - - if (property.isValid()) - convertValues(propertyType); -} - -void QPropertyAnimationPrivate::updateProperty(const QVariant &newValue) -{ - if (!target || state == QAbstractAnimation::Stopped) - return; - - if (hasMetaProperty == 1) { - if (newValue.userType() == propertyType) { - //no conversion is needed, we directly call the QObject::qt_metacall - void *data = const_cast(newValue.constData()); - target->qt_metacall(QMetaObject::WriteProperty, propertyIndex, &data); - } else { - property.write(target, newValue); - } - } else { - target->setProperty(propertyName.constData(), newValue); - } -} - -void QPropertyAnimationPrivate::_q_targetDestroyed() -{ - Q_Q(QPropertyAnimation); - //we stop here so that this animation is removed from the global hash - q->stop(); - target = 0; -} - -/*! - Construct a QPropertyAnimation object. \a parent is passed to QObject's - constructor. -*/ -QPropertyAnimation::QPropertyAnimation(QObject *parent) - : QVariantAnimation(*new QPropertyAnimationPrivate, parent) -{ -} - -/*! - Construct a QPropertyAnimation object. \a parent is passed to QObject's - constructor. The animation changes the property \a propertyName on \a - target. The default duration is 250ms. - - \sa targetObject, propertyName -*/ -QPropertyAnimation::QPropertyAnimation(QObject *target, const QByteArray &propertyName, QObject *parent) - : QVariantAnimation(*new QPropertyAnimationPrivate, parent) -{ - setTargetObject(target); - setPropertyName(propertyName); -} - -/*! - Destroys the QPropertyAnimation instance. - */ -QPropertyAnimation::~QPropertyAnimation() -{ - stop(); -} - -/*! - \property QPropertyAnimation::targetObject - \brief the target QObject for this animation. - - This property defines the target QObject for this animation. - */ -QObject *QPropertyAnimation::targetObject() const -{ - Q_D(const QPropertyAnimation); - return d->target; -} - -void QPropertyAnimation::setTargetObject(QObject *target) -{ - Q_D(QPropertyAnimation); - if (d->target == target) - return; - - if (d->state != QAbstractAnimation::Stopped) { - qWarning("QPropertyAnimation::setTargetObject: you can't change the target of a running animation"); - return; - } - - //we need to get notified when the target is destroyed - if (d->target) - disconnect(d->target, SIGNAL(destroyed()), this, SLOT(_q_targetDestroyed())); - - if (target) - connect(target, SIGNAL(destroyed()), SLOT(_q_targetDestroyed())); - - d->target = target; - d->hasMetaProperty = 0; - d->updateMetaProperty(); -} - -/*! - \property QPropertyAnimation::propertyName - \brief the target property name for this animation - - This property defines the target property name for this animation. The - property name is required for the animation to operate. - */ -QByteArray QPropertyAnimation::propertyName() const -{ - Q_D(const QPropertyAnimation); - return d->propertyName; -} - -void QPropertyAnimation::setPropertyName(const QByteArray &propertyName) -{ - Q_D(QPropertyAnimation); - if (d->state != QAbstractAnimation::Stopped) { - qWarning("QPropertyAnimation::setPropertyName: you can't change the property name of a running animation"); - return; - } - - d->propertyName = propertyName; - d->hasMetaProperty = 0; - d->updateMetaProperty(); -} - - -/*! - \reimp - */ -bool QPropertyAnimation::event(QEvent *event) -{ - return QVariantAnimation::event(event); -} - -/*! - This virtual function is called by QVariantAnimation whenever the current value - changes. \a value is the new, updated value. It updates the current value - of the property on the target object. - - \sa currentValue, currentTime - */ -void QPropertyAnimation::updateCurrentValue(const QVariant &value) -{ - Q_D(QPropertyAnimation); - d->updateProperty(value); -} - -/*! - \reimp - - If the startValue is not defined when the state of the animation changes from Stopped to Running, - the current property value is used as the initial value for the animation. -*/ -void QPropertyAnimation::updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) -{ - Q_D(QPropertyAnimation); - - if (!d->target) { - qWarning("QPropertyAnimation::updateState: Changing state of an animation without target"); - return; - } - - QVariantAnimation::updateState(oldState, newState); - QMutexLocker locker(guardHashLock()); - QPropertyAnimationHash * hash = _q_runningAnimations(); - QPropertyAnimationPair key(d->target, d->propertyName); - if (newState == Running) { - d->updateMetaProperty(); - QPropertyAnimation *oldAnim = hash->value(key, 0); - if (oldAnim) { - // try to stop the top level group - QAbstractAnimation *current = oldAnim; - while (current->group() && current->state() != Stopped) - current = current->group(); - current->stop(); - } - hash->insert(key, this); - - // update the default start value - if (oldState == Stopped) { - d->setDefaultStartValue(d->target->property(d->propertyName.constData())); - } - } else if (hash->value(key) == this) { - hash->remove(key); - } -} - -#include "moc_qpropertyanimation.cpp" - -QT_END_NAMESPACE - -#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qpropertyanimation.h b/src/corelib/animation/qpropertyanimation.h deleted file mode 100644 index 5b06bd2..0000000 --- a/src/corelib/animation/qpropertyanimation.h +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QPROPERTYANIMATION_H -#define QPROPERTYANIMATION_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -#ifndef QT_NO_ANIMATION - -class QPropertyAnimationPrivate; -class Q_CORE_EXPORT QPropertyAnimation : public QVariantAnimation -{ - Q_OBJECT - Q_PROPERTY(QByteArray propertyName READ propertyName WRITE setPropertyName) - Q_PROPERTY(QObject* targetObject READ targetObject WRITE setTargetObject) - -public: - QPropertyAnimation(QObject *parent = 0); - QPropertyAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0); - ~QPropertyAnimation(); - - QObject *targetObject() const; - void setTargetObject(QObject *target); - - QByteArray propertyName() const; - void setPropertyName(const QByteArray &propertyName); - -protected: - bool event(QEvent *event); - - void updateCurrentValue(const QVariant &value); - void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - Q_PRIVATE_SLOT(d_func(), void _q_targetDestroyed()); -private: - Q_DISABLE_COPY(QPropertyAnimation) - Q_DECLARE_PRIVATE(QPropertyAnimation) -}; - -#endif //QT_NO_ANIMATION - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif // QPROPERTYANIMATION_H diff --git a/src/corelib/animation/qpropertyanimation_p.h b/src/corelib/animation/qpropertyanimation_p.h deleted file mode 100644 index b51d039..0000000 --- a/src/corelib/animation/qpropertyanimation_p.h +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QPROPERTYANIMATION_P_H -#define QPROPERTYANIMATION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of QIODevice. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qpropertyanimation.h" -#include - -#include "qvariantanimation_p.h" - -QT_BEGIN_NAMESPACE - -class QPropertyAnimationPrivate : public QVariantAnimationPrivate -{ - Q_DECLARE_PUBLIC(QPropertyAnimation) -public: - QPropertyAnimationPrivate() - : target(0), propertyType(0), propertyIndex(0), hasMetaProperty(false) - { - } - - void _q_targetDestroyed(); - - QObject *target; - - //for the QProperty - QMetaProperty property; - int propertyType; - int propertyIndex; - - int hasMetaProperty; - QByteArray propertyName; - void updateProperty(const QVariant &); - void updateMetaProperty(); -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/animation/qsequentialanimationgroup.cpp b/src/corelib/animation/qsequentialanimationgroup.cpp deleted file mode 100644 index 14814a7..0000000 --- a/src/corelib/animation/qsequentialanimationgroup.cpp +++ /dev/null @@ -1,594 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/*! - \class QSequentialAnimationGroup - \brief The QSequentialAnimationGroup class provides a sequential group of animations. - \since 4.6 - \ingroup animation - - QSequentialAnimationGroup is a QAnimationGroup that runs its - animations in sequence, i.e., it starts one animation after - another has finished playing. The animations are played in the - order they are added to the group (using - \l{QAnimationGroup::}{addAnimation()} or - \l{QAnimationGroup::}{insertAnimationAt()}). The animation group - finishes when its last animation has finished. - - At each moment there is at most one animation that is active in - the group; it is returned by currentAnimation(). An empty group - has no current animation. - - A sequential animation group can be treated as any other - animation, i.e., it can be started, stopped, and added to other - groups. You can also call addPause() or insertPauseAt() to add a - pause to a sequential animation group. - - \code - QSequentialAnimationGroup group; - - group.addAnimation(anim1); - group.addAnimation(anim2); - - group.start(); - \endcode - - In this example, \c anim1 and \c anim2 are two already set up - \l{QPropertyAnimation}s. - - \sa QAnimationGroup, QAbstractAnimation, {The Animation Framework} -*/ - -#ifndef QT_NO_ANIMATION - -#include "qsequentialanimationgroup.h" -#include "qsequentialanimationgroup_p.h" - -#include "qpauseanimation.h" - -#include - -QT_BEGIN_NAMESPACE - - - -bool QSequentialAnimationGroupPrivate::atEnd() const -{ - // we try to detect if we're at the end of the group - //this is true if the following conditions are true: - // 1. we're in the last loop - // 2. the direction is forward - // 3. the current animation is the last one - // 4. the current animation has reached its end - const int animTotalCurrentTime = QAbstractAnimationPrivate::get(currentAnimation)->totalCurrentTime; - return (currentLoop == loopCount - 1 - && direction == QAbstractAnimation::Forward - && currentAnimation == animations.last() - && animTotalCurrentTime == animationActualTotalDuration(currentAnimationIndex)); -} - -int QSequentialAnimationGroupPrivate::animationActualTotalDuration(int index) const -{ - QAbstractAnimation *anim = animations.at(index); - int ret = anim->totalDuration(); - if (ret == -1 && actualDuration.size() > index) - ret = actualDuration.at(index); //we can try the actual duration there - return ret; -} - -QSequentialAnimationGroupPrivate::AnimationIndex QSequentialAnimationGroupPrivate::indexForTime(int msecs) const -{ - Q_Q(const QSequentialAnimationGroup); - Q_ASSERT(!animations.isEmpty()); - - AnimationIndex ret; - int duration = 0; - - // in case duration is -1, currentLoop will always be 0 - ret.timeOffset = currentLoop * q->duration(); - - for (int i = 0; i < animations.size(); ++i) { - duration = animationActualTotalDuration(i); - - // 'animation' is the current animation if one of these reasons is true: - // 1. it's duration is undefined - // 2. it ends after msecs - // 3. it is the last animation (this can happen in case there is at least 1 uncontrolled animation) - // 4. it ends exactly in msecs and the direction is backwards - if (duration == -1 || msecs < (ret.timeOffset + duration) - || (msecs == (ret.timeOffset + duration) && direction == QAbstractAnimation::Backward)) { - ret.index = i; - return ret; - } - - // 'animation' has a non-null defined duration and is not the one at time 'msecs'. - ret.timeOffset += duration; - } - - // this can only happen when one of those conditions is true: - // 1. the duration of the group is undefined and we passed its actual duration - // 2. there are only 0-duration animations in the group - ret.timeOffset -= duration; - ret.index = animations.size() - 1; - return ret; -} - -void QSequentialAnimationGroupPrivate::restart() -{ - // restarting the group by making the first/last animation the current one - if (direction == QAbstractAnimation::Forward) { - lastLoop = 0; - if (currentAnimationIndex == 0) - activateCurrentAnimation(); - else - setCurrentAnimation(0); - } else { // direction == QAbstractAnimation::Backward - lastLoop = loopCount - 1; - int index = animations.size() - 1; - if (currentAnimationIndex == index) - activateCurrentAnimation(); - else - setCurrentAnimation(index); - } -} - -/*! - \internal - This manages advancing the execution of a group running forwards (time has gone forward), - which is the same behaviour for rewinding the execution of a group running backwards - (time has gone backward). -*/ -void QSequentialAnimationGroupPrivate::advanceForwards(const AnimationIndex &newAnimationIndex) -{ - if (lastLoop < currentLoop) { - // we need to fast forward to the end - for (int i = currentAnimationIndex; i < animations.size(); ++i) { - QAbstractAnimation *anim = animations.at(i); - setCurrentAnimation(i, true); - anim->setCurrentTime(animationActualTotalDuration(i)); - } - // this will make sure the current animation is reset to the beginning - if (animations.size() == 1) - // we need to force activation because setCurrentAnimation will have no effect - activateCurrentAnimation(); - else - setCurrentAnimation(0, true); - } - - // and now we need to fast forward from the current position to - for (int i = currentAnimationIndex; i < newAnimationIndex.index; ++i) { //### WRONG, - QAbstractAnimation *anim = animations.at(i); - setCurrentAnimation(i, true); - anim->setCurrentTime(animationActualTotalDuration(i)); - } - // setting the new current animation will happen later -} - -/*! - \internal - This manages rewinding the execution of a group running forwards (time has gone forward), - which is the same behaviour for advancing the execution of a group running backwards - (time has gone backward). -*/ -void QSequentialAnimationGroupPrivate::rewindForwards(const AnimationIndex &newAnimationIndex) -{ - if (lastLoop > currentLoop) { - // we need to fast rewind to the beginning - for (int i = currentAnimationIndex; i >= 0 ; --i) { - QAbstractAnimation *anim = animations.at(i); - setCurrentAnimation(i, true); - anim->setCurrentTime(0); - } - // this will make sure the current animation is reset to the end - if (animations.size() == 1) - // we need to force activation because setCurrentAnimation will have no effect - activateCurrentAnimation(); - else - setCurrentAnimation(animations.count() - 1, true); - } - - // and now we need to fast rewind from the current position to - for (int i = currentAnimationIndex; i > newAnimationIndex.index; --i) { - QAbstractAnimation *anim = animations.at(i); - setCurrentAnimation(i, true); - anim->setCurrentTime(0); - } - // setting the new current animation will happen later -} - -/*! - \fn QSequentialAnimationGroup::currentAnimationChanged(QAbstractAnimation *current) - - QSequentialAnimationGroup emits this signal when currentAnimation - has been changed. \a current is the current animation. - - \sa currentAnimation() -*/ - - -/*! - Constructs a QSequentialAnimationGroup. - \a parent is passed to QObject's constructor. -*/ -QSequentialAnimationGroup::QSequentialAnimationGroup(QObject *parent) - : QAnimationGroup(*new QSequentialAnimationGroupPrivate, parent) -{ -} - -/*! - \internal -*/ -QSequentialAnimationGroup::QSequentialAnimationGroup(QSequentialAnimationGroupPrivate &dd, - QObject *parent) - : QAnimationGroup(dd, parent) -{ -} - -/*! - Destroys the animation group. It will also destroy all its animations. -*/ -QSequentialAnimationGroup::~QSequentialAnimationGroup() -{ -} - -/*! - Adds a pause of \a msecs to this animation group. - The pause is considered as a special type of animation, thus count() will be - increased by one. - \sa insertPauseAt(), QAnimationGroup::addAnimation() -*/ -QPauseAnimation *QSequentialAnimationGroup::addPause(int msecs) -{ - QPauseAnimation *pause = new QPauseAnimation(msecs); - addAnimation(pause); - return pause; -} - -/*! - Inserts a pause of \a msecs milliseconds at \a index in this animation - group. - - \sa addPause(), QAnimationGroup::insertAnimationAt() -*/ -QPauseAnimation *QSequentialAnimationGroup::insertPauseAt(int index, int msecs) -{ - Q_D(const QSequentialAnimationGroup); - - if (index < 0 || index > d->animations.size()) { - qWarning("QSequentialAnimationGroup::insertPauseAt: index is out of bounds"); - return 0; - } - - QPauseAnimation *pause = new QPauseAnimation(msecs); - insertAnimationAt(index, pause); - return pause; -} - - -/*! - \property QSequentialAnimationGroup::currentAnimation - Returns the animation in the current time. - - \sa currentAnimationChanged() -*/ -QAbstractAnimation *QSequentialAnimationGroup::currentAnimation() const -{ - Q_D(const QSequentialAnimationGroup); - return d->currentAnimation; -} - -/*! - \reimp -*/ -int QSequentialAnimationGroup::duration() const -{ - Q_D(const QSequentialAnimationGroup); - int ret = 0; - - for (int i = 0; i < d->animations.size(); ++i) { - QAbstractAnimation *animation = d->animations.at(i); - const int currentDuration = animation->totalDuration(); - if (currentDuration == -1) - return -1; // Undetermined length - - ret += currentDuration; - } - - return ret; -} - -/*! - \reimp -*/ -void QSequentialAnimationGroup::updateCurrentTime(int msecs) -{ - Q_D(QSequentialAnimationGroup); - if (!d->currentAnimation) - return; - - const QSequentialAnimationGroupPrivate::AnimationIndex newAnimationIndex = d->indexForTime(msecs); - - // remove unneeded animations from actualDuration list - while (newAnimationIndex.index < d->actualDuration.size()) - d->actualDuration.removeLast(); - - // newAnimationIndex.index is the new current animation - if (d->lastLoop < d->currentLoop - || (d->lastLoop == d->currentLoop && d->currentAnimationIndex < newAnimationIndex.index)) { - // advancing with forward direction is the same as rewinding with backwards direction - d->advanceForwards(newAnimationIndex); - } else if (d->lastLoop > d->currentLoop - || (d->lastLoop == d->currentLoop && d->currentAnimationIndex > newAnimationIndex.index)) { - // rewinding with forward direction is the same as advancing with backwards direction - d->rewindForwards(newAnimationIndex); - } - - d->setCurrentAnimation(newAnimationIndex.index); - - const int newCurrentTime = msecs - newAnimationIndex.timeOffset; - - if (d->currentAnimation) { - d->currentAnimation->setCurrentTime(newCurrentTime); - if (d->atEnd()) { - //we make sure that we don't exceed the duration here - d->currentTime += QAbstractAnimationPrivate::get(d->currentAnimation)->totalCurrentTime - newCurrentTime; - stop(); - } - } else { - //the only case where currentAnimation could be null - //is when all animations have been removed - Q_ASSERT(d->animations.isEmpty()); - d->currentTime = 0; - stop(); - } - - d->lastLoop = d->currentLoop; -} - -/*! - \reimp -*/ -void QSequentialAnimationGroup::updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) -{ - Q_D(QSequentialAnimationGroup); - QAnimationGroup::updateState(oldState, newState); - - if (!d->currentAnimation) - return; - - switch (newState) { - case Stopped: - d->currentAnimation->stop(); - break; - case Paused: - if (oldState == d->currentAnimation->state() - && oldState == QSequentialAnimationGroup::Running) { - d->currentAnimation->pause(); - } - else - d->restart(); - break; - case Running: - if (oldState == d->currentAnimation->state() - && oldState == QSequentialAnimationGroup::Paused) - d->currentAnimation->start(); - else - d->restart(); - break; - } -} - -/*! - \reimp -*/ -void QSequentialAnimationGroup::updateDirection(QAbstractAnimation::Direction direction) -{ - Q_D(QSequentialAnimationGroup); - // we need to update the direction of the current animation - if (state() != Stopped && d->currentAnimation) - d->currentAnimation->setDirection(direction); -} - -/*! - \reimp -*/ -bool QSequentialAnimationGroup::event(QEvent *event) -{ - return QAnimationGroup::event(event); -} - -void QSequentialAnimationGroupPrivate::setCurrentAnimation(int index, bool intermediate) -{ - Q_Q(QSequentialAnimationGroup); - - index = qMin(index, animations.count() - 1); - - if (index == -1) { - Q_ASSERT(animations.isEmpty()); - currentAnimationIndex = -1; - currentAnimation = 0; - return; - } - - // need these two checks below because this func can be called after the current animation - // has been removed - if (index == currentAnimationIndex && animations.at(index) == currentAnimation) - return; - - // stop the old current animation - if (currentAnimation) - currentAnimation->stop(); - - currentAnimation = animations.at(index); - currentAnimationIndex = index; - - emit q->currentAnimationChanged(currentAnimation); - - activateCurrentAnimation(intermediate); -} - -void QSequentialAnimationGroupPrivate::activateCurrentAnimation(bool intermediate) -{ - Q_Q(QSequentialAnimationGroup); - - if (!currentAnimation) - return; - - if (state == QSequentialAnimationGroup::Stopped) - return; - - currentAnimation->stop(); - - // we ensure the direction is consistent with the group's direction - currentAnimation->setDirection(direction); - - // connects to the finish signal of uncontrolled animations - if (currentAnimation->totalDuration() == -1) - QObject::connect(currentAnimation, SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); - - currentAnimation->start(); - if (!intermediate && state == QSequentialAnimationGroup::Paused) - currentAnimation->pause(); -} - -void QSequentialAnimationGroupPrivate::_q_uncontrolledAnimationFinished() -{ - Q_Q(QSequentialAnimationGroup); - Q_ASSERT(qobject_cast(q->sender()) == currentAnimation); - - // we trust the duration returned by the animation - while (actualDuration.size() < (currentAnimationIndex + 1)) - actualDuration.append(-1); - actualDuration[currentAnimationIndex] = currentAnimation->currentTime(); - - QObject::disconnect(currentAnimation, SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); - - if ((direction == QAbstractAnimation::Forward && currentAnimation == animations.last()) - || (direction == QAbstractAnimation::Backward && currentAnimationIndex == 0)) { - // we don't handle looping of a group with undefined duration - q->stop(); - } else if (direction == QAbstractAnimation::Forward) { - // set the current animation to be the next one - setCurrentAnimation(currentAnimationIndex + 1); - } else { - // set the current animation to be the previous one - setCurrentAnimation(currentAnimationIndex - 1); - } -} - -/*! - \internal - This method is called whenever an animation is added to - the group at index \a index. - Note: We only support insertion after the current animation -*/ -void QSequentialAnimationGroupPrivate::animationInsertedAt(int index) -{ - if (currentAnimation == 0) - setCurrentAnimation(0); // initialize the current animation - - if (currentAnimationIndex == index - && currentAnimation->currentTime() == 0 && currentAnimation->currentLoop() == 0) { - //in this case we simply insert an animation before the current one has actually started - setCurrentAnimation(index); - } - - //we update currentAnimationIndex in case it has changed (the animation pointer is still valid) - currentAnimationIndex = animations.indexOf(currentAnimation); - - if (index < currentAnimationIndex || currentLoop != 0) { - qWarning("QSequentialGroup::insertAnimationAt only supports to add animations after the current one."); - return; //we're not affected because it is added after the current one - } -} - -/*! - \internal - This method is called whenever an animation is removed from - the group at index \a index. The animation is no more listed when this - method is called. -*/ -void QSequentialAnimationGroupPrivate::animationRemovedAt(int index) -{ - Q_Q(QSequentialAnimationGroup); - QAnimationGroupPrivate::animationRemovedAt(index); - - Q_ASSERT(currentAnimation); // currentAnimation should always be set - - if (actualDuration.size() > index) - actualDuration.removeAt(index); - - const int currentIndex = animations.indexOf(currentAnimation); - if (currentIndex == -1) { - //we're removing the current animation, let's update it to another one - if (index < animations.count()) - setCurrentAnimation(index); //let's try to take the next one - else if (index > 0) - setCurrentAnimation(index - 1); - else// case all animations were removed - setCurrentAnimation(-1); - } else if (currentAnimationIndex > index) { - currentAnimationIndex--; - } - - // duration of the previous animations up to the current animation - currentTime = 0; - for (int i = 0; i < currentAnimationIndex; ++i) { - const int current = animationActualTotalDuration(i); - currentTime += current; - } - - if (currentIndex != -1) { - //the current animation is not the one being removed - //so we add its current time to the current time of this group - currentTime += QAbstractAnimationPrivate::get(currentAnimation)->totalCurrentTime; - } - - //let's also update the total current time - totalCurrentTime = currentTime + loopCount * q->duration(); -} - -QT_END_NAMESPACE - -#include "moc_qsequentialanimationgroup.cpp" - -#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qsequentialanimationgroup.h b/src/corelib/animation/qsequentialanimationgroup.h deleted file mode 100644 index 4701a76..0000000 --- a/src/corelib/animation/qsequentialanimationgroup.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSEQUENTIALANIMATIONGROUP_H -#define QSEQUENTIALANIMATIONGROUP_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -#ifndef QT_NO_ANIMATION - -class QPauseAnimation; -class QSequentialAnimationGroupPrivate; - -class Q_CORE_EXPORT QSequentialAnimationGroup : public QAnimationGroup -{ - Q_OBJECT - Q_PROPERTY(QAbstractAnimation* currentAnimation READ currentAnimation NOTIFY currentAnimationChanged) - -public: - QSequentialAnimationGroup(QObject *parent = 0); - ~QSequentialAnimationGroup(); - - QPauseAnimation *addPause(int msecs); - QPauseAnimation *insertPauseAt(int index, int msecs); - - QAbstractAnimation *currentAnimation() const; - int duration() const; - -Q_SIGNALS: - void currentAnimationChanged(QAbstractAnimation *current); - -protected: - QSequentialAnimationGroup(QSequentialAnimationGroupPrivate &dd, QObject *parent); - bool event(QEvent *event); - - void updateCurrentTime(int msecs); - void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - void updateDirection(QAbstractAnimation::Direction direction); - -private: - Q_DISABLE_COPY(QSequentialAnimationGroup) - Q_DECLARE_PRIVATE(QSequentialAnimationGroup) - Q_PRIVATE_SLOT(d_func(), void _q_uncontrolledAnimationFinished()) -}; - -#endif //QT_NO_ANIMATION - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif //QSEQUENTIALANIMATIONGROUP_H diff --git a/src/corelib/animation/qsequentialanimationgroup_p.h b/src/corelib/animation/qsequentialanimationgroup_p.h deleted file mode 100644 index 3ac90f8..0000000 --- a/src/corelib/animation/qsequentialanimationgroup_p.h +++ /dev/null @@ -1,111 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSEQUENTIALANIMATIONGROUP_P_H -#define QSEQUENTIALANIMATIONGROUP_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of QIODevice. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qsequentialanimationgroup.h" -#include "qanimationgroup_p.h" - - -QT_BEGIN_NAMESPACE - -class QSequentialAnimationGroupPrivate : public QAnimationGroupPrivate -{ - Q_DECLARE_PUBLIC(QSequentialAnimationGroup) -public: - QSequentialAnimationGroupPrivate() - : currentAnimation(0), currentAnimationIndex(-1), lastLoop(0) - { } - - - struct AnimationIndex - { - AnimationIndex() : index(0), timeOffset(0) {} - // index points to the animation at timeOffset, skipping 0 duration animations. - // Note that the index semantic is slightly different depending on the direction. - int index; // the index of the animation in timeOffset - int timeOffset; // time offset when the animation at index starts. - }; - - int animationActualTotalDuration(int index) const; - AnimationIndex indexForTime(int msecs) const; - - void setCurrentAnimation(int index, bool intermediate = false); - void activateCurrentAnimation(bool intermediate = false); - - void animationInsertedAt(int index); - void animationRemovedAt(int index); - - bool atEnd() const; - - QAbstractAnimation *currentAnimation; - int currentAnimationIndex; - - // this is the actual duration of uncontrolled animations - // it helps seeking and even going forward - QList actualDuration; - - void restart(); - int lastLoop; - - // handle time changes - void rewindForwards(const AnimationIndex &newAnimationIndex); - void advanceForwards(const AnimationIndex &newAnimationIndex); - - // private slot - void _q_uncontrolledAnimationFinished(); -}; - -QT_END_NAMESPACE - -#endif //QSEQUENTIALANIMATIONGROUP_P_H diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp deleted file mode 100644 index a6834bb..0000000 --- a/src/corelib/animation/qvariantanimation.cpp +++ /dev/null @@ -1,644 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT_NO_ANIMATION - -#include "qvariantanimation.h" -#include "qvariantanimation_p.h" - -#include -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -/*! - \class QVariantAnimation - \ingroup animation - \brief The QVariantAnimation class provides an abstract base class for animations. - \since 4.6 - - This class is part of \l{The Animation Framework}. It serves as a - base class for property and item animations, with functions for - shared functionality. - - QVariantAnimation cannot be used directly as it is an abstract - class; it does not implement - \l{QAbstractAnimation::}{updateCurrentValue()} from - QAbstractAnimation. The class performs interpolation over - \l{QVariant}s, but leaves using the interpolated values to its - subclasses. Currently, Qt provides QPropertyAnimation, which - animates Qt \l{Qt's Property System}{properties}. See the - QPropertyAnimation class description if you wish to animate such - properties. - - You can then set start and end values for the property by calling - setStartValue() and setEndValue(), and finally call start() to - start the animation. QVariantAnimation will interpolate the - property of the target object and emit valueChanged(). To react to - a change in the current value you have to reimplement the - updateCurrentValue() virtual function. - - It is also possible to set values at specified steps situated - between the start and end value. The interpolation will then - touch these points at the specified steps. Note that the start and - end values are defined as the key values at 0.0 and 1.0. - - There are two ways to affect how QVariantAnimation interpolates - the values. You can set an easing curve by calling - setEasingCurve(), and configure the duration by calling - setDuration(). You can change how the QVariants are interpolated - by creating a subclass of QVariantAnimation, and reimplementing - the virtual interpolated() function. - - Subclassing QVariantAnimation can be an alternative if you have - \l{QVariant}s that you do not wish to declare as Qt properties. - Note, however, that you in most cases will be better off declaring - your QVariant as a property. - - Not all QVariant types are supported. Below is a list of currently - supported QVariant types: - - \list - \o \l{QMetaType::}{Int} - \o \l{QMetaType::}{Double} - \o \l{QMetaType::}{Float} - \o \l{QMetaType::}{QLine} - \o \l{QMetaType::}{QLineF} - \o \l{QMetaType::}{QPoint} - \o \l{QMetaType::}{QSize} - \o \l{QMetaType::}{QSizeF} - \o \l{QMetaType::}{QRect} - \o \l{QMetaType::}{QRectF} - \endlist - - If you need to interpolate other variant types, including custom - types, you have to implement interpolation for these yourself. - You do this by reimplementing interpolated(), which returns - interpolation values for the value being interpolated. - - \omit We need some snippets around here. \endomit - - \sa QPropertyAnimation, QAbstractAnimation, {The Animation Framework} -*/ - -/*! - \fn void QVariantAnimation::valueChanged(const QVariant &value) - - QVariantAnimation emits this signal whenever the current \a value changes. - - \sa currentValue, startValue, endValue -*/ - -static bool animationValueLessThan(const QVariantAnimation::KeyValue &p1, const QVariantAnimation::KeyValue &p2) -{ - return p1.first < p2.first; -} - -template<> Q_INLINE_TEMPLATE QRect _q_interpolate(const QRect &f, const QRect &t, qreal progress) -{ - QRect ret; - ret.setCoords(_q_interpolate(f.left(), t.left(), progress), - _q_interpolate(f.top(), t.top(), progress), - _q_interpolate(f.right(), t.right(), progress), - _q_interpolate(f.bottom(), t.bottom(), progress)); - return ret; -} - -template<> Q_INLINE_TEMPLATE QRectF _q_interpolate(const QRectF &f, const QRectF &t, qreal progress) -{ - qreal x1, y1, w1, h1; - f.getRect(&x1, &y1, &w1, &h1); - qreal x2, y2, w2, h2; - t.getRect(&x2, &y2, &w2, &h2); - return QRectF(_q_interpolate(x1, x2, progress), _q_interpolate(y1, y2, progress), - _q_interpolate(w1, w2, progress), _q_interpolate(h1, h2, progress)); -} - -template<> Q_INLINE_TEMPLATE QLine _q_interpolate(const QLine &f, const QLine &t, qreal progress) -{ - return QLine( _q_interpolate(f.p1(), t.p1(), progress), _q_interpolate(f.p2(), t.p2(), progress)); -} - -template<> Q_INLINE_TEMPLATE QLineF _q_interpolate(const QLineF &f, const QLineF &t, qreal progress) -{ - return QLineF( _q_interpolate(f.p1(), t.p1(), progress), _q_interpolate(f.p2(), t.p2(), progress)); -} - -void QVariantAnimationPrivate::convertValues(int t) -{ - //this ensures that all the keyValues are of type t - for (int i = 0; i < keyValues.count(); ++i) { - QVariantAnimation::KeyValue &pair = keyValues[i]; - if (pair.second.userType() != t) - pair.second.convert(static_cast(t)); - } - interpolator = 0; // if the type changed we need to update the interpolator -} - -/*! - \internal - The goal of this function is to update the currentInterval member. As a consequence, we also - need to update the currentValue. - Set \a force to true to always recalculate the interval. -*/ -void QVariantAnimationPrivate::recalculateCurrentInterval(bool force/*=false*/) -{ - // can't interpolate if we have only 1 key value - if (keyValues.count() <= 1) - return; - - const qreal progress = easing.valueForProgress(((duration == 0) ? qreal(1) : qreal(currentTime) / qreal(duration))); - - if (force || progress < currentInterval.start.first || progress > currentInterval.end.first) { - //let's update currentInterval - QVariantAnimation::KeyValues::const_iterator itStart = qLowerBound(keyValues.constBegin(), - keyValues.constEnd(), - qMakePair(progress, QVariant()), - animationValueLessThan); - QVariantAnimation::KeyValues::const_iterator itEnd = itStart; - - // If we are at the end we should continue to use the last keyValues in case of extrapolation (progress > 1.0). - // This is because the easing function can return a value slightly outside the range [0, 1] - if (itStart != keyValues.constEnd()) { - // this can't happen because we always prepend the default start value there - if (itStart == keyValues.constBegin()) { - ++itEnd; - } else { - --itStart; - } - - // update all the values of the currentInterval - currentInterval.start = *itStart; - currentInterval.end = *itEnd; - } - } - setCurrentValueForProgress(progress); -} - -void QVariantAnimationPrivate::setCurrentValueForProgress(const qreal progress) -{ - Q_Q(QVariantAnimation); - - const qreal startProgress = currentInterval.start.first; - const qreal endProgress = currentInterval.end.first; - const qreal localProgress = (progress - startProgress) / (endProgress - startProgress); - - QVariant ret = q->interpolated(currentInterval.start.second, - currentInterval.end.second, - localProgress); - qSwap(currentValue, ret); - q->updateCurrentValue(currentValue); - if ((connectedSignals & changedSignalMask) && currentValue != ret) { - //the value has changed - emit q->valueChanged(currentValue); - } -} - -QVariant QVariantAnimationPrivate::valueAt(qreal step) const -{ - QVariantAnimation::KeyValues::const_iterator result = - qBinaryFind(keyValues.begin(), keyValues.end(), qMakePair(step, QVariant()), animationValueLessThan); - if (result != keyValues.constEnd()) - return result->second; - - return QVariant(); -} - -void QVariantAnimationPrivate::setValueAt(qreal step, const QVariant &value) -{ - if (step < qreal(0.0) || step > qreal(1.0)) { - qWarning("QVariantAnimation::setValueAt: invalid step = %f", step); - return; - } - - QVariantAnimation::KeyValue pair(step, value); - - QVariantAnimation::KeyValues::iterator result = qLowerBound(keyValues.begin(), keyValues.end(), pair, animationValueLessThan); - if (result == keyValues.end() || result->first != step) { - keyValues.insert(result, pair); - } else { - if (value.isValid()) - result->second = value; // replaces the previous value - else if (step == 0 && !hasStartValue && defaultStartValue.isValid()) - result->second = defaultStartValue; // resets to the default start value - else - keyValues.erase(result); // removes the previous value - } - - recalculateCurrentInterval(/*force=*/true); -} - -void QVariantAnimationPrivate::setDefaultStartValue(const QVariant &value) -{ - defaultStartValue = value; - if (!hasStartValue) - setValueAt(0, value); -} - -/*! - Construct a QVariantAnimation object. \a parent is passed to QAbstractAnimation's - constructor. -*/ -QVariantAnimation::QVariantAnimation(QObject *parent) : QAbstractAnimation(*new QVariantAnimationPrivate, parent) -{ - d_func()->init(); -} - -/*! - \internal -*/ -QVariantAnimation::QVariantAnimation(QVariantAnimationPrivate &dd, QObject *parent) : QAbstractAnimation(dd, parent) -{ - d_func()->init(); -} - -/*! - Destroys the animation. -*/ -QVariantAnimation::~QVariantAnimation() -{ -} - -/*! - \property QVariantAnimation::easingCurve - \brief the easing curve of the animation - - This property defines the easing curve of the animation. By - default, a linear easing curve is used, resulting in linear - interpolation. Other curves are provided, for instance, - QEasingCurve::InCirc, which provides a circular entry curve. - Another example is QEasingCurve::InOutElastic, which provides an - elastic effect on the values of the interpolated variant. - - The easing curve is used with the interpolator, the interpolated() - virtual function, the animation's duration, and iterationCount, to - control how the current value changes as the animation progresses. -*/ -QEasingCurve QVariantAnimation::easingCurve() const -{ - Q_D(const QVariantAnimation); - return d->easing; -} - -void QVariantAnimation::setEasingCurve(const QEasingCurve &easing) -{ - Q_D(QVariantAnimation); - d->easing = easing; - d->recalculateCurrentInterval(); -} - -Q_GLOBAL_STATIC(QVector, registeredInterpolators) -Q_GLOBAL_STATIC(QReadWriteLock, registeredInterpolatorsLock) - -/*! - \fn void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) - \relates QVariantAnimation - \threadsafe - - Registers a custom interpolator \a func for the template type \c{T}. - The interpolator has to be registered before the animation is constructed. - To unregister (and use the default interpolator) set \a func to 0. - */ - -/*! - \internal - \typedef QVariantAnimation::Interpolator - - This is a typedef for a pointer to a function with the following - signature: - \code - QVariant myInterpolator(const QVariant &from, const QVariant &to, qreal progress); - \endcode - -*/ - -/*! \internal - * Registers a custom interpolator \a func for the specific \a interpolationType. - * The interpolator has to be registered before the animation is constructed. - * To unregister (and use the default interpolator) set \a func to 0. - */ -void QVariantAnimation::registerInterpolator(QVariantAnimation::Interpolator func, int interpolationType) -{ - // will override any existing interpolators - QWriteLocker locker(registeredInterpolatorsLock()); - if (int(interpolationType) >= registeredInterpolators()->count()) - registeredInterpolators()->resize(int(interpolationType) + 1); - registeredInterpolators()->replace(interpolationType, func); -} - - -template static inline QVariantAnimation::Interpolator castToInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) -{ - return reinterpret_cast(func); -} - -QVariantAnimation::Interpolator QVariantAnimationPrivate::getInterpolator(int interpolationType) -{ - QReadLocker locker(registeredInterpolatorsLock()); - QVariantAnimation::Interpolator ret = 0; - if (interpolationType < registeredInterpolators()->count()) { - ret = registeredInterpolators()->at(interpolationType); - if (ret) return ret; - } - - switch(interpolationType) - { - case QMetaType::Int: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::Double: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::Float: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::QLine: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::QLineF: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::QPoint: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::QPointF: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::QSize: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::QSizeF: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::QRect: - return castToInterpolator(_q_interpolateVariant); - case QMetaType::QRectF: - return castToInterpolator(_q_interpolateVariant); - default: - return 0; //this type is not handled - } -} - -/*! - \property QVariantAnimation::duration - \brief the duration of the animation - - This property describes the duration in milliseconds of the - animation. The default duration is 250 milliseconds. - - \sa QAbstractAnimation::duration() - */ -int QVariantAnimation::duration() const -{ - Q_D(const QVariantAnimation); - return d->duration; -} - -void QVariantAnimation::setDuration(int msecs) -{ - Q_D(QVariantAnimation); - if (msecs < 0) { - qWarning("QVariantAnimation::setDuration: cannot set a negative duration"); - return; - } - if (d->duration == msecs) - return; - d->duration = msecs; - d->recalculateCurrentInterval(); -} - -/*! - \property QVariantAnimation::startValue - \brief the optional start value of the animation - - This property describes the optional start value of the animation. If - omitted, or if a null QVariant is assigned as the start value, the - animation will use the current position of the end when the animation - is started. - - \sa endValue -*/ -QVariant QVariantAnimation::startValue() const -{ - return keyValueAt(0); -} - -void QVariantAnimation::setStartValue(const QVariant &value) -{ - setKeyValueAt(0, value); -} - -/*! - \property QVariantAnimation::endValue - \brief the end value of the animation - - This property describes the end value of the animation. - - \sa startValue - */ -QVariant QVariantAnimation::endValue() const -{ - return keyValueAt(1); -} - -void QVariantAnimation::setEndValue(const QVariant &value) -{ - setKeyValueAt(1, value); -} - - -/*! - Returns the key frame value for the given \a step. The given \a step - must be in the range 0 to 1. If there is no KeyValue for \a step, - it returns an invalid QVariant. - - \sa keyValues(), setKeyValueAt() -*/ -QVariant QVariantAnimation::keyValueAt(qreal step) const -{ - Q_D(const QVariantAnimation); - if (step == 0 && !d->hasStartValue) - return QVariant(); //special case where we don't have an explicit startValue - - return d->valueAt(step); -} - -/*! - \typedef QVariantAnimation::KeyValue - - This is a typedef for QPair. -*/ -/*! - \typedef QVariantAnimation::KeyValues - - This is a typedef for QVector -*/ - -/*! - Creates a key frame at the given \a step with the given \a value. - The given \a step must be in the range 0 to 1. - - \sa setKeyValues(), keyValueAt() -*/ -void QVariantAnimation::setKeyValueAt(qreal step, const QVariant &value) -{ - Q_D(QVariantAnimation); - if (step == 0) - d->hasStartValue = value.isValid(); - d->setValueAt(step, value); -} - -/*! - Returns the key frames of this animation. - - \sa keyValueAt(), setKeyValues() -*/ -QVariantAnimation::KeyValues QVariantAnimation::keyValues() const -{ - Q_D(const QVariantAnimation); - QVariantAnimation::KeyValues ret = d->keyValues; - //in case we added the default start value, we remove it - if (!d->hasStartValue && !ret.isEmpty() && ret.at(0).first == 0) - ret.remove(0); - return ret; -} - -/*! - Replaces the current set of key frames with the given \a keyValues. - the step of the key frames must be in the range 0 to 1. - - \sa keyValues(), keyValueAt() -*/ -void QVariantAnimation::setKeyValues(const KeyValues &keyValues) -{ - Q_D(QVariantAnimation); - d->keyValues = keyValues; - qSort(d->keyValues.begin(), d->keyValues.end(), animationValueLessThan); - d->hasStartValue = !d->keyValues.isEmpty() && d->keyValues.at(0).first == 0; - d->recalculateCurrentInterval(/*force=*/true); -} - -/*! - \property QVariantAnimation::currentValue - \brief the current value of the animation. - - This property describes the current value; an interpolated value - between the \l{startValue}{start value} and the \l{endValue}{end - value}, using the current time for progress. The value itself is - obtained from interpolated(), which is called repeatedly as the - animation is running. - - QVariantAnimation calls the virtual updateCurrentValue() function - when the current value changes. This is particularly useful for - subclasses that need to track updates. For example, - QPropertyAnimation uses this function to animate Qt \l{Qt's - Property System}{properties}. - - \sa startValue, endValue -*/ -QVariant QVariantAnimation::currentValue() const -{ - Q_D(const QVariantAnimation); - if (!d->currentValue.isValid()) - const_cast(d)->recalculateCurrentInterval(); - return d->currentValue; -} - -/*! - \reimp - */ -bool QVariantAnimation::event(QEvent *event) -{ - return QAbstractAnimation::event(event); -} - -/*! - \reimp -*/ -void QVariantAnimation::updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) -{ - Q_UNUSED(oldState); - Q_UNUSED(newState); -} - -/*! - - This virtual function returns the linear interpolation between - variants \a from and \a to, at \a progress, usually a value - between 0 and 1. You can reimplement this function in a subclass - of QVariantAnimation to provide your own interpolation algorithm. - - Note that in order for the interpolation to work with a - QEasingCurve that return a value smaller than 0 or larger than 1 - (such as QEasingCurve::InBack) you should make sure that it can - extrapolate. If the semantic of the datatype does not allow - extrapolation this function should handle that gracefully. - - You should call the QVariantAnimation implementation of this - function if you want your class to handle the types already - supported by Qt (see class QVariantAnimation description for a - list of supported types). - - \sa QEasingCurve - */ -QVariant QVariantAnimation::interpolated(const QVariant &from, const QVariant &to, qreal progress) const -{ - Q_D(const QVariantAnimation); - if (d->interpolator == 0) { - if (from.userType() == to.userType()) - d->interpolator = QVariantAnimationPrivate::getInterpolator(from.userType()); - if (d->interpolator == 0) //no interpolator found - return QVariant(); - } - - return d->interpolator(from.constData(), to.constData(), progress); -} - -/*! - \reimp - */ -void QVariantAnimation::updateCurrentTime(int msecs) -{ - Q_D(QVariantAnimation); - Q_UNUSED(msecs); - d->recalculateCurrentInterval(); -} - -QT_END_NAMESPACE - -#include "moc_qvariantanimation.cpp" - -#endif //QT_NO_ANIMATION diff --git a/src/corelib/animation/qvariantanimation.h b/src/corelib/animation/qvariantanimation.h deleted file mode 100644 index 5b90930..0000000 --- a/src/corelib/animation/qvariantanimation.h +++ /dev/null @@ -1,130 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QANIMATION_H -#define QANIMATION_H - -#include -#include -#include -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -#ifndef QT_NO_ANIMATION - -class QVariantAnimationPrivate; -class Q_CORE_EXPORT QVariantAnimation : public QAbstractAnimation -{ - Q_OBJECT - Q_PROPERTY(QVariant startValue READ startValue WRITE setStartValue) - Q_PROPERTY(QVariant endValue READ endValue WRITE setEndValue) - Q_PROPERTY(QVariant currentValue READ currentValue NOTIFY currentValueChanged) - Q_PROPERTY(int duration READ duration WRITE setDuration) - Q_PROPERTY(QEasingCurve easingCurve READ easingCurve WRITE setEasingCurve) - -public: - typedef QPair KeyValue; - typedef QVector KeyValues; - - QVariantAnimation(QObject *parent = 0); - ~QVariantAnimation(); - - QVariant startValue() const; - void setStartValue(const QVariant &value); - - QVariant endValue() const; - void setEndValue(const QVariant &value); - - QVariant keyValueAt(qreal step) const; - void setKeyValueAt(qreal step, const QVariant &value); - - KeyValues keyValues() const; - void setKeyValues(const KeyValues &values); - - QVariant currentValue() const; - - int duration() const; - void setDuration(int msecs); - - QEasingCurve easingCurve() const; - void setEasingCurve(const QEasingCurve &easing); - - typedef QVariant (*Interpolator)(const void *from, const void *to, qreal progress); - -Q_SIGNALS: - void valueChanged(const QVariant &value); - -protected: - QVariantAnimation(QVariantAnimationPrivate &dd, QObject *parent = 0); - bool event(QEvent *event); - - void updateCurrentTime(int msecs); - void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - - virtual void updateCurrentValue(const QVariant &value) = 0; - virtual QVariant interpolated(const QVariant &from, const QVariant &to, qreal progress) const; - -private: - template friend void qRegisterAnimationInterpolator(QVariant (*func)(const T &, const T &, qreal)); - static void registerInterpolator(Interpolator func, int interpolationType); - - Q_DISABLE_COPY(QVariantAnimation) - Q_DECLARE_PRIVATE(QVariantAnimation) -}; - -template -static void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) { - QVariantAnimation::registerInterpolator(reinterpret_cast(func), qMetaTypeId()); -} - -#endif //QT_NO_ANIMATION - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif //QANIMATION_H diff --git a/src/corelib/animation/qvariantanimation_p.h b/src/corelib/animation/qvariantanimation_p.h deleted file mode 100644 index 0d296db..0000000 --- a/src/corelib/animation/qvariantanimation_p.h +++ /dev/null @@ -1,130 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QANIMATION_P_H -#define QANIMATION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of QIODevice. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qvariantanimation.h" -#include -#include -#include - -#include "qabstractanimation_p.h" - -QT_BEGIN_NAMESPACE - -class QVariantAnimationPrivate : public QAbstractAnimationPrivate -{ - Q_DECLARE_PUBLIC(QVariantAnimation) -public: - - QVariantAnimationPrivate() : duration(250), hasStartValue(false) - { - } - - void init() - { - //we keep the mask so that we emit valueChanged only when needed (for performance reasons) - changedSignalMask = (1 << q_func()->metaObject()->indexOfSignal("valueChanged(QVariant)")); - currentInterval.start.first = currentInterval.end.first = 2; //will force the initial refresh - interpolator = 0; - } - - static QVariantAnimationPrivate *get(QVariantAnimation *q) - { - return q->d_func(); - } - - void setDefaultStartValue(const QVariant &value); - - int duration; - QEasingCurve easing; - - QVariantAnimation::KeyValues keyValues; - QVariant currentValue; - QVariant defaultStartValue; - bool hasStartValue; - - //this is used to keep track of the KeyValue interval in which we currently are - struct - { - QVariantAnimation::KeyValue start, end; - } currentInterval; - - mutable QVariantAnimation::Interpolator interpolator; - - quint32 changedSignalMask; - - void setCurrentValueForProgress(const qreal progress); - void recalculateCurrentInterval(bool force=false); - void setValueAt(qreal, const QVariant &); - QVariant valueAt(qreal step) const; - void convertValues(int t); - - static QVariantAnimation::Interpolator getInterpolator(int interpolationType); -}; - -//this should make the interpolation faster -template inline T _q_interpolate(const T &f, const T &t, qreal progress) -{ - return T(f + (t - f) * progress); -} - -template inline QVariant _q_interpolateVariant(const T &from, const T &to, qreal progress) -{ - return _q_interpolate(from, to, progress); -} - - -QT_END_NAMESPACE - -#endif //QANIMATION_P_H diff --git a/src/corelib/corelib.pro b/src/corelib/corelib.pro index db51d43..f99d57f 100644 --- a/src/corelib/corelib.pro +++ b/src/corelib/corelib.pro @@ -5,7 +5,6 @@ DEFINES += QT_BUILD_CORE_LIB QT_NO_USING_NAMESPACE win32-msvc*|win32-icc:QMAKE_LFLAGS += /BASE:0x67000000 include(../qbase.pri) -include(animation/animation.pri) include(arch/arch.pri) include(concurrent/concurrent.pri) include(global/global.pri) @@ -15,7 +14,6 @@ include(io/io.pri) include(plugin/plugin.pri) include(kernel/kernel.pri) include(codecs/codecs.pri) -include(statemachine/statemachine.pri) include(xml/xml.pri) mac|darwin:LIBS += -framework ApplicationServices diff --git a/src/corelib/kernel/kernel.pri b/src/corelib/kernel/kernel.pri index ecef555..68649a6 100644 --- a/src/corelib/kernel/kernel.pri +++ b/src/corelib/kernel/kernel.pri @@ -12,7 +12,7 @@ HEADERS += \ kernel/qcoreevent.h \ kernel/qmetaobject.h \ kernel/qmetatype.h \ - kernel/qmimedata.h \ + kernel/qmimedata.h \ kernel/qobject.h \ kernel/qobjectdefs.h \ kernel/qsignalmapper.h \ @@ -27,8 +27,8 @@ HEADERS += \ kernel/qvariant_p.h \ kernel/qmetaobject_p.h \ kernel/qobject_p.h \ - kernel/qcoreglobaldata_p.h \ - kernel/qsharedmemory.h \ + kernel/qcoreglobaldata_p.h \ + kernel/qsharedmemory.h \ kernel/qsharedmemory_p.h \ kernel/qsystemsemaphore.h \ kernel/qsystemsemaphore_p.h \ @@ -43,7 +43,7 @@ SOURCES += \ kernel/qcoreevent.cpp \ kernel/qmetaobject.cpp \ kernel/qmetatype.cpp \ - kernel/qmimedata.cpp \ + kernel/qmimedata.cpp \ kernel/qobject.cpp \ kernel/qobjectcleanuphandler.cpp \ kernel/qsignalmapper.cpp \ diff --git a/src/corelib/kernel/qcoreevent.cpp b/src/corelib/kernel/qcoreevent.cpp index d6b0174..11a2d3c 100644 --- a/src/corelib/kernel/qcoreevent.cpp +++ b/src/corelib/kernel/qcoreevent.cpp @@ -264,8 +264,6 @@ QT_BEGIN_NAMESPACE \omitvalue NetworkReplyUpdated \omitvalue FutureCallOut \omitvalue CocoaRequestModal - \omitvalue Wrapped - \omitvalue Signal */ /*! diff --git a/src/corelib/kernel/qcoreevent.h b/src/corelib/kernel/qcoreevent.h index 18188a8..fa472e6 100644 --- a/src/corelib/kernel/qcoreevent.h +++ b/src/corelib/kernel/qcoreevent.h @@ -44,7 +44,6 @@ #include #include -#include QT_BEGIN_HEADER @@ -55,9 +54,7 @@ QT_MODULE(Core) class QEventPrivate; class Q_CORE_EXPORT QEvent // event base class { - Q_GADGET QDOC_PROPERTY(bool accepted READ isAccepted WRITE setAccepted) - Q_ENUMS(Type) public: enum Type { /* @@ -269,10 +266,7 @@ public: CocoaRequestModal = 190, // Internal for requesting an application modal Cocoa Window MacGLClearDrawable = 191, // Internal Cocoa, the window has changed, so we must clear - Signal = 192, - Wrapped = 193, - - // 512 reserved for Qt Jambi's MetaCall event + // 512 reserved for Qt Jambi's MetaCall event // 513 reserved for Qt Jambi's DeleteOnMainThread event User = 1000, // first user event id diff --git a/src/corelib/statemachine/qabstractstate.cpp b/src/corelib/statemachine/qabstractstate.cpp deleted file mode 100644 index 942722f..0000000 --- a/src/corelib/statemachine/qabstractstate.cpp +++ /dev/null @@ -1,202 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qabstractstate.h" -#include "qabstractstate_p.h" -#include "qstate.h" -#include "qstate_p.h" -#include "qstatemachine.h" -#include "qstatemachine_p.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QAbstractState - - \brief The QAbstractState class is the base class of states of a QStateMachine. - - \since 4.6 - \ingroup statemachine - - The QAbstractState class is the abstract base class of states that are part - of a QStateMachine. It defines the interface that all state objects have in - common. QAbstractState is part of \l{The State Machine Framework}. - - The entered() signal is emitted when the state has been entered. The - exited() signal is emitted when the state has been exited. - - The parentState() function returns the state's parent state. The machine() - function returns the state machine that the state is part of. - - \section1 Subclassing - - The onEntry() function is called when the state is entered; reimplement this - function to perform custom processing when the state is entered. - - The onExit() function is called when the state is exited; reimplement this - function to perform custom processing when the state is exited. -*/ - -QAbstractStatePrivate::QAbstractStatePrivate() -{ -} - -QAbstractStatePrivate *QAbstractStatePrivate::get(QAbstractState *q) -{ - return q->d_func(); -} - -QStateMachine *QAbstractStatePrivate::machine() const -{ - Q_Q(const QAbstractState); - QObject *par = q->parent(); - while (par != 0) { - if (QStateMachine *mach = qobject_cast(par)) - return mach; - par = par->parent(); - } - return 0; -} - -void QAbstractStatePrivate::callOnEntry(QEvent *e) -{ - Q_Q(QAbstractState); - q->onEntry(e); -} - -void QAbstractStatePrivate::callOnExit(QEvent *e) -{ - Q_Q(QAbstractState); - q->onExit(e); -} - -void QAbstractStatePrivate::emitEntered() -{ - Q_Q(QAbstractState); - emit q->entered(); -} - -void QAbstractStatePrivate::emitExited() -{ - Q_Q(QAbstractState); - emit q->exited(); -} - -/*! - Constructs a new state with the given \a parent state. -*/ -QAbstractState::QAbstractState(QState *parent) - : QObject(*new QAbstractStatePrivate, parent) -{ -} - -/*! - \internal -*/ -QAbstractState::QAbstractState(QAbstractStatePrivate &dd, QState *parent) - : QObject(dd, parent) -{ -} - -/*! - Destroys this state. -*/ -QAbstractState::~QAbstractState() -{ -} - -/*! - Returns this state's parent state, or 0 if the state has no parent state. -*/ -QState *QAbstractState::parentState() const -{ - return qobject_cast(parent()); -} - -/*! - Returns the state machine that this state is part of, or 0 if the state is - not part of a state machine. -*/ -QStateMachine *QAbstractState::machine() const -{ - Q_D(const QAbstractState); - return d->machine(); -} - -/*! - \fn QAbstractState::onExit(QEvent *event) - - This function is called when the state is exited. The given \a event is what - caused the state to be exited. Reimplement this function to perform custom - processing when the state is exited. -*/ - -/*! - \fn QAbstractState::onEntry(QEvent *event) - - This function is called when the state is entered. The given \a event is - what caused the state to be entered. Reimplement this function to perform - custom processing when the state is entered. -*/ - -/*! - \fn QAbstractState::entered() - - This signal is emitted when the state has been entered (after onEntry() has - been called). -*/ - -/*! - \fn QAbstractState::exited() - - This signal is emitted when the state has been exited (after onExit() has - been called). -*/ - -/*! - \reimp -*/ -bool QAbstractState::event(QEvent *e) -{ - return QObject::event(e); -} - -QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qabstractstate.h b/src/corelib/statemachine/qabstractstate.h deleted file mode 100644 index d0ebb52..0000000 --- a/src/corelib/statemachine/qabstractstate.h +++ /dev/null @@ -1,90 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QABSTRACTSTATE_H -#define QABSTRACTSTATE_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QState; -class QStateMachine; - -class QAbstractStatePrivate; -class Q_CORE_EXPORT QAbstractState : public QObject -{ - Q_OBJECT -public: - ~QAbstractState(); - - QState *parentState() const; - QStateMachine *machine() const; - -Q_SIGNALS: - void entered(); - void exited(); - -protected: - QAbstractState(QState *parent = 0); - - virtual void onEntry(QEvent *event) = 0; - virtual void onExit(QEvent *event) = 0; - - bool event(QEvent *e); - -protected: - QAbstractState(QAbstractStatePrivate &dd, QState *parent); - -private: - Q_DISABLE_COPY(QAbstractState) - Q_DECLARE_PRIVATE(QAbstractState) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qabstractstate_p.h b/src/corelib/statemachine/qabstractstate_p.h deleted file mode 100644 index 2aad47e..0000000 --- a/src/corelib/statemachine/qabstractstate_p.h +++ /dev/null @@ -1,84 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QABSTRACTSTATE_P_H -#define QABSTRACTSTATE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -class QStateMachine; - -class QAbstractState; -class Q_CORE_EXPORT QAbstractStatePrivate - : public QObjectPrivate -{ - Q_DECLARE_PUBLIC(QAbstractState) - -public: - QAbstractStatePrivate(); - - static QAbstractStatePrivate *get(QAbstractState *q); - - QStateMachine *machine() const; - - void callOnEntry(QEvent *e); - void callOnExit(QEvent *e); - - void emitEntered(); - void emitExited(); -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/statemachine/qabstracttransition.cpp b/src/corelib/statemachine/qabstracttransition.cpp deleted file mode 100644 index dfcafeb..0000000 --- a/src/corelib/statemachine/qabstracttransition.cpp +++ /dev/null @@ -1,342 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qabstracttransition.h" -#include "qabstracttransition_p.h" -#include "qabstractstate.h" -#include "qstate.h" -#include "qstatemachine.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QAbstractTransition - - \brief The QAbstractTransition class is the base class of transitions between QAbstractState objects. - - \since 4.6 - \ingroup statemachine - - The QAbstractTransition class is the abstract base class of transitions - between states (QAbstractState objects) of a - QStateMachine. QAbstractTransition is part of \l{The State Machine - Framework}. - - The sourceState() function returns the source of the transition. The - targetStates() function returns the targets of the transition. The machine() - function returns the state machine that the transition is part of. - - Transitions can cause animations to be played. Use the addAnimation() - function to add an animation to the transition. - - \section1 Subclassing - - The eventTest() function is called by the state machine to determine whether - an event should trigger the transition. In your reimplementation you - typically check the event type and cast the event object to the proper type, - and check that one or more properties of the event meet your criteria. - - The onTransition() function is called when the transition is triggered; - reimplement this function to perform custom processing for the transition. -*/ - -/*! - \property QAbstractTransition::sourceState - - \brief the source state (parent) of this transition -*/ - -/*! - \property QAbstractTransition::targetState - - \brief the target state of this transition -*/ - -/*! - \property QAbstractTransition::targetStates - - \brief the target states of this transition - - If multiple states are specified, all must be descendants of the same - parallel group state. -*/ - -QAbstractTransitionPrivate::QAbstractTransitionPrivate() -{ -} - -QAbstractTransitionPrivate *QAbstractTransitionPrivate::get(QAbstractTransition *q) -{ - return q->d_func(); -} - -QStateMachine *QAbstractTransitionPrivate::machine() const -{ - Q_Q(const QAbstractTransition); - QObject *par = q->parent(); - while (par != 0) { - if (QStateMachine *mach = qobject_cast(par)) - return mach; - par = par->parent(); - } - return 0; -} - -bool QAbstractTransitionPrivate::callEventTest(QEvent *e) -{ - Q_Q(QAbstractTransition); - return q->eventTest(e); -} - -void QAbstractTransitionPrivate::callOnTransition(QEvent *e) -{ - Q_Q(QAbstractTransition); - q->onTransition(e); -} - -QState *QAbstractTransitionPrivate::sourceState() const -{ - Q_Q(const QAbstractTransition); - return qobject_cast(q->parent()); -} - -/*! - Constructs a new QAbstractTransition object with the given \a sourceState. -*/ -QAbstractTransition::QAbstractTransition(QState *sourceState) - : QObject(*new QAbstractTransitionPrivate, sourceState) -{ -} - -/*! - Constructs a new QAbstractTransition object with the given \a targets and \a - sourceState. -*/ -QAbstractTransition::QAbstractTransition(const QList &targets, - QState *sourceState) - : QObject(*new QAbstractTransitionPrivate, sourceState) -{ - setTargetStates(targets); -} - -/*! - \internal -*/ -QAbstractTransition::QAbstractTransition(QAbstractTransitionPrivate &dd, - QState *parent) - : QObject(dd, parent) -{ -} - -/*! - \internal -*/ -QAbstractTransition::QAbstractTransition(QAbstractTransitionPrivate &dd, - const QList &targets, - QState *parent) - : QObject(dd, parent) -{ - setTargetStates(targets); -} - -/*! - Destroys this transition. -*/ -QAbstractTransition::~QAbstractTransition() -{ -} - -/*! - Returns the source state of this transition, or 0 if this transition has no - source state. -*/ -QState *QAbstractTransition::sourceState() const -{ - Q_D(const QAbstractTransition); - return d->sourceState(); -} - -/*! - Returns the target state of this transition, or 0 if the transition has no - target. -*/ -QAbstractState *QAbstractTransition::targetState() const -{ - Q_D(const QAbstractTransition); - if (d->targetStates.isEmpty()) - return 0; - return d->targetStates.first(); -} - -/*! - Sets the \a target state of this transition. -*/ -void QAbstractTransition::setTargetState(QAbstractState* target) -{ - Q_D(QAbstractTransition); - if (!target) - d->targetStates.clear(); - else - setTargetStates(QList() << target); -} - -/*! - Returns the target states of this transition, or an empty list if this - transition has no target states. -*/ -QList QAbstractTransition::targetStates() const -{ - Q_D(const QAbstractTransition); - QList result; - for (int i = 0; i < d->targetStates.size(); ++i) { - QAbstractState *target = d->targetStates.at(i); - if (target) - result.append(target); - } - return result; -} - -/*! - Sets the target states of this transition to be the given \a targets. -*/ -void QAbstractTransition::setTargetStates(const QList &targets) -{ - Q_D(QAbstractTransition); - - for (int i=0; imachine() != 0 && target->machine()->rootState() == target) { - qWarning("QAbstractTransition::setTargetStates: root state cannot be target of transition"); - return; - } - } - - d->targetStates.clear(); - for (int i = 0; i < targets.size(); ++i) - d->targetStates.append(targets.at(i)); -} - -/*! - Returns the state machine that this transition is part of, or 0 if the - transition is not part of a state machine. -*/ -QStateMachine *QAbstractTransition::machine() const -{ - Q_D(const QAbstractTransition); - return d->machine(); -} - -#ifndef QT_NO_ANIMATION - -/*! - Adds the given \a animation to this transition. - The transition does not take ownership of the animation. - - \sa removeAnimation(), animations() -*/ -void QAbstractTransition::addAnimation(QAbstractAnimation *animation) -{ - Q_D(QAbstractTransition); - if (!animation) { - qWarning("QAbstractTransition::addAnimation: cannot add null animation"); - return; - } - d->animations.append(animation); -} - -/*! - Removes the given \a animation from this transition. - - \sa addAnimation() -*/ -void QAbstractTransition::removeAnimation(QAbstractAnimation *animation) -{ - Q_D(QAbstractTransition); - if (!animation) { - qWarning("QAbstractTransition::removeAnimation: cannot remove null animation"); - return; - } - d->animations.removeOne(animation); -} - -/*! - Returns the list of animations associated with this transition, or an empty - list if it has no animations. - - \sa addAnimation() -*/ -QList QAbstractTransition::animations() const -{ - Q_D(const QAbstractTransition); - return d->animations; -} - -#endif - -/*! - \fn QAbstractTransition::eventTest(QEvent *event) - - This function is called to determine whether the given \a event should cause - this transition to trigger. Reimplement this function and return true if the - event should trigger the transition, otherwise return false. -*/ - -/*! - \fn QAbstractTransition::onTransition(QEvent *event) - - This function is called when the transition is triggered. The given \a event - is what caused the transition to trigger. Reimplement this function to - perform custom processing when the transition is triggered. -*/ - -/*! - \reimp -*/ -bool QAbstractTransition::event(QEvent *e) -{ - return QObject::event(e); -} - -QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qabstracttransition.h b/src/corelib/statemachine/qabstracttransition.h deleted file mode 100644 index c63d55a..0000000 --- a/src/corelib/statemachine/qabstracttransition.h +++ /dev/null @@ -1,111 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QABSTRACTTRANSITION_H -#define QABSTRACTTRANSITION_H - -#include - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QEvent; -class QAbstractState; -class QState; -class QStateMachine; - -#ifndef QT_NO_ANIMATION -class QAbstractAnimation; -#endif - -class QAbstractTransitionPrivate; -class Q_CORE_EXPORT QAbstractTransition : public QObject -{ - Q_OBJECT - Q_PROPERTY(QState* sourceState READ sourceState) - Q_PROPERTY(QAbstractState* targetState READ targetState WRITE setTargetState) - Q_PROPERTY(QList targetStates READ targetStates WRITE setTargetStates) -public: - QAbstractTransition(QState *sourceState = 0); - QAbstractTransition(const QList &targets, QState *sourceState = 0); - virtual ~QAbstractTransition(); - - QState *sourceState() const; - QAbstractState *targetState() const; - void setTargetState(QAbstractState* target); - QList targetStates() const; - void setTargetStates(const QList &targets); - - QStateMachine *machine() const; - -#ifndef QT_NO_ANIMATION - void addAnimation(QAbstractAnimation *animation); - void removeAnimation(QAbstractAnimation *animation); - QList animations() const; -#endif - -protected: - virtual bool eventTest(QEvent *event) = 0; - - virtual void onTransition(QEvent *event) = 0; - - bool event(QEvent *e); - -protected: - QAbstractTransition(QAbstractTransitionPrivate &dd, QState *parent); - QAbstractTransition(QAbstractTransitionPrivate &dd, - const QList &targets, QState *parent); - -private: - Q_DISABLE_COPY(QAbstractTransition) - Q_DECLARE_PRIVATE(QAbstractTransition) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qabstracttransition_p.h b/src/corelib/statemachine/qabstracttransition_p.h deleted file mode 100644 index f067984..0000000 --- a/src/corelib/statemachine/qabstracttransition_p.h +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QABSTRACTTRANSITION_P_H -#define QABSTRACTTRANSITION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -#include -#include - -QT_BEGIN_NAMESPACE - -class QAbstractState; -class QState; -class QStateMachine; - -class QAbstractTransition; -class Q_CORE_EXPORT QAbstractTransitionPrivate - : public QObjectPrivate -{ - Q_DECLARE_PUBLIC(QAbstractTransition) -public: - QAbstractTransitionPrivate(); - - static QAbstractTransitionPrivate *get(QAbstractTransition *q); - - bool callEventTest(QEvent *e); - void callOnTransition(QEvent *e); - QState *sourceState() const; - QStateMachine *machine() const; - - QList > targetStates; - -#ifndef QT_NO_ANIMATION - QList animations; -#endif -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/statemachine/qeventtransition.cpp b/src/corelib/statemachine/qeventtransition.cpp deleted file mode 100644 index 74eb577..0000000 --- a/src/corelib/statemachine/qeventtransition.cpp +++ /dev/null @@ -1,282 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qeventtransition.h" -#include "qeventtransition_p.h" -#include "qwrappedevent.h" -#include "qstate.h" -#include "qstate_p.h" -#include "qstatemachine.h" -#include "qstatemachine_p.h" -#include - -QT_BEGIN_NAMESPACE - -/*! - \class QEventTransition - - \brief The QEventTransition class provides a QObject-specific transition for Qt events. - - \since 4.6 - \ingroup statemachine - - A QEventTransition object binds an event to a particular QObject. - QEventTransition is part of \l{The State Machine Framework}. - - Example: - - \code - QPushButton *button = ...; - QState *s1 = ...; - QState *s2 = ...; - // If in s1 and the button receives an Enter event, transition to s2 - QEventTransition *enterTransition = new QEventTransition(button, QEvent::Enter); - enterTransition->setTargetState(s2); - s1->addTransition(enterTransition); - // If in s2 and the button receives an Exit event, transition back to s1 - QEventTransition *leaveTransition = new QEventTransition(button, QEvent::Leave); - leaveTransition->setTargetState(s1); - s2->addTransition(leaveTransition); - \endcode - - \section1 Subclassing - - When reimplementing the eventTest() function, you should first call the base - implementation to verify that the event is a QWrappedEvent for the proper - object and event type. You may then cast the event to a QWrappedEvent and - get the original event by calling QWrappedEvent::event(), and perform - additional checks on that object. - - \sa QState::addTransition() -*/ - -/*! - \property QEventTransition::eventObject - - \brief the event source that this event transition is associated with -*/ - -/*! - \property QEventTransition::eventType - - \brief the type of event that this event transition is associated with -*/ -QEventTransitionPrivate::QEventTransitionPrivate() -{ - object = 0; - eventType = QEvent::None; - registered = false; -} - -QEventTransitionPrivate *QEventTransitionPrivate::get(QEventTransition *q) -{ - return q->d_func(); -} - -void QEventTransitionPrivate::invalidate() -{ - Q_Q(QEventTransition); - if (registered) { - QState *source = sourceState(); - QStatePrivate *source_d = QStatePrivate::get(source); - QStateMachinePrivate *mach = QStateMachinePrivate::get(source_d->machine()); - if (mach) { - mach->unregisterEventTransition(q); - if (mach->configuration.contains(source)) - mach->registerEventTransition(q); - } - } -} - -/*! - Constructs a new QEventTransition object with the given \a sourceState. -*/ -QEventTransition::QEventTransition(QState *sourceState) - : QAbstractTransition(*new QEventTransitionPrivate, sourceState) -{ -} - -/*! - Constructs a new QEventTransition object associated with events of the given - \a type for the given \a object, and with the given \a sourceState. -*/ -QEventTransition::QEventTransition(QObject *object, QEvent::Type type, - QState *sourceState) - : QAbstractTransition(*new QEventTransitionPrivate, sourceState) -{ - Q_D(QEventTransition); - d->registered = false; - d->object = object; - d->eventType = type; -} - -/*! - Constructs a new QEventTransition object associated with events of the given - \a type for the given \a object. The transition has the given \a targets and - \a sourceState. -*/ -QEventTransition::QEventTransition(QObject *object, QEvent::Type type, - const QList &targets, - QState *sourceState) - : QAbstractTransition(*new QEventTransitionPrivate, targets, sourceState) -{ - Q_D(QEventTransition); - d->registered = false; - d->object = object; - d->eventType = type; -} - -/*! - \internal -*/ -QEventTransition::QEventTransition(QEventTransitionPrivate &dd, QState *parent) - : QAbstractTransition(dd, parent) -{ -} - -/*! - \internal -*/ -QEventTransition::QEventTransition(QEventTransitionPrivate &dd, QObject *object, - QEvent::Type type, QState *parent) - : QAbstractTransition(dd, parent) -{ - Q_D(QEventTransition); - d->registered = false; - d->object = object; - d->eventType = type; -} - -/*! - \internal -*/ -QEventTransition::QEventTransition(QEventTransitionPrivate &dd, QObject *object, - QEvent::Type type, const QList &targets, - QState *parent) - : QAbstractTransition(dd, targets, parent) -{ - Q_D(QEventTransition); - d->registered = false; - d->object = object; - d->eventType = type; -} - -/*! - Destroys this QObject event transition. -*/ -QEventTransition::~QEventTransition() -{ -} - -/*! - Returns the event type that this event transition is associated with. -*/ -QEvent::Type QEventTransition::eventType() const -{ - Q_D(const QEventTransition); - return d->eventType; -} - -/*! - Sets the event \a type that this event transition is associated with. -*/ -void QEventTransition::setEventType(QEvent::Type type) -{ - Q_D(QEventTransition); - if (d->eventType == type) - return; - d->eventType = type; - d->invalidate(); -} - -/*! - Returns the event source associated with this event transition. -*/ -QObject *QEventTransition::eventObject() const -{ - Q_D(const QEventTransition); - return d->object; -} - -/*! - Sets the event source associated with this event transition to be the given - \a object. -*/ -void QEventTransition::setEventObject(QObject *object) -{ - Q_D(QEventTransition); - if (d->object == object) - return; - d->object = object; - d->invalidate(); -} - -/*! - \reimp -*/ -bool QEventTransition::eventTest(QEvent *event) -{ - Q_D(const QEventTransition); - if (event->type() == QEvent::Wrapped) { - QWrappedEvent *we = static_cast(event); - return (we->object() == d->object) - && (we->event()->type() == d->eventType); - } - return false; -} - -/*! - \reimp -*/ -void QEventTransition::onTransition(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \reimp -*/ -bool QEventTransition::event(QEvent *e) -{ - return QAbstractTransition::event(e); -} - -QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qeventtransition.h b/src/corelib/statemachine/qeventtransition.h deleted file mode 100644 index 3530bdd..0000000 --- a/src/corelib/statemachine/qeventtransition.h +++ /dev/null @@ -1,96 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEVENTTRANSITION_H -#define QEVENTTRANSITION_H - -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QEventTransitionPrivate; -class Q_CORE_EXPORT QEventTransition : public QAbstractTransition -{ - Q_OBJECT - Q_PROPERTY(QObject* eventObject READ eventObject WRITE setEventObject) - Q_PROPERTY(QEvent::Type eventType READ eventType WRITE setEventType) -public: - QEventTransition(QState *sourceState = 0); - QEventTransition(QObject *object, QEvent::Type type, QState *sourceState = 0); - QEventTransition(QObject *object, QEvent::Type type, - const QList &targets, QState *sourceState = 0); - ~QEventTransition(); - - QObject *eventObject() const; - void setEventObject(QObject *object); - - QEvent::Type eventType() const; - void setEventType(QEvent::Type type); - -protected: - bool eventTest(QEvent *event); - void onTransition(QEvent *event); - - bool event(QEvent *e); - -protected: - QEventTransition(QEventTransitionPrivate &dd, QState *parent); - QEventTransition(QEventTransitionPrivate &dd, QObject *object, - QEvent::Type type, QState *parent); - QEventTransition(QEventTransitionPrivate &dd, QObject *object, - QEvent::Type type, const QList &targets, - QState *parent); - -private: - Q_DISABLE_COPY(QEventTransition) - Q_DECLARE_PRIVATE(QEventTransition) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qeventtransition_p.h b/src/corelib/statemachine/qeventtransition_p.h deleted file mode 100644 index fca8c0d..0000000 --- a/src/corelib/statemachine/qeventtransition_p.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEVENTTRANSITION_P_H -#define QEVENTTRANSITION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qabstracttransition_p.h" - -QT_BEGIN_NAMESPACE - -class QEventTransition; -class Q_CORE_EXPORT QEventTransitionPrivate : public QAbstractTransitionPrivate -{ - Q_DECLARE_PUBLIC(QEventTransition) -public: - QEventTransitionPrivate(); - - static QEventTransitionPrivate *get(QEventTransition *q); - - void invalidate(); - - bool registered; - QObject *object; - QEvent::Type eventType; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/statemachine/qfinalstate.cpp b/src/corelib/statemachine/qfinalstate.cpp deleted file mode 100644 index 0980336..0000000 --- a/src/corelib/statemachine/qfinalstate.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qfinalstate.h" -#include "qabstractstate_p.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QFinalState - - \brief The QFinalState class provides a final state. - - \since 4.6 - \ingroup statemachine - - A final state is used to communicate that (part of) a QStateMachine has - finished its work. When a final top-level state is entered, the state - machine's \l{QStateMachine::finished()}{finished}() signal is emitted. In - general, when a final substate (a child of a QState) is entered, the parent - state's \l{QState::finished()}{finished}() signal is emitted. QFinalState - is part of \l{The State Machine Framework}. - - To use a final state, you create a QFinalState object and add a transition - to it from another state. Example: - - \code - QPushButton button; - - QStateMachine machine; - QState *s1 = new QState(); - QFinalState *s2 = new QFinalState(); - s1->addTransition(&button, SIGNAL(clicked()), s2); - machine.addState(s1); - machine.addState(s2); - - QObject::connect(&machine, SIGNAL(finished()), QApplication::instance(), SLOT(quit())); - machine.setInitialState(s1); - machine.start(); - \endcode - - \sa QStateMachine::finished(), QState::finished() -*/ - -class QFinalStatePrivate : public QAbstractStatePrivate -{ - Q_DECLARE_PUBLIC(QFinalState) - -public: - QFinalStatePrivate(); -}; - -QFinalStatePrivate::QFinalStatePrivate() -{ -} - -/*! - Constructs a new QFinalState object with the given \a parent state. -*/ -QFinalState::QFinalState(QState *parent) - : QAbstractState(*new QFinalStatePrivate, parent) -{ -} - -/*! - Destroys this final state. -*/ -QFinalState::~QFinalState() -{ -} - -/*! - \reimp -*/ -void QFinalState::onEntry(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \reimp -*/ -void QFinalState::onExit(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \reimp -*/ -bool QFinalState::event(QEvent *e) -{ - return QAbstractState::event(e); -} - -QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qfinalstate.h b/src/corelib/statemachine/qfinalstate.h deleted file mode 100644 index fa68394..0000000 --- a/src/corelib/statemachine/qfinalstate.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QFINALSTATE_H -#define QFINALSTATE_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QFinalStatePrivate; -class Q_CORE_EXPORT QFinalState : public QAbstractState -{ - Q_OBJECT -public: - QFinalState(QState *parent = 0); - ~QFinalState(); - -protected: - void onEntry(QEvent *event); - void onExit(QEvent *event); - - bool event(QEvent *e); - -private: - Q_DISABLE_COPY(QFinalState) - Q_DECLARE_PRIVATE(QFinalState) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qhistorystate.cpp b/src/corelib/statemachine/qhistorystate.cpp deleted file mode 100644 index 517faa8..0000000 --- a/src/corelib/statemachine/qhistorystate.cpp +++ /dev/null @@ -1,223 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qhistorystate.h" -#include "qhistorystate_p.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QHistoryState - - \brief The QHistoryState class provides a means of returning to a previously active substate. - - \since 4.6 - \ingroup statemachine - - A history state is a pseudo-state that represents the child state that the - parent state was in the last time the parent state was exited. A transition - with a history state as its target is in fact a transition to one of the - other child states of the parent state. QHistoryState is part of \l{The - State Machine Framework}. - - Use the setDefaultState() function to set the state that should be entered - if the parent state has never been entered. Example: - - \code - QStateMachine machine; - - QState *s1 = new QState(); - QState *s11 = new QState(s1); - QState *s12 = new QState(s1); - - QHistoryState *s1h = new QHistoryState(s1); - s1h->setDefaultState(s11); - - machine.addState(s1); - - QState *s2 = new QState(); - machine.addState(s2); - - QPushButton *button = new QPushButton(); - // Clicking the button will cause the state machine to enter the child state - // that s1 was in the last time s1 was exited, or the history state's default - // state if s1 has never been entered. - s1->addTransition(button, SIGNAL(clicked()), s1h); - \endcode - - By default a history state is shallow, meaning that it won't remember nested - states. This can be configured through the historyType property. -*/ - -/*! - \property QHistoryState::defaultState - - \brief the default state of this history state -*/ - -/*! - \property QHistoryState::historyType - - \brief the type of history that this history state records - - The default value of this property is QHistoryState::ShallowHistory. -*/ - -/*! - \enum QHistoryState::HistoryType - - This enum specifies the type of history that a QHistoryState records. - - \value ShallowHistory Only the immediate child states of the parent state - are recorded. In this case a transition with the history state as its - target will end up in the immediate child state that the parent was in the - last time it was exited. This is the default. - - \value DeepHistory Nested states are recorded. In this case a transition - with the history state as its target will end up in the most deeply nested - descendant state the parent was in the last time it was exited. -*/ - -QHistoryStatePrivate::QHistoryStatePrivate() - : defaultState(0) -{ -} - -QHistoryStatePrivate *QHistoryStatePrivate::get(QHistoryState *q) -{ - return q->d_func(); -} - -/*! - Constructs a new shallow history state with the given \a parent state. -*/ -QHistoryState::QHistoryState(QState *parent) - : QAbstractState(*new QHistoryStatePrivate, parent) -{ - Q_D(QHistoryState); - d->historyType = ShallowHistory; -} -/*! - Constructs a new history state of the given \a type, with the given \a - parent state. -*/ -QHistoryState::QHistoryState(HistoryType type, QState *parent) - : QAbstractState(*new QHistoryStatePrivate, parent) -{ - Q_D(QHistoryState); - d->historyType = type; -} - -/*! - Destroys this history state. -*/ -QHistoryState::~QHistoryState() -{ -} - -/*! - Returns this history state's default state. The default state indicates the - state to transition to if the parent state has never been entered before. -*/ -QAbstractState *QHistoryState::defaultState() const -{ - Q_D(const QHistoryState); - return d->defaultState; -} - -/*! - Sets this history state's default state to be the given \a state. - \a state must be a sibling of this history state. -*/ -void QHistoryState::setDefaultState(QAbstractState *state) -{ - Q_D(QHistoryState); - if (state && state->parentState() != parentState()) { - qWarning("QHistoryState::setDefaultState: state %p does not belong " - "to this history state's group (%p)", state, parentState()); - return; - } - d->defaultState = state; -} - -/*! - Returns the type of history that this history state records. -*/ -QHistoryState::HistoryType QHistoryState::historyType() const -{ - Q_D(const QHistoryState); - return d->historyType; -} - -/*! - Sets the \a type of history that this history state records. -*/ -void QHistoryState::setHistoryType(HistoryType type) -{ - Q_D(QHistoryState); - d->historyType = type; -} - -/*! - \reimp -*/ -void QHistoryState::onEntry(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \reimp -*/ -void QHistoryState::onExit(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \reimp -*/ -bool QHistoryState::event(QEvent *e) -{ - return QAbstractState::event(e); -} - -QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qhistorystate.h b/src/corelib/statemachine/qhistorystate.h deleted file mode 100644 index a0682bd..0000000 --- a/src/corelib/statemachine/qhistorystate.h +++ /dev/null @@ -1,91 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QHISTORYSTATE_H -#define QHISTORYSTATE_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QHistoryStatePrivate; -class Q_CORE_EXPORT QHistoryState : public QAbstractState -{ - Q_OBJECT - Q_PROPERTY(QAbstractState* defaultState READ defaultState WRITE setDefaultState) - Q_PROPERTY(HistoryType historyType READ historyType WRITE setHistoryType) - Q_ENUMS(HistoryType) -public: - enum HistoryType { - ShallowHistory, - DeepHistory - }; - - QHistoryState(QState *parent = 0); - QHistoryState(HistoryType type, QState *parent = 0); - ~QHistoryState(); - - QAbstractState *defaultState() const; - void setDefaultState(QAbstractState *state); - - HistoryType historyType() const; - void setHistoryType(HistoryType type); - -protected: - void onEntry(QEvent *event); - void onExit(QEvent *event); - - bool event(QEvent *e); - -private: - Q_DISABLE_COPY(QHistoryState) - Q_DECLARE_PRIVATE(QHistoryState) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qhistorystate_p.h b/src/corelib/statemachine/qhistorystate_p.h deleted file mode 100644 index 5aaa64c..0000000 --- a/src/corelib/statemachine/qhistorystate_p.h +++ /dev/null @@ -1,79 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QHISTORYSTATE_P_H -#define QHISTORYSTATE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qabstractstate_p.h" - -#include - -QT_BEGIN_NAMESPACE - -class QHistoryState; -class QHistoryStatePrivate : public QAbstractStatePrivate -{ - Q_DECLARE_PUBLIC(QHistoryState) - -public: - QHistoryStatePrivate(); - - static QHistoryStatePrivate *get(QHistoryState *q); - - QAbstractState *defaultState; - QHistoryState::HistoryType historyType; - QList configuration; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/statemachine/qsignalevent.h b/src/corelib/statemachine/qsignalevent.h deleted file mode 100644 index 8221f68..0000000 --- a/src/corelib/statemachine/qsignalevent.h +++ /dev/null @@ -1,77 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSIGNALEVENT_H -#define QSIGNALEVENT_H - -#include - -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class Q_CORE_EXPORT QSignalEvent : public QEvent -{ -public: - QSignalEvent(const QObject *sender, int signalIndex, - const QList &arguments); - ~QSignalEvent(); - - inline const QObject *sender() const { return m_sender; } - inline int signalIndex() const { return m_signalIndex; } - inline QList arguments() const { return m_arguments; } - -private: - const QObject *m_sender; - int m_signalIndex; - QList m_arguments; -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qsignaleventgenerator_p.h b/src/corelib/statemachine/qsignaleventgenerator_p.h deleted file mode 100644 index cf0ea1e..0000000 --- a/src/corelib/statemachine/qsignaleventgenerator_p.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSIGNALEVENTGENERATOR_P_H -#define QSIGNALEVENTGENERATOR_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -QT_BEGIN_NAMESPACE - -class QStateMachine; - -class QSignalEventGenerator : public QObject -{ -public: - QSignalEventGenerator(QStateMachine *parent); - - static const QMetaObject staticMetaObject; - virtual const QMetaObject *metaObject() const; - virtual void *qt_metacast(const char *); - virtual int qt_metacall(QMetaObject::Call, int, void **argv); - -private: - Q_DISABLE_COPY(QSignalEventGenerator) -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/statemachine/qsignaltransition.cpp b/src/corelib/statemachine/qsignaltransition.cpp deleted file mode 100644 index 4caa917..0000000 --- a/src/corelib/statemachine/qsignaltransition.cpp +++ /dev/null @@ -1,257 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qsignaltransition.h" -#include "qsignaltransition_p.h" -#include "qsignalevent.h" -#include "qstate.h" -#include "qstate_p.h" -#include "qstatemachine.h" -#include "qstatemachine_p.h" -#include - -QT_BEGIN_NAMESPACE - -/*! - \class QSignalTransition - - \brief The QSignalTransition class provides a transition based on a Qt signal. - - \since 4.6 - \ingroup statemachine - - Typically you would use the overload of QState::addTransition() that takes a - sender and signal as arguments, rather than creating QSignalTransition - objects directly. QSignalTransition is part of \l{The State Machine - Framework}. - - You can subclass QSignalTransition and reimplement eventTest() to make a - signal transition conditional; the event object passed to eventTest() will - be a QSignalEvent object. Example: - - \code - class CheckedTransition : public QSignalTransition - { - public: - CheckedTransition(QCheckBox *check) - : QSignalTransition(check, SIGNAL(stateChanged(int))) {} - protected: - bool eventTest(QEvent *e) const { - if (!QSignalTransition::eventTest(e)) - return false; - QSignalEvent *se = static_cast(e); - return (se->arguments().at(0).toInt() == Qt::Checked); - } - }; - - ... - - QCheckBox *check = new QCheckBox(); - check->setTristate(true); - - QState *s1 = new QState(); - QState *s2 = new QState(); - CheckedTransition *t1 = new CheckedTransition(check); - t1->setTargetState(s2); - s1->addTransition(t1); - \endcode -*/ - -/*! - \property QSignalTransition::senderObject - - \brief the sender object that this signal transition is associated with -*/ - -/*! - \property QSignalTransition::signal - - \brief the signal that this signal transition is associated with -*/ - -QSignalTransitionPrivate::QSignalTransitionPrivate() -{ - sender = 0; - signalIndex = -1; -} - -QSignalTransitionPrivate *QSignalTransitionPrivate::get(QSignalTransition *q) -{ - return q->d_func(); -} - -void QSignalTransitionPrivate::invalidate() -{ - Q_Q(QSignalTransition); - if (signalIndex != -1) { - QState *source = sourceState(); - QStatePrivate *source_d = QStatePrivate::get(source); - QStateMachinePrivate *mach = QStateMachinePrivate::get(source_d->machine()); - if (mach) { - mach->unregisterSignalTransition(q); - if (mach->configuration.contains(source)) - mach->registerSignalTransition(q); - } - } -} - -/*! - Constructs a new signal transition with the given \a sourceState. -*/ -QSignalTransition::QSignalTransition(QState *sourceState) - : QAbstractTransition(*new QSignalTransitionPrivate, sourceState) -{ -} - -/*! - Constructs a new signal transition associated with the given \a signal of - the given \a sender, and with the given \a sourceState. -*/ -QSignalTransition::QSignalTransition(QObject *sender, const char *signal, - QState *sourceState) - : QAbstractTransition(*new QSignalTransitionPrivate, sourceState) -{ - Q_D(QSignalTransition); - d->sender = sender; - d->signal = signal; -} - -/*! - Constructs a new signal transition associated with the given \a signal of - the given \a sender. The transition has the given \a targets and \a - sourceState. -*/ -QSignalTransition::QSignalTransition(QObject *sender, const char *signal, - const QList &targets, - QState *sourceState) - : QAbstractTransition(*new QSignalTransitionPrivate, targets, sourceState) -{ - Q_D(QSignalTransition); - d->sender = sender; - d->signal = signal; -} - -/*! - Destroys this signal transition. -*/ -QSignalTransition::~QSignalTransition() -{ -} - -/*! - Returns the sender object associated with this signal transition. -*/ -QObject *QSignalTransition::senderObject() const -{ - Q_D(const QSignalTransition); - return d->sender; -} - -/*! - Sets the \a sender object associated with this signal transition. -*/ -void QSignalTransition::setSenderObject(QObject *sender) -{ - Q_D(QSignalTransition); - if (sender == d->sender) - return; - d->sender = sender; - d->invalidate(); -} - -/*! - Returns the signal associated with this signal transition. -*/ -QByteArray QSignalTransition::signal() const -{ - Q_D(const QSignalTransition); - return d->signal; -} - -/*! - Sets the \a signal associated with this signal transition. -*/ -void QSignalTransition::setSignal(const QByteArray &signal) -{ - Q_D(QSignalTransition); - if (signal == d->signal) - return; - d->signal = signal; - d->invalidate(); -} - -/*! - \reimp - - The \a event is a QSignalEvent object. The default implementation returns - true if the event's sender and signal index match this transition, and - returns false otherwise. -*/ -bool QSignalTransition::eventTest(QEvent *event) -{ - Q_D(const QSignalTransition); - if (event->type() == QEvent::Signal) { - if (d->signalIndex == -1) - return false; - QSignalEvent *se = static_cast(event); - return (se->sender() == d->sender) - && (se->signalIndex() == d->signalIndex); - } - return false; -} - -/*! - \reimp -*/ -void QSignalTransition::onTransition(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \reimp -*/ -bool QSignalTransition::event(QEvent *e) -{ - return QAbstractTransition::event(e); -} - -QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qsignaltransition.h b/src/corelib/statemachine/qsignaltransition.h deleted file mode 100644 index b485785..0000000 --- a/src/corelib/statemachine/qsignaltransition.h +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSIGNALTRANSITION_H -#define QSIGNALTRANSITION_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QSignalTransitionPrivate; -class Q_CORE_EXPORT QSignalTransition : public QAbstractTransition -{ - Q_OBJECT - Q_PROPERTY(QObject* senderObject READ senderObject WRITE setSenderObject) - Q_PROPERTY(QByteArray signal READ signal WRITE setSignal) -public: - QSignalTransition(QState *sourceState = 0); - QSignalTransition(QObject *sender, const char *signal, - QState *sourceState = 0); - QSignalTransition(QObject *sender, const char *signal, - const QList &targets, - QState *sourceState = 0); - ~QSignalTransition(); - - QObject *senderObject() const; - void setSenderObject(QObject *sender); - - QByteArray signal() const; - void setSignal(const QByteArray &signal); - -protected: - bool eventTest(QEvent *event); - void onTransition(QEvent *event); - - bool event(QEvent *e); - -private: - Q_DISABLE_COPY(QSignalTransition) - Q_DECLARE_PRIVATE(QSignalTransition) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qsignaltransition_p.h b/src/corelib/statemachine/qsignaltransition_p.h deleted file mode 100644 index a23e58c..0000000 --- a/src/corelib/statemachine/qsignaltransition_p.h +++ /dev/null @@ -1,78 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSIGNALTRANSITION_P_H -#define QSIGNALTRANSITION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qabstracttransition_p.h" - -QT_BEGIN_NAMESPACE - -class QSignalTransition; -class QSignalTransitionPrivate : public QAbstractTransitionPrivate -{ - Q_DECLARE_PUBLIC(QSignalTransition) -public: - QSignalTransitionPrivate(); - - static QSignalTransitionPrivate *get(QSignalTransition *q); - - void invalidate(); - - QObject *sender; - QByteArray signal; - int signalIndex; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/statemachine/qstate.cpp b/src/corelib/statemachine/qstate.cpp deleted file mode 100644 index e42e463..0000000 --- a/src/corelib/statemachine/qstate.cpp +++ /dev/null @@ -1,497 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qstate.h" -#include "qstate_p.h" -#include "qhistorystate.h" -#include "qhistorystate_p.h" -#include "qabstracttransition.h" -#include "qabstracttransition_p.h" -#include "qsignaltransition.h" -#include "qstatemachine.h" -#include "qstatemachine_p.h" - -QT_BEGIN_NAMESPACE - -/*! - \class QState - - \brief The QState class provides a general-purpose state for QStateMachine. - - \since 4.6 - \ingroup statemachine - - QState objects can have child states, and can have transitions to other - states. QState is part of \l{The State Machine Framework}. - - The addTransition() function adds a transition. The removeTransition() - function removes a transition. - - The assignProperty() function is used for defining property assignments that - should be performed when a state is entered. - - Top-level states must be passed QStateMachine::rootState() as their parent - state, or added to a state machine using QStateMachine::addState(). - - \section1 States with Child States - - The childMode property determines how child states are treated. For - non-parallel state groups, the setInitialState() function must be called to - set the initial state. The child states are mutually exclusive states, and - the state machine needs to know which child state to enter when the parent - state is the target of a transition. - - The state emits the QState::finished() signal when a final child state - (QFinalState) is entered. - - The setErrorState() sets the state's error state. The error state is the - state that the state machine will transition to if an error is detected when - attempting to enter the state (e.g. because no initial state has been set). - -*/ - -/*! - \property QState::initialState - - \brief the initial state of this state (one of its child states) -*/ - -/*! - \property QState::errorState - - \brief the error state of this state -*/ - -/*! - \property QState::childMode - - \brief the child mode of this state - - The default value of this property is QState::ExclusiveStates. -*/ - -/*! - \enum QState::ChildMode - - This enum specifies how a state's child states are treated. - - \value ExclusiveStates The child states are mutually exclusive and an - initial state must be set by calling QState::setInitialState(). - - \value ParallelStates The child states are parallel. When the parent state - is entered, all its child states are entered in parallel. -*/ - -QStatePrivate::QStatePrivate() - : errorState(0), initialState(0), childMode(QState::ExclusiveStates) -{ -} - -QStatePrivate::~QStatePrivate() -{ -} - -QStatePrivate *QStatePrivate::get(QState *q) -{ - if (!q) - return 0; - return q->d_func(); -} - -const QStatePrivate *QStatePrivate::get(const QState *q) -{ - if (!q) - return 0; - return q->d_func(); -} - -void QStatePrivate::emitFinished() -{ - Q_Q(QState); - emit q->finished(); -} - -void QStatePrivate::emitPolished() -{ - Q_Q(QState); - emit q->polished(); -} - -/*! - Constructs a new state with the given \a parent state. -*/ -QState::QState(QState *parent) - : QAbstractState(*new QStatePrivate, parent) -{ -} - -/*! - Constructs a new state with the given \a childMode and the given \a parent - state. -*/ -QState::QState(ChildMode childMode, QState *parent) - : QAbstractState(*new QStatePrivate, parent) -{ - Q_D(QState); - d->childMode = childMode; -} - -/*! - \internal -*/ -QState::QState(QStatePrivate &dd, QState *parent) - : QAbstractState(dd, parent) -{ -} - -/*! - Destroys this state. -*/ -QState::~QState() -{ -} - -QList QStatePrivate::childStates() const -{ - QList result; - QList::const_iterator it; - for (it = children.constBegin(); it != children.constEnd(); ++it) { - QAbstractState *s = qobject_cast(*it); - if (!s || qobject_cast(s)) - continue; - result.append(s); - } - return result; -} - -QList QStatePrivate::historyStates() const -{ - QList result; - QList::const_iterator it; - for (it = children.constBegin(); it != children.constEnd(); ++it) { - QHistoryState *h = qobject_cast(*it); - if (h) - result.append(h); - } - return result; -} - -QList QStatePrivate::transitions() const -{ - QList result; - QList::const_iterator it; - for (it = children.constBegin(); it != children.constEnd(); ++it) { - QAbstractTransition *t = qobject_cast(*it); - if (t) - result.append(t); - } - return result; -} - -/*! - Instructs this state to set the property with the given \a name of the given - \a object to the given \a value when the state is entered. - - \sa polished() -*/ -void QState::assignProperty(QObject *object, const char *name, - const QVariant &value) -{ - Q_D(QState); - if (!object) { - qWarning("QState::assignProperty: cannot assign property '%s' of null object", name); - return; - } - for (int i = 0; i < d->propertyAssignments.size(); ++i) { - QPropertyAssignment &assn = d->propertyAssignments[i]; - if ((assn.object == object) && (assn.propertyName == name)) { - assn.value = value; - return; - } - } - d->propertyAssignments.append(QPropertyAssignment(object, name, value)); -} - -/*! - Returns this state group's error state. - - \sa QStateMachine::errorState(), QStateMachine::setErrorState() -*/ -QAbstractState *QState::errorState() const -{ - Q_D(const QState); - return d->errorState; -} - -/*! - Sets this state's error state to be the given \a state. If the error state - is not set, or if it is set to 0, the state will inherit its parent's error - state recursively. - - \sa QStateMachine::setErrorState(), QStateMachine::errorState() -*/ -void QState::setErrorState(QAbstractState *state) -{ - Q_D(QState); - if (state != 0 && state->machine() != machine()) { - qWarning("QState::setErrorState: error state cannot belong " - "to a different state machine"); - return; - } - if (state != 0 && state->machine() != 0 && state->machine()->rootState() == state) { - qWarning("QStateMachine::setErrorState: root state cannot be error state"); - return; - } - - d->errorState = state; -} - -/*! - Adds the given \a transition. The transition has this state as the source. - This state takes ownership of the transition. If the transition is successfully - added, the function will return the \a transition pointer. Otherwise it will return null. -*/ -QAbstractTransition *QState::addTransition(QAbstractTransition *transition) -{ - Q_D(QState); - if (!transition) { - qWarning("QState::addTransition: cannot add null transition"); - return 0; - } - - // machine() will always be non-null for root state - if (machine() != 0 && machine()->rootState() == this) { - qWarning("QState::addTransition: cannot add transition from root state"); - return 0; - } - - const QList > &targets = QAbstractTransitionPrivate::get(transition)->targetStates; - for (int i = 0; i < targets.size(); ++i) { - QAbstractState *t = targets.at(i); - if (!t) { - qWarning("QState::addTransition: cannot add transition to null state"); - return 0; - } - if ((QAbstractStatePrivate::get(t)->machine() != d->machine()) - && QAbstractStatePrivate::get(t)->machine() && d->machine()) { - qWarning("QState::addTransition: cannot add transition " - "to a state in a different state machine"); - return 0; - } - } - transition->setParent(this); - if (machine() != 0 && machine()->configuration().contains(this)) - QStateMachinePrivate::get(machine())->registerTransitions(this); - return transition; -} - -/*! - Adds a transition associated with the given \a signal of the given \a sender - object, and returns the new QSignalTransition object. The transition has - this state as the source, and the given \a target as the target state. -*/ -QSignalTransition *QState::addTransition(QObject *sender, const char *signal, - QAbstractState *target) -{ - if (!sender) { - qWarning("QState::addTransition: sender cannot be null"); - return 0; - } - if (!signal) { - qWarning("QState::addTransition: signal cannot be null"); - return 0; - } - if (!target) { - qWarning("QState::addTransition: cannot add transition to null state"); - return 0; - } - if (*signal && sender->metaObject()->indexOfSignal(signal+1) == -1) { - qWarning("QState::addTransition: no such signal %s::%s", - sender->metaObject()->className(), signal+1); - return 0; - } - QSignalTransition *trans = new QSignalTransition(sender, signal, QList() << target); - addTransition(trans); - return trans; -} - -namespace { - -// ### Make public? -class UnconditionalTransition : public QAbstractTransition -{ -public: - UnconditionalTransition(QAbstractState *target) - : QAbstractTransition(QList() << target) {} -protected: - void onTransition(QEvent *) {} - bool eventTest(QEvent *) { return true; } -}; - -} // namespace - -/*! - Adds an unconditional transition from this state to the given \a target - state, and returns then new transition object. -*/ -QAbstractTransition *QState::addTransition(QAbstractState *target) -{ - if (!target) { - qWarning("QState::addTransition: cannot add transition to null state"); - return 0; - } - UnconditionalTransition *trans = new UnconditionalTransition(target); - return addTransition(trans); -} - -/*! - Removes the given \a transition from this state. The state releases - ownership of the transition. - - \sa addTransition() -*/ -void QState::removeTransition(QAbstractTransition *transition) -{ - Q_D(QState); - if (!transition) { - qWarning("QState::removeTransition: cannot remove null transition"); - return; - } - if (transition->sourceState() != this) { - qWarning("QState::removeTransition: transition %p's source state (%p)" - " is different from this state (%p)", - transition, transition->sourceState(), this); - return; - } - QStateMachinePrivate *mach = QStateMachinePrivate::get(d->machine()); - if (mach) - mach->unregisterTransition(transition); - transition->setParent(0); -} - -/*! - \reimp -*/ -void QState::onEntry(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \reimp -*/ -void QState::onExit(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - Returns this state's initial state, or 0 if the state has no initial state. -*/ -QAbstractState *QState::initialState() const -{ - Q_D(const QState); - return d->initialState; -} - -/*! - Sets this state's initial state to be the given \a state. - \a state has to be a child of this state. -*/ -void QState::setInitialState(QAbstractState *state) -{ - Q_D(QState); - if (d->childMode == QState::ParallelStates) { - qWarning("QState::setInitialState: ignoring attempt to set initial state " - "of parallel state group %p", this); - return; - } - if (state && (state->parentState() != this)) { - qWarning("QState::setInitialState: state %p is not a child of this state (%p)", - state, this); - return; - } - d->initialState = state; -} - -/*! - Returns the child mode of this state. -*/ -QState::ChildMode QState::childMode() const -{ - Q_D(const QState); - return d->childMode; -} - -/*! - Sets the child \a mode of this state. -*/ -void QState::setChildMode(ChildMode mode) -{ - Q_D(QState); - d->childMode = mode; -} - -/*! - \reimp -*/ -bool QState::event(QEvent *e) -{ - return QAbstractState::event(e); -} - -/*! - \fn QState::finished() - - This signal is emitted when a final child state of this state is entered. - - \sa QFinalState -*/ - -/*! - \fn QState::polished() - - This signal is emitted when all properties have been assigned their final value. - - \sa QState::assignProperty(), QAbstractTransition::addAnimation() -*/ - -QT_END_NAMESPACE diff --git a/src/corelib/statemachine/qstate.h b/src/corelib/statemachine/qstate.h deleted file mode 100644 index 6729c69..0000000 --- a/src/corelib/statemachine/qstate.h +++ /dev/null @@ -1,113 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSTATE_H -#define QSTATE_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QAbstractTransition; -class QSignalTransition; - -class QStatePrivate; -class Q_CORE_EXPORT QState : public QAbstractState -{ - Q_OBJECT - Q_PROPERTY(QAbstractState* initialState READ initialState WRITE setInitialState) - Q_PROPERTY(QAbstractState* errorState READ errorState WRITE setErrorState) - Q_PROPERTY(ChildMode childMode READ childMode WRITE setChildMode) - Q_ENUMS(ChildMode) -public: - enum ChildMode { - ExclusiveStates, - ParallelStates - }; - - QState(QState *parent = 0); - QState(ChildMode childMode, QState *parent = 0); - ~QState(); - - QAbstractState *errorState() const; - void setErrorState(QAbstractState *state); - - QAbstractTransition *addTransition(QAbstractTransition *transition); - QSignalTransition *addTransition(QObject *sender, const char *signal, QAbstractState *target); - QAbstractTransition *addTransition(QAbstractState *target); - void removeTransition(QAbstractTransition *transition); - - QAbstractState *initialState() const; - void setInitialState(QAbstractState *state); - - ChildMode childMode() const; - void setChildMode(ChildMode mode); - - void assignProperty(QObject *object, const char *name, - const QVariant &value); - -Q_SIGNALS: - void finished(); - void polished(); - -protected: - void onEntry(QEvent *event); - void onExit(QEvent *event); - - bool event(QEvent *e); - -protected: - QState(QStatePrivate &dd, QState *parent); - -private: - Q_DISABLE_COPY(QState) - Q_DECLARE_PRIVATE(QState) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qstate_p.h b/src/corelib/statemachine/qstate_p.h deleted file mode 100644 index 1f913b4..0000000 --- a/src/corelib/statemachine/qstate_p.h +++ /dev/null @@ -1,108 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSTATE_P_H -#define QSTATE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "qabstractstate_p.h" - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -struct QPropertyAssignment -{ - QPropertyAssignment() - : object(0) {} - QPropertyAssignment(QObject *o, const QByteArray &n, - const QVariant &v, bool es = true) - : object(o), propertyName(n), value(v), explicitlySet(es) - {} - QObject *object; - QByteArray propertyName; - QVariant value; - bool explicitlySet; -}; - -class QAbstractTransition; -class QHistoryState; - -class QState; -class Q_CORE_EXPORT QStatePrivate : public QAbstractStatePrivate -{ - Q_DECLARE_PUBLIC(QState) -public: - QStatePrivate(); - ~QStatePrivate(); - - static QStatePrivate *get(QState *q); - static const QStatePrivate *get(const QState *q); - - QList childStates() const; - QList historyStates() const; - QList transitions() const; - - void emitFinished(); - void emitPolished(); - - QAbstractState *errorState; - QAbstractState *initialState; - QState::ChildMode childMode; - - QList propertyAssignments; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp deleted file mode 100644 index 744515b..0000000 --- a/src/corelib/statemachine/qstatemachine.cpp +++ /dev/null @@ -1,2216 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qstatemachine.h" -#include "qstate.h" -#include "qstate_p.h" -#include "qstatemachine_p.h" -#include "qabstracttransition.h" -#include "qabstracttransition_p.h" -#include "qsignaltransition.h" -#include "qsignaltransition_p.h" -#include "qsignalevent.h" -#include "qsignaleventgenerator_p.h" -#include "qabstractstate.h" -#include "qabstractstate_p.h" -#include "qfinalstate.h" -#include "qhistorystate.h" -#include "qhistorystate_p.h" -#include "private/qobject_p.h" -#include "private/qthread_p.h" - -#ifndef QT_NO_STATEMACHINE_EVENTFILTER -#include "qeventtransition.h" -#include "qeventtransition_p.h" -#include "qwrappedevent.h" -#endif - -#ifndef QT_NO_ANIMATION -#include "qpropertyanimation.h" -#include "qanimationgroup.h" -#include -#endif - -#include -#include - -QT_BEGIN_NAMESPACE - -/*! - \class QStateMachine - \reentrant - - \brief The QStateMachine class provides a hierarchical finite state machine. - - \since 4.6 - \ingroup statemachine - - QStateMachine is based on the concepts and notation of - \l{Statecharts: A visual formalism for complex - systems}{Statecharts}. QStateMachine is part of \l{The State - Machine Framework}. - - A state machine manages a set of states (classes that inherit from - QAbstractState) and transitions (descendants of - QAbstractTransition) between those states; these states and - transitions define a state graph. Once a state graph has been - built, the state machine can execute it. \l{QStateMachine}'s - execution algorithm is based on the \l{State Chart XML: State - Machine Notation for Control Abstraction}{State Chart XML (SCXML)} - algorithm. The framework's \l{The State Machine - Framework}{overview} gives several state graphs and the code to - build them. - - The rootState() is the parent of all top-level states in the - machine; it is used, for instance, when the state graph is - deleted. It is created by the machine. - - Use the addState() function to add a state to the state machine. - All top-level states are added to the root state. States are - removed with the removeState() function. Removing states while the - machine is running is discouraged. - - Before the machine can be started, the \l{initialState}{initial - state} must be set. The initial state is the state that the - machine enters when started. You can then start() the state - machine. The started() signal is emitted when the initial state is - entered. - - The machine is event driven and keeps its own event loop. Events - are posted to the machine through postEvent(). Note that this - means that it executes asynchronously, and that it will not - progress without a running event loop. You will normally not have - to post events to the machine directly as Qt's transitions, e.g., - QEventTransition and its subclasses, handle this. But for custom - transitions triggered by events, postEvent() is useful. - - The state machine processes events and takes transitions until a - top-level final state is entered; the state machine then emits the - finished() signal. You can also stop() the state machine - explicitly. The stopped() signal is emitted in this case. - - The following snippet shows a state machine that will finish when a button - is clicked: - - \code - QPushButton button; - - QStateMachine machine; - QState *s1 = new QState(); - s1->assignProperty(&button, "text", "Click me"); - - QFinalState *s2 = new QFinalState(); - s1->addTransition(&button, SIGNAL(clicked()), s2); - - machine.addState(s1); - machine.addState(s2); - machine.setInitialState(s1); - machine.start(); - \endcode - - This code example uses QState, which inherits QAbstractState. The - QState class provides a state that you can use to set properties - and invoke methods on \l{QObject}s when the state is entered or - exited. It also contains convenience functions for adding - transitions, e.g., \l{QSignalTransition}s as in this example. See - the QState class description for further details. - - If an error is encountered, the machine will enter the - \l{errorState}{error state}, which is a special state created by - the machine. The types of errors possible are described by the - \l{QStateMachine::}{Error} enum. After the error state is entered, - the type of the error can be retrieved with error(). The execution - of the state graph will not stop when the error state is entered. - So it is possible to handle the error, for instance, by connecting - to the \l{QAbstractState::}{entered()} signal of the error state. - It is also possible to set a custom error state with - setErrorState(). - - \omit This stuff will be moved elsewhere -This is - typically used in conjunction with \l{Signals and Slots}{signals}; the - signals determine the flow of the state graph, whereas the states' property - assignments and method invocations are the actions. - - The postEvent() function posts an event to the state machine. This is useful - when you are using custom events to trigger transitions. - \endomit - - \sa QAbstractState, QAbstractTransition, QState, {The State Machine Framework} -*/ - -/*! - \property QStateMachine::rootState - - \brief the root state of this state machine -*/ - -/*! - \property QStateMachine::initialState - - \brief the initial state of this state machine - - The initial state must be one of the rootState()'s child states. -*/ - -/*! - \property QStateMachine::errorState - - \brief the error state of this state machine -*/ - -/*! - \property QStateMachine::errorString - - \brief the error string of this state machine -*/ - -/*! - \property QStateMachine::globalRestorePolicy - - \brief the restore policy for states of this state machine. - - The default value of this property is - QStateMachine::DoNotRestoreProperties. -*/ - -#ifndef QT_NO_ANIMATION -/*! - \property QStateMachine::animationsEnabled - - \brief whether animations are enabled - - The default value of this property is true. - - \sa QAbstractTransition::addAnimation() -*/ -#endif - -// #define QSTATEMACHINE_DEBUG - -QStateMachinePrivate::QStateMachinePrivate() -{ - state = NotRunning; - processing = false; - processingScheduled = false; - stop = false; - error = QStateMachine::NoError; - globalRestorePolicy = QStateMachine::DoNotRestoreProperties; - rootState = 0; - initialErrorStateForRoot = 0; - signalEventGenerator = 0; -#ifndef QT_NO_ANIMATION - animationsEnabled = true; -#endif -} - -QStateMachinePrivate::~QStateMachinePrivate() -{ - qDeleteAll(internalEventQueue); - qDeleteAll(externalEventQueue); -} - -QStateMachinePrivate *QStateMachinePrivate::get(QStateMachine *q) -{ - if (q) - return q->d_func(); - return 0; -} - -static QEvent *cloneEvent(QEvent *e) -{ - switch (e->type()) { - case QEvent::None: - return new QEvent(*e); - case QEvent::Timer: - return new QTimerEvent(*static_cast(e)); - default: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - } - return 0; -} - -const QStateMachinePrivate::Handler qt_kernel_statemachine_handler = { - cloneEvent -}; - -const QStateMachinePrivate::Handler *QStateMachinePrivate::handler = &qt_kernel_statemachine_handler; - -Q_CORE_EXPORT const QStateMachinePrivate::Handler *qcoreStateMachineHandler() -{ - return &qt_kernel_statemachine_handler; -} - -static int indexOfDescendant(QState *s, QAbstractState *desc) -{ - QList childStates = QStatePrivate::get(s)->childStates(); - for (int i = 0; i < childStates.size(); ++i) { - QAbstractState *c = childStates.at(i); - if ((c == desc) || QStateMachinePrivate::isDescendantOf(desc, c)) { - return i; - } - } - return -1; -} - -bool QStateMachinePrivate::stateEntryLessThan(QAbstractState *s1, QAbstractState *s2) -{ - if (s1->parent() == s2->parent()) { - return s1->children().indexOf(s1) - < s2->children().indexOf(s2); - } else if (isDescendantOf(s1, s2)) { - return false; - } else if (isDescendantOf(s2, s1)) { - return true; - } else { - QState *lca = findLCA(QList() << s1 << s2); - Q_ASSERT(lca != 0); - return (indexOfDescendant(lca, s1) < indexOfDescendant(lca, s2)); - } -} - -bool QStateMachinePrivate::stateExitLessThan(QAbstractState *s1, QAbstractState *s2) -{ - if (s1->parent() == s2->parent()) { - return s1->children().indexOf(s1) - < s2->children().indexOf(s2); - } else if (isDescendantOf(s1, s2)) { - return true; - } else if (isDescendantOf(s2, s1)) { - return false; - } else { - QState *lca = findLCA(QList() << s1 << s2); - Q_ASSERT(lca != 0); - return (indexOfDescendant(lca, s1) < indexOfDescendant(lca, s2)); - } -} - -QState *QStateMachinePrivate::findLCA(const QList &states) -{ - if (states.isEmpty()) - return 0; - QList ancestors = properAncestors(states.at(0), 0); - for (int i = 0; i < ancestors.size(); ++i) { - QState *anc = ancestors.at(i); - bool ok = true; - for (int j = states.size() - 1; (j > 0) && ok; --j) { - const QAbstractState *s = states.at(j); - if (!isDescendantOf(s, anc)) - ok = false; - } - if (ok) - return anc; - } - return 0; -} - -bool QStateMachinePrivate::isPreempted(const QAbstractState *s, const QSet &transitions) const -{ - QSet::const_iterator it; - for (it = transitions.constBegin(); it != transitions.constEnd(); ++it) { - QAbstractTransition *t = *it; - QList lst = t->targetStates(); - if (!lst.isEmpty()) { - lst.prepend(t->sourceState()); - QAbstractState *lca = findLCA(lst); - if (isDescendantOf(s, lca)) { -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ":" << transitions << "preempts selection of a transition from" - << s << "because" << s << "is a descendant of" << lca; -#endif - return true; - } - } - } - return false; -} - -QSet QStateMachinePrivate::selectTransitions(QEvent *event) const -{ - Q_Q(const QStateMachine); - QSet enabledTransitions; - QSet::const_iterator it; - const_cast(q)->beginSelectTransitions(event); - for (it = configuration.constBegin(); it != configuration.constEnd(); ++it) { - QAbstractState *state = *it; - if (!isAtomic(state)) - continue; - if (isPreempted(state, enabledTransitions)) - continue; - QList lst = properAncestors(state, 0); - if (QState *grp = qobject_cast(state)) - lst.prepend(grp); - bool found = false; - for (int j = 0; (j < lst.size()) && !found; ++j) { - QState *s = lst.at(j); - QList transitions = QStatePrivate::get(s)->transitions(); - for (int k = 0; k < transitions.size(); ++k) { - QAbstractTransition *t = transitions.at(k); - if (QAbstractTransitionPrivate::get(t)->callEventTest(event)) { -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": selecting transition" << t; -#endif - enabledTransitions.insert(t); - found = true; - break; - } - } - } - } - const_cast(q)->endSelectTransitions(event); - return enabledTransitions; -} - -void QStateMachinePrivate::microstep(QEvent *event, const QList &enabledTransitions) -{ -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": begin microstep( enabledTransitions:" << enabledTransitions << ")"; - qDebug() << q_func() << ": configuration before exiting states:" << configuration; -#endif - QList exitedStates = exitStates(event, enabledTransitions); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": configuration after exiting states:" << configuration; -#endif - executeTransitionContent(event, enabledTransitions); - QList enteredStates = enterStates(event, enabledTransitions); - applyProperties(enabledTransitions, exitedStates, enteredStates); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": configuration after entering states:" << configuration; - qDebug() << q_func() << ": end microstep"; -#endif -} - -QList QStateMachinePrivate::exitStates(QEvent *event, const QList &enabledTransitions) -{ -// qDebug() << "exitStates(" << enabledTransitions << ")"; - QSet statesToExit; -// QSet statesToSnapshot; - for (int i = 0; i < enabledTransitions.size(); ++i) { - QAbstractTransition *t = enabledTransitions.at(i); - QList lst = t->targetStates(); - if (lst.isEmpty()) - continue; - lst.prepend(t->sourceState()); - QAbstractState *lca = findLCA(lst); - if (lca == 0) { - setError(QStateMachine::NoCommonAncestorForTransitionError, t->sourceState()); - lst = pendingErrorStates.toList(); - lst.prepend(t->sourceState()); - - lca = findLCA(lst); - Q_ASSERT(lca != 0); - } - - { - QSet::const_iterator it; - for (it = configuration.constBegin(); it != configuration.constEnd(); ++it) { - QAbstractState *s = *it; - if (isDescendantOf(s, lca)) - statesToExit.insert(s); - } - } - } - QList statesToExit_sorted = statesToExit.toList(); - qSort(statesToExit_sorted.begin(), statesToExit_sorted.end(), stateExitLessThan); - for (int i = 0; i < statesToExit_sorted.size(); ++i) { - QAbstractState *s = statesToExit_sorted.at(i); - if (QState *grp = qobject_cast(s)) { - QList hlst = QStatePrivate::get(grp)->historyStates(); - for (int j = 0; j < hlst.size(); ++j) { - QHistoryState *h = hlst.at(j); - QHistoryStatePrivate::get(h)->configuration.clear(); - QSet::const_iterator it; - for (it = configuration.constBegin(); it != configuration.constEnd(); ++it) { - QAbstractState *s0 = *it; - if (QHistoryStatePrivate::get(h)->historyType == QHistoryState::DeepHistory) { - if (isAtomic(s0) && isDescendantOf(s0, s)) - QHistoryStatePrivate::get(h)->configuration.append(s0); - } else if (s0->parentState() == s) { - QHistoryStatePrivate::get(h)->configuration.append(s0); - } - } -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": recorded" << ((QHistoryStatePrivate::get(h)->historyType == QHistoryState::DeepHistory) ? "deep" : "shallow") - << "history for" << s << "in" << h << ":" << QHistoryStatePrivate::get(h)->configuration; -#endif - } - } - } - for (int i = 0; i < statesToExit_sorted.size(); ++i) { - QAbstractState *s = statesToExit_sorted.at(i); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": exiting" << s; -#endif - QAbstractStatePrivate::get(s)->callOnExit(event); - configuration.remove(s); - QAbstractStatePrivate::get(s)->emitExited(); - } - return statesToExit_sorted; -} - -void QStateMachinePrivate::executeTransitionContent(QEvent *event, const QList &enabledTransitions) -{ - for (int i = 0; i < enabledTransitions.size(); ++i) { - QAbstractTransition *t = enabledTransitions.at(i); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": triggering" << t; -#endif - QAbstractTransitionPrivate::get(t)->callOnTransition(event); - } -} - -QList QStateMachinePrivate::enterStates(QEvent *event, const QList &enabledTransitions) -{ -#ifdef QSTATEMACHINE_DEBUG - Q_Q(QStateMachine); -#endif -// qDebug() << "enterStates(" << enabledTransitions << ")"; - QSet statesToEnter; - QSet statesForDefaultEntry; - - if (pendingErrorStates.isEmpty()) { - for (int i = 0; i < enabledTransitions.size(); ++i) { - QAbstractTransition *t = enabledTransitions.at(i); - QList lst = t->targetStates(); - if (lst.isEmpty()) - continue; - lst.prepend(t->sourceState()); - QState *lca = findLCA(lst); - for (int j = 1; j < lst.size(); ++j) { - QAbstractState *s = lst.at(j); - addStatesToEnter(s, lca, statesToEnter, statesForDefaultEntry); - if (isParallel(lca)) { - QList lcac = QStatePrivate::get(lca)->childStates(); - foreach (QAbstractState* child,lcac) { - if (!statesToEnter.contains(child)) - addStatesToEnter(child,lca,statesToEnter,statesForDefaultEntry); - } - } - } - } - } - - // Did an error occur while selecting transitions? Then we enter the error state. - if (!pendingErrorStates.isEmpty()) { - statesToEnter.clear(); - statesToEnter = pendingErrorStates; - statesForDefaultEntry = pendingErrorStatesForDefaultEntry; - pendingErrorStates.clear(); - pendingErrorStatesForDefaultEntry.clear(); - } - - QList statesToEnter_sorted = statesToEnter.toList(); - qSort(statesToEnter_sorted.begin(), statesToEnter_sorted.end(), stateEntryLessThan); - - for (int i = 0; i < statesToEnter_sorted.size(); ++i) { - QAbstractState *s = statesToEnter_sorted.at(i); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": entering" << s; -#endif - configuration.insert(s); - registerTransitions(s); - QAbstractStatePrivate::get(s)->callOnEntry(event); - QAbstractStatePrivate::get(s)->emitEntered(); - if (statesForDefaultEntry.contains(s)) { - // ### executeContent(s.initial.transition.children()) - } - if (isFinal(s)) { - QState *parent = s->parentState(); - if (parent) { - QState *grandparent = parent->parentState(); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": emitting finished signal for" << parent; -#endif - QStatePrivate::get(parent)->emitFinished(); - if (grandparent && isParallel(grandparent)) { - bool allChildStatesFinal = true; - QList childStates = QStatePrivate::get(grandparent)->childStates(); - for (int j = 0; j < childStates.size(); ++j) { - QAbstractState *cs = childStates.at(j); - if (!isInFinalState(cs)) { - allChildStatesFinal = false; - break; - } - } - if (allChildStatesFinal) { -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": emitting finished signal for" << grandparent; -#endif - QStatePrivate::get(grandparent)->emitFinished(); - } - } - } - } - } - { - QSet::const_iterator it; - for (it = configuration.constBegin(); it != configuration.constEnd(); ++it) { - if (isFinal(*it) && (*it)->parentState() == rootState) { - processing = false; - stopProcessingReason = Finished; - break; - } - } - } -// qDebug() << "configuration:" << configuration.toList(); - return statesToEnter_sorted; -} - -void QStateMachinePrivate::addStatesToEnter(QAbstractState *s, QState *root, - QSet &statesToEnter, - QSet &statesForDefaultEntry) -{ - if (QHistoryState *h = qobject_cast(s)) { - QList hconf = QHistoryStatePrivate::get(h)->configuration; - if (!hconf.isEmpty()) { - for (int k = 0; k < hconf.size(); ++k) { - QAbstractState *s0 = hconf.at(k); - addStatesToEnter(s0, root, statesToEnter, statesForDefaultEntry); - } - #ifdef QSTATEMACHINE_DEBUG - qDebug() <historyType == QHistoryState::DeepHistory) ? "deep" : "shallow") - << "history from" << s << ":" << hconf; - #endif - } else { - QList hlst; - if (QHistoryStatePrivate::get(h)->defaultState) - hlst.append(QHistoryStatePrivate::get(h)->defaultState); - - if (hlst.isEmpty()) { - setError(QStateMachine::NoDefaultStateInHistoryStateError, h); - } else { - for (int k = 0; k < hlst.size(); ++k) { - QAbstractState *s0 = hlst.at(k); - addStatesToEnter(s0, root, statesToEnter, statesForDefaultEntry); - } - #ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": initial history targets for" << s << ":" << hlst; - #endif - } - } - } else { - statesToEnter.insert(s); - if (isParallel(s)) { - QState *grp = qobject_cast(s); - QList lst = QStatePrivate::get(grp)->childStates(); - for (int i = 0; i < lst.size(); ++i) { - QAbstractState *child = lst.at(i); - addStatesToEnter(child, grp, statesToEnter, statesForDefaultEntry); - } - } else if (isCompound(s)) { - statesForDefaultEntry.insert(s); - QState *grp = qobject_cast(s); - QAbstractState *initial = grp->initialState(); - if (initial != 0) { - addStatesToEnter(initial, grp, statesToEnter, statesForDefaultEntry); - } else { - setError(QStateMachine::NoInitialStateError, grp); - return; - } - } - QList ancs = properAncestors(s, root); - for (int i = 0; i < ancs.size(); ++i) { - QState *anc = ancs.at(i); - if (!anc->parentState()) - continue; - statesToEnter.insert(anc); - if (isParallel(anc)) { - QList lst = QStatePrivate::get(anc)->childStates(); - for (int j = 0; j < lst.size(); ++j) { - QAbstractState *child = lst.at(j); - bool hasDescendantInList = false; - QSet::const_iterator it; - for (it = statesToEnter.constBegin(); it != statesToEnter.constEnd(); ++it) { - if (isDescendantOf(*it, child)) { - hasDescendantInList = true; - break; - } - } - if (!hasDescendantInList) - addStatesToEnter(child, anc, statesToEnter, statesForDefaultEntry); - } - } - } - } -} - -void QStateMachinePrivate::applyProperties(const QList &transitionList, - const QList &exitedStates, - const QList &enteredStates) -{ - Q_Q(QStateMachine); -#ifdef QT_NO_ANIMATION - Q_UNUSED(transitionList); -#endif - // Process the property assignments of the entered states. - QHash > propertyAssignmentsForState; - QHash pendingRestorables = registeredRestorables; - for (int i = 0; i < enteredStates.size(); ++i) { - QState *s = qobject_cast(enteredStates.at(i)); - if (!s) - continue; - - QList assignments = QStatePrivate::get(s)->propertyAssignments; - for (int j = 0; j < assignments.size(); ++j) { - const QPropertyAssignment &assn = assignments.at(j); - if (globalRestorePolicy == QStateMachine::RestoreProperties) { - registerRestorable(assn.object, assn.propertyName); - } - pendingRestorables.remove(RestorableId(assn.object, assn.propertyName)); - propertyAssignmentsForState[s].append(assn); - } - - // Remove pending restorables for all parent states to avoid restoring properties - // before the state that assigned them is exited. If state does not explicitly - // assign a property which is assigned by the parent, it inherits the parent's assignment. - QState *parentState = s; - while ((parentState = parentState->parentState()) != 0) { - assignments = QStatePrivate::get(parentState)->propertyAssignments; - for (int j=0; j 0) - propertyAssignmentsForState[s].append(assn); - } - } - } - if (!pendingRestorables.isEmpty()) { - QAbstractState *s; - if (!enteredStates.isEmpty()) - s = enteredStates.last(); // ### handle if parallel - else - s = 0; - propertyAssignmentsForState[s] << restorablesToPropertyList(pendingRestorables); - } - -#ifndef QT_NO_ANIMATION - // Gracefully terminate playing animations for states that are exited. - for (int i = 0; i < exitedStates.size(); ++i) { - QAbstractState *s = exitedStates.at(i); - QList animations = animationsForState.take(s); - for (int j = 0; j < animations.size(); ++j) { - QAbstractAnimation *anim = animations.at(j); - QObject::disconnect(anim, SIGNAL(finished()), q, SLOT(_q_animationFinished())); - stateForAnimation.remove(anim); - - // Stop the (top-level) animation. - // ### Stopping nested animation has weird behavior. - QAbstractAnimation *topLevelAnim = anim; - while (QAnimationGroup *group = topLevelAnim->group()) - topLevelAnim = group; - topLevelAnim->stop(); - - if (resetAnimationEndValues.contains(anim)) { - qobject_cast(anim)->setEndValue(QVariant()); // ### generalize - resetAnimationEndValues.remove(anim); - } - QPropertyAssignment assn = propertyForAnimation.take(anim); - Q_ASSERT(assn.object != 0); - // If there is no property assignment that sets this property, - // set the property to its target value. - bool found = false; - QHash >::const_iterator it; - for (it = propertyAssignmentsForState.constBegin(); it != propertyAssignmentsForState.constEnd(); ++it) { - const QList &assignments = it.value(); - for (int k = 0; k < assignments.size(); ++k) { - if ((assignments.at(k).object == assn.object) - && (assignments.at(k).propertyName == assn.propertyName)) { - found = true; - break; - } - } - } - if (!found) { - assn.object->setProperty(assn.propertyName, assn.value); - } - } - } - - // Find the animations to use for the state change. - QList selectedAnimations; - if (animationsEnabled) { - for (int i = 0; i < transitionList.size(); ++i) { - QAbstractTransition *transition = transitionList.at(i); - - selectedAnimations << transition->animations(); - selectedAnimations << defaultAnimationsForSource.values(transition->sourceState()); - - QList targetStates = transition->targetStates(); - for (int j=0; j >::iterator it; - for (it = propertyAssignmentsForState.begin(); it != propertyAssignmentsForState.end(); ) { - QList::iterator it2; - QAbstractState *s = it.key(); - QList &assignments = it.value(); - for (it2 = assignments.begin(); it2 != assignments.end(); ) { - QPair, QList > ret; - ret = initializeAnimation(anim, *it2); - QList handlers = ret.first; - if (!handlers.isEmpty()) { - for (int j = 0; j < handlers.size(); ++j) { - QAbstractAnimation *a = handlers.at(j); - propertyForAnimation.insert(a, *it2); - stateForAnimation.insert(a, s); - animationsForState[s].append(a); - // ### connect to just the top-level animation? - QObject::disconnect(a, SIGNAL(finished()), q, SLOT(_q_animationFinished())); - QObject::connect(a, SIGNAL(finished()), q, SLOT(_q_animationFinished())); - } - it2 = assignments.erase(it2); - } else { - ++it2; - } - for (int j = 0; j < ret.second.size(); ++j) - resetAnimationEndValues.insert(ret.second.at(j)); - } - if (assignments.isEmpty()) - it = propertyAssignmentsForState.erase(it); - else - ++it; - } - // We require that at least one animation is valid. - // ### generalize - QList variantAnims = qFindChildren(anim); - if (QVariantAnimation *va = qobject_cast(anim)) - variantAnims.append(va); - - bool hasValidEndValue = false; - for (int j = 0; j < variantAnims.size(); ++j) { - if (variantAnims.at(j)->endValue().isValid()) { - hasValidEndValue = true; - break; - } - } - - if (hasValidEndValue) { - anim->start(); - } - } -#endif // !QT_NO_ANIMATION - - // Immediately set the properties that are not animated. - { - QHash >::const_iterator it; - for (it = propertyAssignmentsForState.constBegin(); it != propertyAssignmentsForState.constEnd(); ++it) { - const QList &assignments = it.value(); - for (int i = 0; i < assignments.size(); ++i) { - const QPropertyAssignment &assn = assignments.at(i); - assn.object->setProperty(assn.propertyName, assn.value); - } - } - } - - // Emit polished signal for entered states that have no animated properties. - for (int i = 0; i < enteredStates.size(); ++i) { - QState *s = qobject_cast(enteredStates.at(i)); - if (s && !animationsForState.contains(s)) - QStatePrivate::get(s)->emitPolished(); - } -} - -bool QStateMachinePrivate::isFinal(const QAbstractState *s) -{ - return qobject_cast(s) != 0; -} - -bool QStateMachinePrivate::isParallel(const QAbstractState *s) -{ - const QState *ss = qobject_cast(s); - return ss && (QStatePrivate::get(ss)->childMode == QState::ParallelStates); -} - -bool QStateMachinePrivate::isCompound(const QAbstractState *s) -{ - const QState *group = qobject_cast(s); - if (!group) - return false; - return (!isParallel(group) && !QStatePrivate::get(group)->childStates().isEmpty()) - || (qobject_cast(group->parent()) != 0); -} - -bool QStateMachinePrivate::isAtomic(const QAbstractState *s) -{ - const QState *ss = qobject_cast(s); - return (ss && QStatePrivate::get(ss)->childStates().isEmpty()) - || isFinal(s); -} - - -bool QStateMachinePrivate::isDescendantOf(const QAbstractState *state, const QAbstractState *other) -{ - Q_ASSERT(state != 0); - for (QAbstractState *s = state->parentState(); s != 0; s = s->parentState()) { - if (s == other) - return true; - } - return false; -} - -QList QStateMachinePrivate::properAncestors(const QAbstractState *state, const QState *upperBound) -{ - Q_ASSERT(state != 0); - QList result; - for (QState *s = state->parentState(); s && s != upperBound; s = s->parentState()) { - result.append(s); - } - return result; -} - -bool QStateMachinePrivate::isInFinalState(QAbstractState* s) const -{ - if (isCompound(s)) { - QState *grp = qobject_cast(s); - QList lst = QStatePrivate::get(grp)->childStates(); - for (int i = 0; i < lst.size(); ++i) { - QAbstractState *cs = lst.at(i); - if (isFinal(cs) && configuration.contains(cs)) - return true; - } - return false; - } else if (isParallel(s)) { - QState *grp = qobject_cast(s); - QList lst = QStatePrivate::get(grp)->childStates(); - for (int i = 0; i < lst.size(); ++i) { - QAbstractState *cs = lst.at(i); - if (!isInFinalState(cs)) - return false; - } - return true; - } - else - return false; -} - -void QStateMachinePrivate::registerRestorable(QObject *object, const QByteArray &propertyName) -{ - RestorableId id(object, propertyName); - if (!registeredRestorables.contains(id)) - registeredRestorables.insert(id, object->property(propertyName)); -} - -QList QStateMachinePrivate::restorablesToPropertyList(const QHash &restorables) const -{ - QList result; - QHash::const_iterator it; - for (it = restorables.constBegin(); it != restorables.constEnd(); ++it) { -// qDebug() << "restorable:" << it.key().first << it.key().second << it.value(); - result.append(QPropertyAssignment(it.key().first, it.key().second, it.value(), /*explicitlySet=*/false)); - } - return result; -} - -/*! - \internal - Returns true if the variable with the given \a id has been registered for restoration. -*/ -bool QStateMachinePrivate::hasRestorable(QObject *object, const QByteArray &propertyName) const -{ - return registeredRestorables.contains(RestorableId(object, propertyName)); -} - -QVariant QStateMachinePrivate::restorableValue(QObject *object, const QByteArray &propertyName) const -{ - return registeredRestorables.value(RestorableId(object, propertyName), QVariant()); -} - - -/*! - \internal - Unregisters the variable identified by \a id -*/ -void QStateMachinePrivate::unregisterRestorable(QObject *object, const QByteArray &propertyName) -{ -// qDebug() << "unregisterRestorable(" << object << propertyName << ")"; - RestorableId id(object, propertyName); - registeredRestorables.remove(id); -} - -QAbstractState *QStateMachinePrivate::findErrorState(QAbstractState *context) -{ - // If the user sets the root state's error state to 0, we return the initial error state - if (context == 0) - return initialErrorStateForRoot; - - // Find error state recursively in parent hierarchy if not set explicitly for context state - QAbstractState *errorState = 0; - - QState *s = qobject_cast(context); - if (s) - errorState = s->errorState(); - - if (!errorState) - errorState = findErrorState(context->parentState()); - - return errorState; -} - -void QStateMachinePrivate::setError(QStateMachine::Error errorCode, QAbstractState *currentContext) -{ - error = errorCode; - - switch (errorCode) { - case QStateMachine::NoInitialStateError: - Q_ASSERT(currentContext != 0); - - errorString = QStateMachine::tr("Missing initial state in compound state '%1'") - .arg(currentContext->objectName()); - - break; - case QStateMachine::NoDefaultStateInHistoryStateError: - Q_ASSERT(currentContext != 0); - - errorString = QStateMachine::tr("Missing default state in history state '%1'") - .arg(currentContext->objectName()); - break; - - case QStateMachine::NoCommonAncestorForTransitionError: - Q_ASSERT(currentContext != 0); - - errorString = QStateMachine::tr("No common ancestor for targets and source of transition from state '%1'") - .arg(currentContext->objectName()); - break; - default: - errorString = QStateMachine::tr("Unknown error"); - }; - - pendingErrorStates.clear(); - pendingErrorStatesForDefaultEntry.clear(); - - QAbstractState *currentErrorState = findErrorState(currentContext); - - // Avoid infinite loop if the error state itself has an error - if (currentContext == currentErrorState) { - Q_ASSERT(currentContext != initialErrorStateForRoot); // RootErrorState is broken - currentErrorState = initialErrorStateForRoot; - } - - Q_ASSERT(currentErrorState != 0); - Q_ASSERT(currentErrorState != rootState); - - QState *lca = findLCA(QList() << currentErrorState << currentContext); - addStatesToEnter(currentErrorState, lca, pendingErrorStates, pendingErrorStatesForDefaultEntry); -} - -#ifndef QT_NO_ANIMATION - -QPair, QList > -QStateMachinePrivate::initializeAnimation(QAbstractAnimation *abstractAnimation, - const QPropertyAssignment &prop) -{ - QList handledAnimations; - QList localResetEndValues; - QAnimationGroup *group = qobject_cast(abstractAnimation); - if (group) { - for (int i = 0; i < group->animationCount(); ++i) { - QAbstractAnimation *animationChild = group->animationAt(i); - QPair, QList > ret; - ret = initializeAnimation(animationChild, prop); - handledAnimations << ret.first; - localResetEndValues << ret.second; - } - } else { - QPropertyAnimation *animation = qobject_cast(abstractAnimation); - if (animation != 0 - && prop.object == animation->targetObject() - && prop.propertyName == animation->propertyName()) { - - // Only change end value if it is undefined - if (!animation->endValue().isValid()) { - animation->setEndValue(prop.value); - localResetEndValues.append(animation); - } - handledAnimations.append(animation); - } - } - return qMakePair(handledAnimations, localResetEndValues); -} - -void QStateMachinePrivate::_q_animationFinished() -{ - Q_Q(QStateMachine); - QAbstractAnimation *anim = qobject_cast(q->sender()); - Q_ASSERT(anim != 0); - QObject::disconnect(anim, SIGNAL(finished()), q, SLOT(_q_animationFinished())); - if (resetAnimationEndValues.contains(anim)) { - qobject_cast(anim)->setEndValue(QVariant()); // ### generalize - resetAnimationEndValues.remove(anim); - } - - // Set the final property value. - QPropertyAssignment assn = propertyForAnimation.take(anim); - Q_ASSERT(assn.object != 0); - assn.object->setProperty(assn.propertyName, assn.value); - if (!assn.explicitlySet) - unregisterRestorable(assn.object, assn.propertyName); - - QAbstractState *state = stateForAnimation.take(anim); - Q_ASSERT(state != 0); - QHash >::iterator it; - it = animationsForState.find(state); - Q_ASSERT(it != animationsForState.end()); - QList &animations = it.value(); - animations.removeOne(anim); - if (animations.isEmpty()) { - animationsForState.erase(it); - QStatePrivate::get(qobject_cast(state))->emitPolished(); - } -} - -#endif // !QT_NO_ANIMATION - -namespace { - -class StartState : public QState -{ -public: - StartState(QState *parent) - : QState(parent) {} -protected: - void onEntry(QEvent *) {} - void onExit(QEvent *) {} -}; - -class InitialTransition : public QAbstractTransition -{ -public: - InitialTransition(QAbstractState *target) - : QAbstractTransition(QList() << target) {} -protected: - virtual bool eventTest(QEvent *) { return true; } - virtual void onTransition(QEvent *) {} -}; - -} // namespace - -void QStateMachinePrivate::_q_start() -{ - Q_Q(QStateMachine); - Q_ASSERT(state == Starting); - if (!rootState) { - state = NotRunning; - return; - } - QAbstractState *initial = rootState->initialState(); - if (initial == 0) - setError(QStateMachine::NoInitialStateError, rootState); - - configuration.clear(); - qDeleteAll(internalEventQueue); - internalEventQueue.clear(); - qDeleteAll(externalEventQueue); - externalEventQueue.clear(); - -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": starting"; -#endif - state = Running; - processingScheduled = true; // we call _q_process() below - emit q->started(); - - StartState *start = new StartState(rootState); - QAbstractTransition *initialTransition = new InitialTransition(initial); - start->addTransition(initialTransition); - QList transitions; - transitions.append(initialTransition); - QEvent nullEvent(QEvent::None); - executeTransitionContent(&nullEvent, transitions); - enterStates(&nullEvent, transitions); - applyProperties(transitions, QList() << start, - QList() << initial); - delete start; - -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": initial configuration:" << configuration; -#endif - _q_process(); -} - -void QStateMachinePrivate::_q_process() -{ - Q_Q(QStateMachine); - Q_ASSERT(state == Running); - Q_ASSERT(!processing); - processing = true; - processingScheduled = false; -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": starting the event processing loop"; -#endif - while (processing) { - if (stop) { - stop = false; - processing = false; - stopProcessingReason = Stopped; - break; - } - QSet enabledTransitions; - QEvent *e = new QEvent(QEvent::None); - enabledTransitions = selectTransitions(e); - if (enabledTransitions.isEmpty()) { - delete e; - e = 0; - } - if (enabledTransitions.isEmpty() && !internalEventQueue.isEmpty()) { - e = internalEventQueue.takeFirst(); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": dequeued internal event" << e << "of type" << e->type(); -#endif - enabledTransitions = selectTransitions(e); - if (enabledTransitions.isEmpty()) { - delete e; - e = 0; - } - } - if (enabledTransitions.isEmpty()) { - if (externalEventQueue.isEmpty()) { - if (internalEventQueue.isEmpty()) { - processing = false; - stopProcessingReason = EventQueueEmpty; - } - } else { - e = externalEventQueue.takeFirst(); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": dequeued external event" << e << "of type" << e->type(); -#endif - enabledTransitions = selectTransitions(e); - if (enabledTransitions.isEmpty()) { - delete e; - e = 0; - } - } - } - if (!enabledTransitions.isEmpty()) { - q->beginMicrostep(e); - microstep(e, enabledTransitions.toList()); - q->endMicrostep(e); - } -#ifdef QSTATEMACHINE_DEBUG - else { - qDebug() << q << ": no transitions enabled"; - } -#endif - delete e; - } -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": finished the event processing loop"; -#endif - switch (stopProcessingReason) { - case EventQueueEmpty: - break; - case Finished: - state = NotRunning; - unregisterAllTransitions(); - emit q->finished(); - break; - case Stopped: - state = NotRunning; - unregisterAllTransitions(); - emit q->stopped(); - break; - } -} - -void QStateMachinePrivate::scheduleProcess() -{ - if ((state != Running) || processing || processingScheduled) - return; - processingScheduled = true; - QMetaObject::invokeMethod(q_func(), "_q_process", Qt::QueuedConnection); -} - -void QStateMachinePrivate::registerTransitions(QAbstractState *state) -{ - QState *group = qobject_cast(state); - if (!group) - return; - QList transitions = QStatePrivate::get(group)->transitions(); - for (int i = 0; i < transitions.size(); ++i) { - QAbstractTransition *t = transitions.at(i); - if (QSignalTransition *st = qobject_cast(t)) { - registerSignalTransition(st); - } -#ifndef QT_NO_STATEMACHINE_EVENTFILTER - else if (QEventTransition *oet = qobject_cast(t)) { - registerEventTransition(oet); - } -#endif - } -} - -void QStateMachinePrivate::unregisterTransition(QAbstractTransition *transition) -{ - if (QSignalTransition *st = qobject_cast(transition)) { - unregisterSignalTransition(st); - } -#ifndef QT_NO_STATEMACHINE_EVENTFILTER - else if (QEventTransition *oet = qobject_cast(transition)) { - unregisterEventTransition(oet); - } -#endif -} - -static int senderSignalIndex(const QObject *sender) -{ - QObjectPrivate *d = QObjectPrivate::get(const_cast(sender)); - QMutexLocker(&d->threadData->mutex); - if (!d->currentSender) - return -1; - - // Return -1 if d->currentSender isn't in d->senders - bool found = false; - for (int i = 0; !found && i < d->senders.count(); ++i) - found = (d->senders.at(i)->sender == d->currentSender->sender); - if (!found) - return -1; - return d->currentSender->signal; -} - -void QStateMachinePrivate::registerSignalTransition(QSignalTransition *transition) -{ - Q_Q(QStateMachine); - if (QSignalTransitionPrivate::get(transition)->signalIndex != -1) - return; // already registered - QObject *sender = QSignalTransitionPrivate::get(transition)->sender; - if (!sender) - return; - QByteArray signal = QSignalTransitionPrivate::get(transition)->signal; - if (signal.startsWith('0'+QSIGNAL_CODE)) - signal.remove(0, 1); - int signalIndex = sender->metaObject()->indexOfSignal(signal); - if (signalIndex == -1) { - qWarning("QSignalTransition: no such signal: %s::%s", - sender->metaObject()->className(), signal.constData()); - return; - } - QVector &connectedSignalIndexes = connections[sender]; - if (connectedSignalIndexes.size() <= signalIndex) - connectedSignalIndexes.resize(signalIndex+1); - if (connectedSignalIndexes.at(signalIndex) == 0) { - if (!signalEventGenerator) - signalEventGenerator = new QSignalEventGenerator(q); - bool ok = QMetaObject::connect(sender, signalIndex, signalEventGenerator, - signalEventGenerator->metaObject()->methodOffset()); - if (!ok) { -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": FAILED to add signal transition from" << transition->sourceState() - << ": ( sender =" << sender << ", signal =" << (signal.mid(1)) - << ", targets =" << transition->targetStates() << ")"; -#endif - return; - } - } - ++connectedSignalIndexes[signalIndex]; - QSignalTransitionPrivate::get(transition)->signalIndex = signalIndex; -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": added signal transition from" << transition->sourceState() - << ": ( sender =" << sender << ", signal =" << (signal.mid(1)) - << ", targets =" << transition->targetStates() << ")"; -#endif -} - -void QStateMachinePrivate::unregisterSignalTransition(QSignalTransition *transition) -{ - int signalIndex = QSignalTransitionPrivate::get(transition)->signalIndex; - if (signalIndex == -1) - return; // not registered - QSignalTransitionPrivate::get(transition)->signalIndex = -1; - const QObject *sender = QSignalTransitionPrivate::get(transition)->sender; - QVector &connectedSignalIndexes = connections[sender]; - Q_ASSERT(connectedSignalIndexes.size() > signalIndex); - Q_ASSERT(connectedSignalIndexes.at(signalIndex) != 0); - if (--connectedSignalIndexes[signalIndex] == 0) { - Q_ASSERT(signalEventGenerator != 0); - QMetaObject::disconnect(sender, signalIndex, signalEventGenerator, - signalEventGenerator->metaObject()->methodOffset()); - int sum = 0; - for (int i = 0; i < connectedSignalIndexes.size(); ++i) - sum += connectedSignalIndexes.at(i); - if (sum == 0) - connections.remove(sender); - } -} - -void QStateMachinePrivate::unregisterAllTransitions() -{ - { - QList transitions = qFindChildren(rootState); - for (int i = 0; i < transitions.size(); ++i) - unregisterSignalTransition(transitions.at(i)); - } - { - QList transitions = qFindChildren(rootState); - for (int i = 0; i < transitions.size(); ++i) - unregisterEventTransition(transitions.at(i)); - } -} - -#ifndef QT_NO_STATEMACHINE_EVENTFILTER -void QStateMachinePrivate::registerEventTransition(QEventTransition *transition) -{ - Q_Q(QStateMachine); - if (QEventTransitionPrivate::get(transition)->registered) - return; - if (transition->eventType() >= QEvent::User) { - qWarning("QObject event transitions are not supported for custom types"); - return; - } - QObject *object = QEventTransitionPrivate::get(transition)->object; - if (!object) - return; - QObjectPrivate *od = QObjectPrivate::get(object); - if (!od->eventFilters.contains(q)) - object->installEventFilter(q); - ++qobjectEvents[object][transition->eventType()]; - QEventTransitionPrivate::get(transition)->registered = true; -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q << ": added event transition from" << transition->sourceState() - << ": ( object =" << object << ", event =" << transition->eventType() - << ", targets =" << transition->targetStates() << ")"; -#endif -} - -void QStateMachinePrivate::unregisterEventTransition(QEventTransition *transition) -{ - Q_Q(QStateMachine); - if (!QEventTransitionPrivate::get(transition)->registered) - return; - QObject *object = QEventTransitionPrivate::get(transition)->object; - QHash &events = qobjectEvents[object]; - Q_ASSERT(events.value(transition->eventType()) > 0); - if (--events[transition->eventType()] == 0) { - events.remove(transition->eventType()); - int sum = 0; - QHash::const_iterator it; - for (it = events.constBegin(); it != events.constEnd(); ++it) - sum += it.value(); - if (sum == 0) { - qobjectEvents.remove(object); - object->removeEventFilter(q); - } - } - QEventTransitionPrivate::get(transition)->registered = false; -} -#endif - -void QStateMachinePrivate::handleTransitionSignal(const QObject *sender, int signalIndex, - void **argv) -{ - const QVector &connectedSignalIndexes = connections[sender]; - Q_ASSERT(connectedSignalIndexes.at(signalIndex) != 0); - const QMetaObject *meta = sender->metaObject(); - QMetaMethod method = meta->method(signalIndex); - QList parameterTypes = method.parameterTypes(); - int argc = parameterTypes.count(); - QList vargs; - for (int i = 0; i < argc; ++i) { - int type = QMetaType::type(parameterTypes.at(i)); - vargs.append(QVariant(type, argv[i+1])); - } - -#ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": sending signal event ( sender =" << sender - << ", signal =" << sender->metaObject()->method(signalIndex).signature() << ")"; -#endif - internalEventQueue.append(new QSignalEvent(sender, signalIndex, vargs)); - scheduleProcess(); -} - -/*! - Constructs a new state machine with the given \a parent. -*/ -QStateMachine::QStateMachine(QObject *parent) - : QObject(*new QStateMachinePrivate, parent) -{ -} - -/*! - \internal -*/ -QStateMachine::QStateMachine(QStateMachinePrivate &dd, QObject *parent) - : QObject(dd, parent) -{ -} - -/*! - Destroys this state machine. -*/ -QStateMachine::~QStateMachine() -{ -} - -namespace { - -class RootErrorState : public QAbstractState -{ -public: - RootErrorState(QState *parent) - : QAbstractState(parent) - { - setObjectName(QString::fromLatin1("DefaultErrorState")); - } - - void onEntry(QEvent *) - { - QAbstractStatePrivate *d = QAbstractStatePrivate::get(this); - QStateMachine *machine = d->machine(); - - qWarning("Unrecoverable error detected in running state machine: %s", - qPrintable(machine->errorString())); - } - - void onExit(QEvent *) {} -}; - -class RootState : public QState -{ -public: - RootState(QState *parent) - : QState(parent) - { - } - - void onEntry(QEvent *) {} - void onExit(QEvent *) {} -}; - -} // namespace - -/*! - Returns this state machine's root state. -*/ -QState *QStateMachine::rootState() const -{ - Q_D(const QStateMachine); - if (!d->rootState) { - const_cast(d)->rootState = new RootState(0); - const_cast(d)->initialErrorStateForRoot = new RootErrorState(d->rootState); - d->rootState->setParent(const_cast(this)); - d->rootState->setErrorState(d->initialErrorStateForRoot); - } - return d->rootState; -} - -/*! - Returns the error state of the state machine's root state. - - \sa QState::errorState() -*/ -QAbstractState *QStateMachine::errorState() const -{ - return rootState()->errorState(); -} - -/*! - Sets the error state of this state machine's root state to be \a state. When a running state - machine encounters an error which puts it in an undefined state, it will enter an error state - based on the context of the error that occurred. It will enter this state regardless of what - is currently in the event queue. - - If the erroneous state has an error state set, this will be entered by the machine. If no error - state has been set, the state machine will search the parent hierarchy recursively for an - error state. The error state of the root state can thus be seen as a global error state that - applies for the states for which a more specific error state has not been set. - - Before entering the error state, the state machine will set the error code returned by error() and - error message returned by errorString(). - - The default error state will print a warning to the console containing the information returned by - errorString(). By setting a new error state on either the state machine itself, or on specific - states, you can fine tune error handling in the state machine. - - If the root state's error state is set to 0, or if the error state selected by the machine itself - contains an error, the default error state will be used. - - \sa QState::setErrorState(), rootState() -*/ -void QStateMachine::setErrorState(QAbstractState *state) -{ - rootState()->setErrorState(state); -} - -/*! \enum QStateMachine::Error - - This enum type defines errors that can occur in the state machine at run time. When the state - machine encounters an unrecoverable error at run time, it will set the error code returned - by error(), the error message returned by errorString(), and enter an error state based on - the context of the error. - - \value NoError No error has occurred. - \value NoInitialStateError The machine has entered a QState with children which does not have an - initial state set. The context of this error is the state which is missing an initial - state. - \value NoDefaultStateInHistoryStateError The machine has entered a QHistoryState which does not have - a default state set. The context of this error is the QHistoryState which is missing a - default state. - \value NoCommonAncestorForTransitionError The machine has selected a transition whose source - and targets are not part of the same tree of states, and thus are not part of the same - state machine. Commonly, this could mean that one of the states has not been given - any parent or added to any machine. The context of this error is the source state of - the transition. - - \sa setErrorState() -*/ - -/*! - \enum QStateMachine::RestorePolicy - - This enum specifies the restore policy type. The restore policy - takes effect when the machine enters a state which sets one or more - properties. If the restore policy is set to RestoreProperties, - the state machine will save the original value of the property before the - new value is set. - - Later, when the machine either enters a state which does not set - a value for the given property, the property will automatically be restored - to its initial value. - - Only one initial value will be saved for any given property. If a value for a property has - already been saved by the state machine, it will not be overwritten until the property has been - successfully restored. - - \value DoNotRestoreProperties The state machine should not save the initial values of properties - and restore them later. - \value RestoreProperties The state machine should save the initial values of properties - and restore them later. - - \sa QStateMachine::globalRestorePolicy QState::assignProperty() -*/ - - -/*! - Returns the error code of the last error that occurred in the state machine. -*/ -QStateMachine::Error QStateMachine::error() const -{ - Q_D(const QStateMachine); - return d->error; -} - -/*! - Returns the error string of the last error that occurred in the state machine. -*/ -QString QStateMachine::errorString() const -{ - Q_D(const QStateMachine); - return d->errorString; -} - -/*! - Clears the error string and error code of the state machine. -*/ -void QStateMachine::clearError() -{ - Q_D(QStateMachine); - d->errorString.clear(); - d->error = NoError; -} - -/*! - Returns the restore policy of the state machine. - - \sa setGlobalRestorePolicy() -*/ -QStateMachine::RestorePolicy QStateMachine::globalRestorePolicy() const -{ - Q_D(const QStateMachine); - return d->globalRestorePolicy; -} - -/*! - Sets the restore policy of the state machine to \a restorePolicy. The default - restore policy is QAbstractState::DoNotRestoreProperties. - - \sa globalRestorePolicy() -*/ -void QStateMachine::setGlobalRestorePolicy(QStateMachine::RestorePolicy restorePolicy) -{ - Q_D(QStateMachine); - d->globalRestorePolicy = restorePolicy; -} - -/*! - Returns this state machine's initial state, or 0 if no initial state has - been set. -*/ -QAbstractState *QStateMachine::initialState() const -{ - Q_D(const QStateMachine); - if (!d->rootState) - return 0; - return d->rootState->initialState(); -} - -/*! - Sets this state machine's initial \a state. -*/ -void QStateMachine::setInitialState(QAbstractState *state) -{ - Q_D(QStateMachine); - if (!d->rootState) { - if (!state) - return; - rootState()->setInitialState(state); - } - d->rootState->setInitialState(state); -} - -/*! - Adds the given \a state to this state machine. The state becomes a top-level - state (i.e. a child of the rootState()). - - If the state is already in a different machine, it will first be removed - from its old machine, and then added to this machine. - - \sa removeState(), rootState(), setInitialState() -*/ -void QStateMachine::addState(QAbstractState *state) -{ - if (!state) { - qWarning("QStateMachine::addState: cannot add null state"); - return; - } - if (QAbstractStatePrivate::get(state)->machine() == this) { - qWarning("QStateMachine::addState: state has already been added to this machine"); - return; - } - state->setParent(rootState()); -} - -/*! - Removes the given \a state from this state machine. The state machine - releases ownership of the state. - - \sa addState() -*/ -void QStateMachine::removeState(QAbstractState *state) -{ - if (!state) { - qWarning("QStateMachine::removeState: cannot remove null state"); - return; - } - if (QAbstractStatePrivate::get(state)->machine() != this) { - qWarning("QStateMachine::removeState: state %p's machine (%p)" - " is different from this machine (%p)", - state, QAbstractStatePrivate::get(state)->machine(), this); - return; - } - state->setParent(0); -} - -/*! - Returns whether this state machine is running. - - start(), stop() -*/ -bool QStateMachine::isRunning() const -{ - Q_D(const QStateMachine); - return (d->state == QStateMachinePrivate::Running); -} - -/*! - Starts this state machine. The machine will reset its configuration and - transition to the initial state. When a final top-level state (QFinalState) - is entered, the machine will emit the finished() signal. - - \sa started(), finished(), stop(), initialState() -*/ -void QStateMachine::start() -{ - Q_D(QStateMachine); - - if (rootState()->initialState() == 0) { - qWarning("QStateMachine::start: No initial state set for machine. Refusing to start."); - return; - } - - switch (d->state) { - case QStateMachinePrivate::NotRunning: - d->state = QStateMachinePrivate::Starting; - QMetaObject::invokeMethod(this, "_q_start", Qt::QueuedConnection); - break; - case QStateMachinePrivate::Starting: - break; - case QStateMachinePrivate::Running: - qWarning("QStateMachine::start(): already running"); - break; - } -} - -/*! - Stops this state machine. The state machine will stop processing events and - then emit the stopped() signal. - - \sa stopped(), start() -*/ -void QStateMachine::stop() -{ - Q_D(QStateMachine); - switch (d->state) { - case QStateMachinePrivate::NotRunning: - break; - case QStateMachinePrivate::Starting: - // the machine will exit as soon as it enters the event processing loop - d->stop = true; - break; - case QStateMachinePrivate::Running: - d->stop = true; - d->scheduleProcess(); - break; - } -} - -/*! - Posts the given \a event for processing by this state machine, with a delay - of \a delay milliseconds. - - This function returns immediately. The event is added to the state machine's - event queue. Events are processed in the order posted. The state machine - takes ownership of the event and deletes it once it has been processed. - - You can only post events when the state machine is running. -*/ -void QStateMachine::postEvent(QEvent *event, int delay) -{ - Q_D(QStateMachine); - if (d->state != QStateMachinePrivate::Running) { - qWarning("QStateMachine::postEvent: cannot post event when the state machine is not running"); - return; - } -#ifdef QSTATEMACHINE_DEBUG - qDebug() << this << ": posting external event" << event << "with delay" << delay; -#endif - if (delay) { - int tid = startTimer(delay); - d->delayedEvents[tid] = event; - } else { - d->externalEventQueue.append(event); - d->scheduleProcess(); - } -} - -/*! - \internal - - Posts the given internal \a event for processing by this state machine. -*/ -void QStateMachine::postInternalEvent(QEvent *event) -{ - Q_D(QStateMachine); -#ifdef QSTATEMACHINE_DEBUG - qDebug() << this << ": posting internal event" << event; -#endif - d->internalEventQueue.append(event); - d->scheduleProcess(); -} - -/*! - \internal - - Returns the maximal consistent set of states (including parallel and final - states) that this state machine is currently in. If a state \c s is in the - configuration, it is always the case that the parent of \c s is also in - c. Note, however, that the rootState() is not an explicit member of the - configuration. -*/ -QSet QStateMachine::configuration() const -{ - Q_D(const QStateMachine); - return d->configuration; -} - -/*! - \fn QStateMachine::started() - - This signal is emitted when the state machine has entered its initial state - (QStateMachine::initialState). - - \sa QStateMachine::finished(), QStateMachine::start() -*/ - -/*! - \fn QStateMachine::finished() - - This signal is emitted when the state machine has reached a top-level final - state (QFinalState). - - \sa QStateMachine::started() -*/ - -/*! - \fn QStateMachine::stopped() - - This signal is emitted when the state machine has stopped. - - \sa QStateMachine::stop(), QStateMachine::finished() -*/ - -/*! - \reimp -*/ -bool QStateMachine::event(QEvent *e) -{ - Q_D(QStateMachine); - if (e->type() == QEvent::Timer) { - QTimerEvent *te = static_cast(e); - int tid = te->timerId(); - if (d->delayedEvents.contains(tid)) { - killTimer(tid); - QEvent *ee = d->delayedEvents.take(tid); - d->externalEventQueue.append(ee); - d->scheduleProcess(); - return true; - } - } else if (e->type() == QEvent::ChildAdded) { - QChildEvent *ce = static_cast(e); - if (QAbstractState *state = qobject_cast(ce->child())) { - if (state != rootState()) { - state->setParent(rootState()); - return true; - } - } - } - return QObject::event(e); -} - -#ifndef QT_NO_STATEMACHINE_EVENTFILTER -/*! - \reimp -*/ -bool QStateMachine::eventFilter(QObject *watched, QEvent *event) -{ - Q_D(QStateMachine); - Q_ASSERT(d->qobjectEvents.contains(watched)); - if (d->qobjectEvents[watched].contains(event->type())) - postEvent(new QWrappedEvent(watched, d->handler->cloneEvent(event))); - return false; -} -#endif - -/*! - \internal - - This function is called when the state machine is about to select - transitions based on the given \a event. - - The default implementation does nothing. -*/ -void QStateMachine::beginSelectTransitions(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \internal - - This function is called when the state machine has finished selecting - transitions based on the given \a event. - - The default implementation does nothing. -*/ -void QStateMachine::endSelectTransitions(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \internal - - This function is called when the state machine is about to do a microstep. - - The default implementation does nothing. -*/ -void QStateMachine::beginMicrostep(QEvent *event) -{ - Q_UNUSED(event); -} - -/*! - \internal - - This function is called when the state machine has finished doing a - microstep. - - The default implementation does nothing. -*/ -void QStateMachine::endMicrostep(QEvent *event) -{ - Q_UNUSED(event); -} - -#ifndef QT_NO_ANIMATION - -/*! - Returns whether animations are enabled for this state machine. -*/ -bool QStateMachine::animationsEnabled() const -{ - Q_D(const QStateMachine); - return d->animationsEnabled; -} - -/*! - Sets whether animations are \a enabled for this state machine. -*/ -void QStateMachine::setAnimationsEnabled(bool enabled) -{ - Q_D(QStateMachine); - d->animationsEnabled = enabled; -} - -/*! - Adds a default \a animation to be considered for any transition. -*/ -void QStateMachine::addDefaultAnimation(QAbstractAnimation *animation) -{ - Q_D(QStateMachine); - d->defaultAnimations.append(animation); -} - -/*! - Returns the list of default animations that will be considered for any transition. -*/ -QList QStateMachine::defaultAnimations() const -{ - Q_D(const QStateMachine); - return d->defaultAnimations; -} - -/*! - Removes \a animation from the list of default animations. -*/ -void QStateMachine::removeDefaultAnimation(QAbstractAnimation *animation) -{ - Q_D(QStateMachine); - d->defaultAnimations.removeAll(animation); -} - -#endif // QT_NO_ANIMATION - - -static const uint qt_meta_data_QSignalEventGenerator[] = { - - // content: - 2, // revision - 0, // classname - 0, 0, // classinfo - 1, 12, // methods - 0, 0, // properties - 0, 0, // enums/sets - 0, 0, // constructors - - // slots: signature, parameters, type, tag, flags - 23, 22, 22, 22, 0x0a, - - 0 // eod -}; - -static const char qt_meta_stringdata_QSignalEventGenerator[] = { - "QSignalEventGenerator\0\0execute()\0" -}; - -const QMetaObject QSignalEventGenerator::staticMetaObject = { - { &QObject::staticMetaObject, qt_meta_stringdata_QSignalEventGenerator, - qt_meta_data_QSignalEventGenerator, 0 } -}; - -const QMetaObject *QSignalEventGenerator::metaObject() const -{ - return &staticMetaObject; -} - -void *QSignalEventGenerator::qt_metacast(const char *_clname) -{ - if (!_clname) return 0; - if (!strcmp(_clname, qt_meta_stringdata_QSignalEventGenerator)) - return static_cast(const_cast< QSignalEventGenerator*>(this)); - return QObject::qt_metacast(_clname); -} - -int QSignalEventGenerator::qt_metacall(QMetaObject::Call _c, int _id, void **_a) -{ - _id = QObject::qt_metacall(_c, _id, _a); - if (_id < 0) - return _id; - if (_c == QMetaObject::InvokeMetaMethod) { - switch (_id) { - case 0: { -// ### in Qt 4.6 we can use QObject::senderSignalIndex() - int signalIndex = senderSignalIndex(this); - Q_ASSERT(signalIndex != -1); - QStateMachine *machine = qobject_cast(parent()); - QStateMachinePrivate::get(machine)->handleTransitionSignal(sender(), signalIndex, _a); - break; - } - default: ; - } - _id -= 1; - } - return _id; -} - -QSignalEventGenerator::QSignalEventGenerator(QStateMachine *parent) - : QObject(parent) -{ -} - -/*! - \class QSignalEvent - - \brief The QSignalEvent class represents a Qt signal event. - - \since 4.6 - \ingroup statemachine - - A signal event is generated by a QStateMachine in response to a Qt - signal. The QSignalTransition class provides a transition associated with a - signal event. QSignalEvent is part of \l{The State Machine Framework}. - - The sender() function returns the object that generated the signal. The - signalIndex() function returns the index of the signal. The arguments() - function returns the arguments of the signal. - - \sa QSignalTransition -*/ - -/*! - \internal - - Constructs a new QSignalEvent object with the given \a sender, \a - signalIndex and \a arguments. -*/ -QSignalEvent::QSignalEvent(const QObject *sender, int signalIndex, - const QList &arguments) - : QEvent(QEvent::Signal), m_sender(sender), - m_signalIndex(signalIndex), m_arguments(arguments) -{ -} - -/*! - Destroys this QSignalEvent. -*/ -QSignalEvent::~QSignalEvent() -{ -} - -/*! - \fn QSignalEvent::sender() const - - Returns the object that emitted the signal. - - \sa QObject::sender() -*/ - -/*! - \fn QSignalEvent::signalIndex() const - - Returns the index of the signal. - - \sa QMetaObject::indexOfSignal(), QMetaObject::method() -*/ - -/*! - \fn QSignalEvent::arguments() const - - Returns the arguments of the signal. -*/ - - -/*! - \class QWrappedEvent - - \brief The QWrappedEvent class holds a clone of an event associated with a QObject. - - \since 4.6 - \ingroup statemachine - - A wrapped event is generated by a QStateMachine in response to a Qt - event. The QEventTransition class provides a transition associated with a - such an event. QWrappedEvent is part of \l{The State Machine Framework}. - - The object() function returns the object that generated the event. The - event() function returns a clone of the original event. - - \sa QEventTransition -*/ - -/*! - \internal - - Constructs a new QWrappedEvent object with the given \a object - and \a event. -*/ -QWrappedEvent::QWrappedEvent(QObject *object, QEvent *event) - : QEvent(QEvent::Wrapped), m_object(object), m_event(event) -{ -} - -/*! - Destroys this QWrappedEvent. -*/ -QWrappedEvent::~QWrappedEvent() -{ -} - -/*! - \fn QWrappedEvent::object() const - - Returns the object that the event is associated with. -*/ - -/*! - \fn QWrappedEvent::event() const - - Returns a clone of the original event. -*/ - -QT_END_NAMESPACE - -#include "moc_qstatemachine.cpp" diff --git a/src/corelib/statemachine/qstatemachine.h b/src/corelib/statemachine/qstatemachine.h deleted file mode 100644 index 2a98a9a..0000000 --- a/src/corelib/statemachine/qstatemachine.h +++ /dev/null @@ -1,166 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSTATEMACHINE_H -#define QSTATEMACHINE_H - -#include - -#include -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QEvent; -class QAbstractState; -class QState; - -class QStateMachinePrivate; -class QAbstractAnimation; -class QAbstractState; -class Q_CORE_EXPORT QStateMachine : public QObject -{ - Q_OBJECT - Q_PROPERTY(QState* rootState READ rootState) - Q_PROPERTY(QAbstractState* initialState READ initialState WRITE setInitialState) - Q_PROPERTY(QAbstractState* errorState READ errorState WRITE setErrorState) - Q_PROPERTY(QString errorString READ errorString) - Q_PROPERTY(RestorePolicy globalRestorePolicy READ globalRestorePolicy WRITE setGlobalRestorePolicy) - Q_ENUMS(RestorePolicy) -#ifndef QT_NO_ANIMATION - Q_PROPERTY(bool animationsEnabled READ animationsEnabled WRITE setAnimationsEnabled) -#endif -public: - enum RestorePolicy { - DoNotRestoreProperties, - RestoreProperties - }; - - enum Error { - NoError, - NoInitialStateError, - NoDefaultStateInHistoryStateError, - NoCommonAncestorForTransitionError - }; - - QStateMachine(QObject *parent = 0); - ~QStateMachine(); - - void addState(QAbstractState *state); - void removeState(QAbstractState *state); - - QState *rootState() const; - - QAbstractState *initialState() const; - void setInitialState(QAbstractState *state); - - QAbstractState *errorState() const; - void setErrorState(QAbstractState *state); - - Error error() const; - QString errorString() const; - void clearError(); - - bool isRunning() const; - -#ifndef QT_NO_ANIMATION - bool animationsEnabled() const; - void setAnimationsEnabled(bool enabled); - - void addDefaultAnimation(QAbstractAnimation *animation); - QList defaultAnimations() const; - void removeDefaultAnimation(QAbstractAnimation *animation); -#endif // QT_NO_ANIMATION - - QStateMachine::RestorePolicy globalRestorePolicy() const; - void setGlobalRestorePolicy(QStateMachine::RestorePolicy restorePolicy); - - void postEvent(QEvent *event, int delay = 0); - - QSet configuration() const; - -#ifndef QT_NO_STATEMACHINE_EVENTFILTER - bool eventFilter(QObject *watched, QEvent *event); -#endif - -public Q_SLOTS: - void start(); - void stop(); - -Q_SIGNALS: - void started(); - void stopped(); - void finished(); - -protected: - void postInternalEvent(QEvent *event); - - virtual void beginSelectTransitions(QEvent *event); - virtual void endSelectTransitions(QEvent *event); - - virtual void beginMicrostep(QEvent *event); - virtual void endMicrostep(QEvent *event); - - bool event(QEvent *e); - -protected: - QStateMachine(QStateMachinePrivate &dd, QObject *parent); - -private: - Q_DISABLE_COPY(QStateMachine) - Q_DECLARE_PRIVATE(QStateMachine) - Q_PRIVATE_SLOT(d_func(), void _q_start()) - Q_PRIVATE_SLOT(d_func(), void _q_process()) -#ifndef QT_NO_ANIMATION - Q_PRIVATE_SLOT(d_func(), void _q_animationFinished()) -#endif -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/qstatemachine_p.h b/src/corelib/statemachine/qstatemachine_p.h deleted file mode 100644 index dfa5575..0000000 --- a/src/corelib/statemachine/qstatemachine_p.h +++ /dev/null @@ -1,217 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSTATEMACHINE_P_H -#define QSTATEMACHINE_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include -#include -#include -#include -#include - -#include "qstate.h" -#include "qstate_p.h" - -QT_BEGIN_NAMESPACE - -class QEvent; -#ifndef QT_NO_STATEMACHINE_EVENTFILTER -class QEventTransition; -#endif -class QSignalEventGenerator; -class QSignalTransition; -class QAbstractState; -class QAbstractTransition; -class QState; - -#ifndef QT_NO_ANIMATION -class QAbstractAnimation; -#endif - -class QStateMachine; -class Q_CORE_EXPORT QStateMachinePrivate - : public QObjectPrivate -{ - Q_DECLARE_PUBLIC(QStateMachine) -public: - enum State { - NotRunning, - Starting, - Running - }; - enum StopProcessingReason { - EventQueueEmpty, - Finished, - Stopped - }; - - QStateMachinePrivate(); - ~QStateMachinePrivate(); - - static QStateMachinePrivate *get(QStateMachine *q); - - static QState *findLCA(const QList &states); - - static bool stateEntryLessThan(QAbstractState *s1, QAbstractState *s2); - static bool stateExitLessThan(QAbstractState *s1, QAbstractState *s2); - - QAbstractState *findErrorState(QAbstractState *context); - void setError(QStateMachine::Error error, QAbstractState *currentContext); - - // private slots - void _q_start(); - void _q_process(); -#ifndef QT_NO_ANIMATION - void _q_animationFinished(); -#endif - - void microstep(QEvent *event, const QList &transitionList); - bool isPreempted(const QAbstractState *s, const QSet &transitions) const; - QSet selectTransitions(QEvent *event) const; - QList exitStates(QEvent *event, const QList &transitionList); - void executeTransitionContent(QEvent *event, const QList &transitionList); - QList enterStates(QEvent *event, const QList &enabledTransitions); - void addStatesToEnter(QAbstractState *s, QState *root, - QSet &statesToEnter, - QSet &statesForDefaultEntry); - - void applyProperties(const QList &transitionList, - const QList &exitedStates, - const QList &enteredStates); - - bool isInFinalState(QAbstractState *s) const; - static bool isFinal(const QAbstractState *s); - static bool isParallel(const QAbstractState *s); - static bool isCompound(const QAbstractState *s); - static bool isAtomic(const QAbstractState *s); - static bool isDescendantOf(const QAbstractState *s, const QAbstractState *other); - static QList properAncestors(const QAbstractState *s, const QState *upperBound); - - void registerTransitions(QAbstractState *state); - void registerSignalTransition(QSignalTransition *transition); - void unregisterSignalTransition(QSignalTransition *transition); -#ifndef QT_NO_STATEMACHINE_EVENTFILTER - void registerEventTransition(QEventTransition *transition); - void unregisterEventTransition(QEventTransition *transition); -#endif - void unregisterTransition(QAbstractTransition *transition); - void unregisterAllTransitions(); - void handleTransitionSignal(const QObject *sender, int signalIndex, - void **args); - void scheduleProcess(); - - typedef QPair RestorableId; - QHash registeredRestorables; - void registerRestorable(QObject *object, const QByteArray &propertyName); - void unregisterRestorable(QObject *object, const QByteArray &propertyName); - bool hasRestorable(QObject *object, const QByteArray &propertyName) const; - QVariant restorableValue(QObject *object, const QByteArray &propertyName) const; - QList restorablesToPropertyList(const QHash &restorables) const; - - State state; - bool processing; - bool processingScheduled; - bool stop; - StopProcessingReason stopProcessingReason; - QState *rootState; - QSet configuration; - QList internalEventQueue; - QList externalEventQueue; - - QStateMachine::Error error; - QStateMachine::RestorePolicy globalRestorePolicy; - - QString errorString; - QSet pendingErrorStates; - QSet pendingErrorStatesForDefaultEntry; - QAbstractState *initialErrorStateForRoot; - -#ifndef QT_NO_ANIMATION - bool animationsEnabled; - - QPair, QList > - initializeAnimation(QAbstractAnimation *abstractAnimation, - const QPropertyAssignment &prop); - - QHash > animationsForState; - QHash propertyForAnimation; - QHash stateForAnimation; - QSet resetAnimationEndValues; - - QList defaultAnimations; - QMultiHash defaultAnimationsForSource; - QMultiHash defaultAnimationsForTarget; - -#endif // QT_NO_ANIMATION - - QSignalEventGenerator *signalEventGenerator; - - QHash > connections; -#ifndef QT_NO_STATEMACHINE_EVENTFILTER - QHash > qobjectEvents; -#endif - QHash delayedEvents; - - typedef QEvent* (*f_cloneEvent)(QEvent*); - struct Handler { - f_cloneEvent cloneEvent; - }; - - static const Handler *handler; -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/corelib/statemachine/qwrappedevent.h b/src/corelib/statemachine/qwrappedevent.h deleted file mode 100644 index b01c608..0000000 --- a/src/corelib/statemachine/qwrappedevent.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QWRAPPEDEVENT_H -#define QWRAPPEDEVENT_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QObject; - -class Q_CORE_EXPORT QWrappedEvent : public QEvent -{ -public: - QWrappedEvent(QObject *object, QEvent *event); - ~QWrappedEvent(); - - inline QObject *object() const { return m_object; } - inline QEvent *event() const { return m_event; } - -private: - QObject *m_object; - QEvent *m_event; - -private: - Q_DISABLE_COPY(QWrappedEvent) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/statemachine/statemachine.pri b/src/corelib/statemachine/statemachine.pri deleted file mode 100644 index 5b19bc1..0000000 --- a/src/corelib/statemachine/statemachine.pri +++ /dev/null @@ -1,30 +0,0 @@ -HEADERS += $$PWD/qstatemachine.h \ - $$PWD/qstatemachine_p.h \ - $$PWD/qsignaleventgenerator_p.h \ - $$PWD/qabstractstate.h \ - $$PWD/qabstractstate_p.h \ - $$PWD/qstate.h \ - $$PWD/qstate_p.h \ - $$PWD/qfinalstate.h \ - $$PWD/qhistorystate.h \ - $$PWD/qhistorystate_p.h \ - $$PWD/qabstracttransition.h \ - $$PWD/qabstracttransition_p.h \ - $$PWD/qsignalevent.h \ - $$PWD/qsignaltransition.h \ - $$PWD/qsignaltransition_p.h - -SOURCES += $$PWD/qstatemachine.cpp \ - $$PWD/qabstractstate.cpp \ - $$PWD/qstate.cpp \ - $$PWD/qfinalstate.cpp \ - $$PWD/qhistorystate.cpp \ - $$PWD/qabstracttransition.cpp \ - $$PWD/qsignaltransition.cpp - -!contains(DEFINES, QT_NO_STATEMACHINE_EVENTFILTER) { -HEADERS += $$PWD/qwrappedevent.h \ - $$PWD/qeventtransition.h \ - $$PWD/qeventtransition_p.h -SOURCES += $$PWD/qeventtransition.cpp -} diff --git a/src/corelib/tools/qeasingcurve.cpp b/src/corelib/tools/qeasingcurve.cpp deleted file mode 100644 index 2b027fc..0000000 --- a/src/corelib/tools/qeasingcurve.cpp +++ /dev/null @@ -1,846 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -/* - -| *property* | *Used for type* | -| period | QEasingCurve::{In,Out,InOut,OutIn}Elastic | -| amplitude | QEasingCurve::{In,Out,InOut,OutIn}Bounce, QEasingCurve::{In,Out,InOut,OutIn}Elastic | -| overshoot | QEasingCurve::{In,Out,InOut,OutIn}Back | - -*/ - - - - -/*! - \class QEasingCurve - \since 4.6 - \ingroup animation - \brief The QEasingCurve class provides easing curves for controlling animation. - - Easing curves describe a function that controls how the speed of the interpolation - between 0 and 1 should be. Easing curves allow transitions from - one value to another to appear more natural than a simple constant speed would allow. - The QEasingCurve class is usually used in conjunction with the QAnimation class, - but can be used on its own. - - To calculate the speed of the interpolation, the easing curve provides the function - valueForProgress(), where the \a progress argument specifies the progress of the - interpolation: 0 is the start value of the interpolation, 1 is the end value of the - interpolation. The returned value is the effective progress of the interpolation. - If the returned value is the same as the input value for all input values the easing - curve is a linear curve. This is the default behaviour. - - For example, - \code - QEasingCurve easing(QEasingCurve::InOutQuad); - - for(qreal t = 0.0; t < 1.0; t+=0.1) - qWarning() << "Effective progress" << t << " is - << easing.valueForProgress(t); - \endcode - will print the effective progress of the interpolation between 0 and 1. - - When using a QAnimation, the easing curve will be used to control the - progress of the interpolation between startValue and endValue: - \code - QAnimation animation; - animation.setStartValue(0); - animation.setEndValue(1000); - animation.setDuration(1000); - animation.setEasingCurve(QEasingCurve::InOutQuad); - \endcode - */ - -/*! - \enum QEasingCurve::Type - - The type of easing curve. - - \value Linear \inlineimage qeasingcurve-linear.png - \br - Easing equation function for a simple linear tweening, - with no easing. - \value InQuad \inlineimage qeasingcurve-inquad.png - \br - Easing equation function for a quadratic (t^2) easing - in: accelerating from zero velocity. - \value OutQuad \inlineimage qeasingcurve-outquad.png - \br - Easing equation function for a quadratic (t^2) easing - out: decelerating to zero velocity. - \value InOutQuad \inlineimage qeasingcurve-inoutquad.png - \br - Easing equation function for a quadratic (t^2) easing - in/out: acceleration until halfway, then deceleration. - \value OutInQuad \inlineimage qeasingcurve-outinquad.png - \br - Easing equation function for a quadratic (t^2) easing - out/in: deceleration until halfway, then acceleration. - \value InCubic \inlineimage qeasingcurve-incubic.png - \br - Easing equation function for a cubic (t^3) easing - in: accelerating from zero velocity. - \value OutCubic \inlineimage qeasingcurve-outcubic.png - \br - Easing equation function for a cubic (t^3) easing - out: decelerating from zero velocity. - \value InOutCubic \inlineimage qeasingcurve-inoutcubic.png - \br - Easing equation function for a cubic (t^3) easing - in/out: acceleration until halfway, then deceleration. - \value OutInCubic \inlineimage qeasingcurve-outincubic.png - \br - Easing equation function for a cubic (t^3) easing - out/in: deceleration until halfway, then acceleration. - \value InQuart \inlineimage qeasingcurve-inquart.png - \br - Easing equation function for a quartic (t^4) easing - in: accelerating from zero velocity. - \value OutQuart \inlineimage qeasingcurve-outquart.png - \br - Easing equation function for a quartic (t^4) easing - out: decelerating from zero velocity. - \value InOutQuart \inlineimage qeasingcurve-inoutquart.png - \br - Easing equation function for a quartic (t^4) easing - in/out: acceleration until halfway, then deceleration. - \value OutInQuart \inlineimage qeasingcurve-outinquart.png - \br - Easing equation function for a quartic (t^4) easing - out/in: deceleration until halfway, then acceleration. - \value InQuint \inlineimage qeasingcurve-inquint.png - \br - Easing equation function for a quintic (t^5) easing - in: accelerating from zero velocity. - \value OutQuint \inlineimage qeasingcurve-outquint.png - \br - Easing equation function for a quintic (t^5) easing - out: decelerating from zero velocity. - \value InOutQuint \inlineimage qeasingcurve-inoutquint.png - \br - Easing equation function for a quintic (t^5) easing - in/out: acceleration until halfway, then deceleration. - \value OutInQuint \inlineimage qeasingcurve-outinquint.png - \br - Easing equation function for a quintic (t^5) easing - out/in: deceleration until halfway, then acceleration. - \value InSine \inlineimage qeasingcurve-insine.png - \br - Easing equation function for a sinusoidal (sin(t)) easing - in: accelerating from zero velocity. - \value OutSine \inlineimage qeasingcurve-outsine.png - \br - Easing equation function for a sinusoidal (sin(t)) easing - out: decelerating from zero velocity. - \value InOutSine \inlineimage qeasingcurve-inoutsine.png - \br - Easing equation function for a sinusoidal (sin(t)) easing - in/out: acceleration until halfway, then deceleration. - \value OutInSine \inlineimage qeasingcurve-outinsine.png - \br - Easing equation function for a sinusoidal (sin(t)) easing - out/in: deceleration until halfway, then acceleration. - \value InExpo \inlineimage qeasingcurve-inexpo.png - \br - Easing equation function for an exponential (2^t) easing - in: accelerating from zero velocity. - \value OutExpo \inlineimage qeasingcurve-outexpo.png - \br - Easing equation function for an exponential (2^t) easing - out: decelerating from zero velocity. - \value InOutExpo \inlineimage qeasingcurve-inoutexpo.png - \br - Easing equation function for an exponential (2^t) easing - in/out: acceleration until halfway, then deceleration. - \value OutInExpo \inlineimage qeasingcurve-outinexpo.png - \br - Easing equation function for an exponential (2^t) easing - out/in: deceleration until halfway, then acceleration. - \value InCirc \inlineimage qeasingcurve-incirc.png - \br - Easing equation function for a circular (sqrt(1-t^2)) easing - in: accelerating from zero velocity. - \value OutCirc \inlineimage qeasingcurve-outcirc.png - \br - Easing equation function for a circular (sqrt(1-t^2)) easing - out: decelerating from zero velocity. - \value InOutCirc \inlineimage qeasingcurve-inoutcirc.png - \br - Easing equation function for a circular (sqrt(1-t^2)) easing - in/out: acceleration until halfway, then deceleration. - \value OutInCirc \inlineimage qeasingcurve-outincirc.png - \br - Easing equation function for a circular (sqrt(1-t^2)) easing - out/in: deceleration until halfway, then acceleration. - \value InElastic \inlineimage qeasingcurve-inelastic.png - \br - Easing equation function for an elastic - (exponentially decaying sine wave) easing in: - accelerating from zero velocity. The peak amplitude - can be set with the \e amplitude parameter, and the - period of decay by the \e period parameter. - \value OutElastic \inlineimage qeasingcurve-outelastic.png - \br - Easing equation function for an elastic - (exponentially decaying sine wave) easing out: - decelerating from zero velocity. The peak amplitude - can be set with the \e amplitude parameter, and the - period of decay by the \e period parameter. - \value InOutElastic \inlineimage qeasingcurve-inoutelastic.png - \br - Easing equation function for an elastic - (exponentially decaying sine wave) easing in/out: - acceleration until halfway, then deceleration. - \value OutInElastic \inlineimage qeasingcurve-outinelastic.png - \br - Easing equation function for an elastic - (exponentially decaying sine wave) easing out/in: - deceleration until halfway, then acceleration. - \value InBack \inlineimage qeasingcurve-inback.png - \br - Easing equation function for a back (overshooting - cubic easing: (s+1)*t^3 - s*t^2) easing in: - accelerating from zero velocity. - \value OutBack \inlineimage qeasingcurve-outback.png - \br - Easing equation function for a back (overshooting - cubic easing: (s+1)*t^3 - s*t^2) easing out: - decelerating from zero velocity. - \value InOutBack \inlineimage qeasingcurve-inoutback.png - \br - Easing equation function for a back (overshooting - cubic easing: (s+1)*t^3 - s*t^2) easing in/out: - acceleration until halfway, then deceleration. - \value OutInBack \inlineimage qeasingcurve-outinback.png - \br - Easing equation function for a back (overshooting - cubic easing: (s+1)*t^3 - s*t^2) easing out/in: - deceleration until halfway, then acceleration. - \value InBounce \inlineimage qeasingcurve-inbounce.png - \br - Easing equation function for a bounce (exponentially - decaying parabolic bounce) easing in: accelerating - from zero velocity. - \value OutBounce \inlineimage qeasingcurve-outbounce.png - \br - Easing equation function for a bounce (exponentially - decaying parabolic bounce) easing out: decelerating - from zero velocity. - \value InOutBounce \inlineimage qeasingcurve-inoutbounce.png - \br - Easing equation function for a bounce (exponentially - decaying parabolic bounce) easing in/out: - acceleration until halfway, then deceleration. - \value OutInBounce \inlineimage qeasingcurve-outinbounce.png - \br - Easing equation function for a bounce (exponentially - decaying parabolic bounce) easing out/in: - deceleration until halfway, then acceleration. - \omitvalue InCurve - \omitvalue OutCurve - \omitvalue SineCurve - \omitvalue CosineCurve - \value Custom This is returned if the user have specified a custom curve type with setCustomType(). Note that you cannot call setType() with this value, but type() can return it. - \omitvalue NCurveTypes -*/ - -/*! - \typedef QEasingCurve::EasingFunction - - This is a typedef for a pointer to a function with the following - signature: - - \snippet doc/src/snippets/code/src_corelib_tools_qeasingcurve.cpp 0 -*/ - -#include "qeasingcurve.h" - -#ifndef QT_NO_DEBUG_STREAM -#include -#include -#endif - -QT_BEGIN_NAMESPACE - -static bool isConfigFunction(QEasingCurve::Type type) -{ - return type >= QEasingCurve::InElastic - && type <= QEasingCurve::OutInBounce; -} - -class QEasingCurveFunction -{ -public: - enum Type { In, Out, InOut, OutIn }; - - QEasingCurveFunction(QEasingCurveFunction::Type type = In, qreal period = 0.3, qreal amplitude = 1.0, - qreal overshoot = 1.70158f) - : _t(type), _p(period), _a(amplitude), _o(overshoot) - { } - virtual ~QEasingCurveFunction() {} - virtual qreal value(qreal t); - virtual QEasingCurveFunction *copy() const; - bool operator==(const QEasingCurveFunction& other); - - Type _t; - qreal _p; - qreal _a; - qreal _o; -}; - -qreal QEasingCurveFunction::value(qreal t) -{ - return t; -} - -QEasingCurveFunction *QEasingCurveFunction::copy() const -{ - return new QEasingCurveFunction(_t, _p, _a, _o); -} - -bool QEasingCurveFunction::operator==(const QEasingCurveFunction& other) -{ - return _t == other._t && - _p == other._p && - _a == other._a && - _o == other._o; -} - -QT_BEGIN_INCLUDE_NAMESPACE -#include "../../3rdparty/easing/easing.cpp" -QT_END_INCLUDE_NAMESPACE - -class QEasingCurvePrivate -{ -public: - QEasingCurvePrivate() - : type(QEasingCurve::Linear), - config(0), - func(&easeNone) - { } - ~QEasingCurvePrivate() { delete config; } - void setType_helper(QEasingCurve::Type); - - QEasingCurve::Type type; - QEasingCurveFunction *config; - QEasingCurve::EasingFunction func; -}; - -struct ElasticEase : public QEasingCurveFunction -{ - ElasticEase(Type type) - : QEasingCurveFunction(type, qreal(0.3), qreal(1.0)) - { } - - QEasingCurveFunction *copy() const - { - ElasticEase *rv = new ElasticEase(_t); - rv->_p = _p; - rv->_a = _a; - return rv; - } - - qreal value(qreal t) - { - qreal p = (_p < 0) ? 0.3f : _p; - qreal a = (_a < 0) ? 1.0f : _a; - switch(_t) { - case In: - return easeInElastic(t, a, p); - case Out: - return easeOutElastic(t, a, p); - case InOut: - return easeInOutElastic(t, a, p); - case OutIn: - return easeOutInElastic(t, a, p); - default: - return t; - } - } -}; - -struct BounceEase : public QEasingCurveFunction -{ - BounceEase(Type type) - : QEasingCurveFunction(type, 0.3f, 1.0f) - { } - - QEasingCurveFunction *copy() const - { - BounceEase *rv = new BounceEase(_t); - rv->_a = _a; - return rv; - } - - qreal value(qreal t) - { - qreal a = (_a < 0) ? 1.0f : _a; - switch(_t) { - case In: - return easeInBounce(t, a); - case Out: - return easeOutBounce(t, a); - case InOut: - return easeInOutBounce(t, a); - case OutIn: - return easeOutInBounce(t, a); - default: - return t; - } - } -}; - -struct BackEase : public QEasingCurveFunction -{ - BackEase(Type type) - : QEasingCurveFunction(type, 0.3f, 1.0f, 1.70158f) - { } - - QEasingCurveFunction *copy() const - { - BackEase *rv = new BackEase(_t); - rv->_o = _o; - return rv; - } - - qreal value(qreal t) - { - qreal o = (_o < 0) ? 1.70158f : _o; - switch(_t) { - case In: - return easeInBack(t, o); - case Out: - return easeOutBack(t, o); - case InOut: - return easeInOutBack(t, o); - case OutIn: - return easeOutInBack(t, o); - default: - return t; - } - } -}; - -static QEasingCurve::EasingFunction curveToFunc(QEasingCurve::Type curve) -{ - switch(curve) { - case QEasingCurve::Linear: - return &easeNone; - case QEasingCurve::InQuad: - return &easeInQuad; - case QEasingCurve::OutQuad: - return &easeOutQuad; - case QEasingCurve::InOutQuad: - return &easeInOutQuad; - case QEasingCurve::OutInQuad: - return &easeOutInQuad; - case QEasingCurve::InCubic: - return &easeInCubic; - case QEasingCurve::OutCubic: - return &easeOutCubic; - case QEasingCurve::InOutCubic: - return &easeInOutCubic; - case QEasingCurve::OutInCubic: - return &easeOutInCubic; - case QEasingCurve::InQuart: - return &easeInQuart; - case QEasingCurve::OutQuart: - return &easeOutQuart; - case QEasingCurve::InOutQuart: - return &easeInOutQuart; - case QEasingCurve::OutInQuart: - return &easeOutInQuart; - case QEasingCurve::InQuint: - return &easeInQuint; - case QEasingCurve::OutQuint: - return &easeOutQuint; - case QEasingCurve::InOutQuint: - return &easeInOutQuint; - case QEasingCurve::OutInQuint: - return &easeOutInQuint; - case QEasingCurve::InSine: - return &easeInSine; - case QEasingCurve::OutSine: - return &easeOutSine; - case QEasingCurve::InOutSine: - return &easeInOutSine; - case QEasingCurve::OutInSine: - return &easeOutInSine; - case QEasingCurve::InExpo: - return &easeInExpo; - case QEasingCurve::OutExpo: - return &easeOutExpo; - case QEasingCurve::InOutExpo: - return &easeInOutExpo; - case QEasingCurve::OutInExpo: - return &easeOutInExpo; - case QEasingCurve::InCirc: - return &easeInCirc; - case QEasingCurve::OutCirc: - return &easeOutCirc; - case QEasingCurve::InOutCirc: - return &easeInOutCirc; - case QEasingCurve::OutInCirc: - return &easeOutInCirc; - // Internal for, compatibility with QTimeLine only ?? - case QEasingCurve::InCurve: - return &easeInCurve; - case QEasingCurve::OutCurve: - return &easeOutCurve; - case QEasingCurve::SineCurve: - return &easeSineCurve; - case QEasingCurve::CosineCurve: - return &easeCosineCurve; - default: - return 0; - }; -} - -static QEasingCurveFunction *curveToFunctionObject(QEasingCurve::Type type) -{ - QEasingCurveFunction *curveFunc = 0; - switch(type) { - case QEasingCurve::InElastic: - curveFunc = new ElasticEase(ElasticEase::In); - break; - case QEasingCurve::OutElastic: - curveFunc = new ElasticEase(ElasticEase::Out); - break; - case QEasingCurve::InOutElastic: - curveFunc = new ElasticEase(ElasticEase::InOut); - break; - case QEasingCurve::OutInElastic: - curveFunc = new ElasticEase(ElasticEase::OutIn); - break; - case QEasingCurve::OutBounce: - curveFunc = new BounceEase(BounceEase::Out); - break; - case QEasingCurve::InBounce: - curveFunc = new BounceEase(BounceEase::In); - break; - case QEasingCurve::OutInBounce: - curveFunc = new BounceEase(BounceEase::OutIn); - break; - case QEasingCurve::InOutBounce: - curveFunc = new BounceEase(BounceEase::InOut); - break; - case QEasingCurve::InBack: - curveFunc = new BackEase(BackEase::In); - break; - case QEasingCurve::OutBack: - curveFunc = new BackEase(BackEase::Out); - break; - case QEasingCurve::InOutBack: - curveFunc = new BackEase(BackEase::InOut); - break; - case QEasingCurve::OutInBack: - curveFunc = new BackEase(BackEase::OutIn); - break; - default: - curveFunc = new QEasingCurveFunction(QEasingCurveFunction::In, 0.3f, 1.0f, 1.70158f); // ### - } - - return curveFunc; -} - -/*! - Constructs an easing curve of the given \a type. - */ -QEasingCurve::QEasingCurve(Type type) - : d_ptr(new QEasingCurvePrivate) -{ - setType(type); -} - -/*! - Construct a copy of \a other. - */ -QEasingCurve::QEasingCurve(const QEasingCurve &other) -: d_ptr(new QEasingCurvePrivate) -{ - // ### non-atomic, requires malloc on shallow copy - *d_ptr = *other.d_ptr; - if(other.d_ptr->config) - d_ptr->config = other.d_ptr->config->copy(); -} - -/*! - Destructor. - */ - -QEasingCurve::~QEasingCurve() -{ - delete d_ptr; -} - -/*! - Copy \a other. - */ -QEasingCurve &QEasingCurve::operator=(const QEasingCurve &other) -{ - // ### non-atomic, requires malloc on shallow copy - if (d_ptr->config) { - delete d_ptr->config; - d_ptr->config = 0; - } - - *d_ptr = *other.d_ptr; - if(other.d_ptr->config) - d_ptr->config = other.d_ptr->config->copy(); - - return *this; -} - -/*! - Compare this easing curve with \a other and returns true if they are - equal. It will also compare the properties of a curve. - */ -bool QEasingCurve::operator==(const QEasingCurve &other) const -{ - bool res = d_ptr->func == other.d_ptr->func - && d_ptr->type == other.d_ptr->type; - if (res && d_ptr->config && other.d_ptr->config) { - // catch the config content - res = d_ptr->config->operator==(*(other.d_ptr->config)); - } - return res; -} - -/*! - \fn bool QEasingCurve::operator!=(const QEasingCurve &other) const - Compare this easing curve with \a other and returns true if they are not equal. - It will also compare the properties of a curve. - - \sa operator==() -*/ - -/*! - Returns the amplitude. This is not applicable for all curve types. - It is only applicable for bounce and elastic curves (curves of type() - QEasingCurve::InBounce, QEasingCurve::OutBounce, QEasingCurve::InOutBounce, - QEasingCurve::OutInBounce, QEasingCurve::InElastic, QEasingCurve::OutElastic, - QEasingCurve::InOutElastic or QEasingCurve::OutInElastic). - */ -qreal QEasingCurve::amplitude() const -{ - return d_ptr->config ? d_ptr->config->_a : 1.0; -} - -/*! - Sets the amplitude to \a amplitude. - - This will set the amplitude of the bounce or the amplitude of the - elastic "spring" effect. The higher the number, the higher the amplitude. - \sa amplitude() -*/ -void QEasingCurve::setAmplitude(qreal amplitude) -{ - if (!d_ptr->config) - d_ptr->config = curveToFunctionObject(d_ptr->type); - d_ptr->config->_a = amplitude; -} - -/*! - Returns the period. This is not applicable for all curve types. - It is only applicable if type() is QEasingCurve::InElastic, QEasingCurve::OutElastic, - QEasingCurve::InOutElastic or QEasingCurve::OutInElastic. - */ -qreal QEasingCurve::period() const -{ - return d_ptr->config ? d_ptr->config->_p : 0.3; -} - -/*! - Sets the period to \a period. - Setting a small period value will give a high frequency of the curve. A - large period will give it a small frequency. - - \sa period() -*/ -void QEasingCurve::setPeriod(qreal period) -{ - if (!d_ptr->config) - d_ptr->config = curveToFunctionObject(d_ptr->type); - d_ptr->config->_p = period; -} - -/*! - Returns the overshoot. This is not applicable for all curve types. - It is only applicable if type() is QEasingCurve::InBack, QEasingCurve::OutBack, - QEasingCurve::InOutBack or QEasingCurve::OutInBack. - */ -qreal QEasingCurve::overshoot() const -{ - return d_ptr->config ? d_ptr->config->_o : 1.70158f; -} - -/*! - Sets the overshoot to \a overshoot. - - 0 produces no overshoot, and the default value of 1.70158 produces an overshoot of 10 percent. - - \sa overshoot() -*/ -void QEasingCurve::setOvershoot(qreal overshoot) -{ - if (!d_ptr->config) - d_ptr->config = curveToFunctionObject(d_ptr->type); - d_ptr->config->_o = overshoot; -} - -/*! - Returns the type of the easing curve. -*/ -QEasingCurve::Type QEasingCurve::type() const -{ - return d_ptr->type; -} - -void QEasingCurvePrivate::setType_helper(QEasingCurve::Type newType) -{ - qreal amp = -1.0; - qreal period = -1.0; - qreal overshoot = -1.0; - - if (config) { - amp = config->_a; - period = config->_p; - overshoot = config->_o; - delete config; - config = 0; - } - - if (isConfigFunction(newType) || (amp != -1.0) || (period != -1.0) || (overshoot != -1.0)) { - config = curveToFunctionObject(newType); - if (amp != -1.0) - config->_a = amp; - if (period != -1.0) - config->_p = period; - if (overshoot != -1.0) - config->_o = overshoot; - func = 0; - } else if (newType != QEasingCurve::Custom) { - func = curveToFunc(newType); - } - Q_ASSERT((func == 0) == (config != 0)); - type = newType; -} - -/*! - Sets the type of the easing curve to \a type. -*/ -void QEasingCurve::setType(Type type) -{ - if (d_ptr->type == type) - return; - if (type < Linear || type >= NCurveTypes - 1) { - qWarning("QEasingCurve: Invalid curve type %d", type); - return; - } - - d_ptr->setType_helper(type); -} - -/*! - Sets a custom easing curve that is defined by the user in the function \a func. - The signature of the function is qreal myEasingFunction(qreal progress), - where \e progress and the return value is considered to be normalized between 0 and 1. - (In some cases the return value can be outside that range) - After calling this function type() will return QEasingCurve::Custom. - \a func cannot be zero. - - \sa customType() - \sa valueForProgress() -*/ -void QEasingCurve::setCustomType(EasingFunction func) -{ - if (!func) { - qWarning("Function pointer must not be null"); - return; - } - d_ptr->func = func; - d_ptr->setType_helper(Custom); -} - -/*! - Returns the function pointer to the custom easing curve. - If type() does not return QEasingCurve::Custom, this function - will return 0. -*/ -QEasingCurve::EasingFunction QEasingCurve::customType() const -{ - return d_ptr->type == Custom ? d_ptr->func : 0; -} - -/*! - Return the effective progress for the easing curve at \a progress. - While \a progress must be between 0 and 1, the returned effective progress - can be outside those bounds. For instance, QEasingCurve::InBack will - return negative values in the beginning of the function. - */ -qreal QEasingCurve::valueForProgress(qreal progress) const -{ - progress = qBound(0, progress, 1); - if (d_ptr->func) - return d_ptr->func(progress); - else if (d_ptr->config) - return d_ptr->config->value(progress); - else - return progress; -} - -#ifndef QT_NO_DEBUG_STREAM -QDebug operator<<(QDebug debug, const QEasingCurve &item) -{ - debug << "type:" << item.d_ptr->type - << "func:" << item.d_ptr->func; - if (item.d_ptr->config) { - debug << QString::fromAscii("period:%1").arg(item.d_ptr->config->_p, 0, 'f', 20) - << QString::fromAscii("amp:%1").arg(item.d_ptr->config->_a, 0, 'f', 20) - << QString::fromAscii("overshoot:%1").arg(item.d_ptr->config->_o, 0, 'f', 20); - } - return debug; -} -#endif - -QT_END_NAMESPACE diff --git a/src/corelib/tools/qeasingcurve.h b/src/corelib/tools/qeasingcurve.h deleted file mode 100644 index a240bc0..0000000 --- a/src/corelib/tools/qeasingcurve.h +++ /dev/null @@ -1,114 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QEASINGCURVE_H -#define QEASINGCURVE_H - -#include -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QEasingCurvePrivate; -class Q_CORE_EXPORT QEasingCurve -{ - Q_GADGET - Q_ENUMS(Type) -public: - enum Type { - Linear, - InQuad, OutQuad, InOutQuad, OutInQuad, - InCubic, OutCubic, InOutCubic, OutInCubic, - InQuart, OutQuart, InOutQuart, OutInQuart, - InQuint, OutQuint, InOutQuint, OutInQuint, - InSine, OutSine, InOutSine, OutInSine, - InExpo, OutExpo, InOutExpo, OutInExpo, - InCirc, OutCirc, InOutCirc, OutInCirc, - InElastic, OutElastic, InOutElastic, OutInElastic, - InBack, OutBack, InOutBack, OutInBack, - InBounce, OutBounce, InOutBounce, OutInBounce, - InCurve, OutCurve, SineCurve, CosineCurve, - Custom, NCurveTypes - }; - - QEasingCurve(Type type = Linear); - QEasingCurve(const QEasingCurve &other); - ~QEasingCurve(); - - QEasingCurve &operator=(const QEasingCurve &other); - bool operator==(const QEasingCurve &other) const; - inline bool operator!=(const QEasingCurve &other) const - { return !(this->operator==(other)); } - - qreal amplitude() const; - void setAmplitude(qreal amplitude); - - qreal period() const; - void setPeriod(qreal period); - - qreal overshoot() const; - void setOvershoot(qreal overshoot); - - Type type() const; - void setType(Type type); - typedef qreal (*EasingFunction)(qreal progress); - void setCustomType(EasingFunction func); - EasingFunction customType() const; - - qreal valueForProgress(qreal progress) const; -private: - QEasingCurvePrivate *d_ptr; - friend Q_CORE_EXPORT QDebug operator<<(QDebug debug, const QEasingCurve &item); -}; - -#ifndef QT_NO_DEBUG_STREAM -Q_CORE_EXPORT QDebug operator<<(QDebug debug, const QEasingCurve &item); -#endif - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/corelib/tools/qtimeline.cpp b/src/corelib/tools/qtimeline.cpp index ee4f73c..3a03558 100644 --- a/src/corelib/tools/qtimeline.cpp +++ b/src/corelib/tools/qtimeline.cpp @@ -48,6 +48,20 @@ QT_BEGIN_NAMESPACE +static const qreal pi = qreal(3.14159265359); +static const qreal halfPi = pi / qreal(2.0); + + +static inline qreal qt_sinProgress(qreal value) +{ + return qSin((value * pi) - halfPi) / 2 + qreal(0.5); +} + +static inline qreal qt_smoothBeginEndMixFactor(qreal value) +{ + return qMin(qMax(1 - value * 2 + qreal(0.3), qreal(0.0)), qreal(1.0)); +} + class QTimeLinePrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QTimeLine) @@ -56,7 +70,7 @@ public: : startTime(0), duration(1000), startFrame(0), endFrame(0), updateInterval(1000 / 25), totalLoopCount(1), currentLoopCount(0), currentTime(0), timerId(0), - direction(QTimeLine::Forward), easingCurve(QEasingCurve::InOutSine), + direction(QTimeLine::Forward), curveShape(QTimeLine::EaseInOutCurve), state(QTimeLine::NotRunning) { } @@ -74,7 +88,7 @@ public: QTime timer; QTimeLine::Direction direction; - QEasingCurve easingCurve; + QTimeLine::CurveShape curveShape; QTimeLine::State state; inline void setState(QTimeLine::State newState) { @@ -509,68 +523,12 @@ void QTimeLine::setUpdateInterval(int interval) QTimeLine::CurveShape QTimeLine::curveShape() const { Q_D(const QTimeLine); - switch (d->easingCurve.type()) { - default: - case QEasingCurve::InOutSine: - return EaseInOutCurve; - case QEasingCurve::InCurve: - return EaseInCurve; - case QEasingCurve::OutCurve: - return EaseOutCurve; - case QEasingCurve::Linear: - return LinearCurve; - case QEasingCurve::SineCurve: - return SineCurve; - case QEasingCurve::CosineCurve: - return CosineCurve; - } - return EaseInOutCurve; + return d->curveShape; } - void QTimeLine::setCurveShape(CurveShape shape) { - switch (shape) { - default: - case EaseInOutCurve: - setEasingCurve(QEasingCurve(QEasingCurve::InOutSine)); - break; - case EaseInCurve: - setEasingCurve(QEasingCurve(QEasingCurve::InCurve)); - break; - case EaseOutCurve: - setEasingCurve(QEasingCurve(QEasingCurve::OutCurve)); - break; - case LinearCurve: - setEasingCurve(QEasingCurve(QEasingCurve::Linear)); - break; - case SineCurve: - setEasingCurve(QEasingCurve(QEasingCurve::SineCurve)); - break; - case CosineCurve: - setEasingCurve(QEasingCurve(QEasingCurve::CosineCurve)); - break; - } -} - -/*! - \property QTimeLine::easingCurve - - Specifies the easing curve that the timeline will use. - If both easing curve and curveShape are set, the last set property will - override the previous one. (If valueForTime() is reimplemented it will - override both) -*/ - -QEasingCurve QTimeLine::easingCurve() const -{ - Q_D(const QTimeLine); - return d->easingCurve; -} - -void QTimeLine::setEasingCurve(const QEasingCurve& curve) -{ Q_D(QTimeLine); - d->easingCurve = curve; + d->curveShape = shape; } /*! @@ -650,8 +608,42 @@ qreal QTimeLine::valueForTime(int msec) const Q_D(const QTimeLine); msec = qMin(qMax(msec, 0), d->duration); + // Simple linear interpolation qreal value = msec / qreal(d->duration); - return d->easingCurve.valueForProgress(value); + + switch (d->curveShape) { + case EaseInOutCurve: + value = qt_sinProgress(value); + break; + // SmoothBegin blends Smooth and Linear Interpolation. + // Progress 0 - 0.3 : Smooth only + // Progress 0.3 - ~ 0.5 : Mix of Smooth and Linear + // Progress ~ 0.5 - 1 : Linear only + case EaseInCurve: { + const qreal sinProgress = qt_sinProgress(value); + const qreal linearProgress = value; + const qreal mix = qt_smoothBeginEndMixFactor(value); + value = sinProgress * mix + linearProgress * (1 - mix); + break; + } + case EaseOutCurve: { + const qreal sinProgress = qt_sinProgress(value); + const qreal linearProgress = value; + const qreal mix = qt_smoothBeginEndMixFactor(1 - value); + value = sinProgress * mix + linearProgress * (1 - mix); + break; + } + case SineCurve: + value = (qSin(((msec * pi * 2) / d->duration) - pi/2) + 1) / 2; + break; + case CosineCurve: + value = (qCos(((msec * pi * 2) / d->duration) - pi/2) + 1) / 2; + break; + default: + break; + } + + return value; } /*! diff --git a/src/corelib/tools/qtimeline.h b/src/corelib/tools/qtimeline.h index 48c9232..18c3980 100644 --- a/src/corelib/tools/qtimeline.h +++ b/src/corelib/tools/qtimeline.h @@ -42,7 +42,6 @@ #ifndef QTIMELINE_H #define QTIMELINE_H -#include #include QT_BEGIN_HEADER @@ -61,7 +60,6 @@ class Q_CORE_EXPORT QTimeLine : public QObject Q_PROPERTY(Direction direction READ direction WRITE setDirection) Q_PROPERTY(int loopCount READ loopCount WRITE setLoopCount) Q_PROPERTY(CurveShape curveShape READ curveShape WRITE setCurveShape) - Q_PROPERTY(QEasingCurve easingCurve READ easingCurve WRITE setEasingCurve) public: enum State { NotRunning, @@ -107,9 +105,6 @@ public: CurveShape curveShape() const; void setCurveShape(CurveShape shape); - QEasingCurve easingCurve() const; - void setEasingCurve(const QEasingCurve &curve); - int currentTime() const; int currentFrame() const; qreal currentValue() const; diff --git a/src/corelib/tools/tools.pri b/src/corelib/tools/tools.pri index 90287cb..a6fdac7 100644 --- a/src/corelib/tools/tools.pri +++ b/src/corelib/tools/tools.pri @@ -11,7 +11,6 @@ HEADERS += \ tools/qcryptographichash.h \ tools/qdatetime.h \ tools/qdatetime_p.h \ - tools/qeasingcurve.h \ tools/qhash.h \ tools/qline.h \ tools/qlinkedlist.h \ @@ -47,7 +46,6 @@ SOURCES += \ tools/qbytearraymatcher.cpp \ tools/qcryptographichash.cpp \ tools/qdatetime.cpp \ - tools/qeasingcurve.cpp \ tools/qhash.cpp \ tools/qline.cpp \ tools/qlinkedlist.cpp \ diff --git a/src/gui/animation/animation.pri b/src/gui/animation/animation.pri deleted file mode 100644 index 27763ca..0000000 --- a/src/gui/animation/animation.pri +++ /dev/null @@ -1,3 +0,0 @@ -# Qt gui animation module - -SOURCES += animation/qguivariantanimation.cpp diff --git a/src/gui/animation/qguivariantanimation.cpp b/src/gui/animation/qguivariantanimation.cpp deleted file mode 100644 index 37ca6a1..0000000 --- a/src/gui/animation/qguivariantanimation.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QT_NO_ANIMATION - -#include -#include - -#include - -QT_BEGIN_NAMESPACE - -template<> Q_INLINE_TEMPLATE QColor _q_interpolate(const QColor &f,const QColor &t, qreal progress) -{ - return QColor(_q_interpolate(f.red(), t.red(), progress), - _q_interpolate(f.green(), t.green(), progress), - _q_interpolate(f.blue(), t.blue(), progress), - _q_interpolate(f.alpha(), t.alpha(), progress)); -} - -static int qRegisterGuiGetInterpolator() -{ - qRegisterAnimationInterpolator(_q_interpolateVariant); - return 1; -} -Q_CONSTRUCTOR_FUNCTION(qRegisterGuiGetInterpolator) - -static int qUnregisterGuiGetInterpolator() -{ - qRegisterAnimationInterpolator(0); - return 1; -} -Q_DESTRUCTOR_FUNCTION(qUnregisterGuiGetInterpolator) - -QT_END_NAMESPACE - -#endif //QT_NO_ANIMATION diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 62e0411..b2569c1 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -95,15 +95,6 @@ class Q_AUTOTEST_EXPORT QGraphicsItemPrivate { Q_DECLARE_PUBLIC(QGraphicsItem) public: - struct TransformData - { - TransformData() : rotationX(0),rotationY(0),rotationZ(0),scaleX(1),scaleY(1), dirty(true) {} - QTransform baseTransform; - QTransform transform; - QPointF transformCenter; - qreal rotationX,rotationY,rotationZ,scaleX,scaleY; - bool dirty; - }; enum Extra { ExtraTransform, ExtraToolTip, @@ -248,7 +239,7 @@ public: } } } - + struct ExtraStruct { ExtraStruct(Extra type, QVariant value) : type(type), value(value) @@ -260,7 +251,6 @@ public: bool operator<(Extra extra) const { return type < extra; } }; - QList extras; QGraphicsItemCache *maybeExtraItemCache() const; diff --git a/src/gui/graphicsview/qgraphicsproxywidget.cpp b/src/gui/graphicsview/qgraphicsproxywidget.cpp index a5b11ff..01b7593 100644 --- a/src/gui/graphicsview/qgraphicsproxywidget.cpp +++ b/src/gui/graphicsview/qgraphicsproxywidget.cpp @@ -976,7 +976,6 @@ void QGraphicsProxyWidget::contextMenuEvent(QGraphicsSceneContextMenuEvent *even } #endif // QT_NO_CONTEXTMENU -#ifndef QT_NO_DRAGANDDROP /*! \reimp */ @@ -1097,7 +1096,6 @@ void QGraphicsProxyWidget::dropEvent(QGraphicsSceneDragDropEvent *event) } #endif } -#endif /*! \reimp diff --git a/src/gui/graphicsview/qgraphicsproxywidget.h b/src/gui/graphicsview/qgraphicsproxywidget.h index ab8c9da..b2c3c8f 100644 --- a/src/gui/graphicsview/qgraphicsproxywidget.h +++ b/src/gui/graphicsview/qgraphicsproxywidget.h @@ -90,12 +90,10 @@ protected: void contextMenuEvent(QGraphicsSceneContextMenuEvent *event); #endif -#ifndef QT_NO_DRAGANDDROP void dragEnterEvent(QGraphicsSceneDragDropEvent *event); void dragLeaveEvent(QGraphicsSceneDragDropEvent *event); void dragMoveEvent(QGraphicsSceneDragDropEvent *event); void dropEvent(QGraphicsSceneDragDropEvent *event); -#endif void hoverEnterEvent(QGraphicsSceneHoverEvent *event); void hoverLeaveEvent(QGraphicsSceneHoverEvent *event); diff --git a/src/gui/gui.pro b/src/gui/gui.pro index 329fb01..1aa6558 100644 --- a/src/gui/gui.pro +++ b/src/gui/gui.pro @@ -19,7 +19,6 @@ win32:include(kernel/win.pri) embedded:include(embedded/embedded.pri) #modules -include(animation/animation.pri) include(kernel/kernel.pri) include(image/image.pri) include(painting/painting.pri) @@ -32,7 +31,6 @@ include(itemviews/itemviews.pri) include(inputmethod/inputmethod.pri) include(graphicsview/graphicsview.pri) include(util/util.pri) -include(statemachine/statemachine.pri) include(math3d/math3d.pri) embedded: QT += network diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp index a9424db..824d6f1 100644 --- a/src/gui/kernel/qapplication.cpp +++ b/src/gui/kernel/qapplication.cpp @@ -838,9 +838,6 @@ void QApplicationPrivate::initialize() // trigger registering of QVariant's GUI types extern int qRegisterGuiVariant(); qRegisterGuiVariant(); - // trigger registering of QStateMachine's GUI types - extern int qRegisterGuiStateMachine(); - qRegisterGuiStateMachine(); is_app_running = true; // no longer starting up @@ -1062,9 +1059,6 @@ QApplication::~QApplication() QApplicationPrivate::fade_tooltip = false; QApplicationPrivate::widgetCount = false; - // trigger unregistering of QStateMachine's GUI types - extern int qUnregisterGuiStateMachine(); - qUnregisterGuiStateMachine(); // trigger unregistering of QVariant's GUI types extern int qUnregisterGuiVariant(); qUnregisterGuiVariant(); diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp index bbe1a76..fdd0c21 100644 --- a/src/gui/painting/qdrawhelper.cpp +++ b/src/gui/painting/qdrawhelper.cpp @@ -6930,7 +6930,7 @@ static void qt_alphamapblit_quint16(QRasterBuffer *rasterBuffer, } void qt_build_pow_tables() { - qreal smoothing = qreal(1.7); + qreal smoothing = 1.7; #ifdef Q_WS_MAC // decided by testing a few things on an iMac, should probably get this from the @@ -6952,15 +6952,15 @@ void qt_build_pow_tables() { } #else for (int i=0; i<256; ++i) { - qt_pow_rgb_gamma[i] = uchar(qRound(pow(i / qreal(255.0), smoothing) * 255)); - qt_pow_rgb_invgamma[i] = uchar(qRound(pow(i / qreal(255.), 1 / smoothing) * 255)); + qt_pow_rgb_gamma[i] = uchar(qRound(pow(i / 255.0, smoothing) * 255)); + qt_pow_rgb_invgamma[i] = uchar(qRound(pow(i / 255.0, 1 / smoothing) * 255)); } #endif #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) const qreal gray_gamma = 2.31; for (int i=0; i<256; ++i) - qt_pow_gamma[i] = uint(qRound(pow(i / qreal(255.), gray_gamma) * 2047)); + qt_pow_gamma[i] = uint(qRound(pow(i / 255.0, gray_gamma) * 2047)); for (int i=0; i<2048; ++i) qt_pow_invgamma[i] = uchar(qRound(pow(i / 2047.0, 1 / gray_gamma) * 255)); #endif diff --git a/src/gui/statemachine/qbasickeyeventtransition.cpp b/src/gui/statemachine/qbasickeyeventtransition.cpp deleted file mode 100644 index f7f1eb6..0000000 --- a/src/gui/statemachine/qbasickeyeventtransition.cpp +++ /dev/null @@ -1,203 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qbasickeyeventtransition_p.h" -#include -#include -#include - -QT_BEGIN_NAMESPACE - -/*! - \internal - \class QBasicKeyEventTransition - \since 4.6 - \ingroup statemachine - - \brief The QBasicKeyEventTransition class provides a transition for Qt key events. -*/ - -class QBasicKeyEventTransitionPrivate : public QAbstractTransitionPrivate -{ - Q_DECLARE_PUBLIC(QBasicKeyEventTransition) -public: - QBasicKeyEventTransitionPrivate(); - - static QBasicKeyEventTransitionPrivate *get(QBasicKeyEventTransition *q); - - QEvent::Type eventType; - int key; - Qt::KeyboardModifiers modifiersMask; -}; - -QBasicKeyEventTransitionPrivate::QBasicKeyEventTransitionPrivate() -{ - eventType = QEvent::None; - key = 0; - modifiersMask = Qt::NoModifier; -} - -QBasicKeyEventTransitionPrivate *QBasicKeyEventTransitionPrivate::get(QBasicKeyEventTransition *q) -{ - return q->d_func(); -} - -/*! - Constructs a new key event transition with the given \a sourceState. -*/ -QBasicKeyEventTransition::QBasicKeyEventTransition(QState *sourceState) - : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState) -{ -} - -/*! - Constructs a new event transition for events of the given \a type for the - given \a key, with the given \a sourceState. -*/ -QBasicKeyEventTransition::QBasicKeyEventTransition(QEvent::Type type, int key, - QState *sourceState) - : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState) -{ - Q_D(QBasicKeyEventTransition); - d->eventType = type; - d->key = key; -} - -/*! - Constructs a new event transition for events of the given \a type for the - given \a key, with the given \a modifiersMask and \a sourceState. -*/ -QBasicKeyEventTransition::QBasicKeyEventTransition(QEvent::Type type, int key, - Qt::KeyboardModifiers modifiersMask, - QState *sourceState) - : QAbstractTransition(*new QBasicKeyEventTransitionPrivate, sourceState) -{ - Q_D(QBasicKeyEventTransition); - d->eventType = type; - d->key = key; - d->modifiersMask = modifiersMask; -} - -/*! - Destroys this event transition. -*/ -QBasicKeyEventTransition::~QBasicKeyEventTransition() -{ -} - -/*! - Returns the event type that this key event transition is associated with. -*/ -QEvent::Type QBasicKeyEventTransition::eventType() const -{ - Q_D(const QBasicKeyEventTransition); - return d->eventType; -} - -/*! - Sets the event \a type that this key event transition is associated with. -*/ -void QBasicKeyEventTransition::setEventType(QEvent::Type type) -{ - Q_D(QBasicKeyEventTransition); - d->eventType = type; -} - -/*! - Returns the key that this key event transition checks for. -*/ -int QBasicKeyEventTransition::key() const -{ - Q_D(const QBasicKeyEventTransition); - return d->key; -} - -/*! - Sets the key that this key event transition will check for. -*/ -void QBasicKeyEventTransition::setKey(int key) -{ - Q_D(QBasicKeyEventTransition); - d->key = key; -} - -/*! - Returns the keyboard modifiers mask that this key event transition checks - for. -*/ -Qt::KeyboardModifiers QBasicKeyEventTransition::modifiersMask() const -{ - Q_D(const QBasicKeyEventTransition); - return d->modifiersMask; -} - -/*! - Sets the keyboard modifiers mask that this key event transition will check - for. -*/ -void QBasicKeyEventTransition::setModifiersMask(Qt::KeyboardModifiers modifiersMask) -{ - Q_D(QBasicKeyEventTransition); - d->modifiersMask = modifiersMask; -} - -/*! - \reimp -*/ -bool QBasicKeyEventTransition::eventTest(QEvent *event) -{ - Q_D(const QBasicKeyEventTransition); - if (event->type() == d->eventType) { - QKeyEvent *ke = static_cast(event); - return (ke->key() == d->key) - && ((ke->modifiers() & d->modifiersMask) == d->modifiersMask); - } - return false; -} - -/*! - \reimp -*/ -void QBasicKeyEventTransition::onTransition(QEvent *) -{ -} - -QT_END_NAMESPACE diff --git a/src/gui/statemachine/qbasickeyeventtransition_p.h b/src/gui/statemachine/qbasickeyeventtransition_p.h deleted file mode 100644 index 39fa6ad..0000000 --- a/src/gui/statemachine/qbasickeyeventtransition_p.h +++ /dev/null @@ -1,93 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QBASICKEYEVENTTRANSITION_P_H -#define QBASICKEYEVENTTRANSITION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -QT_BEGIN_NAMESPACE - -class QBasicKeyEventTransitionPrivate; -class Q_AUTOTEST_EXPORT QBasicKeyEventTransition : public QAbstractTransition -{ - Q_OBJECT -public: - QBasicKeyEventTransition(QState *sourceState = 0); - QBasicKeyEventTransition(QEvent::Type type, int key, QState *sourceState = 0); - QBasicKeyEventTransition(QEvent::Type type, int key, - Qt::KeyboardModifiers modifiersMask, - QState *sourceState = 0); - ~QBasicKeyEventTransition(); - - QEvent::Type eventType() const; - void setEventType(QEvent::Type type); - - int key() const; - void setKey(int key); - - Qt::KeyboardModifiers modifiersMask() const; - void setModifiersMask(Qt::KeyboardModifiers modifiers); - -protected: - bool eventTest(QEvent *event); - void onTransition(QEvent *); - -private: - Q_DISABLE_COPY(QBasicKeyEventTransition) - Q_DECLARE_PRIVATE(QBasicKeyEventTransition) -}; - -QT_END_NAMESPACE - -#endif diff --git a/src/gui/statemachine/qbasicmouseeventtransition.cpp b/src/gui/statemachine/qbasicmouseeventtransition.cpp deleted file mode 100644 index 20dd792..0000000 --- a/src/gui/statemachine/qbasicmouseeventtransition.cpp +++ /dev/null @@ -1,208 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qbasicmouseeventtransition_p.h" -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -/*! - \internal - \class QBasicMouseEventTransition - \since 4.6 - \ingroup statemachine - - \brief The QBasicMouseEventTransition class provides a transition for Qt mouse events. -*/ - -class QBasicMouseEventTransitionPrivate : public QAbstractTransitionPrivate -{ - Q_DECLARE_PUBLIC(QBasicMouseEventTransition) -public: - QBasicMouseEventTransitionPrivate(); - - static QBasicMouseEventTransitionPrivate *get(QBasicMouseEventTransition *q); - - QEvent::Type eventType; - Qt::MouseButton button; - Qt::KeyboardModifiers modifiersMask; - QPainterPath path; -}; - -QBasicMouseEventTransitionPrivate::QBasicMouseEventTransitionPrivate() -{ - eventType = QEvent::None; - button = Qt::NoButton; -} - -QBasicMouseEventTransitionPrivate *QBasicMouseEventTransitionPrivate::get(QBasicMouseEventTransition *q) -{ - return q->d_func(); -} - -/*! - Constructs a new mouse event transition with the given \a sourceState. -*/ -QBasicMouseEventTransition::QBasicMouseEventTransition(QState *sourceState) - : QAbstractTransition(*new QBasicMouseEventTransitionPrivate, sourceState) -{ -} - -/*! - Constructs a new mouse event transition for events of the given \a type. -*/ -QBasicMouseEventTransition::QBasicMouseEventTransition(QEvent::Type type, - Qt::MouseButton button, - QState *sourceState) - : QAbstractTransition(*new QBasicMouseEventTransitionPrivate, sourceState) -{ - Q_D(QBasicMouseEventTransition); - d->eventType = type; - d->button = button; -} - -/*! - Destroys this mouse event transition. -*/ -QBasicMouseEventTransition::~QBasicMouseEventTransition() -{ -} - -/*! - Returns the event type that this mouse event transition is associated with. -*/ -QEvent::Type QBasicMouseEventTransition::eventType() const -{ - Q_D(const QBasicMouseEventTransition); - return d->eventType; -} - -/*! - Sets the event \a type that this mouse event transition is associated with. -*/ -void QBasicMouseEventTransition::setEventType(QEvent::Type type) -{ - Q_D(QBasicMouseEventTransition); - d->eventType = type; -} - -/*! - Returns the button that this mouse event transition checks for. -*/ -Qt::MouseButton QBasicMouseEventTransition::button() const -{ - Q_D(const QBasicMouseEventTransition); - return d->button; -} - -/*! - Sets the button that this mouse event transition will check for. -*/ -void QBasicMouseEventTransition::setButton(Qt::MouseButton button) -{ - Q_D(QBasicMouseEventTransition); - d->button = button; -} - -/*! - Returns the keyboard modifiers mask that this mouse event transition checks - for. -*/ -Qt::KeyboardModifiers QBasicMouseEventTransition::modifiersMask() const -{ - Q_D(const QBasicMouseEventTransition); - return d->modifiersMask; -} - -/*! - Sets the keyboard modifiers mask that this mouse event transition will check - for. -*/ -void QBasicMouseEventTransition::setModifiersMask(Qt::KeyboardModifiers modifiersMask) -{ - Q_D(QBasicMouseEventTransition); - d->modifiersMask = modifiersMask; -} - -/*! - Returns the path for this mouse event transition. -*/ -QPainterPath QBasicMouseEventTransition::path() const -{ - Q_D(const QBasicMouseEventTransition); - return d->path; -} - -/*! - Sets the path for this mouse event transition. -*/ -void QBasicMouseEventTransition::setPath(const QPainterPath &path) -{ - Q_D(QBasicMouseEventTransition); - d->path = path; -} - -/*! - \reimp -*/ -bool QBasicMouseEventTransition::eventTest(QEvent *event) -{ - Q_D(const QBasicMouseEventTransition); - if (event->type() == d->eventType) { - QMouseEvent *me = static_cast(event); - return (me->button() == d->button) - && ((me->modifiers() & d->modifiersMask) == d->modifiersMask) - && (d->path.isEmpty() || d->path.contains(me->pos())); - } - return false; -} - -/*! - \reimp -*/ -void QBasicMouseEventTransition::onTransition(QEvent *) -{ -} - -QT_END_NAMESPACE diff --git a/src/gui/statemachine/qbasicmouseeventtransition_p.h b/src/gui/statemachine/qbasicmouseeventtransition_p.h deleted file mode 100644 index 6c0afe4..0000000 --- a/src/gui/statemachine/qbasicmouseeventtransition_p.h +++ /dev/null @@ -1,98 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QBASICMOUSEEVENTTRANSITION_P_H -#define QBASICMOUSEEVENTTRANSITION_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -QT_BEGIN_NAMESPACE - -class QPainterPath; - -class QBasicMouseEventTransitionPrivate; -class Q_AUTOTEST_EXPORT QBasicMouseEventTransition : public QAbstractTransition -{ - Q_OBJECT -public: - QBasicMouseEventTransition(QState *sourceState = 0); - QBasicMouseEventTransition(QEvent::Type type, Qt::MouseButton button, - QState *sourceState = 0); - ~QBasicMouseEventTransition(); - - QEvent::Type eventType() const; - void setEventType(QEvent::Type type); - - Qt::MouseButton button() const; - void setButton(Qt::MouseButton button); - - Qt::KeyboardModifiers modifiersMask() const; - void setModifiersMask(Qt::KeyboardModifiers modifiers); - - QPainterPath path() const; - void setPath(const QPainterPath &path); - -protected: - bool eventTest(QEvent *event); - void onTransition(QEvent *); - -private: - Q_DISABLE_COPY(QBasicMouseEventTransition) - Q_DECLARE_PRIVATE(QBasicMouseEventTransition) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/gui/statemachine/qguistatemachine.cpp b/src/gui/statemachine/qguistatemachine.cpp deleted file mode 100644 index 612e43e..0000000 --- a/src/gui/statemachine/qguistatemachine.cpp +++ /dev/null @@ -1,559 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -Q_CORE_EXPORT const QStateMachinePrivate::Handler *qcoreStateMachineHandler(); - -static QEvent *cloneEvent(QEvent *e) -{ - switch (e->type()) { - case QEvent::MouseButtonPress: - case QEvent::MouseButtonRelease: - case QEvent::MouseButtonDblClick: - case QEvent::MouseMove: - return new QMouseEvent(*static_cast(e)); - case QEvent::KeyPress: - case QEvent::KeyRelease: - return new QKeyEvent(*static_cast(e)); - case QEvent::FocusIn: - case QEvent::FocusOut: - return new QFocusEvent(*static_cast(e)); - case QEvent::Enter: - return new QEvent(*e); - case QEvent::Leave: - return new QEvent(*e); - break; - case QEvent::Paint: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::Move: - return new QMoveEvent(*static_cast(e)); - case QEvent::Resize: - return new QResizeEvent(*static_cast(e)); - case QEvent::Create: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::Destroy: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::Show: - return new QShowEvent(*static_cast(e)); - case QEvent::Hide: - return new QHideEvent(*static_cast(e)); - case QEvent::Close: - return new QCloseEvent(*static_cast(e)); - case QEvent::Quit: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ParentChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ParentAboutToChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ThreadChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::WindowActivate: - case QEvent::WindowDeactivate: - return new QEvent(*e); - - case QEvent::ShowToParent: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::HideToParent: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::Wheel: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::WindowTitleChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::WindowIconChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ApplicationWindowIconChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ApplicationFontChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ApplicationLayoutDirectionChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ApplicationPaletteChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::PaletteChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::Clipboard: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::Speech: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::MetaCall: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::SockAct: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::WinEventAct: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::DeferredDelete: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::DragEnter: - return new QDragEnterEvent(*static_cast(e)); - case QEvent::DragMove: - return new QDragMoveEvent(*static_cast(e)); - case QEvent::DragLeave: - return new QDragLeaveEvent(*static_cast(e)); - case QEvent::Drop: - return new QDropEvent(*static_cast(e)); - case QEvent::DragResponse: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ChildAdded: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ChildPolished: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; -#ifdef QT3_SUPPORT - case QEvent::ChildInsertedRequest: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ChildInserted: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::LayoutHint: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; -#endif - case QEvent::ChildRemoved: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ShowWindowRequest: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::PolishRequest: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::Polish: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::LayoutRequest: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::UpdateRequest: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::UpdateLater: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::EmbeddingControl: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ActivateControl: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::DeactivateControl: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ContextMenu: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::InputMethod: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::AccessibilityPrepare: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::TabletMove: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::LocaleChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::LanguageChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::LayoutDirectionChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::Style: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::TabletPress: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::TabletRelease: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::OkRequest: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::HelpRequest: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::IconDrag: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::FontChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::EnabledChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ActivationChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::StyleChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::IconTextChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ModifiedChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::MouseTrackingChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::WindowBlocked: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::WindowUnblocked: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::WindowStateChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::ToolTip: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::WhatsThis: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::StatusTip: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::ActionChanged: - case QEvent::ActionAdded: - case QEvent::ActionRemoved: - return new QActionEvent(*static_cast(e)); - - case QEvent::FileOpen: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::Shortcut: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ShortcutOverride: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - -#ifdef QT3_SUPPORT - case QEvent::Accel: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::AccelAvailable: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; -#endif - - case QEvent::WhatsThisClicked: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::ToolBarChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::ApplicationActivate: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ApplicationDeactivate: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::QueryWhatsThis: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::EnterWhatsThisMode: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::LeaveWhatsThisMode: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::ZOrderChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::HoverEnter: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::HoverLeave: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::HoverMove: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::AccessibilityHelp: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::AccessibilityDescription: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - -#ifdef QT_KEYPAD_NAVIGATION - case QEvent::EnterEditFocus: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::LeaveEditFocus: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; -#endif - case QEvent::AcceptDropsChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::MenubarUpdated: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::ZeroTimerEvent: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::GraphicsSceneMouseMove: - case QEvent::GraphicsSceneMousePress: - case QEvent::GraphicsSceneMouseRelease: - case QEvent::GraphicsSceneMouseDoubleClick: { - QGraphicsSceneMouseEvent *me = static_cast(e); - QGraphicsSceneMouseEvent *me2 = new QGraphicsSceneMouseEvent(me->type()); - me2->setWidget(me->widget()); - me2->setPos(me->pos()); - me2->setScenePos(me->scenePos()); - me2->setScreenPos(me->screenPos()); -// ### for all buttons - me2->setButtonDownPos(Qt::LeftButton, me->buttonDownPos(Qt::LeftButton)); - me2->setButtonDownPos(Qt::RightButton, me->buttonDownPos(Qt::RightButton)); - me2->setButtonDownScreenPos(Qt::LeftButton, me->buttonDownScreenPos(Qt::LeftButton)); - me2->setButtonDownScreenPos(Qt::RightButton, me->buttonDownScreenPos(Qt::RightButton)); - me2->setLastPos(me->lastPos()); - me2->setLastScenePos(me->lastScenePos()); - me2->setLastScreenPos(me->lastScreenPos()); - me2->setButtons(me->buttons()); - me2->setButton(me->button()); - me2->setModifiers(me->modifiers()); - return me2; - } - - case QEvent::GraphicsSceneContextMenu: { - QGraphicsSceneContextMenuEvent *me = static_cast(e); - QGraphicsSceneContextMenuEvent *me2 = new QGraphicsSceneContextMenuEvent(me->type()); - me2->setWidget(me->widget()); - me2->setPos(me->pos()); - me2->setScenePos(me->scenePos()); - me2->setScreenPos(me->screenPos()); - me2->setModifiers(me->modifiers()); - me2->setReason(me->reason()); - return me2; - } - - case QEvent::GraphicsSceneHoverEnter: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneHoverMove: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneHoverLeave: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneHelp: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneDragEnter: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneDragMove: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneDragLeave: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneDrop: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneWheel: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::KeyboardLayoutChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::DynamicPropertyChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::TabletEnterProximity: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::TabletLeaveProximity: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::NonClientAreaMouseMove: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::NonClientAreaMouseButtonPress: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::NonClientAreaMouseButtonRelease: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::NonClientAreaMouseButtonDblClick: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::MacSizeChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::ContentsRectChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::MacGLWindowChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::FutureCallOut: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::GraphicsSceneResize: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::GraphicsSceneMove: { - QGraphicsSceneMoveEvent *me = static_cast(e); - QGraphicsSceneMoveEvent *me2 = new QGraphicsSceneMoveEvent(); - me2->setWidget(me->widget()); - me2->setNewPos(me->newPos()); - me2->setOldPos(me->oldPos()); - return me2; - } - - case QEvent::CursorChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - case QEvent::ToolTipChange: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::NetworkReplyUpdated: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - - case QEvent::GrabMouse: - case QEvent::UngrabMouse: - case QEvent::GrabKeyboard: - case QEvent::UngrabKeyboard: - return new QEvent(*e); - -#ifdef QT_MAC_USE_COCOA - case QEvent::CocoaRequestModal: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; -#endif - case QEvent::User: - case QEvent::MaxUser: - Q_ASSERT_X(false, "cloneEvent()", "not implemented"); - break; - default: - ; - } - return qcoreStateMachineHandler()->cloneEvent(e); -} - -const QStateMachinePrivate::Handler qt_gui_statemachine_handler = { - cloneEvent -}; - -static const QStateMachinePrivate::Handler *qt_guistatemachine_last_handler = 0; -int qRegisterGuiStateMachine() -{ - qt_guistatemachine_last_handler = QStateMachinePrivate::handler; - QStateMachinePrivate::handler = &qt_gui_statemachine_handler; - return 1; -} -Q_CONSTRUCTOR_FUNCTION(qRegisterGuiStateMachine) - -int qUnregisterGuiStateMachine() -{ - QStateMachinePrivate::handler = qt_guistatemachine_last_handler; - return 1; -} -Q_DESTRUCTOR_FUNCTION(qUnregisterGuiStateMachine) - -QT_END_NAMESPACE diff --git a/src/gui/statemachine/qkeyeventtransition.cpp b/src/gui/statemachine/qkeyeventtransition.cpp deleted file mode 100644 index f803711..0000000 --- a/src/gui/statemachine/qkeyeventtransition.cpp +++ /dev/null @@ -1,186 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qkeyeventtransition.h" -#include "qbasickeyeventtransition_p.h" -#include -#include - -QT_BEGIN_NAMESPACE - -/*! - \class QKeyEventTransition - - \brief The QKeyEventTransition class provides a transition for key events. - - \since 4.6 - \ingroup statemachine - - QKeyEventTransition is part of \l{The State Machine Framework}. - - \sa QState::addTransition() -*/ - -/*! - \property QKeyEventTransition::key - - \brief the key that this key event transition is associated with -*/ - -/*! - \property QKeyEventTransition::modifiersMask - - \brief the keyboard modifiers mask that this key event transition checks for -*/ - -class QKeyEventTransitionPrivate : public QEventTransitionPrivate -{ - Q_DECLARE_PUBLIC(QKeyEventTransition) -public: - QKeyEventTransitionPrivate() {} - - QBasicKeyEventTransition *transition; -}; - -/*! - Constructs a new key event transition with the given \a sourceState. -*/ -QKeyEventTransition::QKeyEventTransition(QState *sourceState) - : QEventTransition(*new QKeyEventTransitionPrivate, sourceState) -{ - Q_D(QKeyEventTransition); - d->transition = new QBasicKeyEventTransition(); -} - -/*! - Constructs a new key event transition for events of the given \a type for - the given \a object, with the given \a key and \a sourceState. -*/ -QKeyEventTransition::QKeyEventTransition(QObject *object, QEvent::Type type, - int key, QState *sourceState) - : QEventTransition(*new QKeyEventTransitionPrivate, object, type, sourceState) -{ - Q_D(QKeyEventTransition); - d->transition = new QBasicKeyEventTransition(type, key); -} - -/*! - Constructs a new key event transition for events of the given \a type for - the given \a object, with the given \a key, \a targets and \a sourceState. -*/ -QKeyEventTransition::QKeyEventTransition(QObject *object, QEvent::Type type, - int key, const QList &targets, - QState *sourceState) - : QEventTransition(*new QKeyEventTransitionPrivate, object, type, targets, sourceState) -{ - Q_D(QKeyEventTransition); - d->transition = new QBasicKeyEventTransition(type, key); -} - -/*! - Destroys this key event transition. -*/ -QKeyEventTransition::~QKeyEventTransition() -{ - Q_D(QKeyEventTransition); - delete d->transition; -} - -/*! - Returns the key that this key event transition checks for. -*/ -int QKeyEventTransition::key() const -{ - Q_D(const QKeyEventTransition); - return d->transition->key(); -} - -/*! - Sets the key that this key event transition will check for. -*/ -void QKeyEventTransition::setKey(int key) -{ - Q_D(QKeyEventTransition); - d->transition->setKey(key); -} - -/*! - Returns the keyboard modifiers mask that this key event transition checks - for. -*/ -Qt::KeyboardModifiers QKeyEventTransition::modifiersMask() const -{ - Q_D(const QKeyEventTransition); - return d->transition->modifiersMask(); -} - -/*! - Sets the keyboard \a modifiers mask that this key event transition will - check for. -*/ -void QKeyEventTransition::setModifiersMask(Qt::KeyboardModifiers modifiersMask) -{ - Q_D(QKeyEventTransition); - d->transition->setModifiersMask(modifiersMask); -} - -/*! - \reimp -*/ -bool QKeyEventTransition::eventTest(QEvent *event) -{ - Q_D(const QKeyEventTransition); - if (!QEventTransition::eventTest(event)) - return false; - QWrappedEvent *we = static_cast(event); - d->transition->setEventType(we->event()->type()); - return QAbstractTransitionPrivate::get(d->transition)->callEventTest(we->event()); -} - -/*! - \reimp -*/ -void QKeyEventTransition::onTransition(QEvent *event) -{ - QEventTransition::onTransition(event); -} - -QT_END_NAMESPACE diff --git a/src/gui/statemachine/qkeyeventtransition.h b/src/gui/statemachine/qkeyeventtransition.h deleted file mode 100644 index 3c8295f..0000000 --- a/src/gui/statemachine/qkeyeventtransition.h +++ /dev/null @@ -1,87 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QKEYEVENTTRANSITION_H -#define QKEYEVENTTRANSITION_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QKeyEventTransitionPrivate; -class Q_GUI_EXPORT QKeyEventTransition : public QEventTransition -{ - Q_OBJECT - Q_PROPERTY(int key READ key WRITE setKey) - Q_PROPERTY(Qt::KeyboardModifiers modifiersMask READ modifiersMask WRITE setModifiersMask) -public: - QKeyEventTransition(QState *sourceState = 0); - QKeyEventTransition(QObject *object, QEvent::Type type, int key, - QState *sourceState = 0); - QKeyEventTransition(QObject *object, QEvent::Type type, int key, - const QList &targets, - QState *sourceState = 0); - ~QKeyEventTransition(); - - int key() const; - void setKey(int key); - - Qt::KeyboardModifiers modifiersMask() const; - void setModifiersMask(Qt::KeyboardModifiers modifiers); - -protected: - void onTransition(QEvent *event); - bool eventTest(QEvent *event); - -private: - Q_DISABLE_COPY(QKeyEventTransition) - Q_DECLARE_PRIVATE(QKeyEventTransition) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/gui/statemachine/qmouseeventtransition.cpp b/src/gui/statemachine/qmouseeventtransition.cpp deleted file mode 100644 index e4e18eb..0000000 --- a/src/gui/statemachine/qmouseeventtransition.cpp +++ /dev/null @@ -1,216 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qmouseeventtransition.h" -#include "qbasicmouseeventtransition_p.h" -#include -#include -#include - -QT_BEGIN_NAMESPACE - -/*! - \class QMouseEventTransition - - \brief The QMouseEventTransition class provides a transition for mouse events. - - \since 4.6 - \ingroup statemachine - - QMouseEventTransition is part of \l{The State Machine Framework}. - - \sa QState::addTransition() -*/ - -/*! - \property QMouseEventTransition::button - - \brief the button that this mouse event transition is associated with -*/ - -/*! - \property QMouseEventTransition::modifiersMask - - \brief the keyboard modifiers mask that this mouse event transition checks for -*/ - -class QMouseEventTransitionPrivate : public QEventTransitionPrivate -{ - Q_DECLARE_PUBLIC(QMouseEventTransition) -public: - QMouseEventTransitionPrivate(); - - QBasicMouseEventTransition *transition; -}; - -QMouseEventTransitionPrivate::QMouseEventTransitionPrivate() -{ -} - -/*! - Constructs a new mouse event transition with the given \a sourceState. -*/ -QMouseEventTransition::QMouseEventTransition(QState *sourceState) - : QEventTransition(*new QMouseEventTransitionPrivate, sourceState) -{ - Q_D(QMouseEventTransition); - d->transition = new QBasicMouseEventTransition(); -} - -/*! - Constructs a new mouse event transition for events of the given \a type for - the given \a object, with the given \a button and \a sourceState. -*/ -QMouseEventTransition::QMouseEventTransition(QObject *object, QEvent::Type type, - Qt::MouseButton button, - QState *sourceState) - : QEventTransition(*new QMouseEventTransitionPrivate, object, type, sourceState) -{ - Q_D(QMouseEventTransition); - d->transition = new QBasicMouseEventTransition(type, button); -} - -/*! - Constructs a new mouse event transition for events of the given \a type for - the given \a object, with the given \a button, \a targets and \a - sourceState. -*/ -QMouseEventTransition::QMouseEventTransition(QObject *object, QEvent::Type type, - Qt::MouseButton button, - const QList &targets, - QState *sourceState) - : QEventTransition(*new QMouseEventTransitionPrivate, object, type, targets, sourceState) -{ - Q_D(QMouseEventTransition); - d->transition = new QBasicMouseEventTransition(type, button); -} - -/*! - Destroys this mouse event transition. -*/ -QMouseEventTransition::~QMouseEventTransition() -{ - Q_D(QMouseEventTransition); - delete d->transition; -} - -/*! - Returns the button that this mouse event transition checks for. -*/ -Qt::MouseButton QMouseEventTransition::button() const -{ - Q_D(const QMouseEventTransition); - return d->transition->button(); -} - -/*! - Sets the \a button that this mouse event transition will check for. -*/ -void QMouseEventTransition::setButton(Qt::MouseButton button) -{ - Q_D(QMouseEventTransition); - d->transition->setButton(button); -} - -/*! - Returns the keyboard modifiers mask that this mouse event transition checks - for. -*/ -Qt::KeyboardModifiers QMouseEventTransition::modifiersMask() const -{ - Q_D(const QMouseEventTransition); - return d->transition->modifiersMask(); -} - -/*! - Sets the keyboard \a modifiers mask that this mouse event transition will - check for. -*/ -void QMouseEventTransition::setModifiersMask(Qt::KeyboardModifiers modifiersMask) -{ - Q_D(QMouseEventTransition); - d->transition->setModifiersMask(modifiersMask); -} - -/*! - Returns the path for this mouse event transition. -*/ -QPainterPath QMouseEventTransition::path() const -{ - Q_D(const QMouseEventTransition); - return d->transition->path(); -} - -/*! - Sets the \a path for this mouse event transition. - If a valid path has been set, the transition will only trigger if the mouse - event position (QMouseEvent::pos()) is inside the path. - - \sa QPainterPath::contains() -*/ -void QMouseEventTransition::setPath(const QPainterPath &path) -{ - Q_D(QMouseEventTransition); - d->transition->setPath(path); -} - -/*! - \reimp -*/ -bool QMouseEventTransition::eventTest(QEvent *event) -{ - Q_D(const QMouseEventTransition); - if (!QEventTransition::eventTest(event)) - return false; - QWrappedEvent *we = static_cast(event); - d->transition->setEventType(we->event()->type()); - return QAbstractTransitionPrivate::get(d->transition)->callEventTest(we->event()); -} - -/*! - \reimp -*/ -void QMouseEventTransition::onTransition(QEvent *event) -{ - QEventTransition::onTransition(event); -} - -QT_END_NAMESPACE diff --git a/src/gui/statemachine/qmouseeventtransition.h b/src/gui/statemachine/qmouseeventtransition.h deleted file mode 100644 index 3f5f3ac..0000000 --- a/src/gui/statemachine/qmouseeventtransition.h +++ /dev/null @@ -1,92 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtGui module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QMOUSEEVENTTRANSITION_H -#define QMOUSEEVENTTRANSITION_H - -#include - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Core) - -class QMouseEventTransitionPrivate; -class QPainterPath; -class Q_GUI_EXPORT QMouseEventTransition : public QEventTransition -{ - Q_OBJECT - Q_PROPERTY(Qt::MouseButton button READ button WRITE setButton) - Q_PROPERTY(Qt::KeyboardModifiers modifiersMask READ modifiersMask WRITE setModifiersMask) -public: - QMouseEventTransition(QState *sourceState = 0); - QMouseEventTransition(QObject *object, QEvent::Type type, - Qt::MouseButton button, QState *sourceState = 0); - QMouseEventTransition(QObject *object, QEvent::Type type, - Qt::MouseButton button, - const QList &targets, - QState *sourceState = 0); - ~QMouseEventTransition(); - - Qt::MouseButton button() const; - void setButton(Qt::MouseButton button); - - Qt::KeyboardModifiers modifiersMask() const; - void setModifiersMask(Qt::KeyboardModifiers modifiers); - - QPainterPath path() const; - void setPath(const QPainterPath &path); - -protected: - void onTransition(QEvent *event); - bool eventTest(QEvent *event); - -private: - Q_DISABLE_COPY(QMouseEventTransition) - Q_DECLARE_PRIVATE(QMouseEventTransition) -}; - -QT_END_NAMESPACE - -QT_END_HEADER - -#endif diff --git a/src/gui/statemachine/statemachine.pri b/src/gui/statemachine/statemachine.pri deleted file mode 100644 index 2eb1e05..0000000 --- a/src/gui/statemachine/statemachine.pri +++ /dev/null @@ -1,13 +0,0 @@ -SOURCES += $$PWD/qguistatemachine.cpp -!contains(DEFINES, QT_NO_STATEMACHINE_EVENTFILTER) { - HEADERS += \ - $$PWD/qkeyeventtransition.h \ - $$PWD/qmouseeventtransition.h \ - $$PWD/qbasickeyeventtransition_p.h \ - $$PWD/qbasicmouseeventtransition_p.h - SOURCES += \ - $$PWD/qkeyeventtransition.cpp \ - $$PWD/qmouseeventtransition.cpp \ - $$PWD/qbasickeyeventtransition.cpp \ - $$PWD/qbasicmouseeventtransition.cpp -} diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro index 316a695..714e19d 100644 --- a/tests/auto/auto.pro +++ b/tests/auto/auto.pro @@ -75,7 +75,6 @@ SUBDIRS += bic \ qaction \ qactiongroup \ qalgorithms \ - qanimationgroup \ qapplication \ qatomicint \ qatomicpointer \ @@ -215,7 +214,6 @@ SUBDIRS += bic \ qpainter \ qpainterpath \ qpalette \ - qparallelanimationgroup \ qpathclipper \ qpen \ qpicture \ @@ -231,7 +229,6 @@ SUBDIRS += bic \ qprocess \ qprogressbar \ qprogressdialog \ - qpropertyanimation \ qpushbutton \ qqueue \ qradiobutton \ @@ -259,7 +256,6 @@ SUBDIRS += bic \ qscrollarea \ qsemaphore \ qsharedpointer \ - qsequentialanimationgroup \ qset \ qsettings \ qshortcut \ @@ -293,7 +289,6 @@ SUBDIRS += bic \ qstackedwidget \ qstandarditem \ qstandarditemmodel \ - qstate \ qstatusbar \ qstl \ qstring \ @@ -347,7 +342,6 @@ SUBDIRS += bic \ qtranslator \ qtransform \ qtransformedscreen \ - qtransition \ qtreeview \ qtreewidget \ qtreewidgetitemiterator \ diff --git a/tests/auto/qanimationgroup/qanimationgroup.pro b/tests/auto/qanimationgroup/qanimationgroup.pro deleted file mode 100644 index 97d33dd..0000000 --- a/tests/auto/qanimationgroup/qanimationgroup.pro +++ /dev/null @@ -1,5 +0,0 @@ -load(qttest_p4) -QT = core gui -SOURCES += tst_qanimationgroup.cpp - - diff --git a/tests/auto/qanimationgroup/tst_qanimationgroup.cpp b/tests/auto/qanimationgroup/tst_qanimationgroup.cpp deleted file mode 100644 index 2952a39..0000000 --- a/tests/auto/qanimationgroup/tst_qanimationgroup.cpp +++ /dev/null @@ -1,413 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include -#include -#include - -//TESTED_CLASS=QAnimationGroup -//TESTED_FILES= - -Q_DECLARE_METATYPE(QAbstractAnimation::State) - -class tst_QAnimationGroup : public QObject -{ - Q_OBJECT -public: - tst_QAnimationGroup(); - virtual ~tst_QAnimationGroup(); - -public Q_SLOTS: - void init(); - void cleanup(); - -private slots: - void construction(); - void emptyGroup(); - void setCurrentTime(); - void statesAndSignals(); - void setParentAutoAdd(); - void beginNestedGroup(); - void addChildTwice(); - void loopWithoutStartValue(); -}; - -tst_QAnimationGroup::tst_QAnimationGroup() -{ -} - -tst_QAnimationGroup::~tst_QAnimationGroup() -{ -} - -void tst_QAnimationGroup::init() -{ - qRegisterMetaType("QAbstractAnimation::State"); -} - -void tst_QAnimationGroup::cleanup() -{ -} - -void tst_QAnimationGroup::construction() -{ - QSequentialAnimationGroup animationgroup; -} - -class AnimationObject : public QObject -{ - Q_OBJECT - Q_PROPERTY(int value READ value WRITE setValue) -public: - AnimationObject(int startValue = 0) - : v(startValue) - { } - - int value() const { return v; } - void setValue(int value) { v = value; } - - int v; -}; - -class TestAnimation : public QVariantAnimation -{ - Q_OBJECT -public: - virtual void updateCurrentValue(const QVariant &value) { Q_UNUSED(value)}; - virtual void updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) - { - Q_UNUSED(oldState) - Q_UNUSED(newState) - }; -}; - -class UncontrolledAnimation : public QPropertyAnimation -{ - Q_OBJECT -public: - UncontrolledAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0) - : QPropertyAnimation(target, propertyName, parent), id(0) - { - setDuration(250); - } - - int duration() const { return -1; /* not time driven */ } - -protected: - void timerEvent(QTimerEvent *event) - { - if (event->timerId() == id) - stop(); - } - - void updateRunning(bool running) - { - if (running) { - id = startTimer(500); - } else { - killTimer(id); - id = 0; - } - } - -private: - int id; -}; - -void tst_QAnimationGroup::emptyGroup() -{ - QSequentialAnimationGroup group; - QSignalSpy groupStateChangedSpy(&group, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - group.start(); - - QCOMPARE(groupStateChangedSpy.count(), 2); - - QCOMPARE(qVariantValue(groupStateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(groupStateChangedSpy.at(1).at(1)), - QAnimationGroup::Stopped); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - - QTest::ignoreMessage(QtWarningMsg, "QAbstractAnimation::pause: Cannot pause a stopped animation"); - group.pause(); - - QCOMPARE(groupStateChangedSpy.count(), 2); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - - group.start(); - - QCOMPARE(qVariantValue(groupStateChangedSpy.at(2).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(groupStateChangedSpy.at(3).at(1)), - QAnimationGroup::Stopped); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - - group.stop(); - - QCOMPARE(groupStateChangedSpy.count(), 4); - QCOMPARE(group.state(), QAnimationGroup::Stopped); -} - -void tst_QAnimationGroup::setCurrentTime() -{ - AnimationObject s_o1; - AnimationObject s_o2; - AnimationObject s_o3; - AnimationObject p_o1; - AnimationObject p_o2; - AnimationObject p_o3; - AnimationObject t_o1; - AnimationObject t_o2; - - // sequence operating on same object/property - QSequentialAnimationGroup *sequence = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); - a2_s_o1->setLoopCount(3); - sequence->addAnimation(a1_s_o1); - sequence->addAnimation(a2_s_o1); - sequence->addAnimation(a3_s_o1); - - // sequence operating on different object/properties - QAnimationGroup *sequence2 = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); - QVariantAnimation *a1_s_o3 = new QPropertyAnimation(&s_o3, "value"); - sequence2->addAnimation(a1_s_o2); - sequence2->addAnimation(a1_s_o3); - - // parallel operating on different object/properties - QAnimationGroup *parallel = new QParallelAnimationGroup(); - QVariantAnimation *a1_p_o1 = new QPropertyAnimation(&p_o1, "value"); - QVariantAnimation *a1_p_o2 = new QPropertyAnimation(&p_o2, "value"); - QVariantAnimation *a1_p_o3 = new QPropertyAnimation(&p_o3, "value"); - a1_p_o2->setLoopCount(3); - parallel->addAnimation(a1_p_o1); - parallel->addAnimation(a1_p_o2); - parallel->addAnimation(a1_p_o3); - - UncontrolledAnimation *notTimeDriven = new UncontrolledAnimation(&t_o1, "value"); - QCOMPARE(notTimeDriven->totalDuration(), -1); - - QVariantAnimation *loopsForever = new QPropertyAnimation(&t_o2, "value"); - loopsForever->setLoopCount(-1); - QCOMPARE(loopsForever->totalDuration(), -1); - - QParallelAnimationGroup group; - group.addAnimation(sequence); - group.addAnimation(sequence2); - group.addAnimation(parallel); - group.addAnimation(notTimeDriven); - group.addAnimation(loopsForever); - - // Current time = 1 - group.setCurrentTime(1); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(sequence->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(parallel->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_p_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_p_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_p_o3->state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); - - QCOMPARE(group.currentTime(), 1); - QCOMPARE(sequence->currentTime(), 1); - QCOMPARE(a1_s_o1->currentTime(), 1); - QCOMPARE(a2_s_o1->currentTime(), 0); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 1); - QCOMPARE(a1_s_o3->currentTime(), 0); - QCOMPARE(a1_p_o1->currentTime(), 1); - QCOMPARE(a1_p_o2->currentTime(), 1); - QCOMPARE(a1_p_o3->currentTime(), 1); - QCOMPARE(notTimeDriven->currentTime(), 1); - QCOMPARE(loopsForever->currentTime(), 1); - - // Current time = 250 - group.setCurrentTime(250); - QCOMPARE(group.currentTime(), 250); - QCOMPARE(sequence->currentTime(), 250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 0); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 0); - QCOMPARE(a1_p_o1->currentTime(), 250); - QCOMPARE(a1_p_o2->currentTime(), 0); - QCOMPARE(a1_p_o2->currentLoop(), 1); - QCOMPARE(a1_p_o3->currentTime(), 250); - QCOMPARE(notTimeDriven->currentTime(), 250); - QCOMPARE(loopsForever->currentTime(), 0); - QCOMPARE(loopsForever->currentLoop(), 1); - QCOMPARE(sequence->currentAnimation(), a2_s_o1); - - // Current time = 251 - group.setCurrentTime(251); - QCOMPARE(group.currentTime(), 251); - QCOMPARE(sequence->currentTime(), 251); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 1); - QCOMPARE(a2_s_o1->currentLoop(), 0); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(sequence2->currentTime(), 251); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 1); - QCOMPARE(a1_p_o1->currentTime(), 250); - QCOMPARE(a1_p_o2->currentTime(), 1); - QCOMPARE(a1_p_o2->currentLoop(), 1); - QCOMPARE(a1_p_o3->currentTime(), 250); - QCOMPARE(notTimeDriven->currentTime(), 251); - QCOMPARE(loopsForever->currentTime(), 1); - QCOMPARE(sequence->currentAnimation(), a2_s_o1); -} - -void tst_QAnimationGroup::statesAndSignals() -{ -} - -void tst_QAnimationGroup::setParentAutoAdd() -{ - QParallelAnimationGroup group; - QVariantAnimation *animation = new QPropertyAnimation(&group); - QCOMPARE(animation->group(), &group); -} - -void tst_QAnimationGroup::beginNestedGroup() -{ - QAnimationGroup *subGroup; - QAnimationGroup *parent = new QParallelAnimationGroup(); - - for (int i = 0; i < 10; ++i) { - if (i & 1) - subGroup = new QParallelAnimationGroup(parent); - else - subGroup = new QSequentialAnimationGroup(parent); - - QCOMPARE(parent->animationCount(), 1); - QAnimationGroup *child = static_cast(parent->animationAt(0)); - - QCOMPARE(child->parent(), static_cast(parent)); - if (i & 1) - QVERIFY(qobject_cast (child)); - else - QVERIFY(qobject_cast (child)); - - parent = child; - } -} - -void tst_QAnimationGroup::addChildTwice() -{ - QPropertyAnimation *subGroup; - QPropertyAnimation *subGroup2; - QAnimationGroup *parent = new QSequentialAnimationGroup(); - - subGroup = new QPropertyAnimation(); - subGroup->setParent(parent); - parent->addAnimation(subGroup); - QCOMPARE(parent->animationCount(), 1); - - parent->clearAnimations(); - - QCOMPARE(parent->animationCount(), 0); - - // adding the same item twice to a group will remove the item from its current position - // and append it to the end - subGroup = new QPropertyAnimation(parent); - subGroup2 = new QPropertyAnimation(parent); - - QCOMPARE(parent->animationCount(), 2); - QCOMPARE(parent->animationAt(0), subGroup); - QCOMPARE(parent->animationAt(1), subGroup2); - - parent->addAnimation(subGroup); - - QCOMPARE(parent->animationCount(), 2); - QCOMPARE(parent->animationAt(0), subGroup2); - QCOMPARE(parent->animationAt(1), subGroup); - - delete parent; -} - -void tst_QAnimationGroup::loopWithoutStartValue() -{ - QAnimationGroup *parent = new QSequentialAnimationGroup(); - QObject o; - o.setProperty("ole", 0); - QCOMPARE(o.property("ole").toInt(), 0); - - QPropertyAnimation anim1(&o, "ole"); - anim1.setEndValue(-50); - anim1.setDuration(100); - - QPropertyAnimation anim2(&o, "ole"); - anim2.setEndValue(50); - anim2.setDuration(100); - - parent->addAnimation(&anim1); - parent->addAnimation(&anim2); - - parent->setLoopCount(-1); - parent->start(); - - QVERIFY(anim1.startValue().isNull()); - QCOMPARE(anim1.currentValue().toInt(), 0); - QCOMPARE(parent->currentLoop(), 0); - - parent->setCurrentTime(200); - QCOMPARE(parent->currentLoop(), 1); - QCOMPARE(anim1.currentValue().toInt(), 50); - parent->stop(); -} - -QTEST_MAIN(tst_QAnimationGroup) -#include "tst_qanimationgroup.moc" diff --git a/tests/auto/qeasingcurve/qeasingcurve.pro b/tests/auto/qeasingcurve/qeasingcurve.pro deleted file mode 100644 index 2b66081..0000000 --- a/tests/auto/qeasingcurve/qeasingcurve.pro +++ /dev/null @@ -1,3 +0,0 @@ -load(qttest_p4) -QT = core -SOURCES += tst_qeasingcurve.cpp diff --git a/tests/auto/qeasingcurve/tst_qeasingcurve.cpp b/tests/auto/qeasingcurve/tst_qeasingcurve.cpp deleted file mode 100644 index 8d42e5e..0000000 --- a/tests/auto/qeasingcurve/tst_qeasingcurve.cpp +++ /dev/null @@ -1,487 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - - -#include - -#if QT_VERSION < 0x040200 -QTEST_NOOP_MAIN -#else - -#include - -//TESTED_CLASS= -//TESTED_FILES= - -class tst_QEasingCurve : public QObject { - Q_OBJECT - -public: - tst_QEasingCurve(); - virtual ~tst_QEasingCurve(); - -public Q_SLOTS: - void init(); - void cleanup(); - -private slots: - void type(); - void propertyDefaults(); - void valueForProgress_data(); - void valueForProgress(); - void setCustomType(); - void operators(); - -protected: -}; - -tst_QEasingCurve::tst_QEasingCurve() -{ -} - -tst_QEasingCurve::~tst_QEasingCurve() -{ -} - -void tst_QEasingCurve::init() -{ -} - -void tst_QEasingCurve::cleanup() -{ -} -#include - -void tst_QEasingCurve::type() -{ - { - QEasingCurve curve(QEasingCurve::Linear); - QCOMPARE(curve.period(), 0.3); - QCOMPARE(curve.amplitude(), 1.0); - - curve.setPeriod(5); - curve.setAmplitude(3); - QCOMPARE(curve.period(), 5.0); - QCOMPARE(curve.amplitude(), 3.0); - - curve.setType(QEasingCurve::InElastic); - QCOMPARE(curve.period(), 5.0); - QCOMPARE(curve.amplitude(), 3.0); - } - - { - QEasingCurve curve(QEasingCurve::InElastic); - QCOMPARE(curve.period(), 0.3); - QCOMPARE(curve.amplitude(), 1.0); - curve.setAmplitude(2); - QCOMPARE(curve.type(), QEasingCurve::InElastic); - curve.setType(QEasingCurve::Linear); - } - - { - // check bounaries - QEasingCurve curve(QEasingCurve::InCubic); - QTest::ignoreMessage(QtWarningMsg, "QEasingCurve: Invalid curve type 9999"); - curve.setType((QEasingCurve::Type)9999); - QCOMPARE(curve.type(), QEasingCurve::InCubic); - QTest::ignoreMessage(QtWarningMsg, "QEasingCurve: Invalid curve type -9999"); - curve.setType((QEasingCurve::Type)-9999); - QCOMPARE(curve.type(), QEasingCurve::InCubic); - QTest::ignoreMessage(QtWarningMsg, QString::fromAscii("QEasingCurve: Invalid curve type %1") - .arg(QEasingCurve::NCurveTypes).toLatin1().constData()); - curve.setType(QEasingCurve::NCurveTypes); - QCOMPARE(curve.type(), QEasingCurve::InCubic); - QTest::ignoreMessage(QtWarningMsg, QString::fromAscii("QEasingCurve: Invalid curve type %1") - .arg(QEasingCurve::Custom).toLatin1().constData()); - curve.setType(QEasingCurve::Custom); - QCOMPARE(curve.type(), QEasingCurve::InCubic); - QTest::ignoreMessage(QtWarningMsg, QString::fromAscii("QEasingCurve: Invalid curve type %1") - .arg(-1).toLatin1().constData()); - curve.setType((QEasingCurve::Type)-1); - QCOMPARE(curve.type(), QEasingCurve::InCubic); - curve.setType(QEasingCurve::Linear); - QCOMPARE(curve.type(), QEasingCurve::Linear); - curve.setType(QEasingCurve::CosineCurve); - QCOMPARE(curve.type(), QEasingCurve::CosineCurve); - } -} - -void tst_QEasingCurve::propertyDefaults() -{ - { - // checks if the defaults are correct, but also demonstrates a weakness with the API. - QEasingCurve curve(QEasingCurve::InElastic); - QCOMPARE(curve.period(), 0.3); - QCOMPARE(curve.amplitude(), 1.0); - QCOMPARE(curve.overshoot(), qreal(1.70158f)); - curve.setType(QEasingCurve::InBounce); - QCOMPARE(curve.period(), 0.3); - QCOMPARE(curve.amplitude(), 1.0); - QCOMPARE(curve.overshoot(), qreal(1.70158f)); - curve.setType(QEasingCurve::Linear); - QCOMPARE(curve.period(), 0.3); - QCOMPARE(curve.amplitude(), 1.0); - QCOMPARE(curve.overshoot(), qreal(1.70158f)); - curve.setType(QEasingCurve::InElastic); - QCOMPARE(curve.period(), 0.3); - QCOMPARE(curve.amplitude(), 1.0); - QCOMPARE(curve.overshoot(), qreal(1.70158f)); - curve.setPeriod(0.4); - curve.setAmplitude(0.6); - curve.setOvershoot(1.0); - curve.setType(QEasingCurve::Linear); - QCOMPARE(curve.period(), 0.4); - QCOMPARE(curve.amplitude(), 0.6); - QCOMPARE(curve.overshoot(), 1.0); - curve.setType(QEasingCurve::InElastic); - QCOMPARE(curve.period(), 0.4); - QCOMPARE(curve.amplitude(), 0.6); - QCOMPARE(curve.overshoot(), 1.0); - } -} - -typedef QList IntList; -Q_DECLARE_METATYPE(IntList) - -void tst_QEasingCurve::valueForProgress_data() -{ - QTest::addColumn("type"); - QTest::addColumn("at"); - QTest::addColumn("expected"); - // automatically generated. - // note that values are scaled from range [0,1] to range [0, 100] in order to store them as - // integer values and avoid fp inaccuracies - - QTest::newRow("Linear") << int(QEasingCurve::Linear) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100); - - QTest::newRow("InQuad") << int(QEasingCurve::InQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 1 << 4 << 9 << 16 << 25 << 36 << 48 << 64 << 81 << 100); - - QTest::newRow("OutQuad") << int(QEasingCurve::OutQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 19 << 36 << 51 << 64 << 75 << 84 << 90 << 96 << 99 << 100); - - QTest::newRow("InOutQuad") << int(QEasingCurve::InOutQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 2 << 8 << 18 << 32 << 50 << 68 << 82 << 92 << 98 << 100); - - QTest::newRow("OutInQuad") << int(QEasingCurve::OutInQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 18 << 32 << 42 << 48 << 50 << 52 << 57 << 68 << 82 << 100); - - QTest::newRow("InCubic") << int(QEasingCurve::InCubic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 2 << 6 << 12 << 21 << 34 << 51 << 72 << 100); - - QTest::newRow("OutCubic") << int(QEasingCurve::OutCubic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 27 << 48 << 65 << 78 << 87 << 93 << 97 << 99 << 99 << 100); - - QTest::newRow("InOutCubic") << int(QEasingCurve::InOutCubic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 3 << 10 << 25 << 50 << 74 << 89 << 96 << 99 << 100); - - QTest::newRow("OutInCubic") << int(QEasingCurve::OutInCubic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 24 << 39 << 46 << 49 << 50 << 50 << 53 << 60 << 75 << 100); - - QTest::newRow("InQuart") << int(QEasingCurve::InQuart) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 0 << 2 << 6 << 12 << 24 << 40 << 65 << 100); - - QTest::newRow("OutQuart") << int(QEasingCurve::OutQuart) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 34 << 59 << 75 << 87 << 93 << 97 << 99 << 99 << 99 << 100); - - QTest::newRow("InOutQuart") << int(QEasingCurve::InOutQuart) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 1 << 6 << 20 << 50 << 79 << 93 << 98 << 99 << 100); - - QTest::newRow("OutInQuart") << int(QEasingCurve::OutInQuart) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 29 << 43 << 48 << 49 << 50 << 50 << 51 << 56 << 70 << 100); - - QTest::newRow("InQuint") << int(QEasingCurve::InQuint) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 0 << 1 << 3 << 7 << 16 << 32 << 59 << 100); - - QTest::newRow("OutQuint") << int(QEasingCurve::OutQuint) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 40 << 67 << 83 << 92 << 96 << 98 << 99 << 99 << 99 << 100); - - QTest::newRow("InOutQuint") << int(QEasingCurve::InOutQuint) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 3 << 16 << 50 << 83 << 96 << 99 << 99 << 100); - - QTest::newRow("OutInQuint") << int(QEasingCurve::OutInQuint) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 33 << 46 << 49 << 49 << 50 << 50 << 50 << 53 << 66 << 100); - - QTest::newRow("InSine") << int(QEasingCurve::InSine) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 1 << 4 << 10 << 19 << 29 << 41 << 54 << 69 << 84 << 100); - - QTest::newRow("OutSine") << int(QEasingCurve::OutSine) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 15 << 30 << 45 << 58 << 70 << 80 << 89 << 95 << 98 << 100); - - QTest::newRow("InOutSine") << int(QEasingCurve::InOutSine) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 2 << 9 << 20 << 34 << 49 << 65 << 79 << 90 << 97 << 100); - - QTest::newRow("OutInSine") << int(QEasingCurve::OutInSine) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 15 << 29 << 40 << 47 << 50 << 52 << 59 << 70 << 84 << 100); - - QTest::newRow("InExpo") << int(QEasingCurve::InExpo) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 0 << 1 << 3 << 6 << 12 << 24 << 49 << 100); - - QTest::newRow("OutExpo") << int(QEasingCurve::OutExpo) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 50 << 75 << 87 << 93 << 96 << 98 << 99 << 99 << 99 << 100); - - QTest::newRow("InOutExpo") << int(QEasingCurve::InOutExpo) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 3 << 12 << 50 << 87 << 96 << 99 << 99 << 100); - - QTest::newRow("OutInExpo") << int(QEasingCurve::OutInExpo) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 37 << 46 << 49 << 49 << 50 << 50 << 50 << 53 << 62 << 100); - - QTest::newRow("InCirc") << int(QEasingCurve::InCirc) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 2 << 4 << 8 << 13 << 19 << 28 << 40 << 56 << 100); - - QTest::newRow("OutCirc") << int(QEasingCurve::OutCirc) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 43 << 59 << 71 << 80 << 86 << 91 << 95 << 97 << 99 << 100); - - QTest::newRow("InOutCirc") << int(QEasingCurve::InOutCirc) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 1 << 4 << 9 << 20 << 50 << 80 << 89 << 95 << 98 << 100); - - QTest::newRow("OutInCirc") << int(QEasingCurve::OutInCirc) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 29 << 40 << 45 << 48 << 50 << 51 << 54 << 60 << 70 << 100); - - QTest::newRow("InElastic") << int(QEasingCurve::InElastic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 0 << 1 << -1 << -3 << 12 << -12 << -25 << 100); - - QTest::newRow("OutElastic") << int(QEasingCurve::OutElastic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 125 << 112 << 87 << 103 << 101 << 98 << 100 << 100 << 99 << 100); - - QTest::newRow("InOutElastic") << int(QEasingCurve::InOutElastic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << -1 << -6 << 50 << 106 << 101 << 99 << 100 << 100); - - QTest::newRow("OutInElastic") << int(QEasingCurve::OutInElastic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 37 << 56 << 49 << 49 << 50 << 49 << 50 << 53 << 24 << 100); - - QTest::newRow("InBack") << int(QEasingCurve::InBack) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << -1 << -4 << -8 << -9 << -8 << -2 << 9 << 29 << 59 << 100); - - QTest::newRow("OutBack") << int(QEasingCurve::OutBack) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 40 << 70 << 90 << 102 << 108 << 109 << 108 << 104 << 101 << 100); - - QTest::newRow("InOutBack") << int(QEasingCurve::InOutBack) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << -3 << -9 << -7 << 8 << 50 << 91 << 107 << 109 << 103 << 100); - - QTest::newRow("OutInBack") << int(QEasingCurve::OutInBack) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 35 << 51 << 54 << 52 << 50 << 47 << 45 << 48 << 64 << 100); - - QTest::newRow("InBounce") << int(QEasingCurve::InBounce) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 1 << 6 << 6 << 22 << 23 << 9 << 31 << 69 << 92 << 100); - - QTest::newRow("OutBounce") << int(QEasingCurve::OutBounce) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 7 << 30 << 68 << 90 << 76 << 77 << 93 << 94 << 98 << 100); - - QTest::newRow("InOutBounce") << int(QEasingCurve::InOutBounce) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 3 << 11 << 4 << 34 << 50 << 65 << 95 << 88 << 97 << 100); - - QTest::newRow("OutInBounce") << int(QEasingCurve::OutInBounce) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 15 << 40 << 27 << 43 << 50 << 56 << 72 << 58 << 84 << 100); - - QTest::newRow("InCurve") << int(QEasingCurve::InCurve) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 2 << 10 << 23 << 37 << 50 << 60 << 70 << 80 << 90 << 100); - - QTest::newRow("OutCurve") << int(QEasingCurve::OutCurve) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 10 << 20 << 30 << 39 << 50 << 62 << 76 << 89 << 97 << 100); - - QTest::newRow("SineCurve") << int(QEasingCurve::SineCurve) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 9 << 34 << 65 << 90 << 100 << 90 << 65 << 34 << 9 << 0); - - QTest::newRow("CosineCurve") << int(QEasingCurve::CosineCurve) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 50 << 79 << 97 << 97 << 79 << 50 << 20 << 2 << 2 << 20 << 49); - -} - - -void tst_QEasingCurve::valueForProgress() -{ -#if 0 - // used to generate data tables... - QFile out; - out.open(stdout, QIODevice::WriteOnly); - for (int c = QEasingCurve::Linear; c < QEasingCurve::NCurveTypes - 1; ++c) { - QEasingCurve curve((QEasingCurve::Type)c); - QMetaObject mo = QEasingCurve::staticMetaObject; - QString strCurve = QLatin1String(mo.enumerator(mo.indexOfEnumerator("Type")).key(c)); - QString strInputs; - QString strOutputs; - - for (int t = 0; t <= 100; t+= 10) { - qreal ease = curve.valueForProgress(t/qreal(100)); - strInputs += QString::fromAscii(" << %1").arg(t); - strOutputs += QString::fromAscii(" << %1").arg(int(100*ease)); - - } - QString str = QString::fromAscii(" QTest::newRow(\"%1\") << int(QEasingCurve::%2)\n" - "\t\t << (IntList() %3)\n" - "\t\t << (IntList() %4);\n\n") - .arg(strCurve) - .arg(strCurve) - .arg(strInputs) - .arg(strOutputs); - out.write(str.toLatin1().constData()); - } - out.close(); - exit(1); -#else - QFETCH(int, type); - QFETCH(IntList, at); - QFETCH(IntList, expected); - - QEasingCurve curve((QEasingCurve::Type)type); - for (int i = 0; i < at.count(); ++i) { - qreal ease = curve.valueForProgress(at.at(i)/qreal(100)); - int ex = expected.at(i); - QCOMPARE(int(100*ease), ex); - } -#endif -} - -static qreal discreteEase(qreal progress) -{ - return qFloor(progress * 10) / qreal(10.0); -} - -void tst_QEasingCurve::setCustomType() -{ - QEasingCurve curve; - curve.setCustomType(&discreteEase); - QCOMPARE(curve.type(), QEasingCurve::Custom); - QCOMPARE(curve.valueForProgress(0.0), 0.0); - QCOMPARE(curve.valueForProgress(0.05), 0.0); - QCOMPARE(curve.valueForProgress(0.10), 0.1); - QCOMPARE(curve.valueForProgress(0.15), 0.1); - QCOMPARE(curve.valueForProgress(0.20), 0.2); - QCOMPARE(curve.valueForProgress(0.25), 0.2); - QCOMPARE(curve.valueForProgress(0.30), 0.3); - QCOMPARE(curve.valueForProgress(0.35), 0.3); - QCOMPARE(curve.valueForProgress(0.999999), 0.9); - - curve.setType(QEasingCurve::Linear); - QCOMPARE(curve.type(), QEasingCurve::Linear); - QCOMPARE(curve.valueForProgress(0.0), 0.0); - QCOMPARE(curve.valueForProgress(0.1), 0.1); - QCOMPARE(curve.valueForProgress(0.5), 0.5); - QCOMPARE(curve.valueForProgress(0.99), 0.99); -} - -void tst_QEasingCurve::operators() -{ - // operator= - QEasingCurve curve; - QEasingCurve curve2; - curve.setCustomType(&discreteEase); - curve2 = curve; - QCOMPARE(curve2.type(), QEasingCurve::Custom); - QCOMPARE(curve2.valueForProgress(0.0), 0.0); - QCOMPARE(curve2.valueForProgress(0.05), 0.0); - QCOMPARE(curve2.valueForProgress(0.15), 0.1); - QCOMPARE(curve2.valueForProgress(0.25), 0.2); - QCOMPARE(curve2.valueForProgress(0.35), 0.3); - QCOMPARE(curve2.valueForProgress(0.999999), 0.9); - - // operator== - curve.setType(QEasingCurve::InBack); - curve2 = curve; - curve2.setOvershoot(qreal(1.70158f)); - QCOMPARE(curve.overshoot(), curve2.overshoot()); - QVERIFY(curve2 == curve); - - curve.setOvershoot(3.0); - QVERIFY(curve2 != curve); - curve2.setOvershoot(3.0); - QVERIFY(curve2 == curve); - - curve2.setType(QEasingCurve::Linear); - QCOMPARE(curve.overshoot(), curve2.overshoot()); - QVERIFY(curve2 != curve); - curve2.setType(QEasingCurve::InBack); - QCOMPARE(curve.overshoot(), curve2.overshoot()); - QVERIFY(curve2 == curve); -} - - -QTEST_MAIN(tst_QEasingCurve) -#include "tst_qeasingcurve.moc" - -#endif //QT_VERSION diff --git a/tests/auto/qmake/testdata/bundle-spaces/some-file b/tests/auto/qmake/testdata/bundle-spaces/some-file index 9975dba..e69de29 100644 --- a/tests/auto/qmake/testdata/bundle-spaces/some-file +++ b/tests/auto/qmake/testdata/bundle-spaces/some-file @@ -1,6 +0,0 @@ -all: - C:\git\qt-kinetic-animations\bin\qmake qdir.pro -o Makefile -spec win32-msvc2008 - nmake -f Makefile -first: all -qmake: - C:\git\qt-kinetic-animations\bin\qmake qdir.pro -o Makefile -spec win32-msvc2008 diff --git a/tests/auto/qparallelanimationgroup/qparallelanimationgroup.pro b/tests/auto/qparallelanimationgroup/qparallelanimationgroup.pro deleted file mode 100644 index f2cacd3..0000000 --- a/tests/auto/qparallelanimationgroup/qparallelanimationgroup.pro +++ /dev/null @@ -1,5 +0,0 @@ -load(qttest_p4) -QT = core gui -SOURCES += tst_qparallelanimationgroup.cpp - - diff --git a/tests/auto/qparallelanimationgroup/tst_qparallelanimationgroup.cpp b/tests/auto/qparallelanimationgroup/tst_qparallelanimationgroup.cpp deleted file mode 100644 index f2ab57a..0000000 --- a/tests/auto/qparallelanimationgroup/tst_qparallelanimationgroup.cpp +++ /dev/null @@ -1,834 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include - -//TESTED_CLASS=QParallelAnimationGroup -//TESTED_FILES= - -Q_DECLARE_METATYPE(QAbstractAnimation::State) - -class tst_QParallelAnimationGroup : public QObject -{ - Q_OBJECT -public: - tst_QParallelAnimationGroup(); - virtual ~tst_QParallelAnimationGroup(); - -public Q_SLOTS: - void init(); - void cleanup(); - -private slots: - void construction(); - void setCurrentTime(); - void clearGroup(); - void propagateGroupUpdateToChildren(); - void updateChildrenWithRunningGroup(); - void deleteChildrenWithRunningGroup(); - void startChildrenWithStoppedGroup(); - void stopGroupWithRunningChild(); - void startGroupWithRunningChild(); - void zeroDurationAnimation(); - void stopUncontrolledAnimations(); - void loopCount_data(); - void loopCount(); - void autoAdd(); -}; - -tst_QParallelAnimationGroup::tst_QParallelAnimationGroup() -{ -} - -tst_QParallelAnimationGroup::~tst_QParallelAnimationGroup() -{ -} - -void tst_QParallelAnimationGroup::init() -{ - qRegisterMetaType("QAbstractAnimation::State"); -} - -void tst_QParallelAnimationGroup::cleanup() -{ -} - -void tst_QParallelAnimationGroup::construction() -{ - QParallelAnimationGroup animationgroup; -} - -class AnimationObject : public QObject -{ - Q_OBJECT - Q_PROPERTY(int value READ value WRITE setValue) -public: - AnimationObject(int startValue = 0) - : v(startValue) - { } - - int value() const { return v; } - void setValue(int value) { v = value; } - - int v; -}; - -class TestAnimation : public QVariantAnimation -{ - Q_OBJECT -public: - virtual void updateCurrentValue(const QVariant &value) { Q_UNUSED(value)}; - virtual void updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) - { - Q_UNUSED(oldState) - Q_UNUSED(newState) - }; -}; - -class TestAnimation2 : public QVariantAnimation -{ - Q_OBJECT -public: - TestAnimation2(QAbstractAnimation *animation) : QVariantAnimation(animation) {} - TestAnimation2(int duration, QAbstractAnimation *animation) : QVariantAnimation(animation), m_duration(duration) {} - - virtual void updateCurrentValue(const QVariant &value) { Q_UNUSED(value)}; - virtual void updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) - { - Q_UNUSED(oldState) - Q_UNUSED(newState) - }; - - virtual int duration() const { - return m_duration; - } -private: - int m_duration; -}; - -class UncontrolledAnimation : public QPropertyAnimation -{ - Q_OBJECT -public: - UncontrolledAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0) - : QPropertyAnimation(target, propertyName, parent), id(0) - { - setDuration(250); - } - - int duration() const { return -1; /* not time driven */ } - -protected: - void timerEvent(QTimerEvent *event) - { - if (event->timerId() == id) - stop(); - } - - void updateRunning(bool running) - { - if (running) { - id = startTimer(500); - } else { - killTimer(id); - id = 0; - } - } - -private: - int id; -}; - -void tst_QParallelAnimationGroup::setCurrentTime() -{ - AnimationObject p_o1; - AnimationObject p_o2; - AnimationObject p_o3; - AnimationObject t_o1; - AnimationObject t_o2; - - // parallel operating on different object/properties - QAnimationGroup *parallel = new QParallelAnimationGroup(); - QVariantAnimation *a1_p_o1 = new QPropertyAnimation(&p_o1, "value"); - QVariantAnimation *a1_p_o2 = new QPropertyAnimation(&p_o2, "value"); - QVariantAnimation *a1_p_o3 = new QPropertyAnimation(&p_o3, "value"); - a1_p_o2->setLoopCount(3); - parallel->addAnimation(a1_p_o1); - parallel->addAnimation(a1_p_o2); - parallel->addAnimation(a1_p_o3); - - UncontrolledAnimation *notTimeDriven = new UncontrolledAnimation(&t_o1, "value"); - QCOMPARE(notTimeDriven->totalDuration(), -1); - - QVariantAnimation *loopsForever = new QPropertyAnimation(&t_o2, "value"); - loopsForever->setLoopCount(-1); - QCOMPARE(loopsForever->totalDuration(), -1); - - QParallelAnimationGroup group; - group.addAnimation(parallel); - group.addAnimation(notTimeDriven); - group.addAnimation(loopsForever); - - // Current time = 1 - group.setCurrentTime(1); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(parallel->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_p_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_p_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_p_o3->state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); - - QCOMPARE(group.currentTime(), 1); - QCOMPARE(a1_p_o1->currentTime(), 1); - QCOMPARE(a1_p_o2->currentTime(), 1); - QCOMPARE(a1_p_o3->currentTime(), 1); - QCOMPARE(notTimeDriven->currentTime(), 1); - QCOMPARE(loopsForever->currentTime(), 1); - - // Current time = 250 - group.setCurrentTime(250); - QCOMPARE(group.currentTime(), 250); - QCOMPARE(a1_p_o1->currentTime(), 250); - QCOMPARE(a1_p_o2->currentTime(), 0); - QCOMPARE(a1_p_o2->currentLoop(), 1); - QCOMPARE(a1_p_o3->currentTime(), 250); - QCOMPARE(notTimeDriven->currentTime(), 250); - QCOMPARE(loopsForever->currentTime(), 0); - QCOMPARE(loopsForever->currentLoop(), 1); - - // Current time = 251 - group.setCurrentTime(251); - QCOMPARE(group.currentTime(), 251); - QCOMPARE(a1_p_o1->currentTime(), 250); - QCOMPARE(a1_p_o2->currentTime(), 1); - QCOMPARE(a1_p_o2->currentLoop(), 1); - QCOMPARE(a1_p_o3->currentTime(), 250); - QCOMPARE(notTimeDriven->currentTime(), 251); - QCOMPARE(loopsForever->currentTime(), 1); -} - -void tst_QParallelAnimationGroup::clearGroup() -{ - QParallelAnimationGroup group; - - for (int i = 0; i < 10; ++i) { - new QParallelAnimationGroup(&group); - } - - QCOMPARE(group.animationCount(), 10); - - int count = group.animationCount(); - QPointer *children = new QPointer[count]; - for (int i = 0; i < count; ++i) { - QVERIFY(group.animationAt(i) != 0); - children[i] = group.animationAt(i); - } - - group.clearAnimations(); - QCOMPARE(group.animationCount(), 0); - QCOMPARE(group.currentTime(), 0); - for (int i = 0; i < count; ++i) - QCOMPARE(children[i], QPointer()); - - delete[] children; -} - -void tst_QParallelAnimationGroup::propagateGroupUpdateToChildren() -{ - // this test verifies if group state changes are updating its children correctly - QParallelAnimationGroup group; - - QObject o; - o.setProperty("ole", 42); - QCOMPARE(o.property("ole").toInt(), 42); - - QPropertyAnimation anim1(&o, "ole"); - anim1.setEndValue(43); - anim1.setDuration(100); - QVERIFY(!anim1.currentValue().isValid()); - QCOMPARE(anim1.currentValue().toInt(), 0); - QCOMPARE(o.property("ole").toInt(), 42); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(200); - - QVERIFY(anim2.currentValue().isValid()); - QCOMPARE(anim2.currentValue().toInt(), 0); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - - group.start(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Running); - - group.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Paused); - QCOMPARE(anim1.state(), QAnimationGroup::Paused); - QCOMPARE(anim2.state(), QAnimationGroup::Paused); - - group.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); -} - -void tst_QParallelAnimationGroup::updateChildrenWithRunningGroup() -{ - // assert that its possible to modify a child's state directly while their group is running - QParallelAnimationGroup group; - - TestAnimation anim; - anim.setStartValue(0); - anim.setEndValue(100); - anim.setDuration(200); - - QSignalSpy groupStateChangedSpy(&group, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy childStateChangedSpy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - QCOMPARE(groupStateChangedSpy.count(), 0); - QCOMPARE(childStateChangedSpy.count(), 0); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim); - - group.start(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim.state(), QAnimationGroup::Running); - - QCOMPARE(groupStateChangedSpy.count(), 1); - QCOMPARE(childStateChangedSpy.count(), 1); - - QCOMPARE(qVariantValue(groupStateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(childStateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - - // starting directly a running child will not have any effect - anim.start(); - - QCOMPARE(groupStateChangedSpy.count(), 1); - QCOMPARE(childStateChangedSpy.count(), 1); - - anim.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim.state(), QAnimationGroup::Paused); - - // in the animation stops directly, the group will still be running - anim.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim.state(), QAnimationGroup::Stopped); -} - -void tst_QParallelAnimationGroup::deleteChildrenWithRunningGroup() -{ - // test if children can be activated when their group is stopped - QParallelAnimationGroup group; - - QVariantAnimation *anim1 = new TestAnimation; - anim1->setStartValue(0); - anim1->setEndValue(100); - anim1->setDuration(200); - group.addAnimation(anim1); - - QCOMPARE(group.duration(), anim1->duration()); - - group.start(); - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim1->state(), QAnimationGroup::Running); - - QTest::qWait(50); - QVERIFY(group.currentTime() > 0); - - delete anim1; - QVERIFY(group.animationCount() == 0); - QCOMPARE(group.duration(), 0); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(group.currentTime(), 0); //that's the invariant -} - -void tst_QParallelAnimationGroup::startChildrenWithStoppedGroup() -{ - // test if children can be activated when their group is stopped - QParallelAnimationGroup group; - - TestAnimation anim1; - anim1.setStartValue(0); - anim1.setEndValue(100); - anim1.setDuration(200); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(200); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - - group.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - anim1.start(); - anim2.start(); - anim2.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Paused); -} - -void tst_QParallelAnimationGroup::stopGroupWithRunningChild() -{ - // children that started independently will not be affected by a group stop - QParallelAnimationGroup group; - - TestAnimation anim1; - anim1.setStartValue(0); - anim1.setEndValue(100); - anim1.setDuration(200); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(200); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - - anim1.start(); - anim2.start(); - anim2.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Paused); - - group.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Paused); - - anim1.stop(); - anim2.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); -} - -void tst_QParallelAnimationGroup::startGroupWithRunningChild() -{ - // as the group has precedence over its children, starting a group will restart all the children - QParallelAnimationGroup group; - - TestAnimation anim1; - anim1.setStartValue(0); - anim1.setEndValue(100); - anim1.setDuration(200); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(200); - - QSignalSpy stateChangedSpy1(&anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy stateChangedSpy2(&anim2, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - QCOMPARE(stateChangedSpy1.count(), 0); - QCOMPARE(stateChangedSpy2.count(), 0); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - - anim1.start(); - anim2.start(); - anim2.pause(); - - QCOMPARE(qVariantValue(stateChangedSpy1.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(stateChangedSpy2.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(stateChangedSpy2.at(1).at(1)), - QAnimationGroup::Paused); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Paused); - - group.start(); - - QCOMPARE(stateChangedSpy1.count(), 3); - QCOMPARE(qVariantValue(stateChangedSpy1.at(1).at(1)), - QAnimationGroup::Stopped); - QCOMPARE(qVariantValue(stateChangedSpy1.at(2).at(1)), - QAnimationGroup::Running); - - QCOMPARE(stateChangedSpy2.count(), 4); - QCOMPARE(qVariantValue(stateChangedSpy2.at(2).at(1)), - QAnimationGroup::Stopped); - QCOMPARE(qVariantValue(stateChangedSpy2.at(3).at(1)), - QAnimationGroup::Running); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Running); -} - -void tst_QParallelAnimationGroup::zeroDurationAnimation() -{ - QParallelAnimationGroup group; - - TestAnimation anim1; - anim1.setStartValue(0); - anim1.setEndValue(100); - anim1.setDuration(0); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(100); - - QSignalSpy stateChangedSpy1(&anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy finishedSpy1(&anim1, SIGNAL(finished())); - - QSignalSpy stateChangedSpy2(&anim2, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy finishedSpy2(&anim2, SIGNAL(finished())); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - QCOMPARE(stateChangedSpy1.count(), 0); - group.start(); - QCOMPARE(stateChangedSpy1.count(), 2); - QCOMPARE(finishedSpy1.count(), 1); - QCOMPARE(qVariantValue(stateChangedSpy1.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(stateChangedSpy1.at(1).at(1)), - QAnimationGroup::Stopped); - - QCOMPARE(stateChangedSpy2.count(), 1); - QCOMPARE(finishedSpy2.count(), 0); - QCOMPARE(qVariantValue(stateChangedSpy1.at(0).at(1)), - QAnimationGroup::Running); - - - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Running); - QCOMPARE(group.state(), QAnimationGroup::Running); - - - group.stop(); - group.setLoopCount(4); - stateChangedSpy1.clear(); - stateChangedSpy2.clear(); - - group.start(); - QCOMPARE(stateChangedSpy1.count(), 2); - QCOMPARE(stateChangedSpy2.count(), 1); - group.setCurrentTime(50); - QCOMPARE(stateChangedSpy1.count(), 2); - QCOMPARE(stateChangedSpy2.count(), 1); - group.setCurrentTime(150); - QCOMPARE(stateChangedSpy1.count(), 4); - QCOMPARE(stateChangedSpy2.count(), 3); - group.setCurrentTime(50); - QCOMPARE(stateChangedSpy1.count(), 6); - QCOMPARE(stateChangedSpy2.count(), 5); - -} - -void tst_QParallelAnimationGroup::stopUncontrolledAnimations() -{ - QParallelAnimationGroup group; - - TestAnimation anim1; - anim1.setStartValue(0); - anim1.setEndValue(100); - anim1.setDuration(0); - - AnimationObject o1; - UncontrolledAnimation notTimeDriven(&o1, "value"); - QCOMPARE(notTimeDriven.totalDuration(), -1); - - TestAnimation loopsForever; - loopsForever.setStartValue(0); - loopsForever.setEndValue(100); - loopsForever.setDuration(100); - loopsForever.setLoopCount(-1); - - QSignalSpy stateChangedSpy(&anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - group.addAnimation(&anim1); - group.addAnimation(¬TimeDriven); - group.addAnimation(&loopsForever); - - group.start(); - - QCOMPARE(stateChangedSpy.count(), 2); - QCOMPARE(qVariantValue(stateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(stateChangedSpy.at(1).at(1)), - QAnimationGroup::Stopped); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Running); - QCOMPARE(loopsForever.state(), QAnimationGroup::Running); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - - notTimeDriven.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever.state(), QAnimationGroup::Running); - - loopsForever.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever.state(), QAnimationGroup::Stopped); -} - -struct AnimState { - AnimState(int time = -1) : time(time), state(-1) {} - AnimState(int time, int state) : time(time), state(state) {} - int time; - int state; -}; - -#define Running QAbstractAnimation::Running -#define Stopped QAbstractAnimation::Stopped - -Q_DECLARE_METATYPE(AnimState) -void tst_QParallelAnimationGroup::loopCount_data() -{ - QTest::addColumn("directionBackward"); - QTest::addColumn("setLoopCount"); - QTest::addColumn("initialGroupTime"); - QTest::addColumn("currentGroupTime"); - QTest::addColumn("expected1"); - QTest::addColumn("expected2"); - QTest::addColumn("expected3"); - - // D U R A T I O N - // 100 60*2 0 - // direction = Forward - QTest::newRow("50") << false << 3 << 0 << 50 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("100") << false << 3 << 0 << 100 << AnimState(100 ) << AnimState( 40, Running) << AnimState( 0, Stopped); - QTest::newRow("110") << false << 3 << 0 << 110 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("120") << false << 3 << 0 << 120 << AnimState( 0, Running) << AnimState( 0, Running) << AnimState( 0, Stopped); - - QTest::newRow("170") << false << 3 << 0 << 170 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("220") << false << 3 << 0 << 220 << AnimState(100 ) << AnimState( 40, Running) << AnimState( 0, Stopped); - QTest::newRow("230") << false << 3 << 0 << 230 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("240") << false << 3 << 0 << 240 << AnimState( 0, Running) << AnimState( 0, Running) << AnimState( 0, Stopped); - - QTest::newRow("290") << false << 3 << 0 << 290 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("340") << false << 3 << 0 << 340 << AnimState(100 ) << AnimState( 40, Running) << AnimState( 0, Stopped); - QTest::newRow("350") << false << 3 << 0 << 350 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("360") << false << 3 << 0 << 360 << AnimState(100, Stopped) << AnimState( 60 ) << AnimState( 0, Stopped); - - QTest::newRow("410") << false << 3 << 0 << 410 << AnimState(100, Stopped) << AnimState( 60, Stopped) << AnimState( 0, Stopped); - QTest::newRow("460") << false << 3 << 0 << 460 << AnimState(100, Stopped) << AnimState( 60, Stopped) << AnimState( 0, Stopped); - QTest::newRow("470") << false << 3 << 0 << 470 << AnimState(100, Stopped) << AnimState( 60, Stopped) << AnimState( 0, Stopped); - QTest::newRow("480") << false << 3 << 0 << 480 << AnimState(100, Stopped) << AnimState( 60, Stopped) << AnimState( 0, Stopped); - - // direction = Forward, rewind - QTest::newRow("120-110") << false << 3 << 120 << 110 << AnimState( 0, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("120-50") << false << 3 << 120 << 50 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("120-0") << false << 3 << 120 << 0 << AnimState( 0, Running) << AnimState( 0, Running) << AnimState( 0, Stopped); - QTest::newRow("300-110") << false << 3 << 300 << 110 << AnimState( 0, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("300-50") << false << 3 << 300 << 50 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("300-0") << false << 3 << 300 << 0 << AnimState( 0, Running) << AnimState( 0, Running) << AnimState( 0, Stopped); - QTest::newRow("115-105") << false << 3 << 115 << 105 << AnimState( 42, Stopped) << AnimState( 45, Running) << AnimState( 0, Stopped); - - // direction = Backward - QTest::newRow("b120-120") << true << 3 << 120 << 120 << AnimState( 42, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); - QTest::newRow("b120-110") << true << 3 << 120 << 110 << AnimState( 42, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("b120-100") << true << 3 << 120 << 100 << AnimState(100, Running) << AnimState( 40, Running) << AnimState( 0, Stopped); - QTest::newRow("b120-50") << true << 3 << 120 << 50 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("b120-0") << true << 3 << 120 << 0 << AnimState( 0, Stopped) << AnimState( 0, Stopped) << AnimState( 0, Stopped); - QTest::newRow("b360-170") << true << 3 << 360 << 170 << AnimState( 50, Running) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("b360-220") << true << 3 << 360 << 220 << AnimState(100, Running) << AnimState( 40, Running) << AnimState( 0, Stopped); - QTest::newRow("b360-210") << true << 3 << 360 << 210 << AnimState( 90, Running) << AnimState( 30, Running) << AnimState( 0, Stopped); - QTest::newRow("b360-120") << true << 3 << 360 << 120 << AnimState( 0, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); - - // rewind, direction = Backward - QTest::newRow("b50-110") << true << 3 << 50 << 110 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - QTest::newRow("b50-120") << true << 3 << 50 << 120 << AnimState(100, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); - QTest::newRow("b50-140") << true << 3 << 50 << 140 << AnimState( 20, Running) << AnimState( 20, Running) << AnimState( 0, Stopped); - QTest::newRow("b50-240") << true << 3 << 50 << 240 << AnimState(100, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); - QTest::newRow("b50-260") << true << 3 << 50 << 260 << AnimState( 20, Running) << AnimState( 20, Running) << AnimState( 0, Stopped); - QTest::newRow("b50-350") << true << 3 << 50 << 350 << AnimState(100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - - // infinite looping - QTest::newRow("inf1220") << false << -1 << 0 << 1220 << AnimState( 20, Running) << AnimState( 20, Running) << AnimState( 0, Stopped); - QTest::newRow("inf1310") << false << -1 << 0 << 1310 << AnimState( 100, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - // infinite looping, direction = Backward (will only loop once) - QTest::newRow("b.inf120-120") << true << -1 << 120 << 120 << AnimState( 42, Stopped) << AnimState( 60, Running) << AnimState( 0, Stopped); - QTest::newRow("b.inf120-20") << true << -1 << 120 << 20 << AnimState( 20, Running) << AnimState( 20, Running) << AnimState( 0, Stopped); - QTest::newRow("b.inf120-110") << true << -1 << 120 << 110 << AnimState( 42, Stopped) << AnimState( 50, Running) << AnimState( 0, Stopped); - - -} - -void tst_QParallelAnimationGroup::loopCount() -{ - QFETCH(bool, directionBackward); - QFETCH(int, setLoopCount); - QFETCH(int, initialGroupTime); - QFETCH(int, currentGroupTime); - QFETCH(AnimState, expected1); - QFETCH(AnimState, expected2); - QFETCH(AnimState, expected3); - - QParallelAnimationGroup group; - - TestAnimation anim1; - anim1.setStartValue(0); - anim1.setEndValue(100); - anim1.setDuration(100); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(60); //total 120 - anim2.setLoopCount(2); - - TestAnimation anim3; - anim3.setStartValue(0); - anim3.setEndValue(100); - anim3.setDuration(0); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - group.addAnimation(&anim3); - - group.setLoopCount(setLoopCount); - if (initialGroupTime >= 0) - group.setCurrentTime(initialGroupTime); - if (directionBackward) - group.setDirection(QAbstractAnimation::Backward); - - group.start(); - if (initialGroupTime >= 0) - group.setCurrentTime(initialGroupTime); - - anim1.setCurrentTime(42); // 42 is "untouched" - anim2.setCurrentTime(42); - - group.setCurrentTime(currentGroupTime); - - QCOMPARE(anim1.currentTime(), expected1.time); - QCOMPARE(anim2.currentTime(), expected2.time); - QCOMPARE(anim3.currentTime(), expected3.time); - - if (expected1.state >=0) - QCOMPARE(int(anim1.state()), expected1.state); - if (expected2.state >=0) - QCOMPARE(int(anim2.state()), expected2.state); - if (expected3.state >=0) - QCOMPARE(int(anim3.state()), expected3.state); - -} - -void tst_QParallelAnimationGroup::autoAdd() -{ - QParallelAnimationGroup group; - QCOMPARE(group.duration(), 0); - TestAnimation2 *test = new TestAnimation2(250, &group); // 0, duration = 250; - QCOMPARE(test->group(), &group); - QCOMPARE(test->duration(), 250); - QCOMPARE(group.duration(), 250); - - test = new TestAnimation2(750, &group); // 1 - QCOMPARE(test->group(), &group); - QCOMPARE(group.duration(), 750); - test = new TestAnimation2(500, &group); // 2 - QCOMPARE(test->group(), &group); - QCOMPARE(group.duration(), 750); - - delete group.animationAt(1); // remove the one with duration = 750 - QCOMPARE(group.duration(), 500); - - delete group.animationAt(1); // remove the one with duration = 500 - QCOMPARE(group.duration(), 250); - - test = static_cast(group.animationAt(0)); - test->setParent(0); // remove the last one (with duration = 250) - QCOMPARE(test->group(), static_cast(0)); - QCOMPARE(group.duration(), 0); -} - -QTEST_MAIN(tst_QParallelAnimationGroup) -#include "tst_qparallelanimationgroup.moc" diff --git a/tests/auto/qpropertyanimation/qpropertyanimation.pro b/tests/auto/qpropertyanimation/qpropertyanimation.pro deleted file mode 100644 index 6d6ddbf..0000000 --- a/tests/auto/qpropertyanimation/qpropertyanimation.pro +++ /dev/null @@ -1,5 +0,0 @@ -load(qttest_p4) -QT = core gui -SOURCES += tst_qpropertyanimation.cpp - - diff --git a/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp b/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp deleted file mode 100644 index 7e910d4..0000000 --- a/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp +++ /dev/null @@ -1,919 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include -#include -#include - -//TESTED_CLASS=QPropertyAnimation -//TESTED_FILES= - -class UncontrolledAnimation : public QPropertyAnimation -{ - Q_OBJECT -public: - int duration() const { return -1; /* not time driven */ } - -protected: - void updateCurrentTime(int msecs) - { - QPropertyAnimation::updateCurrentTime(msecs); - if (msecs >= QPropertyAnimation::duration()) - stop(); - } -}; - -class tst_QPropertyAnimation : public QObject -{ - Q_OBJECT -public: - tst_QPropertyAnimation(); - virtual ~tst_QPropertyAnimation(); - -public Q_SLOTS: - void init(); - void cleanup(); - -private slots: - void construction(); - void setCurrentTime_data(); - void setCurrentTime(); - void statesAndSignals_data(); - void statesAndSignals(); - void deletion1(); - void deletion2(); - void deletion3(); - void duration0(); - void noStartValue(); - void noStartValueWithLoop(); - void startWhenAnotherIsRunning(); - void easingcurve_data(); - void easingcurve(); - void startWithoutStartValue(); - void playForwardBackward(); - void interpolated(); - void setStartEndValues(); - void zeroDurationStart(); - void operationsInStates_data(); - void operationsInStates(); - void oneKeyValue(); - void updateOnSetKeyValues(); -}; - -tst_QPropertyAnimation::tst_QPropertyAnimation() -{ -} - -tst_QPropertyAnimation::~tst_QPropertyAnimation() -{ -} - -void tst_QPropertyAnimation::init() -{ - qRegisterMetaType("QAbstractAnimation::State"); - qRegisterMetaType("QAbstractAnimation::DeletionPolicy"); -} - -void tst_QPropertyAnimation::cleanup() -{ -} - -class AnimationObject : public QObject -{ - Q_OBJECT - Q_PROPERTY(int value READ value WRITE setValue) - Q_PROPERTY(qreal realValue READ realValue WRITE setRealValue) -public: - AnimationObject(int startValue = 0) - : v(startValue) - { } - - int value() const { return v; } - void setValue(int value) { v = value; } - - qreal realValue() const { return rv; } - void setRealValue(qreal value) { rv = value; } - - int v; - qreal rv; -}; - - -void tst_QPropertyAnimation::construction() -{ - QPropertyAnimation panimation; -} - -void tst_QPropertyAnimation::setCurrentTime_data() -{ - QTest::addColumn("duration"); - QTest::addColumn("loopCount"); - QTest::addColumn("currentTime"); - QTest::addColumn("testCurrentTime"); - QTest::addColumn("testCurrentLoop"); - - QTest::newRow("-1") << -1 << 1 << 0 << 0 << 0; - QTest::newRow("0") << 0 << 1 << 0 << 0 << 0; - QTest::newRow("1") << 0 << 1 << 1 << 0 << 0; - QTest::newRow("2") << 0 << 2 << 1 << 0 << 0; - QTest::newRow("3") << 1 << 1 << 0 << 0 << 0; - QTest::newRow("4") << 1 << 1 << 1 << 1 << 0; - QTest::newRow("5") << 1 << 2 << 1 << 0 << 1; - QTest::newRow("6") << 1 << 2 << 2 << 1 << 1; - QTest::newRow("7") << 1 << 2 << 3 << 1 << 1; - QTest::newRow("8") << 1 << 3 << 2 << 0 << 2; - QTest::newRow("9") << 1 << 3 << 3 << 1 << 2; - QTest::newRow("a") << 10 << 1 << 0 << 0 << 0; - QTest::newRow("b") << 10 << 1 << 1 << 1 << 0; - QTest::newRow("c") << 10 << 1 << 10 << 10 << 0; - QTest::newRow("d") << 10 << 2 << 10 << 0 << 1; - QTest::newRow("e") << 10 << 2 << 11 << 1 << 1; - QTest::newRow("f") << 10 << 2 << 20 << 10 << 1; - QTest::newRow("g") << 10 << 2 << 21 << 10 << 1; - QTest::newRow("negloop 0") << 10 << -1 << 0 << 0 << 0; - QTest::newRow("negloop 1") << 10 << -1 << 10 << 0 << 1; - QTest::newRow("negloop 2") << 10 << -1 << 15 << 5 << 1; - QTest::newRow("negloop 3") << 10 << -1 << 20 << 0 << 2; - QTest::newRow("negloop 4") << 10 << -1 << 30 << 0 << 3; -} - -void tst_QPropertyAnimation::setCurrentTime() -{ - QFETCH(int, duration); - QFETCH(int, loopCount); - QFETCH(int, currentTime); - QFETCH(int, testCurrentTime); - QFETCH(int, testCurrentLoop); - - QPropertyAnimation animation; - if (duration < 0) - QTest::ignoreMessage(QtWarningMsg, "QVariantAnimation::setDuration: cannot set a negative duration"); - animation.setDuration(duration); - animation.setLoopCount(loopCount); - animation.setCurrentTime(currentTime); - - QCOMPARE(animation.currentTime(), testCurrentTime); - QCOMPARE(animation.currentLoop(), testCurrentLoop); -} - -void tst_QPropertyAnimation::statesAndSignals_data() -{ - QTest::addColumn("uncontrolled"); - QTest::newRow("normal animation") << false; - QTest::newRow("animation with undefined duration") << true; -} - -void tst_QPropertyAnimation::statesAndSignals() -{ - QFETCH(bool, uncontrolled); - QPropertyAnimation *anim = uncontrolled ? new UncontrolledAnimation : new QPropertyAnimation; - anim->setDuration(100); - - QSignalSpy finishedSpy(anim, SIGNAL(finished())); - QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy currentLoopSpy(anim, SIGNAL(currentLoopChanged(int))); - - anim->setCurrentTime(1); - anim->setCurrentTime(100); - QCOMPARE(finishedSpy.count(), 0); - QCOMPARE(runningSpy.count(), 0); - QCOMPARE(currentLoopSpy.count(), 0); - QCOMPARE(anim->state(), QAnimationGroup::Stopped); - - anim->setLoopCount(3); - anim->setCurrentTime(101); - - if (uncontrolled) - QSKIP("Uncontrolled animations don't handle looping", SkipSingle); - - QCOMPARE(currentLoopSpy.count(), 1); - QCOMPARE(anim->currentLoop(), 1); - - anim->setCurrentTime(0); - QCOMPARE(currentLoopSpy.count(), 2); - QCOMPARE(anim->currentLoop(), 0); - - anim->start(); - QCOMPARE(anim->state(), QAnimationGroup::Running); - QCOMPARE(runningSpy.count(), 1); //anim must have started - QCOMPARE(anim->currentLoop(), 0); - runningSpy.clear(); - - anim->stop(); - QCOMPARE(anim->state(), QAnimationGroup::Stopped); - QCOMPARE(runningSpy.count(), 1); //anim must have stopped - QCOMPARE(finishedSpy.count(), 0); - QCOMPARE(anim->currentTime(), 0); - QCOMPARE(anim->currentLoop(), 0); - QCOMPARE(currentLoopSpy.count(), 2); - runningSpy.clear(); - - anim->start(); - QTest::qWait(1000); - QCOMPARE(anim->state(), QAnimationGroup::Stopped); - QCOMPARE(runningSpy.count(), 2); //started and stopped again - runningSpy.clear(); - QCOMPARE(finishedSpy.count(), 1); - QCOMPARE(anim->currentTime(), 100); - QCOMPARE(anim->currentLoop(), 2); - QCOMPARE(currentLoopSpy.count(), 4); - - anim->start(); // auto-rewinds - QCOMPARE(anim->state(), QAnimationGroup::Running); - QCOMPARE(anim->currentTime(), 0); - QCOMPARE(anim->currentLoop(), 0); - QCOMPARE(currentLoopSpy.count(), 5); - QCOMPARE(runningSpy.count(), 1); // anim has started - QCOMPARE(finishedSpy.count(), 1); - QCOMPARE(anim->currentLoop(), 0); - runningSpy.clear(); - - QTest::qWait(1000); - - QCOMPARE(currentLoopSpy.count(), 7); - QCOMPARE(anim->state(), QAnimationGroup::Stopped); - QCOMPARE(anim->currentLoop(), 2); - QCOMPARE(runningSpy.count(), 1); // anim has stopped - QCOMPARE(finishedSpy.count(), 2); - QCOMPARE(anim->currentTime(), 100); - - delete anim; -} - -void tst_QPropertyAnimation::deletion1() -{ - QObject *object = new QWidget; - QPointer anim = new QPropertyAnimation(object,"minimumWidth"); - - //test that the animation is deleted correctly depending of the deletion flag passed in start() - QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy finishedSpy(anim, SIGNAL(finished())); - anim->setStartValue(10); - anim->setEndValue(20); - anim->setDuration(200); - anim->start(); - QCOMPARE(runningSpy.count(), 1); - QCOMPARE(finishedSpy.count(), 0); - - QVERIFY(anim); - QCOMPARE(anim->state(), QAnimationGroup::Running); - QTest::qWait(100); - QVERIFY(anim); - QCOMPARE(anim->state(), QAnimationGroup::Running); - QTest::qWait(150); - QVERIFY(anim); //The animation should not have been deleted - QCOMPARE(anim->state(), QAnimationGroup::Stopped); - QCOMPARE(runningSpy.count(), 2); - QCOMPARE(finishedSpy.count(), 1); - - anim->start(QVariantAnimation::DeleteWhenStopped); - QVERIFY(anim); - QCOMPARE(anim->state(), QAnimationGroup::Running); - QTest::qWait(100); - QVERIFY(anim); - QCOMPARE(anim->state(), QAnimationGroup::Running); - QTest::qWait(150); - QVERIFY(!anim); //The animation must have been deleted - QCOMPARE(runningSpy.count(), 4); - QCOMPARE(finishedSpy.count(), 2); - delete object; -} - -void tst_QPropertyAnimation::deletion2() -{ - //test that the animation get deleted if the object is deleted - QObject *object = new QWidget; - QPointer anim = new QPropertyAnimation(object,"minimumWidth"); - anim->setStartValue(10); - anim->setEndValue(20); - anim->setDuration(200); - - QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy finishedSpy(anim, SIGNAL(finished())); - - anim->setStartValue(10); - anim->setEndValue(20); - anim->setDuration(200); - anim->start(); - - QTest::qWait(50); - QVERIFY(anim); - QCOMPARE(anim->state(), QAnimationGroup::Running); - - QCOMPARE(runningSpy.count(), 1); - QCOMPARE(finishedSpy.count(), 0); - - //we can't call deletaLater directly because the delete would only happen in the next loop of _this_ event loop - QTimer::singleShot(0, object, SLOT(deleteLater())); - QTest::qWait(50); - - QVERIFY(anim->targetObject() == 0); -} - -void tst_QPropertyAnimation::deletion3() -{ - //test that the stopped signal is emit when the animation is destroyed - QObject *object = new QWidget; - QPropertyAnimation *anim = new QPropertyAnimation(object,"minimumWidth"); - anim->setStartValue(10); - anim->setEndValue(20); - anim->setDuration(200); - - QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy finishedSpy(anim, SIGNAL(finished())); - anim->start(); - - QTest::qWait(50); - QCOMPARE(anim->state(), QAnimationGroup::Running); - QCOMPARE(runningSpy.count(), 1); - QCOMPARE(finishedSpy.count(), 0); - delete anim; - QCOMPARE(runningSpy.count(), 2); - QCOMPARE(finishedSpy.count(), 0); -} - -void tst_QPropertyAnimation::duration0() -{ - QObject o; - o.setProperty("ole", 42); - QCOMPARE(o.property("ole").toInt(), 42); - - QPropertyAnimation animation(&o, "ole"); - animation.setEndValue(43); - QVERIFY(!animation.currentValue().isValid()); - QCOMPARE(animation.currentValue().toInt(), 0); - QCOMPARE(o.property("ole").toInt(), 42); - animation.setDuration(0); - animation.start(); - QCOMPARE(animation.state(), QAnimationGroup::Stopped); - QCOMPARE(animation.currentTime(), 0); - QCOMPARE(o.property("ole").toInt(), 43); -} - -class StartValueTester : public QObject -{ - Q_OBJECT - Q_PROPERTY(int ole READ ole WRITE setOle) -public: - StartValueTester() : o(0) { } - int ole() const { return o; } - void setOle(int v) { o = v; values << v; } - - int o; - QList values; -}; - -void tst_QPropertyAnimation::noStartValue() -{ - StartValueTester o; - o.setProperty("ole", 42); - o.values.clear(); - - QPropertyAnimation a(&o, "ole"); - a.setEndValue(420); - a.setDuration(250); - a.start(); - - QTest::qWait(300); - - QCOMPARE(o.values.first(), 42); - QCOMPARE(o.values.last(), 420); -} - -void tst_QPropertyAnimation::noStartValueWithLoop() -{ - StartValueTester o; - o.setProperty("ole", 42); - o.values.clear(); - - QPropertyAnimation a(&o, "ole"); - a.setEndValue(420); - a.setDuration(250); - a.setLoopCount(2); - a.start(); - - a.setCurrentTime(250); - QCOMPARE(o.values.first(), 42); - QCOMPARE(a.currentValue().toInt(), 42); - QCOMPARE(o.values.last(), 42); - - a.setCurrentTime(500); - QCOMPARE(a.currentValue().toInt(), 420); -} - -void tst_QPropertyAnimation::startWhenAnotherIsRunning() -{ - StartValueTester o; - o.setProperty("ole", 42); - o.values.clear(); - - { - //normal case: the animation finishes and is deleted - QPointer anim = new QPropertyAnimation(&o, "ole"); - QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - anim->start(QVariantAnimation::DeleteWhenStopped); - QTest::qWait(anim->duration() + 50); - QCOMPARE(runningSpy.count(), 2); //started and then stopped - QVERIFY(!anim); - } - - { - QPointer anim = new QPropertyAnimation(&o, "ole"); - QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - anim->start(QVariantAnimation::DeleteWhenStopped); - QTest::qWait(anim->duration()/2); - QPointer anim2 = new QPropertyAnimation(&o, "ole"); - QCOMPARE(runningSpy.count(), 1); - QCOMPARE(anim->state(), QVariantAnimation::Running); - - //anim2 will interrupt anim1 - QMetaObject::invokeMethod(anim2, "start", Qt::QueuedConnection, Q_ARG(QAbstractAnimation::DeletionPolicy, QVariantAnimation::DeleteWhenStopped)); - QTest::qWait(50); - QVERIFY(!anim); //anim should have been deleted - QVERIFY(anim2); - QTest::qWait(anim2->duration()); - QVERIFY(!anim2); //anim2 is finished: it should have been deleted by now - QVERIFY(!anim); - } - -} - -// copy from easing.cpp in case that function changes definition -static qreal easeInOutBack(qreal t) -{ - qreal s = 1.70158; - qreal t_adj = 2.0f * (qreal)t; - if (t_adj < 1) { - s *= 1.525f; - return 1.0/2*(t_adj*t_adj*((s+1)*t_adj - s)); - } else { - t_adj -= 2; - s *= 1.525f; - return 1.0/2*(t_adj*t_adj*((s+1)*t_adj + s) + 2); - } -} - -void tst_QPropertyAnimation::easingcurve_data() -{ - QTest::addColumn("currentTime"); - QTest::addColumn("expectedvalue"); - - QTest::newRow("interpolation1") << 0 << 0; - QTest::newRow("interpolation2") << 1000 << 1000; - QTest::newRow("extrapolationbelow") << 250 << -99; - QTest::newRow("extrapolationabove") << 750 << 1099; -} - -void tst_QPropertyAnimation::easingcurve() -{ - QFETCH(int, currentTime); - QFETCH(int, expectedvalue); - QObject o; - o.setProperty("ole", 42); - QCOMPARE(o.property("ole").toInt(), 42); - - QPropertyAnimation pAnimation(&o, "ole"); - pAnimation.setStartValue(0); - pAnimation.setEndValue(1000); - pAnimation.setDuration(1000); - - // this easingcurve assumes that we extrapolate before startValue and after endValue - QEasingCurve easingCurve; - easingCurve.setCustomType(easeInOutBack); - pAnimation.setEasingCurve(easingCurve); - pAnimation.start(); - pAnimation.pause(); - pAnimation.setCurrentTime(currentTime); - QCOMPARE(o.property("ole").toInt(), expectedvalue); -} - -void tst_QPropertyAnimation::startWithoutStartValue() -{ - QObject o; - o.setProperty("ole", 42); - QCOMPARE(o.property("ole").toInt(), 42); - - QPropertyAnimation anim(&o, "ole"); - anim.setEndValue(100); - - anim.start(); - - QTest::qWait(100); - int current = anim.currentValue().toInt(); - //it is somewhere in the animation - QVERIFY(current > 42); - QVERIFY(current < 100); - - QTest::qWait(200); - QCOMPARE(anim.state(), QVariantAnimation::Stopped); - - anim.setEndValue(110); - anim.start(); - current = anim.currentValue().toInt(); - // the default start value will reevaluate the current property - // and set it to the end value of the last iteration - QCOMPARE(current, 100); - QTest::qWait(100); - current = anim.currentValue().toInt(); - //it is somewhere in the animation - QVERIFY(current >= 100); - QVERIFY(current <= 110); -} - -void tst_QPropertyAnimation::playForwardBackward() -{ - QObject o; - o.setProperty("ole", 0); - QCOMPARE(o.property("ole").toInt(), 0); - - QPropertyAnimation anim(&o, "ole"); - anim.setEndValue(100); - anim.start(); - QTest::qWait(anim.duration() + 50); - QCOMPARE(anim.state(), QAbstractAnimation::Stopped); - QCOMPARE(anim.currentTime(), anim.duration()); - - //the animation is at the end - anim.setDirection(QVariantAnimation::Backward); - anim.start(); - QCOMPARE(anim.state(), QAbstractAnimation::Running); - QTest::qWait(anim.duration() + 50); - QCOMPARE(anim.state(), QAbstractAnimation::Stopped); - QCOMPARE(anim.currentTime(), 0); - - //the direction is backward - //restarting should jump to the end - anim.start(); - QCOMPARE(anim.state(), QAbstractAnimation::Running); - QCOMPARE(anim.currentTime(), anim.duration()); - QTest::qWait(anim.duration() + 50); - QCOMPARE(anim.state(), QAbstractAnimation::Stopped); - QCOMPARE(anim.currentTime(), 0); -} - -struct Number -{ - Number() {} - Number(int n) - : n(n) {} - - Number(const Number &other) - : n(other.n){} - - Number &operator=(const Number &other) { - n = other.n; - return *this; - } - bool operator==(const Number &other) const { - return n == other.n; - } - - int n; -}; - -Q_DECLARE_METATYPE(Number) -Q_DECLARE_METATYPE(QAbstractAnimation::State) - -QVariant numberInterpolator(const Number &f, const Number &t, qreal progress) -{ - return qVariantFromValue(Number(f.n + (t.n - f.n)*progress)); -} - -QVariant xaxisQPointInterpolator(const QPointF &f, const QPointF &t, qreal progress) -{ - return QPointF(f.x() + (t.x() - f.x())*progress, f.y()); -} - -void tst_QPropertyAnimation::interpolated() -{ - QObject o; - o.setProperty("point", QPointF()); //this will avoid warnings - o.setProperty("number", qVariantFromValue(Number(42))); - QCOMPARE(qVariantValue(o.property("number")), Number(42)); - { - qRegisterAnimationInterpolator(numberInterpolator); - QPropertyAnimation anim(&o, "number"); - anim.setStartValue(qVariantFromValue(Number(0))); - anim.setEndValue(qVariantFromValue(Number(100))); - anim.setDuration(1000); - anim.start(); - anim.pause(); - anim.setCurrentTime(100); - Number t(qVariantValue(o.property("number"))); - QCOMPARE(t, Number(10)); - anim.setCurrentTime(500); - QCOMPARE(qVariantValue(o.property("number")), Number(50)); - } - { - qRegisterAnimationInterpolator(xaxisQPointInterpolator); - QPropertyAnimation anim(&o, "point"); - anim.setStartValue(QPointF(0,0)); - anim.setEndValue(QPointF(100, 100)); - anim.setDuration(1000); - anim.start(); - anim.pause(); - anim.setCurrentTime(100); - QCOMPARE(o.property("point"), QVariant(QPointF(10, 0))); - anim.setCurrentTime(500); - QCOMPARE(o.property("point"), QVariant(QPointF(50, 0))); - } - { - // unregister it and see if we get back the default behaviour - qRegisterAnimationInterpolator(0); - QPropertyAnimation anim(&o, "point"); - anim.setStartValue(QPointF(0,0)); - anim.setEndValue(QPointF(100, 100)); - anim.setDuration(1000); - anim.start(); - anim.pause(); - anim.setCurrentTime(100); - QCOMPARE(o.property("point").toPointF(), QPointF(10, 10)); - anim.setCurrentTime(500); - QCOMPARE(o.property("point").toPointF(), QPointF(50, 50)); - } - - { - // Interpolate a qreal property with a int interpolator - AnimationObject o1; - o1.setRealValue(42.42); - QPropertyAnimation anim(&o1, "realValue"); - anim.setStartValue(0); - anim.setEndValue(100); - anim.start(); - QCOMPARE(o1.realValue(), qreal(0)); - anim.setCurrentTime(250); - QCOMPARE(o1.realValue(), qreal(100)); - } -} - -void tst_QPropertyAnimation::setStartEndValues() -{ - //this tests the start value, end value and default start value - QObject o; - o.setProperty("ole", 42); - QPropertyAnimation anim(&o, "ole"); - QVariantAnimation::KeyValues values; - QCOMPARE(anim.keyValues(), values); - - //let's add a start value - anim.setStartValue(0); - values << QVariantAnimation::KeyValue(0, 0); - QCOMPARE(anim.keyValues(), values); - - anim.setEndValue(10); - values << QVariantAnimation::KeyValue(1, 10); - QCOMPARE(anim.keyValues(), values); - - //now we can play with objects - QCOMPARE(o.property("ole").toInt(), 42); - QCOMPARE(o.property("ole").toInt(), 42); - anim.start(); - QVERIFY(anim.startValue().isValid()); - QCOMPARE(o.property("ole"), anim.startValue()); - - //now we remove the explicit start value and test the implicit one - anim.stop(); - o.setProperty("ole", 42); - values.remove(0); - anim.setStartValue(QVariant()); //reset the start value - QCOMPARE(anim.keyValues(), values); - QVERIFY(!anim.startValue().isValid()); - anim.start(); - QCOMPARE(o.property("ole").toInt(), 42); - anim.setCurrentTime(anim.duration()/2); - QCOMPARE(o.property("ole").toInt(), 26); //just in the middle of the animation - anim.setCurrentTime(anim.duration()); - QCOMPARE(anim.state(), QAnimationGroup::Stopped); //it should have stopped - QVERIFY(anim.endValue().isValid()); - QCOMPARE(o.property("ole"), anim.endValue()); //end of the animations - - //now we set back the startValue - anim.setStartValue(5); - QVERIFY(anim.startValue().isValid()); - anim.start(); - QCOMPARE(o.property("ole").toInt(), 5); -} - -void tst_QPropertyAnimation::zeroDurationStart() -{ - QPropertyAnimation anim; - QSignalSpy spy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - anim.setDuration(0); - QCOMPARE(anim.state(), QAbstractAnimation::Stopped); - anim.start(); - //the animation stops immediately - QCOMPARE(anim.state(), QAbstractAnimation::Stopped); - QCOMPARE(spy.count(), 2); - - //let's check the first state change - const QVariantList firstChange = spy.first(); - //old state - QCOMPARE(qVariantValue(firstChange.first()), QAbstractAnimation::Stopped); - //new state - QCOMPARE(qVariantValue(firstChange.last()), QAbstractAnimation::Running); - - //let's check the first state change - const QVariantList secondChange = spy.last(); - //old state - QCOMPARE(qVariantValue(secondChange.first()), QAbstractAnimation::Running); - //new state - QCOMPARE(qVariantValue(secondChange.last()), QAbstractAnimation::Stopped); -} - -#define Pause 1 -#define Start 2 -#define Resume 3 -#define Stop 4 - -void tst_QPropertyAnimation::operationsInStates_data() -{ - QTest::addColumn("originState"); - QTest::addColumn("operation"); - QTest::addColumn("expectedWarning"); - QTest::addColumn("expectedState"); - - QString pauseWarn(QLatin1String("QAbstractAnimation::pause: Cannot pause a stopped animation")); - QString resumeWarn(QLatin1String("QAbstractAnimation::resume: Cannot resume an animation that is not paused")); - - QTest::newRow("S-pause") << QAbstractAnimation::Stopped << Pause << pauseWarn << QAbstractAnimation::Stopped; - QTest::newRow("S-start") << QAbstractAnimation::Stopped << Start << QString() << QAbstractAnimation::Running; - QTest::newRow("S-resume") << QAbstractAnimation::Stopped << Resume << resumeWarn << QAbstractAnimation::Stopped; - QTest::newRow("S-stop") << QAbstractAnimation::Stopped << Stop << QString() << QAbstractAnimation::Stopped; - - QTest::newRow("P-pause") << QAbstractAnimation::Paused << Pause << QString() << QAbstractAnimation::Paused; - QTest::newRow("P-start") << QAbstractAnimation::Paused << Start << QString() << QAbstractAnimation::Running; - QTest::newRow("P-resume") << QAbstractAnimation::Paused << Resume << QString() << QAbstractAnimation::Running; - QTest::newRow("P-stop") << QAbstractAnimation::Paused << Stop << QString() << QAbstractAnimation::Stopped; - - QTest::newRow("R-pause") << QAbstractAnimation::Running << Pause << QString() << QAbstractAnimation::Paused; - QTest::newRow("R-start") << QAbstractAnimation::Running << Start << QString() << QAbstractAnimation::Running; - QTest::newRow("R-resume") << QAbstractAnimation::Running << Resume << resumeWarn << QAbstractAnimation::Running; - QTest::newRow("R-stop") << QAbstractAnimation::Running << Stop << QString() << QAbstractAnimation::Stopped; -} - -void tst_QPropertyAnimation::operationsInStates() -{ -/** - * | pause() |start() |resume() |stop() - * ----------+------------+-----------+-----------+-------------------+ - * Stopped | Stopped |Running |Stopped |Stopped | - * _| qWarning |restart |qWarning | | - * Paused | Paused |Running |Running |Stopped | - * _| | | | | - * Running | Paused |Running |Running |Stopped | - * | |restart |qWarning | | - * ----------+------------+-----------+-----------+-------------------+ -**/ - - QFETCH(QAbstractAnimation::State, originState); - QFETCH(int, operation); - QFETCH(QString, expectedWarning); - QFETCH(QAbstractAnimation::State, expectedState); - - QObject o; - o.setProperty("ole", 42); - QPropertyAnimation anim(&o, "ole"); - QSignalSpy spy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - anim.stop(); - switch (originState) { - case QAbstractAnimation::Stopped: - break; - case QAbstractAnimation::Paused: - anim.start(); - anim.pause(); - break; - case QAbstractAnimation::Running: - anim.start(); - break; - } - if (!expectedWarning.isEmpty()) { - QTest::ignoreMessage(QtWarningMsg, qPrintable(expectedWarning)); - } - QCOMPARE(anim.state(), originState); - switch (operation) { - case Pause: - anim.pause(); - break; - case Start: - anim.start(); - break; - case Resume: - anim.resume(); - break; - case Stop: - anim.stop(); - break; - } - - QCOMPARE(anim.state(), expectedState); -} -#undef Pause -#undef Start -#undef Resume -#undef Stop - -void tst_QPropertyAnimation::oneKeyValue() -{ - QObject o; - o.setProperty("ole", 42); - QCOMPARE(o.property("ole").toInt(), 42); - - QPropertyAnimation animation(&o, "ole"); - animation.setStartValue(43); - animation.setEndValue(44); - animation.setDuration(100); - - animation.setCurrentTime(0); - - QVERIFY(animation.currentValue().isValid()); - QCOMPARE(animation.currentValue().toInt(), 43); - QCOMPARE(o.property("ole").toInt(), 42); - - // remove the last key value - animation.setKeyValueAt(1.0, QVariant()); - - // we will neither interpolate, nor update the current value - // since there is only one 1 key value defined - animation.setCurrentTime(100); - - // the animation should not have been modified - QVERIFY(animation.currentValue().isValid()); - QCOMPARE(animation.currentValue().toInt(), 43); - QCOMPARE(o.property("ole").toInt(), 42); -} - -void tst_QPropertyAnimation::updateOnSetKeyValues() -{ - QObject o; - o.setProperty("ole", 100); - QCOMPARE(o.property("ole").toInt(), 100); - - QPropertyAnimation animation(&o, "ole"); - animation.setStartValue(100); - animation.setEndValue(200); - animation.setDuration(100); - - animation.setCurrentTime(50); - QCOMPARE(animation.currentValue().toInt(), 150); - animation.setKeyValueAt(0.0, 300); - QCOMPARE(animation.currentValue().toInt(), 250); - - o.setProperty("ole", 100); - QPropertyAnimation animation2(&o, "ole"); - QVariantAnimation::KeyValues kValues; - kValues << QVariantAnimation::KeyValue(0.0, 100) << QVariantAnimation::KeyValue(1.0, 200); - animation2.setKeyValues(kValues); - animation2.setDuration(100); - animation2.setCurrentTime(50); - QCOMPARE(animation2.currentValue().toInt(), 150); - - kValues.clear(); - kValues << QVariantAnimation::KeyValue(0.0, 300) << QVariantAnimation::KeyValue(1.0, 200); - animation2.setKeyValues(kValues); - - QCOMPARE(animation2.currentValue().toInt(), animation.currentValue().toInt()); -} - -QTEST_MAIN(tst_QPropertyAnimation) -#include "tst_qpropertyanimation.moc" diff --git a/tests/auto/qsequentialanimationgroup/qsequentialanimationgroup.pro b/tests/auto/qsequentialanimationgroup/qsequentialanimationgroup.pro deleted file mode 100644 index ad861c3..0000000 --- a/tests/auto/qsequentialanimationgroup/qsequentialanimationgroup.pro +++ /dev/null @@ -1,5 +0,0 @@ -load(qttest_p4) -QT = core gui -SOURCES += tst_qsequentialanimationgroup.cpp - - diff --git a/tests/auto/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp b/tests/auto/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp deleted file mode 100644 index 0631343..0000000 --- a/tests/auto/qsequentialanimationgroup/tst_qsequentialanimationgroup.cpp +++ /dev/null @@ -1,1649 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include "../../shared/util.h" - -#include -#include - -//TESTED_CLASS=QSequentialAnimationGroup -//TESTED_FILES= - -Q_DECLARE_METATYPE(QAbstractAnimation::State) -Q_DECLARE_METATYPE(QAbstractAnimation*) - -class tst_QSequentialAnimationGroup : public QObject -{ - Q_OBJECT -public: - tst_QSequentialAnimationGroup(); - virtual ~tst_QSequentialAnimationGroup(); - -public Q_SLOTS: - void init(); - void cleanup(); - -private slots: - void construction(); - void setCurrentTime(); - void setCurrentTimeWithUncontrolledAnimation(); - void seekingForwards(); - void seekingBackwards(); - void pauseAndResume(); - void restart(); - void looping(); - void startDelay(); - void clearGroup(); - void groupWithZeroDurationAnimations(); - void propagateGroupUpdateToChildren(); - void updateChildrenWithRunningGroup(); - void deleteChildrenWithRunningGroup(); - void startChildrenWithStoppedGroup(); - void stopGroupWithRunningChild(); - void startGroupWithRunningChild(); - void zeroDurationAnimation(); - void stopUncontrolledAnimations(); - void finishWithUncontrolledAnimation(); - void addRemoveAnimation(); - void currentAnimation(); - void currentAnimationWithZeroDuration(); - void insertAnimation(); - void clearAnimations(); -}; - -tst_QSequentialAnimationGroup::tst_QSequentialAnimationGroup() -{ -} - -tst_QSequentialAnimationGroup::~tst_QSequentialAnimationGroup() -{ -} - -void tst_QSequentialAnimationGroup::init() -{ - qRegisterMetaType("QAbstractAnimation::State"); - qRegisterMetaType("QAbstractAnimation*"); -} - -void tst_QSequentialAnimationGroup::cleanup() -{ -} - -void tst_QSequentialAnimationGroup::construction() -{ - QSequentialAnimationGroup animationgroup; -} - -class AnimationObject : public QObject -{ - Q_OBJECT - Q_PROPERTY(int value READ value WRITE setValue) -public: - AnimationObject(int startValue = 0) - : v(startValue) - { } - - int value() const { return v; } - void setValue(int value) { v = value; } - - int v; -}; - -class TestAnimation : public QVariantAnimation -{ - Q_OBJECT -public: - virtual void updateCurrentValue(const QVariant &value) { Q_UNUSED(value)}; - virtual void updateState(QAbstractAnimation::State oldState, - QAbstractAnimation::State newState) - { - Q_UNUSED(oldState) - Q_UNUSED(newState) - }; -}; - -class UncontrolledAnimation : public QPropertyAnimation -{ - Q_OBJECT -public: - UncontrolledAnimation(QObject *target, const QByteArray &propertyName, QObject *parent = 0) - : QPropertyAnimation(target, propertyName, parent) - { - setDuration(250); - } - - int duration() const { return -1; /* not time driven */ } - -protected: - void updateCurrentTime(int msecs) - { - QPropertyAnimation::updateCurrentTime(msecs); - if (msecs >= QPropertyAnimation::duration()) - stop(); - } -}; - -void tst_QSequentialAnimationGroup::setCurrentTime() -{ - AnimationObject s_o1; - AnimationObject s_o2; - AnimationObject s_o3; - - // sequence operating on same object/property - QAnimationGroup *sequence = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); - a2_s_o1->setLoopCount(3); - sequence->addAnimation(a1_s_o1); - sequence->addAnimation(a2_s_o1); - sequence->addAnimation(a3_s_o1); - - // sequence operating on different object/properties - QAnimationGroup *sequence2 = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); - QVariantAnimation *a1_s_o3 = new QPropertyAnimation(&s_o3, "value"); - sequence2->addAnimation(a1_s_o2); - sequence2->addAnimation(a1_s_o3); - - QSequentialAnimationGroup group; - group.addAnimation(sequence); - group.addAnimation(sequence2); - - // Current time = 1 - group.setCurrentTime(1); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(sequence->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - - QCOMPARE(group.currentTime(), 1); - QCOMPARE(sequence->currentTime(), 1); - QCOMPARE(a1_s_o1->currentTime(), 1); - QCOMPARE(a2_s_o1->currentTime(), 0); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 250 - group.setCurrentTime(250); - QCOMPARE(group.currentTime(), 250); - QCOMPARE(sequence->currentTime(), 250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 0); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 251 - group.setCurrentTime(251); - QCOMPARE(group.currentTime(), 251); - QCOMPARE(sequence->currentTime(), 251); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 1); - QCOMPARE(a2_s_o1->currentLoop(), 0); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(sequence2->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 750 - group.setCurrentTime(750); - QCOMPARE(group.currentTime(), 750); - QCOMPARE(sequence->currentTime(), 750); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 0); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(sequence2->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 1000 - group.setCurrentTime(1000); - QCOMPARE(group.currentTime(), 1000); - QCOMPARE(sequence->currentTime(), 1000); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(sequence2->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 1010 - group.setCurrentTime(1010); - QCOMPARE(group.currentTime(), 1010); - QCOMPARE(sequence->currentTime(), 1010); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 10); - QCOMPARE(sequence2->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 1250 - group.setCurrentTime(1250); - QCOMPARE(group.currentTime(), 1250); - QCOMPARE(sequence->currentTime(), 1250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 250); - QCOMPARE(sequence2->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 1500 - group.setCurrentTime(1500); - QCOMPARE(group.currentTime(), 1500); - QCOMPARE(sequence->currentTime(), 1250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 250); - QCOMPARE(sequence2->currentTime(), 250); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 1750 - group.setCurrentTime(1750); - QCOMPARE(group.currentTime(), 1750); - QCOMPARE(sequence->currentTime(), 1250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 250); - QCOMPARE(sequence2->currentTime(), 500); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 250); - - // Current time = 2000 - group.setCurrentTime(2000); - QCOMPARE(group.currentTime(), 1750); - QCOMPARE(sequence->currentTime(), 1250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 250); - QCOMPARE(sequence2->currentTime(), 500); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 250); -} - -void tst_QSequentialAnimationGroup::setCurrentTimeWithUncontrolledAnimation() -{ - AnimationObject s_o1; - AnimationObject s_o2; - AnimationObject t_o1; - AnimationObject t_o2; - - // sequence operating on different object/properties - QAnimationGroup *sequence = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); - sequence->addAnimation(a1_s_o1); - sequence->addAnimation(a1_s_o2); - - UncontrolledAnimation *notTimeDriven = new UncontrolledAnimation(&t_o1, "value"); - QCOMPARE(notTimeDriven->totalDuration(), -1); - - QVariantAnimation *loopsForever = new QPropertyAnimation(&t_o2, "value"); - loopsForever->setLoopCount(-1); - QCOMPARE(loopsForever->totalDuration(), -1); - - QSequentialAnimationGroup group; - group.addAnimation(sequence); - group.addAnimation(notTimeDriven); - group.addAnimation(loopsForever); - group.start(); - group.pause(); // this allows the group to listen for the finish signal of its children - - // Current time = 1 - group.setCurrentTime(1); - QCOMPARE(group.state(), QAnimationGroup::Paused); - QCOMPARE(sequence->state(), QAnimationGroup::Paused); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Paused); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); - - QCOMPARE(group.currentTime(), 1); - QCOMPARE(sequence->currentTime(), 1); - QCOMPARE(a1_s_o1->currentTime(), 1); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(notTimeDriven->currentTime(), 0); - QCOMPARE(loopsForever->currentTime(), 0); - - // Current time = 250 - group.setCurrentTime(250); - QCOMPARE(group.currentTime(), 250); - QCOMPARE(sequence->currentTime(), 250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(notTimeDriven->currentTime(), 0); - QCOMPARE(loopsForever->currentTime(), 0); - - // Current time = 500 - group.setCurrentTime(500); - QCOMPARE(group.currentTime(), 500); - QCOMPARE(sequence->currentTime(), 500); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(notTimeDriven->currentTime(), 0); - QCOMPARE(loopsForever->currentTime(), 0); - QCOMPARE(group.currentAnimation(), notTimeDriven); - - // Current time = 505 - group.setCurrentTime(505); - QCOMPARE(group.currentTime(), 505); - QCOMPARE(sequence->currentTime(), 500); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(notTimeDriven->currentTime(), 5); - QCOMPARE(loopsForever->currentTime(), 0); - QCOMPARE(group.currentAnimation(), notTimeDriven); - QCOMPARE(sequence->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven->state(), QAnimationGroup::Paused); - QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); - - // Current time = 750 (end of notTimeDriven animation) - group.setCurrentTime(750); - QCOMPARE(group.currentTime(), 750); - QCOMPARE(sequence->currentTime(), 500); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(notTimeDriven->currentTime(), 250); - QCOMPARE(loopsForever->currentTime(), 0); - QCOMPARE(group.currentAnimation(), loopsForever); - QCOMPARE(sequence->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever->state(), QAnimationGroup::Paused); - - // Current time = 800 (as notTimeDriven was finished at 750, loopsforever should still run) - group.setCurrentTime(800); - QCOMPARE(group.currentTime(), 800); - QCOMPARE(group.currentAnimation(), loopsForever); - QCOMPARE(sequence->currentTime(), 500); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(notTimeDriven->currentTime(), 250); - QCOMPARE(loopsForever->currentTime(), 50); - - loopsForever->stop(); // this should stop the group - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(sequence->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven->state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever->state(), QAnimationGroup::Stopped); -} - -void tst_QSequentialAnimationGroup::seekingForwards() -{ - AnimationObject s_o1; - AnimationObject s_o2; - AnimationObject s_o3; - - // sequence operating on same object/property - QAnimationGroup *sequence = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); - a2_s_o1->setLoopCount(3); - sequence->addAnimation(a1_s_o1); - sequence->addAnimation(a2_s_o1); - sequence->addAnimation(a3_s_o1); - - // sequence operating on different object/properties - QAnimationGroup *sequence2 = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); - QVariantAnimation *a1_s_o3 = new QPropertyAnimation(&s_o3, "value"); - sequence2->addAnimation(a1_s_o2); - sequence2->addAnimation(a1_s_o3); - - QSequentialAnimationGroup group; - group.addAnimation(sequence); - group.addAnimation(sequence2); - - // Current time = 1 - group.setCurrentTime(1); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(sequence->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); - - QCOMPARE(group.currentTime(), 1); - QCOMPARE(sequence->currentTime(), 1); - QCOMPARE(a1_s_o1->currentTime(), 1); - QCOMPARE(a2_s_o1->currentTime(), 0); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(sequence2->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // Current time = 1500 - group.setCurrentTime(1500); - QCOMPARE(group.currentTime(), 1500); - QCOMPARE(sequence->currentTime(), 1250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 250); - QCOMPARE(sequence2->currentTime(), 250); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 0); - - // this will restart the group - group.start(); - group.pause(); - QCOMPARE(group.state(), QAnimationGroup::Paused); - QCOMPARE(sequence->state(), QAnimationGroup::Paused); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Paused); - QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); - - // Current time = 1750 - group.setCurrentTime(1750); - QCOMPARE(group.currentTime(), 1750); - QCOMPARE(sequence->currentTime(), 1250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 250); - QCOMPARE(sequence2->currentTime(), 500); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 250); -} - -void tst_QSequentialAnimationGroup::seekingBackwards() -{ - AnimationObject s_o1; - AnimationObject s_o2; - AnimationObject s_o3; - - // sequence operating on same object/property - QAnimationGroup *sequence = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); - a2_s_o1->setLoopCount(3); - sequence->addAnimation(a1_s_o1); - sequence->addAnimation(a2_s_o1); - sequence->addAnimation(a3_s_o1); - - // sequence operating on different object/properties - QAnimationGroup *sequence2 = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o2 = new QPropertyAnimation(&s_o2, "value"); - QVariantAnimation *a1_s_o3 = new QPropertyAnimation(&s_o3, "value"); - sequence2->addAnimation(a1_s_o2); - sequence2->addAnimation(a1_s_o3); - - QSequentialAnimationGroup group; - group.addAnimation(sequence); - group.addAnimation(sequence2); - - group.start(); - - // Current time = 1600 - group.setCurrentTime(1600); - QCOMPARE(group.currentTime(), 1600); - QCOMPARE(sequence->currentTime(), 1250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 250); - QCOMPARE(sequence2->currentTime(), 350); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 100); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(sequence->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(sequence2->state(), QAnimationGroup::Running); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o3->state(), QAnimationGroup::Running); - - // Seeking backwards, current time = 1 - group.setCurrentTime(1); - QCOMPARE(group.currentTime(), 1); - QCOMPARE(sequence->currentTime(), 1); - QCOMPARE(a1_s_o1->currentTime(), 1); - - QEXPECT_FAIL("", "rewinding in nested groups is considered as a restart from the children," - "hence they don't reset from their current animation", Continue); - QCOMPARE(a2_s_o1->currentTime(), 0); - QEXPECT_FAIL("", "rewinding in nested groups is considered as a restart from the children," - "hence they don't reset from their current animation", Continue); - QCOMPARE(a2_s_o1->currentLoop(), 0); - QEXPECT_FAIL("", "rewinding in nested groups is considered as a restart from the children," - "hence they don't reset from their current animation", Continue); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(sequence2->currentTime(), 0); - QCOMPARE(a1_s_o2->currentTime(), 0); - QCOMPARE(a1_s_o3->currentTime(), 0); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(sequence->state(), QAnimationGroup::Running); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Running); - QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); - - // Current time = 2000 - group.setCurrentTime(2000); - QCOMPARE(group.currentTime(), 1750); - QCOMPARE(sequence->currentTime(), 1250); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 2); - QCOMPARE(a3_s_o1->currentTime(), 250); - QCOMPARE(sequence2->currentTime(), 500); - QCOMPARE(a1_s_o2->currentTime(), 250); - QCOMPARE(a1_s_o3->currentTime(), 250); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(sequence->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(sequence2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o2->state(), QAnimationGroup::Stopped); - QCOMPARE(a1_s_o3->state(), QAnimationGroup::Stopped); -} - -typedef QList StateList; - -static bool compareStates(const QSignalSpy& spy, const StateList &expectedStates) -{ - bool equals = true; - for (int i = 0; i < qMax(expectedStates.count(), spy.count()); ++i) { - if (i >= spy.count() || i >= expectedStates.count()) { - equals = false; - break; - } - QList args = spy.at(i); - QAbstractAnimation::State st = expectedStates.at(i); - QAbstractAnimation::State actual = qVariantValue(args.value(1)); - if (equals && actual != st) { - equals = false; - break; - } - } - if (!equals) { - const char *stateStrings[] = {"Stopped", "Paused", "Running"}; - QString e,a; - for (int i = 0; i < qMax(expectedStates.count(), spy.count()); ++i) { - if (i < expectedStates.count()) { - int exp = int(expectedStates.at(i)); - if (!e.isEmpty()) - e += QLatin1String(", "); - e += QLatin1String(stateStrings[exp]); - } - if (i < spy.count()) { - QList args = spy.at(i); - QAbstractAnimation::State actual = qVariantValue(args.value(1)); - if (!a.isEmpty()) - a += QLatin1String(", "); - if (int(actual) >= 0 && int(actual) <= 2) { - a += QLatin1String(stateStrings[int(actual)]); - } else { - a += QLatin1String("NaN"); - } - } - - } - qDebug("\n" - "expected (count == %d): %s\n" - "actual (count == %d): %s\n", expectedStates.count(), qPrintable(e), spy.count(), qPrintable(a)); - } - return equals; -} - -void tst_QSequentialAnimationGroup::pauseAndResume() -{ - AnimationObject s_o1; - - // sequence operating on same object/property - QAnimationGroup *sequence = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); - a2_s_o1->setLoopCount(2); - sequence->addAnimation(a1_s_o1); - sequence->addAnimation(a2_s_o1); - sequence->addAnimation(a3_s_o1); - sequence->setLoopCount(2); - - QSignalSpy a1StateChangedSpy(a1_s_o1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy seqStateChangedSpy(sequence, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - QSequentialAnimationGroup group; - group.addAnimation(sequence); - - group.start(); - group.pause(); - - // Current time = 1751 - group.setCurrentTime(1751); - QCOMPARE(group.currentTime(), 1751); - QCOMPARE(sequence->currentTime(), 751); - QCOMPARE(sequence->currentLoop(), 1); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 1); - QCOMPARE(a3_s_o1->currentLoop(), 0); - QCOMPARE(a3_s_o1->currentTime(), 1); - - QCOMPARE(group.state(), QAnimationGroup::Paused); - QCOMPARE(sequence->state(), QAnimationGroup::Paused); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a3_s_o1->state(), QAnimationGroup::Paused); - - QCOMPARE(a1StateChangedSpy.count(), 5); // Running,Paused,Stopped,Running,Stopped - QCOMPARE(seqStateChangedSpy.count(), 2); // Running,Paused - - QVERIFY(compareStates(a1StateChangedSpy, (StateList() << QAbstractAnimation::Running - << QAbstractAnimation::Paused - << QAbstractAnimation::Stopped - << QAbstractAnimation::Running - << QAbstractAnimation::Stopped))); - - QCOMPARE(qVariantValue(a1StateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(a1StateChangedSpy.at(1).at(1)), - QAnimationGroup::Paused); - QCOMPARE(qVariantValue(a1StateChangedSpy.at(2).at(1)), - QAnimationGroup::Stopped); - QCOMPARE(qVariantValue(a1StateChangedSpy.at(3).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(a1StateChangedSpy.at(4).at(1)), - QAnimationGroup::Stopped); - - QCOMPARE(qVariantValue(seqStateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(seqStateChangedSpy.at(1).at(1)), - QAnimationGroup::Paused); - - group.resume(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(sequence->state(), QAnimationGroup::Running); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a3_s_o1->state(), QAnimationGroup::Running); - - QVERIFY(group.currentTime() >= 1751); - QVERIFY(sequence->currentTime() >= 751); - QCOMPARE(sequence->currentLoop(), 1); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 1); - QCOMPARE(a3_s_o1->currentLoop(), 0); - QVERIFY(a3_s_o1->currentTime() >= 1); - - QCOMPARE(seqStateChangedSpy.count(), 3); // Running,Paused,Running - QCOMPARE(qVariantValue(seqStateChangedSpy.at(2).at(1)), - QAnimationGroup::Running); - - group.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Paused); - QCOMPARE(sequence->state(), QAnimationGroup::Paused); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a3_s_o1->state(), QAnimationGroup::Paused); - - QVERIFY(group.currentTime() >= 1751); - QVERIFY(sequence->currentTime() >= 751); - QCOMPARE(sequence->currentLoop(), 1); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 1); - QCOMPARE(a3_s_o1->currentLoop(), 0); - QVERIFY(a3_s_o1->currentTime() >= 1); - - QCOMPARE(seqStateChangedSpy.count(), 4); // Running,Paused,Running,Paused - QCOMPARE(qVariantValue(seqStateChangedSpy.at(3).at(1)), - QAnimationGroup::Paused); - - group.stop(); - - QCOMPARE(seqStateChangedSpy.count(), 5); // Running,Paused,Running,Paused,Stopped - QCOMPARE(qVariantValue(seqStateChangedSpy.at(4).at(1)), - QAnimationGroup::Stopped); -} - -void tst_QSequentialAnimationGroup::restart() -{ - AnimationObject s_o1; - - // sequence operating on same object/property - QAnimationGroup *sequence = new QSequentialAnimationGroup(); - QSignalSpy seqCurrentAnimChangedSpy(sequence, SIGNAL(currentAnimationChanged(QAbstractAnimation*))); - QSignalSpy seqStateChangedSpy(sequence, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - QVariantAnimation *anims[3]; - QSignalSpy *animsStateChanged[3]; - - for (int i = 0; i < 3; i++) { - anims[i] = new QPropertyAnimation(&s_o1, "value"); - anims[i]->setDuration(100); - animsStateChanged[i] = new QSignalSpy(anims[i], SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - } - - anims[1]->setLoopCount(2); - sequence->addAnimation(anims[0]); - sequence->addAnimation(anims[1]); - sequence->addAnimation(anims[2]); - sequence->setLoopCount(2); - - QSequentialAnimationGroup group; - group.addAnimation(sequence); - - group.start(); - - QTest::qWait(500); - - QCOMPARE(group.state(), QAnimationGroup::Running); - - QTest::qWait(300); - QTRY_COMPARE(group.state(), QAnimationGroup::Stopped); - - for (int i = 0; i < 3; i++) { - QCOMPARE(animsStateChanged[i]->count(), 4); - QCOMPARE(qVariantValue(animsStateChanged[i]->at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(animsStateChanged[i]->at(1).at(1)), - QAnimationGroup::Stopped); - QCOMPARE(qVariantValue(animsStateChanged[i]->at(2).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(animsStateChanged[i]->at(3).at(1)), - QAnimationGroup::Stopped); - } - - QCOMPARE(seqStateChangedSpy.count(), 2); - QCOMPARE(qVariantValue(seqStateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(seqStateChangedSpy.at(1).at(1)), - QAnimationGroup::Stopped); - - QCOMPARE(seqCurrentAnimChangedSpy.count(), 6); - for(int i=0; i(seqCurrentAnimChangedSpy.at(i).at(0))); - - group.start(); - - QCOMPARE(animsStateChanged[0]->count(), 5); - QCOMPARE(animsStateChanged[1]->count(), 4); - QCOMPARE(animsStateChanged[2]->count(), 4); - QCOMPARE(seqStateChangedSpy.count(), 3); -} - -void tst_QSequentialAnimationGroup::looping() -{ - AnimationObject s_o1; - AnimationObject s_o2; - AnimationObject s_o3; - - // sequence operating on same object/property - QSequentialAnimationGroup *sequence = new QSequentialAnimationGroup(); - QVariantAnimation *a1_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a2_s_o1 = new QPropertyAnimation(&s_o1, "value"); - QVariantAnimation *a3_s_o1 = new QPropertyAnimation(&s_o1, "value"); - - QSignalSpy a1Spy(a1_s_o1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy a2Spy(a2_s_o1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy a3Spy(a3_s_o1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy seqSpy(sequence, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - a2_s_o1->setLoopCount(2); - sequence->addAnimation(a1_s_o1); - sequence->addAnimation(a2_s_o1); - sequence->addAnimation(a3_s_o1); - sequence->setLoopCount(2); - - QSequentialAnimationGroup group; - QSignalSpy groupSpy(&group, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - group.addAnimation(sequence); - group.setLoopCount(2); - - group.start(); - group.pause(); - - // Current time = 1750 - group.setCurrentTime(1750); - QCOMPARE(group.currentTime(), 1750); - QCOMPARE(sequence->currentTime(), 750); - QCOMPARE(sequence->currentLoop(), 1); - QCOMPARE(a1_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 1); - // this animation is at the beginning because it is the current one inside sequence - QCOMPARE(a3_s_o1->currentLoop(), 0); - QCOMPARE(a3_s_o1->currentTime(), 0); - QCOMPARE(sequence->currentAnimation(), a3_s_o1); - - QCOMPARE(group.state(), QAnimationGroup::Paused); - QCOMPARE(sequence->state(), QAnimationGroup::Paused); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a3_s_o1->state(), QAnimationGroup::Paused); - - QCOMPARE(a1Spy.count(), 5); // Running,Paused,Stopped,Running,Stopped - QVERIFY(compareStates(a1Spy, (StateList() << QAbstractAnimation::Running - << QAbstractAnimation::Paused - << QAbstractAnimation::Stopped - << QAbstractAnimation::Running - << QAbstractAnimation::Stopped))); - - QCOMPARE(a2Spy.count(), 4); // Running,Stopped,Running,Stopped - QVERIFY(compareStates(a3Spy, (StateList() << QAbstractAnimation::Running - << QAbstractAnimation::Stopped - << QAbstractAnimation::Running - << QAbstractAnimation::Paused))); - - QCOMPARE(seqSpy.count(), 2); // Running,Paused - QCOMPARE(groupSpy.count(), 2); // Running,Paused - - // Looping, current time = duration + 1 - group.setCurrentTime(group.duration() + 1); - QCOMPARE(group.currentTime(), 1); - QCOMPARE(group.currentLoop(), 1); - QCOMPARE(sequence->currentTime(), 1); - QCOMPARE(sequence->currentLoop(), 0); - QCOMPARE(a1_s_o1->currentTime(), 1); - QCOMPARE(a2_s_o1->currentTime(), 250); - QCOMPARE(a2_s_o1->currentLoop(), 1); - // this animation is at the end because it was run on the previous loop - QCOMPARE(a3_s_o1->currentLoop(), 0); - QCOMPARE(a3_s_o1->currentTime(), 250); - - QCOMPARE(group.state(), QAnimationGroup::Paused); - QCOMPARE(sequence->state(), QAnimationGroup::Paused); - QCOMPARE(a1_s_o1->state(), QAnimationGroup::Paused); - QCOMPARE(a2_s_o1->state(), QAnimationGroup::Stopped); - QCOMPARE(a3_s_o1->state(), QAnimationGroup::Stopped); - - QCOMPARE(a1Spy.count(), 7); // Running,Paused,Stopped,Running,Stopped,Running,Stopped - QCOMPARE(a2Spy.count(), 4); // Running, Stopped, Running, Stopped - QVERIFY(compareStates(a3Spy, (StateList() << QAbstractAnimation::Running - << QAbstractAnimation::Stopped - << QAbstractAnimation::Running - << QAbstractAnimation::Paused - << QAbstractAnimation::Stopped))); - QVERIFY(compareStates(seqSpy, (StateList() << QAbstractAnimation::Running - << QAbstractAnimation::Paused - << QAbstractAnimation::Stopped - << QAbstractAnimation::Running - << QAbstractAnimation::Paused))); - QCOMPARE(groupSpy.count(), 2); -} - -void tst_QSequentialAnimationGroup::startDelay() -{ - QSequentialAnimationGroup group; - group.addPause(250); - group.addPause(125); - QCOMPARE(group.totalDuration(), 375); - - QEventLoop loop; - QObject::connect(&group, SIGNAL(finished()), &loop, SLOT(quit())); - - QTime time; - time.start(); - group.start(); - loop.exec(); - - QVERIFY(time.elapsed() >= 375); - QVERIFY(time.elapsed() < 1000); -} - -void tst_QSequentialAnimationGroup::clearGroup() -{ - QSequentialAnimationGroup group; - - for (int i = 0; i < 10; ++i) { - QSequentialAnimationGroup *subGroup = new QSequentialAnimationGroup(&group); - group.addPause(100); - subGroup->addPause(10); - } - - QCOMPARE(group.animationCount(), 20); - - int count = group.animationCount(); - QPointer *children = new QPointer[count]; - for (int i = 0; i < count; ++i) { - QVERIFY(group.animationAt(i) != 0); - children[i] = group.animationAt(i); - } - - group.clearAnimations(); - QCOMPARE(group.animationCount(), 0); - QCOMPARE(group.currentTime(), 0); - for (int i = 0; i < count; ++i) - QCOMPARE(children[i], QPointer()); - - delete[] children; -} - -void tst_QSequentialAnimationGroup::groupWithZeroDurationAnimations() -{ - QObject o; - QObject o2; - - o.setProperty("myProperty", 42); - o.setProperty("myOtherProperty", 13); - o2.setProperty("myProperty", 42); - o2.setProperty("myOtherProperty", 13); - - QSequentialAnimationGroup group; - - QVariantAnimation *a1 = new QPropertyAnimation(&o, "myProperty"); - a1->setDuration(0); - a1->setEndValue(43); - group.addAnimation(a1); - - //this should just run fine and change nothing - group.setCurrentTime(0); - QCOMPARE(group.currentAnimation(), a1); - - QVariantAnimation *a2 = new QPropertyAnimation(&o2, "myOtherProperty"); - a2->setDuration(500); - a2->setEndValue(31); - group.addAnimation(a2); - - QVariantAnimation *a3 = new QPropertyAnimation(&o, "myProperty"); - a3->setDuration(0); - a3->setEndValue(44); - group.addAnimation(a3); - - QVariantAnimation *a4 = new QPropertyAnimation(&o, "myOtherProperty"); - a4->setDuration(250); - a4->setEndValue(75); - group.addAnimation(a4); - - QVariantAnimation *a5 = new QPropertyAnimation(&o2, "myProperty"); - a5->setDuration(0); - a5->setEndValue(12); - group.addAnimation(a5); - - QCOMPARE(o.property("myProperty").toInt(), 42); - QCOMPARE(o.property("myOtherProperty").toInt(), 13); - QCOMPARE(o2.property("myProperty").toInt(), 42); - QCOMPARE(o2.property("myOtherProperty").toInt(), 13); - - - group.start(); - - QCOMPARE(o.property("myProperty").toInt(), 43); - QCOMPARE(o.property("myOtherProperty").toInt(), 13); - QCOMPARE(o2.property("myProperty").toInt(), 42); - QCOMPARE(o2.property("myOtherProperty").toInt(), 13); - - QTest::qWait(50); - - int o2val = o2.property("myOtherProperty").toInt(); - QVERIFY(o2val > 13); - QVERIFY(o2val < 31); - QCOMPARE(o.property("myProperty").toInt(), 43); - QCOMPARE(o.property("myOtherProperty").toInt(), 13); - - QTest::qWait(500); - - QCOMPARE(o.property("myProperty").toInt(), 44); - QCOMPARE(o2.property("myProperty").toInt(), 42); - QCOMPARE(o2.property("myOtherProperty").toInt(), 31); - QCOMPARE(a1->state(), QAnimationGroup::Stopped); - QCOMPARE(a2->state(), QAnimationGroup::Stopped); - QCOMPARE(a3->state(), QAnimationGroup::Stopped); - QCOMPARE(a4->state(), QAnimationGroup::Running); - QCOMPARE(a5->state(), QAnimationGroup::Stopped); - QCOMPARE(group.state(), QAnimationGroup::Running); - QTest::qWait(500); - - QTRY_COMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(o.property("myProperty").toInt(), 44); - QCOMPARE(o.property("myOtherProperty").toInt(), 75); - QCOMPARE(o2.property("myProperty").toInt(), 12); - QCOMPARE(o2.property("myOtherProperty").toInt(), 31); - QCOMPARE(a1->state(), QAnimationGroup::Stopped); - QCOMPARE(a2->state(), QAnimationGroup::Stopped); - QCOMPARE(a3->state(), QAnimationGroup::Stopped); - QCOMPARE(a4->state(), QAnimationGroup::Stopped); - QCOMPARE(a5->state(), QAnimationGroup::Stopped); -} - -void tst_QSequentialAnimationGroup::propagateGroupUpdateToChildren() -{ - // this test verifies if group state changes are updating its children correctly - QSequentialAnimationGroup group; - - QObject o; - o.setProperty("ole", 42); - QCOMPARE(o.property("ole").toInt(), 42); - - QPropertyAnimation anim1(&o, "ole"); - anim1.setEndValue(43); - anim1.setDuration(100); - QVERIFY(!anim1.currentValue().isValid()); - QCOMPARE(anim1.currentValue().toInt(), 0); - QCOMPARE(o.property("ole").toInt(), 42); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(200); - - QVERIFY(anim2.currentValue().isValid()); - QCOMPARE(anim2.currentValue().toInt(), 0); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - - group.start(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Paused); - QCOMPARE(anim1.state(), QAnimationGroup::Paused); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); -} - -void tst_QSequentialAnimationGroup::updateChildrenWithRunningGroup() -{ - // assert that its possible to modify a child's state directly while their group is running - QSequentialAnimationGroup group; - - TestAnimation anim; - anim.setStartValue(0); - anim.setEndValue(100); - anim.setDuration(200); - - QSignalSpy groupStateChangedSpy(&group, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy childStateChangedSpy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - QCOMPARE(groupStateChangedSpy.count(), 0); - QCOMPARE(childStateChangedSpy.count(), 0); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim); - - group.start(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim.state(), QAnimationGroup::Running); - - QCOMPARE(groupStateChangedSpy.count(), 1); - QCOMPARE(childStateChangedSpy.count(), 1); - - QCOMPARE(qVariantValue(groupStateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(childStateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - - // starting directly a running child will not have any effect - anim.start(); - - QCOMPARE(groupStateChangedSpy.count(), 1); - QCOMPARE(childStateChangedSpy.count(), 1); - - anim.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim.state(), QAnimationGroup::Paused); - - // in the animation stops directly, the group will still be running - anim.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim.state(), QAnimationGroup::Stopped); -} - -void tst_QSequentialAnimationGroup::deleteChildrenWithRunningGroup() -{ - // test if children can be activated when their group is stopped - QSequentialAnimationGroup group; - - QVariantAnimation *anim1 = new TestAnimation; - anim1->setStartValue(0); - anim1->setEndValue(100); - anim1->setDuration(200); - group.addAnimation(anim1); - - QCOMPARE(group.duration(), anim1->duration()); - - group.start(); - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim1->state(), QAnimationGroup::Running); - - QTest::qWait(50); - QVERIFY(group.currentTime() > 0); - - delete anim1; - QCOMPARE(group.animationCount(), 0); - QCOMPARE(group.duration(), 0); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(group.currentTime(), 0); //that's the invariant -} - -void tst_QSequentialAnimationGroup::startChildrenWithStoppedGroup() -{ - // test if children can be activated when their group is stopped - QSequentialAnimationGroup group; - - TestAnimation anim1; - anim1.setStartValue(0); - anim1.setEndValue(100); - anim1.setDuration(200); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(200); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - - group.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - anim1.start(); - anim2.start(); - anim2.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Paused); -} - -void tst_QSequentialAnimationGroup::stopGroupWithRunningChild() -{ - // children that started independently will not be affected by a group stop - QSequentialAnimationGroup group; - - TestAnimation anim1; - anim1.setStartValue(0); - anim1.setEndValue(100); - anim1.setDuration(200); - - TestAnimation anim2; - anim2.setStartValue(0); - anim2.setEndValue(100); - anim2.setDuration(200); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); - - group.addAnimation(&anim1); - group.addAnimation(&anim2); - - anim1.start(); - anim2.start(); - anim2.pause(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Paused); - - group.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Running); - QCOMPARE(anim2.state(), QAnimationGroup::Paused); - - anim1.stop(); - anim2.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1.state(), QAnimationGroup::Stopped); - QCOMPARE(anim2.state(), QAnimationGroup::Stopped); -} - -void tst_QSequentialAnimationGroup::startGroupWithRunningChild() -{ - // as the group has precedence over its children, starting a group will restart all the children - QSequentialAnimationGroup group; - - TestAnimation *anim1 = new TestAnimation(); - anim1->setStartValue(0); - anim1->setEndValue(100); - anim1->setDuration(200); - - TestAnimation *anim2 = new TestAnimation(); - anim2->setStartValue(0); - anim2->setEndValue(100); - anim2->setDuration(200); - - QSignalSpy stateChangedSpy1(anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - QSignalSpy stateChangedSpy2(anim2, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - QCOMPARE(stateChangedSpy1.count(), 0); - QCOMPARE(stateChangedSpy2.count(), 0); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1->state(), QAnimationGroup::Stopped); - QCOMPARE(anim2->state(), QAnimationGroup::Stopped); - - group.addAnimation(anim1); - group.addAnimation(anim2); - - anim1->start(); - anim2->start(); - anim2->pause(); - - QVERIFY(compareStates(stateChangedSpy1, (StateList() << QAbstractAnimation::Running))); - - QVERIFY(compareStates(stateChangedSpy2, (StateList() << QAbstractAnimation::Running - << QAbstractAnimation::Paused))); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1->state(), QAnimationGroup::Running); - QCOMPARE(anim2->state(), QAnimationGroup::Paused); - - group.start(); - - QVERIFY(compareStates(stateChangedSpy1, (StateList() << QAbstractAnimation::Running - << QAbstractAnimation::Stopped - << QAbstractAnimation::Running))); - QVERIFY(compareStates(stateChangedSpy2, (StateList() << QAbstractAnimation::Running - << QAbstractAnimation::Paused))); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim1->state(), QAnimationGroup::Running); - QCOMPARE(anim2->state(), QAnimationGroup::Paused); - - QTest::qWait(300); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim1->state(), QAnimationGroup::Stopped); - QCOMPARE(anim2->state(), QAnimationGroup::Running); - - QCOMPARE(stateChangedSpy2.count(), 4); - QCOMPARE(qVariantValue(stateChangedSpy2.at(2).at(1)), - QAnimationGroup::Stopped); - QCOMPARE(qVariantValue(stateChangedSpy2.at(3).at(1)), - QAnimationGroup::Running); - - group.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(anim1->state(), QAnimationGroup::Stopped); - QCOMPARE(anim2->state(), QAnimationGroup::Stopped); -} - -void tst_QSequentialAnimationGroup::zeroDurationAnimation() -{ - QSequentialAnimationGroup group; - - TestAnimation *anim1 = new TestAnimation(); - anim1->setStartValue(0); - anim1->setEndValue(100); - anim1->setDuration(0); - - TestAnimation *anim2 = new TestAnimation(); - anim2->setStartValue(0); - anim2->setEndValue(100); - anim2->setDuration(100); - - AnimationObject o1; - QPropertyAnimation *anim3 = new QPropertyAnimation(&o1, "value"); - anim3->setEndValue(100); - anim3->setDuration(0); - - QSignalSpy stateChangedSpy(anim1, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - group.addAnimation(anim1); - group.addAnimation(anim2); - group.addAnimation(anim3); - group.setLoopCount(2); - group.start(); - - QCOMPARE(stateChangedSpy.count(), 2); - QCOMPARE(qVariantValue(stateChangedSpy.at(0).at(1)), - QAnimationGroup::Running); - QCOMPARE(qVariantValue(stateChangedSpy.at(1).at(1)), - QAnimationGroup::Stopped); - - QCOMPARE(anim1->state(), QAnimationGroup::Stopped); - QCOMPARE(anim2->state(), QAnimationGroup::Running); - QCOMPARE(group.state(), QAnimationGroup::Running); - - //now let's try to seek to the next loop - group.setCurrentTime(group.duration() + 1); - QCOMPARE(anim1->state(), QAnimationGroup::Stopped); - QCOMPARE(anim2->state(), QAnimationGroup::Running); - QCOMPARE(anim3->state(), QAnimationGroup::Stopped); - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(o1.value(), 100); //anim3 should have been run -} - -void tst_QSequentialAnimationGroup::stopUncontrolledAnimations() -{ - QSequentialAnimationGroup group; - - AnimationObject o1; - UncontrolledAnimation notTimeDriven(&o1, "value"); - QCOMPARE(notTimeDriven.totalDuration(), -1); - - TestAnimation loopsForever; - loopsForever.setStartValue(0); - loopsForever.setEndValue(100); - loopsForever.setDuration(100); - loopsForever.setLoopCount(-1); - - group.addAnimation(¬TimeDriven); - group.addAnimation(&loopsForever); - - group.start(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Running); - QCOMPARE(loopsForever.state(), QAnimationGroup::Stopped); - - notTimeDriven.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever.state(), QAnimationGroup::Running); - - loopsForever.stop(); - - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); - QCOMPARE(loopsForever.state(), QAnimationGroup::Stopped); -} - -void tst_QSequentialAnimationGroup::finishWithUncontrolledAnimation() -{ - AnimationObject o1; - - //1st case: - //first we test a group with one uncontrolled animation - QSequentialAnimationGroup group; - UncontrolledAnimation notTimeDriven(&o1, "value", &group); - QSignalSpy spy(&group, SIGNAL(finished())); - - group.start(); - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Running); - QCOMPARE(group.currentTime(), 0); - QCOMPARE(notTimeDriven.currentTime(), 0); - - QTest::qWait(300); //wait for the end of notTimeDriven - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); - const int actualDuration = notTimeDriven.currentTime(); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(group.currentTime(), actualDuration); - QCOMPARE(spy.count(), 1); - - //2nd case: - // lets make sure the seeking will work again - spy.clear(); - QPropertyAnimation anim(&group); - QSignalSpy animStateChangedSpy(&anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); - - group.setCurrentTime(300); - QCOMPARE(group.state(), QAnimationGroup::Stopped); - QCOMPARE(notTimeDriven.currentTime(), actualDuration); - QCOMPARE(group.currentAnimation(), &anim); - - //3rd case: - //now let's add a perfectly defined animation at the end - QCOMPARE(animStateChangedSpy.count(), 0); - group.start(); - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Running); - QCOMPARE(group.currentTime(), 0); - QCOMPARE(notTimeDriven.currentTime(), 0); - - QCOMPARE(animStateChangedSpy.count(), 0); - - QTest::qWait(300); //wait for the end of notTimeDriven - QCOMPARE(notTimeDriven.state(), QAnimationGroup::Stopped); - QCOMPARE(group.state(), QAnimationGroup::Running); - QCOMPARE(anim.state(), QAnimationGroup::Running); - QCOMPARE(group.currentAnimation(), &anim); - QCOMPARE(animStateChangedSpy.count(), 1); - QTest::qWait(300); //wait for the end of anim - - QCOMPARE(anim.state(), QAnimationGroup::Stopped); - QCOMPARE(anim.currentTime(), anim.duration()); - - //we should simply be at the end - QCOMPARE(spy.count(), 1); - QCOMPARE(animStateChangedSpy.count(), 2); - QCOMPARE(group.currentTime(), notTimeDriven.currentTime() + anim.currentTime()); -} - -void tst_QSequentialAnimationGroup::addRemoveAnimation() -{ - //this test is specific to the sequential animation group - QSequentialAnimationGroup group; - - QCOMPARE(group.duration(), 0); - QCOMPARE(group.currentTime(), 0); - QVariantAnimation *anim1 = new QPropertyAnimation; - group.addAnimation(anim1); - QCOMPARE(group.duration(), 250); - QCOMPARE(group.currentTime(), 0); - QCOMPARE(group.currentAnimation(), anim1); - - //let's append an animation - QVariantAnimation *anim2 = new QPropertyAnimation; - group.addAnimation(anim2); - QCOMPARE(group.duration(), 500); - QCOMPARE(group.currentTime(), 0); - QCOMPARE(group.currentAnimation(), anim1); - - //let's prepend an animation - QVariantAnimation *anim0 = new QPropertyAnimation; - group.insertAnimationAt(0, anim0); - QCOMPARE(group.duration(), 750); - QCOMPARE(group.currentTime(), 0); - QCOMPARE(group.currentAnimation(), anim0); //anim0 has become the new currentAnimation - - group.setCurrentTime(300); //anim0 | anim1 | anim2 - QCOMPARE(group.currentTime(), 300); - QCOMPARE(group.currentAnimation(), anim1); - QCOMPARE(anim1->currentTime(), 50); - - group.removeAnimation(anim0); //anim1 | anim2 - QCOMPARE(group.currentTime(), 50); - QCOMPARE(group.currentAnimation(), anim1); - QCOMPARE(anim1->currentTime(), 50); - - group.setCurrentTime(0); - group.insertAnimationAt(0, anim0); //anim0 | anim1 | anim2 - group.setCurrentTime(300); - QCOMPARE(group.currentTime(), 300); - QCOMPARE(group.currentAnimation(), anim1); - QCOMPARE(anim1->currentTime(), 50); - - group.removeAnimation(anim1); //anim0 | anim2 - QCOMPARE(group.currentTime(), 250); - QCOMPARE(group.currentAnimation(), anim2); - QCOMPARE(anim0->currentTime(), 250); -} - -void tst_QSequentialAnimationGroup::currentAnimation() -{ - QSequentialAnimationGroup group; - QVERIFY(group.currentAnimation() == 0); - - QPropertyAnimation anim; - anim.setDuration(0); - group.addAnimation(&anim); - QCOMPARE(group.currentAnimation(), &anim); -} - -void tst_QSequentialAnimationGroup::currentAnimationWithZeroDuration() -{ - QSequentialAnimationGroup group; - QVERIFY(group.currentAnimation() == 0); - - QPropertyAnimation zero1; - zero1.setDuration(0); - QPropertyAnimation zero2; - zero2.setDuration(0); - - QPropertyAnimation anim; - - QPropertyAnimation zero3; - zero3.setDuration(0); - QPropertyAnimation zero4; - zero4.setDuration(0); - - - group.addAnimation(&zero1); - group.addAnimation(&zero2); - group.addAnimation(&anim); - group.addAnimation(&zero3); - group.addAnimation(&zero4); - - QCOMPARE(group.currentAnimation(), &zero1); - - group.setCurrentTime(0); - QCOMPARE(group.currentAnimation(), &anim); - - group.setCurrentTime(group.duration()); - QCOMPARE(group.currentAnimation(), &zero4); - - group.setDirection(QAbstractAnimation::Backward); - - group.setCurrentTime(0); - QCOMPARE(group.currentAnimation(), &zero1); - - group.setCurrentTime(group.duration()); - QCOMPARE(group.currentAnimation(), &anim); -} - -void tst_QSequentialAnimationGroup::insertAnimation() -{ - QSequentialAnimationGroup group; - group.setLoopCount(2); - QPropertyAnimation *anim = new QPropertyAnimation(&group); - QCOMPARE(group.duration(), anim->duration()); - group.setCurrentTime(300); - QCOMPARE(group.currentLoop(), 1); - - //this will crash if the sequential group calls duration on the created animation - new QPropertyAnimation(&group); -} - - -class SequentialAnimationGroup : public QSequentialAnimationGroup -{ - Q_OBJECT -public slots: - void clearAnimations() - { - QSequentialAnimationGroup::clearAnimations(); - } - - void refill() - { - stop(); - clearAnimations(); - new QPropertyAnimation(this); - start(); - } - -}; - - -void tst_QSequentialAnimationGroup::clearAnimations() -{ - SequentialAnimationGroup group; - QPointer anim1 = new QPropertyAnimation(&group); - group.connect(anim1, SIGNAL(finished()), SLOT(clearAnimations())); - new QPropertyAnimation(&group); - QCOMPARE(group.animationCount(), 2); - - group.start(); - QTest::qWait(anim1->duration() + 100); - QCOMPARE(group.animationCount(), 0); - QCOMPARE(group.state(), QAbstractAnimation::Stopped); - QCOMPARE(group.currentTime(), 0); - - anim1 = new QPropertyAnimation(&group); - group.connect(anim1, SIGNAL(finished()), SLOT(refill())); - group.start(); - QTest::qWait(anim1->duration() + 100); - QVERIFY(anim1 == 0); //anim1 should have been deleted - QCOMPARE(group.state(), QAbstractAnimation::Running); -} - -QTEST_MAIN(tst_QSequentialAnimationGroup) -#include "tst_qsequentialanimationgroup.moc" diff --git a/tests/auto/qstate/qstate.pro b/tests/auto/qstate/qstate.pro deleted file mode 100644 index 9131fa8..0000000 --- a/tests/auto/qstate/qstate.pro +++ /dev/null @@ -1,5 +0,0 @@ -load(qttest_p4) -QT = core -SOURCES += tst_qstate.cpp - - diff --git a/tests/auto/qstate/tst_qstate.cpp b/tests/auto/qstate/tst_qstate.cpp deleted file mode 100644 index 75b1905..0000000 --- a/tests/auto/qstate/tst_qstate.cpp +++ /dev/null @@ -1,340 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -****************************************************************************/ - -#include - -#include "qstate.h" -#include "qstatemachine.h" -#include "qsignaltransition.h" - -// Will try to wait for the condition while allowing event processing -#define QTRY_COMPARE(__expr, __expected) \ - do { \ - const int __step = 50; \ - const int __timeout = 5000; \ - if ((__expr) != (__expected)) { \ - QTest::qWait(0); \ - } \ - for (int __i = 0; __i < __timeout && ((__expr) != (__expected)); __i+=__step) { \ - QTest::qWait(__step); \ - } \ - QCOMPARE(__expr, __expected); \ - } while(0) - -//TESTED_CLASS= -//TESTED_FILES= - -class tst_QState : public QObject -{ - Q_OBJECT - -public: - tst_QState(); - virtual ~tst_QState(); - -private slots: -#if 0 - void test(); -#endif - void assignProperty(); - void assignPropertyTwice(); - void historyInitialState(); - -private: - bool functionCalled; -}; - -tst_QState::tst_QState() : functionCalled(false) -{ -} - -tst_QState::~tst_QState() -{ -} - -#if 0 -void tst_QState::test() -{ - QStateMachine machine; - QState *s1 = new QState(machine.rootState()); - - QCOMPARE(s1->machine(), &machine); - QCOMPARE(s1->parentState(), machine.rootState()); - QCOMPARE(s1->initialState(), (QState*)0); - QVERIFY(s1->childStates().isEmpty()); - QVERIFY(s1->transitions().isEmpty()); - - QCOMPARE(s1->isFinal(), false); - s1->setFinal(true); - QCOMPARE(s1->isFinal(), true); - s1->setFinal(false); - QCOMPARE(s1->isFinal(), false); - - QCOMPARE(s1->isParallel(), false); - s1->setParallel(true); - QCOMPARE(s1->isParallel(), true); - s1->setParallel(false); - QCOMPARE(s1->isParallel(), false); - - QCOMPARE(s1->isAtomic(), true); - QCOMPARE(s1->isCompound(), false); - QCOMPARE(s1->isComplex(), false); - - QState *s11 = new QState(s1); - QCOMPARE(s11->parentState(), s1); - QCOMPARE(s11->isAtomic(), true); - QCOMPARE(s11->isCompound(), false); - QCOMPARE(s11->isComplex(), false); - QCOMPARE(s11->machine(), s1->machine()); - QVERIFY(s11->isDescendantOf(s1)); - - QCOMPARE(s1->initialState(), (QState*)0); - QCOMPARE(s1->childStates().size(), 1); - QCOMPARE(s1->childStates().at(0), s11); - - QCOMPARE(s1->isAtomic(), false); - QCOMPARE(s1->isCompound(), true); - QCOMPARE(s1->isComplex(), true); - - s1->setParallel(true); - QCOMPARE(s1->isAtomic(), false); - QCOMPARE(s1->isCompound(), false); - QCOMPARE(s1->isComplex(), true); - - QState *s12 = new QState(s1); - QCOMPARE(s12->parentState(), s1); - QCOMPARE(s12->isAtomic(), true); - QCOMPARE(s12->isCompound(), false); - QCOMPARE(s12->isComplex(), false); - QCOMPARE(s12->machine(), s1->machine()); - QVERIFY(s12->isDescendantOf(s1)); - QVERIFY(!s12->isDescendantOf(s11)); - - QCOMPARE(s1->initialState(), (QState*)0); - QCOMPARE(s1->childStates().size(), 2); - QCOMPARE(s1->childStates().at(0), s11); - QCOMPARE(s1->childStates().at(1), s12); - - QCOMPARE(s1->isAtomic(), false); - QCOMPARE(s1->isCompound(), false); - QCOMPARE(s1->isComplex(), true); - - s1->setParallel(false); - QCOMPARE(s1->isAtomic(), false); - QCOMPARE(s1->isCompound(), true); - QCOMPARE(s1->isComplex(), true); - - s1->setInitialState(s11); - QCOMPARE(s1->initialState(), s11); - - s1->setInitialState(0); - QCOMPARE(s1->initialState(), (QState*)0); - - s1->setInitialState(s12); - QCOMPARE(s1->initialState(), s12); - - QState *s13 = new QState(); - s1->setInitialState(s13); - QCOMPARE(s13->parentState(), s1); - QCOMPARE(s1->childStates().size(), 3); - QCOMPARE(s1->childStates().at(0), s11); - QCOMPARE(s1->childStates().at(1), s12); - QCOMPARE(s1->childStates().at(2), s13); - QVERIFY(s13->isDescendantOf(s1)); - - QVERIFY(s12->childStates().isEmpty()); - - QState *s121 = new QState(s12); - QCOMPARE(s121->parentState(), s12); - QCOMPARE(s121->isAtomic(), true); - QCOMPARE(s121->isCompound(), false); - QCOMPARE(s121->isComplex(), false); - QCOMPARE(s121->machine(), s12->machine()); - QVERIFY(s121->isDescendantOf(s12)); - QVERIFY(s121->isDescendantOf(s1)); - QVERIFY(!s121->isDescendantOf(s11)); - - QCOMPARE(s12->childStates().size(), 1); - QCOMPARE(s12->childStates().at(0), (QState*)s121); - - QCOMPARE(s1->childStates().size(), 3); - QCOMPARE(s1->childStates().at(0), s11); - QCOMPARE(s1->childStates().at(1), s12); - QCOMPARE(s1->childStates().at(2), s13); - - s11->addTransition(s12); - QCOMPARE(s11->transitions().size(), 1); - QCOMPARE(s11->transitions().at(0)->sourceState(), s11); - QCOMPARE(s11->transitions().at(0)->targetStates().size(), 1); - QCOMPARE(s11->transitions().at(0)->targetStates().at(0), s12); - QCOMPARE(s11->transitions().at(0)->eventType(), QEvent::None); - - QState *s14 = new QState(); - s12->addTransition(QList() << s13 << s14); - QCOMPARE(s12->transitions().size(), 1); - QCOMPARE(s12->transitions().at(0)->sourceState(), s12); - QCOMPARE(s12->transitions().at(0)->targetStates().size(), 2); - QCOMPARE(s12->transitions().at(0)->targetStates().at(0), s13); - QCOMPARE(s12->transitions().at(0)->targetStates().at(1), s14); - QCOMPARE(s12->transitions().at(0)->eventType(), QEvent::None); - - s13->addTransition(this, SIGNAL(destroyed()), s14); - QCOMPARE(s13->transitions().size(), 1); - QCOMPARE(s13->transitions().at(0)->sourceState(), s13); - QCOMPARE(s13->transitions().at(0)->targetStates().size(), 1); - QCOMPARE(s13->transitions().at(0)->targetStates().at(0), s14); - QCOMPARE(s13->transitions().at(0)->eventType(), QEvent::Signal); - QVERIFY(qobject_cast(s13->transitions().at(0)) != 0); - - delete s13->transitions().at(0); - QCOMPARE(s13->transitions().size(), 0); - - s12->addTransition(this, SIGNAL(destroyed()), s11); - QCOMPARE(s12->transitions().size(), 2); -} -#endif - -class TestClass: public QObject -{ - Q_OBJECT -public: - TestClass() : called(false) {} - bool called; - -public slots: - void slot() { called = true; } - - -}; - -void tst_QState::assignProperty() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("fooBar", 10); - - QState *s1 = new QState(machine.rootState()); - s1->assignProperty(object, "fooBar", 20); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(object->property("fooBar").toInt(), 20); -} - -void tst_QState::assignPropertyTwice() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("fooBar", 10); - - QState *s1 = new QState(machine.rootState()); - s1->assignProperty(object, "fooBar", 20); - s1->assignProperty(object, "fooBar", 30); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(object->property("fooBar").toInt(), 30); -} - -class EventTestTransition: public QAbstractTransition -{ -public: - EventTestTransition(QEvent::Type type, QState *targetState) - : QAbstractTransition(QList() << targetState), m_type(type) - { - } - -protected: - bool eventTest(QEvent *e) - { - return e->type() == m_type; - } - - void onTransition(QEvent *) {} - -private: - QEvent::Type m_type; - -}; - -void tst_QState::historyInitialState() -{ - QStateMachine machine; - - QState *s1 = new QState(machine.rootState()); - - QState *s2 = new QState(machine.rootState()); - QHistoryState *h1 = new QHistoryState(s2); - - s2->setInitialState(h1); - - QState *s3 = new QState(s2); - h1->setDefaultState(s3); - - QState *s4 = new QState(s2); - - s1->addTransition(new EventTestTransition(QEvent::User, s2)); - s2->addTransition(new EventTestTransition(QEvent::User, s1)); - s3->addTransition(new EventTestTransition(QEvent::Type(QEvent::User+1), s4)); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s3)); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s3)); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User+1))); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s4)); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s4)); -} - - -QTEST_MAIN(tst_QState) -#include "tst_qstate.moc" diff --git a/tests/auto/qstatemachine/qstatemachine.pro b/tests/auto/qstatemachine/qstatemachine.pro deleted file mode 100644 index e5b32b5..0000000 --- a/tests/auto/qstatemachine/qstatemachine.pro +++ /dev/null @@ -1,4 +0,0 @@ -load(qttest_p4) -QT = core gui -SOURCES += tst_qstatemachine.cpp - diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp deleted file mode 100644 index 40c01bd..0000000 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ /dev/null @@ -1,3548 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the test suite of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include - -#include "qstatemachine.h" -#include "qstate.h" -#include "qhistorystate.h" -#include "qkeyeventtransition.h" -#include "qmouseeventtransition.h" -#include "private/qstate_p.h" -#include "private/qstatemachine_p.h" - -// Will try to wait for the condition while allowing event processing -#define QTRY_COMPARE(__expr, __expected) \ - do { \ - const int __step = 50; \ - const int __timeout = 5000; \ - if ((__expr) != (__expected)) { \ - QTest::qWait(0); \ - } \ - for (int __i = 0; __i < __timeout && ((__expr) != (__expected)); __i+=__step) { \ - QTest::qWait(__step); \ - } \ - QCOMPARE(__expr, __expected); \ - } while(0) - -//TESTED_CLASS= -//TESTED_FILES= - -static int globalTick; - -// Run exec for a maximum of TIMEOUT msecs -#define QCOREAPPLICATION_EXEC(TIMEOUT) \ -{ \ - QTimer timer; \ - timer.setSingleShot(true); \ - timer.setInterval(TIMEOUT); \ - timer.start(); \ - connect(&timer, SIGNAL(timeout()), QCoreApplication::instance(), SLOT(quit())); \ - QCoreApplication::exec(); \ -} - -class tst_QStateMachine : public QObject -{ - Q_OBJECT -public: - tst_QStateMachine(); - virtual ~tst_QStateMachine(); - -private slots: - void init(); - void cleanup(); - - void rootState(); - void addAndRemoveState(); - void stateEntryAndExit(); - void assignProperty(); - void assignPropertyWithAnimation(); - void postEvent(); - void stateFinished(); - void parallelStates(); - void allSourceToTargetConfigurations(); - void signalTransitions(); - void eventTransitions(); - void historyStates(); - void startAndStop(); - void targetStateWithNoParent(); - void targetStateDeleted(); - void transitionToRootState(); - void transitionEntersParent(); - - void defaultErrorState(); - void customGlobalErrorState(); - void customLocalErrorStateInBrokenState(); - void customLocalErrorStateInOtherState(); - void customLocalErrorStateInParentOfBrokenState(); - void customLocalErrorStateOverridesParent(); - void errorStateHasChildren(); - void errorStateHasErrors(); - void errorStateIsRootState(); - void errorStateEntersParentFirst(); - void customErrorStateIsNull(); - void clearError(); - void historyStateHasNowhereToGo(); - void historyStateAsInitialState(); - void brokenStateIsNeverEntered(); - void customErrorStateNotInGraph(); - void transitionToStateNotInGraph(); - void restoreProperties(); - - void defaultGlobalRestorePolicy(); - void globalRestorePolicySetToRestore(); - void globalRestorePolicySetToDoNotRestore(); - - //void restorePolicyNotInherited(); - //void mixedRestoreProperties(); - //void setRestorePolicyToDoNotRestore(); - //void setGlobalRestorePolicyToGlobalRestore(); - //void restorePolicyOnChildState(); - - void transitionWithParent(); - void transitionsFromParallelStateWithNoChildren(); - void parallelStateTransition(); - void parallelStateAssignmentsDone(); - void nestedRestoreProperties(); - void nestedRestoreProperties2(); - - void simpleAnimation(); - void twoAnimations(); - void twoAnimatedTransitions(); - void playAnimationTwice(); - void nestedTargetStateForAnimation(); - void animatedGlobalRestoreProperty(); - void specificTargetValueOfAnimation(); - - void addDefaultAnimation(); - void addDefaultAnimationWithUnusedAnimation(); - void removeDefaultAnimation(); - void overrideDefaultAnimationWithSpecific(); - -// void addDefaultAnimationForSource(); -// void addDefaultAnimationForTarget(); -// void removeDefaultAnimationForSource(); -// void removeDefaultAnimationForTarget(); -// void overrideDefaultAnimationWithSource(); -// void overrideDefaultAnimationWithTarget(); -// void overrideDefaultSourceAnimationWithSpecific(); -// void overrideDefaultTargetAnimationWithSpecific(); -// void overrideDefaultTargetAnimationWithSource(); -}; - -tst_QStateMachine::tst_QStateMachine() -{ -} - -tst_QStateMachine::~tst_QStateMachine() -{ -} - -class TestState : public QState -{ -public: - enum Event { - Entry, - Exit - }; - TestState(QState *parent) - : QState(parent) {} - QList > events; -protected: - virtual void onEntry(QEvent *) { - events.append(qMakePair(globalTick++, Entry)); - } - virtual void onExit(QEvent *) { - events.append(qMakePair(globalTick++, Exit)); - } -}; - -class TestTransition : public QAbstractTransition -{ -public: - TestTransition(QAbstractState *target) - : QAbstractTransition(QList() << target) {} - QList triggers; -protected: - virtual bool eventTest(QEvent *) { - return true; - } - virtual void onTransition(QEvent *) { - triggers.append(globalTick++); - } -}; - -void tst_QStateMachine::init() -{ -} - -void tst_QStateMachine::cleanup() -{ -} - -class EventTransition : public QAbstractTransition -{ -public: - EventTransition(QEvent::Type type, QAbstractState *target, QState *parent = 0) - : QAbstractTransition(QList() << target, parent), m_type(type) {} -protected: - virtual bool eventTest(QEvent *e) { - return (e->type() == m_type); - } - virtual void onTransition(QEvent *) {} -private: - QEvent::Type m_type; -}; - -void tst_QStateMachine::transitionToRootState() -{ - QStateMachine machine; - - QState *initialState = new QState(); - machine.addState(initialState); - machine.setInitialState(initialState); - - QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::setTargetStates: root state cannot be target of transition"); - initialState->addTransition(new EventTransition(QEvent::User, machine.rootState())); - - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(initialState)); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(initialState)); -} - -void tst_QStateMachine::transitionEntersParent() -{ - QStateMachine machine; - - QObject *entryController = new QObject(&machine); - entryController->setObjectName("entryController"); - entryController->setProperty("greatGrandParentEntered", false); - entryController->setProperty("grandParentEntered", false); - entryController->setProperty("parentEntered", false); - entryController->setProperty("stateEntered", false); - - QState *greatGrandParent = new QState(); - greatGrandParent->setObjectName("grandParent"); - greatGrandParent->assignProperty(entryController, "greatGrandParentEntered", true); - machine.addState(greatGrandParent); - machine.setInitialState(greatGrandParent); - - QState *grandParent = new QState(greatGrandParent); - grandParent->setObjectName("grandParent"); - grandParent->assignProperty(entryController, "grandParentEntered", true); - - QState *parent = new QState(grandParent); - parent->setObjectName("parent"); - parent->assignProperty(entryController, "parentEntered", true); - - QState *state = new QState(parent); - state->setObjectName("state"); - state->assignProperty(entryController, "stateEntered", true); - - QState *initialStateOfGreatGrandParent = new QState(greatGrandParent); - initialStateOfGreatGrandParent->setObjectName("initialStateOfGreatGrandParent"); - greatGrandParent->setInitialState(initialStateOfGreatGrandParent); - - initialStateOfGreatGrandParent->addTransition(new EventTransition(QEvent::User, state)); - - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(entryController->property("greatGrandParentEntered").toBool(), true); - QCOMPARE(entryController->property("grandParentEntered").toBool(), false); - QCOMPARE(entryController->property("parentEntered").toBool(), false); - QCOMPARE(entryController->property("stateEntered").toBool(), false); - QCOMPARE(machine.configuration().count(), 2); - QVERIFY(machine.configuration().contains(greatGrandParent)); - QVERIFY(machine.configuration().contains(initialStateOfGreatGrandParent)); - - entryController->setProperty("greatGrandParentEntered", false); - entryController->setProperty("grandParentEntered", false); - entryController->setProperty("parentEntered", false); - entryController->setProperty("stateEntered", false); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(entryController->property("greatGrandParentEntered").toBool(), false); - QCOMPARE(entryController->property("grandParentEntered").toBool(), true); - QCOMPARE(entryController->property("parentEntered").toBool(), true); - QCOMPARE(entryController->property("stateEntered").toBool(), true); - QCOMPARE(machine.configuration().count(), 4); - QVERIFY(machine.configuration().contains(greatGrandParent)); - QVERIFY(machine.configuration().contains(grandParent)); - QVERIFY(machine.configuration().contains(parent)); - QVERIFY(machine.configuration().contains(state)); -} - -void tst_QStateMachine::defaultErrorState() -{ - QStateMachine machine; - QVERIFY(machine.errorState() != 0); - - QState *brokenState = new QState(); - brokenState->setObjectName("MyInitialState"); - - machine.addState(brokenState); - machine.setInitialState(brokenState); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'MyInitialState'"); - - // initialState has no initial state - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); - QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'MyInitialState'")); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(machine.errorState())); -} - -class CustomErrorState: public QState -{ -public: - CustomErrorState(QStateMachine *machine, QState *parent = 0) - : QState(parent), error(QStateMachine::NoError), m_machine(machine) - { - } - - void onEntry(QEvent *) - { - error = m_machine->error(); - errorString = m_machine->errorString(); - } - - QStateMachine::Error error; - QString errorString; - -private: - QStateMachine *m_machine; -}; - -void tst_QStateMachine::customGlobalErrorState() -{ - QStateMachine machine; - - CustomErrorState *customErrorState = new CustomErrorState(&machine); - customErrorState->setObjectName("customErrorState"); - machine.addState(customErrorState); - machine.setErrorState(customErrorState); - - QState *initialState = new QState(); - initialState->setObjectName("initialState"); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *brokenState = new QState(); - brokenState->setObjectName("brokenState"); - machine.addState(brokenState); - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(machine.errorState(), customErrorState); - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(initialState)); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(initialState)); - - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(customErrorState)); - QCOMPARE(customErrorState->error, QStateMachine::NoInitialStateError); - QCOMPARE(customErrorState->errorString, QString::fromLatin1("Missing initial state in compound state 'brokenState'")); - QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); - QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'brokenState'")); -} - -void tst_QStateMachine::customLocalErrorStateInBrokenState() -{ - QStateMachine machine; - CustomErrorState *customErrorState = new CustomErrorState(&machine); - machine.addState(customErrorState); - - QState *initialState = new QState(); - initialState->setObjectName("initialState"); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *brokenState = new QState(); - brokenState->setObjectName("brokenState"); - machine.addState(brokenState); - brokenState->setErrorState(customErrorState); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(customErrorState)); - QCOMPARE(customErrorState->error, QStateMachine::NoInitialStateError); -} - -void tst_QStateMachine::customLocalErrorStateInOtherState() -{ - QStateMachine machine; - CustomErrorState *customErrorState = new CustomErrorState(&machine); - machine.addState(customErrorState); - - QState *initialState = new QState(); - initialState->setObjectName("initialState"); - QTest::ignoreMessage(QtWarningMsg, "QState::setErrorState: error state cannot belong to a different state machine"); - initialState->setErrorState(customErrorState); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *brokenState = new QState(); - brokenState->setObjectName("brokenState"); - - machine.addState(brokenState); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - - QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'brokenState'"); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(machine.errorState())); -} - -void tst_QStateMachine::customLocalErrorStateInParentOfBrokenState() -{ - QStateMachine machine; - CustomErrorState *customErrorState = new CustomErrorState(&machine); - machine.addState(customErrorState); - - QState *initialState = new QState(); - initialState->setObjectName("initialState"); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *parentOfBrokenState = new QState(); - machine.addState(parentOfBrokenState); - parentOfBrokenState->setObjectName("parentOfBrokenState"); - parentOfBrokenState->setErrorState(customErrorState); - - QState *brokenState = new QState(parentOfBrokenState); - brokenState->setObjectName("brokenState"); - parentOfBrokenState->setInitialState(brokenState); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(customErrorState)); -} - -void tst_QStateMachine::customLocalErrorStateOverridesParent() -{ - QStateMachine machine; - CustomErrorState *customErrorStateForParent = new CustomErrorState(&machine); - machine.addState(customErrorStateForParent); - - CustomErrorState *customErrorStateForBrokenState = new CustomErrorState(&machine); - machine.addState(customErrorStateForBrokenState); - - QState *initialState = new QState(); - initialState->setObjectName("initialState"); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *parentOfBrokenState = new QState(); - machine.addState(parentOfBrokenState); - parentOfBrokenState->setObjectName("parentOfBrokenState"); - parentOfBrokenState->setErrorState(customErrorStateForParent); - - QState *brokenState = new QState(parentOfBrokenState); - brokenState->setObjectName("brokenState"); - brokenState->setErrorState(customErrorStateForBrokenState); - parentOfBrokenState->setInitialState(brokenState); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(customErrorStateForBrokenState)); - QCOMPARE(customErrorStateForBrokenState->error, QStateMachine::NoInitialStateError); - QCOMPARE(customErrorStateForParent->error, QStateMachine::NoError); -} - -void tst_QStateMachine::errorStateHasChildren() -{ - QStateMachine machine; - CustomErrorState *customErrorState = new CustomErrorState(&machine); - customErrorState->setObjectName("customErrorState"); - machine.addState(customErrorState); - - machine.setErrorState(customErrorState); - - QState *childOfErrorState = new QState(customErrorState); - childOfErrorState->setObjectName("childOfErrorState"); - customErrorState->setInitialState(childOfErrorState); - - QState *initialState = new QState(); - initialState->setObjectName("initialState"); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *brokenState = new QState(); - brokenState->setObjectName("brokenState"); - machine.addState(brokenState); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 2); - QVERIFY(machine.configuration().contains(customErrorState)); - QVERIFY(machine.configuration().contains(childOfErrorState)); -} - - -void tst_QStateMachine::errorStateHasErrors() -{ - QStateMachine machine; - CustomErrorState *customErrorState = new CustomErrorState(&machine); - customErrorState->setObjectName("customErrorState"); - machine.addState(customErrorState); - - QAbstractState *oldErrorState = machine.errorState(); - machine.setErrorState(customErrorState); - - QState *childOfErrorState = new QState(customErrorState); - childOfErrorState->setObjectName("childOfErrorState"); - - QState *initialState = new QState(); - initialState->setObjectName("initialState"); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *brokenState = new QState(); - brokenState->setObjectName("brokenState"); - machine.addState(brokenState); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); - QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'customErrorState'"); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(oldErrorState)); // Fall back to default - QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); - QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'customErrorState'")); -} - -void tst_QStateMachine::errorStateIsRootState() -{ - QStateMachine machine; - QTest::ignoreMessage(QtWarningMsg, "QStateMachine::setErrorState: root state cannot be error state"); - machine.setErrorState(machine.rootState()); - - QState *initialState = new QState(); - initialState->setObjectName("initialState"); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *brokenState = new QState(); - brokenState->setObjectName("brokenState"); - machine.addState(brokenState); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialState->addTransition(new EventTransition(QEvent::Type(QEvent::User + 1), brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::Type(QEvent::User + 1))); - QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'brokenState'"); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(machine.errorState())); -} - -void tst_QStateMachine::errorStateEntersParentFirst() -{ - QStateMachine machine; - - QObject *entryController = new QObject(&machine); - entryController->setObjectName("entryController"); - entryController->setProperty("greatGrandParentEntered", false); - entryController->setProperty("grandParentEntered", false); - entryController->setProperty("parentEntered", false); - entryController->setProperty("errorStateEntered", false); - - QState *greatGrandParent = new QState(); - greatGrandParent->setObjectName("greatGrandParent"); - greatGrandParent->assignProperty(entryController, "greatGrandParentEntered", true); - machine.addState(greatGrandParent); - machine.setInitialState(greatGrandParent); - - QState *grandParent = new QState(greatGrandParent); - grandParent->setObjectName("grandParent"); - grandParent->assignProperty(entryController, "grandParentEntered", true); - - QState *parent = new QState(grandParent); - parent->setObjectName("parent"); - parent->assignProperty(entryController, "parentEntered", true); - - QState *errorState = new QState(parent); - errorState->setObjectName("errorState"); - errorState->assignProperty(entryController, "errorStateEntered", true); - machine.setErrorState(errorState); - - QState *initialStateOfGreatGrandParent = new QState(greatGrandParent); - initialStateOfGreatGrandParent->setObjectName("initialStateOfGreatGrandParent"); - greatGrandParent->setInitialState(initialStateOfGreatGrandParent); - - QState *brokenState = new QState(greatGrandParent); - brokenState->setObjectName("brokenState"); - - QState *childState = new QState(brokenState); - childState->setObjectName("childState"); - - initialStateOfGreatGrandParent->addTransition(new EventTransition(QEvent::User, brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(entryController->property("greatGrandParentEntered").toBool(), true); - QCOMPARE(entryController->property("grandParentEntered").toBool(), false); - QCOMPARE(entryController->property("parentEntered").toBool(), false); - QCOMPARE(entryController->property("errorStateEntered").toBool(), false); - QCOMPARE(machine.configuration().count(), 2); - QVERIFY(machine.configuration().contains(greatGrandParent)); - QVERIFY(machine.configuration().contains(initialStateOfGreatGrandParent)); - - entryController->setProperty("greatGrandParentEntered", false); - entryController->setProperty("grandParentEntered", false); - entryController->setProperty("parentEntered", false); - entryController->setProperty("errorStateEntered", false); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(entryController->property("greatGrandParentEntered").toBool(), false); - QCOMPARE(entryController->property("grandParentEntered").toBool(), true); - QCOMPARE(entryController->property("parentEntered").toBool(), true); - QCOMPARE(entryController->property("errorStateEntered").toBool(), true); - QCOMPARE(machine.configuration().count(), 4); - QVERIFY(machine.configuration().contains(greatGrandParent)); - QVERIFY(machine.configuration().contains(grandParent)); - QVERIFY(machine.configuration().contains(parent)); - QVERIFY(machine.configuration().contains(errorState)); -} - -void tst_QStateMachine::customErrorStateIsNull() -{ - QStateMachine machine; - QAbstractState *oldErrorState = machine.errorState(); - machine.rootState()->setErrorState(0); - - QState *initialState = new QState(); - machine.addState(initialState); - machine.setInitialState(initialState); - - QState *brokenState = new QState(); - machine.addState(brokenState); - - new QState(brokenState); - initialState->addTransition(new EventTransition(QEvent::User, brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state ''"); - QCoreApplication::processEvents(); - - QCOMPARE(machine.errorState(), reinterpret_cast(0)); - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(oldErrorState)); -} - -void tst_QStateMachine::clearError() -{ - QStateMachine machine; - machine.setErrorState(new QState(machine.rootState())); // avoid warnings - - QState *brokenState = new QState(machine.rootState()); - brokenState->setObjectName("brokenState"); - machine.setInitialState(brokenState); - new QState(brokenState); - - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(machine.error(), QStateMachine::NoInitialStateError); - QCOMPARE(machine.errorString(), QString::fromLatin1("Missing initial state in compound state 'brokenState'")); - - machine.clearError(); - - QCOMPARE(machine.error(), QStateMachine::NoError); - QVERIFY(machine.errorString().isEmpty()); -} - -void tst_QStateMachine::historyStateAsInitialState() -{ - QStateMachine machine; - - QHistoryState *hs = new QHistoryState(machine.rootState()); - machine.setInitialState(hs); - - QState *s1 = new QState(machine.rootState()); - hs->setDefaultState(s1); - - QState *s2 = new QState(machine.rootState()); - - QHistoryState *s2h = new QHistoryState(s2); - s2->setInitialState(s2h); - - QState *s21 = new QState(s2); - s2h->setDefaultState(s21); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s21)); -} - -void tst_QStateMachine::historyStateHasNowhereToGo() -{ - QStateMachine machine; - - QState *initialState = new QState(machine.rootState()); - machine.setInitialState(initialState); - machine.setErrorState(new QState(machine.rootState())); // avoid warnings - - QState *brokenState = new QState(machine.rootState()); - brokenState->setObjectName("brokenState"); - brokenState->setInitialState(new QState(brokenState)); - - QHistoryState *historyState = new QHistoryState(brokenState); - historyState->setObjectName("historyState"); - initialState->addTransition(new EventTransition(QEvent::User, historyState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(machine.errorState())); - QCOMPARE(machine.error(), QStateMachine::NoDefaultStateInHistoryStateError); - QCOMPARE(machine.errorString(), QString::fromLatin1("Missing default state in history state 'historyState'")); -} - -void tst_QStateMachine::brokenStateIsNeverEntered() -{ - QStateMachine machine; - - QObject *entryController = new QObject(&machine); - entryController->setProperty("brokenStateEntered", false); - entryController->setProperty("childStateEntered", false); - entryController->setProperty("errorStateEntered", false); - - QState *initialState = new QState(machine.rootState()); - machine.setInitialState(initialState); - - QState *errorState = new QState(machine.rootState()); - errorState->assignProperty(entryController, "errorStateEntered", true); - machine.setErrorState(errorState); - - QState *brokenState = new QState(machine.rootState()); - brokenState->assignProperty(entryController, "brokenStateEntered", true); - brokenState->setObjectName("brokenState"); - - QState *childState = new QState(brokenState); - childState->assignProperty(entryController, "childStateEntered", true); - - initialState->addTransition(new EventTransition(QEvent::User, brokenState)); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(entryController->property("errorStateEntered").toBool(), true); - QCOMPARE(entryController->property("brokenStateEntered").toBool(), false); - QCOMPARE(entryController->property("childStateEntered").toBool(), false); -} - -void tst_QStateMachine::transitionToStateNotInGraph() -{ - QStateMachine machine; - - QState *initialState = new QState(machine.rootState()); - initialState->setObjectName("initialState"); - machine.setInitialState(initialState); - - QState independentState; - independentState.setObjectName("independentState"); - initialState->addTransition(&independentState); - - machine.start(); - QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: No common ancestor for targets and source of transition from state 'initialState'"); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(qobject_cast(machine.rootState())->errorState())); -} - -void tst_QStateMachine::customErrorStateNotInGraph() -{ - QStateMachine machine; - - QState errorState; - errorState.setObjectName("errorState"); - QTest::ignoreMessage(QtWarningMsg, "QState::setErrorState: error state cannot belong to a different state machine"); - machine.setErrorState(&errorState); - QVERIFY(&errorState != machine.errorState()); - - QState *initialBrokenState = new QState(machine.rootState()); - initialBrokenState->setObjectName("initialBrokenState"); - machine.setInitialState(initialBrokenState); - new QState(initialBrokenState); - - machine.start(); - QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: Missing initial state in compound state 'initialBrokenState'"); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(machine.errorState())); -} - -void tst_QStateMachine::restoreProperties() -{ - QStateMachine machine; - QCOMPARE(machine.globalRestorePolicy(), QStateMachine::DoNotRestoreProperties); - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - - QObject *object = new QObject(&machine); - object->setProperty("a", 1); - object->setProperty("b", 2); - - QState *S1 = new QState(); - S1->setObjectName("S1"); - S1->assignProperty(object, "a", 3); - machine.addState(S1); - - QState *S2 = new QState(); - S2->setObjectName("S2"); - S2->assignProperty(object, "b", 5); - machine.addState(S2); - - QState *S3 = new QState(); - S3->setObjectName("S3"); - machine.addState(S3); - - QFinalState *S4 = new QFinalState(); - machine.addState(S4); - - S1->addTransition(new EventTransition(QEvent::User, S2)); - S2->addTransition(new EventTransition(QEvent::User, S3)); - S3->addTransition(S4); - - machine.setInitialState(S1); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(object->property("a").toInt(), 3); - QCOMPARE(object->property("b").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(object->property("a").toInt(), 1); - QCOMPARE(object->property("b").toInt(), 5); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(object->property("a").toInt(), 1); - QCOMPARE(object->property("b").toInt(), 2); -} - -void tst_QStateMachine::rootState() -{ - QStateMachine machine; - QVERIFY(machine.rootState() != 0); - QVERIFY(qobject_cast(machine.rootState()) != 0); - QCOMPARE(qobject_cast(machine.rootState())->parentState(), (QState*)0); - QCOMPARE(machine.rootState()->parent(), (QObject*)&machine); - QCOMPARE(machine.rootState()->machine(), &machine); - - QState *s1 = new QState(machine.rootState()); - QCOMPARE(s1->parentState(), machine.rootState()); - - QState *s2 = new QState(); - s2->setParent(&machine); - QCOMPARE(s2->parentState(), machine.rootState()); -} - -void tst_QStateMachine::addAndRemoveState() -{ - QStateMachine machine; - QStatePrivate *root_d = QStatePrivate::get(machine.rootState()); - QCOMPARE(root_d->childStates().size(), 1); // the error state - QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); - - QTest::ignoreMessage(QtWarningMsg, "QStateMachine::addState: cannot add null state"); - machine.addState(0); - - QState *s1 = new QState(); - QCOMPARE(s1->parentState(), (QState*)0); - QCOMPARE(s1->machine(), (QStateMachine*)0); - machine.addState(s1); - QCOMPARE(s1->machine(), &machine); - QCOMPARE(s1->parentState(), machine.rootState()); - QCOMPARE(root_d->childStates().size(), 2); - QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); - QCOMPARE(root_d->childStates().at(1), (QAbstractState*)s1); - - QTest::ignoreMessage(QtWarningMsg, "QStateMachine::addState: state has already been added to this machine"); - machine.addState(s1); - - QState *s2 = new QState(); - QCOMPARE(s2->parentState(), (QState*)0); - machine.addState(s2); - QCOMPARE(s2->parentState(), machine.rootState()); - QCOMPARE(root_d->childStates().size(), 3); - QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); - QCOMPARE(root_d->childStates().at(1), (QAbstractState*)s1); - QCOMPARE(root_d->childStates().at(2), (QAbstractState*)s2); - - QTest::ignoreMessage(QtWarningMsg, "QStateMachine::addState: state has already been added to this machine"); - machine.addState(s2); - - machine.removeState(s1); - QCOMPARE(s1->parentState(), (QState*)0); - QCOMPARE(root_d->childStates().size(), 2); - QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); - QCOMPARE(root_d->childStates().at(1), (QAbstractState*)s2); - - machine.removeState(s2); - QCOMPARE(s2->parentState(), (QState*)0); - QCOMPARE(root_d->childStates().size(), 1); - QCOMPARE(root_d->childStates().at(0), (QAbstractState*)machine.errorState()); - - QTest::ignoreMessage(QtWarningMsg, "QStateMachine::removeState: cannot remove null state"); - machine.removeState(0); - - delete s1; - delete s2; - // ### how to deal with this? - // machine.removeState(machine.errorState()); -} - -void tst_QStateMachine::stateEntryAndExit() -{ - // Two top-level states - { - QStateMachine machine; - - TestState *s1 = new TestState(machine.rootState()); - QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: cannot add transition to null state"); - s1->addTransition((QAbstractState*)0); - QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: cannot add null transition"); - s1->addTransition((QAbstractTransition*)0); - QTest::ignoreMessage(QtWarningMsg, "QState::removeTransition: cannot remove null transition"); - s1->removeTransition((QAbstractTransition*)0); - - TestState *s2 = new TestState(machine.rootState()); - QFinalState *s3 = new QFinalState(machine.rootState()); - - TestTransition *t = new TestTransition(s2); - QCOMPARE(t->machine(), (QStateMachine*)0); - QCOMPARE(t->sourceState(), (QState*)0); - QCOMPARE(t->targetState(), s2); - QCOMPARE(t->targetStates().size(), 1); - QCOMPARE(t->targetStates().at(0), s2); - t->setTargetState(0); - QCOMPARE(t->targetState(), (QState*)0); - QVERIFY(t->targetStates().isEmpty()); - t->setTargetState(s2); - QCOMPARE(t->targetState(), s2); - QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::setTargetStates: target state(s) cannot be null"); - t->setTargetStates(QList() << 0); - QCOMPARE(t->targetState(), s2); - t->setTargetStates(QList() << s2); - QCOMPARE(t->targetState(), s2); - QCOMPARE(t->targetStates().size(), 1); - QCOMPARE(t->targetStates().at(0), s2); - QCOMPARE(s1->addTransition(t), (QAbstractTransition*)t); - QCOMPARE(t->sourceState(), s1); - QCOMPARE(t->machine(), &machine); - - { - QAbstractTransition *trans = s2->addTransition(s3); - QVERIFY(trans != 0); - QCOMPARE(trans->sourceState(), (QAbstractState*)s2); - QCOMPARE(trans->targetState(), (QAbstractState*)s3); - { - char warning[256]; - sprintf(warning, "QState::removeTransition: transition %p's source state (%p) is different from this state (%p)", trans, s2, s1); - QTest::ignoreMessage(QtWarningMsg, warning); - s1->removeTransition(trans); - } - s2->removeTransition(trans); - QCOMPARE(trans->sourceState(), (QAbstractState*)0); - QCOMPARE(trans->targetState(), (QAbstractState*)s3); - QCOMPARE(s2->addTransition(trans), trans); - QCOMPARE(trans->sourceState(), (QAbstractState*)s2); - } - - QSignalSpy startedSpy(&machine, SIGNAL(started())); - QSignalSpy stoppedSpy(&machine, SIGNAL(stopped())); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s1); - QCOMPARE(machine.initialState(), (QAbstractState*)s1); - { - char warning[256]; - sprintf(warning, "QState::setInitialState: state %p is not a child of this state (%p)", machine.rootState(), machine.rootState()); - QTest::ignoreMessage(QtWarningMsg, warning); - machine.setInitialState(machine.rootState()); - QCOMPARE(machine.initialState(), (QAbstractState*)s1); - } - QVERIFY(machine.configuration().isEmpty()); - globalTick = 0; - QVERIFY(!machine.isRunning()); - machine.start(); - - QTRY_COMPARE(startedSpy.count(), 1); - QTRY_COMPARE(finishedSpy.count(), 1); - QTRY_COMPARE(stoppedSpy.count(), 0); - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(s3)); - - // s1 is entered - QCOMPARE(s1->events.count(), 2); - QCOMPARE(s1->events.at(0).first, 0); - QCOMPARE(s1->events.at(0).second, TestState::Entry); - // s1 is exited - QCOMPARE(s1->events.at(1).first, 1); - QCOMPARE(s1->events.at(1).second, TestState::Exit); - // t is triggered - QCOMPARE(t->triggers.count(), 1); - QCOMPARE(t->triggers.at(0), 2); - // s2 is entered - QCOMPARE(s2->events.count(), 2); - QCOMPARE(s2->events.at(0).first, 3); - QCOMPARE(s2->events.at(0).second, TestState::Entry); - // s2 is exited - QCOMPARE(s2->events.at(1).first, 4); - QCOMPARE(s2->events.at(1).second, TestState::Exit); - } - // Two top-level states, one has two child states - { - QStateMachine machine; - - TestState *s1 = new TestState(machine.rootState()); - TestState *s11 = new TestState(s1); - TestState *s12 = new TestState(s1); - TestState *s2 = new TestState(machine.rootState()); - QFinalState *s3 = new QFinalState(machine.rootState()); - s1->setInitialState(s11); - TestTransition *t1 = new TestTransition(s12); - s11->addTransition(t1); - TestTransition *t2 = new TestTransition(s2); - s12->addTransition(t2); - s2->addTransition(s3); - - QSignalSpy startedSpy(&machine, SIGNAL(started())); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s1); - globalTick = 0; - machine.start(); - - QTRY_COMPARE(startedSpy.count(), 1); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(s3)); - - // s1 is entered - QCOMPARE(s1->events.count(), 2); - QCOMPARE(s1->events.at(0).first, 0); - QCOMPARE(s1->events.at(0).second, TestState::Entry); - // s11 is entered - QCOMPARE(s11->events.count(), 2); - QCOMPARE(s11->events.at(0).first, 1); - QCOMPARE(s11->events.at(0).second, TestState::Entry); - // s11 is exited - QCOMPARE(s11->events.at(1).first, 2); - QCOMPARE(s11->events.at(1).second, TestState::Exit); - // t1 is triggered - QCOMPARE(t1->triggers.count(), 1); - QCOMPARE(t1->triggers.at(0), 3); - // s12 is entered - QCOMPARE(s12->events.count(), 2); - QCOMPARE(s12->events.at(0).first, 4); - QCOMPARE(s12->events.at(0).second, TestState::Entry); - // s12 is exited - QCOMPARE(s12->events.at(1).first, 5); - QCOMPARE(s12->events.at(1).second, TestState::Exit); - // s1 is exited - QCOMPARE(s1->events.at(1).first, 6); - QCOMPARE(s1->events.at(1).second, TestState::Exit); - // t2 is triggered - QCOMPARE(t2->triggers.count(), 1); - QCOMPARE(t2->triggers.at(0), 7); - // s2 is entered - QCOMPARE(s2->events.count(), 2); - QCOMPARE(s2->events.at(0).first, 8); - QCOMPARE(s2->events.at(0).second, TestState::Entry); - // s2 is exited - QCOMPARE(s2->events.at(1).first, 9); - QCOMPARE(s2->events.at(1).second, TestState::Exit); - } -} - -void tst_QStateMachine::assignProperty() -{ - QStateMachine machine; - QState *s1 = new QState(machine.rootState()); - - QTest::ignoreMessage(QtWarningMsg, "QState::assignProperty: cannot assign property 'foo' of null object"); - s1->assignProperty(0, "foo", QVariant()); - - s1->assignProperty(s1, "objectName", "s1"); - QFinalState *s2 = new QFinalState(machine.rootState()); - s1->addTransition(s2); - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - QCOMPARE(s1->objectName(), QString::fromLatin1("s1")); - - s1->assignProperty(s1, "objectName", "foo"); - machine.start(); - QCoreApplication::processEvents(); - QCOMPARE(s1->objectName(), QString::fromLatin1("foo")); - - s1->assignProperty(s1, "noSuchProperty", 123); - machine.start(); - QCoreApplication::processEvents(); - QCOMPARE(s1->objectName(), QString::fromLatin1("foo")); - QCOMPARE(s1->dynamicPropertyNames().size(), 1); - QCOMPARE(s1->dynamicPropertyNames().at(0), QByteArray("noSuchProperty")); - - QSignalSpy polishedSpy(s1, SIGNAL(polished())); - machine.start(); - QCoreApplication::processEvents(); - QCOMPARE(polishedSpy.count(), 1); -} - -void tst_QStateMachine::assignPropertyWithAnimation() -{ - // Single animation - { - QStateMachine machine; - QVERIFY(machine.animationsEnabled()); - machine.setAnimationsEnabled(false); - QVERIFY(!machine.animationsEnabled()); - machine.setAnimationsEnabled(true); - QVERIFY(machine.animationsEnabled()); - QObject obj; - obj.setProperty("foo", 321); - obj.setProperty("bar", 654); - QState *s1 = new QState(machine.rootState()); - s1->assignProperty(&obj, "foo", 123); - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(&obj, "foo", 456); - s2->assignProperty(&obj, "bar", 789); - QAbstractTransition *trans = s1->addTransition(s2); - QVERIFY(trans->animations().isEmpty()); - QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::addAnimation: cannot add null animation"); - trans->addAnimation(0); - QPropertyAnimation anim(&obj, "foo"); - anim.setDuration(250); - trans->addAnimation(&anim); - QCOMPARE(trans->animations().size(), 1); - QCOMPARE(trans->animations().at(0), (QAbstractAnimation*)&anim); - QCOMPARE(anim.parent(), (QObject*)0); - QTest::ignoreMessage(QtWarningMsg, "QAbstractTransition::removeAnimation: cannot remove null animation"); - trans->removeAnimation(0); - trans->removeAnimation(&anim); - QVERIFY(trans->animations().isEmpty()); - trans->addAnimation(&anim); - QCOMPARE(trans->animations().size(), 1); - QCOMPARE(trans->animations().at(0), (QAbstractAnimation*)&anim); - QFinalState *s3 = new QFinalState(machine.rootState()); - s2->addTransition(s2, SIGNAL(polished()), s3); - - machine.setInitialState(s1); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(obj.property("foo").toInt(), 456); - QCOMPARE(obj.property("bar").toInt(), 789); - } - // Two animations - { - QStateMachine machine; - QObject obj; - obj.setProperty("foo", 321); - obj.setProperty("bar", 654); - QState *s1 = new QState(machine.rootState()); - s1->assignProperty(&obj, "foo", 123); - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(&obj, "foo", 456); - s2->assignProperty(&obj, "bar", 789); - QAbstractTransition *trans = s1->addTransition(s2); - QPropertyAnimation anim(&obj, "foo"); - anim.setDuration(150); - trans->addAnimation(&anim); - QPropertyAnimation anim2(&obj, "bar"); - anim2.setDuration(150); - trans->addAnimation(&anim2); - QFinalState *s3 = new QFinalState(machine.rootState()); - s2->addTransition(s2, SIGNAL(polished()), s3); - - machine.setInitialState(s1); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(obj.property("foo").toInt(), 456); - QCOMPARE(obj.property("bar").toInt(), 789); - } - // Animation group - { - QStateMachine machine; - QObject obj; - obj.setProperty("foo", 321); - obj.setProperty("bar", 654); - QState *s1 = new QState(machine.rootState()); - s1->assignProperty(&obj, "foo", 123); - s1->assignProperty(&obj, "bar", 321); - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(&obj, "foo", 456); - s2->assignProperty(&obj, "bar", 654); - s2->assignProperty(&obj, "baz", 789); - QAbstractTransition *trans = s1->addTransition(s2); - QSequentialAnimationGroup group; - group.addAnimation(new QPropertyAnimation(&obj, "foo")); - group.addAnimation(new QPropertyAnimation(&obj, "bar")); - trans->addAnimation(&group); - QFinalState *s3 = new QFinalState(machine.rootState()); - s2->addTransition(s2, SIGNAL(polished()), s3); - - machine.setInitialState(s1); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(obj.property("foo").toInt(), 456); - QCOMPARE(obj.property("bar").toInt(), 654); - QCOMPARE(obj.property("baz").toInt(), 789); - } - // Nested states - { - QStateMachine machine; - QObject obj; - obj.setProperty("foo", 321); - obj.setProperty("bar", 654); - QState *s1 = new QState(machine.rootState()); - QCOMPARE(s1->childMode(), QState::ExclusiveStates); - s1->setChildMode(QState::ParallelStates); - QCOMPARE(s1->childMode(), QState::ParallelStates); - s1->setChildMode(QState::ExclusiveStates); - QCOMPARE(s1->childMode(), QState::ExclusiveStates); - QCOMPARE(s1->initialState(), (QAbstractState*)0); - s1->setObjectName("s1"); - s1->assignProperty(&obj, "foo", 123); - s1->assignProperty(&obj, "bar", 456); - QState *s2 = new QState(machine.rootState()); - s2->setObjectName("s2"); - s2->assignProperty(&obj, "foo", 321); - QState *s21 = new QState(s2); - s21->setObjectName("s21"); - s21->assignProperty(&obj, "bar", 654); - QState *s22 = new QState(s2); - s22->setObjectName("s22"); - s22->assignProperty(&obj, "bar", 789); - s2->setInitialState(s21); - QCOMPARE(s2->initialState(), (QAbstractState*)s21); - - QAbstractTransition *trans = s1->addTransition(s2); - QPropertyAnimation anim(&obj, "foo"); - anim.setDuration(500); - trans->addAnimation(&anim); - QPropertyAnimation anim2(&obj, "bar"); - anim2.setDuration(250); - trans->addAnimation(&anim2); - - s21->addTransition(s21, SIGNAL(polished()), s22); - - QFinalState *s3 = new QFinalState(machine.rootState()); - s22->addTransition(s2, SIGNAL(polished()), s3); - - machine.setInitialState(s1); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(obj.property("foo").toInt(), 321); - QCOMPARE(obj.property("bar").toInt(), 789); - } -} - -struct StringEvent : public QEvent -{ -public: - StringEvent(const QString &val) - : QEvent(QEvent::Type(QEvent::User+2)), - value(val) {} - - QString value; -}; - -class StringTransition : public QAbstractTransition -{ -public: - StringTransition(const QString &value, QAbstractState *target) - : QAbstractTransition(QList() << target), m_value(value) {} - -protected: - virtual bool eventTest(QEvent *e) - { - if (e->type() != QEvent::Type(QEvent::User+2)) - return false; - StringEvent *se = static_cast(e); - return (m_value == se->value) && (!m_cond.isValid() || (m_cond.indexIn(m_value) != -1)); - } - virtual void onTransition(QEvent *) {} - -private: - QString m_value; - QRegExp m_cond; -}; - -class StringEventPoster : public QState -{ -public: - StringEventPoster(QStateMachine *machine, const QString &value, QState *parent = 0) - : QState(parent), m_machine(machine), m_value(value), m_delay(0) {} - - void setString(const QString &value) - { m_value = value; } - void setDelay(int delay) - { m_delay = delay; } - -protected: - virtual void onEntry(QEvent *) - { - m_machine->postEvent(new StringEvent(m_value), m_delay); - } - virtual void onExit(QEvent *) {} - -private: - QStateMachine *m_machine; - QString m_value; - int m_delay; -}; - -void tst_QStateMachine::postEvent() -{ - for (int x = 0; x < 2; ++x) { - QStateMachine machine; - { - QEvent e(QEvent::None); - QTest::ignoreMessage(QtWarningMsg, "QStateMachine::postEvent: cannot post event when the state machine is not running"); - machine.postEvent(&e); - } - StringEventPoster *s1 = new StringEventPoster(&machine, "a"); - if (x == 1) - s1->setDelay(100); - QFinalState *s2 = new QFinalState; - s1->addTransition(new StringTransition("a", s2)); - machine.addState(s1); - machine.addState(s2); - machine.setInitialState(s1); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s2)); - - s1->setString("b"); - QFinalState *s3 = new QFinalState(); - machine.addState(s3); - s1->addTransition(new StringTransition("b", s3)); - finishedSpy.clear(); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s3)); - } -} - -void tst_QStateMachine::stateFinished() -{ - QStateMachine machine; - QState *s1 = new QState(machine.rootState()); - QState *s1_1 = new QState(s1); - QFinalState *s1_2 = new QFinalState(s1); - s1_1->addTransition(s1_2); - s1->setInitialState(s1_1); - QFinalState *s2 = new QFinalState(machine.rootState()); - s1->addTransition(s1, SIGNAL(finished()), s2); - machine.setInitialState(s1); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s2)); -} - -void tst_QStateMachine::parallelStates() -{ - QStateMachine machine; - - QState *s1 = new QState(QState::ParallelStates); - QCOMPARE(s1->childMode(), QState::ParallelStates); - QState *s1_1 = new QState(s1); - QState *s1_1_1 = new QState(s1_1); - QFinalState *s1_1_f = new QFinalState(s1_1); - s1_1_1->addTransition(s1_1_f); - s1_1->setInitialState(s1_1_1); - QState *s1_2 = new QState(s1); - QState *s1_2_1 = new QState(s1_2); - QFinalState *s1_2_f = new QFinalState(s1_2); - s1_2_1->addTransition(s1_2_f); - s1_2->setInitialState(s1_2_1); - { - char warning[256]; - sprintf(warning, "QState::setInitialState: ignoring attempt to set initial state of parallel state group %p", s1); - QTest::ignoreMessage(QtWarningMsg, warning); - s1->setInitialState(0); - } - machine.addState(s1); - - QFinalState *s2 = new QFinalState(); - machine.addState(s2); - - s1->addTransition(s1, SIGNAL(finished()), s2); - - machine.setInitialState(s1); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s2)); -} - -void tst_QStateMachine::allSourceToTargetConfigurations() -{ - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - s0->setObjectName("s0"); - QState *s1 = new QState(s0); - s1->setObjectName("s1"); - QState *s11 = new QState(s1); - s11->setObjectName("s11"); - QState *s2 = new QState(s0); - s2->setObjectName("s2"); - QState *s21 = new QState(s2); - s21->setObjectName("s21"); - QState *s211 = new QState(s21); - s211->setObjectName("s211"); - QFinalState *f = new QFinalState(machine.rootState()); - f->setObjectName("f"); - - s0->setInitialState(s1); - s1->setInitialState(s11); - s2->setInitialState(s21); - s21->setInitialState(s211); - - s11->addTransition(new StringTransition("g", s211)); - s1->addTransition(new StringTransition("a", s1)); - s1->addTransition(new StringTransition("b", s11)); - s1->addTransition(new StringTransition("c", s2)); - s1->addTransition(new StringTransition("d", s0)); - s1->addTransition(new StringTransition("f", s211)); - s211->addTransition(new StringTransition("d", s21)); - s211->addTransition(new StringTransition("g", s0)); - s211->addTransition(new StringTransition("h", f)); - s21->addTransition(new StringTransition("b", s211)); - s2->addTransition(new StringTransition("c", s1)); - s2->addTransition(new StringTransition("f", s11)); - s0->addTransition(new StringTransition("e", s211)); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new StringEvent("a")); - QCoreApplication::processEvents(); - machine.postEvent(new StringEvent("b")); - QCoreApplication::processEvents(); - machine.postEvent(new StringEvent("c")); - QCoreApplication::processEvents(); - machine.postEvent(new StringEvent("d")); - QCoreApplication::processEvents(); - machine.postEvent(new StringEvent("e")); - QCoreApplication::processEvents(); - machine.postEvent(new StringEvent("f")); - QCoreApplication::processEvents(); - machine.postEvent(new StringEvent("g")); - QCoreApplication::processEvents(); - machine.postEvent(new StringEvent("h")); - QCoreApplication::processEvents(); - - QTRY_COMPARE(finishedSpy.count(), 1); -} - -class SignalEmitter : public QObject -{ -Q_OBJECT - public: - SignalEmitter(QObject *parent = 0) - : QObject(parent) {} - void emitSignalWithNoArg() - { emit signalWithNoArg(); } - void emitSignalWithIntArg(int arg) - { emit signalWithIntArg(arg); } - void emitSignalWithStringArg(const QString &arg) - { emit signalWithStringArg(arg); } -Q_SIGNALS: - void signalWithNoArg(); - void signalWithIntArg(int); - void signalWithStringArg(const QString &); -}; - -class TestSignalTransition : public QSignalTransition -{ -public: - TestSignalTransition(QState *sourceState = 0) - : QSignalTransition(sourceState) {} - TestSignalTransition(QObject *sender, const char *signal, - QAbstractState *target) - : QSignalTransition(sender, signal, QList() << target) {} - QVariantList argumentsReceived() const { - return m_args; - } -protected: - bool eventTest(QEvent *e) { - if (!QSignalTransition::eventTest(e)) - return false; - QSignalEvent *se = static_cast(e); - const_cast(this)->m_args = se->arguments(); - return true; - } -private: - QVariantList m_args; -}; - -void tst_QStateMachine::signalTransitions() -{ - { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: sender cannot be null"); - QCOMPARE(s0->addTransition(0, SIGNAL(noSuchSignal()), 0), (QObject*)0); - - SignalEmitter emitter; - QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: signal cannot be null"); - QCOMPARE(s0->addTransition(&emitter, 0, 0), (QObject*)0); - - QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: cannot add transition to null state"); - QCOMPARE(s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), 0), (QObject*)0); - - QFinalState *s1 = new QFinalState(machine.rootState()); - QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: no such signal SignalEmitter::noSuchSignal()"); - QCOMPARE(s0->addTransition(&emitter, SIGNAL(noSuchSignal()), s1), (QObject*)0); - - { - QSignalTransition *trans = s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), s1); - QVERIFY(trans != 0); - QCOMPARE(trans->sourceState(), s0); - QCOMPARE(trans->targetState(), (QAbstractState*)s1); - QCOMPARE(trans->senderObject(), (QObject*)&emitter); - QCOMPARE(trans->signal(), QByteArray(SIGNAL(signalWithNoArg()))); - } - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - emitter.emitSignalWithNoArg(); - - QTRY_COMPARE(finishedSpy.count(), 1); - - emitter.emitSignalWithNoArg(); - } - { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QFinalState *s1 = new QFinalState(machine.rootState()); - SignalEmitter emitter; - TestSignalTransition *trans = new TestSignalTransition(&emitter, SIGNAL(signalWithIntArg(int)), s1); - s0->addTransition(trans); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - emitter.emitSignalWithIntArg(123); - - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(trans->argumentsReceived().size(), 1); - QCOMPARE(trans->argumentsReceived().at(0).toInt(), 123); - } - { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QFinalState *s1 = new QFinalState(machine.rootState()); - SignalEmitter emitter; - TestSignalTransition *trans = new TestSignalTransition(&emitter, SIGNAL(signalWithStringArg(QString)), s1); - s0->addTransition(trans); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - QString testString = QString::fromLatin1("hello"); - emitter.emitSignalWithStringArg(testString); - - QTRY_COMPARE(finishedSpy.count(), 1); - QCOMPARE(trans->argumentsReceived().size(), 1); - QCOMPARE(trans->argumentsReceived().at(0).toString(), testString); - } - { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QFinalState *s1 = new QFinalState(machine.rootState()); - - TestSignalTransition *trans = new TestSignalTransition(); - QCOMPARE(trans->senderObject(), (QObject*)0); - QCOMPARE(trans->signal(), QByteArray()); - - SignalEmitter emitter; - trans->setSenderObject(&emitter); - QCOMPARE(trans->senderObject(), (QObject*)&emitter); - trans->setSignal(SIGNAL(signalWithNoArg())); - QCOMPARE(trans->signal(), QByteArray(SIGNAL(signalWithNoArg()))); - trans->setTargetState(s1); - s0->addTransition(trans); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - emitter.emitSignalWithNoArg(); - - QTRY_COMPARE(finishedSpy.count(), 1); - } - // Multiple transitions for same (object,signal) - { - QStateMachine machine; - SignalEmitter emitter; - QState *s0 = new QState(machine.rootState()); - QState *s1 = new QState(machine.rootState()); - QSignalTransition *t0 = s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), s1); - QSignalTransition *t1 = s1->addTransition(&emitter, SIGNAL(signalWithNoArg()), s0); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s0)); - - emitter.emitSignalWithNoArg(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - - s0->removeTransition(t0); - emitter.emitSignalWithNoArg(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s0)); - - emitter.emitSignalWithNoArg(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s0)); - - s1->removeTransition(t1); - emitter.emitSignalWithNoArg(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s0)); - - s0->addTransition(t0); - s1->addTransition(t1); - emitter.emitSignalWithNoArg(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - } -} - -void tst_QStateMachine::eventTransitions() -{ - QPushButton button; - for (int x = 0; x < 2; ++x) { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QFinalState *s1 = new QFinalState(machine.rootState()); - - QMouseEventTransition *trans; - if (x == 0) { - trans = new QMouseEventTransition(&button, QEvent::MouseButtonPress, Qt::LeftButton); - QCOMPARE(trans->targetState(), (QAbstractState*)0); - trans->setTargetState(s1); - } else { - trans = new QMouseEventTransition(&button, QEvent::MouseButtonPress, - Qt::LeftButton, QList() << s1); - } - QCOMPARE(trans->eventType(), QEvent::MouseButtonPress); - QCOMPARE(trans->button(), Qt::LeftButton); - QCOMPARE(trans->targetState(), (QAbstractState*)s1); - s0->addTransition(trans); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - QTest::mousePress(&button, Qt::LeftButton); - QTRY_COMPARE(finishedSpy.count(), 1); - - QTest::mousePress(&button, Qt::LeftButton); - - trans->setEventType(QEvent::MouseButtonRelease); - QCOMPARE(trans->eventType(), QEvent::MouseButtonRelease); - machine.start(); - QCoreApplication::processEvents(); - QTest::mouseRelease(&button, Qt::LeftButton); - QTRY_COMPARE(finishedSpy.count(), 2); - } - for (int x = 0; x < 3; ++x) { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QFinalState *s1 = new QFinalState(machine.rootState()); - - QEventTransition *trans; - if (x == 0) { - trans = new QEventTransition(); - QCOMPARE(trans->eventObject(), (QObject*)0); - QCOMPARE(trans->eventType(), QEvent::None); - trans->setEventObject(&button); - trans->setEventType(QEvent::MouseButtonPress); - trans->setTargetState(s1); - } else if (x == 1) { - trans = new QEventTransition(&button, QEvent::MouseButtonPress); - trans->setTargetState(s1); - } else { - trans = new QEventTransition(&button, QEvent::MouseButtonPress, - QList() << s1); - } - QCOMPARE(trans->eventObject(), (QObject*)&button); - QCOMPARE(trans->eventType(), QEvent::MouseButtonPress); - QCOMPARE(trans->targetState(), (QAbstractState*)s1); - s0->addTransition(trans); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - QTest::mousePress(&button, Qt::LeftButton); - QCoreApplication::processEvents(); - - QTRY_COMPARE(finishedSpy.count(), 1); - } - { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QFinalState *s1 = new QFinalState(machine.rootState()); - - QMouseEventTransition *trans = new QMouseEventTransition(); - QCOMPARE(trans->eventObject(), (QObject*)0); - QCOMPARE(trans->eventType(), QEvent::None); - QCOMPARE(trans->button(), Qt::NoButton); - trans->setEventObject(&button); - trans->setEventType(QEvent::MouseButtonPress); - trans->setButton(Qt::LeftButton); - trans->setTargetState(s1); - s0->addTransition(trans); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - QTest::mousePress(&button, Qt::LeftButton); - QCoreApplication::processEvents(); - - QTRY_COMPARE(finishedSpy.count(), 1); - } - - { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QFinalState *s1 = new QFinalState(machine.rootState()); - - QKeyEventTransition *trans = new QKeyEventTransition(&button, QEvent::KeyPress, Qt::Key_A); - QCOMPARE(trans->eventType(), QEvent::KeyPress); - QCOMPARE(trans->key(), (int)Qt::Key_A); - trans->setTargetState(s1); - s0->addTransition(trans); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - QTest::keyPress(&button, Qt::Key_A); - QCoreApplication::processEvents(); - - QTRY_COMPARE(finishedSpy.count(), 1); - } - { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QFinalState *s1 = new QFinalState(machine.rootState()); - - QKeyEventTransition *trans = new QKeyEventTransition(); - QCOMPARE(trans->eventObject(), (QObject*)0); - QCOMPARE(trans->eventType(), QEvent::None); - QCOMPARE(trans->key(), 0); - trans->setEventObject(&button); - trans->setEventType(QEvent::KeyPress); - trans->setKey(Qt::Key_A); - trans->setTargetState(s1); - s0->addTransition(trans); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - - QTest::keyPress(&button, Qt::Key_A); - QCoreApplication::processEvents(); - - QTRY_COMPARE(finishedSpy.count(), 1); - } - // Multiple transitions for same (object,event) - { - QStateMachine machine; - QState *s0 = new QState(machine.rootState()); - QState *s1 = new QState(machine.rootState()); - QEventTransition *t0 = new QEventTransition(&button, QEvent::MouseButtonPress); - t0->setTargetState(s1); - s0->addTransition(t0); - QEventTransition *t1 = new QEventTransition(&button, QEvent::MouseButtonPress); - t1->setTargetState(s0); - s1->addTransition(t1); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.setInitialState(s0); - machine.start(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s0)); - - QTest::mousePress(&button, Qt::LeftButton); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - - s0->removeTransition(t0); - QTest::mousePress(&button, Qt::LeftButton); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s0)); - - QTest::mousePress(&button, Qt::LeftButton); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s0)); - - s1->removeTransition(t1); - QTest::mousePress(&button, Qt::LeftButton); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s0)); - - s0->addTransition(t0); - s1->addTransition(t1); - QTest::mousePress(&button, Qt::LeftButton); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - } -} - -void tst_QStateMachine::historyStates() -{ - for (int x = 0; x < 2; ++x) { - QStateMachine machine; - QState *root = machine.rootState(); - QState *s0 = new QState(root); - QState *s00 = new QState(s0); - QState *s01 = new QState(s0); - QHistoryState *s0h; - if (x == 0) { - s0h = new QHistoryState(s0); - QCOMPARE(s0h->historyType(), QHistoryState::ShallowHistory); - s0h->setHistoryType(QHistoryState::DeepHistory); - } else { - s0h = new QHistoryState(QHistoryState::DeepHistory, s0); - } - QCOMPARE(s0h->historyType(), QHistoryState::DeepHistory); - s0h->setHistoryType(QHistoryState::ShallowHistory); - QCOMPARE(s0h->historyType(), QHistoryState::ShallowHistory); - QCOMPARE(s0h->defaultState(), (QAbstractState*)0); - s0h->setDefaultState(s00); - QCOMPARE(s0h->defaultState(), (QAbstractState*)s00); - char warning[256]; - sprintf(warning, "QHistoryState::setDefaultState: state %p does not belong to this history state's group (%p)", s0, s0); - QTest::ignoreMessage(QtWarningMsg, warning); - s0h->setDefaultState(s0); - QState *s1 = new QState(root); - QFinalState *s2 = new QFinalState(root); - - s00->addTransition(new StringTransition("a", s01)); - s0->addTransition(new StringTransition("b", s1)); - s1->addTransition(new StringTransition("c", s0h)); - s0->addTransition(new StringTransition("d", s2)); - - root->setInitialState(s0); - s0->setInitialState(s00); - - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s0)); - QVERIFY(machine.configuration().contains(s00)); - - machine.postEvent(new StringEvent("a")); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s0)); - QVERIFY(machine.configuration().contains(s01)); - - machine.postEvent(new StringEvent("b")); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - - machine.postEvent(new StringEvent("c")); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s0)); - QVERIFY(machine.configuration().contains(s01)); - - machine.postEvent(new StringEvent("d")); - QCoreApplication::processEvents(); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s2)); - - QTRY_COMPARE(finishedSpy.count(), 1); - } -} - -void tst_QStateMachine::startAndStop() -{ - QStateMachine machine; - QSignalSpy startedSpy(&machine, SIGNAL(started())); - QSignalSpy stoppedSpy(&machine, SIGNAL(stopped())); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - QVERIFY(!machine.isRunning()); - QTest::ignoreMessage(QtWarningMsg, "QStateMachine::start: No initial state set for machine. Refusing to start."); - machine.start(); - QCOMPARE(startedSpy.count(), 0); - QCOMPARE(stoppedSpy.count(), 0); - QCOMPARE(finishedSpy.count(), 0); - QVERIFY(!machine.isRunning()); - machine.stop(); - QCOMPARE(startedSpy.count(), 0); - QCOMPARE(stoppedSpy.count(), 0); - QCOMPARE(finishedSpy.count(), 0); - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - machine.start(); - QTRY_COMPARE(machine.isRunning(), true); - QTRY_COMPARE(startedSpy.count(), 1); - QCOMPARE(stoppedSpy.count(), 0); - QCOMPARE(finishedSpy.count(), 0); - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(s1)); - - machine.stop(); - QTRY_COMPARE(machine.isRunning(), false); - QTRY_COMPARE(stoppedSpy.count(), 1); - QCOMPARE(startedSpy.count(), 1); - QCOMPARE(finishedSpy.count(), 0); - - QCOMPARE(machine.configuration().count(), 1); - QVERIFY(machine.configuration().contains(s1)); -} - -void tst_QStateMachine::targetStateWithNoParent() -{ - QStateMachine machine; - QState *s1 = new QState(machine.rootState()); - s1->setObjectName("s1"); - QState s2; - s1->addTransition(&s2); - machine.setInitialState(s1); - QSignalSpy startedSpy(&machine, SIGNAL(started())); - QSignalSpy stoppedSpy(&machine, SIGNAL(stopped())); - QSignalSpy finishedSpy(&machine, SIGNAL(finished())); - machine.start(); - QTest::ignoreMessage(QtWarningMsg, "Unrecoverable error detected in running state machine: No common ancestor for targets and source of transition from state 's1'"); - QTRY_COMPARE(machine.isRunning(), true); - QTRY_COMPARE(startedSpy.count(), 1); - QCOMPARE(stoppedSpy.count(), 0); - QCOMPARE(finishedSpy.count(), 0); - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(machine.errorState())); - QCOMPARE(machine.error(), QStateMachine::NoCommonAncestorForTransitionError); -} - -void tst_QStateMachine::targetStateDeleted() -{ - QStateMachine machine; - QState *s1 = new QState(machine.rootState()); - s1->setObjectName("s1"); - QState *s2 = new QState(machine.rootState()); - QAbstractTransition *trans = s1->addTransition(s2); - delete s2; - QCOMPARE(trans->targetState(), (QAbstractState*)0); - QVERIFY(trans->targetStates().isEmpty()); -} - -void tst_QStateMachine::defaultGlobalRestorePolicy() -{ - QStateMachine machine; - - QObject *propertyHolder = new QObject(&machine); - propertyHolder->setProperty("a", 1); - propertyHolder->setProperty("b", 2); - - QState *s1 = new QState(machine.rootState()); - s1->assignProperty(propertyHolder, "a", 3); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(propertyHolder, "b", 4); - - QState *s3 = new QState(machine.rootState()); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - s2->addTransition(new EventTransition(QEvent::User, s3)); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 4); -} - -/* -void tst_QStateMachine::restorePolicyNotInherited() -{ - QStateMachine machine; - - QObject *propertyHolder = new QObject(); - propertyHolder->setProperty("a", 1); - propertyHolder->setProperty("b", 2); - - QState *parentState = new QState(machine.rootState()); - parentState->setObjectName("parentState"); - parentState->setRestorePolicy(QState::RestoreProperties); - - QState *s1 = new QState(parentState); - s1->setObjectName("s1"); - s1->assignProperty(propertyHolder, "a", 3); - parentState->setInitialState(s1); - - QState *s2 = new QState(parentState); - s2->setObjectName("s2"); - s2->assignProperty(propertyHolder, "b", 4); - - QState *s3 = new QState(parentState); - s3->setObjectName("s3"); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - s2->addTransition(new EventTransition(QEvent::User, s3)); - - machine.setInitialState(parentState); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 4); - -}*/ - -void tst_QStateMachine::globalRestorePolicySetToDoNotRestore() -{ - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::DoNotRestoreProperties); - - QObject *propertyHolder = new QObject(&machine); - propertyHolder->setProperty("a", 1); - propertyHolder->setProperty("b", 2); - - QState *s1 = new QState(machine.rootState()); - s1->assignProperty(propertyHolder, "a", 3); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(propertyHolder, "b", 4); - - QState *s3 = new QState(machine.rootState()); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - s2->addTransition(new EventTransition(QEvent::User, s3)); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 4); -} - -/* -void tst_QStateMachine::setRestorePolicyToDoNotRestore() -{ - QObject *object = new QObject(); - object->setProperty("a", 1); - object->setProperty("b", 2); - - QStateMachine machine; - - QState *S1 = new QState(); - S1->setObjectName("S1"); - S1->assignProperty(object, "a", 3); - S1->setRestorePolicy(QState::DoNotRestoreProperties); - machine.addState(S1); - - QState *S2 = new QState(); - S2->setObjectName("S2"); - S2->assignProperty(object, "b", 5); - S2->setRestorePolicy(QState::DoNotRestoreProperties); - machine.addState(S2); - - QState *S3 = new QState(); - S3->setObjectName("S3"); - S3->setRestorePolicy(QState::DoNotRestoreProperties); - machine.addState(S3); - - QFinalState *S4 = new QFinalState(); - machine.addState(S4); - - S1->addTransition(new EventTransition(QEvent::User, S2)); - S2->addTransition(new EventTransition(QEvent::User, S3)); - S3->addTransition(S4); - - machine.setInitialState(S1); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(object->property("a").toInt(), 3); - QCOMPARE(object->property("b").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(object->property("a").toInt(), 3); - QCOMPARE(object->property("b").toInt(), 5); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(object->property("a").toInt(), 3); - QCOMPARE(object->property("b").toInt(), 5); -} - -void tst_QStateMachine::setGlobalRestorePolicyToGlobalRestore() -{ - s_countWarnings = false; - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::GlobalRestorePolicy); - - QCOMPARE(machine.globalRestorePolicy(), QStateMachine::DoNotRestoreProperties); - QCOMPARE(s_msgType, QtWarningMsg); - - s_msgType = QtDebugMsg; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - machine.setGlobalRestorePolicy(QStateMachine::GlobalRestorePolicy); - - QCOMPARE(machine.globalRestorePolicy(), QStateMachine::RestoreProperties); - QCOMPARE(s_msgType, QtWarningMsg); -} - - -void tst_QStateMachine::restorePolicyOnChildState() -{ - QStateMachine machine; - - QObject *propertyHolder = new QObject(); - propertyHolder->setProperty("a", 1); - propertyHolder->setProperty("b", 2); - - QState *parentState = new QState(machine.rootState()); - parentState->setObjectName("parentState"); - - QState *s1 = new QState(parentState); - s1->setRestorePolicy(QState::RestoreProperties); - s1->setObjectName("s1"); - s1->assignProperty(propertyHolder, "a", 3); - parentState->setInitialState(s1); - - QState *s2 = new QState(parentState); - s2->setRestorePolicy(QState::RestoreProperties); - s2->setObjectName("s2"); - s2->assignProperty(propertyHolder, "b", 4); - - QState *s3 = new QState(parentState); - s3->setRestorePolicy(QState::RestoreProperties); - s3->setObjectName("s3"); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - s2->addTransition(new EventTransition(QEvent::User, s3)); - - machine.setInitialState(parentState); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 1); - QCOMPARE(propertyHolder->property("b").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 1); - QCOMPARE(propertyHolder->property("b").toInt(), 2); -} -*/ - -void tst_QStateMachine::globalRestorePolicySetToRestore() -{ - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - - QObject *propertyHolder = new QObject(&machine); - propertyHolder->setProperty("a", 1); - propertyHolder->setProperty("b", 2); - - QState *s1 = new QState(machine.rootState()); - s1->assignProperty(propertyHolder, "a", 3); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(propertyHolder, "b", 4); - - QState *s3 = new QState(machine.rootState()); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - s2->addTransition(new EventTransition(QEvent::User, s3)); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 3); - QCOMPARE(propertyHolder->property("b").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 1); - QCOMPARE(propertyHolder->property("b").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("a").toInt(), 1); - QCOMPARE(propertyHolder->property("b").toInt(), 2); -} - -/* -void tst_QStateMachine::mixedRestoreProperties() -{ - QStateMachine machine; - - QObject *propertyHolder = new QObject(); - propertyHolder->setProperty("a", 1); - - QState *s1 = new QState(machine.rootState()); - s1->setRestorePolicy(QState::RestoreProperties); - s1->assignProperty(propertyHolder, "a", 3); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(propertyHolder, "a", 4); - - QState *s3 = new QState(machine.rootState()); - - QState *s4 = new QState(machine.rootState()); - s4->assignProperty(propertyHolder, "a", 5); - - QState *s5 = new QState(machine.rootState()); - s5->setRestorePolicy(QState::RestoreProperties); - s5->assignProperty(propertyHolder, "a", 6); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - s2->addTransition(new EventTransition(QEvent::User, s3)); - s3->addTransition(new EventTransition(QEvent::User, s4)); - s4->addTransition(new EventTransition(QEvent::User, s5)); - s5->addTransition(new EventTransition(QEvent::User, s3)); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - // Enter s1, save current - QCOMPARE(propertyHolder->property("a").toInt(), 3); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - // Enter s2, restorePolicy == DoNotRestore, so restore all properties - QCOMPARE(propertyHolder->property("a").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - // Enter s3 - QCOMPARE(propertyHolder->property("a").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - // Enter s4 - QCOMPARE(propertyHolder->property("a").toInt(), 5); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - // Enter s5, save current - QCOMPARE(propertyHolder->property("a").toInt(), 6); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - // Enter s3, restore - QCOMPARE(propertyHolder->property("a").toInt(), 5); -} -*/ - -void tst_QStateMachine::transitionWithParent() -{ - QStateMachine machine; - QState *s1 = new QState(machine.rootState()); - QState *s2 = new QState(machine.rootState()); - EventTransition *trans = new EventTransition(QEvent::User, s2, s1); - QCOMPARE(trans->sourceState(), s1); - QCOMPARE(trans->targetState(), (QAbstractState*)s2); - QCOMPARE(trans->targetStates().size(), 1); - QCOMPARE(trans->targetStates().at(0), (QAbstractState*)s2); -} - -void tst_QStateMachine::simpleAnimation() -{ - QStateMachine machine; - - QObject *object = new QObject(&machine); - object->setProperty("fooBar", 1.0); - - QState *s1 = new QState(machine.rootState()); - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "fooBar", 2.0); - - EventTransition *et = new EventTransition(QEvent::User, s2); - QPropertyAnimation *animation = new QPropertyAnimation(object, "fooBar", s2); - et->addAnimation(animation); - s1->addTransition(et); - - QState *s3 = new QState(machine.rootState()); - s2->addTransition(animation, SIGNAL(finished()), s3); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("fooBar").toDouble(), 2.0); -} - -class SlotCalledCounter: public QObject -{ - Q_OBJECT -public: - SlotCalledCounter() : counter(0) {} - - int counter; - -public slots: - void slot() { counter++; } -}; - -void tst_QStateMachine::twoAnimations() -{ - QStateMachine machine; - - QObject *object = new QObject(&machine); - object->setProperty("foo", 1.0); - object->setProperty("bar", 3.0); - - QState *s1 = new QState(machine.rootState()); - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - s2->assignProperty(object, "bar", 10.0); - - QPropertyAnimation *animationFoo = new QPropertyAnimation(object, "foo", s2); - QPropertyAnimation *animationBar = new QPropertyAnimation(object, "bar", s2); - animationBar->setDuration(900); - - SlotCalledCounter counter; - connect(animationFoo, SIGNAL(finished()), &counter, SLOT(slot())); - connect(animationBar, SIGNAL(finished()), &counter, SLOT(slot())); - - EventTransition *et = new EventTransition(QEvent::User, s2); - et->addAnimation(animationFoo); - et->addAnimation(animationBar); - s1->addTransition(et); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - s2->addTransition(s2, SIGNAL(polished()), s3); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 2.0); - QCOMPARE(object->property("bar").toDouble(), 10.0); - - QCOMPARE(counter.counter, 2); -} - -void tst_QStateMachine::twoAnimatedTransitions() -{ - QStateMachine machine; - - QObject *object = new QObject(&machine); - object->setProperty("foo", 1.0); - - QState *s1 = new QState(machine.rootState()); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 5.0); - QPropertyAnimation *fooAnimation = new QPropertyAnimation(object, "foo", s2); - s1->addTransition(new EventTransition(QEvent::User, s2))->addAnimation(fooAnimation); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - s2->addTransition(fooAnimation, SIGNAL(finished()), s3); - - QState *s4 = new QState(machine.rootState()); - s4->assignProperty(object, "foo", 2.0); - QPropertyAnimation *fooAnimation2 = new QPropertyAnimation(object, "foo", s4); - s3->addTransition(new EventTransition(QEvent::User, s4))->addAnimation(fooAnimation2); - - QState *s5 = new QState(machine.rootState()); - QObject::connect(s5, SIGNAL(entered()), QApplication::instance(), SLOT(quit())); - s4->addTransition(fooAnimation2, SIGNAL(finished()), s5); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 5.0); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s5)); - QCOMPARE(object->property("foo").toDouble(), 2.0); -} - -void tst_QStateMachine::playAnimationTwice() -{ - QStateMachine machine; - - QObject *object = new QObject(&machine); - object->setProperty("foo", 1.0); - - QState *s1 = new QState(machine.rootState()); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 5.0); - QPropertyAnimation *fooAnimation = new QPropertyAnimation(object, "foo", s2); - s1->addTransition(new EventTransition(QEvent::User, s2))->addAnimation(fooAnimation); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - s2->addTransition(fooAnimation, SIGNAL(finished()), s3); - - QState *s4 = new QState(machine.rootState()); - s4->assignProperty(object, "foo", 2.0); - s3->addTransition(new EventTransition(QEvent::User, s4))->addAnimation(fooAnimation); - - QState *s5 = new QState(machine.rootState()); - QObject::connect(s5, SIGNAL(entered()), QApplication::instance(), SLOT(quit())); - s4->addTransition(fooAnimation, SIGNAL(finished()), s5); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 5.0); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s5)); - QCOMPARE(object->property("foo").toDouble(), 2.0); -} - -void tst_QStateMachine::nestedTargetStateForAnimation() -{ - QStateMachine machine; - - QObject *object = new QObject(&machine); - object->setProperty("foo", 1.0); - object->setProperty("bar", 3.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - QState *s2 = new QState(machine.rootState()); - - s2->assignProperty(object, "foo", 2.0); - - QState *s2Child = new QState(s2); - s2Child->assignProperty(object, "bar", 10.0); - s2->setInitialState(s2Child); - - QState *s2Child2 = new QState(s2); - s2Child2->assignProperty(object, "bar", 11.0); - QAbstractTransition *at = s2Child->addTransition(new EventTransition(QEvent::User, s2Child2)); - - QPropertyAnimation *animation = new QPropertyAnimation(object, "bar", s2); - animation->setDuration(2000); - connect(animation, SIGNAL(finished()), &counter, SLOT(slot())); - at->addAnimation(animation); - - at = s1->addTransition(new EventTransition(QEvent::User, s2)); - - animation = new QPropertyAnimation(object, "foo", s2); - connect(animation, SIGNAL(finished()), &counter, SLOT(slot())); - at->addAnimation(animation); - - animation = new QPropertyAnimation(object, "bar", s2); - connect(animation, SIGNAL(finished()), &counter, SLOT(slot())); - at->addAnimation(animation); - - QState *s3 = new QState(machine.rootState()); - s2->addTransition(s2Child, SIGNAL(polished()), s3); - - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - machine.postEvent(new QEvent(QEvent::User)); - - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 2.0); - QCOMPARE(object->property("bar").toDouble(), 10.0); - QCOMPARE(counter.counter, 2); -} - -void tst_QStateMachine::animatedGlobalRestoreProperty() -{ - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - - QObject *object = new QObject(&machine); - object->setProperty("foo", 1.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - - QState *s4 = new QState(machine.rootState()); - QObject::connect(s4, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - QAbstractTransition *at = s1->addTransition(new EventTransition(QEvent::User, s2)); - QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", s2); - connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); - at->addAnimation(pa); - - at = s2->addTransition(pa, SIGNAL(finished()), s3); - pa = new QPropertyAnimation(object, "foo", s3); - connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); - at->addAnimation(pa); - - at = s3->addTransition(pa, SIGNAL(finished()), s4); - pa = new QPropertyAnimation(object, "foo", s4); - connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); - at->addAnimation(pa); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s4)); - QCOMPARE(object->property("foo").toDouble(), 1.0); - QCOMPARE(counter.counter, 2); -} - -void tst_QStateMachine::specificTargetValueOfAnimation() -{ - QStateMachine machine; - - QObject *object = new QObject(&machine); - object->setProperty("foo", 1.0); - - QState *s1 = new QState(machine.rootState()); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QPropertyAnimation *anim = new QPropertyAnimation(object, "foo"); - anim->setEndValue(10.0); - s1->addTransition(new EventTransition(QEvent::User, s2))->addAnimation(anim); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - s2->addTransition(anim, SIGNAL(finished()), s3); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 2.0); - QCOMPARE(anim->endValue().toDouble(), 10.0); -} - -void tst_QStateMachine::addDefaultAnimation() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("foo", 1.0); - - QState *s1 = new QState(machine.rootState()); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", &machine); - machine.addDefaultAnimation(pa); - s2->addTransition(pa, SIGNAL(finished()), s3); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 2.0); -} - -void tst_QStateMachine::addDefaultAnimationWithUnusedAnimation() -{ - QStateMachine machine; - - QObject *object = new QObject(&machine); - object->setProperty("foo", 1.0); - object->setProperty("bar", 2.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", &machine); - connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); - machine.addDefaultAnimation(pa); - s2->addTransition(pa, SIGNAL(finished()), s3); - - pa = new QPropertyAnimation(object, "bar", &machine); - connect(pa, SIGNAL(finished()), &counter, SLOT(slot())); - machine.addDefaultAnimation(pa); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 2.0); - QCOMPARE(counter.counter, 1); -} - -void tst_QStateMachine::removeDefaultAnimation() -{ - QStateMachine machine; - - QObject propertyHolder; - propertyHolder.setProperty("foo", 0); - - QCOMPARE(machine.defaultAnimations().size(), 0); - - QPropertyAnimation *anim = new QPropertyAnimation(&propertyHolder, "foo"); - - machine.addDefaultAnimation(anim); - - QCOMPARE(machine.defaultAnimations().size(), 1); - QVERIFY(machine.defaultAnimations().contains(anim)); - - machine.removeDefaultAnimation(anim); - - QCOMPARE(machine.defaultAnimations().size(), 0); - - machine.addDefaultAnimation(anim); - - QPropertyAnimation *anim2 = new QPropertyAnimation(&propertyHolder, "foo"); - machine.addDefaultAnimation(anim2); - - QCOMPARE(machine.defaultAnimations().size(), 2); - QVERIFY(machine.defaultAnimations().contains(anim)); - QVERIFY(machine.defaultAnimations().contains(anim2)); - - machine.removeDefaultAnimation(anim); - - QCOMPARE(machine.defaultAnimations().size(), 1); - QVERIFY(machine.defaultAnimations().contains(anim2)); - - machine.removeDefaultAnimation(anim2); - QCOMPARE(machine.defaultAnimations().size(), 0); -} - -void tst_QStateMachine::overrideDefaultAnimationWithSpecific() -{ - QStateMachine machine; - - QObject *object = new QObject(&machine); - object->setProperty("foo", 1.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - QAbstractTransition *at = s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); - connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); - s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); - connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - machine.addDefaultAnimation(defaultAnimation); - at->addAnimation(moreSpecificAnimation); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(counter.counter, 2); // specific animation started and stopped -} - -/* -void tst_QStateMachine::addDefaultAnimationForSource() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("foo", 1.0); - - QState *s1 = new QState(machine.rootState()); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", &machine); - machine.addDefaultAnimationForSourceState(s1, pa); - s2->addTransition(pa, SIGNAL(finished()), s3); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 2.0); -} - -void tst_QStateMachine::addDefaultAnimationForTarget() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("foo", 1.0); - - QState *s1 = new QState(machine.rootState()); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *pa = new QPropertyAnimation(object, "foo", &machine); - machine.addDefaultAnimationForTargetState(s2, pa); - s2->addTransition(pa, SIGNAL(finished()), s3); - - machine.setInitialState(s1); - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(object->property("foo").toDouble(), 2.0); -} - -void tst_QStateMachine::removeDefaultAnimationForSource() -{ - QStateMachine machine; - - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); - - QPropertyAnimation *anim = new QPropertyAnimation(this, "foo"); - - machine.addDefaultAnimationForSourceState(machine.rootState(), anim); - - QCOMPARE(machine.defaultAnimations().size(), 0); - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 1); - QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim)); - - machine.removeDefaultAnimationForTargetState(machine.rootState(), anim); - - QCOMPARE(machine.defaultAnimations().size(), 0); - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 1); - QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim)); - - machine.removeDefaultAnimationForSourceState(machine.rootState(), anim); - - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); - - machine.addDefaultAnimationForSourceState(machine.rootState(), anim); - - QPropertyAnimation *anim2 = new QPropertyAnimation(this, "foo"); - machine.addDefaultAnimationForSourceState(machine.rootState(), anim2); - - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 2); - QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim)); - QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim2)); - - machine.removeDefaultAnimationForSourceState(machine.rootState(), anim); - - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 1); - QVERIFY(machine.defaultAnimationsForSourceState(machine.rootState()).contains(anim2)); - - machine.removeDefaultAnimationForSourceState(machine.rootState(), anim2); - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); -} - -void tst_QStateMachine::removeDefaultAnimationForTarget() -{ - QStateMachine machine; - - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); - - QPropertyAnimation *anim = new QPropertyAnimation(this, "foo"); - - machine.addDefaultAnimationForTargetState(machine.rootState(), anim); - - QCOMPARE(machine.defaultAnimations().size(), 0); - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 1); - QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim)); - - machine.removeDefaultAnimationForSourceState(machine.rootState(), anim); - - QCOMPARE(machine.defaultAnimations().size(), 0); - QCOMPARE(machine.defaultAnimationsForSourceState(machine.rootState()).size(), 0); - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 1); - QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim)); - - machine.removeDefaultAnimationForTargetState(machine.rootState(), anim); - - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); - - machine.addDefaultAnimationForTargetState(machine.rootState(), anim); - - QPropertyAnimation *anim2 = new QPropertyAnimation(this, "foo"); - machine.addDefaultAnimationForTargetState(machine.rootState(), anim2); - - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 2); - QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim)); - QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim2)); - - machine.removeDefaultAnimationForTargetState(machine.rootState(), anim); - - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 1); - QVERIFY(machine.defaultAnimationsForTargetState(machine.rootState()).contains(anim2)); - - machine.removeDefaultAnimationForTargetState(machine.rootState(), anim2); - QCOMPARE(machine.defaultAnimationsForTargetState(machine.rootState()).size(), 0); -} - -void tst_QStateMachine::overrideDefaultAnimationWithSource() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("foo", 1.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); - connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); - s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); - connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - machine.addDefaultAnimation(defaultAnimation); - machine.addDefaultAnimationForSourceState(s1, moreSpecificAnimation); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(counter.counter, 2); // specific animation started and stopped -} - -void tst_QStateMachine::overrideDefaultAnimationWithTarget() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("foo", 1.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); - connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); - s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); - connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - machine.addDefaultAnimation(defaultAnimation); - machine.addDefaultAnimationForTargetState(s2, moreSpecificAnimation); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(counter.counter, 2); // specific animation started and stopped - -} - -void tst_QStateMachine::overrideDefaultSourceAnimationWithSpecific() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("foo", 1.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - QAbstractTransition *at = s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); - connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); - s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); - connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - machine.addDefaultAnimationForSourceState(s1, defaultAnimation); - at->addAnimation(moreSpecificAnimation); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(counter.counter, 2); // specific animation started and stopped -} - -void tst_QStateMachine::overrideDefaultTargetAnimationWithSpecific() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("foo", 1.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - QAbstractTransition *at = s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); - connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); - s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); - connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - machine.addDefaultAnimationForTargetState(s2, defaultAnimation); - at->addAnimation(moreSpecificAnimation); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(counter.counter, 2); // specific animation started and stopped -} - -void tst_QStateMachine::overrideDefaultTargetAnimationWithSource() -{ - QStateMachine machine; - - QObject *object = new QObject(); - object->setProperty("foo", 1.0); - - SlotCalledCounter counter; - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(object, "foo", 2.0); - - QState *s3 = new QState(machine.rootState()); - QObject::connect(s3, SIGNAL(entered()), QCoreApplication::instance(), SLOT(quit())); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - - QPropertyAnimation *defaultAnimation = new QPropertyAnimation(object, "foo"); - connect(defaultAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - QPropertyAnimation *moreSpecificAnimation = new QPropertyAnimation(object, "foo"); - s2->addTransition(moreSpecificAnimation, SIGNAL(finished()), s3); - connect(moreSpecificAnimation, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State)), &counter, SLOT(slot())); - - machine.addDefaultAnimationForTargetState(s2, defaultAnimation); - machine.addDefaultAnimationForSourceState(s1, moreSpecificAnimation); - - machine.start(); - QCoreApplication::processEvents(); - - machine.postEvent(new QEvent(QEvent::User)); - QCOREAPPLICATION_EXEC(5000); - - QVERIFY(machine.configuration().contains(s3)); - QCOMPARE(counter.counter, 2); // specific animation started and stopped -} - -*/ - -void tst_QStateMachine::parallelStateAssignmentsDone() -{ - QStateMachine machine; - - QObject *propertyHolder = new QObject(&machine); - propertyHolder->setProperty("foo", 123); - propertyHolder->setProperty("bar", 456); - propertyHolder->setProperty("zoot", 789); - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *parallelState = new QState(QState::ParallelStates, machine.rootState()); - parallelState->assignProperty(propertyHolder, "foo", 321); - - QState *s2 = new QState(parallelState); - s2->assignProperty(propertyHolder, "bar", 654); - - QState *s3 = new QState(parallelState); - s3->assignProperty(propertyHolder, "zoot", 987); - - s1->addTransition(new EventTransition(QEvent::User, parallelState)); - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("foo").toInt(), 123); - QCOMPARE(propertyHolder->property("bar").toInt(), 456); - QCOMPARE(propertyHolder->property("zoot").toInt(), 789); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(propertyHolder->property("foo").toInt(), 321); - QCOMPARE(propertyHolder->property("bar").toInt(), 654); - QCOMPARE(propertyHolder->property("zoot").toInt(), 987); -} - -void tst_QStateMachine::transitionsFromParallelStateWithNoChildren() -{ - QStateMachine machine; - - QState *parallelState = new QState(QState::ParallelStates, machine.rootState()); - machine.setInitialState(parallelState); - - QState *s1 = new QState(machine.rootState()); - parallelState->addTransition(new EventTransition(QEvent::User, s1)); - - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(1, machine.configuration().size()); - QVERIFY(machine.configuration().contains(parallelState)); - - machine.postEvent(new QEvent(QEvent::User)); - - QCoreApplication::processEvents(); - - QCOMPARE(1, machine.configuration().size()); - QVERIFY(machine.configuration().contains(s1)); -} - -void tst_QStateMachine::parallelStateTransition() -{ - QStateMachine machine; - - QState *parallelState = new QState(QState::ParallelStates, machine.rootState()); - machine.setInitialState(parallelState); - - QState *s1 = new QState(parallelState); - QState *s2 = new QState(parallelState); - - QState *s1InitialChild = new QState(s1); - s1->setInitialState(s1InitialChild); - - QState *s2InitialChild = new QState(s2); - s2->setInitialState(s2InitialChild); - - QState *s1OtherChild = new QState(s1); - - s1->addTransition(new EventTransition(QEvent::User, s1OtherChild)); - - machine.start(); - QCoreApplication::processEvents(); - - QVERIFY(machine.configuration().contains(parallelState)); - QVERIFY(machine.configuration().contains(s1)); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s1InitialChild)); - QVERIFY(machine.configuration().contains(s2InitialChild)); - QCOMPARE(machine.configuration().size(), 5); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QVERIFY(machine.configuration().contains(parallelState)); - - QVERIFY(machine.configuration().contains(s1)); - - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s1OtherChild)); - QVERIFY(machine.configuration().contains(s2InitialChild)); - QCOMPARE(machine.configuration().size(), 5); - -} - -void tst_QStateMachine::nestedRestoreProperties() -{ - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - - QObject *propertyHolder = new QObject(&machine); - propertyHolder->setProperty("foo", 1); - propertyHolder->setProperty("bar", 2); - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(propertyHolder, "foo", 3); - - QState *s21 = new QState(s2); - s21->assignProperty(propertyHolder, "bar", 4); - s2->setInitialState(s21); - - QState *s22 = new QState(s2); - s22->assignProperty(propertyHolder, "bar", 5); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - s21->addTransition(new EventTransition(QEvent::User, s22)); - - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - QCOMPARE(propertyHolder->property("foo").toInt(), 1); - QCOMPARE(propertyHolder->property("bar").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s21)); - QCOMPARE(propertyHolder->property("foo").toInt(), 3); - QCOMPARE(propertyHolder->property("bar").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s22)); - QCOMPARE(propertyHolder->property("foo").toInt(), 3); - QCOMPARE(propertyHolder->property("bar").toInt(), 5); -} - -void tst_QStateMachine::nestedRestoreProperties2() -{ - QStateMachine machine; - machine.setGlobalRestorePolicy(QStateMachine::RestoreProperties); - - QObject *propertyHolder = new QObject(&machine); - propertyHolder->setProperty("foo", 1); - propertyHolder->setProperty("bar", 2); - - QState *s1 = new QState(machine.rootState()); - machine.setInitialState(s1); - - QState *s2 = new QState(machine.rootState()); - s2->assignProperty(propertyHolder, "foo", 3); - - QState *s21 = new QState(s2); - s21->assignProperty(propertyHolder, "bar", 4); - s2->setInitialState(s21); - - QState *s22 = new QState(s2); - s22->assignProperty(propertyHolder, "foo", 6); - s22->assignProperty(propertyHolder, "bar", 5); - - s1->addTransition(new EventTransition(QEvent::User, s2)); - s21->addTransition(new EventTransition(QEvent::User, s22)); - s22->addTransition(new EventTransition(QEvent::User, s21)); - - machine.start(); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 1); - QVERIFY(machine.configuration().contains(s1)); - QCOMPARE(propertyHolder->property("foo").toInt(), 1); - QCOMPARE(propertyHolder->property("bar").toInt(), 2); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s21)); - QCOMPARE(propertyHolder->property("foo").toInt(), 3); - QCOMPARE(propertyHolder->property("bar").toInt(), 4); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s22)); - QCOMPARE(propertyHolder->property("foo").toInt(), 6); - QCOMPARE(propertyHolder->property("bar").toInt(), 5); - - machine.postEvent(new QEvent(QEvent::User)); - QCoreApplication::processEvents(); - - QCOMPARE(machine.configuration().size(), 2); - QVERIFY(machine.configuration().contains(s2)); - QVERIFY(machine.configuration().contains(s21)); - QCOMPARE(propertyHolder->property("foo").toInt(), 3); - QCOMPARE(propertyHolder->property("bar").toInt(), 4); - -} - - -QTEST_MAIN(tst_QStateMachine) -#include "tst_qstatemachine.moc" diff --git a/tests/benchmarks/benchmarks.pro b/tests/benchmarks/benchmarks.pro index 4c39373..8e2c243 100644 --- a/tests/benchmarks/benchmarks.pro +++ b/tests/benchmarks/benchmarks.pro @@ -1,7 +1,6 @@ TEMPLATE = subdirs SUBDIRS = containers-associative \ containers-sequential \ - qanimation \ qbytearray \ qpainter \ qtestlib-simple events \ diff --git a/tests/benchmarks/qanimation/dummyanimation.cpp b/tests/benchmarks/qanimation/dummyanimation.cpp deleted file mode 100644 index 6fb1d0a..0000000 --- a/tests/benchmarks/qanimation/dummyanimation.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "dummyanimation.h" -#include "dummyobject.h" - - -DummyAnimation::DummyAnimation(DummyObject *d) : m_dummy(d) -{ -} - -void DummyAnimation::updateCurrentValue(const QVariant &value) -{ - if (state() == Stopped) - return; - if (m_dummy) - m_dummy->setRect(value.toRect()); -} - -void DummyAnimation::updateState(State state) -{ - Q_UNUSED(state); -} diff --git a/tests/benchmarks/qanimation/dummyanimation.h b/tests/benchmarks/qanimation/dummyanimation.h deleted file mode 100644 index fe6592b..0000000 --- a/tests/benchmarks/qanimation/dummyanimation.h +++ /dev/null @@ -1,19 +0,0 @@ -#include - -#ifndef _DUMMYANIMATION_H__ - -class DummyObject; - -class DummyAnimation : public QVariantAnimation -{ -public: - DummyAnimation(DummyObject *d); - - void updateCurrentValue(const QVariant &value); - void updateState(State state); - -private: - DummyObject *m_dummy; -}; - -#endif \ No newline at end of file diff --git a/tests/benchmarks/qanimation/dummyobject.cpp b/tests/benchmarks/qanimation/dummyobject.cpp deleted file mode 100644 index bd76388..0000000 --- a/tests/benchmarks/qanimation/dummyobject.cpp +++ /dev/null @@ -1,25 +0,0 @@ -#include "dummyobject.h" - -DummyObject::DummyObject() -{ -} - -QRect DummyObject::rect() const -{ - return m_rect; -} - -void DummyObject::setRect(const QRect &r) -{ - m_rect = r; -} - -float DummyObject::opacity() const -{ - return m_opacity; -} - -void DummyObject::setOpacity(float o) -{ - m_opacity = o; -} diff --git a/tests/benchmarks/qanimation/dummyobject.h b/tests/benchmarks/qanimation/dummyobject.h deleted file mode 100644 index c989662..0000000 --- a/tests/benchmarks/qanimation/dummyobject.h +++ /dev/null @@ -1,23 +0,0 @@ -#include - -#ifndef _DUMMYOBJECT_H__ - -class DummyObject : public QObject -{ - Q_OBJECT - Q_PROPERTY(QRect rect READ rect WRITE setRect) - Q_PROPERTY(float opacity READ opacity WRITE setOpacity) -public: - DummyObject(); - QRect rect() const; - void setRect(const QRect &r); - float opacity() const; - void setOpacity(float); - -private: - QRect m_rect; - float m_opacity; -}; - - -#endif \ No newline at end of file diff --git a/tests/benchmarks/qanimation/main.cpp b/tests/benchmarks/qanimation/main.cpp deleted file mode 100644 index 7bb770f..0000000 --- a/tests/benchmarks/qanimation/main.cpp +++ /dev/null @@ -1,150 +0,0 @@ -#include -#include - -#include "dummyobject.h" -#include "dummyanimation.h" -#include "rectanimation.h" - -#define ITERATION_COUNT 10e3 - -class tst_qanimation : public QObject -{ - Q_OBJECT -private slots: - void itemPropertyAnimation(); - void itemPropertyAnimation_data() { data();} - void dummyAnimation(); - void dummyAnimation_data() { data();} - void dummyPropertyAnimation(); - void dummyPropertyAnimation_data() { data();} - void rectAnimation(); - void rectAnimation_data() { data();} - - void floatAnimation_data() { data(); } - void floatAnimation(); - -private: - void data(); -}; - - -void tst_qanimation::data() -{ - QTest::addColumn("started"); - QTest::newRow("NotRunning") << false; - QTest::newRow("Running") << true; -} - -void tst_qanimation::itemPropertyAnimation() -{ - QFETCH(bool, started); - QGraphicsWidget item; - - //then the property animation - { - QPropertyAnimation anim(&item, "pos"); - anim.setDuration(ITERATION_COUNT); - anim.setStartValue(QPointF(0,0)); - anim.setEndValue(QPointF(ITERATION_COUNT,ITERATION_COUNT)); - if (started) - anim.start(); - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - anim.setCurrentTime(i); - } - } - } - -} - -void tst_qanimation::dummyAnimation() -{ - QFETCH(bool, started); - DummyObject dummy; - - //first the dummy animation - { - DummyAnimation anim(&dummy); - anim.setDuration(ITERATION_COUNT); - anim.setStartValue(QRect(0, 0, 0, 0)); - anim.setEndValue(QRect(0, 0, ITERATION_COUNT,ITERATION_COUNT)); - if (started) - anim.start(); - QBENCHMARK { - for(int i = 0; i < anim.duration(); ++i) { - anim.setCurrentTime(i); - } - } - } -} - -void tst_qanimation::dummyPropertyAnimation() -{ - QFETCH(bool, started); - DummyObject dummy; - - //then the property animation - { - QPropertyAnimation anim(&dummy, "rect"); - anim.setDuration(ITERATION_COUNT); - anim.setStartValue(QRect(0, 0, 0, 0)); - anim.setEndValue(QRect(0, 0, ITERATION_COUNT,ITERATION_COUNT)); - if (started) - anim.start(); - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - anim.setCurrentTime(i); - } - } - } -} - -void tst_qanimation::rectAnimation() -{ - //this is the simplest animation you can do - QFETCH(bool, started); - DummyObject dummy; - - //then the property animation - { - RectAnimation anim(&dummy); - anim.setDuration(ITERATION_COUNT); - anim.setStartValue(QRect(0, 0, 0, 0)); - anim.setEndValue(QRect(0, 0, ITERATION_COUNT,ITERATION_COUNT)); - if (started) - anim.start(); - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - anim.setCurrentTime(i); - } - } - } -} - -void tst_qanimation::floatAnimation() -{ - //this is the simplest animation you can do - QFETCH(bool, started); - DummyObject dummy; - - //then the property animation - { - QPropertyAnimation anim(&dummy, "opacity"); - anim.setDuration(ITERATION_COUNT); - anim.setStartValue(0.f); - anim.setEndValue(1.f); - if (started) - anim.start(); - QBENCHMARK { - for(int i = 0; i < ITERATION_COUNT; ++i) { - anim.setCurrentTime(i); - } - } - } -} - - - -QTEST_MAIN(tst_qanimation) - -#include "main.moc" diff --git a/tests/benchmarks/qanimation/qanimation.pro b/tests/benchmarks/qanimation/qanimation.pro deleted file mode 100644 index 55cd75e..0000000 --- a/tests/benchmarks/qanimation/qanimation.pro +++ /dev/null @@ -1,18 +0,0 @@ -load(qttest_p4) -TEMPLATE = app -TARGET = tst_qanimation -DEPENDPATH += . -INCLUDEPATH += . - -CONFIG += release -#CONFIG += debug - - -SOURCES += main.cpp \ - dummyobject.cpp \ - dummyanimation.cpp \ - rectanimation.cpp - -HEADERS += dummyobject.h \ - dummyanimation.h \ - rectanimation.h diff --git a/tests/benchmarks/qanimation/rectanimation.cpp b/tests/benchmarks/qanimation/rectanimation.cpp deleted file mode 100644 index d60a943..0000000 --- a/tests/benchmarks/qanimation/rectanimation.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "rectanimation.h" -#include "dummyobject.h" - -static inline int interpolateInteger(int from, int to, qreal progress) -{ - return from + (to - from) * progress; -} - - -RectAnimation::RectAnimation(DummyObject *obj) : m_object(obj), m_dura(250) -{ -} - -void RectAnimation::setEndValue(const QRect &rect) -{ - m_end = rect; -} - -void RectAnimation::setStartValue(const QRect &rect) -{ - m_start = rect; -} - -void RectAnimation::setDuration(int d) -{ - m_dura = d; -} - -int RectAnimation::duration() const -{ - return m_dura; -} - - -void RectAnimation::updateCurrentTime(int msecs) -{ - qreal progress = m_easing.valueForProgress( qreal(msecs) / qreal(m_dura) ); - QRect now; - now.setCoords(interpolateInteger(m_start.left(), m_end.left(), progress), - interpolateInteger(m_start.top(), m_end.top(), progress), - interpolateInteger(m_start.right(), m_end.right(), progress), - interpolateInteger(m_start.bottom(), m_end.bottom(), progress)); - - bool changed = (now != m_current); - if (changed) - m_current = now; - - if (state() == Stopped) - return; - - if (m_object) - m_object->setRect(m_current); -} - -void RectAnimation::updateState(QAbstractAnimation::State state) -{ - Q_UNUSED(state); -} diff --git a/tests/benchmarks/qanimation/rectanimation.h b/tests/benchmarks/qanimation/rectanimation.h deleted file mode 100644 index 99b82b4..0000000 --- a/tests/benchmarks/qanimation/rectanimation.h +++ /dev/null @@ -1,30 +0,0 @@ -#include - -#ifndef _RECTANIMATION_H__ - -class DummyObject; - -//this class is even simpler than the dummy -//and uses no QVariant at all -class RectAnimation : public QAbstractAnimation -{ -public: - RectAnimation(DummyObject *obj); - - void setEndValue(const QRect &rect); - void setStartValue(const QRect &rect); - - void setDuration(int d); - int duration() const; - - virtual void updateCurrentTime(int msecs); - virtual void updateState(QAbstractAnimation::State state); - -private: - DummyObject *m_object; - QEasingCurve m_easing; - QRect m_start, m_end, m_current; - int m_dura; -}; - -#endif diff --git a/tests/benchmarks/qvariant/qvariant.pro b/tests/benchmarks/qvariant/qvariant.pro index 63b5442..68b4a97 100644 --- a/tests/benchmarks/qvariant/qvariant.pro +++ b/tests/benchmarks/qvariant/qvariant.pro @@ -3,6 +3,7 @@ TEMPLATE = app TARGET = tst_qvariant DEPENDPATH += . INCLUDEPATH += . +QT -= gui CONFIG += release #CONFIG += debug diff --git a/tests/benchmarks/qvariant/tst_qvariant.cpp b/tests/benchmarks/qvariant/tst_qvariant.cpp index 0eb1ae2..4a7ad02 100644 --- a/tests/benchmarks/qvariant/tst_qvariant.cpp +++ b/tests/benchmarks/qvariant/tst_qvariant.cpp @@ -38,9 +38,7 @@ ** $QT_END_LICENSE$ ** ****************************************************************************/ - #include -#include #include #define ITERATION_COUNT 1e5 @@ -49,73 +47,64 @@ class tst_qvariant : public QObject { Q_OBJECT private slots: - void testBound(); - void doubleVariantCreation(); void floatVariantCreation(); void rectVariantCreation(); void stringVariantCreation(); - void pixmapVariantCreation(); - void doubleVariantSetValue(); void floatVariantSetValue(); void rectVariantSetValue(); void stringVariantSetValue(); - void doubleVariantAssignment(); void floatVariantAssignment(); void rectVariantAssignment(); void stringVariantAssignment(); }; -void tst_qvariant::testBound() + +void tst_qvariant::doubleVariantCreation() { - qreal d = qreal(.5); + double d = 0; QBENCHMARK { for(int i = 0; i < ITERATION_COUNT; ++i) { - d = qBound(0, d, 1); + QVariant v(d); } } } -template -static void variantCreation(T val) +void tst_qvariant::floatVariantCreation() { + float f = 0; QBENCHMARK { for(int i = 0; i < ITERATION_COUNT; ++i) { - QVariant v(val); + QVariant v(f); } } } -void tst_qvariant::doubleVariantCreation() -{ - variantCreation(0.0); -} - -void tst_qvariant::floatVariantCreation() -{ - variantCreation(0.0f); -} - void tst_qvariant::rectVariantCreation() { - variantCreation(QRect(1, 2, 3, 4)); + QRect r(1,2,3,4); + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + QVariant v(r); + } + } } void tst_qvariant::stringVariantCreation() { - variantCreation(QString()); -} - -void tst_qvariant::pixmapVariantCreation() -{ - variantCreation(QPixmap()); + QString s; + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + QVariant v(s); + } + } } -template -static void variantSetValue(T d) +void tst_qvariant::doubleVariantSetValue() { + double d = 0; QVariant v; QBENCHMARK { for(int i = 0; i < ITERATION_COUNT; ++i) { @@ -124,55 +113,81 @@ static void variantSetValue(T d) } } -void tst_qvariant::doubleVariantSetValue() -{ - variantSetValue(0.0); -} - void tst_qvariant::floatVariantSetValue() { - variantSetValue(0.0f); + float f = 0; + QVariant v; + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + qVariantSetValue(v, f); + } + } } void tst_qvariant::rectVariantSetValue() { - variantSetValue(QRect()); + QRect r; + QVariant v; + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + qVariantSetValue(v, r); + } + } } void tst_qvariant::stringVariantSetValue() { - variantSetValue(QString()); -} - -template -static void variantAssignment(T d) -{ + QString s; QVariant v; QBENCHMARK { for(int i = 0; i < ITERATION_COUNT; ++i) { - v = d; + qVariantSetValue(v, s); } } } void tst_qvariant::doubleVariantAssignment() { - variantAssignment(0.0); + double d = 0; + QVariant v; + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + v = d; + } + } } void tst_qvariant::floatVariantAssignment() { - variantAssignment(0.0f); + float f = 0; + QVariant v; + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + v = f; + } + } } void tst_qvariant::rectVariantAssignment() { - variantAssignment(QRect()); + QRect r; + QVariant v; + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + v = r; + } + } } void tst_qvariant::stringVariantAssignment() { - variantAssignment(QString()); + QString s; + QVariant v; + QBENCHMARK { + for(int i = 0; i < ITERATION_COUNT; ++i) { + v = s; + } + } } QTEST_MAIN(tst_qvariant) -- cgit v0.12 From a97862318a6b3f72a05a3e66ebcf5f0e455bb42a Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Fri, 11 Apr 2008 13:12:02 +0200 Subject: Don't use memcmp it's terribly slow. Added qMemEquals method that returns true if the two memory regions contain the same content. Reviewed-By: Thiago Macieira --- src/corelib/tools/qstring.cpp | 152 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 146 insertions(+), 6 deletions(-) diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp index c3649e3..81b55b7 100644 --- a/src/corelib/tools/qstring.cpp +++ b/src/corelib/tools/qstring.cpp @@ -195,6 +195,142 @@ static int ucstrnicmp(const ushort *a, const ushort *b, int l) return ucstricmp(a, a + l, b, b + l); } +#if 0 +static bool qMemEquals(const quint8 *a, const quint8 *b, int bytes) +{ + if (a == b) + return true; + + // check alignement + qptrdiff align = ((quintptr)a - (quintptr)b); +// if (sizeof(void *) == 8 && !(align & 7)) { +// } else + if (!(align & 3)) { + quintptr pa = (quintptr)a; + if (pa & 3) { + if (pa & 1) { + if (*a != *b) + return false; + ++a; + ++b; + --bytes; + } + if (pa & 2) { + if (*reinterpret_cast(a) != *reinterpret_cast(b)) + return false; + a += 2; + b += 2; + bytes -= 2; + } + } + int tail = (bytes & 3); + const quint32 *sa = reinterpret_cast(a); + const quint32 *sb = reinterpret_cast(b); + const quint32 *e = sa + (bytes >> 2); + while (sa < e) { + if (*sa != *sb) + return false; + ++sa; + ++sb; + } + a = reinterpret_cast(sa); + b = reinterpret_cast(sb); + if (tail) { + if (tail & 2) { + if (*reinterpret_cast(a) != *reinterpret_cast(b)) + return false; + sa += 2; + sb += 2; + } + if (tail & 1) { + if (*a != *b) + return false; + } + } + } else if (!(align & 1)) { + quintptr pa = (quintptr)a; + if (pa & 1) { + if (*a != *b) + return false; + ++a; + ++b; + --bytes; + } + bool tail = (bytes & 1); + const quint16 *sa = reinterpret_cast(a); + const quint16 *sb = reinterpret_cast(b); + const quint16 *e = sa + (bytes >> 1); + while (sa < e) { + if (*sa != *sb) + return false; + ++sa; + ++sb; + } + a = reinterpret_cast(sa); + b = reinterpret_cast(sb); + if (tail) { + if (*a != *b) + return false; + } + } else { + const quint8 *e = a + bytes; + while (a < e) { + if (*a != *b) + return false; + ++a; + ++b; + } + } + return true; +} +#endif + +static bool qMemEquals(const quint16 *a, const quint16 *b, int length) +{ + if (a == b) + return true; + + // check alignement + qptrdiff align = ((quintptr)a - (quintptr)b); + Q_ASSERT(!(align & 1)); +// if (sizeof(void *) == 8 && !(align & 7)) { +// } else + if (!(align & 3)) { + quintptr pa = (quintptr)a; + if (pa & 2) { + if (*a != *b) + return false; + ++a; + ++b; + --length; + } + int tail = (length & 1); + const quint32 *sa = reinterpret_cast(a); + const quint32 *sb = reinterpret_cast(b); + const quint32 *e = sa + (length >> 1); + while (sa < e) { + if (*sa != *sb) + return false; + ++sa; + ++sb; + } + a = reinterpret_cast(sa); + b = reinterpret_cast(sb); + if (tail) { + if (*a != *b) + return false; + } + } else if (!(align & 1)) { + const quint16 *e = a + length; + while (a < e) { + if (*a != *b) + return false; + ++a; + ++b; + } + } + return true; +} /*! \internal @@ -1908,8 +2044,10 @@ QString &QString::replace(QChar c, const QLatin1String &after, Qt::CaseSensitivi */ bool QString::operator==(const QString &other) const { - return (size() == other.size()) && - (memcmp((char*)unicode(),(char*)other.unicode(), size()*sizeof(QChar))==0); + if (d->size != other.d->size) + return false; + + return qMemEquals(d->data, other.d->data, d->size); } /*! @@ -3136,7 +3274,7 @@ bool QString::startsWith(const QString& s, Qt::CaseSensitivity cs) const if (s.d->size > d->size) return false; if (cs == Qt::CaseSensitive) { - return memcmp((char*)d->data, (char*)s.d->data, s.d->size*sizeof(QChar)) == 0; + return qMemEquals(d->data, s.d->data, s.d->size); } else { uint last = 0; uint olast = 0; @@ -3207,7 +3345,7 @@ bool QString::endsWith(const QString& s, Qt::CaseSensitivity cs) const if (pos < 0) return false; if (cs == Qt::CaseSensitive) { - return memcmp((char*)&d->data[pos], (char*)s.d->data, s.d->size*sizeof(QChar)) == 0; + return qMemEquals(d->data + pos, s.d->data, s.d->size); } else { uint last = 0; uint olast = 0; @@ -7692,7 +7830,8 @@ QString QStringRef::toString() const { */ bool operator==(const QStringRef &s1,const QStringRef &s2) { return (s1.size() == s2.size() && - (memcmp((char*)s1.unicode(), (char*)s2.unicode(), s1.size()*sizeof(QChar))==0)); } + qMemEquals((const ushort *)s1.unicode(), (const ushort *)s2.unicode(), s1.size())); +} /*! \relates QStringRef @@ -7701,7 +7840,8 @@ bool operator==(const QStringRef &s1,const QStringRef &s2) */ bool operator==(const QString &s1,const QStringRef &s2) { return (s1.size() == s2.size() && - (memcmp((char*)s1.unicode(), (char*)s2.unicode(), s1.size()*sizeof(QChar))==0)); } + qMemEquals((const ushort *)s1.unicode(), (const ushort *)s2.unicode(), s1.size())); +} /*! \relates QStringRef -- cgit v0.12 From 7c848d093e2ce12528d8af435a6e10bc0e28f1e3 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Mon, 18 May 2009 23:24:03 +0200 Subject: Add a benchmark for QString::operator== Reviewed-By: Bradley T. Hughes --- tests/benchmarks/qstring/main.cpp | 104 +++++++++++++++++++++++++++++++++++ tests/benchmarks/qstring/qstring.pro | 4 ++ 2 files changed, 108 insertions(+) create mode 100644 tests/benchmarks/qstring/main.cpp create mode 100644 tests/benchmarks/qstring/qstring.pro diff --git a/tests/benchmarks/qstring/main.cpp b/tests/benchmarks/qstring/main.cpp new file mode 100644 index 0000000..c7962bd --- /dev/null +++ b/tests/benchmarks/qstring/main.cpp @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ +#include +#include + +class tst_QString: public QObject +{ + Q_OBJECT +private slots: + void equals() const; + void equals_data() const; +}; + +void tst_QString::equals() const +{ + QFETCH(QString, a); + QFETCH(QString, b); + + QBENCHMARK { + a == b; + } +} + +void tst_QString::equals_data() const +{ + static const struct { + ushort data[80]; + int dummy; // just to ensure 4-byte alignment + } data = { + { + 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, // 16 + 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, // 32 + 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, // 48 + 64, 64, 64, 64, 64, 64, 64, 64, + 64, 64, 64, 64, 64, 64, 64, 64, // 64 + 64, 64, 64, 64, 64, 64, 64, 64, + 96, 96, 96, 96, 96, 96, 96, 96 // 80 + }, 0 + }; + const QChar *ptr = reinterpret_cast(data.data); + + QTest::addColumn("a"); + QTest::addColumn("b"); + QString base = QString::fromRawData(ptr, 64); + + QTest::newRow("different-length") << base << QString::fromRawData(ptr, 4); + QTest::newRow("same-string") << base << base; + QTest::newRow("same-data") << base << QString::fromRawData(ptr, 64); + + // don't use length > 64, since that crosses a cache line + QTest::newRow("aligned-odd") + << QString::fromRawData(ptr, 63) << QString::fromRawData(ptr + 2, 63); + QTest::newRow("aligned-even") + << QString::fromRawData(ptr, 64) << QString::fromRawData(ptr + 2, 64); + QTest::newRow("unaligned-even") + << QString::fromRawData(ptr, 63) << QString::fromRawData(ptr + 1, 63); + QTest::newRow("unaligned-odd") + << QString::fromRawData(ptr, 64) << QString::fromRawData(ptr + 1, 64); +} + +QTEST_MAIN(tst_QString) + +#include "main.moc" diff --git a/tests/benchmarks/qstring/qstring.pro b/tests/benchmarks/qstring/qstring.pro new file mode 100644 index 0000000..74423e7 --- /dev/null +++ b/tests/benchmarks/qstring/qstring.pro @@ -0,0 +1,4 @@ +load(qttest_p4) +TARGET = tst_qstring +QT -= gui +SOURCES += main.cpp -- cgit v0.12 From 2387c77787ec279981d58c46cfb5bde3e1530790 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Mon, 18 May 2009 23:24:26 +0200 Subject: Optimise QString comparison based on the results from the benchmark Reviewed-By: Bradley T. Hughes --- src/corelib/tools/qstring.cpp | 163 ++++++++++-------------------------------- 1 file changed, 38 insertions(+), 125 deletions(-) diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp index 81b55b7..456fdfd 100644 --- a/src/corelib/tools/qstring.cpp +++ b/src/corelib/tools/qstring.cpp @@ -195,139 +195,52 @@ static int ucstrnicmp(const ushort *a, const ushort *b, int l) return ucstricmp(a, a + l, b, b + l); } -#if 0 -static bool qMemEquals(const quint8 *a, const quint8 *b, int bytes) +static bool qMemEquals(const quint16 *a, const quint16 *b, int length) { + // Benchmarking indicates that doing memcmp is much slower than + // executing the comparison ourselves. + // To make it even faster, we do a 32-bit comparison, comparing + // twice the amount of data as a normal word-by-word comparison. + // + // Benchmarking results on a 2.33 GHz Core2 Duo, with a 64-QChar + // block of data, with 4194304 iterations (per iteration): + // operation usec cpu ticks + // memcmp 330 710 + // 16-bit 135 285-290 + // 32-bit aligned 69.7 135-145 + // + // Testing also indicates that unaligned 32-bit loads are as + // performant as 32-bit aligned. if (a == b) return true; - // check alignement - qptrdiff align = ((quintptr)a - (quintptr)b); -// if (sizeof(void *) == 8 && !(align & 7)) { -// } else - if (!(align & 3)) { - quintptr pa = (quintptr)a; - if (pa & 3) { - if (pa & 1) { - if (*a != *b) - return false; - ++a; - ++b; - --bytes; - } - if (pa & 2) { - if (*reinterpret_cast(a) != *reinterpret_cast(b)) - return false; - a += 2; - b += 2; - bytes -= 2; - } - } - int tail = (bytes & 3); - const quint32 *sa = reinterpret_cast(a); - const quint32 *sb = reinterpret_cast(b); - const quint32 *e = sa + (bytes >> 2); - while (sa < e) { - if (*sa != *sb) - return false; - ++sa; - ++sb; - } - a = reinterpret_cast(sa); - b = reinterpret_cast(sb); - if (tail) { - if (tail & 2) { - if (*reinterpret_cast(a) != *reinterpret_cast(b)) - return false; - sa += 2; - sb += 2; - } - if (tail & 1) { - if (*a != *b) - return false; - } - } - } else if (!(align & 1)) { - quintptr pa = (quintptr)a; - if (pa & 1) { - if (*a != *b) - return false; - ++a; - ++b; - --bytes; - } - bool tail = (bytes & 1); - const quint16 *sa = reinterpret_cast(a); - const quint16 *sb = reinterpret_cast(b); - const quint16 *e = sa + (bytes >> 1); - while (sa < e) { - if (*sa != *sb) - return false; - ++sa; - ++sb; - } - a = reinterpret_cast(sa); - b = reinterpret_cast(sb); - if (tail) { - if (*a != *b) - return false; - } - } else { - const quint8 *e = a + bytes; - while (a < e) { - if (*a != *b) + register union { + const quint16 *w; + const quint32 *d; + quintptr value; + } sa, sb; + sa.w = a; + sb.w = b; + + // check alignment + bool unaligned = (sa.value | sb.value) & 2; +#if defined(__i386__) || defined(__x86_64__) || defined(_M_X64_) + unaligned = false; +#endif + if (!unaligned) { + // both addresses are 4-bytes aligned (or this is an x86) + // do a fast 32-bit comparison + for (register int halfLength = length / 2; halfLength; --halfLength, ++sa.d, ++sb.d) { + if (*sa.d != *sb.d) return false; - ++a; - ++b; } + return length & 1 ? (*sa.w == *sb.w) : true; } - return true; -} -#endif -static bool qMemEquals(const quint16 *a, const quint16 *b, int length) -{ - if (a == b) - return true; - - // check alignement - qptrdiff align = ((quintptr)a - (quintptr)b); - Q_ASSERT(!(align & 1)); -// if (sizeof(void *) == 8 && !(align & 7)) { -// } else - if (!(align & 3)) { - quintptr pa = (quintptr)a; - if (pa & 2) { - if (*a != *b) - return false; - ++a; - ++b; - --length; - } - int tail = (length & 1); - const quint32 *sa = reinterpret_cast(a); - const quint32 *sb = reinterpret_cast(b); - const quint32 *e = sa + (length >> 1); - while (sa < e) { - if (*sa != *sb) - return false; - ++sa; - ++sb; - } - a = reinterpret_cast(sa); - b = reinterpret_cast(sb); - if (tail) { - if (*a != *b) - return false; - } - } else if (!(align & 1)) { - const quint16 *e = a + length; - while (a < e) { - if (*a != *b) - return false; - ++a; - ++b; - } + // one or both of the addresses isn't 2-byte aligned + for ( ; length; --length, ++sa.w, ++sb.w) { + if (*sa.w != *sb.w) + return false; } return true; } -- cgit v0.12 From 1ff30b2b88af31cf18d2a1e6961c3ed7bd9b0240 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Tue, 19 May 2009 14:38:49 +0200 Subject: Reintroduce the unaligned-unaligned 32-bit code that I had removed out of ignorance. If both pointers are out of 4-byte alignment, doing the first load will align them so we can do 32-bit comparisons. Lars's code had this before, but I misunderstood it and removed, thinking it was doing misaligned accesses. I experimented with moving the tail comparison above the 32-bit comparison to save a register, but it made things worse. Reviewed-By: Bradley T. Hughes --- src/corelib/tools/qstring.cpp | 45 +++++++++++++++++++++++++-------------- tests/benchmarks/qstring/main.cpp | 41 +++++++++++++++++++++++++---------- 2 files changed, 59 insertions(+), 27 deletions(-) diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp index 456fdfd..29509c5 100644 --- a/src/corelib/tools/qstring.cpp +++ b/src/corelib/tools/qstring.cpp @@ -206,12 +206,12 @@ static bool qMemEquals(const quint16 *a, const quint16 *b, int length) // block of data, with 4194304 iterations (per iteration): // operation usec cpu ticks // memcmp 330 710 - // 16-bit 135 285-290 - // 32-bit aligned 69.7 135-145 + // 16-bit 79 167-171 + // 32-bit aligned 49 105-109 // // Testing also indicates that unaligned 32-bit loads are as // performant as 32-bit aligned. - if (a == b) + if (a == b || !length) return true; register union { @@ -223,24 +223,37 @@ static bool qMemEquals(const quint16 *a, const quint16 *b, int length) sb.w = b; // check alignment - bool unaligned = (sa.value | sb.value) & 2; -#if defined(__i386__) || defined(__x86_64__) || defined(_M_X64_) - unaligned = false; -#endif - if (!unaligned) { - // both addresses are 4-bytes aligned (or this is an x86) + if ((sa.value & 2) == (sb.value & 2)) { + // both addresses have the same alignment + if (sa.value & 2) { + // both addresses are not aligned to 4-bytes boundaries + // compare the first character + if (*sa.w != *sb.w) + return false; + --length; + ++sa.w; + ++sb.w; + + // now both addresses are 4-bytes aligned + } + + // both addresses are 4-bytes aligned // do a fast 32-bit comparison - for (register int halfLength = length / 2; halfLength; --halfLength, ++sa.d, ++sb.d) { + register const quint32 *e = sa.d + (length >> 1); + for ( ; sa.d != e; ++sa.d, ++sb.d) { if (*sa.d != *sb.d) return false; } - return length & 1 ? (*sa.w == *sb.w) : true; - } - // one or both of the addresses isn't 2-byte aligned - for ( ; length; --length, ++sa.w, ++sb.w) { - if (*sa.w != *sb.w) - return false; + // do we have a tail? + return (length & 1) ? *sa.w == *sb.w : true; + } else { + // one of the addresses isn't 4-byte aligned but the other is + register const quint16 *e = sa.w + length; + for ( ; sa.w != e; ++sa.w, ++sb.w) { + if (*sa.w != *sb.w) + return false; + } } return true; } diff --git a/tests/benchmarks/qstring/main.cpp b/tests/benchmarks/qstring/main.cpp index c7962bd..cbbf0a1 100644 --- a/tests/benchmarks/qstring/main.cpp +++ b/tests/benchmarks/qstring/main.cpp @@ -74,8 +74,8 @@ void tst_QString::equals_data() const 64, 64, 64, 64, 64, 64, 64, 64, // 48 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, // 64 - 64, 64, 64, 64, 64, 64, 64, 64, - 96, 96, 96, 96, 96, 96, 96, 96 // 80 + 64, 64, 64, 64, 96, 96, 96, 96, + 64, 64, 96, 96, 96, 96, 96, 96 // 80 }, 0 }; const QChar *ptr = reinterpret_cast(data.data); @@ -88,15 +88,34 @@ void tst_QString::equals_data() const QTest::newRow("same-string") << base << base; QTest::newRow("same-data") << base << QString::fromRawData(ptr, 64); - // don't use length > 64, since that crosses a cache line - QTest::newRow("aligned-odd") - << QString::fromRawData(ptr, 63) << QString::fromRawData(ptr + 2, 63); - QTest::newRow("aligned-even") - << QString::fromRawData(ptr, 64) << QString::fromRawData(ptr + 2, 64); - QTest::newRow("unaligned-even") - << QString::fromRawData(ptr, 63) << QString::fromRawData(ptr + 1, 63); - QTest::newRow("unaligned-odd") - << QString::fromRawData(ptr, 64) << QString::fromRawData(ptr + 1, 64); + // try to avoid crossing a cache line (that is, at ptr[64]) + QTest::newRow("aligned-aligned-4n") + << QString::fromRawData(ptr, 60) << QString::fromRawData(ptr + 2, 60); + QTest::newRow("aligned-unaligned-4n") + << QString::fromRawData(ptr, 60) << QString::fromRawData(ptr + 1, 60); + QTest::newRow("unaligned-unaligned-4n") + << QString::fromRawData(ptr + 1, 60) << QString::fromRawData(ptr + 3, 60); + + QTest::newRow("aligned-aligned-4n+1") + << QString::fromRawData(ptr, 61) << QString::fromRawData(ptr + 2, 61); + QTest::newRow("aligned-unaligned-4n+1") + << QString::fromRawData(ptr, 61) << QString::fromRawData(ptr + 1, 61); + QTest::newRow("unaligned-unaligned-4n+1") + << QString::fromRawData(ptr + 1, 61) << QString::fromRawData(ptr + 3, 61); + + QTest::newRow("aligned-aligned-4n-1") + << QString::fromRawData(ptr, 59) << QString::fromRawData(ptr + 2, 59); + QTest::newRow("aligned-unaligned-4n-1") + << QString::fromRawData(ptr, 59) << QString::fromRawData(ptr + 1, 59); + QTest::newRow("unaligned-unaligned-4n-1") + << QString::fromRawData(ptr + 1, 59) << QString::fromRawData(ptr + 3, 59); + + QTest::newRow("aligned-aligned-2n") + << QString::fromRawData(ptr, 58) << QString::fromRawData(ptr + 2, 58); + QTest::newRow("aligned-unaligned-2n") + << QString::fromRawData(ptr, 58) << QString::fromRawData(ptr + 1, 58); + QTest::newRow("unaligned-unaligned-2n") + << QString::fromRawData(ptr + 1, 58) << QString::fromRawData(ptr + 3, 58); } QTEST_MAIN(tst_QString) -- cgit v0.12 From 759b7ee720fa365f93fe02ecb5b842adce81d02d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 22 May 2009 14:14:31 +0200 Subject: Fixed potential bug caused by change b89efc8e7f32. If ensureSpace causes the layoutData to reallocate then the initialGlyphs pointers will no longer be valid. Reviewed-by: Simon Hausmann --- src/gui/text/qtextengine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/text/qtextengine.cpp b/src/gui/text/qtextengine.cpp index da1ab25..d41d414 100644 --- a/src/gui/text/qtextengine.cpp +++ b/src/gui/text/qtextengine.cpp @@ -1219,7 +1219,7 @@ void QTextEngine::shapeTextWithHarfbuzz(int item) const QFontEngine *actualFontEngine = font; uint engineIdx = 0; if (font->type() == QFontEngine::Multi) { - engineIdx = uint(initialGlyphs.glyphs[glyph_pos] >> 24); + engineIdx = uint(availableGlyphs(&si).glyphs[glyph_pos] >> 24); actualFontEngine = static_cast(font)->engine(engineIdx); } -- cgit v0.12 From 1cfb5bcaa2cab142479ee975e25d9f605f852dad Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Fri, 22 May 2009 14:30:01 +0200 Subject: Don't loop around sigaction because it can't return EINTR. Asked by Oswald. Reviewed-by: Oswald Buddenhagen --- src/corelib/io/qprocess_unix.cpp | 23 +++++++---------------- 1 file changed, 7 insertions(+), 16 deletions(-) diff --git a/src/corelib/io/qprocess_unix.cpp b/src/corelib/io/qprocess_unix.cpp index 33d4a47..1fedd55 100644 --- a/src/corelib/io/qprocess_unix.cpp +++ b/src/corelib/io/qprocess_unix.cpp @@ -140,15 +140,6 @@ static void qt_native_close(int fd) } while (ret == -1 && errno == EINTR); } -static void qt_native_sigaction(int signum, const struct sigaction *act, - struct sigaction *oldact) -{ - int ret; - do { - ret = ::sigaction(signum, act, oldact); - } while (ret == -1 && errno == EINTR); -} - static void qt_native_dup2(int oldfd, int newfd) { int ret; @@ -255,7 +246,7 @@ QProcessManager::QProcessManager() memset(&action, 0, sizeof(action)); action.sa_handler = qt_sa_sigchld_handler; action.sa_flags = SA_NOCLDSTOP; - qt_native_sigaction(SIGCHLD, &action, &oldAction); + ::sigaction(SIGCHLD, &action, &oldAction); if (oldAction.sa_handler != qt_sa_sigchld_handler) qt_sa_old_sigchld_handler = oldAction.sa_handler; } @@ -282,9 +273,9 @@ QProcessManager::~QProcessManager() memset(&action, 0, sizeof(action)); action.sa_handler = qt_sa_old_sigchld_handler; action.sa_flags = SA_NOCLDSTOP; - qt_native_sigaction(SIGCHLD, &action, &oldAction); + ::sigaction(SIGCHLD, &action, &oldAction); if (oldAction.sa_handler != qt_sa_sigchld_handler) { - qt_native_sigaction(SIGCHLD, &oldAction, 0); + ::sigaction(SIGCHLD, &oldAction, 0); } } @@ -900,7 +891,7 @@ static void qt_ignore_sigpipe() struct sigaction noaction; memset(&noaction, 0, sizeof(noaction)); noaction.sa_handler = SIG_IGN; - qt_native_sigaction(SIGPIPE, &noaction, 0); + ::sigaction(SIGPIPE, &noaction, 0); } } @@ -1270,7 +1261,7 @@ bool QProcessPrivate::startDetached(const QString &program, const QStringList &a struct sigaction noaction; memset(&noaction, 0, sizeof(noaction)); noaction.sa_handler = SIG_IGN; - qt_native_sigaction(SIGPIPE, &noaction, 0); + ::sigaction(SIGPIPE, &noaction, 0); ::setsid(); @@ -1316,7 +1307,7 @@ bool QProcessPrivate::startDetached(const QString &program, const QStringList &a struct sigaction noaction; memset(&noaction, 0, sizeof(noaction)); noaction.sa_handler = SIG_IGN; - qt_native_sigaction(SIGPIPE, &noaction, 0); + ::sigaction(SIGPIPE, &noaction, 0); // '\1' means execv failed char c = '\1'; @@ -1327,7 +1318,7 @@ bool QProcessPrivate::startDetached(const QString &program, const QStringList &a struct sigaction noaction; memset(&noaction, 0, sizeof(noaction)); noaction.sa_handler = SIG_IGN; - qt_native_sigaction(SIGPIPE, &noaction, 0); + ::sigaction(SIGPIPE, &noaction, 0); // '\2' means internal error char c = '\2'; -- cgit v0.12 From 562adecf4f938f593674f03b425a79b89e238518 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:17:20 +0200 Subject: Don't block copy sequential files in QFile::rename Block copying a sequential file is potentially a destructive operation, because there is no guarantee copy+remove will succeed. In these cases the fallback should not be tried. The user is better equipped to decide how to handle such failures and to ensure no data losses occur, e.g., copy without removing the original file. Reviewed-by: MariusSO Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qfile.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index d7da800..4110494 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -718,6 +718,11 @@ QFile::rename(const QString &newName) return true; } + if (isSequential()) { + d->setError(QFile::RenameError, tr("Will not rename sequential file using block copy")); + return false; + } + QFile in(fileName()); QFile out(newName); if (in.open(QIODevice::ReadOnly)) { -- cgit v0.12 From f1e9c0f3d22d611bfaa14c30a34e6042500a0cb8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:24:43 +0200 Subject: Allow renaming QTemporaryFiles on windows Changed the fallback implementation to use 'this' instead of a new QFile. This allows a QTemporaryFile to be block-copied to the destination and the source to be removed (QTemporaryFile is special because it isn't really closed). Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qfile.cpp | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index 4110494..d3cee9a 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -723,26 +723,25 @@ QFile::rename(const QString &newName) return false; } - QFile in(fileName()); QFile out(newName); - if (in.open(QIODevice::ReadOnly)) { + if (open(QIODevice::ReadOnly)) { if (out.open(QIODevice::WriteOnly | QIODevice::Truncate)) { bool error = false; char block[4096]; - qint64 read; - while ((read = in.read(block, sizeof(block))) > 0) { - if (read != out.write(block, read)) { + qint64 bytes; + while ((bytes = read(block, sizeof(block))) > 0) { + if (bytes != out.write(block, bytes)) { d->setError(QFile::RenameError, out.errorString()); error = true; break; } } - if (read == -1) { - d->setError(QFile::RenameError, in.errorString()); + if (bytes == -1) { + d->setError(QFile::RenameError, errorString()); error = true; } if(!error) { - if (!in.remove()) { + if (!remove()) { d->setError(QFile::RenameError, tr("Cannot remove source file")); error = true; } @@ -751,10 +750,12 @@ QFile::rename(const QString &newName) out.remove(); else setFileName(newName); + close(); return !error; } + close(); } - d->setError(QFile::RenameError, out.isOpen() ? in.errorString() : out.errorString()); + d->setError(QFile::RenameError, out.isOpen() ? errorString() : out.errorString()); } return false; } -- cgit v0.12 From fd7cb7faa765835de6e7beb24f018c417d9ad7d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 13 May 2009 17:13:48 +0200 Subject: QFile::copy: close source file when using fallback mechanism Also added check in test case for rename fallback. Task-number: 165920 Reviewed-by: Thiago --- src/corelib/io/qfile.cpp | 1 + tests/auto/qfile/copy-fallback.qrc | 5 +++++ tests/auto/qfile/test/test.pro | 2 +- tests/auto/qfile/tst_qfile.cpp | 30 ++++++++++++++++++++++++++++++ 4 files changed, 37 insertions(+), 1 deletion(-) create mode 100644 tests/auto/qfile/copy-fallback.qrc diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index d3cee9a..a0bd8b4 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -914,6 +914,7 @@ QFile::copy(const QString &newName) out.setAutoRemove(false); #endif } + close(); } if(!error) { QFile::setPermissions(newName, permissions()); diff --git a/tests/auto/qfile/copy-fallback.qrc b/tests/auto/qfile/copy-fallback.qrc new file mode 100644 index 0000000..864491f --- /dev/null +++ b/tests/auto/qfile/copy-fallback.qrc @@ -0,0 +1,5 @@ + + + copy-fallback.qrc + + diff --git a/tests/auto/qfile/test/test.pro b/tests/auto/qfile/test/test.pro index 68f4c05..8d26f5e 100644 --- a/tests/auto/qfile/test/test.pro +++ b/tests/auto/qfile/test/test.pro @@ -17,7 +17,7 @@ QT = core network DEFINES += SRCDIR=\\\"$$PWD/../\\\" } -RESOURCES += ../qfile.qrc ../rename-fallback.qrc +RESOURCES += ../qfile.qrc ../rename-fallback.qrc ../copy-fallback.qrc TARGET = ../tst_qfile diff --git a/tests/auto/qfile/tst_qfile.cpp b/tests/auto/qfile/tst_qfile.cpp index 98e1859..7e28d12 100644 --- a/tests/auto/qfile/tst_qfile.cpp +++ b/tests/auto/qfile/tst_qfile.cpp @@ -125,6 +125,7 @@ private slots: void copy(); void copyRemovesTemporaryFile() const; void copyShouldntOverwrite(); + void copyFallback(); void link(); void linkToDir(); void absolutePathLinkToRelativePath(); @@ -213,6 +214,9 @@ void tst_QFile::cleanup() // TODO: Add cleanup code here. // This will be executed immediately after each test is run. + // for copyFallback() + QFile::remove("file-copy-destination.txt"); + // for renameFallback() QFile::remove("file-rename-destination.txt"); @@ -907,6 +911,31 @@ void tst_QFile::copyShouldntOverwrite() QFile::remove("tst_qfile.cpy"); } +void tst_QFile::copyFallback() +{ + // Using a resource file to trigger QFile::copy's fallback handling + QFile file(":/copy-fallback.qrc"); + QFile::remove("file-copy-destination.txt"); + + QVERIFY2(file.exists(), "test precondition"); + QVERIFY2(!QFile::exists("file-copy-destination.txt"), "test precondition"); + + // Fallback copy of closed file. + QVERIFY(file.copy("file-copy-destination.txt")); + QVERIFY(QFile::exists("file-copy-destination.txt")); + QVERIFY(!file.isOpen()); + + QVERIFY(QFile::remove("file-copy-destination.txt")); + + // Fallback copy of open file. + QVERIFY(file.open(QIODevice::ReadOnly)); + QVERIFY(file.copy("file-copy-destination.txt")); + QVERIFY(QFile::exists("file-copy-destination.txt")); + QVERIFY(!file.isOpen()); + + QFile::remove("file-copy-destination.txt"); +} + #ifdef Q_OS_WIN #include #include @@ -2081,6 +2110,7 @@ void tst_QFile::renameFallback() QVERIFY(!file.rename("file-rename-destination.txt")); QVERIFY(!QFile::exists("file-rename-destination.txt")); + QVERIFY(!file.isOpen()); } void tst_QFile::renameMultiple() -- cgit v0.12 From 3580f5b4d002cca714d443054f8cdd6aefca3287 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:30:47 +0200 Subject: QFile::rename fallback: reset permissions and error state on success Fallback implementation for rename operation should try to copy permissions from the original file to the destination file. Note that failures at this point are not treated as errors. Errors previously set by the native fileEngine are also reset before returning. Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qfile.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index a0bd8b4..10b812b 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -748,8 +748,11 @@ QFile::rename(const QString &newName) } if (error) out.remove(); - else + else { + setPermissions(permissions()); + unsetError(); setFileName(newName); + } close(); return !error; } -- cgit v0.12 From 3672deb3b35fc0660c58a8ecc741b989dd0bfc8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Tue, 19 May 2009 14:02:12 +0200 Subject: Fix auto test When copying a resource file to the native file system the (read-only) permissions also get copied. On Windows platforms, this was preventing a test file from being deleted. Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- tests/auto/qfile/tst_qfile.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/tests/auto/qfile/tst_qfile.cpp b/tests/auto/qfile/tst_qfile.cpp index 7e28d12..9ee4d7c 100644 --- a/tests/auto/qfile/tst_qfile.cpp +++ b/tests/auto/qfile/tst_qfile.cpp @@ -215,7 +215,11 @@ void tst_QFile::cleanup() // This will be executed immediately after each test is run. // for copyFallback() - QFile::remove("file-copy-destination.txt"); + if (QFile::exists("file-copy-destination.txt")) { + QFile::setPermissions("file-copy-destination.txt", + QFile::ReadOwner | QFile::WriteOwner); + QFile::remove("file-copy-destination.txt"); + } // for renameFallback() QFile::remove("file-rename-destination.txt"); @@ -925,6 +929,9 @@ void tst_QFile::copyFallback() QVERIFY(QFile::exists("file-copy-destination.txt")); QVERIFY(!file.isOpen()); + // Need to reset permissions on Windows to be able to delete + QVERIFY(QFile::setPermissions("file-copy-destination.txt", + QFile::ReadOwner | QFile::WriteOwner)); QVERIFY(QFile::remove("file-copy-destination.txt")); // Fallback copy of open file. -- cgit v0.12 From 662e8997e9777c6661dde2134e43e35963a12cb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:34:57 +0200 Subject: QTemporaryFile: don't clear filePath if remove fails Reviewed-by: MariusSO Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 6a9125c..b0809c6 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -364,9 +364,11 @@ bool QTemporaryFileEngine::remove() // Since the QTemporaryFileEngine::close() does not really close the file, // we must explicitly call QFSFileEngine::close() before we remove it. QFSFileEngine::close(); - bool removed = QFSFileEngine::remove(); - d->filePath.clear(); - return removed; + if (QFSFileEngine::remove()) { + d->filePath.clear(); + return true; + } + return false; } bool QTemporaryFileEngine::close() -- cgit v0.12 From cfa01206e38d120c0ddb17aec7358aadff30b6f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 12:40:01 +0200 Subject: QTemporaryFile would forget fileName while file was "closed" Note: this showed even if the file descriptor was kept open. Reviewed-by: Peter Hartmann Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 3 ++- tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index b0809c6..11e88e2 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -603,7 +603,8 @@ void QTemporaryFile::setAutoRemove(bool b) QString QTemporaryFile::fileName() const { - if(!isOpen()) + Q_D(const QTemporaryFile); + if(d->fileName.isEmpty()) return QString(); return fileEngine()->fileName(QAbstractFileEngine::DefaultName); } diff --git a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp index 2daa0f6..c6a43ff 100644 --- a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp +++ b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp @@ -77,6 +77,7 @@ private slots: void fileTemplate_data(); void getSetCheck(); void fileName(); + void fileNameIsEmpty(); void autoRemove(); void write(); void openCloseOpenClose(); @@ -189,6 +190,27 @@ void tst_QTemporaryFile::fileName() QCOMPARE(absoluteFilePath, absoluteTempPath); } +void tst_QTemporaryFile::fileNameIsEmpty() +{ + QString filename; + { + QTemporaryFile file; + QVERIFY(file.fileName().isEmpty()); + + QVERIFY(file.open()); + QVERIFY(!file.fileName().isEmpty()); + + filename = file.fileName(); + QVERIFY(QFile::exists(filename)); + + file.close(); + QVERIFY(!file.isOpen()); + QVERIFY(QFile::exists(filename)); + QVERIFY(!file.fileName().isEmpty()); + } + QVERIFY(!QFile::exists(filename)); +} + void tst_QTemporaryFile::autoRemove() { // Test auto remove @@ -358,6 +380,7 @@ void tst_QTemporaryFile::rename() QVERIFY(file.rename("temporary-file.txt")); QVERIFY(!dir.exists(tempname)); QVERIFY(dir.exists("temporary-file.txt")); + QCOMPARE(file.fileName(), QString("temporary-file.txt")); } QVERIFY(!dir.exists(tempname)); -- cgit v0.12 From 70f616238e77d866420f2c6e12afe04b529fe808 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 20 May 2009 20:13:51 +0200 Subject: Documentation fix We souldn't be returning an empty string for the fileName, just because the file is closed. E.g., after a rename, the file will be closed, but should still have a name. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 11e88e2..e83d7e9 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -432,8 +432,8 @@ QTemporaryFilePrivate::~QTemporaryFilePrivate() file will exist and be kept open internally by QTemporaryFile. The file name of the temporary file can be found by calling fileName(). - Note that this is only defined while the file is open; the function returns - an empty string before the file is opened and after it is closed. + Note that this is only defined after the file is first opened; the function + returns an empty string before this. A temporary file will have some static part of the name and some part that is calculated to be unique. The default filename \c -- cgit v0.12 From 5cb1ed45ba55dbc9752e0f6f47cc6d1525464646 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 13:01:52 +0200 Subject: QTemporaryFile: handle failures from QFSFileEngine::open(mode, fd) For now, this only happens if Append mode is requested and we're unable to seek to the end of the file. Theoretically, this could change in the future so it's better to err on the safe side. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index e83d7e9..b6eff94 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -322,7 +322,6 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) qfilename += QLatin1String(".XXXXXX"); int suffixLength = qfilename.length() - (qfilename.lastIndexOf(QLatin1String("XXXXXX"), -1, Qt::CaseSensitive) + 6); - d->closeFileHandle = true; char *filename = qstrdup(qfilename.toLocal8Bit()); #ifndef Q_WS_WIN @@ -330,16 +329,19 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) if (fd != -1) { // First open the fd as an external file descriptor to // initialize the engine properly. - QFSFileEngine::open(openMode, fd); + if (QFSFileEngine::open(openMode, fd)) { - // Allow the engine to close the handle even if it's "external". - d->closeFileHandle = true; + // Allow the engine to close the handle even if it's "external". + d->closeFileHandle = true; - // Restore the file names (open() resets them). - d->filePath = QString::fromLocal8Bit(filename); //changed now! - d->nativeInitFileName(); - delete [] filename; - return true; + // Restore the file names (open() resets them). + d->filePath = QString::fromLocal8Bit(filename); //changed now! + d->nativeInitFileName(); + delete [] filename; + return true; + } + + QT_CLOSE(fd); } delete [] filename; setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(errno)); -- cgit v0.12 From f1793cbff8aa9b4adcb5fd511e495f7e96811e2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 14:58:44 +0200 Subject: Unconditionally open temporary files in ReadWrite mode Although QTemporaryFile hides QFile::open(OpenMode), this function is still available when accessing instance methods through the base class. Unconditionally setting ReadWrite allows the temporary file to be re-opened with different flags. Task-number: 248223 Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 1 + tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp | 15 +++++++++++++++ 2 files changed, 16 insertions(+) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index b6eff94..3f8f978 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -720,6 +720,7 @@ bool QTemporaryFile::open(OpenMode flags) return true; } + flags |= QIODevice::ReadWrite; if (QFile::open(flags)) { d->fileName = d->fileEngine->fileName(QAbstractFileEngine::DefaultName); return true; diff --git a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp index c6a43ff..26f5f40 100644 --- a/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp +++ b/tests/auto/qtemporaryfile/tst_qtemporaryfile.cpp @@ -87,6 +87,8 @@ private slots: void stressTest(); void rename(); void renameFdLeak(); + void reOpenThroughQFile(); + public: }; @@ -424,5 +426,18 @@ void tst_QTemporaryFile::renameFdLeak() #endif } +void tst_QTemporaryFile::reOpenThroughQFile() +{ + QByteArray data("abcdefghij"); + + QTemporaryFile file; + QVERIFY(((QFile &)file).open(QIODevice::WriteOnly)); + QCOMPARE(file.write(data), (qint64)data.size()); + + file.close(); + QVERIFY(file.open()); + QCOMPARE(file.readAll(), data); +} + QTEST_MAIN(tst_QTemporaryFile) #include "tst_qtemporaryfile.moc" -- cgit v0.12 From 27369e563263e82a9c5747da54370eb0a225b3d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 18:40:03 +0200 Subject: QTemporaryFile: really (re)open file if it has been really closed... In some circumstances, the file descriptor in QTemporaryFile is actually closed and setOpenMode alone won't give us reOpen semantics. Added function to QTemporaryFileEngine that checks if we have open file handles. On open, if we currently hold no handles, re-open the file. Trying to open a new file while we hold open handles would lead to leaks, so added an assert there, to be on the safe side. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 23 +++++++++++++++++++++-- 1 file changed, 21 insertions(+), 2 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 3f8f978..5e08ed8 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -294,6 +294,7 @@ public: QTemporaryFileEngine(const QString &file) : QFSFileEngine(file) { } ~QTemporaryFileEngine(); + bool isReallyOpen(); void setFileName(const QString &file); bool open(QIODevice::OpenMode flags); @@ -306,6 +307,21 @@ QTemporaryFileEngine::~QTemporaryFileEngine() QFSFileEngine::close(); } +bool QTemporaryFileEngine::isReallyOpen() +{ + Q_D(QFSFileEngine); + + if (!((0 == d->fh) && (-1 == d->fd) +#if defined Q_OS_WIN + && (INVALID_HANDLE_VALUE == d->fileHandle) +#endif + )) + return true; + + return false; + +} + void QTemporaryFileEngine::setFileName(const QString &file) { // Really close the file, so we don't leak @@ -316,6 +332,7 @@ void QTemporaryFileEngine::setFileName(const QString &file) bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) { Q_D(QFSFileEngine); + Q_ASSERT(!isReallyOpen()); QString qfilename = d->filePath; if(!qfilename.contains(QLatin1String("XXXXXX"))) @@ -716,8 +733,10 @@ bool QTemporaryFile::open(OpenMode flags) { Q_D(QTemporaryFile); if (!d->fileName.isEmpty()) { - setOpenMode(flags); - return true; + if (static_cast(fileEngine())->isReallyOpen()) { + setOpenMode(flags); + return true; + } } flags |= QIODevice::ReadWrite; -- cgit v0.12 From 84cbe8ffa4a7189c46efca9bb6387e80ab889c5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 15 Apr 2009 14:37:35 +0200 Subject: QTemporaryFile: there's no need to keep another pointer to the engine here Lifetime of the engine is already handled by the native engine. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 5e08ed8..ec539d4 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -409,17 +409,14 @@ protected: bool autoRemove; QString templateName; - mutable QTemporaryFileEngine *fileEngine; }; -QTemporaryFilePrivate::QTemporaryFilePrivate() : autoRemove(true), fileEngine(0) +QTemporaryFilePrivate::QTemporaryFilePrivate() : autoRemove(true) { } QTemporaryFilePrivate::~QTemporaryFilePrivate() { - delete fileEngine; - fileEngine = 0; } //************* QTemporaryFile -- cgit v0.12 From 1044e75822270d702a3e9f14a87954321984c942 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 20:24:20 +0200 Subject: QTemporaryFileEngine now tracks if a fileName has been generated With recent changes to QTemporaryFile, allowing the file to be closed, the engine has to keep track of whether a fileName has already been generated, so we don't generate new files after the first one. If the file is closed but we already have a name for it, then just forward the call to the base file engine. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index ec539d4..564ec59 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -291,7 +291,11 @@ class QTemporaryFileEngine : public QFSFileEngine { Q_DECLARE_PRIVATE(QFSFileEngine) public: - QTemporaryFileEngine(const QString &file) : QFSFileEngine(file) { } + QTemporaryFileEngine(const QString &file, bool fileIsTemplate = true) + : QFSFileEngine(file), filePathIsTemplate(fileIsTemplate) + { + } + ~QTemporaryFileEngine(); bool isReallyOpen(); @@ -300,6 +304,8 @@ public: bool open(QIODevice::OpenMode flags); bool remove(); bool close(); + + bool filePathIsTemplate; }; QTemporaryFileEngine::~QTemporaryFileEngine() @@ -334,6 +340,9 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) Q_D(QFSFileEngine); Q_ASSERT(!isReallyOpen()); + if (!filePathIsTemplate) + return QFSFileEngine::open(openMode); + QString qfilename = d->filePath; if(!qfilename.contains(QLatin1String("XXXXXX"))) qfilename += QLatin1String(".XXXXXX"); @@ -353,6 +362,7 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) // Restore the file names (open() resets them). d->filePath = QString::fromLocal8Bit(filename); //changed now! + filePathIsTemplate = false; d->nativeInitFileName(); delete [] filename; return true; @@ -370,6 +380,7 @@ bool QTemporaryFileEngine::open(QIODevice::OpenMode openMode) } d->filePath = QString::fromLocal8Bit(filename); + filePathIsTemplate = false; d->nativeInitFileName(); d->closeFileHandle = true; delete [] filename; @@ -714,8 +725,12 @@ QTemporaryFile *QTemporaryFile::createLocalFile(QFile &file) QAbstractFileEngine *QTemporaryFile::fileEngine() const { Q_D(const QTemporaryFile); - if(!d->fileEngine) - d->fileEngine = new QTemporaryFileEngine(d->templateName); + if(!d->fileEngine) { + if (d->fileName.isEmpty()) + d->fileEngine = new QTemporaryFileEngine(d->templateName); + else + d->fileEngine = new QTemporaryFileEngine(d->fileName, false); + } return d->fileEngine; } -- cgit v0.12 From ba706d2564f1181fa4cc596a46bb2a041c62c28f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 13:08:04 +0200 Subject: QTemporaryFile: really close files before renaming This gets temporary file renaming working on Windows, without requiring block-copying. While we could #ifdef this behavior for Windows, it's preferrable to maintain consistency in the exposed interface. Reviewed-by: Thiago --- src/corelib/io/qtemporaryfile.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 564ec59..7c0b018 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -303,6 +303,7 @@ public: bool open(QIODevice::OpenMode flags); bool remove(); + bool rename(const QString &newName); bool close(); bool filePathIsTemplate; @@ -401,6 +402,12 @@ bool QTemporaryFileEngine::remove() return false; } +bool QTemporaryFileEngine::rename(const QString &newName) +{ + QFSFileEngine::close(); + return QFSFileEngine::rename(newName); +} + bool QTemporaryFileEngine::close() { // Don't close the file, just seek to the front. -- cgit v0.12 From a0396c8c68aca446e68434e516bd46d749093b0f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Mon, 18 May 2009 11:51:12 +0200 Subject: Reset openMode to NotOpen when returning false from QFile::open() When connecting to an open file descriptor, set the openMode in the file system engine, as is done for file handles. Reviewed-by: Thiago --- src/corelib/io/qfsfileengine.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/corelib/io/qfsfileengine.cpp b/src/corelib/io/qfsfileengine.cpp index 61ea7cc..1c8f0e9 100644 --- a/src/corelib/io/qfsfileengine.cpp +++ b/src/corelib/io/qfsfileengine.cpp @@ -312,6 +312,10 @@ bool QFSFileEnginePrivate::openFh(QIODevice::OpenMode openMode, FILE *fh) if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); + + this->openMode = QIODevice::NotOpen; + this->fh = 0; + return false; } } @@ -335,6 +339,7 @@ bool QFSFileEngine::open(QIODevice::OpenMode openMode, int fd) if ((openMode & QFile::WriteOnly) && !(openMode & (QFile::ReadOnly | QFile::Append))) openMode |= QFile::Truncate; + d->openMode = openMode; d->lastFlushFailed = false; d->closeFileHandle = false; d->nativeFilePath.clear(); @@ -367,6 +372,10 @@ bool QFSFileEnginePrivate::openFd(QIODevice::OpenMode openMode, int fd) if (ret == -1) { q->setError(errno == EMFILE ? QFile::ResourceError : QFile::OpenError, qt_error_string(int(errno))); + + this->openMode = QIODevice::NotOpen; + this->fd = -1; + return false; } } -- cgit v0.12 From 3ebbecd49d9e3cd8818634d5da5c7b1850190d54 Mon Sep 17 00:00:00 2001 From: "Bradley T. Hughes" Date: Fri, 22 May 2009 14:30:27 +0200 Subject: Make the default size of QMutexPool a prime number As pointed out by Olivier, this should allow for better distribution in the array. I also removed the unnecessary count member, since we can use QVarLengthArray.count() instead. --- src/corelib/thread/qmutexpool.cpp | 8 ++++---- src/corelib/thread/qmutexpool_p.h | 5 ++--- 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/corelib/thread/qmutexpool.cpp b/src/corelib/thread/qmutexpool.cpp index 77a3cca..0d7c890 100644 --- a/src/corelib/thread/qmutexpool.cpp +++ b/src/corelib/thread/qmutexpool.cpp @@ -96,9 +96,9 @@ Q_GLOBAL_STATIC_WITH_ARGS(QMutexPool, globalMutexPool, (QMutex::Recursive)) QMutexPool is destructed. */ QMutexPool::QMutexPool(QMutex::RecursionMode recursionMode, int size) - : mutexes(size), count(size), recursionMode(recursionMode) + : mutexes(size), recursionMode(recursionMode) { - for (int index = 0; index < count; ++index) { + for (int index = 0; index < mutexes.count(); ++index) { mutexes[index] = 0; } } @@ -109,7 +109,7 @@ QMutexPool::QMutexPool(QMutex::RecursionMode recursionMode, int size) */ QMutexPool::~QMutexPool() { - for (int index = 0; index < count; ++index) { + for (int index = 0; index < mutexes.count(); ++index) { delete mutexes[index]; mutexes[index] = 0; } @@ -130,7 +130,7 @@ QMutexPool *QMutexPool::instance() QMutex *QMutexPool::get(const void *address) { Q_ASSERT_X(address != 0, "QMutexPool::get()", "'address' argument cannot be zero"); - int index = int((quintptr(address) >> (sizeof(address) >> 1)) % count); + int index = int((quintptr(address) >> (sizeof(address) >> 1)) % mutexes.count()); if (!mutexes[index]) { // mutex not created, create one diff --git a/src/corelib/thread/qmutexpool_p.h b/src/corelib/thread/qmutexpool_p.h index 4c1e32c..30a16d4 100644 --- a/src/corelib/thread/qmutexpool_p.h +++ b/src/corelib/thread/qmutexpool_p.h @@ -64,7 +64,7 @@ QT_BEGIN_NAMESPACE class Q_CORE_EXPORT QMutexPool { public: - explicit QMutexPool(QMutex::RecursionMode recursionMode = QMutex::NonRecursive, int size = 128); + explicit QMutexPool(QMutex::RecursionMode recursionMode = QMutex::NonRecursive, int size = 131); ~QMutexPool(); QMutex *get(const void *address); @@ -72,8 +72,7 @@ public: static QMutex *globalInstanceGet(const void *address); private: - QVarLengthArray, 128> mutexes; - int count; + QVarLengthArray, 131> mutexes; QMutex::RecursionMode recursionMode; }; -- cgit v0.12 From 96a5352b9460573a29dd31e884269e84187f6f88 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Fri, 22 May 2009 14:36:16 +0200 Subject: Fix compile issue Reviewed-by: Kent Hansen --- examples/animation/stickman/stickman.pro | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/animation/stickman/stickman.pro b/examples/animation/stickman/stickman.pro index 956b49c..1dbbce9 100644 --- a/examples/animation/stickman/stickman.pro +++ b/examples/animation/stickman/stickman.pro @@ -10,6 +10,8 @@ SOURCES += main.cpp \ lifecycle.cpp \ graphicsview.cpp +INCLUDEPATH += $$PWD + include(editor/editor.pri) # install -- cgit v0.12 From 8b2a16bd7f434a159e34e93dbffc983927a0a143 Mon Sep 17 00:00:00 2001 From: Markus Goetz Date: Fri, 22 May 2009 13:20:10 +0200 Subject: Fixed compilation with -qtnamespace Task-number: 254333 Reviewed-by: Andy Shaw --- src/corelib/io/qtemporaryfile.cpp | 4 +++- src/corelib/kernel/qsharedmemory_unix.cpp | 4 ++-- src/corelib/kernel/qsystemsemaphore_p.h | 4 ++-- src/corelib/kernel/qtranslator.cpp | 4 ++-- src/network/access/qhttp.cpp | 4 ++-- src/network/kernel/qnetworkproxy.cpp | 4 ++-- src/network/kernel/qurlinfo.cpp | 4 ++-- src/network/socket/qhttpsocketengine.cpp | 4 ++-- src/scripttools/debugging/qscriptenginedebugger.cpp | 13 ++++++++++--- 9 files changed, 27 insertions(+), 18 deletions(-) diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index 7c0b018..b4d8a48 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -766,6 +766,8 @@ bool QTemporaryFile::open(OpenMode flags) return false; } +QT_END_NAMESPACE + #endif // QT_NO_TEMPORARYFILE -QT_END_NAMESPACE + diff --git a/src/corelib/kernel/qsharedmemory_unix.cpp b/src/corelib/kernel/qsharedmemory_unix.cpp index 487c653..61d56f4 100644 --- a/src/corelib/kernel/qsharedmemory_unix.cpp +++ b/src/corelib/kernel/qsharedmemory_unix.cpp @@ -49,10 +49,10 @@ #include -QT_BEGIN_NAMESPACE - #ifndef QT_NO_SHAREDMEMORY +QT_BEGIN_NAMESPACE + #include #include #include diff --git a/src/corelib/kernel/qsystemsemaphore_p.h b/src/corelib/kernel/qsystemsemaphore_p.h index 81d4f10..a4a7389 100644 --- a/src/corelib/kernel/qsystemsemaphore_p.h +++ b/src/corelib/kernel/qsystemsemaphore_p.h @@ -101,9 +101,9 @@ public: QSystemSemaphore::SystemSemaphoreError error; }; -#endif // QT_NO_SYSTEMSEMAPHORE +QT_END_NAMESPACE +#endif // QT_NO_SYSTEMSEMAPHORE -QT_END_NAMESPACE #endif // QSYSTEMSEMAPHORE_P_H diff --git a/src/corelib/kernel/qtranslator.cpp b/src/corelib/kernel/qtranslator.cpp index 77d6599..3e4b467 100644 --- a/src/corelib/kernel/qtranslator.cpp +++ b/src/corelib/kernel/qtranslator.cpp @@ -819,6 +819,6 @@ bool QTranslator::isEmpty() const Use translate(\a context, \a sourceText, \a comment) instead. */ -#endif // QT_NO_TRANSLATION - QT_END_NAMESPACE + +#endif // QT_NO_TRANSLATION diff --git a/src/network/access/qhttp.cpp b/src/network/access/qhttp.cpp index 7d14ab6..30befb3 100644 --- a/src/network/access/qhttp.cpp +++ b/src/network/access/qhttp.cpp @@ -64,10 +64,10 @@ # include "qtimer.h" #endif -QT_BEGIN_NAMESPACE - #ifndef QT_NO_HTTP +QT_BEGIN_NAMESPACE + class QHttpNormalRequest; class QHttpRequest { diff --git a/src/network/kernel/qnetworkproxy.cpp b/src/network/kernel/qnetworkproxy.cpp index 62bdfc7..fd3a85a 100644 --- a/src/network/kernel/qnetworkproxy.cpp +++ b/src/network/kernel/qnetworkproxy.cpp @@ -1258,6 +1258,6 @@ QList QNetworkProxyFactory::proxyForQuery(const QNetworkProxyQuer return globalNetworkProxy()->proxyForQuery(query); } -#endif // QT_NO_NETWORKPROXY - QT_END_NAMESPACE + +#endif // QT_NO_NETWORKPROXY diff --git a/src/network/kernel/qurlinfo.cpp b/src/network/kernel/qurlinfo.cpp index 255c9ea..d90c480 100644 --- a/src/network/kernel/qurlinfo.cpp +++ b/src/network/kernel/qurlinfo.cpp @@ -726,6 +726,6 @@ bool QUrlInfo::isValid() const return d != 0; } -#endif // QT_NO_URLINFO - QT_END_NAMESPACE + +#endif // QT_NO_URLINFO diff --git a/src/network/socket/qhttpsocketengine.cpp b/src/network/socket/qhttpsocketengine.cpp index 540c443..5a2a746 100644 --- a/src/network/socket/qhttpsocketengine.cpp +++ b/src/network/socket/qhttpsocketengine.cpp @@ -768,6 +768,6 @@ QAbstractSocketEngine *QHttpSocketEngineHandler::createSocketEngine(int, QObject return 0; } -#endif - QT_END_NAMESPACE + +#endif diff --git a/src/scripttools/debugging/qscriptenginedebugger.cpp b/src/scripttools/debugging/qscriptenginedebugger.cpp index e35bd1d..0f8b600 100644 --- a/src/scripttools/debugging/qscriptenginedebugger.cpp +++ b/src/scripttools/debugging/qscriptenginedebugger.cpp @@ -63,16 +63,23 @@ #include #include +// this has to be outside the namespace +static void initScriptEngineDebuggerResources() +{ + Q_INIT_RESOURCE(scripttools_debugging); +} + +QT_BEGIN_NAMESPACE + class QtScriptDebuggerResourceInitializer { public: QtScriptDebuggerResourceInitializer() { - Q_INIT_RESOURCE(scripttools_debugging); + // call outside-the-namespace function + initScriptEngineDebuggerResources(); } }; -QT_BEGIN_NAMESPACE - /*! \since 4.5 \class QScriptEngineDebugger -- cgit v0.12 From df77e086585ad9f0fe5c7778643a76e5634ac7cd Mon Sep 17 00:00:00 2001 From: Leonardo Sobral Cunha Date: Fri, 22 May 2009 14:40:18 +0200 Subject: Fix QEasingCurve autotests Easing curve autotests was converting the easing(qreal) to int before, but this is a very rough comparison and was failing due to different conversions to int, so now we do a qFuzzyCompare. Reviewed-by: Thierry --- tests/auto/qeasingcurve/tst_qeasingcurve.cpp | 208 +++++++++++++++++++++++++-- 1 file changed, 193 insertions(+), 15 deletions(-) diff --git a/tests/auto/qeasingcurve/tst_qeasingcurve.cpp b/tests/auto/qeasingcurve/tst_qeasingcurve.cpp index 8d42e5e..8fe15b1 100644 --- a/tests/auto/qeasingcurve/tst_qeasingcurve.cpp +++ b/tests/auto/qeasingcurve/tst_qeasingcurve.cpp @@ -179,28 +179,205 @@ void tst_QEasingCurve::propertyDefaults() } typedef QList IntList; +typedef QList RealList; Q_DECLARE_METATYPE(IntList) +Q_DECLARE_METATYPE(RealList) void tst_QEasingCurve::valueForProgress_data() { QTest::addColumn("type"); QTest::addColumn("at"); - QTest::addColumn("expected"); + QTest::addColumn("expected"); // automatically generated. // note that values are scaled from range [0,1] to range [0, 100] in order to store them as // integer values and avoid fp inaccuracies - QTest::newRow("Linear") << int(QEasingCurve::Linear) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100); + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.1 << 0.2 << 0.3 << 0.4 << 0.5 << 0.6 << 0.7 << 0.8 << 0.9 << 1); QTest::newRow("InQuad") << int(QEasingCurve::InQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 1 << 4 << 9 << 16 << 25 << 36 << 48 << 64 << 81 << 100); + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.01 << 0.04 << 0.09 << 0.16 << 0.25 << 0.36 << 0.49 << 0.64 << 0.81 << 1); QTest::newRow("OutQuad") << int(QEasingCurve::OutQuad) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.19 << 0.36 << 0.51 << 0.64 << 0.75 << 0.84 << 0.91 << 0.96 << 0.99 << 1); + + QTest::newRow("InOutQuad") << int(QEasingCurve::InOutQuad) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.02 << 0.08 << 0.18 << 0.32 << 0.5 << 0.68 << 0.82 << 0.92 << 0.98 << 1); + + QTest::newRow("OutInQuad") << int(QEasingCurve::OutInQuad) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.18 << 0.32 << 0.42 << 0.48 << 0.5 << 0.52 << 0.58 << 0.68 << 0.82 << 1); + + QTest::newRow("InCubic") << int(QEasingCurve::InCubic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.001 << 0.008 << 0.027 << 0.064 << 0.125 << 0.216 << 0.343 << 0.512 << 0.729 << 1); + + QTest::newRow("OutCubic") << int(QEasingCurve::OutCubic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.271 << 0.488 << 0.657 << 0.784 << 0.875 << 0.936 << 0.973 << 0.992 << 0.999 << 1); + + QTest::newRow("InOutCubic") << int(QEasingCurve::InOutCubic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.004 << 0.032 << 0.108 << 0.256 << 0.5 << 0.744 << 0.892 << 0.968 << 0.996 << 1); + + QTest::newRow("OutInCubic") << int(QEasingCurve::OutInCubic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.244 << 0.392 << 0.468 << 0.496 << 0.5 << 0.504 << 0.532 << 0.608 << 0.756 << 1); + + QTest::newRow("InQuart") << int(QEasingCurve::InQuart) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.0001 << 0.0016 << 0.0081 << 0.0256 << 0.0625 << 0.1296 << 0.2401 << 0.4096 << 0.6561 << 1); + + QTest::newRow("OutQuart") << int(QEasingCurve::OutQuart) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.3439 << 0.5904 << 0.7599 << 0.8704 << 0.9375 << 0.9744 << 0.9919 << 0.9984 << 0.9999 << 1); + + QTest::newRow("InOutQuart") << int(QEasingCurve::InOutQuart) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.0008 << 0.0128 << 0.0648 << 0.2048 << 0.5 << 0.7952 << 0.9352 << 0.9872 << 0.9992 << 1); + + QTest::newRow("OutInQuart") << int(QEasingCurve::OutInQuart) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.2952 << 0.4352 << 0.4872 << 0.4992 << 0.5 << 0.5008 << 0.5128 << 0.5648 << 0.7048 << 1); + + QTest::newRow("InQuint") << int(QEasingCurve::InQuint) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 1e-05 << 0.00032 << 0.00243 << 0.01024 << 0.03125 << 0.07776 << 0.1681 << 0.3277 << 0.5905 << 1); + + QTest::newRow("OutQuint") << int(QEasingCurve::OutQuint) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.4095 << 0.6723 << 0.8319 << 0.9222 << 0.9688 << 0.9898 << 0.9976 << 0.9997 << 1 << 1); + + QTest::newRow("InOutQuint") << int(QEasingCurve::InOutQuint) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.00016 << 0.00512 << 0.03888 << 0.1638 << 0.5 << 0.8362 << 0.9611 << 0.9949 << 0.9998 << 1); + + QTest::newRow("OutInQuint") << int(QEasingCurve::OutInQuint) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.3362 << 0.4611 << 0.4949 << 0.4998 << 0.5 << 0.5002 << 0.5051 << 0.5389 << 0.6638 << 1); + + QTest::newRow("InSine") << int(QEasingCurve::InSine) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.01231 << 0.04894 << 0.109 << 0.191 << 0.2929 << 0.4122 << 0.546 << 0.691 << 0.8436 << 1); + + QTest::newRow("OutSine") << int(QEasingCurve::OutSine) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.1564 << 0.309 << 0.454 << 0.5878 << 0.7071 << 0.809 << 0.891 << 0.9511 << 0.9877 << 1); + + QTest::newRow("InOutSine") << int(QEasingCurve::InOutSine) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.02447 << 0.09549 << 0.2061 << 0.3455 << 0.5 << 0.6545 << 0.7939 << 0.9045 << 0.9755 << 1); + + QTest::newRow("OutInSine") << int(QEasingCurve::OutInSine) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.1545 << 0.2939 << 0.4045 << 0.4755 << 0.5 << 0.5245 << 0.5955 << 0.7061 << 0.8455 << 1); + + QTest::newRow("InExpo") << int(QEasingCurve::InExpo) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.0009531 << 0.002906 << 0.006812 << 0.01462 << 0.03025 << 0.0615 << 0.124 << 0.249 << 0.499 << 1); + + QTest::newRow("OutExpo") << int(QEasingCurve::OutExpo) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.5005 << 0.7507 << 0.8759 << 0.9384 << 0.9697 << 0.9854 << 0.9932 << 0.9971 << 0.999 << 1); + + QTest::newRow("InOutExpo") << int(QEasingCurve::InOutExpo) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.001453 << 0.007312 << 0.03075 << 0.1245 << 0.5002 << 0.8754 << 0.9692 << 0.9927 << 0.9985 << 1); + + QTest::newRow("OutInExpo") << int(QEasingCurve::OutInExpo) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.3754 << 0.4692 << 0.4927 << 0.4985 << 0.5 << 0.5015 << 0.5073 << 0.5308 << 0.6245 << 1); + + QTest::newRow("InCirc") << int(QEasingCurve::InCirc) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.005013 << 0.0202 << 0.04606 << 0.08348 << 0.134 << 0.2 << 0.2859 << 0.4 << 0.5641 << 1); + + QTest::newRow("OutCirc") << int(QEasingCurve::OutCirc) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.4359 << 0.6 << 0.7141 << 0.8 << 0.866 << 0.9165 << 0.9539 << 0.9798 << 0.995 << 1); + + QTest::newRow("InOutCirc") << int(QEasingCurve::InOutCirc) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.0101 << 0.04174 << 0.1 << 0.2 << 0.5 << 0.8 << 0.9 << 0.9583 << 0.9899 << 1); + + QTest::newRow("OutInCirc") << int(QEasingCurve::OutInCirc) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.3 << 0.4 << 0.4583 << 0.4899 << 0.5 << 0.5101 << 0.5417 << 0.6 << 0.7 << 1); + + QTest::newRow("InElastic") << int(QEasingCurve::InElastic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.001953 << -0.001953 << -0.003906 << 0.01562 << -0.01562 << -0.03125 << 0.125 << -0.125 << -0.25 << 1); + + QTest::newRow("OutElastic") << int(QEasingCurve::OutElastic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 1.25 << 1.125 << 0.875 << 1.031 << 1.016 << 0.9844 << 1.004 << 1.002 << 0.998 << 1); + + QTest::newRow("InOutElastic") << int(QEasingCurve::InOutElastic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << -0.0009766 << 0.007812 << -0.01563 << -0.0625 << 0.5 << 1.062 << 1.016 << 0.9922 << 1.001 << 1); + + QTest::newRow("OutInElastic") << int(QEasingCurve::OutInElastic) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.375 << 0.5625 << 0.4922 << 0.498 << 0.5 << 0.4961 << 0.5078 << 0.5313 << 0.25 << 1); + + QTest::newRow("InBack") << int(QEasingCurve::InBack) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << -0.01431 << -0.04645 << -0.0802 << -0.09935 << -0.0877 << -0.02903 << 0.09287 << 0.2942 << 0.5912 << 1); + + QTest::newRow("OutBack") << int(QEasingCurve::OutBack) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.4088 << 0.7058 << 0.9071 << 1.029 << 1.088 << 1.099 << 1.08 << 1.046 << 1.014 << 1); + + QTest::newRow("InOutBack") << int(QEasingCurve::InOutBack) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << -0.03752 << -0.09256 << -0.07883 << 0.08993 << 0.5 << 0.9101 << 1.079 << 1.093 << 1.038 << 1); + + QTest::newRow("OutInBack") << int(QEasingCurve::OutInBack) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.3529 << 0.5145 << 0.5497 << 0.5232 << 0.5 << 0.4768 << 0.4503 << 0.4855 << 0.6471 << 1); + + QTest::newRow("InBounce") << int(QEasingCurve::InBounce) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.01188 << 0.06 << 0.06937 << 0.2275 << 0.2344 << 0.09 << 0.3194 << 0.6975 << 0.9244 << 1); + + QTest::newRow("OutBounce") << int(QEasingCurve::OutBounce) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.07563 << 0.3025 << 0.6806 << 0.91 << 0.7656 << 0.7725 << 0.9306 << 0.94 << 0.9881 << 1); + + QTest::newRow("InOutBounce") << int(QEasingCurve::InOutBounce) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.03 << 0.1138 << 0.045 << 0.3488 << 0.5 << 0.6512 << 0.955 << 0.8862 << 0.97 << 1); + + QTest::newRow("OutInBounce") << int(QEasingCurve::OutInBounce) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.1513 << 0.41 << 0.2725 << 0.44 << 0.5 << 0.56 << 0.7275 << 0.59 << 0.8488 << 1); + + QTest::newRow("InCurve") << int(QEasingCurve::InCurve) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.02447 << 0.1059 << 0.2343 << 0.3727 << 0.5 << 0.6055 << 0.7 << 0.8 << 0.9 << 1); + + QTest::newRow("OutCurve") << int(QEasingCurve::OutCurve) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.1 << 0.2 << 0.3 << 0.3945 << 0.5 << 0.6273 << 0.7657 << 0.8941 << 0.9755 << 1); + + QTest::newRow("SineCurve") << int(QEasingCurve::SineCurve) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.09549 << 0.3455 << 0.6545 << 0.9045 << 1 << 0.9045 << 0.6545 << 0.3455 << 0.09549 << 0); + + QTest::newRow("CosineCurve") << int(QEasingCurve::CosineCurve) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0.5 << 0.7939 << 0.9755 << 0.9755 << 0.7939 << 0.5 << 0.2061 << 0.02447 << 0.02447 << 0.2061 << 0.5); + + /* + QTest::newRow("InQuad") << int(QEasingCurve::InQuad) + << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) + << (RealList() << 0 << 0.01 << 0.04 << 0.09 << 0.16 << 0.25 << 0.36 << 0.49 << 0.64 << 0.81 << 1); + QTest::newRow("OutQuad") << int(QEasingCurve::OutQuad) << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 19 << 36 << 51 << 64 << 75 << 84 << 90 << 96 << 99 << 100); + << (IntList() << 0 << 0.19 << 0.36 << 0.51 << 0.64 << 0.75 << 0.84 << 0.91 << 0.96 << 0.99 << 1); QTest::newRow("InOutQuad") << int(QEasingCurve::InOutQuad) << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) @@ -369,7 +546,7 @@ void tst_QEasingCurve::valueForProgress_data() QTest::newRow("CosineCurve") << int(QEasingCurve::CosineCurve) << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) << (IntList() << 50 << 79 << 97 << 97 << 79 << 50 << 20 << 2 << 2 << 20 << 49); - +*/ } @@ -389,12 +566,11 @@ void tst_QEasingCurve::valueForProgress() for (int t = 0; t <= 100; t+= 10) { qreal ease = curve.valueForProgress(t/qreal(100)); strInputs += QString::fromAscii(" << %1").arg(t); - strOutputs += QString::fromAscii(" << %1").arg(int(100*ease)); - + strOutputs += " << " + QString().setNum(ease, 'g', 4); } QString str = QString::fromAscii(" QTest::newRow(\"%1\") << int(QEasingCurve::%2)\n" - "\t\t << (IntList() %3)\n" - "\t\t << (IntList() %4);\n\n") + " << (IntList() %3)\n" + " << (RealList()%4);\n\n") .arg(strCurve) .arg(strCurve) .arg(strInputs) @@ -406,13 +582,15 @@ void tst_QEasingCurve::valueForProgress() #else QFETCH(int, type); QFETCH(IntList, at); - QFETCH(IntList, expected); + QFETCH(RealList, expected); QEasingCurve curve((QEasingCurve::Type)type); for (int i = 0; i < at.count(); ++i) { qreal ease = curve.valueForProgress(at.at(i)/qreal(100)); - int ex = expected.at(i); - QCOMPARE(int(100*ease), ex); + // converting ease to 4 precision qreal to match the generated samples + qreal easeConv = qreal(QString().setNum(ease, 'g', 4).toDouble()); + qreal ex = expected.at(i); + QVERIFY(qFuzzyCompare(easeConv, ex)); } #endif } -- cgit v0.12 From 289befd1bce5b47c48887d1fe23fb912b60a8e56 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 14:42:59 +0200 Subject: add some edge case tests for QStateMachine::start() & stop() --- tests/auto/qstatemachine/tst_qstatemachine.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index 40c01bd..8354d03 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -2092,6 +2092,9 @@ void tst_QStateMachine::startAndStop() QCOMPARE(machine.configuration().count(), 1); QVERIFY(machine.configuration().contains(s1)); + QTest::ignoreMessage(QtWarningMsg, "QStateMachine::start(): already running"); + machine.start(); + machine.stop(); QTRY_COMPARE(machine.isRunning(), false); QTRY_COMPARE(stoppedSpy.count(), 1); @@ -2100,6 +2103,11 @@ void tst_QStateMachine::startAndStop() QCOMPARE(machine.configuration().count(), 1); QVERIFY(machine.configuration().contains(s1)); + + machine.start(); + machine.stop(); + QTRY_COMPARE(startedSpy.count(), 2); + QCOMPARE(stoppedSpy.count(), 2); } void tst_QStateMachine::targetStateWithNoParent() -- cgit v0.12 From fbab99479f83c4e51e4a28fd088a5f12f19dbf15 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 14:43:36 +0200 Subject: add qstatemachine autotest to auto.pro --- tests/auto/auto.pro | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro index 38fa380..27e3c74 100644 --- a/tests/auto/auto.pro +++ b/tests/auto/auto.pro @@ -295,6 +295,7 @@ SUBDIRS += _networkselftest \ qstandarditem \ qstandarditemmodel \ qstate \ + qstatemachine \ qstatusbar \ qstl \ qstring \ -- cgit v0.12 From 751e0f1b70cb0c80e88f99e5137329d6f4b76562 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Fri, 22 May 2009 14:58:06 +0200 Subject: qdoc: Moved some qdoc comments into the .cpp file common to all packages. Task-number: 252494 --- src/corelib/io/qfsfileengine.cpp | 113 +++++++++++++++++++++++++++++++++++ src/corelib/io/qfsfileengine_win.cpp | 83 ------------------------- 2 files changed, 113 insertions(+), 83 deletions(-) diff --git a/src/corelib/io/qfsfileengine.cpp b/src/corelib/io/qfsfileengine.cpp index 61ea7cc..99c1909 100644 --- a/src/corelib/io/qfsfileengine.cpp +++ b/src/corelib/io/qfsfileengine.cpp @@ -868,6 +868,119 @@ bool QFSFileEngine::supportsExtension(Extension extension) const return false; } +/*! \fn bool QFSFileEngine::caseSensitive() const + Returns true for Windows, false for Unix. +*/ + +/*! \fn bool QFSFileEngine::copy(const QString ©Name) + + For windows, copy the file to file \a copyName. + + Not implemented for Unix. +*/ + +/*! \fn QString QFSFileEngine::currentPath(const QString &fileName) + For Unix, returns the current working directory for the file + engine. + + For Windows, returns the canonicalized form of the current path used + by the file engine for the drive specified by \a fileName. On + Windows, each drive has its own current directory, so a different + path is returned for file names that include different drive names + (e.g. A: or C:). + + \sa setCurrentPath() +*/ + +/*! \fn QFileInfoList QFSFileEngine::drives() + For Windows, returns the list of drives in the file system as a list + of QFileInfo objects. On unix, Mac OS X and Windows CE, only the + root path is returned. On Windows, this function returns all drives + (A:\, C:\, D:\, etc.). + + For Unix, the list contains just the root path "/". +*/ + +/*! \fn QString QFSFileEngine::fileName(FileName file) const + \reimp +*/ + +/*! \fn QDateTime QFSFileEngine::fileTime(FileTime time) const + \reimp +*/ + +/*! \fn QString QFSFileEngine::homePath() + Returns the home path of the current user. + + \sa rootPath() +*/ + +/*! \fn bool QFSFileEngine::isRelativePath() const + \reimp +*/ + +/*! \fn bool QFSFileEngine::link(const QString &newName) + + Creates a link from the file currently specified by fileName() to + \a newName. What a link is depends on the underlying filesystem + (be it a shortcut on Windows or a symbolic link on Unix). Returns + true if successful; otherwise returns false. +*/ + +/*! \fn bool QFSFileEngine::mkdir(const QString &name, bool createParentDirectories) const + \reimp +*/ + +/*! \fn uint QFSFileEngine::ownerId(FileOwner own) const + In Unix, if stat() is successful, the \c uid is returned if + \a own is the owner. Otherwise the \c gid is returned. If stat() + is unsuccessful, -2 is reuturned. + + For Windows, -2 is always returned. +*/ + +/*! \fn QString QFSFileEngine::owner() const + \reimp +*/ + +/*! \fn bool QFSFileEngine::remove() + \reimp +*/ + +/*! \fn bool QFSFileEngine::rename(const QString &newName) + \reimp +*/ + +/*! \fn bool QFSFileEngine::rmdir(const QString &name, bool recurseParentDirectories) const + \reimp +*/ + +/*! \fn QString QFSFileEngine::rootPath() + Returns the root path. + + \sa homePath() +*/ + +/*! \fn bool QFSFileEngine::setCurrentPath(const QString &path) + Sets the current path (e.g., for QDir), to \a path. Returns true if the + new path exists; otherwise this function does nothing, and returns false. + + \sa currentPath() +*/ + +/*! \fn bool QFSFileEngine::setPermissions(uint perms) + \reimp +*/ + +/*! \fn bool QFSFileEngine::setSize(qint64 size) + \reimp +*/ + +/*! \fn QString QFSFileEngine::tempPath() + Returns the temporary path (i.e., a path in which it is safe + to store temporary files). +*/ + QT_END_NAMESPACE #endif // QT_NO_FSFILEENGINE diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp index 63506c2..b22d6c7 100644 --- a/src/corelib/io/qfsfileengine_win.cpp +++ b/src/corelib/io/qfsfileengine_win.cpp @@ -946,9 +946,6 @@ bool QFSFileEnginePrivate::nativeIsSequential() const return false; } -/*! - \reimp -*/ bool QFSFileEngine::remove() { Q_D(QFSFileEngine); @@ -959,9 +956,6 @@ bool QFSFileEngine::remove() }); } -/*! - \reimp -*/ bool QFSFileEngine::copy(const QString ©Name) { Q_D(QFSFileEngine); @@ -974,9 +968,6 @@ bool QFSFileEngine::copy(const QString ©Name) }); } -/*! - \reimp -*/ bool QFSFileEngine::rename(const QString &newName) { Q_D(QFSFileEngine); @@ -1017,9 +1008,6 @@ static inline bool mkDir(const QString &path) }); } -/*! - \reimp -*/ static inline bool rmDir(const QString &path) { QT_WA({ @@ -1029,9 +1017,6 @@ static inline bool rmDir(const QString &path) }); } -/*! - \reimp -*/ static inline bool isDirPath(const QString &dirPath, bool *existed) { QString path = dirPath; @@ -1054,9 +1039,6 @@ static inline bool isDirPath(const QString &dirPath, bool *existed) return fileAttrib & FILE_ATTRIBUTE_DIRECTORY; } -/*! - \reimp -*/ bool QFSFileEngine::mkdir(const QString &name, bool createParentDirectories) const { QString dirName = name; @@ -1097,9 +1079,6 @@ bool QFSFileEngine::mkdir(const QString &name, bool createParentDirectories) con return mkDir(name); } -/*! - \reimp -*/ bool QFSFileEngine::rmdir(const QString &name, bool recurseParentDirectories) const { QString dirName = name; @@ -1120,20 +1099,11 @@ bool QFSFileEngine::rmdir(const QString &name, bool recurseParentDirectories) co return rmDir(name); } -/*! - \reimp -*/ bool QFSFileEngine::caseSensitive() const { return false; } -/*! - Sets the current path (e.g., for QDir), to \a path. Returns true if the - new path exists; otherwise this function does nothing, and returns false. - - \sa currentPath() -*/ bool QFSFileEngine::setCurrentPath(const QString &path) { if (!QDir(path).exists()) @@ -1153,16 +1123,6 @@ bool QFSFileEngine::setCurrentPath(const QString &path) #endif } -/*! - Returns the canonicalized form of the current path used by the file - engine for the drive specified by \a fileName. - - On Windows, each drive has its own current directory, so a different - path is returned for file names that include different drive names - (e.g. A: or C:). - - \sa setCurrentPath() -*/ QString QFSFileEngine::currentPath(const QString &fileName) { #if !defined(Q_OS_WINCE) @@ -1219,11 +1179,6 @@ QString QFSFileEngine::currentPath(const QString &fileName) #endif } -/*! - Returns the home path of the current user. - - \sa rootPath() -*/ QString QFSFileEngine::homePath() { QString ret; @@ -1277,11 +1232,6 @@ QString QFSFileEngine::homePath() return QDir::fromNativeSeparators(ret); } -/*! - Returns the root path. - - \sa homePath() -*/ QString QFSFileEngine::rootPath() { #if defined(Q_OS_WINCE) @@ -1299,10 +1249,6 @@ QString QFSFileEngine::rootPath() return ret; } -/*! - Returns the temporary path (i.e., a path in which it is safe to store - temporary files). -*/ QString QFSFileEngine::tempPath() { QString ret; @@ -1330,11 +1276,6 @@ QString QFSFileEngine::tempPath() return ret; } -/*! - Returns the list of drives in the file system as a list of QFileInfo - objects. On unix, Mac OS X and Windows CE, only the root path is returned. - On Windows, this function returns all drives (A:\, C:\, D:\, etc.). -*/ QFileInfoList QFSFileEngine::drives() { QFileInfoList ret; @@ -1556,9 +1497,6 @@ QString QFSFileEnginePrivate::getLink() const return readLink(filePath); } -/*! - \reimp -*/ bool QFSFileEngine::link(const QString &newName) { #if !defined(Q_OS_WINCE) @@ -1816,9 +1754,6 @@ QAbstractFileEngine::FileFlags QFSFileEngine::fileFlags(QAbstractFileEngine::Fil return ret; } -/*! - \reimp -*/ QString QFSFileEngine::fileName(FileName file) const { Q_D(const QFSFileEngine); @@ -1912,9 +1847,6 @@ QString QFSFileEngine::fileName(FileName file) const return d->filePath; } -/*! - \reimp -*/ bool QFSFileEngine::isRelativePath() const { Q_D(const QFSFileEngine); @@ -1924,18 +1856,12 @@ bool QFSFileEngine::isRelativePath() const || (d->filePath.at(0) == QLatin1Char('/') && d->filePath.at(1) == QLatin1Char('/'))))); // drive, e.g. a: } -/*! - \reimp -*/ uint QFSFileEngine::ownerId(FileOwner /*own*/) const { static const uint nobodyID = (uint) -2; return nobodyID; } -/*! - \reimp -*/ QString QFSFileEngine::owner(FileOwner own) const { #if !defined(QT_NO_LIBRARY) @@ -1974,9 +1900,6 @@ QString QFSFileEngine::owner(FileOwner own) const return QString(QLatin1String("")); } -/*! - \reimp -*/ bool QFSFileEngine::setPermissions(uint perms) { Q_D(QFSFileEngine); @@ -2003,9 +1926,6 @@ bool QFSFileEngine::setPermissions(uint perms) return ret; } -/*! - \reimp -*/ bool QFSFileEngine::setSize(qint64 size) { Q_D(QFSFileEngine); @@ -2075,9 +1995,6 @@ static inline QDateTime fileTimeToQDateTime(const FILETIME *time) return ret; } -/*! - \reimp -*/ QDateTime QFSFileEngine::fileTime(FileTime time) const { Q_D(const QFSFileEngine); -- cgit v0.12 From 327d94ce8054718d0ce157604594e470e90d6cb4 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Fri, 22 May 2009 15:14:11 +0200 Subject: Fixes a potential crash when changing system palette with QGtkStyle The problem was that we installed an eventfilter regardless if the gtk symbols were defined or not. Instead we now initialize and check for the symbols before we install the filter. Task-number: 254342 Reviewed-by: ogoffart --- src/gui/styles/qgtkstyle.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index ca71da2..86653df 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -140,10 +140,7 @@ static const char * const dock_widget_restore_xpm[] = class QGtkStyleFilter : public QObject { public: - QGtkStyleFilter() { - qApp->installEventFilter(this); - } - + QGtkStyleFilter() {} private: bool eventFilter(QObject *obj, QEvent *e); }; @@ -167,7 +164,12 @@ class QGtkStylePrivate : public QCleanlooksStylePrivate public: QGtkStylePrivate() : QCleanlooksStylePrivate() - {} + { + QGtk::initGtkWidgets(); + if (QGtk::isThemeAvailable()) + qApp->installEventFilter(&filter); + + } QGtkStyleFilter filter; }; @@ -243,7 +245,6 @@ static QString uniqueName(const QString &key, const QStyleOption *option, const QGtkStyle::QGtkStyle() : QCleanlooksStyle(*new QGtkStylePrivate) { - QGtk::initGtkWidgets(); } /*! -- cgit v0.12 From 93106a55db7bd781cde889425912ebc4a277eb8f Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Wed, 22 Apr 2009 19:03:52 +0200 Subject: Fix syntax of the fcntl system call: this is not setsockopt Reviewed-By: Oswald Buddenhagen --- src/corelib/io/qfsfileengine_unix.cpp | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/corelib/io/qfsfileengine_unix.cpp b/src/corelib/io/qfsfileengine_unix.cpp index 18b92e2..459725c 100644 --- a/src/corelib/io/qfsfileengine_unix.cpp +++ b/src/corelib/io/qfsfileengine_unix.cpp @@ -273,9 +273,8 @@ qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len) int oldFlags = fcntl(QT_FILENO(fh), F_GETFL); for (int i = 0; i < 2; ++i) { // Unix: Make the underlying file descriptor non-blocking - int v = 1; if ((oldFlags & O_NONBLOCK) == 0) - fcntl(QT_FILENO(fh), F_SETFL, oldFlags | O_NONBLOCK, &v, sizeof(v)); + fcntl(QT_FILENO(fh), F_SETFL, oldFlags | O_NONBLOCK); // Cross platform stdlib read size_t read = 0; @@ -293,8 +292,7 @@ qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len) // Unix: Restore the blocking state of the underlying socket if ((oldFlags & O_NONBLOCK) == 0) { - int v = 1; - fcntl(QT_FILENO(fh), F_SETFL, oldFlags, &v, sizeof(v)); + fcntl(QT_FILENO(fh), F_SETFL, oldFlags); if (readBytes == 0) { int readByte = 0; do { @@ -311,8 +309,7 @@ qint64 QFSFileEnginePrivate::nativeRead(char *data, qint64 len) } // Unix: Restore the blocking state of the underlying socket if ((oldFlags & O_NONBLOCK) == 0) { - int v = 1; - fcntl(QT_FILENO(fh), F_SETFL, oldFlags, &v, sizeof(v)); + fcntl(QT_FILENO(fh), F_SETFL, oldFlags); } if (readBytes == 0 && !feof(fh)) { // if we didn't read anything and we're not at EOF, it must be an error -- cgit v0.12 From b50f191132580771b470d5804a0a6616fbc1873f Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 15:30:52 +0200 Subject: Don't use the time() function; use QTime instead time() is not available on all platforms. --- examples/animation/moveblocks/main.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/animation/moveblocks/main.cpp b/examples/animation/moveblocks/main.cpp index b00485e..d315112 100644 --- a/examples/animation/moveblocks/main.cpp +++ b/examples/animation/moveblocks/main.cpp @@ -41,7 +41,6 @@ #include #include -#include class StateSwitchEvent: public QEvent { @@ -288,7 +287,7 @@ int main(int argc, char **argv) window.resize(300, 300); window.show(); - qsrand(time(0)); + qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); return app.exec(); } -- cgit v0.12 From 74d54eeabcd648ee5100853299de8af5ac4b36f2 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 15:42:27 +0200 Subject: Make sure M_PI is defined It isn't on all platforms. --- examples/animation/stickman/stickman.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/animation/stickman/stickman.cpp b/examples/animation/stickman/stickman.cpp index e00ea41..a3b200c 100644 --- a/examples/animation/stickman/stickman.cpp +++ b/examples/animation/stickman/stickman.cpp @@ -48,6 +48,10 @@ #define _USE_MATH_DEFINES #include +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + static const int NodeCount = 16; static const qreal Coords[NodeCount * 2] = { 0.0, -150.0, // head, #0 -- cgit v0.12 From 049135667302482af66eeaf9a2323d5ee1551132 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 22 May 2009 15:42:31 +0200 Subject: Doc - updating the screenshot Reviewed-By: TrustMe --- doc/src/images/inputdialogs.png | Bin 4244 -> 30369 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/doc/src/images/inputdialogs.png b/doc/src/images/inputdialogs.png index 135c2f6..8bda185 100644 Binary files a/doc/src/images/inputdialogs.png and b/doc/src/images/inputdialogs.png differ -- cgit v0.12 From 24d798694b794732240e85fa65b958b8c97cbef5 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 16:19:21 +0200 Subject: make sure event transition is correctly unregistered/re-registered When the eventType or eventObject is changed while the state is active, the transition needs to be unregistered _before_ either property is changed, only _then_ can it be re-registered. --- src/corelib/statemachine/qeventtransition.cpp | 29 ++++++++++++++------------ src/corelib/statemachine/qeventtransition_p.h | 3 ++- tests/auto/qstatemachine/tst_qstatemachine.cpp | 13 ++++++++++++ 3 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/corelib/statemachine/qeventtransition.cpp b/src/corelib/statemachine/qeventtransition.cpp index 74eb577..f25d821 100644 --- a/src/corelib/statemachine/qeventtransition.cpp +++ b/src/corelib/statemachine/qeventtransition.cpp @@ -111,19 +111,20 @@ QEventTransitionPrivate *QEventTransitionPrivate::get(QEventTransition *q) return q->d_func(); } -void QEventTransitionPrivate::invalidate() +void QEventTransitionPrivate::unregister() { Q_Q(QEventTransition); - if (registered) { - QState *source = sourceState(); - QStatePrivate *source_d = QStatePrivate::get(source); - QStateMachinePrivate *mach = QStateMachinePrivate::get(source_d->machine()); - if (mach) { - mach->unregisterEventTransition(q); - if (mach->configuration.contains(source)) - mach->registerEventTransition(q); - } - } + if (!registered || !machine()) + return; + QStateMachinePrivate::get(machine())->unregisterEventTransition(q); +} + +void QEventTransitionPrivate::maybeRegister() +{ + Q_Q(QEventTransition); + if (!machine() || !machine()->configuration().contains(sourceState())) + return; + QStateMachinePrivate::get(machine())->registerEventTransition(q); } /*! @@ -223,8 +224,9 @@ void QEventTransition::setEventType(QEvent::Type type) Q_D(QEventTransition); if (d->eventType == type) return; + d->unregister(); d->eventType = type; - d->invalidate(); + d->maybeRegister(); } /*! @@ -245,8 +247,9 @@ void QEventTransition::setEventObject(QObject *object) Q_D(QEventTransition); if (d->object == object) return; + d->unregister(); d->object = object; - d->invalidate(); + d->maybeRegister(); } /*! diff --git a/src/corelib/statemachine/qeventtransition_p.h b/src/corelib/statemachine/qeventtransition_p.h index fca8c0d..600cec0 100644 --- a/src/corelib/statemachine/qeventtransition_p.h +++ b/src/corelib/statemachine/qeventtransition_p.h @@ -66,7 +66,8 @@ public: static QEventTransitionPrivate *get(QEventTransition *q); - void invalidate(); + void unregister(); + void maybeRegister(); bool registered; QObject *object; diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index 8354d03..a5070cb 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -1836,6 +1836,19 @@ void tst_QStateMachine::eventTransitions() QCoreApplication::processEvents(); QTest::mouseRelease(&button, Qt::LeftButton); QTRY_COMPARE(finishedSpy.count(), 2); + + machine.start(); + QCoreApplication::processEvents(); + trans->setEventType(QEvent::MouseButtonPress); + QTest::mousePress(&button, Qt::LeftButton); + QTRY_COMPARE(finishedSpy.count(), 3); + + QPushButton button2; + machine.start(); + QCoreApplication::processEvents(); + trans->setEventObject(&button2); + QTest::mousePress(&button2, Qt::LeftButton); + QTRY_COMPARE(finishedSpy.count(), 4); } for (int x = 0; x < 3; ++x) { QStateMachine machine; -- cgit v0.12 From 1602820bb4d2b13f843594194ace2186f4f72806 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 16:31:40 +0200 Subject: make sure signal transition is correctly unregistered/re-registered When the signal or senderObject is changed while the state is active, the transition needs to be unregistered _before_ either property is changed, only _then_ can it be re-registered. --- src/corelib/statemachine/qsignaltransition.cpp | 29 +++++++++++---------- src/corelib/statemachine/qsignaltransition_p.h | 3 ++- tests/auto/qstatemachine/tst_qstatemachine.cpp | 35 ++++++++++++++++++++------ 3 files changed, 45 insertions(+), 22 deletions(-) diff --git a/src/corelib/statemachine/qsignaltransition.cpp b/src/corelib/statemachine/qsignaltransition.cpp index 4caa917..9ffcb9c 100644 --- a/src/corelib/statemachine/qsignaltransition.cpp +++ b/src/corelib/statemachine/qsignaltransition.cpp @@ -118,19 +118,20 @@ QSignalTransitionPrivate *QSignalTransitionPrivate::get(QSignalTransition *q) return q->d_func(); } -void QSignalTransitionPrivate::invalidate() +void QSignalTransitionPrivate::unregister() { Q_Q(QSignalTransition); - if (signalIndex != -1) { - QState *source = sourceState(); - QStatePrivate *source_d = QStatePrivate::get(source); - QStateMachinePrivate *mach = QStateMachinePrivate::get(source_d->machine()); - if (mach) { - mach->unregisterSignalTransition(q); - if (mach->configuration.contains(source)) - mach->registerSignalTransition(q); - } - } + if ((signalIndex == -1) || !machine()) + return; + QStateMachinePrivate::get(machine())->unregisterSignalTransition(q); +} + +void QSignalTransitionPrivate::maybeRegister() +{ + Q_Q(QSignalTransition); + if (!machine() || !machine()->configuration().contains(sourceState())) + return; + QStateMachinePrivate::get(machine())->registerSignalTransition(q); } /*! @@ -193,8 +194,9 @@ void QSignalTransition::setSenderObject(QObject *sender) Q_D(QSignalTransition); if (sender == d->sender) return; + d->unregister(); d->sender = sender; - d->invalidate(); + d->maybeRegister(); } /*! @@ -214,8 +216,9 @@ void QSignalTransition::setSignal(const QByteArray &signal) Q_D(QSignalTransition); if (signal == d->signal) return; + d->unregister(); d->signal = signal; - d->invalidate(); + d->maybeRegister(); } /*! diff --git a/src/corelib/statemachine/qsignaltransition_p.h b/src/corelib/statemachine/qsignaltransition_p.h index a23e58c..339de63 100644 --- a/src/corelib/statemachine/qsignaltransition_p.h +++ b/src/corelib/statemachine/qsignaltransition_p.h @@ -66,7 +66,8 @@ public: static QSignalTransitionPrivate *get(QSignalTransition *q); - void invalidate(); + void unregister(); + void maybeRegister(); QObject *sender; QByteArray signal; diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index a5070cb..6de7e1a 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -1666,14 +1666,12 @@ void tst_QStateMachine::signalTransitions() QTest::ignoreMessage(QtWarningMsg, "QState::addTransition: no such signal SignalEmitter::noSuchSignal()"); QCOMPARE(s0->addTransition(&emitter, SIGNAL(noSuchSignal()), s1), (QObject*)0); - { - QSignalTransition *trans = s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), s1); - QVERIFY(trans != 0); - QCOMPARE(trans->sourceState(), s0); - QCOMPARE(trans->targetState(), (QAbstractState*)s1); - QCOMPARE(trans->senderObject(), (QObject*)&emitter); - QCOMPARE(trans->signal(), QByteArray(SIGNAL(signalWithNoArg()))); - } + QSignalTransition *trans = s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), s1); + QVERIFY(trans != 0); + QCOMPARE(trans->sourceState(), s0); + QCOMPARE(trans->targetState(), (QAbstractState*)s1); + QCOMPARE(trans->senderObject(), (QObject*)&emitter); + QCOMPARE(trans->signal(), QByteArray(SIGNAL(signalWithNoArg()))); QSignalSpy finishedSpy(&machine, SIGNAL(finished())); machine.setInitialState(s0); @@ -1685,6 +1683,27 @@ void tst_QStateMachine::signalTransitions() QTRY_COMPARE(finishedSpy.count(), 1); emitter.emitSignalWithNoArg(); + + trans->setSignal(SIGNAL(signalWithIntArg(int))); + QCOMPARE(trans->signal(), QByteArray(SIGNAL(signalWithIntArg(int)))); + machine.start(); + QCoreApplication::processEvents(); + emitter.emitSignalWithIntArg(123); + QTRY_COMPARE(finishedSpy.count(), 2); + + machine.start(); + QCoreApplication::processEvents(); + trans->setSignal(SIGNAL(signalWithNoArg())); + QCOMPARE(trans->signal(), QByteArray(SIGNAL(signalWithNoArg()))); + emitter.emitSignalWithNoArg(); + QTRY_COMPARE(finishedSpy.count(), 3); + + SignalEmitter emitter2; + machine.start(); + QCoreApplication::processEvents(); + trans->setSenderObject(&emitter2); + emitter2.emitSignalWithNoArg(); + QTRY_COMPARE(finishedSpy.count(), 4); } { QStateMachine machine; -- cgit v0.12 From c6d683eefc76b6bb5be465533c5fead97fedcdc4 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Fri, 22 May 2009 16:40:58 +0200 Subject: Fix compilation on Solaris for animation API. Reviewed-by: thierry --- src/corelib/animation/qvariantanimation.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/animation/qvariantanimation.h b/src/corelib/animation/qvariantanimation.h index 5b90930..3ae172f 100644 --- a/src/corelib/animation/qvariantanimation.h +++ b/src/corelib/animation/qvariantanimation.h @@ -117,7 +117,7 @@ private: }; template -static void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) { +void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) { QVariantAnimation::registerInterpolator(reinterpret_cast(func), qMetaTypeId()); } -- cgit v0.12 From d19ed9d337b79a3dc88690db66a8ea8d4482cddd Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 16:41:41 +0200 Subject: add tests for multiple signal/event transitions from same source --- tests/auto/qstatemachine/tst_qstatemachine.cpp | 68 ++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index 6de7e1a..c01d077 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -1815,6 +1815,43 @@ void tst_QStateMachine::signalTransitions() QCOMPARE(machine.configuration().size(), 1); QVERIFY(machine.configuration().contains(s1)); } + // multiple signal transitions from same source + { + QStateMachine machine; + SignalEmitter emitter; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + s0->addTransition(&emitter, SIGNAL(signalWithNoArg()), s1); + QFinalState *s2 = new QFinalState(machine.rootState()); + s0->addTransition(&emitter, SIGNAL(signalWithIntArg(int)), s2); + QFinalState *s3 = new QFinalState(machine.rootState()); + s0->addTransition(&emitter, SIGNAL(signalWithStringArg(QString)), s3); + + QSignalSpy startedSpy(&machine, SIGNAL(started())); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + + machine.start(); + QTRY_COMPARE(startedSpy.count(), 1); + emitter.emitSignalWithNoArg(); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + machine.start(); + QTRY_COMPARE(startedSpy.count(), 2); + emitter.emitSignalWithIntArg(123); + QTRY_COMPARE(finishedSpy.count(), 2); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s2)); + + machine.start(); + QTRY_COMPARE(startedSpy.count(), 3); + emitter.emitSignalWithStringArg("hello"); + QTRY_COMPARE(finishedSpy.count(), 3); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s3)); + } } void tst_QStateMachine::eventTransitions() @@ -2024,6 +2061,37 @@ void tst_QStateMachine::eventTransitions() QCOMPARE(machine.configuration().size(), 1); QVERIFY(machine.configuration().contains(s1)); } + // multiple event transitions from same source + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + QFinalState *s2 = new QFinalState(machine.rootState()); + QEventTransition *t0 = new QEventTransition(&button, QEvent::MouseButtonPress); + t0->setTargetState(s1); + s0->addTransition(t0); + QEventTransition *t1 = new QEventTransition(&button, QEvent::MouseButtonRelease); + t1->setTargetState(s2); + s0->addTransition(t1); + + QSignalSpy startedSpy(&machine, SIGNAL(started())); + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + + machine.start(); + QTRY_COMPARE(startedSpy.count(), 1); + QTest::mousePress(&button, Qt::LeftButton); + QTRY_COMPARE(finishedSpy.count(), 1); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s1)); + + machine.start(); + QTRY_COMPARE(startedSpy.count(), 2); + QTest::mouseRelease(&button, Qt::LeftButton); + QTRY_COMPARE(finishedSpy.count(), 2); + QCOMPARE(machine.configuration().size(), 1); + QVERIFY(machine.configuration().contains(s2)); + } } void tst_QStateMachine::historyStates() -- cgit v0.12 From 5ae1ccd2b12fcbc55fa2d14c39d8da3f4440a11d Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 16:50:03 +0200 Subject: test what happens when changing to an invalid signal while state is active --- tests/auto/qstatemachine/tst_qstatemachine.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index c01d077..76c5de1 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -1704,6 +1704,12 @@ void tst_QStateMachine::signalTransitions() trans->setSenderObject(&emitter2); emitter2.emitSignalWithNoArg(); QTRY_COMPARE(finishedSpy.count(), 4); + + machine.start(); + QCoreApplication::processEvents(); + QTest::ignoreMessage(QtWarningMsg, "QSignalTransition: no such signal: SignalEmitter::noSuchSignal()"); + trans->setSignal(SIGNAL(noSuchSignal())); + QCOMPARE(trans->signal(), QByteArray(SIGNAL(noSuchSignal()))); } { QStateMachine machine; -- cgit v0.12 From fc7a43cceba63b79a40183334ab97527483113e3 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Fri, 22 May 2009 16:55:28 +0200 Subject: Fix compilation breakage on Windows caused by 6c1d7e57. On Windows, QT_NO_IPV6 isn't defined, but the necessary includes were missing. So #include winsock2.h and also use our own structures. Reviewed-By: Trust Me --- src/network/socket/qnativesocketengine_p.h | 36 +++++++++++++++++++++---- src/network/socket/qnativesocketengine_unix.cpp | 2 +- src/network/socket/qnativesocketengine_win.cpp | 35 ------------------------ 3 files changed, 32 insertions(+), 41 deletions(-) diff --git a/src/network/socket/qnativesocketengine_p.h b/src/network/socket/qnativesocketengine_p.h index 825c333..eb031d3 100644 --- a/src/network/socket/qnativesocketengine_p.h +++ b/src/network/socket/qnativesocketengine_p.h @@ -56,7 +56,9 @@ #include "QtNetwork/qhostaddress.h" #include "private/qabstractsocketengine_p.h" #ifndef Q_OS_WIN -#include "qplatformdefs.h" +# include "qplatformdefs.h" +#else +# include #endif QT_BEGIN_NAMESPACE @@ -90,13 +92,37 @@ static inline int qt_socket_socket(int domain, int type, int protocol) #endif +// Use our own defines and structs which we know are correct +# define QT_SS_MAXSIZE 128 +# define QT_SS_ALIGNSIZE (sizeof(qint64)) +# define QT_SS_PAD1SIZE (QT_SS_ALIGNSIZE - sizeof (short)) +# define QT_SS_PAD2SIZE (QT_SS_MAXSIZE - (sizeof (short) + QT_SS_PAD1SIZE + QT_SS_ALIGNSIZE)) +struct qt_sockaddr_storage { + short ss_family; + char __ss_pad1[QT_SS_PAD1SIZE]; + qint64 __ss_align; + char __ss_pad2[QT_SS_PAD2SIZE]; +}; + +// sockaddr_in6 size changed between old and new SDK +// Only the new version is the correct one, so always +// use this structure. +struct qt_in6_addr { + quint8 qt_s6_addr[16]; +}; +struct qt_sockaddr_in6 { + short sin6_family; /* AF_INET6 */ + quint16 sin6_port; /* Transport level port number */ + quint32 sin6_flowinfo; /* IPv6 flow information */ + struct qt_in6_addr sin6_addr; /* IPv6 address */ + quint32 sin6_scope_id; /* set of interfaces for a scope */ +}; + union qt_sockaddr { sockaddr a; sockaddr_in a4; -#if !defined(QT_NO_IPV6) - sockaddr_in6 a6; -#endif - sockaddr_storage storage; + qt_sockaddr_in6 a6; + qt_sockaddr_storage storage; }; class QNativeSocketEnginePrivate; diff --git a/src/network/socket/qnativesocketengine_unix.cpp b/src/network/socket/qnativesocketengine_unix.cpp index 2b11e8e..75b5a64 100644 --- a/src/network/socket/qnativesocketengine_unix.cpp +++ b/src/network/socket/qnativesocketengine_unix.cpp @@ -119,7 +119,7 @@ static inline void qt_socket_getPortAndAddress(const qt_sockaddr *s, quint16 *po #if !defined(QT_NO_IPV6) if (s->a.sa_family == AF_INET6) { Q_IPV6ADDR tmp; - memcpy(&tmp, &s->a6.sin6_addr.s6_addr, sizeof(tmp)); + memcpy(&tmp, &s->a6.sin6_addr, sizeof(tmp)); if (addr) { QHostAddress tmpAddress; tmpAddress.setAddress(tmp); diff --git a/src/network/socket/qnativesocketengine_win.cpp b/src/network/socket/qnativesocketengine_win.cpp index d140be2..b08d7b0 100644 --- a/src/network/socket/qnativesocketengine_win.cpp +++ b/src/network/socket/qnativesocketengine_win.cpp @@ -149,41 +149,6 @@ static QByteArray qt_prettyDebug(const char *data, int len, int maxLength) #endif -#if !defined (QT_NO_IPV6) - -// Use our own defines and structs which we know are correct -# define QT_SS_MAXSIZE 128 -# define QT_SS_ALIGNSIZE (sizeof(__int64)) -# define QT_SS_PAD1SIZE (QT_SS_ALIGNSIZE - sizeof (short)) -# define QT_SS_PAD2SIZE (QT_SS_MAXSIZE - (sizeof (short) + QT_SS_PAD1SIZE + QT_SS_ALIGNSIZE)) -struct qt_sockaddr_storage { - short ss_family; - char __ss_pad1[QT_SS_PAD1SIZE]; - __int64 __ss_align; - char __ss_pad2[QT_SS_PAD2SIZE]; -}; - -// sockaddr_in6 size changed between old and new SDK -// Only the new version is the correct one, so always -// use this structure. -struct qt_in6_addr { - u_char qt_s6_addr[16]; -}; -typedef struct { - short sin6_family; /* AF_INET6 */ - u_short sin6_port; /* Transport level port number */ - u_long sin6_flowinfo; /* IPv6 flow information */ - struct qt_in6_addr sin6_addr; /* IPv6 address */ - u_long sin6_scope_id; /* set of interfaces for a scope */ -} qt_sockaddr_in6; - -#else - -typedef void * qt_sockaddr_in6 ; - - -#endif - #ifndef AF_INET6 #define AF_INET6 23 /* Internetwork Version 6 */ #endif -- cgit v0.12 From 73f953dce2c184c36476c3412880a7aee10ef638 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 22 May 2009 17:22:05 +0200 Subject: add various tests Trying to get coverage up to 100% --- tests/auto/qstatemachine/tst_qstatemachine.cpp | 104 ++++++++++++++++++++----- 1 file changed, 86 insertions(+), 18 deletions(-) diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index 76c5de1..768a683 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -81,6 +81,24 @@ static int globalTick; QCoreApplication::exec(); \ } +class SignalEmitter : public QObject +{ +Q_OBJECT + public: + SignalEmitter(QObject *parent = 0) + : QObject(parent) {} + void emitSignalWithNoArg() + { emit signalWithNoArg(); } + void emitSignalWithIntArg(int arg) + { emit signalWithIntArg(arg); } + void emitSignalWithStringArg(const QString &arg) + { emit signalWithStringArg(arg); } +Q_SIGNALS: + void signalWithNoArg(); + void signalWithIntArg(int); + void signalWithStringArg(const QString &); +}; + class tst_QStateMachine : public QObject { Q_OBJECT @@ -1045,6 +1063,20 @@ void tst_QStateMachine::addAndRemoveState() QTest::ignoreMessage(QtWarningMsg, "QStateMachine::removeState: cannot remove null state"); machine.removeState(0); + { + QStateMachine machine2; + { + char warning[256]; + sprintf(warning, "QStateMachine::removeState: state %p's machine (%p) is different from this machine (%p)", + machine2.rootState(), &machine2, &machine); + QTest::ignoreMessage(QtWarningMsg, warning); + machine.removeState(machine2.rootState()); + } + // ### check this behavior + machine.addState(machine2.rootState()); + QCOMPARE(machine2.rootState()->parent(), (QObject*)machine.rootState()); + } + delete s1; delete s2; // ### how to deal with this? @@ -1397,6 +1429,44 @@ void tst_QStateMachine::assignPropertyWithAnimation() QCOMPARE(obj.property("foo").toInt(), 321); QCOMPARE(obj.property("bar").toInt(), 789); } + // Aborted animation + { + QStateMachine machine; + SignalEmitter emitter; + QObject obj; + obj.setProperty("foo", 321); + obj.setProperty("bar", 654); + QState *group = new QState(machine.rootState()); + QState *s1 = new QState(group); + group->setInitialState(s1); + s1->assignProperty(&obj, "foo", 123); + QState *s2 = new QState(group); + s2->assignProperty(&obj, "foo", 456); + s2->assignProperty(&obj, "bar", 789); + QAbstractTransition *trans = s1->addTransition(&emitter, SIGNAL(signalWithNoArg()), s2); + QPropertyAnimation anim(&obj, "foo"); + anim.setDuration(8000); + trans->addAnimation(&anim); + QPropertyAnimation anim2(&obj, "bar"); + anim2.setDuration(8000); + trans->addAnimation(&anim2); + QState *s3 = new QState(group); + s3->assignProperty(&obj, "foo", 911); + s2->addTransition(&emitter, SIGNAL(signalWithNoArg()), s3); + + machine.setInitialState(group); + machine.start(); + QTRY_COMPARE(machine.configuration().contains(s1), true); + QSignalSpy polishedSpy(s2, SIGNAL(polished())); + emitter.emitSignalWithNoArg(); + QTRY_COMPARE(machine.configuration().contains(s2), true); + QVERIFY(polishedSpy.isEmpty()); + emitter.emitSignalWithNoArg(); // will cause animations from s1-->s2 to abort + QTRY_COMPARE(machine.configuration().contains(s3), true); + QVERIFY(polishedSpy.isEmpty()); + QCOMPARE(obj.property("foo").toInt(), 911); + QCOMPARE(obj.property("bar").toInt(), 789); + } } struct StringEvent : public QEvent @@ -1606,24 +1676,6 @@ void tst_QStateMachine::allSourceToTargetConfigurations() QTRY_COMPARE(finishedSpy.count(), 1); } -class SignalEmitter : public QObject -{ -Q_OBJECT - public: - SignalEmitter(QObject *parent = 0) - : QObject(parent) {} - void emitSignalWithNoArg() - { emit signalWithNoArg(); } - void emitSignalWithIntArg(int arg) - { emit signalWithIntArg(arg); } - void emitSignalWithStringArg(const QString &arg) - { emit signalWithStringArg(arg); } -Q_SIGNALS: - void signalWithNoArg(); - void signalWithIntArg(int); - void signalWithStringArg(const QString &); -}; - class TestSignalTransition : public QSignalTransition { public: @@ -2098,6 +2150,22 @@ void tst_QStateMachine::eventTransitions() QCOMPARE(machine.configuration().size(), 1); QVERIFY(machine.configuration().contains(s2)); } + // custom event + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + + QEventTransition *trans = new QEventTransition(&button, QEvent::Type(QEvent::User+1)); + trans->setTargetState(s1); + s0->addTransition(trans); + + QSignalSpy startedSpy(&machine, SIGNAL(started())); + machine.setInitialState(s0); + machine.start(); + QTest::ignoreMessage(QtWarningMsg, "QObject event transitions are not supported for custom types"); + QTRY_COMPARE(startedSpy.count(), 1); + } } void tst_QStateMachine::historyStates() -- cgit v0.12 From 701bdcbc8b7751834f6d24844bcb91a23cbdc409 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Fri, 22 May 2009 15:48:23 +0200 Subject: Pressing enter in a QPlainTextEdit embedded on a itemview should insert a newline Do the same special case as for QTextEdit (yes, this is a pitty that we have special cases like that Reviewed-by: Thierry Task-number: 252532 --- src/gui/itemviews/qitemdelegate.cpp | 3 +- src/gui/itemviews/qstyleditemdelegate.cpp | 3 +- tests/auto/qitemdelegate/tst_qitemdelegate.cpp | 78 ++++++++++++++++++++++++++ 3 files changed, 82 insertions(+), 2 deletions(-) diff --git a/src/gui/itemviews/qitemdelegate.cpp b/src/gui/itemviews/qitemdelegate.cpp index 3b7eb2d..a748199 100644 --- a/src/gui/itemviews/qitemdelegate.cpp +++ b/src/gui/itemviews/qitemdelegate.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -1194,7 +1195,7 @@ bool QItemDelegate::eventFilter(QObject *object, QEvent *event) case Qt::Key_Enter: case Qt::Key_Return: #ifndef QT_NO_TEXTEDIT - if (qobject_cast(editor)) + if (qobject_cast(editor) || qobject_cast(editor)) return false; // don't filter enter key events for QTextEdit // We want the editor to be able to process the key press // before committing the data (e.g. so it can do diff --git a/src/gui/itemviews/qstyleditemdelegate.cpp b/src/gui/itemviews/qstyleditemdelegate.cpp index be0971b..7f2c8ed 100644 --- a/src/gui/itemviews/qstyleditemdelegate.cpp +++ b/src/gui/itemviews/qstyleditemdelegate.cpp @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #include @@ -646,7 +647,7 @@ bool QStyledItemDelegate::eventFilter(QObject *object, QEvent *event) case Qt::Key_Enter: case Qt::Key_Return: #ifndef QT_NO_TEXTEDIT - if (qobject_cast(editor)) + if (qobject_cast(editor) || qobject_cast(editor)) return false; // don't filter enter key events for QTextEdit // We want the editor to be able to process the key press // before committing the data (e.g. so it can do diff --git a/tests/auto/qitemdelegate/tst_qitemdelegate.cpp b/tests/auto/qitemdelegate/tst_qitemdelegate.cpp index 27741e0..615ac01 100644 --- a/tests/auto/qitemdelegate/tst_qitemdelegate.cpp +++ b/tests/auto/qitemdelegate/tst_qitemdelegate.cpp @@ -59,6 +59,8 @@ #include #include +#include +#include Q_DECLARE_METATYPE(QAbstractItemDelegate::EndEditHint) @@ -226,6 +228,8 @@ private slots: void decoration(); void editorEvent_data(); void editorEvent(); + void enterKey_data(); + void enterKey(); }; @@ -1048,6 +1052,80 @@ void tst_QItemDelegate::editorEvent() QCOMPARE(index.data(Qt::CheckStateRole).toInt(), expectedCheckState); } +void tst_QItemDelegate::enterKey_data() +{ + QTest::addColumn("widget"); + QTest::addColumn("key"); + QTest::addColumn("expectedFocus"); + + QTest::newRow("lineedit enter") << 1 << int(Qt::Key_Enter) << false; + QTest::newRow("textedit enter") << 2 << int(Qt::Key_Enter) << true; + QTest::newRow("plaintextedit enter") << 3 << int(Qt::Key_Enter) << true; + QTest::newRow("plaintextedit return") << 3 << int(Qt::Key_Return) << true; + QTest::newRow("plaintextedit tab") << 3 << int(Qt::Key_Tab) << false; + QTest::newRow("lineedit tab") << 1 << int(Qt::Key_Tab) << false; +} + +void tst_QItemDelegate::enterKey() +{ + QFETCH(int, widget); + QFETCH(int, key); + QFETCH(bool, expectedFocus); + + QStandardItemModel model; + model.appendRow(new QStandardItem()); + + QListView view; + view.setModel(&model); + view.show(); + QApplication::setActiveWindow(&view); + view.setFocus(); + QTest::qWait(30); + + struct TestDelegate : public QItemDelegate + { + int widgetType; + virtual QWidget* createEditor(QWidget* parent, const QStyleOptionViewItem& /*option*/, const QModelIndex& /*index*/) const + { + QWidget *editor = 0; + switch(widgetType) { + case 1: + editor = new QLineEdit(parent); + break; + case 2: + editor = new QTextEdit(parent); + break; + case 3: + editor = new QPlainTextEdit(parent); + break; + } + editor->setObjectName(QString::fromLatin1("TheEditor")); + return editor; + } + } delegate; + + delegate.widgetType = widget; + + view.setItemDelegate(&delegate); + QModelIndex index = model.index(0, 0); + view.setCurrentIndex(index); // the editor will only selectAll on the current index + view.edit(index); + QTest::qWait(30); + + QList lineEditors = qFindChildren(view.viewport(), QString::fromLatin1("TheEditor")); + QCOMPARE(lineEditors.count(), 1); + + QWidget *editor = lineEditors.at(0); + QCOMPARE(editor->hasFocus(), true); + + QTest::keyClick(editor, Qt::Key(key)); + QApplication::processEvents(); + + QCOMPARE(editor->hasFocus(), expectedFocus); +} + + + // ### _not_ covered: // editing with a custom editor factory -- cgit v0.12 From 37b0711beb909f3d0bd6f2420aa44bc49e786cd5 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Fri, 22 May 2009 17:47:01 +0200 Subject: Fix build on Solaris for qHash function in QPixmapCache. Reviewed-by:thierry --- src/gui/image/qpixmapcache.cpp | 2 +- src/gui/image/qpixmapcache_p.h | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gui/image/qpixmapcache.cpp b/src/gui/image/qpixmapcache.cpp index 810ce65..eb1ebd1 100644 --- a/src/gui/image/qpixmapcache.cpp +++ b/src/gui/image/qpixmapcache.cpp @@ -183,7 +183,7 @@ QT_BEGIN_INCLUDE_NAMESPACE #include "qpixmapcache.moc" QT_END_INCLUDE_NAMESPACE -static uint qHash(const QPixmapCache::Key &k) +uint qHash(const QPixmapCache::Key &k) { return qHash(QPMCache::get(k)->key); } diff --git a/src/gui/image/qpixmapcache_p.h b/src/gui/image/qpixmapcache_p.h index 5aa6eaf..a35e0d2 100644 --- a/src/gui/image/qpixmapcache_p.h +++ b/src/gui/image/qpixmapcache_p.h @@ -60,6 +60,8 @@ QT_BEGIN_NAMESPACE +uint qHash(const QPixmapCache::Key &k); + class QPixmapCache::KeyData { public: -- cgit v0.12 From bbf3361d42c85d9da712e0261ecc87d62a29e403 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Fri, 22 May 2009 18:13:46 +0200 Subject: Remove IRIX code. IRIX is no longer supported, so I won't bother fixing this part of the code. Reviewed-by: Oswald Buddenhagen --- src/corelib/io/qprocess_unix.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/corelib/io/qprocess_unix.cpp b/src/corelib/io/qprocess_unix.cpp index c39588c..b06e217 100644 --- a/src/corelib/io/qprocess_unix.cpp +++ b/src/corelib/io/qprocess_unix.cpp @@ -385,17 +385,10 @@ static void qt_create_pipe(int *pipe) qt_native_close(pipe[0]); if (pipe[1] != -1) qt_native_close(pipe[1]); -#ifdef Q_OS_IRIX - if (::socketpair(AF_UNIX, SOCK_STREAM, 0, pipe) == -1) { - qWarning("QProcessPrivate::createPipe: Cannot create pipe %p: %s", - pipe, qPrintable(qt_error_string(errno))); - } -#else if (::pipe(pipe) != 0) { qWarning("QProcessPrivate::createPipe: Cannot create pipe %p: %s", pipe, qPrintable(qt_error_string(errno))); } -#endif ::fcntl(pipe[0], F_SETFD, FD_CLOEXEC); ::fcntl(pipe[1], F_SETFD, FD_CLOEXEC); } -- cgit v0.12 From dacc8cb0b2abd5ec3e9603c9bcf5b8f489639404 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Fri, 22 May 2009 18:14:34 +0200 Subject: Reorganise the pipe creation code. Put all pipe creation calls together. Reviewed-by: Oswald Buddenhagen --- src/corelib/io/qprocess_unix.cpp | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/src/corelib/io/qprocess_unix.cpp b/src/corelib/io/qprocess_unix.cpp index b06e217..e87c314 100644 --- a/src/corelib/io/qprocess_unix.cpp +++ b/src/corelib/io/qprocess_unix.cpp @@ -580,29 +580,27 @@ void QProcessPrivate::startProcess() processManager()->start(); // Initialize pipes + if (!createChannel(stdinChannel) || + !createChannel(stdoutChannel) || + !createChannel(stderrChannel)) + return; qt_create_pipe(childStartedPipe); + qt_create_pipe(deathPipe); + ::fcntl(deathPipe[0], F_SETFD, FD_CLOEXEC); + ::fcntl(deathPipe[1], F_SETFD, FD_CLOEXEC); + if (threadData->eventDispatcher) { startupSocketNotifier = new QSocketNotifier(childStartedPipe[0], QSocketNotifier::Read, q); QObject::connect(startupSocketNotifier, SIGNAL(activated(int)), q, SLOT(_q_startupNotification())); - } - qt_create_pipe(deathPipe); - ::fcntl(deathPipe[0], F_SETFD, FD_CLOEXEC); - ::fcntl(deathPipe[1], F_SETFD, FD_CLOEXEC); - if (threadData->eventDispatcher) { deathNotifier = new QSocketNotifier(deathPipe[0], QSocketNotifier::Read, q); QObject::connect(deathNotifier, SIGNAL(activated(int)), q, SLOT(_q_processDied())); } - if (!createChannel(stdinChannel) || - !createChannel(stdoutChannel) || - !createChannel(stderrChannel)) - return; - // Start the process (platform dependent) q->setProcessState(QProcess::Starting); -- cgit v0.12 From 88316df0e845ee11b436c8dad9f1a225f52eb08c Mon Sep 17 00:00:00 2001 From: Frederik Schwarzer Date: Fri, 22 May 2009 15:06:49 +0200 Subject: wording: Warnung -> Achtung --- translations/qt_de.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/translations/qt_de.ts b/translations/qt_de.ts index 33f9ea8..7752970 100644 --- a/translations/qt_de.ts +++ b/translations/qt_de.ts @@ -66,15 +66,15 @@ Warning: You do not seem to have the package gstreamer0.10-plugins-good installed. Some video features have been disabled. - Warnung: Das Paket gstreamer0.10-plugins-good ist nicht installiert. -Einige Video-Funktionen stehen nicht zur Verfügung. + Achtung: Das Paket gstreamer0.10-plugins-good ist nicht installiert. +Einige Video-Funktionen stehen nicht zur Verfügung. Warning: You do not seem to have the base GStreamer plugins installed. All audio and video support has been disabled - Warnung: Die grundlegenden GStreamer-plugins sind nicht installiert. -Die Audio- und Video-Unterstützung wurde abgeschaltet + Achtung: Die grundlegenden GStreamer-Plugins sind nicht installiert. +Die Audio- und Video-Unterstützung steht nicht zur Verfügung. @@ -1373,7 +1373,7 @@ nach Warning: - Warnung: + Achtung: -- cgit v0.12 From 0fd48121fc5695b6f526839a3e6c7863bcef0074 Mon Sep 17 00:00:00 2001 From: Frederik Schwarzer Date: Fri, 22 May 2009 15:08:28 +0200 Subject: wording: Voransicht -> Vorschau --- translations/qt_de.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/translations/qt_de.ts b/translations/qt_de.ts index 7752970..4fa3027 100644 --- a/translations/qt_de.ts +++ b/translations/qt_de.ts @@ -291,12 +291,12 @@ Bitte prüfen Sie die Gstreamer-Installation und stellen Sie sicher, dass das Pa Preview File Info - Voransicht der Datei-Information + Vorschau der Datei-Informationen Preview File Contents - Voransicht des Datei-Inhalts + Vorschau des Datei-Inhalts -- cgit v0.12 From f00f66b2d2e3d892980f3957eebd7bc36ac315b4 Mon Sep 17 00:00:00 2001 From: Frederik Schwarzer Date: Fri, 22 May 2009 15:10:21 +0200 Subject: wrong translation of the Chinese writing systems The translations for Traditional and Simplified Chinese are Chinesisch (Langzeichen) and Chinesisch (Kurzzeichen) --- translations/qt_de.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/translations/qt_de.ts b/translations/qt_de.ts index 4fa3027..b82e9a3 100644 --- a/translations/qt_de.ts +++ b/translations/qt_de.ts @@ -1887,12 +1887,12 @@ Möchten sie die Datei trotzdem löschen? Simplified Chinese - Vereinfachtes Chinesisch + Chinesisch (Kurzzeichen) Traditional Chinese - Traditionelles Chinesisch + Chinesisch (Langzeichen) -- cgit v0.12 From a4662d096c46003df2e3c9e2b3ece294fd134986 Mon Sep 17 00:00:00 2001 From: Frederik Schwarzer Date: Fri, 22 May 2009 15:14:18 +0200 Subject: quite a bunch of fixes and suggenstions If it comes to unification in wording style, there is a long road ahead... --- translations/qt_de.ts | 144 +++++++++++++++++++++++++------------------------- 1 file changed, 72 insertions(+), 72 deletions(-) diff --git a/translations/qt_de.ts b/translations/qt_de.ts index b82e9a3..f623925 100644 --- a/translations/qt_de.ts +++ b/translations/qt_de.ts @@ -85,7 +85,7 @@ Die Audio- und Video-Unterstützung steht nicht zur Verfügung. Check your Gstreamer installation and make sure you have libgstreamer-plugins-base installed. - Das Abspielen konnte nicht gestartet werden. + Die Wiedergabe kann nicht gestartet werden. Bitte prüfen Sie die Gstreamer-Installation und stellen Sie sicher, dass das Paket libgstreamer-plugins-base installiert ist. @@ -139,7 +139,7 @@ Bitte prüfen Sie die Gstreamer-Installation und stellen Sie sicher, dass das Pa Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1% - Die Regler wird zur Einstellung der Lautstärke benutzt. Die Position links entspricht 0%; die Position rechts entspricht %1% + Mit diesem Regler stellen Sie die Lautstärke ein. Die Position links entspricht 0%; die Position rechts entspricht %1% @@ -392,7 +392,7 @@ Bitte prüfen Sie die Gstreamer-Installation und stellen Sie sicher, dass das Pa Sort by &Name - Nach &Name sortieren + Nach &Namen sortieren @@ -497,7 +497,7 @@ Bitte prüfen Sie die Gstreamer-Installation und stellen Sie sicher, dass das Pa File not found. Check path and filename. %1 -Datei konnte nicht gefunden werden. +Datei kann nicht gefunden werden. Überprüfen Sie Pfad und Dateinamen. @@ -617,7 +617,7 @@ nach Defaults - Defaults + Voreinstellungen @@ -699,7 +699,7 @@ nach Contains commands to manipulate the window - Enthält Befehle zum Ändern der Fenstergröße + Enthält Befehle zum Ändern der Fenstergröße @@ -772,18 +772,18 @@ nach The protocol `%1' does not support getting files - Das Protokoll `%1' unterstützt nicht das Laden von Files + Das Protokoll `%1' unterstützt nicht das Laden von Dateien The protocol `%1' does not support putting files - Das Protokoll `%1' unterstützt nicht das Speichern von Files + Das Protokoll `%1' unterstützt nicht das Speichern von Dateien The protocol `%1' does not support copying or moving files or directories - Das Protokoll `%1' unterstützt nicht das Kopieren oder Verschieben von Dateien oder Verzeichnissen + Das Protokoll `%1' unterstützt nicht das Kopieren oder Verschieben von Dateien oder Verzeichnissen @@ -847,7 +847,7 @@ nach Operation on socket is not supported - Diese Socketoperation wird nicht unterstützt + Diese Socket-Operation wird nicht unterstützt @@ -899,7 +899,7 @@ nach Incompatible Qt Library Error - Qt Bibliothek ist inkompatibel + Die Qt-Bibliothek ist inkompatibel @@ -909,7 +909,7 @@ nach Activates the program's main window - Aktiviert das Programmhauptfenster + Aktiviert das Hauptfenster der Anwendung @@ -1066,17 +1066,17 @@ nach Unable to commit transaction - Die Transaktion konnte nicht durchgeführt werden (Operation 'commit' fehlgeschlagen) + Die Transaktion kann nicht durchgeführt werden (Operation 'commit' fehlgeschlagen) Unable to rollback transaction - Die Transaktion konnte nicht rückgängig gemacht werden (Operation 'rollback' fehlgeschlagen) + Die Transaktion kann nicht rückgängig gemacht werden (Operation 'rollback' fehlgeschlagen) Unable to set autocommit - 'autocommit' konnte nicht aktiviert werden + 'autocommit' kann nicht aktiviert werden @@ -1085,32 +1085,32 @@ nach Unable to execute statement - Der Befehl konnte nicht ausgeführt werden + Der Befehl kann nicht ausgeführt werden Unable to prepare statement - Der Befehl konnte nicht initialisiert werden + Der Befehl kann nicht initialisiert werden Unable to bind variable - Die Variable konnte nicht gebunden werden + Die Variable kann nicht gebunden werden Unable to fetch record %1 - Der Datensatz %1 konnte nicht abgeholt werden + Der Datensatz %1 kann nicht abgeholt werden Unable to fetch next - Der nächste Datensatz konnte nicht abgeholt werden + Der nächste Datensatz kann nicht abgeholt werden Unable to fetch first - Der erste Datensatz konnte nicht abgeholt werden + Der erste Datensatz kann nicht abgeholt werden @@ -1358,7 +1358,7 @@ nach &Show this message again - Diese Meldung noch einmal an&zeigen + Diese Meldung wieder an&zeigen @@ -1397,12 +1397,12 @@ nach Cannot open %1 for input - %1 konnte nicht zum Lesen geöffnet werden + %1 kann nicht zum Lesen geöffnet werden Cannot open for output - Das Öffnen zum Schreiben schlug fehl + Das Öffnen zum Schreiben ist fehlgeschlagen @@ -1565,12 +1565,12 @@ Stellen Sie sicher, dass der Verzeichnisname richtig ist. '%1' is write protected. Do you want to delete it anyway? '%1' ist schreibgeschützt. -Möchten sie die Datei trotzdem löschen? +Möchten Sie die Datei trotzdem löschen? Are sure you want to delete '%1'? - Sind Sie sicher, dass Sie %1 löschen möchten? + Sind Sie sicher, dass Sie '%1' löschen möchten? @@ -1624,7 +1624,7 @@ Möchten sie die Datei trotzdem löschen? Look in: - Suche in: + Suchen in: @@ -1658,7 +1658,7 @@ Möchten sie die Datei trotzdem löschen? %1 bytes - %1 byte + %1 Byte @@ -2296,7 +2296,7 @@ Möchten sie die Datei trotzdem löschen? SSL handshake failed - Es trat ein Fehler im Ablauf des SSL-Protokolls auf. + Im Ablauf des SSL-Protokolls ist ein Fehler aufgetreten. @@ -2580,7 +2580,7 @@ Möchten sie die Datei trotzdem löschen? The plugin '%1' uses incompatible Qt library. (Cannot mix debug and release libraries.) - Das Plugin '%1' verwendet eine inkompatible Qt-Bibliothek. (Im Debug- und Release-Modus erstellte Bibliotheken können nicht zusammen verwendet werden.) + Das Plugin '%1' verwendet eine inkompatible Qt-Bibliothek. (Im Debug- bzw. Release-Modus erstellte Bibliotheken können nicht zusammen verwendet werden.) @@ -2670,7 +2670,7 @@ Möchten sie die Datei trotzdem löschen? %1: Connection refused - %1: Der Aufbau einer Verbindung wurde verweigert + %1: Der Verbindungsaufbau wurde verweigert @@ -2696,13 +2696,13 @@ Möchten sie die Datei trotzdem löschen? %1: Socket resource error - %1: Socketfehler (Ressourcenproblem) + %1: Socket-Fehler (Ressourcenproblem) %1: Socket operation timed out - %1: Zeitüberschreitung bei Socketoperation + %1: Zeitüberschreitung bei Socket-Operation @@ -2721,7 +2721,7 @@ Möchten sie die Datei trotzdem löschen? %1: The socket operation is not supported - %1: Diese Socketoperation wird nicht unterstützt + %1: Diese Socket-Operation wird nicht unterstützt @@ -2740,7 +2740,7 @@ Möchten sie die Datei trotzdem löschen? Unable to open database ' - Die Datenbankverbindung konnte nicht geöffnet werden ' + Die Datenbankverbindung kann nicht geöffnet werden ' @@ -2750,17 +2750,17 @@ Möchten sie die Datei trotzdem löschen? Unable to begin transaction - Es konnte keine Transaktion gestartet werden + Es kann keine Transaktion gestartet werden Unable to commit transaction - Die Transaktion konnte nicht durchgeführt werden (Operation 'commit' fehlgeschlagen) + Die Transaktion kann nicht durchgeführt werden (Operation 'commit' fehlgeschlagen) Unable to rollback transaction - Die Transaktion konnte nicht rückgängig gemacht werden (Operation 'rollback' fehlgeschlagen) + Die Transaktion kann nicht rückgängig gemacht werden (Operation 'rollback' fehlgeschlagen) @@ -3422,7 +3422,7 @@ Möchten sie die Datei trotzdem löschen? Socket error on %1: %2 - Socketfehler bei %1: %2 + Socket-Fehler bei %1: %2 @@ -3815,7 +3815,7 @@ Möchten sie die Datei trotzdem löschen? Print To File ... - In Datei drucken + In Datei drucken ... @@ -4022,12 +4022,12 @@ Bitte wählen Sie einen anderen Dateinamen. Print to File (PDF) - Druck in PDF-Datei + In PDF-Datei drucken Print to File (Postscript) - Druck in Postscript-Datei + In Postscript-Datei drucken @@ -4967,97 +4967,97 @@ Bitte wählen Sie einen anderen Dateinamen. Open URL - Öffne URL + URL öffnen Launch Mail - Start Mail + Mail starten Launch Media - Start Media Player + Medienspieler starten Launch (0) - Start (0) + (0) starten Launch (1) - Start (1) + (1) starten Launch (2) - Start (2) + (2) starten Launch (3) - Start (3) + (3) starten Launch (4) - Start (4) + (4) starten Launch (5) - Start (5) + (5) starten Launch (6) - Start (6) + (6) starten Launch (7) - Start (7) + (7) starten Launch (8) - Start (8) + (8) starten Launch (9) - Start (9) + (9) starten Launch (A) - Start (A) + (A) starten Launch (B) - Start (B) + (B) starten Launch (C) - Start (C) + (C) starten Launch (D) - Start (D) + (D) starten Launch (E) - Start (E) + (E) starten Launch (F) - Start (F) + (F) starten @@ -5385,12 +5385,12 @@ Bitte wählen Sie einen anderen Dateinamen. Error while reading: %1 - Beim Lesen trat ein Fehler auf: %1 + Beim Lesen ist ein Fehler aufgetreten: %1 Error during SSL handshake: %1 - Es trat ein Fehler im Ablauf des SSL-Protokolls auf: %1 + Im Ablauf des SSL-Protokolls ist ein Fehler aufgetreten: %1 @@ -5455,7 +5455,7 @@ Bitte wählen Sie einen anderen Dateinamen. %1: already exists - %1: existiert bereits + %1: Existiert bereits @@ -5469,7 +5469,7 @@ Bitte wählen Sie einen anderen Dateinamen. Unable to open connection - Die Datenbankverbindung konnte nicht geöffnet werden + Die Datenbankverbindung kann nicht geöffnet werden @@ -5495,7 +5495,7 @@ Bitte wählen Sie einen anderen Dateinamen. Operation on socket is not supported - Diese Socketoperation wird nicht unterstützt + Diese Socket-Operation wird nicht unterstützt @@ -7342,7 +7342,7 @@ Bitte wählen Sie einen anderen Dateinamen. %1 is not an atomic type. Casting is only possible to atomic types. - %1 ist kein atomarer Typ. Es können nur "cast"-Operation zu atomaren Typen durchgeführt werden. + %1 ist kein atomarer Typ. "cast"-Operation können nur zu atomaren Typen durchgeführt werden. @@ -7397,17 +7397,17 @@ Bitte wählen Sie einen anderen Dateinamen. Integer division (%1) by zero (%2) is undefined. - Die Ganzzahldivision (%1) durch Null (%2) ist nicht definiert. + Die Ganzzahldivision (%1) durch Null (%2) ist nicht definiert. Division (%1) by zero (%2) is undefined. - Die Division (%1) durch Null (%2) ist nicht definiert. + Die Division (%1) durch Null (%2) ist nicht definiert. Modulus division (%1) by zero (%2) is undefined. - Die Modulo-Division (%1) durch Null (%2) ist nicht definiert. + Die Modulo-Division (%1) durch Null (%2) ist nicht definiert. @@ -7443,13 +7443,13 @@ Bitte wählen Sie einen anderen Dateinamen. The namespace for a user defined function cannot be empty (try the predefined prefix %1 which exists for cases like this) - Der Namensraum einer nutzerdefinierten Funktion darf nicht leer sein (für diesen Zweck gibt es den vordefinierten Präfix %1) + Der Namensraum einer benutzerdefinierten Funktion darf nicht leer sein (für diesen Zweck gibt es den vordefinierten Präfix %1) A default namespace declaration must occur before function, variable, and option declarations. - Die Deklaration des Default-Namensraums muss vor Funktions- Variablen- oder Optionsdeklaration erfolgen. + Die Deklaration des Default-Namensraums muss vor Funktions-, Variablen- oder Optionsdeklaration erfolgen. -- cgit v0.12 From 263834072595e8de71136886d607f80b5b015572 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Fri, 22 May 2009 19:09:46 +0200 Subject: Disable the SH_Menu_AllowActiveAndDisabled on plastique style. This restore the KDE3's behaviour. Do not disable it on Windows as we are aware of customer using the QPlastiqueStyle on Windows that might rely on this (for behaviour consistancy with others Windows applications) Reviewed-by: jbache Task-number: 254210 --- src/gui/styles/qplastiquestyle.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/gui/styles/qplastiquestyle.cpp b/src/gui/styles/qplastiquestyle.cpp index 66464ff..587f2b5 100644 --- a/src/gui/styles/qplastiquestyle.cpp +++ b/src/gui/styles/qplastiquestyle.cpp @@ -5460,6 +5460,11 @@ int QPlastiqueStyle::styleHint(StyleHint hint, const QStyleOption *option, const case SH_Menu_SubMenuPopupDelay: ret = 96; // from Plastik break; +#ifndef Q_OS_WIN + case SH_Menu_AllowActiveAndDisabled: + ret = false; + break; +#endif default: ret = QWindowsStyle::styleHint(hint, option, widget, returnData); break; -- cgit v0.12 From 73a9e0fac1e1b417878286791877bcefeedb16a1 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 22 May 2009 19:28:41 +0200 Subject: Fix changed behaviour after QEglProperties::value() patch Patch 27fadaa7eb2d58b47e7f0f508e3402e7a8de3894 (Make QEglProperties::value() return the EGL default if not set) changed behaviour. This patch reverts this change to behaviour but keeps QEglProperties::value() returning the EGL default value. --- src/opengl/qegl.cpp | 20 ++++++++++---------- src/opengl/qgl_egl.cpp | 8 ++++---- 2 files changed, 14 insertions(+), 14 deletions(-) diff --git a/src/opengl/qegl.cpp b/src/opengl/qegl.cpp index aebc3cb..c6c258b 100644 --- a/src/opengl/qegl.cpp +++ b/src/opengl/qegl.cpp @@ -119,7 +119,7 @@ bool QEglContext::chooseConfig if (red == props.value(EGL_RED_SIZE) && green == props.value(EGL_GREEN_SIZE) && blue == props.value(EGL_BLUE_SIZE) && - (props.value(EGL_ALPHA_SIZE) == EGL_DONT_CARE || + (props.value(EGL_ALPHA_SIZE) == 0 || alpha == props.value(EGL_ALPHA_SIZE))) { cfg = configs[index]; delete [] configs; @@ -448,7 +448,7 @@ int QEglProperties::value(int name) const case EGL_NATIVE_VISUAL_ID: case EGL_NONE: qWarning("QEglProperties::value() - Attibute %d does not affect config selection", name); - return 0; + return EGL_DONT_CARE; default: qWarning("QEglProperties::value() - Attibute %d is unknown in EGL <=1.4", name); return EGL_DONT_CARE; @@ -640,13 +640,13 @@ QString QEglProperties::toString() const #endif val = value(EGL_DEPTH_SIZE); - if (val != EGL_DONT_CARE) { + if (val != 0) { addTag(str, QLatin1String(" depth=")); str += QString::number(val); } val = value(EGL_STENCIL_SIZE); - if (val != EGL_DONT_CARE) { + if (val != 0) { addTag(str, QLatin1String(" stencil=")); str += QString::number(val); } @@ -696,7 +696,7 @@ QString QEglProperties::toString() const } val = value(EGL_LEVEL); - if (val != EGL_DONT_CARE) { + if (val != 0) { addTag(str, QLatin1String(" level=")); str += QString::number(val); } @@ -747,13 +747,13 @@ QString QEglProperties::toString() const #endif val = value(EGL_SAMPLES); - if (val != EGL_DONT_CARE) { + if (val != 0) { addTag(str, QLatin1String(" samples=")); str += QString::number(val); } val = value(EGL_SAMPLE_BUFFERS); - if (val != EGL_DONT_CARE) { + if (val != 0) { addTag(str, QLatin1String(" sample-buffers=")); str += QString::number(val); } @@ -802,7 +802,7 @@ QString QEglProperties::toString() const #ifdef EGL_LUMINANCE_SIZE val = value(EGL_LUMINANCE_SIZE); - if (val != EGL_DONT_CARE) { + if (val != 0) { addTag(str, QLatin1String(" luminance=")); str += QString::number(val); } @@ -810,7 +810,7 @@ QString QEglProperties::toString() const #ifdef EGL_ALPHA_MASK_SIZE val = value(EGL_ALPHA_MASK_SIZE); - if (val != EGL_DONT_CARE) { + if (val != 0) { addTag(str, QLatin1String(" alpha-mask=")); str += QString::number(val); } @@ -818,7 +818,7 @@ QString QEglProperties::toString() const #ifdef EGL_CONFORMANT val = value(EGL_CONFORMANT); - if (val != EGL_DONT_CARE) { + if (val != 0) { if (val) addTag(str, QLatin1String(" conformant=true")); else diff --git a/src/opengl/qgl_egl.cpp b/src/opengl/qgl_egl.cpp index 98c5710..287c537 100644 --- a/src/opengl/qgl_egl.cpp +++ b/src/opengl/qgl_egl.cpp @@ -57,14 +57,14 @@ void qt_egl_set_format(QEglProperties& props, int deviceType, const QGLFormat& f // Set the pixel format to that contained in the QGLFormat // if the system hasn't already chosen a fixed format to // match the pixmap, widget, etc. - if (props.value(EGL_RED_SIZE) == EGL_DONT_CARE || f.redBufferSize() != -1) + if (props.value(EGL_RED_SIZE) == 0 || f.redBufferSize() != -1) props.setValue(EGL_RED_SIZE, f.redBufferSize() == -1 ? 1 : f.redBufferSize()); - if (props.value(EGL_GREEN_SIZE) == EGL_DONT_CARE || f.greenBufferSize() != -1) + if (props.value(EGL_GREEN_SIZE) == 0 || f.greenBufferSize() != -1) props.setValue(EGL_GREEN_SIZE, f.greenBufferSize() == -1 ? 1 : f.greenBufferSize()); - if (props.value(EGL_BLUE_SIZE) == EGL_DONT_CARE || f.blueBufferSize() != -1) + if (props.value(EGL_BLUE_SIZE) == 0 || f.blueBufferSize() != -1) props.setValue(EGL_BLUE_SIZE, f.blueBufferSize() == -1 ? 1 : f.blueBufferSize()); if (f.alpha()) { - if (props.value(EGL_ALPHA_SIZE) == EGL_DONT_CARE || f.alphaBufferSize() != -1) + if (props.value(EGL_ALPHA_SIZE) == 0 || f.alphaBufferSize() != -1) props.setValue(EGL_ALPHA_SIZE, f.alphaBufferSize() == -1 ? 1 : f.alphaBufferSize()); } -- cgit v0.12 From c8e908a3ee259576ffe96e382ab677d7e3df1a4f Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 22 May 2009 16:48:51 +0200 Subject: Try to use the X11 visual ID provided by EGL EGL has an EGL_NATIVE_VISUAL_ID which can by used as the window's visual ID. We now try to use this ID to avoid an XVisual <-> EGLConfig mis-match. Of course this is usually broken in the EGL library, so we fall back to trying to match outselves. --- src/opengl/qgl_x11egl.cpp | 104 +++++++++++++++++++++++++++++++++------------- 1 file changed, 74 insertions(+), 30 deletions(-) diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 480a2dc..74b9038 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -114,13 +114,6 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) eglSwapInterval(d->eglContext->display(), d->glFormat.swapInterval()); #endif - // Create the EGL surface to draw into. - if (!d->eglContext->createSurface(device())) { - delete d->eglContext; - d->eglContext = 0; - return false; - } - return true; } @@ -250,13 +243,34 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, return; } + + // Create the EGL Context (which will also choose the config for us) if (d->glcx) d->glcx->doneCurrent(); QGLContext* oldcx = d->glcx; d->glcx = context; + bool createFailed = false; + if (!d->glcx->isValid()) { + if (!d->glcx->create(shareContext ? shareContext : oldcx)) + createFailed = true; + } + if (createFailed) { + if (deleteOldContext) + delete oldcx; + return; + } + + if (d->glcx->windowCreated() || d->glcx->deviceIsPixmap()) { + if (deleteOldContext) + delete oldcx; + return; + } + + + + // Make sure native winIds are avaliable if (parentWidget()) { - // force creation of delay-created widgets parentWidget()->winId(); if (parentWidget()->x11Info().screen() != x11Info().screen()) d_func()->xinfo = parentWidget()->d_func()->xinfo; @@ -267,16 +281,55 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, hide(); XVisualInfo vi; + memset(&vi, 0, sizeof(XVisualInfo)); + + // Check to see if EGL is suggesting an appropriate visual id: + EGLint nativeVisualId; + QEglContext* qeglCtx = d->glcx->d_func()->eglContext; + qeglCtx->configAttrib(EGL_NATIVE_VISUAL_ID, &nativeVisualId); + vi.visualid = nativeVisualId; + + if (vi.visualid) { + // EGL has suggested a visual id, so get the rest of the visual info for that id: + XVisualInfo *chosenVisualInfo; + int matchingCount = 0; + chosenVisualInfo = XGetVisualInfo(x11Info().display(), VisualIDMask, &vi, &matchingCount); + if (chosenVisualInfo) { + memcpy(&vi, chosenVisualInfo, sizeof(XVisualInfo)); + XFree(chosenVisualInfo); + } + else { + qWarning("Warning: EGL suggested using X visual ID %d for config %d, but this seems to be invalid!", + nativeVisualId, (int)qeglCtx->config()); + vi.visualid = 0; + } + } + + if (vi.visualid == 0) { + // EGL does not know the visual ID, so try to select an appropriate one ourselves: + EGLint depth; + qeglCtx->configAttrib(EGL_BUFFER_SIZE, &depth); + + int err; + err = XMatchVisualInfo(x11Info().display(), x11Info().screen(), depth, TrueColor, &vi); + if (err == 0) { + qWarning("Warning: Can't find an X visual which matches the EGL config(%d)'s depth (%d)!", + (int)qeglCtx->config(), depth); + depth = x11Info().depth(); + err = XMatchVisualInfo(x11Info().display(), x11Info().screen(), depth, TrueColor, &vi); + if (err == 0) { + qWarning("Error: Couldn't get any matching X visual!"); + return; + } + else + qWarning(" - Falling back to X11 suggested depth (%d)", depth); + } - int err = XMatchVisualInfo(x11Info().display(), x11Info().screen(), x11Info().depth(), TrueColor, &vi); - if (err == 0) { - qWarning("Error: Couldn't get a matching X visual for format"); - return; } XSetWindowAttributes a; - Window p = RootWindow(X11->display, vi.screen); + Window p = RootWindow(x11Info().display(), x11Info().screen()); if (parentWidget()) p = parentWidget()->winId(); @@ -294,27 +347,18 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, create(w); // Create with the ID of the window we've just created - d->eglSurfaceWindowId = w; // Remember the window id we created the surface for - - if (visible) - show(); - bool createFailed = false; - if (!d->glcx->isValid()) { - if (!d->glcx->create(shareContext ? shareContext : oldcx)) - createFailed = true; - } - if (createFailed) { - if (deleteOldContext) - delete oldcx; + // Create the EGL surface to draw into. + if (!d->glcx->d_func()->eglContext->createSurface(this)) { + delete d->glcx->d_func()->eglContext; + d->glcx->d_func()->eglContext = 0; return; } - if (d->glcx->windowCreated() || d->glcx->deviceIsPixmap()) { - if (deleteOldContext) - delete oldcx; - return; - } + d->eglSurfaceWindowId = w; // Remember the window id we created the surface for + + if (visible) + show(); d->glcx->setWindowCreated(true); } -- cgit v0.12 From 43eccd4e52402b9020a0cf26aa1486784f8abe0e Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Fri, 22 May 2009 18:34:05 +0200 Subject: If EGL fails to provide a valid Visual ID, try XRender for ARGBs This patch is inspired by the "Fix ARGB visuals" patch in the Maemo branch. Thanks go to the author of that patch (who isn't signed up to Gitorious and thus can't be named - you know who you are! Thanks!!). This patch should also fix ARGB visuals (even if they are supplied by EGL) as such visuals require a colormap. --- src/opengl/qgl_x11egl.cpp | 64 ++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 9 deletions(-) diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 74b9038..514e763 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -295,7 +295,8 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, int matchingCount = 0; chosenVisualInfo = XGetVisualInfo(x11Info().display(), VisualIDMask, &vi, &matchingCount); if (chosenVisualInfo) { - memcpy(&vi, chosenVisualInfo, sizeof(XVisualInfo)); + qDebug("Using X Visual ID (%d) provided by EGL", (int)vi.visualid); + vi = *chosenVisualInfo; XFree(chosenVisualInfo); } else { @@ -305,11 +306,38 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, } } + // If EGL does not know the visual ID, so try to select an appropriate one ourselves, first + // using XRender if we're supposed to have an alpha, then falling back to XGetVisualInfo + + bool useArgb = context->format().alpha() && !context->deviceIsPixmap(); +#if !defined(QT_NO_XRENDER) + if (vi.visualid == 0 && useArgb) { + // Try to use XRender to find an ARGB visual we can use + vi.screen = x11Info().screen(); + vi.depth = 32; + vi.c_class = TrueColor; + XVisualInfo *matchingVisuals; + int matchingCount = 0; + matchingVisuals = XGetVisualInfo(x11Info().display(), + VisualScreenMask|VisualDepthMask|VisualClassMask, + &vi, &matchingCount); + + for (int i = 0; i < matchingCount; ++i) { + XRenderPictFormat *format; + format = XRenderFindVisualFormat(x11Info().display(), matchingVisuals[i].visual); + if (format->type == PictTypeDirect && format->direct.alphaMask) { + vi = matchingVisuals[i]; + qDebug("Using X Visual ID (%d) for ARGB visual as provided by XRender", (int)vi.visualid); + break; + } + } + XFree(matchingVisuals); + } +#endif + if (vi.visualid == 0) { - // EGL does not know the visual ID, so try to select an appropriate one ourselves: EGLint depth; qeglCtx->configAttrib(EGL_BUFFER_SIZE, &depth); - int err; err = XMatchVisualInfo(x11Info().display(), x11Info().screen(), depth, TrueColor, &vi); if (err == 0) { @@ -320,13 +348,27 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, if (err == 0) { qWarning("Error: Couldn't get any matching X visual!"); return; - } - else + } else qWarning(" - Falling back to X11 suggested depth (%d)", depth); - } + } else + qDebug("Using X Visual ID (%d) for EGL provided depth (%d)", (int)vi.visualid, depth); + // Don't try to use ARGB now unless the visual is 32-bit - even then it might stil fail :-( + if (useArgb) + useArgb = vi.depth == 32; } +// qDebug("Visual Info:"); +// qDebug(" bits_per_rgb=%d", vi.bits_per_rgb); +// qDebug(" red_mask=0x%x", vi.red_mask); +// qDebug(" green_mask=0x%x", vi.green_mask); +// qDebug(" blue_mask=0x%x", vi.blue_mask); +// qDebug(" colormap_size=%d", vi.colormap_size); +// qDebug(" c_class=%d", vi.c_class); +// qDebug(" depth=%d", vi.depth); +// qDebug(" screen=%d", vi.screen); +// qDebug(" visualid=%d", vi.visualid); + XSetWindowAttributes a; Window p = RootWindow(x11Info().display(), x11Info().screen()); @@ -337,9 +379,13 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, a.background_pixel = colmap.pixel(palette().color(backgroundRole())); a.border_pixel = colmap.pixel(Qt::black); - Window w = XCreateWindow(X11->display, p, x(), y(), width(), height(), - 0, vi.depth, InputOutput, vi.visual, - CWBackPixel|CWBorderPixel, &a); + unsigned int valueMask = CWBackPixel|CWBorderPixel; + if(useArgb) { + a.colormap = XCreateColormap(x11Info().display(), p, vi.visual, AllocNone); + valueMask |= CWColormap; + } + Window w = XCreateWindow(x11Info().display(), p, x(), y(), width(), height(), + 0, vi.depth, InputOutput, vi.visual, valueMask, &a); if (deleteOldContext) delete oldcx; -- cgit v0.12 From a5104ef77f71b068228ffe6d7c64845889c18c81 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Sat, 23 May 2009 13:18:23 +0200 Subject: Fix another compilation breakage introduced by the fix to the compilation breakage introduced in 6c1d7e57. The fix in fc7a43cce did fix the failure, but created another one because qhostinfo_win.cpp also had a copy of qt_sockaddr_in6 Reviewed-by: Jason McDonald --- src/network/kernel/qhostinfo_win.cpp | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/src/network/kernel/qhostinfo_win.cpp b/src/network/kernel/qhostinfo_win.cpp index 0a34e2b..472bc4b 100644 --- a/src/network/kernel/qhostinfo_win.cpp +++ b/src/network/kernel/qhostinfo_win.cpp @@ -72,21 +72,6 @@ struct qt_addrinfo qt_addrinfo *ai_next; }; -// sockaddr_in6 size changed between old and new SDK -// Only the new version is the correct one, so always -// use this structure. -struct qt_in6_addr { - uchar qt_s6_addr[16]; -}; - -struct qt_sockaddr_in6 { - short sin6_family; /* AF_INET6 */ - u_short sin6_port; /* Transport level port number */ - u_long sin6_flowinfo; /* IPv6 flow information */ - struct qt_in6_addr sin6_addr; /* IPv6 address */ - u_long sin6_scope_id; /* set of interfaces for a scope */ -}; - //### #define QT_SOCKLEN_T int #ifndef NI_MAXHOST // already defined to 1025 in ws2tcpip.h? -- cgit v0.12 From 26302d22f4dbf3482aacad89ad65bf5b7ed6ae53 Mon Sep 17 00:00:00 2001 From: axasia Date: Sat, 23 May 2009 23:33:49 +0900 Subject: Update japanese translation of Qt Assistant 4.5 --- translations/assistant_ja.ts | 395 ++++++++++++++++++++++--------------------- 1 file changed, 203 insertions(+), 192 deletions(-) diff --git a/translations/assistant_ja.ts b/translations/assistant_ja.ts index 1853155..5e4d2c9 100644 --- a/translations/assistant_ja.ts +++ b/translations/assistant_ja.ts @@ -1,12 +1,12 @@ - + AboutDialog &Close - + é–‰ã˜ã‚‹(&C) @@ -14,18 +14,19 @@ Warning - + 警告 Unable to launch external application. - + 外部アプリケーションを起動ã§ãã¾ã›ã‚“。 + OK - + OK @@ -37,42 +38,42 @@ Bookmarks - + ブックマーク Add Bookmark - + ブックマークã®è¿½åŠ  Bookmark: - + ブックマーク: Add in Folder: - + 追加先フォルダ: + - + + New Folder - + æ–°ã—ã„フォルダ Delete Folder - + フォルダを削除 Rename Folder - + フォルダã®åå‰å¤‰æ›´ @@ -80,23 +81,23 @@ Bookmarks - + ブックマーク Remove - + 削除 You are going to delete a Folder, this will also<br>remove it's content. Are you sure to continue? - + フォルダを削除ã™ã‚‹ã¨ä¸­èº«ã‚‚削除ã•れã¾ã™ãŒã€ç¶šã‘ã¦ã‚ˆã‚ã—ã„ã§ã™ã‹? New Folder - + æ–°ã—ã„フォルダ @@ -104,47 +105,47 @@ Filter: - + フィルタ: Remove - + 削除 Delete Folder - + フォルダを削除 Rename Folder - + フォルダã®åå‰å¤‰æ›´ Show Bookmark - + ブックマークを開ã Show Bookmark in New Tab - + ブックマークを新ã—ã„タブã§é–‹ã Delete Bookmark - + ブックマークを削除 Rename Bookmark - + ブックマークã®åå‰å¤‰æ›´ Add - + 追加 @@ -152,48 +153,48 @@ Add new page - + æ–°ã—ã„ページã®è¿½åŠ  Close current page - + ç¾åœ¨ã®ãƒšãƒ¼ã‚¸ã‚’é–‰ã˜ã‚‹ Print Document - + ドキュメントをå°åˆ· unknown - + 䏿˜Ž Add New Page - + æ–°ã—ã„ページã®è¿½åŠ  Close This Page - + ã“ã®ãƒšãƒ¼ã‚¸ã‚’é–‰ã˜ã‚‹ Close Other Pages - + ä»–ã®ãƒšãƒ¼ã‚¸ã‚’é–‰ã˜ã‚‹ Add Bookmark for this Page... - + ã“ã®ãƒšãƒ¼ã‚¸ã‚’ブックマークã«è¿½åŠ ... Search - + 検索 @@ -201,12 +202,12 @@ Open Link - + リンクを開ã Open Link in New Tab - + リンクを新ã—ã„タブã§é–‹ã @@ -214,12 +215,12 @@ Add Filter Name - + フィルタåを追加 Filter Name: - + フィルタå: @@ -227,27 +228,27 @@ Previous - + 戻る Next - + 進む Case Sensitive - + 大文字/å°æ–‡å­—を区別ã™ã‚‹ Whole words - + å˜èªžå˜ä½ã§æ¤œç´¢ã™ã‚‹ <img src=":/trolltech/assistant/images/wrap.png">&nbsp;Search wrapped - + <img src=":/trolltech/assistant/images/wrap.png">&nbsp;見ã¤ã‹ã‚‰ãªã‘れã°å…ˆé ­ã‹ã‚‰æ¤œç´¢ã™ã‚‹ @@ -255,27 +256,27 @@ Font - + フォント &Writing system - + 文字セット(&W) &Family - + フォントå(&F) &Style - + スタイル(&S) &Point size - + サイズ(&P) @@ -283,38 +284,39 @@ Help - + ヘルプ OK - + OK <title>Error 404...</title><div align="center"><br><br><h1>The page could not be found</h1><br><h3>'%1'</h3></div> - + <title>Error 404...</title><div align="center"><br><br><h1>ページãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“ã§ã—ãŸ</h1><br><h3>'%1'</h3></div> Copy &Link Location - + リンクã®URLをコピー(&L) Open Link in New Tab Ctrl+LMB - + リンクを新ã—ã„タブã§é–‹ã Ctrl+LMB Open Link in New Tab - + リンクを新ã—ã„タブã§é–‹ã Unable to launch external application. - + 外部アプリケーションを起動ã§ãã¾ã›ã‚“。 + @@ -322,17 +324,17 @@ &Look for: - + 検索文字列(&L): Open Link - + リンクを開ã Open Link in New Tab - + リンクを新ã—ã„タブã§é–‹ã @@ -341,97 +343,98 @@ Install Documentation - + ドキュメントã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ« Downloading documentation info... - + ドキュメント情報をダウンロード中... Download canceled. - + ダウンロードを中止ã—ã¾ã—ãŸã€‚ Done. - + 完了. The file %1 already exists. Do you want to overwrite it? - + %1 ã¯æ—¢ã«å­˜åœ¨ã—ã¾ã™ã€‚上書ãã—ã¾ã™ã‹? Unable to save the file %1: %2. - + ファイルをä¿å­˜ã§ãã¾ã›ã‚“。%1: %2. Downloading %1... - + %1 をダウンロード中... Download failed: %1. - + ダウンロード失敗: %1. Documentation info file is corrupt! - + ドキュメント情報ファイルãŒä¸æ­£ã§ã™! Download failed: Downloaded file is corrupted. - + ダウンロード失敗: ダウンロードã—ãŸãƒ•ァイルãŒä¸æ­£ã§ã™ã€‚ Installing documentation %1... - + %1 ã®ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆã‚’インストール中... Error while installing documentation: %1 - + ドキュメントã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ä¸­ã«ã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ã¾ã—ãŸ: +%1 Available Documentation: - + 使用å¯èƒ½ãªãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆ: Install - + インストール Cancel - + キャンセル Close - + é–‰ã˜ã‚‹ Installation Path: - + インストール先ã®ãƒ‘ス: ... - + ... @@ -440,298 +443,298 @@ Index - + インデックス Contents - + コンテンツ Bookmarks - + ブックマーク Search - + 検索 Qt Assistant - + Qt Assistant Unfiltered - + フィルタãªã— Page Set&up... - + ページ設定(&U)... Print Preview... - + å°åˆ·ãƒ—レビュー... &Print... - + å°åˆ·(&P)... New &Tab - + æ–°ã—ã„タブ(&T) &Close Tab - + タブを閉ã˜ã‚‹(&C) &Quit - + 終了(&Q) CTRL+Q - + CTRL+Q &Copy selected Text - + é¸æŠžä¸­ã®æ–‡å­—をコピー(&C) &Find in Text... - + 検索(&F)... Find &Next - + 次を検索(&N) Find &Previous - + å‰ã‚’検索(&P) Preferences... - + 設定... Zoom &in - + 拡大(&I) Zoom &out - + 縮å°(&O) Normal &Size - + 普通ã®å¤§ãã•(&S) Ctrl+0 - + Ctrl+0 ALT+C - + ALT+C ALT+I - + ALT+I ALT+S - + ALT+S &Home - + ホーム(&H) Ctrl+Home - + Ctrl+Home &Back - + 戻る(&B) &Forward - + 進む(&F) Sync with Table of Contents - + 内容ã¨ç›®æ¬¡ã‚’åŒæœŸã™ã‚‹ Next Page - + 次ã®ãƒšãƒ¼ã‚¸ Ctrl+Alt+Right - + Ctrl+Alt+Right Previous Page - + å‰ã®ãƒšãƒ¼ã‚¸ Ctrl+Alt+Left - + Ctrl+Alt+Left Add Bookmark... - + ブックマークã®è¿½åŠ ... About... - + Qt Assistant ã«ã¤ã„ã¦... Navigation Toolbar - + ナビゲーション ツールãƒãƒ¼ Toolbars - + ツールãƒãƒ¼ Filter Toolbar - + フィルター ツールãƒãƒ¼ Filtered by: - + フィルタæ¡ä»¶: Address Toolbar - + アドレス ツールãƒãƒ¼ Address: - + アドレス: Could not find the associated content item. - + 関連付ã„ãŸå†…容ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“。 About %1 - + %1 ã«ã¤ã„㦠Updating search index - + 検索インデックスを更新中 Looking for Qt Documentation... - + Qt ドキュメントを探ã—ã¦ã„ã¾ã™... &Window - + ウィンドウ(&W) Minimize - + 最å°åŒ– Ctrl+M - + Ctrl+M Zoom - + ズーム &File - + ファイル(&F) &Edit - + 編集(&E) &View - + 表示(&V) &Go - + ジャンプ(&G) &Bookmarks - + ブックマーク(&B) &Help - + ヘルプ(&H) ALT+O - + ALT+O CTRL+D - + CTRL+D @@ -741,47 +744,47 @@ Add Documentation - + ドキュメントã®è¿½åŠ  Qt Compressed Help Files (*.qch) - + 圧縮済㿠Qt ヘルプファイル (*.qch) The specified file is not a valid Qt Help File! - + 指定ã•れãŸãƒ•ã‚¡ã‚¤ãƒ«ã¯æœ‰åŠ¹ãª Qt ヘルプ ファイルã§ã¯ã‚りã¾ã›ã‚“! The namespace %1 is already registered! - + ãƒãƒ¼ãƒ ã‚¹ãƒšãƒ¼ã‚¹ %1 ã¯æ—¢ã«ç™»éŒ²æ¸ˆã¿ã§ã™! Remove Documentation - + ドキュメントã®é™¤åŽ» Some documents currently opened in Assistant reference the documentation you are attempting to remove. Removing the documentation will close those documents. - + 除去ã—よã†ã¨ã—ã¦ã„ã‚‹ã„ãã¤ã‹ã®ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆã¯ Assistant 上ã§å‚ç…§ã•れã¦ã„ã¾ã™ã€‚除去ã™ã‚‹ã¨ã€ã“れらã®ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆã¯é–‰ã˜ã‚‰ã‚Œã¾ã™ã€‚ Cancel - + キャンセル OK - + OK Use custom settings - + 独自設定を使用ã™ã‚‹ @@ -789,92 +792,92 @@ Preferences - + 設定 Fonts - + フォント Font settings: - + フォント設定: Browser - + ブラウザー Application - + アプリケーション Filters - + フィルタ Filter: - + フィルタ: Attributes: - + 属性: 1 - + 1 Add - + 追加 Remove - + 削除 Documentation - + ドキュメント Registered Documentation: - + 登録済ã¿ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆ: Add... - + 追加... Options - + オプション Current Page - + ç¾åœ¨ã®ãƒšãƒ¼ã‚¸ Restore to default - + ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆè¨­å®šã«æˆ»ã™ Homepage - + ホームページ @@ -882,64 +885,64 @@ The specified collection file does not exist! - + 指定ã•れãŸã‚³ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ãƒ•ァイルã¯å­˜åœ¨ã—ã¾ã›ã‚“! Missing collection file! - + コレクションファイルãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“! Invalid URL! - + 䏿­£ãªURLã§ã™! Missing URL! - + URLãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“! Unknown widget: %1 - + 䏿˜Žãªã‚¦ã‚£ã‚¸ã‚§ãƒƒãƒˆ: %1 Missing widget! - + ウィジェットãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“! The specified Qt help file does not exist! - + 指定ã•れ㟠Qt ヘルプ ファイルãŒå­˜åœ¨ã—ã¾ã›ã‚“! Missing help file! - + ヘルプファイルãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“! Missing filter argument! - + フィルタ引数ãŒä¸è¶³ã—ã¦ã„ã¾ã™! Unknown option: %1 - + 䏿˜Žãªã‚ªãƒ—ション: %1 Qt Assistant - + Qt Assistant @@ -948,12 +951,16 @@ Reason: %2 - + ドキュメントファイルを登録ã§ãã¾ã›ã‚“ã§ã—ãŸã€‚ +%1 + +原因: +%2 Documentation successfully registered. - + ドキュメントã®ç™»éŒ²ã«æˆåŠŸã—ã¾ã—ãŸã€‚ @@ -962,28 +969,32 @@ Reason: Reason: %2 - + ドキュメントファイルを解除ã§ãã¾ã›ã‚“ã§ã—ãŸã€‚ +%1 + +原因: +%2 Documentation successfully unregistered. - + ドキュメントã®è§£æ”¾ã«æˆåŠŸã—ã¾ã—ãŸã€‚ Cannot load sqlite database driver! - + SQLite データベース ドライãƒãƒ¼ã‚’ロードã§ãã¾ã›ã‚“! The specified collection file could not be read! - + 指定ã•れãŸã‚³ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ãƒ•ァイルã¯èª­ã¿è¾¼ã‚ã¾ã›ã‚“! Bookmark - + ブックマーク @@ -991,12 +1002,12 @@ Reason: Debugging Remote Control - + リモート コントロールをデãƒãƒƒã‚°ä¸­ Received Command: %1 %2 - + å—ä¿¡ã—ãŸã‚³ãƒžãƒ³ãƒ‰: %1 %2 @@ -1004,28 +1015,28 @@ Reason: &Copy - + コピー(&C) Copy &Link Location - + リンクã®URLをコピー(&L) Open Link in New Tab - + リンクを新ã—ã„タブã§é–‹ã Select All - + ã™ã¹ã¦ã‚’é¸æŠž Open Link - + リンクを開ã @@ -1033,27 +1044,27 @@ Reason: Choose a topic for <b>%1</b>: - + <b>%1</b> ã®æ¤œç´¢å…ˆãƒˆãƒ”ãƒƒã‚¯ã‚’é¸æŠžã—ã¦ãã ã•ã„: Choose Topic - + ãƒˆãƒ”ãƒƒã‚¯ã‚’é¸æŠž &Topics - + トピック(&T) &Display - + 表示(&D) &Close - + é–‰ã˜ã‚‹(&C) -- cgit v0.12 From 91be6a182c2c16f9abedbaa9e90e776a7a07e34c Mon Sep 17 00:00:00 2001 From: Ritt Konstantin Date: Sun, 24 May 2009 07:42:45 +0400 Subject: Update Russian translation for Qt libraries (xmlpatterns and statemachine are not translated yet) --- translations/qt_ru.qm | Bin 60815 -> 107081 bytes translations/qt_ru.ts | 3042 ++++++++++++++++++++++++------------------------- 2 files changed, 1519 insertions(+), 1523 deletions(-) diff --git a/translations/qt_ru.qm b/translations/qt_ru.qm index 63b7b8b..6467629 100644 Binary files a/translations/qt_ru.qm and b/translations/qt_ru.qm differ diff --git a/translations/qt_ru.ts b/translations/qt_ru.ts index 28e786b..a27b8c4 100644 --- a/translations/qt_ru.ts +++ b/translations/qt_ru.ts @@ -1,37 +1,30 @@ - + AudioOutput <html>The audio playback device <b>%1</b> does not work.<br/>Falling back to <b>%2</b>.</html> - + <html>Звуковое уÑтройÑтво <b>%1</b> не работает.<br/>Будет иÑпользоватьÑÑ <b>%2</b>.</html> <html>Switching to the audio playback device <b>%1</b><br/>which just became available and has higher preference.</html> - + <html>Переключение на звуковое уÑтройÑтво <b>%1</b><br/>, которое доÑтупно и имеет выÑший приоритет.</html> Revert back to device '%1' - + Возвращение к уÑтройÑтву '%1' CloseButton - + Close Tab - - - - - PPDOptionsModel - - Name - Ð˜Ð¼Ñ + Закрыть вкладку @@ -39,32 +32,32 @@ Notifications - + Ð£Ð²ÐµÐ´Ð¾Ð¼Ð»ÐµÐ½Ð¸Ñ Music - + Музыка Video - + Видео Communication - + Общение Games - + Игры Accessibility - + СредÑтва Ð´Ð»Ñ Ð»ÑŽÐ´ÐµÐ¹ Ñ Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð½Ñ‹Ð¼Ð¸ возможноÑÑ‚Ñми @@ -73,13 +66,15 @@ Warning: You do not seem to have the package gstreamer0.10-plugins-good installed. Some video features have been disabled. - + Внимание: Похоже, пакет gstreamer0.10-plugins-good не уÑтановлен. + Ðекоторые возможноÑти воÑÐ¿Ñ€Ð¾Ð¸Ð·Ð²ÐµÐ´ÐµÐ½Ð¸Ñ Ð²Ð¸Ð´ÐµÐ¾ недоÑтупны. Warning: You do not seem to have the base GStreamer plugins installed. All audio and video support has been disabled - + Внимание: Похоже, оÑновной модуль GStreamer не уÑтановлен. + Поддержка видео и аудио невозможна @@ -90,12 +85,15 @@ Check your Gstreamer installation and make sure you have libgstreamer-plugins-base installed. - + Ðевозможно начать воÑпроизведение. + +Проверьте уÑтановку Gstreamer и убедитеÑÑŒ, +что пакет libgstreamer-plugins-base уÑтановлен. A required codec is missing. You need to install the following codec(s) to play this content: %0 - + ОтÑутÑтвует необходимый кодек. Вам нужно уÑтановить Ñледующие кодеки Ð´Ð»Ñ Ð²Ð¾ÑÐ¿Ñ€Ð¾Ð¸Ð·Ð²ÐµÐ´ÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½Ð¾Ð³Ð¾ Ñодержимого: %0 @@ -107,27 +105,27 @@ have libgstreamer-plugins-base installed. Could not open media source. - + Ðе удалоÑÑŒ открыть иÑточник медиа-данных. Invalid source type. - + Ðеверный тип иÑточника медиа-данных. Could not locate media source. - + Ðе удалоÑÑŒ найти иÑточник медиа-данных. Could not open audio device. The device is already in use. - + Ðе удалоÑÑŒ открыть звуковое уÑтройÑтво. УÑтройÑтво уже иÑпользуетÑÑ. Could not decode media source. - + Ðе удалоÑÑŒ декодировать иÑточник медиа-данных. @@ -136,14 +134,14 @@ have libgstreamer-plugins-base installed. Volume: %1% - + ГромкоÑть: %1% Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1% - + ИÑпользуйте ползунок Ð´Ð»Ñ Ð½Ð°Ñтройки громкоÑти. КрайнÑÑ Ð»ÐµÐ²Ð°Ñ Ð¿Ð¾Ð·Ð¸Ñ†Ð¸Ñ ÑоответÑтвует 0%, ÑÐ°Ð¼Ð°Ñ Ð¿Ñ€Ð°Ð²Ð°Ñ - %1% @@ -151,7 +149,7 @@ have libgstreamer-plugins-base installed. %1, %2 not defined - + %1, %2 не определен @@ -164,52 +162,52 @@ have libgstreamer-plugins-base installed. True - True + Да False - False + Ðет Insert - Ð’Ñтавить + Ð’Ñтавить Update - Обновить + Обновить Delete - Удалить + Удалить Q3FileDialog - + Copy or Move a File - Копировать или перемеÑтить файл + Копировать или перемеÑтить файл Read: %1 - Открытие: %1 + Чтение: %1 Write: %1 - ЗапиÑÑŒ: %1 + ЗапиÑÑŒ: %1 - + Cancel - Отмена + Отмена @@ -217,307 +215,307 @@ have libgstreamer-plugins-base installed. All Files (*) - Ð’Ñе файлы (*) + Ð’Ñе файлы (*) Name - Ð˜Ð¼Ñ + Ð˜Ð¼Ñ Size - Размер + Размер Type - Тип + Тип Date - Дата + Дата Attributes - Ðтрибуты + Ðтрибуты &OK - &OK + &Готово Look &in: - &Смотреть в: + &Папка: File &name: - &Ð˜Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð°: + &Ð˜Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð°: File &type: - &Тип файла: + &Тип файла: Back - Ðазад + Ðазад One directory up - Вверх на один уровень + Ðа один уровень вверх Create New Folder - Создать новый каталог + Создать каталог List View - СпиÑок + СпиÑок Detail View - Детальный вид + Подробный вид Preview File Info - ПредпроÑмотр информации о файле + ПредпроÑмотр информации о файле Preview File Contents - ПредпроÑмотр Ñодержимого файла + ПредпроÑмотр Ñодержимого файла Read-write - Чтение-запиÑÑŒ + Чтение и запиÑÑŒ Read-only - Только чтение + Только чтение Write-only - Только запиÑÑŒ + Только запиÑÑŒ Inaccessible - Ðет доÑтупа + Ðет доÑтупа Symlink to File - СÑылка на файл + СÑылка на файл Symlink to Directory - СÑылка на каталог + СÑылка на каталог Symlink to Special - СÑылка на Ñпецфайл + СÑылка на Ñпецфайл File - Файл + Файл Dir - Каталог + Каталог Special - Спецфайл + Спецфайл Open - Открыть + Открыть Save As - Сохранить как + Сохранить как &Open - &Открыть + &Открыть &Save - &Сохранить + &Сохранить &Rename - &Переименовать + &Переименовать &Delete - &Удалить + &Удалить R&eload - О&бновить + О&бновить Sort by &Name - По &имени + По &имени Sort by &Size - По &размеру + По &размеру Sort by &Date - По &дате + По &дате &Unsorted - &Ðе упорÑдочивать + &Ðе упорÑдочивать Sort - УпорÑдочить + УпорÑдочить Show &hidden files - Показать &Ñкрытые файлы + Показать Ñкр&ытые файлы the file - файл + файл the directory - каталог + каталог the symlink - ÑÑылку + ÑÑылку Delete %1 - Удалить %1 + Удалить %1 <qt>Are you sure you wish to delete %1 "%2"?</qt> - <qt>Ð’Ñ‹ дейÑтвительно хотите удалить %1 "%2"?</qt> + <qt>Ð’Ñ‹ дейÑтвительно хотите удалить %1 "%2"?</qt> &Yes - &Да + &Да &No - &Ðет + &Ðет New Folder 1 - Ðовый каталог 1 + Ðовый каталог 1 New Folder - Ðовый каталог + Ðовый каталог New Folder %1 - Ðовый каталог %1 + Ðовый каталог %1 Find Directory - Ðайти каталог + Ðайти каталог Directories - Каталоги + Каталоги Directory: - Каталог: + каталог: Error - Ошибка + Ошибка %1 File not found. Check path and filename. - %1 + %1 Файл не найден. Проверьте правильноÑть пути и имени файла. All Files (*.*) - Ð’Ñе файлы (*.*) + Ð’Ñе файлы (*.*) Open - Открыть + Открыть Select a Directory - Выбрать каталог + Выбрать каталог @@ -527,21 +525,21 @@ Check path and filename. Could not read directory %1 - Ðевозможно проÑмотреть каталог + Ðе удалоÑÑŒ прочитать каталог %1 Could not create directory %1 - Ðевозможно Ñоздать каталог + Ðе удалоÑÑŒ Ñоздать каталог %1 Could not remove file or directory %1 - Ðевозможно удалить файл или каталог + Ðе удалоÑÑŒ удалить файл или каталог %1 @@ -550,7 +548,7 @@ Check path and filename. %1 to %2 - Ðевозможно переименовать + Ðе удалоÑÑŒ переименовать %1 в %2 @@ -559,14 +557,14 @@ to Could not open %1 - Ðевозможно открыть + Ðе удалоÑÑŒ открыть %1 Could not write %1 - Ðевозможно запиÑать + Ðе удалоÑÑŒ запиÑать %1 @@ -575,12 +573,12 @@ to Line up - ВыровнÑть + ВыровнÑть Customize... - ÐаÑтроить... + ÐаÑтроить... @@ -588,7 +586,7 @@ to Operation stopped by the user - ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ð¿Ñ€ÐµÑ€Ð²Ð°Ð½Ð° пользователем + ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ð¿Ñ€ÐµÑ€Ð²Ð°Ð½Ð° пользователем @@ -597,36 +595,36 @@ to Cancel - Отмена + Отмена Q3TabDialog - - + + OK - OK + Готово - + Apply - Применить + Применить Help - Справка + Справка Defaults - По умолчанию + По умолчанию Cancel - Отмена + Отмена @@ -634,38 +632,38 @@ to &Undo - &Отменить + &Отменить дейÑтвие &Redo - &Повторить + &Повторить дейÑтвие Cu&t - &Вырезать + &Вырезать &Copy - &Копировать + &Копировать &Paste - &Ð’Ñтавить + Ð’&Ñтавить Clear - ОчиÑтить + ОчиÑтить Select All - Выделить вÑе + Выделить вÑе @@ -673,67 +671,67 @@ to System - + СиÑтемное меню Restore up - + ВоÑÑтановить Minimize - Свернуть + Минимизировать Restore down - + ВоÑÑтановить Maximize - Развернуть + РаÑпахнуть Close - Закрыть + Закрыть Contains commands to manipulate the window - + Содержит команды ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð¾ÐºÐ½Ð¾Ð¼ Puts a minimized back to normal - + Возвращает минимизированное окно в нормальное ÑоÑтоÑние Moves the window out of the way - + Сворачивает окно Puts a maximized window back to normal - + Возвращает раÑпахнутое окно в нормальное ÑоÑтоÑние Makes the window full screen - + Разворачивает окно на веÑÑŒ Ñкран Closes the window - + Зыкрывает окно Displays the name of the window and contains controls to manipulate it - + Отображает название окна и Ñодержит команды ÑƒÐ¿Ñ€Ð°Ð²Ð»ÐµÐ½Ð¸Ñ Ð¸Ð¼ @@ -741,7 +739,7 @@ to More... - Больше... + Больше... @@ -751,49 +749,49 @@ to The protocol `%1' is not supported - Протокол `%1' не поддерживаетÑÑ + Протокол `%1' не поддерживаетÑÑ The protocol `%1' does not support listing directories - Протокол `%1' не поддерживает проÑмотр каталогов + Протокол `%1' не поддерживает проÑмотр каталогов The protocol `%1' does not support creating new directories - Протокол `%1' не поддерживает Ñоздание новых каталогов + Протокол `%1' не поддерживает Ñоздание каталогов The protocol `%1' does not support removing files or directories - Протокол `%1' не поддерживает удаление файлов или каталогов + Протокол `%1' не поддерживает удаление файлов или каталогов The protocol `%1' does not support renaming files or directories - Протокол `%1' не поддерживает переименование файлов или каталогов + Протокол `%1' не поддерживает переименование файлов или каталогов The protocol `%1' does not support getting files - Протокол `%1' не поддерживает доÑтавку файлов + Протокол `%1' не поддерживает доÑтавку файлов The protocol `%1' does not support putting files - Протокол `%1' не поддерживает отправку файлов + Протокол `%1' не поддерживает отправку файлов The protocol `%1' does not support copying or moving files or directories - Протокол `%1' не поддерживает копирование или перемещение файлов и каталогов + Протокол `%1' не поддерживает копирование или перемещение файлов или каталогов (unknown) - (неизвеÑтно) + (неизвеÑтно) @@ -801,27 +799,27 @@ to &Cancel - &Отмена + &Отмена < &Back - < &Ðазад + < &Ðазад &Next > - &Вперед > + &Вперед > &Finish - &Финиш + &Закончить &Help - &Справка + &Справка @@ -832,68 +830,67 @@ to Host not found - + Узел не найден Connection refused - Отказано в Ñоединении + Отказано в Ñоединении Connection timed out - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° Ñоединение иÑтекло Operation on socket is not supported - + ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ñ Ñокетом не поддерживаетÑÑ Socket operation timed out - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° операцию Ñ Ñокетом иÑтекло Socket is not connected - + Сокет не подключён Network unreachable - + Сеть недоÑтупна QAbstractSpinBox - + &Step up - + Шаг вв&ерх Step &down - + Шаг вн&из &Select All - + &Выделить вÑе QApplication - - QT_LAYOUT_DIRECTION - Translate this string to the string 'LTR' in left-to-right languages or to 'RTL' in right-to-left languages (such as Hebrew and Arabic) to get proper widget layout. - LTR + + Activate + Ðктивировать @@ -906,37 +903,38 @@ to Ошибка ÑовмеÑтимоÑти библиотеки Qt - - Activate - + + QT_LAYOUT_DIRECTION + Translate this string to the string 'LTR' in left-to-right languages or to 'RTL' in right-to-left languages (such as Hebrew and Arabic) to get proper widget layout. + LTR - + Activates the program's main window - + Ðктивирует главное окно программы QAxSelect - + Select ActiveX Control - + Выберите компоненту ActiveX - + OK - OK + Готово - + &Cancel - &Отмена + &Отмена - + COM &Object: - + COM &Объект: @@ -944,17 +942,17 @@ to Uncheck - + СнÑть отметку Check - + Отметить Toggle - + Переключить @@ -977,17 +975,17 @@ to &Red: - &КраÑ: + &КраÑный: &Green: - &Зел: + &Зелёный: Bl&ue: - С&ин: + С&иний: @@ -997,7 +995,7 @@ to Select Color - + Выберите цвет @@ -1007,28 +1005,12 @@ to &Custom colors - &СобÑтвенные цвета - - - &Define Custom Colors >> - &Выбрать ÑобÑтвенные цвета >> - - - OK - OK - - - Cancel - Отмена + &Произвольные цвета &Add to Custom Colors - &Добавить к ÑобÑтвенным цветам - - - Select color - Выбрать цвет + &Добавить к произвольным цветам @@ -1037,22 +1019,22 @@ to Open - Открыть + Открыть False - False + Ðет True - True + Да Close - Закрыть + Закрыть @@ -1061,19 +1043,19 @@ to %1: key is empty QSystemSemaphore - + %1: пуÑтой ключ %1: unable to make key QSystemSemaphore - + %1: невозможно Ñоздать ключ %1: ftok failed QSystemSemaphore - + %1: ошибка ftok @@ -1081,22 +1063,22 @@ to Unable to connect - + Ðевозможно ÑоединитьÑÑ Unable to commit transaction - + Ðевозможно выполнить транзакцию Unable to rollback transaction - + Ðевозможно откатить транзакцию Unable to set autocommit - + Ðевозможно уÑтановить автовыполнение транзакции @@ -1105,32 +1087,32 @@ to Unable to execute statement - + Ðевозможно выполнить выражение Unable to prepare statement - + Ðевозможно подготовить выражение Unable to bind variable - + Ðевозможно привÑзать значение Unable to fetch record %1 - + Ðевозможно получить запиÑÑŒ %1 Unable to fetch next - + Ðевозможно получить Ñледующую Ñтроку Unable to fetch first - + Ðевозможно получить первую Ñтроку @@ -1184,162 +1166,162 @@ to Done - + Готово QDialogButtonBox - + OK - OK + Готово - - Save - Сохранить + + &OK + &Готово - + &Save - &Сохранить + &Сохранить + + + + Save + Сохранить Open - Открыть + Открыть - Cancel - Отмена + &Cancel + &Отмена - &Cancel - &Отмена + Cancel + Отмена - Close - Закрыть + &Close + &Закрыть - &Close - &Закрыть + Close + Закрыть Apply - Применить + Применить Reset - + СброÑить Help - Справка + Справка Don't Save - + Ðе ÑохранÑть Discard - + Ðе применÑть &Yes - &Да + Д&а Yes to &All - + Да Ð´Ð»Ñ &вÑех &No - &Ðет + &Ðет N&o to All - + Ð&ет Ð´Ð»Ñ Ð²Ñех Save All - + Сохранить вÑе Abort - + Прервать Retry - + Попробовать ещё Ignore - + Игнорировать Restore Defaults - + ВоÑÑтановить Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Ð¿Ð¾ умолчанию Close without Saving - - - - - &OK - &OK + Закрыть без ÑÐ¾Ñ…Ñ€Ð°Ð½ÐµÐ½Ð¸Ñ QDirModel - + Name - Ð˜Ð¼Ñ + Ð˜Ð¼Ñ Size - Размер + Размер Kind Match OS X Finder - + Вид Type All other platforms - Тип + Тип Date Modified - + Дата Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ @@ -1347,7 +1329,7 @@ to Close - Закрыть + Закрыть @@ -1365,28 +1347,18 @@ to More - + Больше Less - + Меньше QErrorMessage - - &Show this message again - &Показывать Ñто Ñообщение в дальнейшем - - - - &OK - &OK - - - + Debug Message: Отладочное Ñообщение: @@ -1400,326 +1372,376 @@ to Fatal Error: КритичеÑÐºÐ°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ°: + + + &Show this message again + &Показывать Ñто Ñообщение в дальнейшем + + + + &OK + &Готово + QFile - + Destination file exists - + Файл ÑущеÑтвует + + + + Will not rename sequential file using block copy + Ðе будет переименовывать поÑледовательный файл, иÑÐ¿Ð¾Ð»ÑŒÐ·ÑƒÑ ÐºÐ¾Ð¿Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ðµ блока - + Cannot remove source file - + Ðевозможно удалить иÑходный файл - + Cannot open %1 for input - + Ðевозможно открыть %1 Ð´Ð»Ñ Ð²Ð²Ð¾Ð´Ð° Cannot open for output - + Ðевозможно открыть Ð´Ð»Ñ Ð²Ñ‹Ð²Ð¾Ð´Ð° Failure to write block - + Сбой запиÑи блока Cannot create %1 for output - + Ðевозможно Ñоздать %1 Ð´Ð»Ñ Ð²Ñ‹Ð²Ð¾Ð´Ð° QFileDialog - - + + All Files (*) Ð’Ñе файлы (*) - - - Back - Ðазад - - - - - List View - СпиÑок + + Directories + Каталоги - - - Detail View - Детальный вид + + + + + &Open + &Открыть - - - File - Файл + + + &Save + &Сохранить - + Open Открыть - - Save As - Сохранить как - - - - - - - &Open - &Открыть + + %1 already exists. +Do you want to replace it? + %1 уже ÑущеÑтвует. +Хотите заменить его? - - - &Save - &Сохранить + + %1 +File not found. +Please verify the correct file name was given. + %1 +Файл не найден. +Проверьте правильноÑть заданного имени файла. - - Recent Places - + + My Computer + Мой компьютер - + &Rename - &Переименовать + &Переименовать &Delete - &Удалить + &Удалить Show &hidden files - Показать &Ñкрытые файлы + Показать Ñкр&ытые файлы - - New Folder - Ðовый каталог + + + Back + Ðазад - - Find Directory - Ðайти каталог + + + Parent Directory + РодительÑкий каталог - - Directories - Каталоги + + + List View + СпиÑок - - All Files (*.*) - Ð’Ñе файлы (*.*) + + + Detail View + Подробный вид - - - Directory: - Каталог: + + + Files of type: + Типы файлов: - - %1 already exists. -Do you want to replace it? - + + + Directory: + Каталог: - + + %1 -File not found. -Please verify the correct file name was given. - +Directory not found. +Please verify the correct directory name was given. + %1 +Каталог не найден. +Проверьте правильноÑть заданного имени каталога. - - My Computer - + + '%1' is write protected. +Do you want to delete it anyway? + '%1' защищён от запиÑи. +Ð’ÑÑ‘-равно хотите удалить? - - - Parent Directory - - + + Are sure you want to delete '%1'? + Ð’Ñ‹ уверены, что хотите удалить '%1'? + - - - Files of type: - + + Could not delete directory. + Ðе удалоÑÑŒ удалить каталог. - - - %1 -Directory not found. -Please verify the correct directory name was given. - + + Recent Places + Ðедавние документы - - '%1' is write protected. -Do you want to delete it anyway? - + + All Files (*.*) + Ð’Ñе файлы (*.*) + + + + Save As + Сохранить как + + + + Drive + ДиÑк + + + + + File + Файл - Are sure you want to delete '%1'? - + File Folder + Match Windows Explorer + Каталог Ñ Ñ„Ð°Ð¹Ð»Ð°Ð¼Ð¸ - - Could not delete directory. - + + Folder + All other platforms + Каталог - - Drive - + + Alias + Mac OS X Finder + ПÑевдоним - + + Shortcut + All other platforms + Ярлык + + + Unknown - + ÐеизвеÑтно + + + + Find Directory + Ðайти каталог - + Show - + Показать - - + + Forward - Вперед + Вперед - + + New Folder + Ðовый каталог + + + &New Folder - + &Ðовый каталог - + &Choose - + &Выбрать - + Remove - + Удалить - - + + File &name: - &Ð˜Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð°: + &Ð˜Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð°: - - + + Look in: - + Перейти к: - - + + Create New Folder - Создать новый каталог + Создать каталог QFileSystemModel - - %1 TB - - - - - %1 GB - - - - - %1 MB - - - - - %1 KB - - - - - %1 bytes - - - - + Invalid filename - + Ðекорректное Ð¸Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð° <b>The name "%1" can not be used.</b><p>Try using another name, with fewer characters or no punctuations marks. - + <b>Ð˜Ð¼Ñ "%1" не может быть иÑпользовано.</b><p>Попробуйте иÑпользовать Ð¸Ð¼Ñ Ð¼ÐµÐ½ÑŒÑˆÐµÐ¹ длины и/или без Ñимволов пунктуации. Name - Ð˜Ð¼Ñ + Ð˜Ð¼Ñ Size - Размер + Размер Kind Match OS X Finder - + Вид Type All other platforms - Тип + Тип Date Modified - + Дата Ð¸Ð·Ð¼ÐµÐ½ÐµÐ½Ð¸Ñ - + My Computer - + Мой компьютер Computer - + Компьютер + + + + + %1 TB + %1 Тб + + + + + %1 GB + %1 Гб + + + + + %1 MB + %1 Мб + + + + + %1 KB + %1 Кб + + + + + %1 bytes + %1 байт @@ -1728,70 +1750,70 @@ Do you want to delete it anyway? Normal - + Обычный Bold - + Жирный Demi Bold - + Срендней жирноÑти Black - + Чёрный Demi - + Средний Light - + Лёгкий Italic - + КурÑив Oblique - + Ðаклонный Any - + Ð›ÑŽÐ±Ð°Ñ Latin - + Латиница Greek - + ГречеÑкий Cyrillic - + Кириллица @@ -1949,7 +1971,7 @@ Do you want to delete it anyway? Font st&yle - &Стиль шрифта + Ст&иль шрифта @@ -1964,12 +1986,12 @@ Do you want to delete it anyway? Stri&keout - &Перечеркивать + Зачёр&кнутый &Underline - П&одчеркивать + П&одчёркнутый @@ -1977,74 +1999,59 @@ Do you want to delete it anyway? Пример - - - Select Font - Выбрать шрифт + + Wr&iting System + &СиÑтема пиÑьма - - Wr&iting System - + + + Select Font + Выберите шрифт QFtp - - Host %1 found - Обнаружен узел %1 - - - - Host found - Узел обнаружен - - - - - - Connected to host %1 - УÑтановлено Ñоединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 - - - - Connected to host - Соединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ уÑтановлено - - - - Connection to %1 closed - Соединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 разорвано - - - - - - Connection closed - Соединение разорвано + + + Not connected + Соединение не уÑтановлено - - + + Host %1 not found - Узел %1 не обнаружен + Узел %1 не найден Connection refused to host %1 - Отказано в Ñоединении Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 + Ð’ Ñоединении Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 отказано Connection timed out to host %1 - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° Ñоединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 иÑтекло + + + + + + Connected to host %1 + УÑтановлено Ñоединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 + + + + + Connection refused for data connection + Отказ в Ñоединении Ð´Ð»Ñ Ð¿ÐµÑ€ÐµÐ´Ð°Ñ‡Ð¸ данных - + - + Unknown error ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° @@ -2054,7 +2061,7 @@ Do you want to delete it anyway? Connecting to host failed: %1 - Ошибка ÑÐ¾ÐµÐ´Ð¸Ð½ÐµÐ½Ð¸Ñ Ñ ÑƒÐ·Ð»Ð¾Ð¼: + Ðе удалоÑÑŒ ÑоединитьÑÑ Ñ ÑƒÐ·Ð»Ð¾Ð¼: %1 @@ -2062,7 +2069,7 @@ Do you want to delete it anyway? Login failed: %1 - Ошибка входа в ÑиÑтему: + Ðе удалоÑÑŒ авторизоватьÑÑ: %1 @@ -2070,7 +2077,7 @@ Do you want to delete it anyway? Listing directory failed: %1 - Ошибка проÑмотра каталога: + Ðе удалоÑÑŒ прочитать каталог: %1 @@ -2078,7 +2085,7 @@ Do you want to delete it anyway? Changing directory failed: %1 - Ошибка Ñмены каталога: + Ðе удалоÑÑŒ Ñменить каталог: %1 @@ -2086,7 +2093,7 @@ Do you want to delete it anyway? Downloading file failed: %1 - Ошибка загрузки файла: + Ðе удалоÑÑŒ загрузить файл: %1 @@ -2094,7 +2101,7 @@ Do you want to delete it anyway? Uploading file failed: %1 - Ошибка отправки файла: + Ðе удалоÑÑŒ отгрузить файл: %1 @@ -2102,7 +2109,7 @@ Do you want to delete it anyway? Removing file failed: %1 - Ошибка ÑƒÐ´Ð°Ð»ÐµÐ½Ð¸Ñ Ñ„Ð°Ð¹Ð»Ð°: + Ðе удалоÑÑŒ удалить файл: %1 @@ -2110,7 +2117,7 @@ Do you want to delete it anyway? Creating directory failed: %1 - Ошибка ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ ÐºÐ°Ñ‚Ð°Ð»Ð¾Ð³Ð°: + Ðе удалоÑÑŒ Ñоздать каталог: %1 @@ -2118,20 +2125,35 @@ Do you want to delete it anyway? Removing directory failed: %1 - Ошибка ÑƒÐ´Ð°Ð»ÐµÐ½Ð¸Ñ ÐºÐ°Ñ‚Ð°Ð»Ð¾Ð³Ð°: + Ðе удалоÑÑŒ удалить каталог: %1 - - - Not connected - Ðет ÑÐ¾ÐµÐ´Ð¸Ð½ÐµÐ½Ð¸Ñ + + + + Connection closed + Соединение закрыто - - - Connection refused for data connection - Отказано в Ñоединении передачи данных + + Host %1 found + Узел %1 найден + + + + Connection to %1 closed + Соединение Ñ %1 закрыто + + + + Host found + Узел найден + + + + Connected to host + Соединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ @@ -2139,7 +2161,7 @@ Do you want to delete it anyway? Unknown error - ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° @@ -2149,12 +2171,12 @@ Do you want to delete it anyway? - + Host not found - + Узел не найден @@ -2162,331 +2184,331 @@ Do you want to delete it anyway? Unknown address type - + ÐеизвеÑтный тип адреÑа Unknown error - ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° QHttp - - - Connection refused - Отказано в Ñоединении - - - - - - Host %1 not found - Узел %1 не обнаружен + + + + + Unknown error + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° - - - Wrong content length - ÐÐµÐ²ÐµÑ€Ð½Ð°Ñ Ð´Ð»Ð¸Ð½Ð° данных + + + Request aborted + Ð—Ð°Ð¿Ñ€Ð¾Ñ Ð¿Ñ€ÐµÑ€Ð²Ð°Ð½ - - HTTPS connection requested but SSL support not compiled in - + + + No server set to connect to + Ðе указан Ñервер Ð´Ð»Ñ Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ - - - - - HTTP request failed - Ошибка HTTP-запроÑа + + + Wrong content length + ÐÐµÐ²ÐµÑ€Ð½Ð°Ñ Ð´Ð»Ð¸Ð½Ð° Ñодержимого - - Host %1 found - Обнаружен узел %1 + + + Server closed connection unexpectedly + Сервер неожиданно разорвал Ñоединение - - Host found - Узел обнаружен + + Unknown authentication method + ÐеизвеÑтный метод авторизации - - Connected to host %1 - УÑтановлено Ñоединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 + + Error writing response to device + Ошибка запиÑи ответа на уÑтройÑтво - - Connected to host - Соединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ уÑтановлено + + + Connection refused + Отказано в Ñоединении - - Connection to %1 closed - Соединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 разорвано + + + + Host %1 not found + Узел %1 не найден - - - Connection closed - Соединение разорвано + + + + + HTTP request failed + HTTP-Ð·Ð°Ð¿Ñ€Ð¾Ñ Ð½Ðµ удалÑÑ - - - - - Unknown error - ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° + + + Invalid HTTP response header + Ðекорректный HTTP-заголовок ответа - - - Request aborted - Ð—Ð°Ð¿Ñ€Ð¾Ñ Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½ + + + + + Invalid HTTP chunked body + Ðекорректное HTTP-фрагментирование данных - - - No server set to connect to - Ðе выбран Ñервер Ð´Ð»Ñ Ð¿Ð¾Ð´ÐºÐ»ÑŽÑ‡ÐµÐ½Ð¸Ñ + + Host %1 found + Узел %1 найден - - - Server closed connection unexpectedly - Ðеожиданный разрыв ÑÐ¾ÐµÐ´Ð¸Ð½ÐµÐ½Ð¸Ñ Ñервером + + Connected to host %1 + УÑтановлено Ñоединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 - - - Invalid HTTP response header - Получен некорректный HTTP-заголовок + + Connection to %1 closed + Соединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ %1 закрыто - - Unknown authentication method - + + Host found + Узел найден - - - - - Invalid HTTP chunked body - Ðекорректный HTTP-ответ + + Connected to host + Соединение Ñ ÑƒÐ·Ð»Ð¾Ð¼ уÑтановлено - - Error writing response to device - + + + Connection closed + Соединение закрыто - + Proxy authentication required - + ТребуетÑÑ Ð°Ð²Ñ‚Ð¾Ñ€Ð¸Ð·Ð°Ñ†Ð¸Ñ Ð½Ð° прокÑи-Ñервере Authentication required - + ТребуетÑÑ Ð°Ð²Ñ‚Ð¾Ñ€Ð¸Ð·Ð°Ñ†Ð¸Ñ Connection refused (or timed out) - + Ð’ Ñоединении отказано (или Ð²Ñ€ÐµÐ¼Ñ Ð¾Ð¶Ð¸Ð´Ð°Ð½Ð¸Ñ Ð¸Ñтекло) Proxy requires authentication - + ПрокÑи-Ñервер требует авторизацию Host requires authentication - + Узел требует авторизацию Data corrupted - + Данные повреждены Unknown protocol specified - + Указан неизвеÑтный протокол SSL handshake failed + + + HTTPS connection requested but SSL support not compiled in + Запрошено Ñоединение по протоколу HTTPS, но поддержка SSL не Ñкомпилирована + QHttpSocketEngine Did not receive HTTP response from proxy - + Ðе получен HTTP-ответ от прокÑи-Ñервера Error parsing authentication request from proxy - + Ошибка разбора запроÑа авторизации от прокÑи-Ñервера Authentication required - + ТребуетÑÑ Ð°Ð²Ñ‚Ð¾Ñ€Ð¸Ð·Ð°Ñ†Ð¸Ñ Proxy denied connection - + ПрокÑи-Ñервер запретил Ñоединение Error communicating with HTTP proxy - + Ошибка обмена данными Ñ Ð¿Ñ€Ð¾ÐºÑи-Ñервером HTTP Proxy server not found - + ПрокÑи-Ñервер не найден Proxy connection refused - + Ð’ Ñоединении прокÑи-Ñервером отказано Proxy server connection timed out - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° Ñоединение Ñ Ð¿Ñ€Ð¾ÐºÑи-Ñервером иÑтекло Proxy connection closed prematurely - + Соединение Ñ Ð¿Ñ€Ð¾ÐºÑи-Ñервером неожиданно закрыто QIBaseDriver - + Error opening database - + Ðевозможно открыть базу данных Could not start transaction - + Ðе удалоÑÑŒ начать транзакцию Unable to commit transaction - + Ðевозможно выполнить транзакцию Unable to rollback transaction - + Ðевозможно откатить транзакцию QIBaseResult - + Unable to create BLOB - + Ðевозможно Ñоздать BLOB Unable to write BLOB - + Ðевозможно запиÑать BLOB Unable to open BLOB - + Ðевозможно открыть BLOB Unable to read BLOB - + Ðевозможно прочитать BLOB - + Could not find array - + Ðе удалоÑÑŒ найти маÑÑив - + Could not get array data - + Ðе удалоÑÑŒ найти данные маÑÑива - + Could not get query info - + Ðе удалоÑÑŒ найти информацию о запроÑе Could not start transaction - + Ðе удалоÑÑŒ начать транзакцию Unable to commit transaction - + Ðевозможно выполнить транзакцию Could not allocate statement - + Ðе удалоÑÑŒ получить реÑурÑÑ‹ Ð´Ð»Ñ ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ Ð²Ñ‹Ñ€Ð°Ð¶ÐµÐ½Ð¸Ñ Could not prepare statement - + Ðе удалоÑÑŒ подготовить выражение Could not describe input statement - + Ðе удалоÑÑŒ опиÑать входÑщее выражение Could not describe statement - + Ðе удалоÑÑŒ опиÑать выражение Unable to close statement - + Ðевозможно закрыть выражение Unable to execute query - + Ðевозможно выполнить Ð·Ð°Ð¿Ñ€Ð¾Ñ Could not fetch next item - + Ðе удалоÑÑŒ получить Ñледующий Ñлемент Could not get statement info - + Ðе удалоÑÑŒ найти информацию о выражении @@ -2494,27 +2516,27 @@ Do you want to delete it anyway? Permission denied - + ДоÑтуп запрещён Too many open files - + Слишком много открытых файлов No such file or directory - + Файл или каталог не ÑущеÑтвует No space left on device - + Ðет Ñвободного меÑта на уÑтройÑтве - + Unknown error - ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° @@ -2545,7 +2567,7 @@ Do you want to delete it anyway? Enter a value: - + Укажите значение: @@ -2553,66 +2575,66 @@ Do you want to delete it anyway? Could not mmap '%1': %2 - + Ðе удалоÑÑŒ выполнить mmap '%1': %2 Plugin verification data mismatch in '%1' - + ÐŸÑ€Ð¾Ð²ÐµÑ€Ð¾Ñ‡Ð½Ð°Ñ Ð¸Ð½Ñ„Ð¾Ñ€Ð¼Ð°Ñ†Ð¸Ñ Ð´Ð»Ñ Ð¼Ð¾Ð´ÑƒÐ»Ñ '%1' не Ñовпадает Could not unmap '%1': %2 - + Ðе удалоÑÑŒ выполнить unmap '%1': %2 The plugin '%1' uses incompatible Qt library. (%2.%3.%4) [%5] - + Модуль '%1' иÑпользует неÑомеÑтимую библиотеку Qt. (%2.%3.%4) [%5] The plugin '%1' uses incompatible Qt library. Expected build key "%2", got "%3" - + Плагин '%1' иÑпользует неÑомеÑтимую библиотеку Qt. ОжидаетÑÑ ÐºÐ»ÑŽÑ‡ "%2", но получен ключ "%3" Unknown error - ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° The shared library was not found. - + ДинамичеÑÐºÐ°Ñ Ð±Ð¸Ð±Ð»Ð¸Ð¾Ñ‚ÐµÐºÐ° не найдена. The file '%1' is not a valid Qt plugin. - + Файл '%1' - не может быть корректным модулем Qt. The plugin '%1' uses incompatible Qt library. (Cannot mix debug and release libraries.) - + Плагин '%1' иÑпользует неÑомеÑтимую библиотеку Qt. (ÐÐµÐ»ÑŒÐ·Ñ Ñовмещать релизные и отладочные библиотеки.) Cannot load library %1: %2 - + Ðевозможно загрузить библиотеку %1: %2 Cannot unload library %1: %2 - + Ðевозможно выгрузить библиотеку %1: %2 Cannot resolve symbol "%1" in %2: %3 - + Ðевозможно разрешить Ñимвол "%1" в %2: %3 @@ -2620,62 +2642,61 @@ Do you want to delete it anyway? &Undo - &Отменить + &Отменить дейÑтвие &Redo - &Повторить + &Повторить дейÑтвие Cu&t - &Вырезать + &Вырезать &Copy - &Копировать + &Копировать &Paste - Ð’&Ñтавить + Ð’&Ñтавить - - Select All - Выделить вÑе + + Delete + Удалить - - Delete - Удалить + + Select All + Выделить вÑе QLocalServer - + %1: Name error - + %1: Ðекорректное Ð¸Ð¼Ñ %1: Permission denied - + %1: ДоÑтуп запрещён %1: Address in use - + %1: ÐÐ´Ñ€ÐµÑ Ð¸ÑпользуетÑÑ - %1: Unknown error %2 - + %1: ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° %2 @@ -2684,13 +2705,13 @@ Do you want to delete it anyway? %1: Connection refused - + %1: Отказано в Ñоединении %1: Remote closed - + %1: Удалённое закрытие @@ -2698,143 +2719,143 @@ Do you want to delete it anyway? %1: Invalid name - + %1: Ðекорректное Ð¸Ð¼Ñ %1: Socket access error - + %1: Ошибка Ð¾Ð±Ñ€Ð°Ñ‰ÐµÐ½Ð¸Ñ Ðº Ñокету %1: Socket resource error - + %1: Ошибка Ð²Ñ‹Ð´ÐµÐ»ÐµÐ½Ð¸Ñ Ñ€ÐµÑурÑов Ñокета %1: Socket operation timed out - + %1: Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° операцию Ñ Ñокетом иÑтекло %1: Datagram too large - + %1: Датаграмма Ñлишком Ð±Ð¾Ð»ÑŒÑˆÐ°Ñ %1: Connection error - + %1: Ошибка ÑÐ¾ÐµÐ´Ð¸Ð½ÐµÐ½Ð¸Ñ %1: The socket operation is not supported - + %1: ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ñ Ñокетом не поддерживаетÑÑ %1: Unknown error - + %1: ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° %1: Unknown error %2 - + %1: ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° %2 QMYSQLDriver - + Unable to open database ' - + Ðевозможно открыть базу данных ' Unable to connect - + Ðевозможно ÑоединитьÑÑ - + Unable to begin transaction - + Ðевозможно начать транзакцию Unable to commit transaction - + Ðевозможно выполнить транзакцию Unable to rollback transaction - + Ðевозможно откатить транзакцию QMYSQLResult - + Unable to fetch data - + Ðевозможно получить данные - + Unable to execute query - + Ðевозможно выполнить Ð·Ð°Ð¿Ñ€Ð¾Ñ Unable to store result - + Ðевозможно Ñохранить результат - + Unable to prepare statement - + Ðевозможно подготовить выражение - + Unable to reset statement - + Ðевозможно ÑброÑить выражение - + Unable to bind value - + Ðевозможно привÑзать значение Unable to execute statement - + Ðевозможно выполнить выражение Unable to bind outvalues - + Ðевозможно привÑзать результирующие Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ Unable to store statement results - + Ðевозможно Ñохранить результат Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Ð²Ñ‹Ñ€Ð°Ð¶ÐµÐ½Ð¸Ñ - + Unable to execute next query - + Ðевозможно выполнить Ñледующий Ð·Ð°Ð¿Ñ€Ð¾Ñ Unable to store next result - + Ðевозможно Ñохранить Ñледующий результат @@ -2842,7 +2863,7 @@ Do you want to delete it anyway? (Untitled) - + (Ðеозаглавлено) @@ -2850,92 +2871,92 @@ Do you want to delete it anyway? %1 - [%2] - %1 - [%2] + %1 - [%2] Close - Закрыть + Закрыть Minimize - Свернуть + Минимизировать Restore Down - ВоÑÑтановить + ВоÑÑтановить &Restore - &ВоÑÑтановить + &ВоÑÑтановить &Move - &ПеремеÑтить + &ПеремеÑтить &Size - &Размер + &Размер Mi&nimize - &Свернуть + &Минимизировать Ma&ximize - Р&азвернуть + Р&аÑпахнуть Stay on &Top - Ð’Ñегда &наверху + ОÑтаватьÑÑ &Ñверху &Close - &Закрыть + &Закрыть - [%1] - + - [%1] Maximize - Развернуть + РаÑпахнуть Unshade - + ВоÑÑтановить из заголовка Shade - + Свернуть в заголовок Restore - + ВоÑÑтановить Help - Справка + Справка Menu - Меню + Меню @@ -2944,91 +2965,68 @@ Do you want to delete it anyway? Close - Закрыть + Закрыть Open - Открыть + Открыть Execute - + Выполнить - QMenuBar - - About - О программе - - - Config - ÐšÐ¾Ð½Ñ„Ð¸Ð³ÑƒÑ€Ð°Ñ†Ð¸Ñ - - - Preference - ÐаÑтройки - - - Options - Параметры - - - Setting - ÐаÑтройки - - - Setup - ÐаÑтройки - - - Quit - Выход - + QMessageBox - Exit - Выход + + Help + Справка - - - QMessageBox - - + + OK - OK + Готово + + + + <h3>About Qt</h3><p>This program uses Qt version %1.</p><p>Qt is a C++ toolkit for cross-platform application development.</p><p>Qt provides single-source portability across MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, and all major commercial Unix variants. Qt is also available for embedded devices as Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt is available under three different licensing options designed to accommodate the needs of our various users.</p>Qt licensed under our commercial license agreement is appropriate for development of proprietary/commercial software where you do not want to share any source code with third parties or otherwise cannot comply with the terms of the GNU LGPL version 2.1 or GNU GPL version 3.0.</p><p>Qt licensed under the GNU LGPL version 2.1 is appropriate for the development of Qt applications (proprietary or open source) provided you can comply with the terms and conditions of the GNU LGPL version 2.1.</p><p>Qt licensed under the GNU General Public License version 3.0 is appropriate for the development of Qt applications where you wish to use such applications in combination with software subject to the terms of the GNU GPL version 3.0 or where you are otherwise willing to comply with the terms of the GNU GPL version 3.0.</p><p>Please see <a href="http://www.qtsoftware.com/products/licensing">www.qtsoftware.com/products/licensing</a> for an overview of Qt licensing.</p><p>Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).</p><p>Qt is a Nokia product. See <a href="http://www.qtsoftware.com/qt/">www.qtsoftware.com/qt</a> for more information.</p> + <h3>О Qt</h3><p>Ð”Ð°Ð½Ð½Ð°Ñ Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð° иÑпользует Qt верÑии %1.</p><p>Qt - Ñто инÑтрумент Ð´Ð»Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ крÑÑплатформенных приложений на C++.</p><p>Qt предоÑтавлÑет переноÑимоÑть между MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux и вÑеми популÑрными вариантами коммерчеÑкой Unix. Также Qt доÑтупна Ð´Ð»Ñ Ð²Ñтраиваемых уÑтройÑтв в виде Qt Ð´Ð»Ñ Embedded Linux и Qt Ð´Ð»Ñ Windows CE.</p><p>Qt доÑтупна под Ñ‚Ñ€ÐµÐ¼Ñ Ñ€Ð°Ð·Ð»Ð¸Ñ‡Ð½Ñ‹Ð¼Ð¸ лицензиÑми, разработанными Ð´Ð»Ñ ÑƒÐ´Ð¾Ð²Ð»ÐµÑ‚Ð²Ð¾Ñ€ÐµÐ½Ð¸Ñ Ñ‚Ñ€ÐµÐ±Ð¾Ð²Ð°Ð½Ð¸Ð¹ различных пользователей.</p>Qt, Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð°Ñ Ð½Ð°ÑˆÐµÐ¹ коммерчеÑкой лицензией, предназначена Ð´Ð»Ñ Ñ€Ð°Ð·Ð²Ð¸Ñ‚Ð¸Ñ Ð¿Ñ€Ð¾Ð¿Ñ€Ð¸ÐµÑ‚Ð°Ñ€Ð½Ð¾Ð³Ð¾/коммерчеÑкого программного обеÑпечениÑ, когда Ð’Ñ‹ не желаете предоÑтавлÑть иÑходные коды третьим Ñторонам; коммерчеÑÐºÐ°Ñ Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸Ñ Ð½Ðµ ÑоответÑтвует уÑловиÑм лицензий GNU LGPL верÑии 2.1 или GNU GPL верÑии 3.0.</p><p>Qt под лицензией GNU LGPL верÑии 2.1 предназначена Ð´Ð»Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ программного обеÑÐ¿ÐµÑ‡ÐµÐ½Ð¸Ñ Ñ Ð¾Ñ‚ÐºÑ€Ñ‹Ñ‚Ñ‹Ð¼ иÑходным кодом или коммерчеÑкого программного обеÑÐ¿ÐµÑ‡ÐµÐ½Ð¸Ñ Ð¿Ñ€Ð¸ Ñоблюдении Ñроков и уÑловий лицензии GNU LGPL верÑии 2.1.</p><p>Qt под лицензией GNU General Public License верÑии 3.0 предназначена Ð´Ð»Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ программных приложений в тех ÑлучаÑÑ…, когда Ð’Ñ‹ хотели бы иÑпользовать такие Ð¿Ñ€Ð¸Ð»Ð¾Ð¶ÐµÐ½Ð¸Ñ Ð² Ñочетании Ñ Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð½Ñ‹Ð¼ обеÑпечением на уÑловиÑÑ… лицензии GNU GPL Ñ Ð²ÐµÑ€Ñии 3.0 или еÑли Ð’Ñ‹ готовы Ñоблюдать уÑÐ»Ð¾Ð²Ð¸Ñ Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸Ð¸ GNU GPL верÑии 3.0.</p><p>ОбратитеÑÑŒ к <a href="http://www.qtsoftware.com/products/licensing">www.qtsoftware.com/products/licensing</a> Ð´Ð»Ñ Ð¾Ð±Ð·Ð¾Ñ€Ð° лицензий Qt.</p><p>Copyright (C) 2009 ÐšÐ¾Ñ€Ð¿Ð¾Ñ€Ð°Ñ†Ð¸Ñ Nokia и/или её дочерние подразделениÑ.</p><p>Qt - продукт Nokia. ОбратитеÑÑŒ к <a href="http://www.qtsoftware.com/qt/">www.qtsoftware.com/qt</a> Ð´Ð»Ñ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð¹ информации.</p> - + About Qt - + О Qt - - Help - Справка + <p>This program uses Qt version %1.</p> + <p>Ð”Ð°Ð½Ð½Ð°Ñ Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð° иÑпользует Qt верÑии %1.</p> - + Show Details... - + Показать подробноÑти... Hide Details... - + Скрыть подробноÑти... - - <h3>About Qt</h3><p>This program uses Qt version %1.</p><p>Qt is a C++ toolkit for cross-platform application development.</p><p>Qt provides single-source portability across MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, and all major commercial Unix variants. Qt is also available for embedded devices as Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt is available under three different licensing options designed to accommodate the needs of our various users.</p>Qt licensed under our commercial license agreement is appropriate for development of proprietary/commercial software where you do not want to share any source code with third parties or otherwise cannot comply with the terms of the GNU LGPL version 2.1 or GNU GPL version 3.0.</p><p>Qt licensed under the GNU LGPL version 2.1 is appropriate for the development of Qt applications (proprietary or open source) provided you can comply with the terms and conditions of the GNU LGPL version 2.1.</p><p>Qt licensed under the GNU General Public License version 3.0 is appropriate for the development of Qt applications where you wish to use such applications in combination with software subject to the terms of the GNU GPL version 3.0 or where you are otherwise willing to comply with the terms of the GNU GPL version 3.0.</p><p>Please see <a href="http://www.qtsoftware.com/products/licensing">www.qtsoftware.com/products/licensing</a> for an overview of Qt licensing.</p><p>Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).</p><p>Qt is a Nokia product. See <a href="http://www.qtsoftware.com/qt/">www.qtsoftware.com/qt</a> for more information.</p> - + <h3>About Qt</h3>%1<p>Qt is a C++ toolkit for cross-platform application development.</p><p>Qt provides single-source portability across MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, and all major commercial Unix variants. Qt is also available for embedded devices as Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt is a Nokia product. See <a href="http://qtsoftware.com/qt/">qtsoftware.com/qt/</a> for more information.</p> + <h3>О Qt</h3>%1<p>Qt - Ñто инÑтрумент Ð´Ð»Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚Ñ‡ÐºÐ¸ крÑÑплатформенных приложений на C++.</p><p>Qt предоÑтавлÑет переноÑимоÑть между MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux и вÑеми популÑрными вариантами коммерчеÑкой Unix. Также Qt доÑтупна Ð´Ð»Ñ Ð²Ñтраиваемых уÑтройÑтв в виде Qt for Embedded Linux и Qt for Windows CE.</p><p>Qt - продукт Nokia. ОбратитеÑÑŒ к <a href="http://qtsoftware.com/qt/">qtsoftware.com/qt/</a> Ð´Ð»Ñ Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð´Ð¾Ð¿Ð¾Ð»Ð½Ð¸Ñ‚ÐµÐ»ÑŒÐ½Ð¾Ð¹ информации.</p> + + + <p>This program uses Qt Open Source Edition version %1.</p><p>Qt Open Source Edition is intended for the development of Open Source applications. You need a commercial Qt license for development of proprietary (closed source) applications.</p><p>Please see <a href="http://qtsoftware.com/company/model/">qtsoftware.com/company/model/</a> for an overview of Qt licensing.</p> + <p>Ð”Ð°Ð½Ð½Ð°Ñ Ð¿Ñ€Ð¾Ð³Ñ€Ð°Ð¼Ð¼Ð° иÑпользует Qt Open Source Edition верÑии %1.</p><p>Qt Open Source Edition предназначена Ð´Ð»Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ Open Source приложений. Ð”Ð»Ñ Ñ€Ð°Ð·Ñ€Ð°Ð±Ð¾Ñ‚ÐºÐ¸ проприетарных (Ñ Ð·Ð°ÐºÑ€Ñ‹Ñ‚Ñ‹Ð¼ иÑходным кодом) приложений необходима коммерчеÑÐºÐ°Ñ Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸Ñ Qt.</p><p>ОбратитеÑÑŒ к официальноÑй Ñтранице <a href="http://qtsoftware.com/company/model/">qtsoftware.com/company/model/</a> Ð´Ð»Ñ Ð¾Ð·Ð½Ð°ÐºÐ¾Ð¼Ð»ÐµÐ½Ð¸Ñ Ñ Ð¼Ð¾Ð´ÐµÐ»Ñми Ð»Ð¸Ñ†ÐµÐ½Ð·Ð¸Ñ€Ð¾Ð²Ð°Ð½Ð¸Ñ Qt.</p> @@ -3057,132 +3055,132 @@ Do you want to delete it anyway? The remote host closed the connection - + Удалённый узел закрыл Ñоединение Network operation timed out - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° Ñетевую операцию иÑтекло Out of resources - + ÐедоÑтаточно реÑурÑов Unsupported socket operation - + ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ñ Ñокетом не поддерживаетÑÑ Protocol type not supported - + Протокол не поддерживаетÑÑ Invalid socket descriptor - + Ðекорректный деÑкриптор Ñокета Network unreachable - + Сеть недоÑтупна Permission denied - + ДоÑтуп запрещён Connection timed out - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° Ñоединение иÑтекло Connection refused - Отказано в Ñоединении + Отказано в Ñоединении The bound address is already in use - + ÐÐ´Ñ€ÐµÑ ÑƒÐ¶Ðµ иÑпользуетÑÑ The address is not available - + ÐÐ´Ñ€ÐµÑ Ð½ÐµÐ´Ð¾Ñтупен The address is protected - + ÐÐ´Ñ€ÐµÑ Ð·Ð°Ñ‰Ð¸Ñ‰Ñ‘Ð½ Unable to send a message - + Ðевозможно отправить Ñообщение Unable to receive a message - + Ðевозможно получить Ñообщение Unable to write - + Ðевозможно запиÑать Network error - + Ошибка Ñети Another socket is already listening on the same port - + Другой Ñокет уже проÑлушивает Ñтот порт Unable to initialize non-blocking socket - + Ðевозможно инициализировать не-блочный Ñокет Unable to initialize broadcast socket - + Ðевозможно инициализировать широковещательный Ñокет Attempt to use IPv6 socket on a platform with no IPv6 support - + Попытка иÑпользовать IPv6 на платформе, не поддерживающей IPv6 Host unreachable - + Узел недоÑтупен Datagram was too large to send - + Датаграмма Ñлишком Ð±Ð¾Ð»ÑŒÑˆÐ°Ñ Ð´Ð»Ñ Ð¾Ñ‚Ð¿Ñ€Ð°Ð²ÐºÐ¸ Operation on non-socket - + ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ñ Ð½Ðµ-Ñокетом Unknown error - ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° The proxy type is invalid for this operation - + Ðекорректный тип прокÑи-Ñервера Ð´Ð»Ñ Ð´Ð°Ð½Ð½Ð¾Ð¹ операции @@ -3190,195 +3188,212 @@ Do you want to delete it anyway? Error opening %1 - + Ошибка Ð¾Ñ‚ÐºÑ€Ñ‹Ñ‚Ð¸Ñ %1 + + + + QNetworkAccessDebugPipeBackend + + + Write error writing to %1: %2 + Ошибка запиÑи в %1: %2 QNetworkAccessFileBackend - + Request for opening non-local file %1 - + Ð—Ð°Ð¿Ñ€Ð¾Ñ Ð½Ð° открытие файла вне файловой ÑиÑтемы %1 - + Error opening %1: %2 - + Ошибка Ð¾Ñ‚ÐºÑ€Ñ‹Ñ‚Ð¸Ñ %1: %2 - + Write error writing to %1: %2 - + Ошибка запиÑи в %1: %2 - + Cannot open %1: Path is a directory - + Ðевозможно открыть %1: Указан путь к каталогу Read error reading from %1: %2 - + Ошибка Ñ‡Ñ‚ÐµÐ½Ð¸Ñ Ð¸Ð· %1: %2 QNetworkAccessFtpBackend - + No suitable proxy found - + ПодходÑщий прокÑи-Ñервер не найден Cannot open %1: is a directory - + Ðевозможно открыть %1: Указан путь к каталогу - + Logging in to %1 failed: authentication required - + Соединение Ñ %1 не удалоÑÑŒ: требуетÑÑ Ð°Ð²Ñ‚Ð¾Ñ€Ð¸Ð·Ð°Ñ†Ð¸Ñ Error while downloading %1: %2 - + Ошибка в процеÑÑе загрузки %1: %2 Error while uploading %1: %2 - + Ошибка в процеÑÑе отгрузки %1: %2 QNetworkAccessHttpBackend - + No suitable proxy found - + ПодходÑщий прокÑи-Ñервер не найден QNetworkReply - + Error downloading %1 - server replied: %2 - + Ошибка загрузки %1 - ответ Ñервера: %2 - + Protocol "%1" is unknown - + ÐеизвеÑтный протокол "%1" QNetworkReplyImpl - + Operation canceled - + ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ð¾Ñ‚Ð¼ÐµÐ½ÐµÐ½Ð° QOCIDriver - + Unable to logon - + Ðевозможно авторизоватьÑÑ Unable to initialize QOCIDriver - + Ðевозможно инициализировать Unable to begin transaction - + Ðевозможно начать транзакцию Unable to commit transaction - + Ðевозможно выполнить транзакцию Unable to rollback transaction - + Ðевозможно откатить транзакцию QOCIResult - + Unable to bind column for batch execute - + Ðевозможно привÑзать Ñтолбец Ð´Ð»Ñ Ð¿Ð°ÐºÐµÑ‚Ð½Ð¾Ð³Ð¾ Ð²Ñ‹Ð¿Ð¾Ð»Ð½ÐµÐ½Ð¸Ñ Unable to execute batch statement - + Ðевозможно выполнить пакетное выражение Unable to goto next - + Ðевозможно перейти к Ñледующей Ñтроке Unable to alloc statement - + Ðевозможно Ñоздать выражение Unable to prepare statement - + Ðевозможно подготовить выражение - + + Unable to get statement type + Ðевозможно определить тип Ð²Ñ‹Ñ€Ð°Ð¶ÐµÐ½Ð¸Ñ + + + Unable to bind value - + Ðевозможно привÑзать результирующие Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ + + + Unable to execute select statement + Ðевозможно выполнить утверждение SELECT Unable to execute statement - + Ðевозможно выполнить выражение QODBCDriver - + Unable to connect - + Ðевозможно ÑоединитьÑÑ Unable to connect - Driver doesn't support all needed functionality - + Ðевозможно ÑоединитьÑÑ - Драйвер не поддерживает требуемый функционал Unable to disable autocommit - + Ðевозможно отключить автовыполнение транзакции Unable to commit transaction - + Ðевозможно выполнить транзакцию Unable to rollback transaction - + Ðевозможно откатить транзакцию Unable to enable autocommit - + Ðевозможно уÑтановить автовыполнение транзакции @@ -3387,50 +3402,50 @@ Do you want to delete it anyway? QODBCResult::reset: Unable to set 'SQL_CURSOR_STATIC' as statement attribute. Please check your ODBC driver configuration - + QODBCResult::reset: Ðевозможно уÑтановить 'SQL_CURSOR_STATIC' атрибутом выражение. Проверьте наÑтройки драйвера ODBC Unable to execute statement - + Ðевозможно выполнить выражение Unable to fetch next - + Ðевозможно получить Ñледующую Ñтроку Unable to prepare statement - + Ðевозможно подготовить выражение Unable to bind variable - + Ðевозможно привÑзать значение Unable to fetch last - + Ðевозможно получить поÑледнюю Ñтроку Unable to fetch - + Ðевозможно получить данные Unable to fetch first - + Ðевозможно получить первую Ñтроку Unable to fetch previous - + Ðевозможно получить предыдущую Ñтроку @@ -3438,61 +3453,58 @@ Do you want to delete it anyway? Home - Home + Operation not supported on %1 - + ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ð½Ðµ поддерживаетÑÑ Ð´Ð»Ñ %1 Invalid URI: %1 - + Ðекорректный URI: %1 - Write error writing to %1: %2 - + Ошибка запиÑи в %1: %2 - Read error reading from %1: %2 - + Ошибка Ñ‡Ñ‚ÐµÐ½Ð¸Ñ Ð¸Ð· %1: %2 - + Socket error on %1: %2 - + Ошика Ñокета Ð´Ð»Ñ %1: %2 Remote host closed the connection prematurely on %1 - + Удалённый узел неожиданно прервал Ñоединение Ð´Ð»Ñ %1 - Protocol error: packet of size 0 received - + Ошибка протокола: получен пакет нулевого размера No host name given - + Ð˜Ð¼Ñ ÑƒÐ·Ð»Ð° не задано QPPDOptionsModel - + Name - Ð˜Ð¼Ñ + Ð˜Ð¼Ñ Value - + Значение @@ -3500,32 +3512,32 @@ Do you want to delete it anyway? Unable to connect - + Ðевозможно ÑоединитьÑÑ Could not begin transaction - + Ðе удалоÑÑŒ начать транзакцию Could not commit transaction - + Ðе удалоÑÑŒ выполнить транзакцию Could not rollback transaction - + Ðе удалоÑÑŒ откатить транзакцию Unable to subscribe - + Ðевозможно подпиÑатьÑÑ Unable to unsubscribe - + Ðевозможно отпиÑатьÑÑ @@ -3533,12 +3545,12 @@ Do you want to delete it anyway? Unable to create query - + Ðевозможно Ñоздать Ð·Ð°Ð¿Ñ€Ð¾Ñ Unable to prepare statement - + Ðевозможно подготовить выражение @@ -3546,102 +3558,106 @@ Do you want to delete it anyway? Centimeters (cm) - + Сантиметры (cm) Millimeters (mm) - + Миллиметры (mm) Inches (in) - + Дюймы (in) Points (pt) - + Точки (pt) - + Form - + Форма - + Paper - + Бумага - + Page size: - + Размер Ñтраницы: - + Width: - + Ширина: - + Height: - + Ð’Ñ‹Ñота: - + Paper source: - + ИÑточник бумаги: - + Orientation - + ÐžÑ€Ð¸ÐµÐ½Ñ‚Ð°Ñ†Ð¸Ñ Ñтраницы - + Portrait - Портрет + ÐšÐ½Ð¸Ð¶Ð½Ð°Ñ - + Landscape - Ðльбом + ÐÐ»ÑŒÐ±Ð¾Ð¼Ð½Ð°Ñ - + Reverse landscape - + ÐŸÐµÑ€ÐµÐ²Ñ‘Ñ€Ð½ÑƒÑ‚Ð°Ñ Ð°Ð»ÑŒÐ±Ð¾Ð¼Ð½Ð°Ñ - + Reverse portrait - + ÐŸÐµÑ€ÐµÐ²Ñ‘Ñ€Ð½ÑƒÑ‚Ð°Ñ ÐºÐ½Ð¸Ð¶Ð½Ð°Ñ - + Margins - + ÐŸÐ¾Ð»Ñ - + + top margin - + верхнее поле - + + left margin - + Левое поле - + + right margin - + правое поле - + + bottom margin - + Ðижнее поле @@ -3649,12 +3665,12 @@ Do you want to delete it anyway? Unknown error - ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° The plugin was not loaded. - + Модуль не был загружен. @@ -3662,13 +3678,13 @@ Do you want to delete it anyway? locally connected - локальный + Ñоединено локально Aliases: %1 - ÐлиаÑÑ‹: %1 + ПÑевдонимы: %1 @@ -3677,54 +3693,7 @@ Do you want to delete it anyway? неизвеÑтно - - OK - OK - - - Cancel - Отмена - - - Print in color if available - Ð¦Ð²ÐµÑ‚Ð½Ð°Ñ Ð¿ÐµÑ‡Ð°Ñ‚ÑŒ - - - Printer - Принтер - - - - Print all - Печатать вÑе - - - - Print range - Печатать диапазон - - - Print last page first - Ðачать Ñ Ð¿Ð¾Ñледней Ñтраницы - - - Number of copies: - ЧиÑло копий: - - - Paper format - Формат бумаги - - - Portrait - Портрет - - - Landscape - Ðльбом - - - + A0 (841 x 1189 mm) A0 (841 x 1189 мм) @@ -3740,11 +3709,16 @@ Do you want to delete it anyway? - A3 (297 x 420 mm) - A3 (297 x 420 мм) + A3 (297 x 420 mm) + A3 (297 x 420 мм) + + + + A4 (210 x 297 mm, 8.26 x 11.7 inches) + A4 (210 x 297 мм, 8.26 x 11.7 дюймов) - + A5 (148 x 210 mm) A5 (148 x 210 мм) @@ -3794,7 +3768,12 @@ Do you want to delete it anyway? B4 (250 x 353 мм) - + + B5 (176 x 250 mm, 6.93 x 9.84 inches) + B5 (176 x 250 мм, 6.93 x 9.84 дюймов) + + + B6 (125 x 176 mm) B6 (125 x 176 мм) @@ -3829,7 +3808,12 @@ Do you want to delete it anyway? DLE (110 x 220 мм) - + + Executive (7.5 x 10 inches, 191 x 254 mm) + Executive (191 x 254 мм, 7.5 x 10 дюймов) + + + Folio (210 x 330 mm) Folio (210 x 330 мм) @@ -3839,88 +3823,87 @@ Do you want to delete it anyway? Ledger (432 x 279 мм) - - Tabloid (279 x 432 mm) - Tabloid (279 x 432 мм) - - - US Common #10 Envelope (105 x 241 mm) - Конверт US #10 (105x241 мм) - - - - A4 (210 x 297 mm, 8.26 x 11.7 inches) - + Legal (8.5 x 14 inches, 216 x 356 mm) + Legal (216 x 356 мм, 8.5 x 14 дюймов) - - B5 (176 x 250 mm, 6.93 x 9.84 inches) - + + Letter (8.5 x 11 inches, 216 x 279 mm) + Letter (216 x 279 мм, 8.5 x 11 дюймов) - - Executive (7.5 x 10 inches, 191 x 254 mm) - + + Tabloid (279 x 432 mm) + Tabloid (279 x 432 мм) - - Legal (8.5 x 14 inches, 216 x 356 mm) - + + US Common #10 Envelope (105 x 241 mm) + Конверт US #10 (105x241 мм) - - Letter (8.5 x 11 inches, 216 x 279 mm) - + + OK + Готово Print - Print - - - File - Файл + Печатать Print To File ... - + Печатать в файл ... + + + + Print range + Печатать диапазон + + + + Print all + Печатать вÑе - + File %1 is not writable. Please choose a different file name. - + %1 недоÑтупен Ð´Ð»Ñ Ð·Ð°Ð¿Ð¸Ñи. +Выберите другое Ð¸Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð°. %1 already exists. Do you want to overwrite it? - + %1 уже ÑущеÑтвует. +Хотите заменить его? - + File exists - + Файл ÑущеÑтвует <qt>Do you want to overwrite it?</qt> - + <qt>Хотите заменить?</qt> Print selection - + Печатать выделенное %1 is a directory. Please choose a different file name. - + %1 - Ñто каталог. +Выберите другое Ð¸Ð¼Ñ Ñ„Ð°Ð¹Ð»Ð°. @@ -4075,48 +4058,48 @@ Please choose a different file name. Custom - + Произвольный - + &Options >> - + &Параметры >> &Print - + &Печатать &Options << - + &Параметры << Print to File (PDF) - + Печатать в файл (PDF) Print to File (Postscript) - + Печатать в файл (Postscript) - + Local file - + Локальный файл Write %1 file - + ЗапиÑÑŒ %1 файл The 'From' value cannot be greater than the 'To' value. - + Значение 'от' не может быть больше Ð·Ð½Ð°Ñ‡ÐµÐ½Ð¸Ñ 'до'. @@ -4125,345 +4108,333 @@ Please choose a different file name. Page Setup - + СвойÑтва Ñтраницы - + %1% - + %1% - + Print Preview - + ПроÑмотр печати - + Next page - + Ð¡Ð»ÐµÐ´ÑƒÑŽÑ‰Ð°Ñ Ñтраница Previous page - + ÐŸÑ€ÐµÐ´Ñ‹Ð´ÑƒÑ‰Ð°Ñ Ñтраница First page - + ÐŸÐµÑ€Ð²Ð°Ñ Ñтраница Last page - + ПоÑледнÑÑ Ñтраница Fit width - + По ширине Fit page - + Ðа вÑÑŽ Ñтраницу Zoom in - + Увеличить Zoom out - + Уменьшить Portrait - Портрет + ÐšÐ½Ð¸Ð¶Ð½Ð°Ñ Landscape - Ðльбом + ÐÐ»ÑŒÐ±Ð¾Ð¼Ð½Ð°Ñ Show single page - + Показать одну Ñтраницу Show facing pages - + Показать титульные Ñтраницы Show overview of all pages - + Показать обзор вÑех Ñтраниц Print - Print + Печатать Page setup - + СвойÑтва Ñтраницы - Close - Закрыть + Закрыть - + Export to PDF - + ЭкÑпорт в PDF Export to PostScript - - - - - QPrintPropertiesDialog - - Save - Сохранить - - - OK - OK + ЭкÑпорт в Postscript QPrintPropertiesWidget - + Form - + Форма - + Page - + Страница - + Advanced - + Дополнительно QPrintSettingsOutput - + Form - + Форма - + Copies - + Копии - + Print range - Печатать диапазон + Печатать диапазон - + Print all - Печатать вÑе + Печатать вÑе - + Pages from - + Страницы от - + to - + до - + Selection - + Выделенные - + Output Settings - + ÐаÑтройки вывода - + Copies: - + КоличеÑтво копий: - + Collate - + Разобрать про копиÑм - + Reverse - + Обратный порÑдок - + Options - Параметры + Параметры - + Color Mode - + Режим цвета - + Color - + Цвет - + Grayscale - + Оттенки Ñерого - + Duplex Printing - + ДвуÑтороннÑÑ Ð¿ÐµÑ‡Ð°Ñ‚ÑŒ - + None - + Ðет - + Long side - + По длинной Ñтороне - + Short side - + По короткой Ñтороне QPrintWidget - + Form - + Форма - + Printer - Принтер + Принтер - + &Name: - + &ИмÑ: - + P&roperties - + С&войÑтва - + Location: - + Положение: - + Preview - + ПредпроÑмотр - + Type: - + Тип: - + Output &file: - + Выходной &файл: - + ... - + ... QProcess - + Could not open input redirection for reading - + Ðе удалоÑÑŒ открыть перенаправление ввода Ð´Ð»Ñ Ñ‡Ñ‚ÐµÐ½Ð¸Ñ Could not open output redirection for writing - + Ðе удалоÑÑŒ открыть перенаправление вывода Ð´Ð»Ñ Ð·Ð°Ð¿Ð¸Ñи - + Resource error (fork failure): %1 - + Ошибка Ð²Ñ‹Ð´ÐµÐ»ÐµÐ½Ð¸Ñ Ñ€ÐµÑурÑов (fork не удалÑÑ): %1 - + Process operation timed out - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° операцию Ñ Ð¿Ñ€Ð¾Ñ†ÐµÑÑом иÑтекло - + Error reading from process - + Ошибка Ð¿Ð¾Ð»ÑƒÑ‡ÐµÐ½Ð¸Ñ Ð´Ð°Ð½Ð½Ñ‹Ñ… от процеÑÑа - + Error writing to process - + Ошибка отправки данных процеÑÑу - + Process crashed - + ПроцеÑÑ Ð·Ð°Ð²ÐµÑ€ÑˆÐ¸Ð»ÑÑ Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ¾Ð¹ - + No program defined - + Программа не указана Process failed to start - + Ðе удалоÑÑŒ запуÑтить процеÑÑ @@ -4479,7 +4450,7 @@ Please choose a different file name. Open - Открыть + Открыть @@ -4487,7 +4458,7 @@ Please choose a different file name. Check - + Отметить @@ -4500,22 +4471,22 @@ Please choose a different file name. disabled feature used - иÑпользовалиÑÑŒ отключенные возможноÑти + иÑпользование отключённых возможноÑтей bad char class syntax - bad char class syntax + неправильный ÑинтакÑÐ¸Ñ ÐºÐ»Ð°ÑÑа Ñимволов bad lookahead syntax - bad lookahead syntax + неправильный предварительный ÑинтакÑÐ¸Ñ bad repetition syntax - bad repetition syntax + неправильный ÑинтакÑÐ¸Ñ Ð¿Ð¾Ð²Ñ‚Ð¾Ñ€ÐµÐ½Ð¸Ñ @@ -4543,22 +4514,22 @@ Please choose a different file name. Error to open database - + Ðевозможно открыть базу данных Unable to begin transaction - + Ðевозможно начать транзакцию Unable to commit transaction - + Ðевозможно выполнить транзакцию Unable to rollback Transaction - + Ðевозможно откатить транзакцию @@ -4566,12 +4537,12 @@ Please choose a different file name. Unable to fetch results - + Ðевозможно получить результат Unable to execute statement - + Ðевозможно выполнить выражение @@ -4579,27 +4550,27 @@ Please choose a different file name. Error opening database - + Ðевозможно открыть базу данных Error closing database - + Ðевозможно закрыть базу данных Unable to begin transaction - + Ðевозможно начать транзакцию Unable to commit transaction - + Ðевозможно выполнить транзакцию Unable to rollback transaction - + Ðевозможно откатить транзакцию @@ -4609,32 +4580,32 @@ Please choose a different file name. Unable to fetch row - + Ðевозможно получить Ñтроку Unable to execute statement - + Ðевозможно выполнить выражение Unable to reset statement - + Ðевозможно ÑброÑить выражение Unable to bind parameters - + Ðевозможно привÑзать параметр Parameter count mismatch - + КоличеÑтво параметров не Ñовпадает No query - + ОтÑутÑтвует Ð·Ð°Ð¿Ñ€Ð¾Ñ @@ -4642,302 +4613,302 @@ Please choose a different file name. Scroll here - + Прокрутить Ñюда Left edge - + К левой границе Top - + Вверх Right edge - + К правой границе Bottom - + Вниз Page left - + Ðа Ñтраницу влево Page up - + Ðа Ñтраницу вверх Page right - + Ðа Ñтраницу вправо Page down - + Ðа Ñтраницу вниз Scroll left - + Прокрутить влево Scroll up - + Прокрутить вверх Scroll right - + Прокрутить вправо Scroll down - + Прокрутить вниз Line up - ВыровнÑть + Ðа Ñтроку вверх Position - + ÐŸÐ¾Ð·Ð¸Ñ†Ð¸Ñ Line down - + Ðа Ñтроку вниз QSharedMemory - + %1: unable to set key on lock - + %1: невозможно уÑтановить ключ на блокировку %1: create size is less then 0 - + %1: размер меньше Ð½ÑƒÐ»Ñ %1: unable to lock - + %1: невозможно заблокировать %1: unable to unlock - + %1: невозможно разблокировать - + %1: permission denied - + %1: доÑтуп запрещён %1: already exists - + %1: уже ÑущеÑтвует %1: doesn't exists - + %1: не ÑущеÑтвует %1: out of resources - + %1: недоÑтаточно реÑурÑов %1: unknown error %2 - + %1: неизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° %2 %1: key is empty - + %1: пуÑтой ключ %1: unix key file doesn't exists - + %1: ÑпецифичеÑкий ключ unix не ÑущеÑтвует %1: ftok failed - + %1: ошибка ftok %1: unable to make key - + %1: невозможно Ñоздать ключ %1: system-imposed size restrictions - + %1: ÑиÑтемой наложены Ð¾Ð³Ñ€Ð°Ð½Ð¸Ñ‡ÐµÐ½Ð¸Ñ Ð½Ð° размер %1: not attached - + %1: не приложенный %1: invalid size - + %1: некорректный размер %1: key error - + %1: некорректный ключ %1: size query failed - + %1: не удалоÑÑŒ запроÑить размер QShortcut - + Space - Space + Пробел Esc - Esc + Tab - Tab + Backtab - Backtab + Backspace - Backspace + Return - Return + Enter - Enter + Ins - Ins + Del - Del + Pause - Pause + Пауза Print - Print + Печатать SysReq - SysReq + Home - Home + End - End + Left - Left + Влево Up - Up + Вверх Right - Right + Вправо Down - Down + Вниз PgUp - PgUp + PgDown - PgDown + CapsLock - CapsLock + NumLock - NumLock + ScrollLock - ScrollLock + @@ -4962,7 +4933,7 @@ Please choose a different file name. Stop - Стоп + ОÑтановить @@ -4972,72 +4943,72 @@ Please choose a different file name. Volume Down - Тише + Volume Mute - Выключить звук + Volume Up - Громче + Bass Boost - Bass Boost + Bass Up - Bass Up + Bass Down - Bass Down + Treble Up - Treble Up + Treble Down - Treble Down + Media Play - ВоÑпроизведение + Media Stop - ОÑтановить воÑпроизведение + Media Previous - ВоÑпроизвеÑти предыдущее + Media Next - ВоÑпроизвеÑти Ñледующее + Media Record - ЗапиÑÑŒ + Favorites - Избранное + @@ -5047,102 +5018,102 @@ Please choose a different file name. Standby - Дежурный режим + Open URL - Открыть URL + Launch Mail - Почта + Launch Media - Проигрыватель + Launch (0) - ЗапуÑтить (0) + Launch (1) - ЗапуÑтить (1) + Launch (2) - ЗапуÑтить (2) + Launch (3) - ЗапуÑтить (3) + Launch (4) - ЗапуÑтить (4) + Launch (5) - ЗапуÑтить (5) + Launch (6) - ЗапуÑтить (6) + Launch (7) - ЗапуÑтить (7) + Launch (8) - ЗапуÑтить (8) + Launch (9) - ЗапуÑтить (9) + Launch (A) - ЗапуÑтить (A) + Launch (B) - ЗапуÑтить (B) + Launch (C) - ЗапуÑтить (C) + Launch (D) - ЗапуÑтить (D) + Launch (E) - ЗапуÑтить (E) + Launch (F) - ЗапуÑтить (F) + @@ -5182,12 +5153,12 @@ Please choose a different file name. Insert - Ð’Ñтавить + Ð’Ñтавка Delete - Удалить + Удаление @@ -5250,41 +5221,41 @@ Please choose a different file name. - - + + Ctrl - Ctrl + - - + + Shift - Shift + - - + + Alt - Alt + - - + + Meta - Meta + - + + - + + - + F%1 - F%1 + - + Home Page @@ -5294,27 +5265,27 @@ Please choose a different file name. Page left - + Страница влево Page up - + Страница вверх Position - + ÐŸÐ¾Ð·Ð¸Ñ†Ð¸Ñ Page right - + Страница вправо Page down - + Страница вниз @@ -5322,72 +5293,72 @@ Please choose a different file name. Connection to proxy refused - + Ð’ Ñоединении прокÑи-Ñервером отказано Connection to proxy closed prematurely - + Соединение Ñ Ð¿Ñ€Ð¾ÐºÑи-Ñервером неожиданно закрыто Proxy host not found - + ПрокÑи-Ñервер не найден Connection to proxy timed out - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° Ñоединение Ñ Ð¿Ñ€Ð¾ÐºÑи-Ñервером иÑтекло Proxy authentication failed - + Ðе удалоÑÑŒ авторизоватьÑÑ Ð½Ð° прокÑи-Ñервере Proxy authentication failed: %1 - + Ðе удалоÑÑŒ авторизоватьÑÑ Ð½Ð° прокÑи-Ñервере: %1 SOCKS version 5 protocol error - + Ошибка протокола SOCKSv5 General SOCKSv5 server failure - + Ошибка Ñервере SOCKSv5 Connection not allowed by SOCKSv5 server - + Соединение не разрешено Ñервером SOCKSv5 TTL expired - + TTL иÑтекло SOCKSv5 command not supported - + Команда SOCKSv5 не поддерживаетÑÑ Address type not supported - + Тип адреÑа не поддерживаетÑÑ Unknown SOCKSv5 proxy error code 0x%1 - + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° SOCKSv5 прокÑи (код 0x%1) Network operation timed out - + Ð’Ñ€ÐµÐ¼Ñ Ð½Ð° Ñетевую операцию иÑтекло @@ -5395,12 +5366,12 @@ Please choose a different file name. More - + Больше Less - + Меньше @@ -5413,7 +5384,7 @@ Please choose a different file name. Delete this record? - Удалить Ñту запиÑÑŒ? + Удалить данную запиÑÑŒ? @@ -5452,7 +5423,7 @@ Please choose a different file name. Confirm - Подтвердить + Подтверждение @@ -5465,12 +5436,12 @@ Please choose a different file name. Unable to write data: %1 - + Ðевозможно запиÑать данные: %1 Error while reading: %1 - + Ошибка чтениÑ: %1 @@ -5490,12 +5461,12 @@ Please choose a different file name. Error creating SSL session, %1 - + Ошибка ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ SSL-ÑеÑÑии, %1 Error creating SSL session: %1 - + Ошибка ÑÐ¾Ð·Ð´Ð°Ð½Ð¸Ñ SSL-ÑеÑÑии: %1 @@ -5505,12 +5476,12 @@ Please choose a different file name. Error loading local certificate, %1 - + Ошибка загрузки локального Ñертификата, %1 Error loading private key, %1 - + Ошибка загрузки приватного ключа, %1 @@ -5519,34 +5490,57 @@ Please choose a different file name. + QStateMachine + + + Missing initial state in compound state '%1' + + + + + Missing default state in history state '%1' + + + + + No common ancestor for targets and source of transition from state '%1' + + + + + Unknown error + ÐеизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° + + + QSystemSemaphore %1: out of resources - + %1: недоÑтаточно реÑурÑов %1: permission denied - + %1: доÑтуп запрещён %1: already exists - + %1: уже ÑущеÑтвует %1: does not exist - + %1: не ÑущеÑтвует %1: unknown error %2 - + %1: неизвеÑÑ‚Ð½Ð°Ñ Ð¾ÑˆÐ¸Ð±ÐºÐ° %2 @@ -5554,12 +5548,12 @@ Please choose a different file name. Unable to open connection - + Ðевозможно открыть Ñоединение Unable to use database - + Ðевозможно иÑпользовать базу данных @@ -5567,12 +5561,12 @@ Please choose a different file name. Scroll Left - + Прокрутить влево Scroll Right - + Прокрутить вправо @@ -5580,7 +5574,7 @@ Please choose a different file name. Operation on socket is not supported - + ÐžÐ¿ÐµÑ€Ð°Ñ†Ð¸Ñ Ñ Ñокетом не поддерживаетÑÑ @@ -5588,42 +5582,42 @@ Please choose a different file name. &Undo - &Отменить + &Отменить дейÑтвие &Redo - &Повторить + &Повторить дейÑтвие Cu&t - &Вырезать + &Вырезать &Copy - &Копировать + &Копировать Copy &Link Location - + Скопировать &Ð°Ð´Ñ€ÐµÑ ÑÑылки &Paste - &Ð’Ñтавить + Ð’&Ñтавить Delete - Удалить + Удалить Select All - Выделить вÑе + Выделить вÑе @@ -5632,13 +5626,13 @@ Please choose a different file name. Press - + Ðажать Open - Открыть + Открыть @@ -5646,7 +5640,7 @@ Please choose a different file name. This platform does not support IPv6 - + Ð”Ð°Ð½Ð½Ð°Ñ Ð¿Ð»Ð°Ñ‚Ñ„Ð¾Ñ€Ð¼Ð° не поддерживает IPv6 @@ -5654,12 +5648,12 @@ Please choose a different file name. Undo - Отменить + Отменить дейÑтвие Redo - Повторить + Повторить дейÑтвие @@ -5667,7 +5661,7 @@ Please choose a different file name. <empty> - + <пуÑто> @@ -5675,12 +5669,12 @@ Please choose a different file name. Undo - Отменить + Отменить дейÑтвие Redo - Повторить + Повторить дейÑтвие @@ -5746,160 +5740,160 @@ Please choose a different file name. Request cancelled - + Ð—Ð°Ð¿Ñ€Ð¾Ñ Ð¾Ñ‚Ð¼ÐµÐ½Ñ‘Ð½ Request blocked - + Ð—Ð°Ð¿Ñ€Ð¾Ñ Ð±Ð»Ð¾ÐºÐ¸Ñ€Ð¾Ð²Ð°Ð½ Cannot show URL - + Ðевозможно отобразить URL Frame load interruped by policy change - + Загрузка фрÑйма прервана изменением политики Cannot show mimetype - + Ðевозможно отобразить тип MIME File does not exist - + Файл не ÑущеÑтвует QWebPage - + Bad HTTP request - + Ðекорректный HTTP-Ð·Ð°Ð¿Ñ€Ð¾Ñ Submit default label for Submit buttons in forms on web pages - + Отправить Submit Submit (input element) alt text for <input> elements with no alt, title, or value - + Отправить Reset default label for Reset buttons in forms on web pages - + СброÑить This is a searchable index. Enter search keywords: text that appears at the start of nearly-obsolete web pages in the form of a 'searchable index' - + Ð˜Ð½Ð´ÐµÐºÑ Ð¿Ð¾Ð¸Ñка. Введите ключевые Ñлова Ð´Ð»Ñ Ð¿Ð¾Ð¸Ñка: Choose File title for file button used in HTML forms - + Обзор... No file selected text to display in file button used in HTML forms when no file is selected - + Файл не указан Open in New Window Open in New Window context menu item - + Открыть в новом окне Save Link... Download Linked File context menu item - + Сохранить по ÑÑылке как... Copy Link Copy Link context menu item - + Копировать Ð°Ð´Ñ€ÐµÑ ÑÑылки Open Image Open Image in New Window context menu item - + Открыть изображение Save Image Download Image context menu item - + Сохранить изображение Copy Image Copy Link context menu item - + Копировать изображение в буффер обмена Open Frame Open Frame in New Window context menu item - + Открыть фрÑйм Copy Copy context menu item - + Копировать Go Back Back context menu item - + Ðазад Go Forward Forward context menu item - + Вперед Stop Stop context menu item - Стоп + ОÑтановить Reload Reload context menu item - + Обновить Cut Cut context menu item - + Вырезать Paste Paste context menu item - + Ð’Ñтавить @@ -5911,7 +5905,7 @@ Please choose a different file name. Ignore Ignore Spelling context menu item - + Игнорировать @@ -5935,13 +5929,13 @@ Please choose a different file name. Open Link Open Link context menu item - + Открыть ÑÑылку Ignore Ignore Grammar context menu item - + Игнорировать @@ -5983,97 +5977,97 @@ Please choose a different file name. Fonts Font context sub-menu item - + Шрифты Bold Bold context menu item - + Жирный Italic Italic context menu item - + КурÑив Underline Underline context menu item - + Подчёркнутый Outline Outline context menu item - + Перечёркнутый Direction Writing direction context sub-menu item - + Ðаправление Text Direction Text direction context sub-menu item - + Ðаправление текÑта Default Default writing direction context menu item - + По умолчанию LTR Left to Right context menu item - + Слева направо RTL Right to Left context menu item - + Справа налево Inspect Inspect Element context menu item - + Проверить No recent searches Label for only item in menu that appears when clicking on the search field image, when no searches have been performed - + ИÑÑ‚Ð¾Ñ€Ð¸Ñ Ð¿Ð¾Ð¸Ñка пуÑта Recent searches label for first item in the menu that appears when clicking on the search field image, used as embedded menu title - + ИÑÑ‚Ð¾Ñ€Ð¸Ñ Ð¿Ð¾Ð¸Ñка Clear recent searches menu item in Recent Searches menu that empties menu's contents - + ОчиÑтить иÑторию поиÑка Unknown Unknown filesize FTP directory listing item - + ÐеизвеÑтно %1 (%2x%3 pixels) Title string for images - + %1 (%2x%3 px) @@ -6083,74 +6077,76 @@ Please choose a different file name. Scroll here - + Прокрутить Ñюда Left edge - + К левой границе Top - + Вверх Right edge - + К правой границе Bottom - + Вниз Page left - + Ðа Ñтраницу влево Page up - + Ðа Ñтраницу вверх Page right - + Ðа Ñтраницу вправо Page down - + Ðа Ñтраницу вниз Scroll left - + Прокрутить влево Scroll up - + Прокрутить вверх Scroll right - + Прокрутить вправо Scroll down - + Прокрутить вниз %n file(s) number of chosen file - - + + %n файл(а) + %n файла + %n файлов @@ -6169,149 +6165,149 @@ Please choose a different file name. - + Move the cursor to the next character - + ПеремеÑтить указатель к Ñледующему Ñимволу Move the cursor to the previous character - + ПеремеÑтить указатель к предыдущему Ñимволу Move the cursor to the next word - + ПеремеÑтить указатель к Ñледующему Ñлову Move the cursor to the previous word - + ПеремеÑтить указатель к предыдущему Ñлову Move the cursor to the next line - + ПеремеÑтить указатель на Ñледующую Ñтроку Move the cursor to the previous line - + ПеремеÑтить указатель на предыдущую Ñтроку Move the cursor to the start of the line - + ПеремеÑтить указатель в начало Ñтроки Move the cursor to the end of the line - + ПеремеÑтить указатель в конец Ñтроки Move the cursor to the start of the block - + ПеремеÑтить указатель в начало блока Move the cursor to the end of the block - + ПеремеÑтить указатель в конец блока Move the cursor to the start of the document - + ПеремеÑтить указатель в начало документа Move the cursor to the end of the document - + ПеремеÑтить указатель в конец документа Select all - + Выделить вÑÑ‘ Select to the next character - + Выделить до Ñледующего Ñимвола Select to the previous character - + Выделить до предыдущего Ñимвола Select to the next word - + Выделить до Ñледующего Ñлова Select to the previous word - + Выделить до предыдущего Ñлова Select to the next line - + Выделить до Ñледующей Ñтроки Select to the previous line - + Выделить до предыдущей Ñтроки Select to the start of the line - + Выделить до начала Ñтроки Select to the end of the line - + Выделить до конца Ñтроки Select to the start of the block - + Выделить до начала блока Select to the end of the block - + Выделить до конца блока Select to the start of the document - + Выделить до начала документа Select to the end of the document - + Выделить до конца документа Delete to the start of the word - + Удалить до начала Ñлова Delete to the end of the word - + Удалить до конца Ñлова Insert a new paragraph - + Ð’Ñтавить новый параграф Insert a new line - + Ð’Ñтавить новую Ñтроку @@ -6319,77 +6315,73 @@ Please choose a different file name. What's This? - Что Ñто? + Что Ñто? QWidget - + * - + * QWizard - < &Back - < &Ðазад - - - - &Finish - &Финиш - - - - &Help - &Справка - - - Go Back - + Ðазад Continue - + Продолжить Commit - + Отправить Done - - - - Quit - Выход + Готово Help - Справка + Справка - + + < &Back + < &Ðазад + + + + &Finish + &Закончить + + + Cancel - Отмена + Отмена + + + + &Help + &Справка - + &Next - + &Вперед &Next > - &Вперед > + &Вперед > @@ -6397,43 +6389,43 @@ Please choose a different file name. &Restore - &ВоÑÑтановить + &ВоÑÑтановить &Move - &ПеремеÑтить + &ПеремеÑтить &Size - &Размер + &Размер Mi&nimize - &Свернуть + &Минимизировать Ma&ximize - Р&азвернуть + Р&аÑпахнуть &Close - &Закрыть + &Закрыть Stay on &Top - Ð’Ñегда &наверху + ОÑтаватьÑÑ &Ñверху Sh&ade - Свернуть в за&головок + Св&ернуть в заголовок @@ -6444,22 +6436,22 @@ Please choose a different file name. Minimize - Свернуть + Минимизировать Restore Down - ВоÑÑтановить + ВоÑÑтановить Close - Закрыть + Закрыть &Unshade - ВоÑÑтановить из за&головка + Ð’&оÑÑтановить из заголовка @@ -6472,7 +6464,7 @@ Please choose a different file name. error triggered by consumer - ошибка инициирована пользователем + ошибка вызвана пользователем @@ -6482,22 +6474,22 @@ Please choose a different file name. more than one document type definition - определен более, чем один тип документов + указано более одного типа документа error occurred while parsing element - в процеÑÑе грамматичеÑкого разбора Ñлемента произошла ошибка + ошибка разбора Ñлемента tag mismatch - отÑутÑтвует тег + Ñ‚Ñг не Ñовпадает error occurred while parsing content - в процеÑÑе грамматичеÑкого разбора произошла ошибка + ошибка разбора документа @@ -6507,101 +6499,101 @@ Please choose a different file name. invalid name for processing instruction - некорректное Ð¸Ð¼Ñ Ð´Ð¸Ñ€ÐµÐºÑ‚Ð¸Ð²Ñ‹ + некорректное Ð¸Ð¼Ñ Ð´Ð¸Ñ€ÐµÐºÑ‚Ð¸Ð²Ñ‹ разбора version expected while reading the XML declaration - при чтении XML-тега ожидалÑÑ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ version + в объÑвлении XML ожидаетÑÑ Ð¾Ð±ÑŠÑвление параметра version wrong value for standalone declaration - некорректное значение параметра standalone + некорректное значение объÑÐ²Ð»ÐµÐ½Ð¸Ñ standalone encoding declaration or standalone declaration expected while reading the XML declaration - при чтении XML-тега ожидалÑÑ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ encoding или параметр standalone + в объÑвлении XML ожидаетÑÑ Ð¾Ð±ÑŠÑвление параметра encoding или standalone standalone declaration expected while reading the XML declaration - при чтении XML-тега ожидалÑÑ Ð¿Ð°Ñ€Ð°Ð¼ÐµÑ‚Ñ€ standalone + в объÑвлении XML ожидаетÑÑ Ð¾Ð±ÑŠÑвление параметра standalone error occurred while parsing document type definition - в процеÑÑе грамматичеÑкого разбора типа документа произошла ошибка + ошибка разбора объÑÐ²Ð»ÐµÐ½Ð¸Ñ Ñ‚Ð¸Ð¿Ð° документа letter is expected - ожидалÑÑ Ñимвол + ожидалаÑÑŒ буква error occurred while parsing comment - в процеÑÑе грамматичеÑкого разбора ÐºÐ¾Ð¼Ð¼ÐµÐ½Ñ‚Ð°Ñ€Ð¸Ñ Ð¿Ñ€Ð¾Ð¸Ð·Ð¾ÑˆÐ»Ð° ошибка + ошибка разбора ÐºÐ¾Ð¼Ð¼ÐµÐ½Ñ‚Ð°Ñ€Ð¸Ñ error occurred while parsing reference - в процеÑÑе грамматичеÑкого разбора ÑÑылки произошла ошибка + ошибка разбора ÑÑылки internal general entity reference not allowed in DTD - internal general entity reference not allowed in DTD + внутреннÑÑ ÑÑылка на общий объкт недопуÑтима в DTD external parsed general entity reference not allowed in attribute value - external parsed general entity reference not allowed in attribute value + внешнÑÑ ÑÑылка на общий объект недопуÑтима в значении атрибута external parsed general entity reference not allowed in DTD - external parsed general entity reference not allowed in DTD + внешнÑÑ ÑÑылка на общий объект недопуÑтима в DTD unparsed entity reference in wrong context - unparsed entity reference in wrong context + Ð½ÐµÑ€Ð°Ð·Ð¾Ð±Ñ€Ð°Ð½Ð½Ð°Ñ ÑÑылка на объект в неправильном контекÑте recursive entities - рекурÑивные объекты + рекурÑÐ¸Ñ Ð¾Ð±ÑŠÐµÐºÑ‚Ð¾Ð² error in the text declaration of an external entity - error in the text declaration of an external entity + ошибка в объÑвлении внешнего объекта QXmlStream - + Extra content at end of document. Invalid entity value. - + Ðекорректное значение объекта. Invalid XML character. - + Ðекорректный Ñимвол XML. Sequence ']]>' not allowed in content. - + ПоÑледовательноÑть ']]>' не допуÑкаетÑÑ Ð² Ñодержимом. @@ -6626,7 +6618,7 @@ Please choose a different file name. Unsupported XML version. - + ÐÐµÐ¿Ð¾Ð´Ð´ÐµÑ€Ð¶Ð¸Ð²Ð°ÐµÐ¼Ð°Ñ Ð²ÐµÑ€ÑÐ¸Ñ XML. @@ -6641,37 +6633,37 @@ Please choose a different file name. Standalone accepts only yes or no. - + ПÑевдоатрибут 'standalone' может принимать только значение yes или no. Invalid attribute in XML declaration. - + Ðекорректный атрибут в объÑвлении XML. Premature end of document. - + Ðеожиданный конец документа. Invalid document. - + Ðекорректный документ. Expected - + ОжидалоÑÑŒ , but got ' - + , получили ' Unexpected ' - + Ðеожиданное ' @@ -6686,7 +6678,7 @@ Please choose a different file name. Start tag expected. - + ОжидаетÑÑ Ð½Ð°Ñ‡Ð°Ð»Ð¾ Ñ‚Ñга. @@ -6719,12 +6711,12 @@ Please choose a different file name. Invalid XML name. - + Ðекорректное Ð¸Ð¼Ñ XML. Opening and ending tag mismatch. - + Открывающий Ñ‚Ñг не Ñовпадает Ñ Ð·Ð°ÐºÑ€Ñ‹Ð²Ð°ÑŽÑ‰Ð¸Ð¼. @@ -6757,7 +6749,7 @@ Please choose a different file name. The standalone pseudo attribute must appear after the encoding. - + ПÑевдоатрибут 'standalone' должен находитьÑÑ Ð¿Ð¾Ñле ÑƒÐºÐ°Ð·Ð°Ð½Ð¸Ñ ÐºÐ¾Ð´Ð¸Ñ€Ð¾Ð²ÐºÐ¸. @@ -6788,11 +6780,6 @@ Please choose a different file name. - - Attribute %1 can't be serialized because it appears at the top level. - - - Year %1 is invalid because it begins with %2. @@ -7070,6 +7057,8 @@ Please choose a different file name. %1 takes at most %n argument(s). %2 is therefore invalid. + + @@ -7077,6 +7066,8 @@ Please choose a different file name. %1 requires at least %n argument(s). %2 is therefore invalid. + + @@ -7165,7 +7156,7 @@ Please choose a different file name. - + It will not be possible to retrieve %1. @@ -7568,6 +7559,11 @@ Please choose a different file name. + + Attribute %1 can't be serialized because it appears at the top level. + + + %1 is an unsupported encoding. @@ -7809,13 +7805,13 @@ Please choose a different file name. Muted - + Без звука Volume: %1% - + ГромкоÑть: %1% -- cgit v0.12 From c95384106fc69c2e78db20a10e8bedc14f3c58d5 Mon Sep 17 00:00:00 2001 From: axasia Date: Sun, 24 May 2009 17:11:13 +0900 Subject: Update japanese translation of Qt Linguist. --- translations/linguist_ja.qm | Bin 30494 -> 36145 bytes translations/linguist_ja.ts | 466 ++++++++++++++++++++++---------------------- 2 files changed, 237 insertions(+), 229 deletions(-) diff --git a/translations/linguist_ja.qm b/translations/linguist_ja.qm index cdb7c1c..a377318 100644 Binary files a/translations/linguist_ja.qm and b/translations/linguist_ja.qm differ diff --git a/translations/linguist_ja.ts b/translations/linguist_ja.ts index 7af3ebb..685af88 100644 --- a/translations/linguist_ja.ts +++ b/translations/linguist_ja.ts @@ -6,7 +6,7 @@ (New Entry) - + (æ–°ã—ã„é …ç›®) @@ -48,74 +48,74 @@ Batch Translation of '%1' - Qt Linguist - + '%1' ã®ä¸€æ‹¬ç¿»è¨³ - Qt Linguist Batch translated %n entries - - + + %n é …ç›®ãŒä¸€æ‹¬ç¿»è¨³ã•れã¾ã—㟠Qt Linguist - Batch Translation - Qt Linguist - 一括翻訳 + Qt Linguist - 一括翻訳 Options - オプション + オプション Set translated entries to finished - 翻訳ã•れãŸé …目を完了ã«ã™ã‚‹ + 翻訳ã•れãŸé …目を完了ã«ã™ã‚‹ Retranslate entries with existing translation - + 訳語ãŒã‚る項目をå†åº¦ç¿»è¨³ã™ã‚‹ Note that the modified entries will be reset to unfinished if 'Set translated entries to finished' above is unchecked. - + 注æ„:'翻訳ã•れãŸé …目を完了ã«ã™ã‚‹'ã«ãƒã‚§ãƒƒã‚¯ãŒã¤ã„ã¦ã„ãªã„å ´åˆã€ç¿»è¨³ã•れãŸé …ç›®ã¯æœªå®Œäº†ã«ãªã‚Šã¾ã™. Translate also finished entries - + 完了ã—ã¦ã„る項目も翻訳ã™ã‚‹ Phrase book preference - フレーズブックã®å„ªå…ˆåº¦ + フレーズブックã®è¨­å®š Move up - 上ã«ç§»å‹• + 上ã«ç§»å‹• Move down - 下ã«ç§»å‹• + 下ã«ç§»å‹• The batch translator will search through the selected phrase books in the order given above. - + 一括翻訳機能ã¯ã€ä¸Šè¨˜ã§é¸æŠžã•れãŸé †ã«ãƒ•レーズブックを検索ã—ã¾ã™ã€‚ &Run - 実行(&R) + 実行(&R) Cancel - キャンセル + キャンセル @@ -138,38 +138,39 @@ <qt>Duplicate messages found in '%1': - + <qt>'%1' ã«é‡è¤‡ã—ãŸãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ãŒè¦‹ã¤ã‹ã‚Šã¾ã—ãŸ: <p>[more duplicates omitted] - + <p>[ã•らã«é‡è¤‡ã—ã¦ã„る部分ã¯çœç•¥ã•れã¾ã—ãŸ] <p>* Context: %1<br>* Source: %2 - + <p>* コンテキスト: %1<br>* ソーステキスト: %2 <br>* Comment: %3 - + <br>* コメント: %3 Linguist does not know the plural rules for '%1'. Will assume a single universal form. - + Linguist ã¯'%1'ã®è¤‡æ•°ã®ãƒ«ãƒ¼ãƒ«ã‚’知りã¾ã›ã‚“。 +å˜ä¸€ã®å…±é€šå½¢å¼ã¨ã¿ãªã—ã¾ã™ã€‚ Cannot create '%2': %1 - + '%2' を作æˆã§ãã¾ã›ã‚“: %1 Universal Form - + å…±é€šå½¢å¼ @@ -200,37 +201,37 @@ Will assume a single universal form. Accelerator possibly superfluous in translation. - 訳ã«ä½™åˆ†ãªã‚¢ã‚¯ã‚»ãƒ©ãƒ¬ãƒ¼ã‚¿ãŒã¤ã„ã¦ã„ã¾ã™ã€‚ + 訳ã«ä½™åˆ†ãªã‚¢ã‚¯ã‚»ãƒ©ãƒ¬ãƒ¼ã‚¿ãŒã¤ã„ã¦ã„ã¾ã™ã€‚ Accelerator possibly missing in translation. - 訳ã«ã‚¢ã‚¯ã‚»ãƒ©ãƒ¬ãƒ¼ã‚¿ãŒæ¬ ã‘ã¦ã„ã¾ã™ã€‚ + 訳ã«ã‚¢ã‚¯ã‚»ãƒ©ãƒ¬ãƒ¼ã‚¿ãŒæ¬ ã‘ã¦ã„ã¾ã™ã€‚ Translation does not end with the same punctuation as the source text. - 訳ãŒã‚½ãƒ¼ã‚¹ãƒ†ã‚­ã‚¹ãƒˆã¨åŒã˜å¥èª­ç‚¹ã§çµ‚ã‚ã£ã¦ã„ã¾ã›ã‚“。 + 訳ãŒã‚½ãƒ¼ã‚¹ãƒ†ã‚­ã‚¹ãƒˆã¨åŒã˜å¥èª­ç‚¹ã§çµ‚ã‚ã£ã¦ã„ã¾ã›ã‚“。 A phrase book suggestion for '%1' was ignored. - '%1' ã«ã¤ã„ã¦ã®ãƒ•レーズブックã®ç¤ºå”†ã‚’無視ã—ã¦ã„ã¾ã™ã€‚ + '%1' ã«ã¤ã„ã¦ã®ãƒ•レーズブックã®ç¤ºå”†ã‚’無視ã—ã¦ã„ã¾ã™ã€‚ Translation does not refer to the same place markers as in the source text. - 訳語ã«ã¯ã‚½ãƒ¼ã‚¹ãƒ†ã‚­ã‚¹ãƒˆã¨åŒã˜æ•°ã® "%" ãŒã‚りã¾ã›ã‚“。 + 訳語ã«ã¯ã‚½ãƒ¼ã‚¹ãƒ†ã‚­ã‚¹ãƒˆã¨åŒã˜æ•°ã® "%" ãŒã‚りã¾ã›ã‚“。 Translation does not contain the necessary %n place marker. - + 訳語ã«å¿…è¦ãª %n 個ã®ãƒ—レースマーカー "%" ãŒã‚りã¾ã›ã‚“。 Unknown error - + 未知ã®ã‚¨ãƒ©ãƒ¼ @@ -248,37 +249,37 @@ Will assume a single universal form. Find - + 検索 &Find what: - + 検索ã™ã‚‹æ–‡å­—列(&F): &Source texts - + ソーステキスト(&S) &Translations - + 訳語(&T) &Match case - + 大/å°æ–‡å­—ã®åŒºåˆ¥(&M) &Comments - + コメント(&C) Ignore &accelerators - + アクセラレータを無視(&A) @@ -388,16 +389,18 @@ Will assume a single universal form. Generated %n translation(s) (%1 finished and %2 unfinished) - - + + %n ä»¶ã®è¨³èªž (%1 ä»¶ãŒå®Œäº†ã€ %2 ä»¶ãŒæœªå®Œäº†) を生æˆã—ã¾ã—㟠+ Ignored %n untranslated source text(s) - - + + %n ä»¶ã®æœªç¿»è¨³ã®ã‚½ãƒ¼ã‚¹ãƒ†ã‚­ã‚¹ãƒˆã‚’無視ã—ã¾ã—㟠+ @@ -413,12 +416,12 @@ Will assume a single universal form. About Qt - Qt ã«ã¤ã„ã¦(&Q) + Qt ã«ã¤ã„㦠About Qt Linguist - Qt Linguist ã«ã¤ã„ã¦(&A) + Qt Linguist ã«ã¤ã„㦠@@ -476,7 +479,7 @@ Will assume a single universal form. Create a new phrase book. - æ–°ã—ã„ãƒ•ãƒ¬ãƒ¼ã‚ºãƒ–ãƒƒã‚¯ã‚’ä½œæˆ + æ–°ã—ã„フレーズブックを作æˆã—ã¾ã™ã€‚ @@ -545,12 +548,12 @@ Will assume a single universal form. Open Read-O&nly... - + 読å–専用ã§é–‹ã(&N)... &Save All - + å…¨ã¦ä¿å­˜(&S) @@ -584,7 +587,7 @@ Will assume a single universal form. Recently Opened &Files - + 最近使ã£ãŸãƒ•ァイル(&F) @@ -625,7 +628,7 @@ Will assume a single universal form. &Edit Phrase Book - フレーズブックを編集(&E)... + フレーズブックを編集(&E) @@ -696,7 +699,7 @@ Will assume a single universal form. MainWindow - メインウィンドウ + MainWindow @@ -753,7 +756,7 @@ Will assume a single universal form. Open a Qt translation source file (TS file) for editing - Qt 翻訳ソースファイル (TS ファイル) を編集用ã«é–‹ãã¾ã™ã€‚ + Qt 翻訳ソースファイル (TS ファイル) を編集用ã«é–‹ãã¾ã™ &Open Phrase Book @@ -810,7 +813,7 @@ Will assume a single universal form. &Print Phrase Book - フレーズブックをå°åˆ·(&P)... + フレーズブックをå°åˆ·(&P) Re&cently opened files @@ -856,172 +859,176 @@ Will assume a single universal form. Source text - ソーステキスト + ソーステキスト Index - + インデックス Context - コンテキスト + コンテキスト Items - 項目数 + 項目数 This panel lists the source contexts. - ã“ã®ãƒ‘ãƒãƒ«ã§ã¯ã‚½ãƒ¼ã‚¹ã®ã‚³ãƒ³ãƒ†ã‚­ã‚¹ãƒˆã‚’一覧表示ã—ã¦ã„ã¾ã™ã€‚ + ã“ã®ãƒ‘ãƒãƒ«ã§ã¯ã‚½ãƒ¼ã‚¹ã®ã‚³ãƒ³ãƒ†ã‚­ã‚¹ãƒˆã‚’一覧表示ã—ã¦ã„ã¾ã™ã€‚ Strings - + 文字列 Phrases and guesses - + ãƒ•ãƒ¬ãƒ¼ã‚ºã¨æŽ¨æ¸¬ Sources and Forms - + ソースã¨ãƒ•ォーム Warnings - + 警告 MOD status bar: file(s) modified - + MOD Loading... - ロードã—ã¦ã„ã¾ã™... + ロードã—ã¦ã„ã¾ã™... Loading File - Qt Linguist - + ロードã—ã¦ã„ã¾ã™ - Qt Linguist The file '%1' does not seem to be related to the currently open file(s) '%2'. Close the open file(s) first? - + ファイル '%1' ã¯ã€æ—¢ã«é–‹ã„ã¦ã„るファイル '%2' ã¨ã¯é–¢é€£ã—ã¦ã„ãªã„よã†ã§ã™ã€‚ + +å…ˆã«é–‹ã„ãŸãƒ•ァイルを閉ã˜ã¾ã™ã‹? The file '%1' does not seem to be related to the file '%2' which is being loaded as well. Skip loading the first named file? - + ファイル '%1' ã¯ã€æ—¢ã«ãƒ­ãƒ¼ãƒ‰ã•れã¦ã„るファイル '%2' ã¨ã¯é–¢é€£ã—ã¦ã„ãªã„よã†ã§ã™ã€‚ + +ファイルã®ãƒ­ãƒ¼ãƒ‰ã‚’スキップã—ã¾ã™ã‹? %n translation unit(s) loaded. - - + + %n ä»¶ã®ç¿»è¨³é …目をロードã—ã¾ã—ãŸã€‚ Related files (%1);; - + %1 ã«é–¢é€£ã—ãŸãƒ•ァイル;; Open Translation Files - + 翻訳ファイルを開ã File saved. - ファイルãŒä¿å­˜ã•れã¾ã—ãŸã€‚ + ファイルãŒä¿å­˜ã•れã¾ã—ãŸã€‚ Release - リリース + リリース Qt message files for released applications (*.qm) All files (*) - リリースã•れãŸã‚¢ãƒ—リケーション用㮠Qt メッセージファイル (*.qm) + リリースã•れãŸã‚¢ãƒ—リケーション用㮠Qt メッセージファイル (*.qm) ã™ã¹ã¦ã®ãƒ•ァイル (*) File created. - ファイルãŒä½œæˆã•れã¾ã—ãŸã€‚ + ファイルãŒä½œæˆã•れã¾ã—ãŸã€‚ Printing... - å°åˆ·ä¸­... + å°åˆ·ä¸­... Context: %1 - コンテキスト: %1 + コンテキスト: %1 finished - 完了 + 完了 unresolved - 未解決 + 未解決 obsolete - ã“ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã§ã¯ä½¿ã‚れã¦ã„ãªã„ + ã“ã®ãƒãƒ¼ã‚¸ãƒ§ãƒ³ã§ã¯ä½¿ã‚れã¦ã„ãªã„ Printing... (page %1) - å°åˆ·ä¸­... (%1 ページ) + å°åˆ·ä¸­... (%1 ページ) Printing completed - å°åˆ·å®Œäº† + å°åˆ·å®Œäº† Printing aborted - å°åˆ·ä¸­æ­¢ + å°åˆ·ä¸­æ­¢ Search wrapped. - 検索ãŒä¸€é€šã‚Šçµ‚ã‚りã¾ã—ãŸã€‚ + 検索ãŒä¸€é€šã‚Šçµ‚ã‚りã¾ã—ãŸã€‚ @@ -1035,13 +1042,13 @@ All files (*) Qt Linguist - Qt Linguist + Qt Linguist Cannot find the string '%1'. - 文字列 '%1' ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“。 + 文字列 '%1' ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“。 Translate @@ -1056,58 +1063,58 @@ All files (*) Search And Translate in '%1' - Qt Linguist - + '%1' å†…ã§æ¤œç´¢ã—ã¦ç¿»è¨³ - Qt Linguist Translate - Qt Linguist - + 翻訳 - Qt Linguist Translated %n entry(s) - - + + %n é …ç›®ãŒç¿»è¨³æ¸ˆã¿ã§ã™ No more occurrences of '%1'. Start over? - + '%1' ã¯ã€ã“れ以上見ã¤ã‹ã‚Šã¾ã›ã‚“ã€‚å…ˆé ­ã«æˆ»ã‚Šã¾ã™ã‹? Create New Phrase Book - æ–°ã—ã„ãƒ•ãƒ¬ãƒ¼ã‚ºãƒ–ãƒƒã‚¯ã‚’ä½œæˆ + æ–°ã—ã„ãƒ•ãƒ¬ãƒ¼ã‚ºãƒ–ãƒƒã‚¯ã‚’ä½œæˆ Qt phrase books (*.qph) All files (*) - Qt フレーズブック (*.qph) -ã™ã¹ã¦ã®ãƒ•ァイル (*) + Qt フレーズブック (*.qph) +å…¨ã¦ã®ãƒ•ァイル (*) Phrase book created. - フレーズブックãŒä½œæˆã•れã¾ã—ãŸã€‚ + フレーズブックãŒä½œæˆã•れã¾ã—ãŸã€‚ Open Phrase Book - フレーズブックを開ã + フレーズブックを開ã Qt phrase books (*.qph);;All files (*) - + Qt フレーズブック (*.qph);;ã™ã¹ã¦ã®ãƒ•ァイル (*) %n phrase(s) loaded. - + %n é …ç›®ã®ãƒ•レーズãŒãƒ­ãƒ¼ãƒ‰ã•れã¾ã—ãŸã€‚ @@ -1116,32 +1123,32 @@ All files (*) Add to phrase book - + フレーズブックã«è¿½åŠ  No appropriate phrasebook found. - + é©åˆ‡ãªãƒ•レーズブックãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“。 Adding entry to phrasebook %1 - + フレーズブック %1 ã«é …目を追加 Select phrase book to add to - + 追加先ã®ãƒ•ãƒ¬ãƒ¼ã‚ºãƒ–ãƒƒã‚¯ã‚’é¸æŠžã—ã¦ãã ã•ã„ Unable to launch Qt Assistant (%1) - + Qt Assistant (%1) ã‚’èµ·å‹•ã§ãã¾ã›ã‚“ Version %1 - ãƒãƒ¼ã‚¸ãƒ§ãƒ³ %1 + ãƒãƒ¼ã‚¸ãƒ§ãƒ³ %1 Open Source Edition @@ -1158,83 +1165,83 @@ All files (*) <center><img src=":/images/splash.png"/></img><p>%1</p></center><p>Qt Linguist is a tool for adding translations to Qt applications.</p><p>%2</p><p>Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).</p><p>The program is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.</p> - <center><img src=":/images/splash.png"/></img><p>%1</p></center><p>Qt Linguist ã¯ã€Qt アプリケーションã®ç¿»è¨³ã‚’行ã†ãƒ„ールã§ã™ã€‚</p><p>%2</p><p>Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). å…¨ã¦ã®æ¨©åˆ©ã¯ä¿è­·ã•れã¦ã„ã¾ã™ã€‚</p><p>ã“ã®ãƒ—ログラムã¯ã€ã€Œè¨­è¨ˆã€ã€ã€Œå¸‚場性ã€ãŠã‚ˆã³ã€Œç‰¹å®šã®ç›®çš„ã¸ã®é©åˆæ€§ã€ã‚‚å«ã‚€ã€ã‚らゆる種類ã®ã€Œä¿è¨¼ãŒãªãã€ã€ã€Œãã®ã¾ã¾ã§ã€æä¾›ã•れã¾ã™ã€‚</p> + <center><img src=":/images/splash.png"/></img><p>%1</p></center><p>Qt Linguist ã¯ã€Qt アプリケーションã®ç¿»è¨³ã‚’行ã†ãƒ„ールã§ã™ã€‚</p><p>%2</p><p>Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). å…¨ã¦ã®æ¨©åˆ©ã¯ä¿è­·ã•れã¦ã„ã¾ã™ã€‚</p><p>ã“ã®ãƒ—ログラムã¯ã€ã€Œè¨­è¨ˆã€ã€ã€Œå¸‚場性ã€ãŠã‚ˆã³ã€Œç‰¹å®šã®ç›®çš„ã¸ã®é©åˆæ€§ã€ã‚‚å«ã‚€ã€ã‚らゆる種類ã®ã€Œä¿è¨¼ãŒãªãã€ã€ã€Œãã®ã¾ã¾ã§ã€æä¾›ã•れã¾ã™ã€‚</p> Do you want to save the modified files? - + 変更ã•れãŸãƒ•ァイルをä¿å­˜ã—ã¾ã™ã‹? Do you want to save '%1'? - '%1' ã‚’ä¿å­˜ã—ã¾ã™ã‹? + '%1' ã‚’ä¿å­˜ã—ã¾ã™ã‹? Qt Linguist[*] - + Qt Linguist[*] %1[*] - Qt Linguist - + %1[*] - Qt Linguist No untranslated translation units left. - + æœªè¨³é …ç›®ã¯æ®‹ã£ã¦ã„ã¾ã›ã‚“。 &Window - ウィンドウ(&W) + ウィンドウ(&W) Minimize - 最å°åŒ– + 最å°åŒ– Ctrl+M - Ctrl+M + Ctrl+M Display the manual for %1. - %1 ã®ãƒžãƒ‹ãƒ¥ã‚¢ãƒ«ã‚’表示ã—ã¾ã™ã€‚ + %1 ã®ãƒžãƒ‹ãƒ¥ã‚¢ãƒ«ã‚’表示ã—ã¾ã™ã€‚ Display information about %1. - %1 ã«ã¤ã„ã¦ã®æƒ…報を表示ã—ã¾ã™ã€‚ + %1 ã«ã¤ã„ã¦ã®æƒ…報を表示ã—ã¾ã™ã€‚ &Save '%1' - + '%1' ã‚’ä¿å­˜ã™ã‚‹(&S) Save '%1' &As... - + '%1' ã‚’åå‰ã‚’付ã‘ã¦ä¿å­˜(&A)... Release '%1' - + '%1' をリリース Release '%1' As... - + '%1' ã‚’åå‰ã‚’付ã‘ã¦ãƒªãƒªãƒ¼ã‚¹... &Close '%1' - + '%1' ã‚’é–‰ã˜ã‚‹(&C) @@ -1253,78 +1260,78 @@ All files (*) &Close - é–‰ã˜ã‚‹(&C) + é–‰ã˜ã‚‹(&C) Save All - + å…¨ã¦ä¿å­˜ &Release All - + å…¨ã¦ãƒªãƒªãƒ¼ã‚¹(&R) Close All - ã™ã¹ã¦é–‰ã˜ã‚‹ + ã™ã¹ã¦é–‰ã˜ã‚‹ Translation File &Settings for '%1'... - + '%1' ã®ç¿»è¨³ãƒ•ァイルã®è¨­å®š(&S)... &Batch Translation of '%1'... - + '%1' ã®ä¸€æ‹¬ç¿»è¨³(&B)... Search And &Translate in '%1'... - + '%1' 内を検索ã—ã¦ç¿»è¨³(&T)... Search And &Translate... - + 検索ã—ã¦è¨³èªžã‚’ç½®æ›(&T)... Cannot read from phrase book '%1'. - フレーズブック '%1' ã‹ã‚‰èª­ã¿å‡ºã›ã¾ã›ã‚“。 + フレーズブック '%1' ã‹ã‚‰èª­ã¿å‡ºã›ã¾ã›ã‚“。 Close this phrase book. - ã“ã®ãƒ•レーズブックを閉ã˜ã¾ã™ã€‚ + ã“ã®ãƒ•レーズブックを閉ã˜ã¾ã™ã€‚ Enables you to add, modify, or delete entries in this phrase book. - + ã“ã®ãƒ•レーズブックã§é …ç›®ã®è¿½åŠ ã€å¤‰æ›´ã€å‰Šé™¤ãŒã§ãã¾ã™ã€‚ Print the entries in this phrase book. - + ã“ã®ãƒ•レーズブックã®é …目をå°åˆ·ã—ã¾ã™ã€‚ Cannot create phrase book '%1'. - フレーズブック '%1' を作æˆã§ãã¾ã›ã‚“。 + フレーズブック '%1' を作æˆã§ãã¾ã›ã‚“。 Do you want to save phrase book '%1'? - + フレーズブック '%1' ã‚’ä¿å­˜ã—ã¾ã™ã‹? All - + ã™ã¹ã¦ @@ -1468,194 +1475,194 @@ All files (*) &Open... - + é–‹ã(&O)... Save - + ä¿å­˜ &Print... - + å°åˆ·(&P)... Print a list of all the translation units in the current translation source file. - + ç¾åœ¨ã® Qt 翻訳ソースファイルã®å…¨ã¦ã®è¨³èªžã®ä¸€è¦§ã‚’å°åˆ·ã—ã¾ã™ã€‚ Undo the last editing operation performed on the current translation. - + ç¾åœ¨ã®ç¿»è¨³ãƒ•ã‚¡ã‚¤ãƒ«ã§æœ€å¾Œã«è¡Œã£ãŸç·¨é›†æ“作をå–り消ã—ã¾ã™ã€‚ &Find... - + 検索(&F)... Previous unfinished item. - + å‰ã®æœªè¨³ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Move to the previous unfinished item. - + å‰ã®æœªå®Œäº†ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Next unfinished item. - + æ¬¡ã®æœªè¨³ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Move to the next unfinished item. - + æ¬¡ã®æœªå®Œäº†ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Move to previous item. - + å‰ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Move to the previous item. - + å‰ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Next item. - + 次ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Move to the next item. - + 次ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Mark item as done and move to the next unfinished item. - + ã“ã®é …ç›®ã«å®Œäº†ã®ãƒžãƒ¼ã‚¯ã‚’ã¤ã‘ã€æ¬¡ã®æœªå®Œäº†ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Mark this item as done and move to the next unfinished item. - + ã“ã®é …ç›®ã«å®Œäº†ã®ãƒžãƒ¼ã‚¯ã‚’ã¤ã‘ã€æ¬¡ã®æœªå®Œäº†ã®é …ç›®ã¸ç§»å‹•ã—ã¾ã™ã€‚ Copy from source text - + ソーステキストã‹ã‚‰ã‚³ãƒ”ー Toggle the validity check of accelerators. - + アクセラレータã®ãƒã‚§ãƒƒã‚¯ã‚’有効ã«ã™ã‚‹ã‹ã©ã†ã‹ã‚’切り替ãˆã¾ã™ã€‚ Toggle the validity check of accelerators, i.e. whether the number of ampersands in the source and translation text is the same. If the check fails, a message is shown in the warnings window. - + ソーステキストã¨è¨³èªžã®ã‚¢ã‚¯ã‚»ãƒ©ãƒ¬ãƒ¼ã‚¿ã®å€‹æ•°ãŒåŒã˜ã‹å¦ã‹ã®ãƒã‚§ãƒƒã‚¯ã‚’有効ã«ã™ã‚‹ã‹ã©ã†ã‹ã‚’切り替ãˆã¾ã™ã€‚ãƒã‚§ãƒƒã‚¯ãŒç„¡åйã«ãªã£ã¦ã„ã¦ã‚‚ã€è­¦å‘Šã‚¦ã‚£ãƒ³ãƒ‰ã‚¦ã«ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã¯è¡¨ç¤ºã•れã¾ã™ã€‚ Toggle the validity check of ending punctuation. - + 末尾ã®å¥èª­ç‚¹ã®ãƒã‚§ãƒƒã‚¯ã‚’有効ã«ã™ã‚‹ã‹ã©ã†ã‹ã‚’切り替ãˆã¾ã™ã€‚ Toggle the validity check of ending punctuation. If the check fails, a message is shown in the warnings window. - + 末尾ã®å¥èª­ç‚¹ã®ãƒã‚§ãƒƒã‚¯ã‚’有効ã«ã™ã‚‹ã‹ã©ã†ã‹ã‚’切り替ãˆã¾ã™ã€‚ãƒã‚§ãƒƒã‚¯ãŒç„¡åйã«ãªã£ã¦ã„ã¦ã‚‚ã€è­¦å‘Šã‚¦ã‚£ãƒ³ãƒ‰ã‚¦ã«ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ãŒè¡¨ç¤ºã•れã¾ã™ã€‚ Toggle checking that phrase suggestions are used. If the check fails, a message is shown in the warnings window. - + フレーズã®ç¤ºå”†ã‚’使ã†ã‹ã©ã†ã‹ã®ãƒã‚§ãƒƒã‚¯ã‚’切り替ãˆã¾ã™ã€‚ãƒã‚§ãƒƒã‚¯ãŒç„¡åйã«ãªã£ã¦ã„ã¦ã‚‚ã€è­¦å‘Šã‚¦ã‚£ãƒ³ãƒ‰ã‚¦ã«ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ãŒè¡¨ç¤ºã•れã¾ã™ã€‚ Toggle the validity check of place markers. - + "%" ã®æ•°ã‚„番å·ã®ãƒã‚§ãƒƒã‚¯ã‚’行ã†ã‹ã©ã†ã‹ã‚’切り替ãˆã¾ã™ã€‚ Toggle the validity check of place markers, i.e. whether %1, %2, ... are used consistently in the source text and translation text. If the check fails, a message is shown in the warnings window. - + ソーステキストã¨è¨³èªžã®"%1"ã‚„"%2"ç­‰ã®ãƒ—ãƒ¬ãƒ¼ã‚¹ãƒžãƒ¼ã‚«ãƒ¼ã®æ•´åˆãŒå–れã¦ã„ã‚‹ã‹å¦ã‹ã®ãƒã‚§ãƒƒã‚¯ã‚’行ã†ã‹ã©ã†ã‹ã‚’切り替ãˆã¾ã™ã€‚ãƒã‚§ãƒƒã‚¯ãŒç„¡åйã«ãªã£ã¦ã„ã¦ã‚‚ã€è­¦å‘Šã‚¦ã‚£ãƒ³ãƒ‰ã‚¦ã«ãƒ¡ãƒƒã‚»ãƒ¼ã‚¸ã¯è¡¨ç¤ºã•れã¾ã™ã€‚ &New Phrase Book... - + æ–°ã—ã„フレーズブック(&N)... &Open Phrase Book... - + フレーズブックを開ã(&O)... &Reset Sorting - + ソート順åºã‚’リセット(&R) Display translation statistics. - + 翻訳ã®çµ±è¨ˆã‚’表示ã—ã¾ã™ã€‚ &Search And Translate... - + 検索ã—ã¦è¨³èªžã‚’ç½®æ›(&S)... Close - é–‰ã˜ã‚‹ + é–‰ã˜ã‚‹ &Close All - + å…¨ã¦é–‰ã˜ã‚‹(&C) Ctrl+W - + Ctrl+W &Batch Translation... - + 一括翻訳(&B)... Translation File &Settings... - + 翻訳ファイルã®è¨­å®š(&S)... &Add to Phrase Book - + フレーズブックã«è¿½åŠ (&A) Ctrl+T - + Ctrl+T Ctrl+J - + Ctrl+J Ctrl+Shift+J - + Ctrl+Shift+J @@ -1707,82 +1714,82 @@ All files (*) German - + German Japanese - + Japanese French - + French Polish - + Polish Chinese - + Chinese Source text - ソーステキスト + ソーステキスト Source text (Plural) - + ソーステキスト(複数) This area shows the plural form of the source text. - + ã“ã®é ˜åŸŸã¯è¤‡æ•°ã®ã‚½ãƒ¼ã‚¹ãƒ†ã‚­ã‚¹ãƒˆã‚’表示ã—ã¾ã™ã€‚ Developer comments - + 開発者ã®ã‚³ãƒ¡ãƒ³ãƒˆ This area shows a comment that may guide you, and the context in which the text occurs. - ã“ã®é ˜åŸŸã¯ã€æ‰‹åŠ©ã‘ã¨ãªã‚‹ã‚³ãƒ¡ãƒ³ãƒˆã¨ã€ãƒ†ã‚­ã‚¹ãƒˆãŒå‡ºã¦ãるコンテキストを表示ã—ã¾ã™ã€‚ + ã“ã®é ˜åŸŸã¯ã€æ‰‹åŠ©ã‘ã¨ãªã‚‹ã‚³ãƒ¡ãƒ³ãƒˆã¨ã€ãƒ†ã‚­ã‚¹ãƒˆãŒå‡ºã¦ãるコンテキストを表示ã—ã¾ã™ã€‚ Here you can enter comments for your own use. They have no effect on the translated applications. - + ã“ã“ã¯ã‚ãªãŸãŒè‡ªåˆ†è‡ªèº«ã®ç‚ºã«ã‚³ãƒ¡ãƒ³ãƒˆã‚’入力ã§ãã¾ã™ã€‚翻訳ã•れãŸã‚¢ãƒ—リケーションã«ã¯ä½•ã®å½±éŸ¿ã‚‚与ãˆã¾ã›ã‚“。 %1 translation (%2) - + %1 翻訳 (%2) This is where you can enter or modify the translation of the above source text. - + ソーステキストã®è¨³ã‚’入力ã—ãŸã‚Šå¤‰æ›´ã—ãŸã‚Šã§ãã‚‹ã¨ã“ã‚ã§ã™ã€‚ %1 translation - + %1 訳 %1 translator comments - + %1 翻訳者ã®ã‚³ãƒ¡ãƒ³ãƒˆ This area shows the source text. - ã“ã®é ˜åŸŸã¯ã‚½ãƒ¼ã‚¹ãƒ†ã‚­ã‚¹ãƒˆã‚’表示ã—ã¾ã™ã€‚ + ã“ã®é ˜åŸŸã¯ã‚½ãƒ¼ã‚¹ãƒ†ã‚­ã‚¹ãƒˆã‚’表示ã—ã¾ã™ã€‚ This is where you can enter or modify the translation of some source text. @@ -1801,7 +1808,8 @@ All files (*) '%1' Line: %2 - + '%1' +行番å·: %2 @@ -1821,22 +1829,22 @@ Line: %2 Completion status for %1 - + %1 ã®ç¿»è¨³å®Œäº†çŠ¶æ³ <file header> - + <ファイル ヘッダー> <context comment> - + <コンテキスト コメント> <unnamed context> - + <ç„¡åã®ã‚³ãƒ³ãƒ†ã‚­ã‚¹ãƒˆ> @@ -1871,7 +1879,7 @@ Line: %2 %1[*] - Qt Linguist - + %1[*] - Qt Linguist @@ -1886,27 +1894,27 @@ Line: %2 &New Entry - + æ–°ã—ã„é …ç›®(&N) Click here to remove the entry from the phrase book. - + フレーズブックã‹ã‚‰ãƒ•レーズを消去ã™ã‚‹ã«ã¯ã“ã“をクリックã—ã¦ãã ã•ã„。 &Remove Entry - + 項目を削除(&R) Settin&gs... - + 設定(&G)... Click here to close this window. - ã“ã®ã‚¦ã‚£ãƒ³ãƒ‰ã‚¦ã‚’é–‰ã˜ã‚‹ã«ã¯ã“ã“をクリックã—ã¦ãã ã•ã„。 + ã“ã®ã‚¦ã‚£ãƒ³ãƒ‰ã‚¦ã‚’é–‰ã˜ã‚‹ã«ã¯ã“ã“をクリックã—ã¾ã™ã€‚ Click here to remove the phrase from the phrase book. @@ -1958,7 +1966,7 @@ Line: %2 This window allows you to add, modify, or delete entries in a phrase book. - + ã“ã®ã‚¦ã‚£ãƒ³ãƒ‰ã‚¦ã§ãƒ•レーズブックã«ãƒ•レーズを追加ã€å¤‰æ›´ã€å‰Šé™¤ã§ãã¾ã™ã€‚ @@ -2006,7 +2014,7 @@ Line: %2 Translation - 訳 + 翻訳 @@ -2014,22 +2022,22 @@ Line: %2 Insert - + 挿入 Edit - 編集 + 編集 Guess (%1) - 推測(%1) + 推測(%1) Guess - 推測 + 推測 @@ -2037,17 +2045,17 @@ Line: %2 Compiled Qt translations - + コンパイル済㿠Qt 翻訳ファイル Translation files (%1);; - + 翻訳ファイル (%1);; All files (*) - + ã™ã¹ã¦ã®ãƒ•ァイル (*) @@ -2063,57 +2071,57 @@ Line: %2 C++ source files - + C++ ソースファイル Java source files - + Java ソースファイル GNU Gettext localization files - + GNU Gettext 日本語化ファイル Qt Script source files - + Qt スクリプト ソースファイル Qt translation sources (format 1.1) - + Qt 翻訳ソース (1.1å½¢å¼) Qt translation sources (format 2.0) - + Qt 翻訳ソース (2.0å½¢å¼) Qt translation sources (latest format) - + Qt 翻訳ソース (最新ã®å½¢å¼) Qt Designer form files - + Qt デザイナ フォームファイル Qt Jambi form files - + Qt Jambi フォームファイル XLIFF localization files - + XLIFF 日本語化ファイル Qt Linguist 'Phrase Book' - + Qt Linguist 'フレーズ ブック' @@ -2147,17 +2155,17 @@ Line: %2 <i>Source code not available</i> - + <i>ソース コードã¯ä½¿ç”¨ã§ãã¾ã›ã‚“</i> <i>File %1 not available</i> - + <i>ファイル %1 ãŒä½¿ç”¨ã§ãã¾ã›ã‚“</i> <i>File %1 not readable</i> - + <i>ファイル %1 ãŒèª­ã¿è¾¼ã‚ã¾ã›ã‚“</i> @@ -2213,7 +2221,7 @@ Line: %2 Translation - 訳 + 翻訳 @@ -2223,7 +2231,7 @@ Line: %2 Close - é–‰ã˜ã‚‹ + é–‰ã˜ã‚‹ @@ -2656,7 +2664,7 @@ All files (*) Texts such as 'TeX' and 'tex' are considered as different when checked. - ã“ã‚Œã‚’é¸æŠžã™ã‚‹ã¨ã€ãŸã¨ãˆã° 'TeX' 㨠'tex' ã¯ç•°ãªã‚‹ã‚‚ã®ã¨è¦‹ãªã•れã¾ã™ã€‚ + é¸æŠžã™ã‚‹ã¨ã€ãŸã¨ãˆã° 'TeX' 㨠'tex' ã¯ç•°ãªã‚‹ã‚‚ã®ã¨è¦‹ãªã•れã¾ã™ã€‚ @@ -2714,27 +2722,27 @@ All files (*) Settings for '%1' - Qt Linguist - + '%1' ã®è¨­å®š - Qt Linguist Source language - + 翻訳元ã®è¨€èªž Language - 言語 + 言語 Country/Region - + 国/地域 Target language - 翻訳先ã®è¨€èªž + 翻訳先ã®è¨€èªž -- cgit v0.12 From 641c7cbdc52f84c07cf5bb628840bd6072e64764 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Mon, 25 May 2009 09:58:27 +1000 Subject: PauseAnimation visual autotest --- .../visual/pauseAnimation/data/raster/image0.png | Bin 0 -> 3209 bytes .../visual/pauseAnimation/data/raster/manifest.qml | 1262 ++++++++++++++++++++ .../declarative/visual/pauseAnimation/image0.png | Bin 3209 -> 0 bytes .../visual/pauseAnimation/manifest-play.xml | 138 --- .../declarative/visual/pauseAnimation/manifest.xml | 138 --- tests/auto/declarative/visual/pauseAnimation/test | 1 + 6 files changed, 1263 insertions(+), 276 deletions(-) create mode 100644 tests/auto/declarative/visual/pauseAnimation/data/raster/image0.png create mode 100644 tests/auto/declarative/visual/pauseAnimation/data/raster/manifest.qml delete mode 100644 tests/auto/declarative/visual/pauseAnimation/image0.png delete mode 100644 tests/auto/declarative/visual/pauseAnimation/manifest-play.xml delete mode 100644 tests/auto/declarative/visual/pauseAnimation/manifest.xml create mode 100644 tests/auto/declarative/visual/pauseAnimation/test diff --git a/tests/auto/declarative/visual/pauseAnimation/data/raster/image0.png b/tests/auto/declarative/visual/pauseAnimation/data/raster/image0.png new file mode 100644 index 0000000..8082422 Binary files /dev/null and b/tests/auto/declarative/visual/pauseAnimation/data/raster/image0.png differ diff --git a/tests/auto/declarative/visual/pauseAnimation/data/raster/manifest.qml b/tests/auto/declarative/visual/pauseAnimation/data/raster/manifest.qml new file mode 100644 index 0000000..de3f32e --- /dev/null +++ b/tests/auto/declarative/visual/pauseAnimation/data/raster/manifest.qml @@ -0,0 +1,1262 @@ +TestLog { + TestFullFrame { + time: 0 + frameId: 0 + } + TestFrame { + time: 16 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 32 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 48 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 64 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 80 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 96 + hash: '336D31586171F22D541B989D24B95CBB' + } + TestFrame { + time: 112 + hash: '6D63FB5C8A80F0280E88B2CDF8641BB9' + } + TestFrame { + time: 128 + hash: 'EF8941674CB61F54853DC33652BB854E' + } + TestFrame { + time: 144 + hash: 'B3F4A2165EC1EE971542B8EF89656CEA' + } + TestFrame { + time: 160 + hash: 'AF3120FE262D2489C0ED33FBBEE1549F' + } + TestFrame { + time: 176 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 192 + hash: '21F0B0437A999BBDE66A913032D495C2' + } + TestFrame { + time: 208 + hash: '0809D32D5BC1BFCE199B1F39A1C68D4F' + } + TestFrame { + time: 224 + hash: '022137587B39F5123835482178A1F1CF' + } + TestFrame { + time: 240 + hash: '97566CE9558D13EA0780BCE233097B27' + } + TestFrame { + time: 256 + hash: '96D79B07DA105B7F631ED61582B26F7E' + } + TestFrame { + time: 272 + hash: 'F4732FF2DF93FE67CB850DEC34184924' + } + TestFrame { + time: 288 + hash: '054E6E52F74A3E24F04E6AD0071F79F8' + } + TestFrame { + time: 304 + hash: 'F541AF93A9FDE62E4BD1C91D30F91E65' + } + TestFrame { + time: 320 + hash: 'C4F844EE71F23635BB3EC7375F6A134F' + } + TestFrame { + time: 336 + hash: '3E52E06DB2BF78762BB9816FE6B105D9' + } + TestFrame { + time: 352 + hash: 'D9604BE23A91327E6AB454609A9D4A13' + } + TestFrame { + time: 368 + hash: 'DC98A9BDD99367C1E9B838D4BE489DCC' + } + TestFrame { + time: 384 + hash: 'E87B00BFC2C2A75A4234EC02A057AD3A' + } + TestFrame { + time: 400 + hash: '5BE4F5C67941EFB6FCEA363C79F1E321' + } + TestFrame { + time: 416 + hash: '6CC9DE62A0C8FA5E42EAC1B01E99AC32' + } + TestFrame { + time: 432 + hash: '62A7133012348F2EC3A388FB685ECC3F' + } + TestFrame { + time: 448 + hash: '4AC43A03CC6F2020AB5F894D704092AC' + } + TestFrame { + time: 464 + hash: 'C1A7B7D6D64AC5584C073C2881290696' + } + TestFrame { + time: 480 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 496 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 512 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 528 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 544 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 560 + hash: 'C1A7B7D6D64AC5584C073C2881290696' + } + TestFrame { + time: 576 + hash: 'C1A7B7D6D64AC5584C073C2881290696' + } + TestFrame { + time: 592 + hash: '4AC43A03CC6F2020AB5F894D704092AC' + } + TestFrame { + time: 608 + hash: '4AC43A03CC6F2020AB5F894D704092AC' + } + TestFrame { + time: 624 + hash: 'FFD39C1122FE2F7877EF30591B539B40' + } + TestFrame { + time: 640 + hash: '62A7133012348F2EC3A388FB685ECC3F' + } + TestFrame { + time: 656 + hash: '45281A70021F81DBEF30334B1480DA1B' + } + TestFrame { + time: 672 + hash: '6CC9DE62A0C8FA5E42EAC1B01E99AC32' + } + TestFrame { + time: 688 + hash: '79EC710576427DF73DD03F39FBA6E2EB' + } + TestFrame { + time: 704 + hash: '5BE4F5C67941EFB6FCEA363C79F1E321' + } + TestFrame { + time: 720 + hash: '7D9096B1EB940C82A37BAF39EF3CCF3E' + } + TestFrame { + time: 736 + hash: 'E87B00BFC2C2A75A4234EC02A057AD3A' + } + TestFrame { + time: 752 + hash: 'DA60100DC55023C3BAB367D97C8F6A85' + } + TestFrame { + time: 768 + hash: 'DC98A9BDD99367C1E9B838D4BE489DCC' + } + TestFrame { + time: 784 + hash: '3F869538028A09020D5E8F528F4FB119' + } + TestFrame { + time: 800 + hash: '9650FD0364C01B11E4F5DCCE51D008AF' + } + TestFrame { + time: 816 + hash: '2CB09D9655ECC30AE6A591B28C0D355C' + } + TestFrame { + time: 832 + hash: '4DB9BC6C11CAF1D77794C2EABB62A44E' + } + TestFrame { + time: 848 + hash: 'CE2B5DD7418868ACF86FEA6AD19CC0C5' + } + TestFrame { + time: 864 + hash: '7C27EF654E645679C90520D6CF00B0C4' + } + TestFrame { + time: 880 + hash: 'AB3E211DF3EF7F5F7A8D712EDC891C0F' + } + TestFrame { + time: 896 + hash: '19D2AE617A49B57DD012677E2834469C' + } + TestFrame { + time: 912 + hash: '5025EB75C88F0760F637E0342B7F88A2' + } + TestFrame { + time: 928 + hash: '005ACBEF952A8EE536E6308A48223E65' + } + TestFrame { + time: 944 + hash: 'F1E0301430D153FB9D15EAFFDFCD5C58' + } + TestFrame { + time: 960 + hash: '5F18A81707F23D377E81A27C1FC41CE9' + } + TestFrame { + time: 976 + hash: 'BCC35497884C158396C7F60759D1FDA4' + } + TestFrame { + time: 992 + hash: '7A4528B000A4EA142D1C77407FA1F581' + } + TestFrame { + time: 1008 + hash: 'BA967A7D810A4531E577E5F6BD2DEF33' + } + TestFrame { + time: 1024 + hash: 'F5AFD9CF8FFE27E9992454B9E68688CB' + } + TestFrame { + time: 1040 + hash: '51D475C7F64A86D3A18FB115297A7B6B' + } + TestFrame { + time: 1056 + hash: '49F5D6FD45C195A8D245B7FEFC1277AB' + } + TestFrame { + time: 1072 + hash: 'F9B0B278659E3A0F78611E6B7F0F2176' + } + TestFrame { + time: 1088 + hash: '0809D32D5BC1BFCE199B1F39A1C68D4F' + } + TestFrame { + time: 1104 + hash: 'B7208D103B63A936DFF8DD8ED224237F' + } + TestFrame { + time: 1120 + hash: 'A57C81049B0DC68090EC7C3327B9922C' + } + TestFrame { + time: 1136 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 1152 + hash: 'AF3120FE262D2489C0ED33FBBEE1549F' + } + TestFrame { + time: 1168 + hash: '0C20D12464ABBDC45041EA5D9F2719B1' + } + TestFrame { + time: 1184 + hash: 'DD60CBAFF6F34027474E92315DBC0EBC' + } + TestFrame { + time: 1200 + hash: '336D31586171F22D541B989D24B95CBB' + } + TestFrame { + time: 1216 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 1232 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 1248 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 1264 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 1280 + hash: '336D31586171F22D541B989D24B95CBB' + } + TestFrame { + time: 1296 + hash: 'F0D8132489C2F2EF760E905B3C093726' + } + TestFrame { + time: 1312 + hash: '6D63FB5C8A80F0280E88B2CDF8641BB9' + } + TestFrame { + time: 1328 + hash: 'DD60CBAFF6F34027474E92315DBC0EBC' + } + TestFrame { + time: 1344 + hash: 'EF8941674CB61F54853DC33652BB854E' + } + TestFrame { + time: 1360 + hash: 'BC426FB7C31751665B0D3F16E2CB0173' + } + TestFrame { + time: 1376 + hash: '0C20D12464ABBDC45041EA5D9F2719B1' + } + TestFrame { + time: 1392 + hash: '53AE93140252373EAA4D9DA73756BD8E' + } + TestFrame { + time: 1408 + hash: '721D7061811B5439C2E8E395917494BC' + } + TestFrame { + time: 1424 + hash: 'AF3120FE262D2489C0ED33FBBEE1549F' + } + TestFrame { + time: 1440 + hash: 'A8B624EBFC9AB713D1CE55F318A6E90D' + } + TestFrame { + time: 1456 + hash: 'A88A8129259F86DF5A73ADDC3649AD37' + } + TestFrame { + time: 1472 + hash: 'A88A8129259F86DF5A73ADDC3649AD37' + } + TestFrame { + time: 1488 + hash: '3DB5E30EF19EA693C21CCF72892C4390' + } + TestFrame { + time: 1504 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 1520 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 1536 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 1552 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 1568 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 1584 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 1600 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 1616 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 1632 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 1648 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 1664 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 1680 + hash: '3DB5E30EF19EA693C21CCF72892C4390' + } + TestFrame { + time: 1696 + hash: '3DB5E30EF19EA693C21CCF72892C4390' + } + TestFrame { + time: 1712 + hash: 'A88A8129259F86DF5A73ADDC3649AD37' + } + TestFrame { + time: 1728 + hash: 'A8B624EBFC9AB713D1CE55F318A6E90D' + } + TestFrame { + time: 1744 + hash: 'A8B624EBFC9AB713D1CE55F318A6E90D' + } + TestFrame { + time: 1760 + hash: 'AF3120FE262D2489C0ED33FBBEE1549F' + } + TestFrame { + time: 1776 + hash: '721D7061811B5439C2E8E395917494BC' + } + TestFrame { + time: 1792 + hash: 'B3F4A2165EC1EE971542B8EF89656CEA' + } + TestFrame { + time: 1808 + hash: '0C20D12464ABBDC45041EA5D9F2719B1' + } + TestFrame { + time: 1824 + hash: 'BC426FB7C31751665B0D3F16E2CB0173' + } + TestFrame { + time: 1840 + hash: 'EF8941674CB61F54853DC33652BB854E' + } + TestFrame { + time: 1856 + hash: 'DD60CBAFF6F34027474E92315DBC0EBC' + } + TestFrame { + time: 1872 + hash: '6D63FB5C8A80F0280E88B2CDF8641BB9' + } + TestFrame { + time: 1888 + hash: 'E74FE4A6BD92CBE8629C8BC8A870104D' + } + TestFrame { + time: 1904 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 1920 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 1936 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 1952 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 1968 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 1984 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 2000 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 2016 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 2032 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 2048 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 2064 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 2080 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 2096 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 2112 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 2128 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 2144 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 2160 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 2176 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 2192 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 2208 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 2224 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 2240 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 2256 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 2272 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 2288 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 2304 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2320 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 2336 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2352 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2368 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2384 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2400 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 2416 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 2432 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2448 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2464 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2480 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 2496 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 2512 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 3504 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 3520 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 3536 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 3552 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 3568 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 3584 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 3600 + hash: 'E74FE4A6BD92CBE8629C8BC8A870104D' + } + TestFrame { + time: 3616 + hash: 'E11455D4E23A5A865E222A7ABA4BA4F9' + } + TestFrame { + time: 3632 + hash: '8757668E56BE6449EC375F0B8FED1BE3' + } + TestFrame { + time: 3648 + hash: '53AE93140252373EAA4D9DA73756BD8E' + } + TestFrame { + time: 3664 + hash: 'A88A8129259F86DF5A73ADDC3649AD37' + } + TestFrame { + time: 3680 + hash: '630D90EEF2673A69E8EBC4EF1BA40E81' + } + TestFrame { + time: 3696 + hash: 'B7208D103B63A936DFF8DD8ED224237F' + } + TestFrame { + time: 3712 + hash: '1516C3547C7CF64832B3BC7DA7C44521' + } + TestFrame { + time: 3728 + hash: '49F5D6FD45C195A8D245B7FEFC1277AB' + } + TestFrame { + time: 3744 + hash: 'F5AFD9CF8FFE27E9992454B9E68688CB' + } + TestFrame { + time: 3760 + hash: '7A4528B000A4EA142D1C77407FA1F581' + } + TestFrame { + time: 3776 + hash: '5F18A81707F23D377E81A27C1FC41CE9' + } + TestFrame { + time: 3792 + hash: '005ACBEF952A8EE536E6308A48223E65' + } + TestFrame { + time: 3808 + hash: '85C135EF72D3D25658A3663E69FFB7C2' + } + TestFrame { + time: 3824 + hash: '7C27EF654E645679C90520D6CF00B0C4' + } + TestFrame { + time: 3840 + hash: '20258F07C613958C32F783466771391A' + } + TestFrame { + time: 3856 + hash: '9650FD0364C01B11E4F5DCCE51D008AF' + } + TestFrame { + time: 3872 + hash: 'F340CDF60C6D4C29D26B7202A093EC70' + } + TestFrame { + time: 3888 + hash: 'D754D35D0793F9F7D4F6249A874E4C45' + } + TestFrame { + time: 3904 + hash: '79EC710576427DF73DD03F39FBA6E2EB' + } + TestFrame { + time: 3920 + hash: '45281A70021F81DBEF30334B1480DA1B' + } + TestFrame { + time: 3936 + hash: 'FFD39C1122FE2F7877EF30591B539B40' + } + TestFrame { + time: 3952 + hash: '4AC43A03CC6F2020AB5F894D704092AC' + } + TestFrame { + time: 3968 + hash: 'C1A7B7D6D64AC5584C073C2881290696' + } + TestFrame { + time: 3984 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 4000 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 4016 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 4032 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 4048 + hash: '29ECE1BCA4D21FB5862091317D430A13' + } + TestFrame { + time: 4064 + hash: 'C1A7B7D6D64AC5584C073C2881290696' + } + TestFrame { + time: 4080 + hash: 'C1A7B7D6D64AC5584C073C2881290696' + } + TestFrame { + time: 4096 + hash: '4AC43A03CC6F2020AB5F894D704092AC' + } + TestFrame { + time: 4112 + hash: '4AC43A03CC6F2020AB5F894D704092AC' + } + TestFrame { + time: 4128 + hash: 'FFD39C1122FE2F7877EF30591B539B40' + } + TestFrame { + time: 4144 + hash: '62A7133012348F2EC3A388FB685ECC3F' + } + TestFrame { + time: 4160 + hash: '45281A70021F81DBEF30334B1480DA1B' + } + TestFrame { + time: 4176 + hash: '6CC9DE62A0C8FA5E42EAC1B01E99AC32' + } + TestFrame { + time: 4192 + hash: '79EC710576427DF73DD03F39FBA6E2EB' + } + TestFrame { + time: 4208 + hash: '5BE4F5C67941EFB6FCEA363C79F1E321' + } + TestFrame { + time: 4224 + hash: '7D9096B1EB940C82A37BAF39EF3CCF3E' + } + TestFrame { + time: 4240 + hash: 'E87B00BFC2C2A75A4234EC02A057AD3A' + } + TestFrame { + time: 4256 + hash: 'DA60100DC55023C3BAB367D97C8F6A85' + } + TestFrame { + time: 4272 + hash: 'DC98A9BDD99367C1E9B838D4BE489DCC' + } + TestFrame { + time: 4288 + hash: 'B2C778A5EFF5F01EDC54F03D8B4DE8C7' + } + TestFrame { + time: 4304 + hash: '9650FD0364C01B11E4F5DCCE51D008AF' + } + TestFrame { + time: 4320 + hash: '2CB09D9655ECC30AE6A591B28C0D355C' + } + TestFrame { + time: 4336 + hash: '4DB9BC6C11CAF1D77794C2EABB62A44E' + } + TestFrame { + time: 4352 + hash: 'CE2B5DD7418868ACF86FEA6AD19CC0C5' + } + TestFrame { + time: 4368 + hash: 'C4F844EE71F23635BB3EC7375F6A134F' + } + TestFrame { + time: 4384 + hash: '4E1FDA8A0495EF968C1CFFB1257426D7' + } + TestFrame { + time: 4400 + hash: '19D2AE617A49B57DD012677E2834469C' + } + TestFrame { + time: 4416 + hash: 'F438E8D2C16B5DE677924C8411219B19' + } + TestFrame { + time: 4432 + hash: '005ACBEF952A8EE536E6308A48223E65' + } + TestFrame { + time: 4448 + hash: '87B71778D52CD8563D171151D4D32407' + } + TestFrame { + time: 4464 + hash: '691CD8BF5C7802FF6C5024827A379FC6' + } + TestFrame { + time: 4480 + hash: 'AB442C0173C3D221B6782D28001DAC77' + } + TestFrame { + time: 4496 + hash: '6F886D4538704C2FAD4D84C68214109F' + } + TestFrame { + time: 4512 + hash: '56D39F233FAE41C60499D6161F891CBC' + } + TestFrame { + time: 4528 + hash: '95D987C3FD1352FB81C42C63634FE53B' + } + TestFrame { + time: 4544 + hash: '96DC84C0C548021910E7C5B580179054' + } + TestFrame { + time: 4560 + hash: 'DDB71CBD57F6E43744D533D4F72B08DB' + } + TestFrame { + time: 4576 + hash: 'F7AB4B197BEA455B22F259913438D207' + } + TestFrame { + time: 4592 + hash: '2AD64CB01C9D50E0118D5ECE0A644DF2' + } + TestFrame { + time: 4608 + hash: '6579681C59DD571DF0EE4429D74FB5C7' + } + TestFrame { + time: 4624 + hash: '630D90EEF2673A69E8EBC4EF1BA40E81' + } + TestFrame { + time: 4640 + hash: '3DB5E30EF19EA693C21CCF72892C4390' + } + TestFrame { + time: 4656 + hash: '721D7061811B5439C2E8E395917494BC' + } + TestFrame { + time: 4672 + hash: 'BC426FB7C31751665B0D3F16E2CB0173' + } + TestFrame { + time: 4688 + hash: 'E11455D4E23A5A865E222A7ABA4BA4F9' + } + TestFrame { + time: 4704 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 4720 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 4736 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 4752 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 4768 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 4784 + hash: '336D31586171F22D541B989D24B95CBB' + } + TestFrame { + time: 4800 + hash: 'F0D8132489C2F2EF760E905B3C093726' + } + TestFrame { + time: 4816 + hash: 'E11455D4E23A5A865E222A7ABA4BA4F9' + } + TestFrame { + time: 4832 + hash: 'DD60CBAFF6F34027474E92315DBC0EBC' + } + TestFrame { + time: 4848 + hash: '8757668E56BE6449EC375F0B8FED1BE3' + } + TestFrame { + time: 4864 + hash: 'BC426FB7C31751665B0D3F16E2CB0173' + } + TestFrame { + time: 4880 + hash: 'B3F4A2165EC1EE971542B8EF89656CEA' + } + TestFrame { + time: 4896 + hash: '53AE93140252373EAA4D9DA73756BD8E' + } + TestFrame { + time: 4912 + hash: '721D7061811B5439C2E8E395917494BC' + } + TestFrame { + time: 4928 + hash: 'AF3120FE262D2489C0ED33FBBEE1549F' + } + TestFrame { + time: 4944 + hash: 'A8B624EBFC9AB713D1CE55F318A6E90D' + } + TestFrame { + time: 4960 + hash: 'A88A8129259F86DF5A73ADDC3649AD37' + } + TestFrame { + time: 4976 + hash: '3DB5E30EF19EA693C21CCF72892C4390' + } + TestFrame { + time: 4992 + hash: '3DB5E30EF19EA693C21CCF72892C4390' + } + TestFrame { + time: 5008 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 5024 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 5040 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 5056 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 5072 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 5088 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 5104 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 5120 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 5136 + hash: '1373545E43FFF7251CEC9E8375EA267F' + } + TestFrame { + time: 5152 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 5168 + hash: 'E553F365912586C6408C8C53B1B7D118' + } + TestFrame { + time: 5184 + hash: '3DB5E30EF19EA693C21CCF72892C4390' + } + TestFrame { + time: 5200 + hash: '3DB5E30EF19EA693C21CCF72892C4390' + } + TestFrame { + time: 5216 + hash: 'A88A8129259F86DF5A73ADDC3649AD37' + } + TestFrame { + time: 5232 + hash: 'A8B624EBFC9AB713D1CE55F318A6E90D' + } + TestFrame { + time: 5248 + hash: 'AF3120FE262D2489C0ED33FBBEE1549F' + } + TestFrame { + time: 5264 + hash: '721D7061811B5439C2E8E395917494BC' + } + TestFrame { + time: 5280 + hash: '53AE93140252373EAA4D9DA73756BD8E' + } + TestFrame { + time: 5296 + hash: 'B3F4A2165EC1EE971542B8EF89656CEA' + } + TestFrame { + time: 5312 + hash: '0C20D12464ABBDC45041EA5D9F2719B1' + } + TestFrame { + time: 5328 + hash: '8757668E56BE6449EC375F0B8FED1BE3' + } + TestFrame { + time: 5344 + hash: 'EF8941674CB61F54853DC33652BB854E' + } + TestFrame { + time: 5360 + hash: 'E11455D4E23A5A865E222A7ABA4BA4F9' + } + TestFrame { + time: 5376 + hash: '6D63FB5C8A80F0280E88B2CDF8641BB9' + } + TestFrame { + time: 5392 + hash: 'E74FE4A6BD92CBE8629C8BC8A870104D' + } + TestFrame { + time: 5408 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5424 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 5440 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 5456 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 5472 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5488 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 5504 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 5520 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 5536 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 5552 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 5568 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 5584 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5600 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5616 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5632 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5648 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5664 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5680 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5696 + hash: '3042003C067B257DE2CB32F650DDE693' + } + TestFrame { + time: 5712 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 5728 + hash: 'A725B59B4947357546BBFC7DF3D830AF' + } + TestFrame { + time: 5744 + hash: 'CE57E27AF329EBA4FAC3AB891F0407CE' + } + TestFrame { + time: 5760 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 5776 + hash: '41BA853C3403F68A23E708DF82E21C53' + } + TestFrame { + time: 5792 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 5808 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5824 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } + TestFrame { + time: 5840 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5856 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5872 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5888 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5904 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 5920 + hash: 'DCF2867C127E041970047EC8F3EDC04F' + } + TestFrame { + time: 5936 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5952 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5968 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 5984 + hash: '675EBBDD22DD22CE45993DF4AF1ACFE9' + } + TestFrame { + time: 6000 + hash: 'A350B70C5238A340E85FD4A3EC0390A3' + } +} diff --git a/tests/auto/declarative/visual/pauseAnimation/image0.png b/tests/auto/declarative/visual/pauseAnimation/image0.png deleted file mode 100644 index 80fd4d1..0000000 Binary files a/tests/auto/declarative/visual/pauseAnimation/image0.png and /dev/null differ diff --git a/tests/auto/declarative/visual/pauseAnimation/manifest-play.xml b/tests/auto/declarative/visual/pauseAnimation/manifest-play.xml deleted file mode 100644 index 6b15341..0000000 --- a/tests/auto/declarative/visual/pauseAnimation/manifest-play.xml +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/auto/declarative/visual/pauseAnimation/manifest.xml b/tests/auto/declarative/visual/pauseAnimation/manifest.xml deleted file mode 100644 index 6b15341..0000000 --- a/tests/auto/declarative/visual/pauseAnimation/manifest.xml +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tests/auto/declarative/visual/pauseAnimation/test b/tests/auto/declarative/visual/pauseAnimation/test new file mode 100644 index 0000000..85bc3c1 --- /dev/null +++ b/tests/auto/declarative/visual/pauseAnimation/test @@ -0,0 +1 @@ +pauseAnimation.qml -- cgit v0.12 From 531274c741aed51946398a30a7be691ef98999bf Mon Sep 17 00:00:00 2001 From: Lincoln Ramsay Date: Mon, 25 May 2009 15:46:50 +1000 Subject: BT: Clean up Mac -arch handling Instead of the multiple character-string replacements, just check for the discrete -arch values that we want to find. This makes the code clearer and should reduce the chance of subtle errors. Reviewed-by: Jason McDonald --- configure | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/configure b/configure index 32efd86..4cf7499 100755 --- a/configure +++ b/configure @@ -2703,23 +2703,24 @@ fi if [ "$PLATFORM_MAC" = "yes" ]; then # check -arch arguments for validity. ALLOWED="x86 ppc x86_64 ppc64 i386" - for i in $CFG_MAC_ARCHS + # Save the list so we can re-write it using only valid values + CFG_MAC_ARCHS_IN="$CFG_MAC_ARCHS" + CFG_MAC_ARCHS= + for i in $CFG_MAC_ARCHS_IN do if echo "$ALLOWED" | grep -w -v "$i" > /dev/null 2>&1; then echo "Unknown architecture: \"$i\". Supported architectures: x86[i386] ppc x86_64 ppc64"; exit 2; fi - done - -# replace "i386" with "x86" to support configuring with -arch i386 as an alias for x86. - CFG_MAC_ARCHS="${CFG_MAC_ARCHS/i386/x86}" - -# Build commmand line arguments we can pass to the compiler during configure tests -# by prefixing each arch with "-arch". - CFG_MAC_ARCHS_GCC_FORMAT="${CFG_MAC_ARCHS/x86/i386}" - CFG_MAC_ARCHS_GCC_FORMAT="${CFG_MAC_ARCHS_GCC_FORMAT/i386_64/x86_64}" - for ARCH in $CFG_MAC_ARCHS_GCC_FORMAT; do - MAC_ARCHS_COMMANDLINE="$MAC_ARCHS_COMMANDLINE -arch $ARCH" + if [ "$i" = "i386" -o "$i" = "x86" ]; then + # These are synonymous values + # CFG_MAC_ARCHS requires x86 while GCC requires i386 + CFG_MAC_ARCHS="$CFG_MAC_ARCHS x86" + MAC_ARCHS_COMMANDLINE="$MAC_ARCHS_COMMANDLINE -arch i386" + else + CFG_MAC_ARCHS="$CFG_MAC_ARCHS $i" + MAC_ARCHS_COMMANDLINE="$MAC_ARCHS_COMMANDLINE -arch $i" + fi done fi @@ -4129,14 +4130,14 @@ if true; then ###[ '!' -f "$outpath/bin/qmake" ]; EXTRA_CXXFLAGS="$EXTRA_CXXFLAGS \$(CARBON_CFLAGS)" EXTRA_OBJS="qsettings_mac.o qcore_mac.o" EXTRA_SRCS="\"$relpath/src/corelib/io/qsettings_mac.cpp\" \"$relpath/src/corelib/kernel/qcore_mac.cpp\"" - if echo "$CFG_MAC_ARCHS" | grep x86 > /dev/null 2>&1; then + if echo "$CFG_MAC_ARCHS" | grep x86 > /dev/null 2>&1; then # matches both x86 and x86_64 X86_CFLAGS="-arch i386" X86_LFLAGS="-arch i386" EXTRA_CFLAGS="$X86_CFLAGS $EXTRA_CFLAGS" EXTRA_CXXFLAGS="$X86_CFLAGS $EXTRA_CXXFLAGS" EXTRA_LFLAGS="$EXTRA_LFLAGS $X86_LFLAGS" fi - if echo "$CFG_MAC_ARCHS" | grep ppc > /dev/null 2>&1; then + if echo "$CFG_MAC_ARCHS" | grep ppc > /dev/null 2>&1; then # matches both ppc and ppc64 PPC_CFLAGS="-arch ppc" PPC_LFLAGS="-arch ppc" EXTRA_CFLAGS="$PPC_CFLAGS $EXTRA_CFLAGS" -- cgit v0.12 From afb81a7527d798618b03319d4c0c47d33487fcfa Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Mon, 25 May 2009 08:48:25 +0200 Subject: Fix a mistake in the doc. Reviewed-by: TrustMe --- src/gui/image/qpixmapcache.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/gui/image/qpixmapcache.cpp b/src/gui/image/qpixmapcache.cpp index eb1ebd1..31d29d6 100644 --- a/src/gui/image/qpixmapcache.cpp +++ b/src/gui/image/qpixmapcache.cpp @@ -491,8 +491,7 @@ bool QPixmapCache::insert(const QString &key, const QPixmap &pixmap) /*! Inserts a copy of the pixmap \a pm into - the cache and return you the key. The key is always greater than 0. - If the key is equals 0 then the insertion failed. + the cache and return you the key. When a pixmap is inserted and the cache is about to exceed its limit, it removes pixmaps until there is enough room for the -- cgit v0.12 From b89f94e7c9550af9aa1df55bd2d3a635229d77f1 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Mon, 25 May 2009 17:07:00 +1000 Subject: Fix with "new" argc/argv. --- tools/qmlviewer/main.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/tools/qmlviewer/main.cpp b/tools/qmlviewer/main.cpp index 38a00bb..ca98dbf 100644 --- a/tools/qmlviewer/main.cpp +++ b/tools/qmlviewer/main.cpp @@ -95,19 +95,19 @@ int main(int argc, char ** argv) if (arg == "-frameless") { frameless = true; } else if (arg == "-skin") { - skin = QString(argv[++i]); + skin = QString(newargv[++i]); } else if (arg == "-cache") { cache = true; } else if (arg == "-recordperiod") { - period = QString(argv[++i]).toInt(); + period = QString(newargv[++i]).toInt(); } else if (arg == "-recordfile") { - recordfile = QString(argv[++i]); + recordfile = QString(newargv[++i]); } else if (arg == "-record") { - recordargs << QString(argv[++i]); + recordargs << QString(newargv[++i]); } else if (arg == "-recorddither") { - dither = QString(argv[++i]); + dither = QString(newargv[++i]); } else if (arg == "-autorecord") { - QString range = QString(argv[++i]); + QString range = QString(newargv[++i]); int dash = range.indexOf('-'); if (dash > 0) autorecord_from = range.left(dash).toInt(); @@ -135,7 +135,7 @@ int main(int argc, char ** argv) translationFile = newargv[i + 1]; ++i; } else if (arg == "-L") { - libraries << QString(argv[++i]); + libraries << QString(newargv[++i]); } else if (arg[0] != '-') { fileName = arg; } else if (1 || arg == "-help") { -- cgit v0.12 From 4147a2c788c39f09ef87181768a779cb701fd2bd Mon Sep 17 00:00:00 2001 From: jasplin Date: Mon, 25 May 2009 09:25:43 +0200 Subject: Added a "Qt 5 FIXME" comment to qmessagebox.h. QMessageBox::question() has the wrong default value for one of its arguments, but fixing it may break existing code, and the workaround is trivial (just specify an explicit value for the default argument). Reviewed-by: TrustMe Task-number: 254131 --- src/gui/dialogs/qmessagebox.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/gui/dialogs/qmessagebox.h b/src/gui/dialogs/qmessagebox.h index 8d9b9fa..c6fb3bc 100644 --- a/src/gui/dialogs/qmessagebox.h +++ b/src/gui/dialogs/qmessagebox.h @@ -191,6 +191,8 @@ public: static StandardButton information(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton); + // ### Qt 5: Replace Ok with Yes|No in question() function. + // Also consider if Ok == Yes and Cancel == No. static StandardButton question(QWidget *parent, const QString &title, const QString &text, StandardButtons buttons = Ok, StandardButton defaultButton = NoButton); -- cgit v0.12 From 878ccb0645e7f1416daeddd6acdc37fea16b5e25 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Mon, 25 May 2009 10:12:27 +0200 Subject: qdoc: Added some missing qdoc comments. Task-number: 252493 --- src/gui/painting/qcolormap_mac.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/gui/painting/qcolormap_mac.cpp b/src/gui/painting/qcolormap_mac.cpp index 96da90f..afe0378 100644 --- a/src/gui/painting/qcolormap_mac.cpp +++ b/src/gui/painting/qcolormap_mac.cpp @@ -55,11 +55,17 @@ public: }; static QColormap *qt_mac_global_map = 0; +/*! + Creates the class's internal colormap. + */ void QColormap::initialize() { qt_mac_global_map = new QColormap; } +/*! + Deletes the class's internal colormap. + */ void QColormap::cleanup() { delete qt_mac_global_map; -- cgit v0.12 From f8d4c07981e556bf416ccd75e7c460a0b84e4e98 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Mon, 25 May 2009 10:32:42 +0200 Subject: Fixed compilation Solaris. --- tools/designer/src/lib/shared/qdesigner_toolbar.cpp | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/tools/designer/src/lib/shared/qdesigner_toolbar.cpp b/tools/designer/src/lib/shared/qdesigner_toolbar.cpp index 0bb91ee..898be1e 100644 --- a/tools/designer/src/lib/shared/qdesigner_toolbar.cpp +++ b/tools/designer/src/lib/shared/qdesigner_toolbar.cpp @@ -440,18 +440,14 @@ QAction *ToolBarEventFilter::actionAt(const QToolBar *tb, const QPoint &pos) return tb->actions().at(index); } +//that's a trick to get acces to the initStyleOption which is a protected member +class FriendlyToolBar : public QToolBar { +public: + friend class ToolBarEventFilter; +}; + QRect ToolBarEventFilter::handleArea(const QToolBar *tb) { - //that's a trick to get acces to the initStyleOption which is a protected member - class FriendlyToolBar : public QToolBar - { - public: -#ifdef Q_NO_USING_KEYWORD - void initStyleOption(QStyleOptionToolBar *option) { QToolBar::initStyleOption(option); } -#else - using QToolBar::initStyleOption; -#endif - }; QStyleOptionToolBar opt; static_cast(tb)->initStyleOption(&opt); return tb->style()->subElementRect(QStyle::SE_ToolBarHandle, &opt, tb); -- cgit v0.12 From 943b709a71b1ffc9abdf459269c79dd1b731d781 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 19 May 2009 09:55:08 +0200 Subject: Made PixelBuffer/FramebufferObject report correct DPI based metrics. We need to use both qt_defaultDpiX and qt_defaultDpiY, and round the resulting metric values. Reviewed-by: Trond --- src/opengl/qglframebufferobject.cpp | 15 ++++++++------- src/opengl/qglpixelbuffer.cpp | 15 ++++++++------- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index f6857ac..8af9f63 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -985,15 +985,16 @@ void QGLFramebufferObject::drawTexture(const QPointF &point, QMacCompatGLuint te } #endif -extern int qt_defaultDpi(); +extern int qt_defaultDpiX(); +extern int qt_defaultDpiY(); /*! \reimp */ int QGLFramebufferObject::metric(PaintDeviceMetric metric) const { Q_D(const QGLFramebufferObject); - float dpmx = qt_defaultDpi()*100./2.54; - float dpmy = qt_defaultDpi()*100./2.54; + float dpmx = qt_defaultDpiX()*100./2.54; + float dpmy = qt_defaultDpiY()*100./2.54; int w = d->size.width(); int h = d->size.height(); switch (metric) { @@ -1016,16 +1017,16 @@ int QGLFramebufferObject::metric(PaintDeviceMetric metric) const return 32;//d->depth; case PdmDpiX: - return (int)(dpmx * 0.0254); + return qRound(dpmx * 0.0254); case PdmDpiY: - return (int)(dpmy * 0.0254); + return qRound(dpmy * 0.0254); case PdmPhysicalDpiX: - return (int)(dpmx * 0.0254); + return qRound(dpmx * 0.0254); case PdmPhysicalDpiY: - return (int)(dpmy * 0.0254); + return qRound(dpmy * 0.0254); default: qWarning("QGLFramebufferObject::metric(), Unhandled metric type: %d.\n", metric); diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp index ce7e9bd..efc58f2 100644 --- a/src/opengl/qglpixelbuffer.cpp +++ b/src/opengl/qglpixelbuffer.cpp @@ -388,15 +388,16 @@ QPaintEngine *QGLPixelBuffer::paintEngine() const #endif } -extern int qt_defaultDpi(); +extern int qt_defaultDpiX(); +extern int qt_defaultDpiY(); /*! \reimp */ int QGLPixelBuffer::metric(PaintDeviceMetric metric) const { Q_D(const QGLPixelBuffer); - float dpmx = qt_defaultDpi()*100./2.54; - float dpmy = qt_defaultDpi()*100./2.54; + float dpmx = qt_defaultDpiX()*100./2.54; + float dpmy = qt_defaultDpiY()*100./2.54; int w = d->req_size.width(); int h = d->req_size.height(); switch (metric) { @@ -419,16 +420,16 @@ int QGLPixelBuffer::metric(PaintDeviceMetric metric) const return 32;//d->depth; case PdmDpiX: - return (int)(dpmx * 0.0254); + return qRound(dpmx * 0.0254); case PdmDpiY: - return (int)(dpmy * 0.0254); + return qRound(dpmy * 0.0254); case PdmPhysicalDpiX: - return (int)(dpmx * 0.0254); + return qRound(dpmx * 0.0254); case PdmPhysicalDpiY: - return (int)(dpmy * 0.0254); + return qRound(dpmy * 0.0254); default: qWarning("QGLPixelBuffer::metric(), Unhandled metric type: %d\n", metric); -- cgit v0.12 From 886c537f2fa225eecc5a68670688e390445a3936 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Mon, 25 May 2009 09:55:23 +0200 Subject: Fixed broken system clip handling in GL2 paint engine. Override systemStateChanged() to get the system clip updates. Reviewed-by: Trond --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 11 +++++++++++ src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h | 2 -- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index caf744a..f174306 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -173,6 +173,7 @@ public: // Clipping & state stuff stolen from QOpenGLPaintEngine: void updateDepthClip(); + void systemStateChanged(); uint use_system_clip : 1; QPaintEngine *last_engine; @@ -1302,6 +1303,16 @@ void QGL2PaintEngineEx::updateClipRegion(const QRegion &clipRegion, Qt::ClipOper d->updateDepthClip(); } +void QGL2PaintEngineExPrivate::systemStateChanged() +{ + Q_Q(QGL2PaintEngineEx); + use_system_clip = !systemClip.isEmpty(); + + if (q->painter()->hasClipping()) + q->updateClipRegion(q->painter()->clipRegion(), Qt::ReplaceClip); + else + q->updateClipRegion(QRegion(), Qt::NoClip); +} void QGL2PaintEngineExPrivate::updateDepthClip() { diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index 76a4fe0..ccf89f0 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -119,6 +119,4 @@ private: Q_DISABLE_COPY(QGL2PaintEngineEx) }; - - #endif -- cgit v0.12 From 7c0073aaa23769a9e9ec08d595190ce61227ae8c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 19 May 2009 15:23:07 +0200 Subject: Fixed bug in uninitialized GL pixmaps. When not setting filtering mode to GL_NEAREST/GL_LINEAR copying back from FBO to texture fails for some reason. Reviewed-by: Trond --- src/opengl/qpixmapdata_gl.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index e3af864..c89b99b 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -167,6 +167,8 @@ void QGLPixmapData::ensureCreated() const glBindTexture(target, m_textureId); glTexImage2D(target, 0, GL_RGBA, m_width, m_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); } if (!m_source.isNull()) { -- cgit v0.12 From fc0b94eb37f5aee0d4921f3c87c87527c5aa8585 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 20 May 2009 10:17:12 +0200 Subject: Fixed bug in QPaintEngineEx::drawTiledPixmap fallback code. The brush transform needs to include the rect position. Reviewed-by: Trond --- src/gui/painting/qpaintengineex.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index 8eaad60..74338b6 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -778,7 +778,7 @@ void QPaintEngineEx::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, con { QBrush brush(state()->pen.color(), pixmap); QTransform xform; - xform.translate(-s.x(), -s.y()); + xform.translate(r.x() - s.x(), r.y() - s.y()); brush.setTransform(xform); qreal pts[] = { r.x(), r.y(), -- cgit v0.12 From bd9197b8c344e2f259f5e1c08a746464a04687bb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 20 May 2009 12:40:59 +0200 Subject: Introduced preserved swap buffer path in GL window surface. When a buffer swap leaves the back buffer intact we don't have to use an FBO or PB, but can render directly to the window's back buffer, yielding higher performance and depending less on extensions such as multisample FBOs and FBO blitting. Reviewed-by: Trond --- src/opengl/qwindowsurface_gl.cpp | 114 ++++++++++++++++++++++----------------- 1 file changed, 64 insertions(+), 50 deletions(-) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index 6fce3e3..a3422b5 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -102,16 +102,18 @@ QGLGraphicsSystem::QGLGraphicsSystem() int spec[16]; spec[i++] = GLX_RGBA; spec[i++] = GLX_DOUBLEBUFFER; -#if 0 - spec[i++] = GLX_DEPTH_SIZE; - spec[i++] = 8; - spec[i++] = GLX_STENCIL_SIZE; - spec[i++] = 8; - spec[i++] = GLX_SAMPLE_BUFFERS_ARB; - spec[i++] = 1; - spec[i++] = GLX_SAMPLES_ARB; - spec[i++] = 4; -#endif + + if (!qgetenv("QT_GL_SWAPBUFFER_PRESERVE").isNull()) { + spec[i++] = GLX_DEPTH_SIZE; + spec[i++] = 8; + spec[i++] = GLX_STENCIL_SIZE; + spec[i++] = 8; + spec[i++] = GLX_SAMPLE_BUFFERS_ARB; + spec[i++] = 1; + spec[i++] = GLX_SAMPLES_ARB; + spec[i++] = 4; + } + spec[i++] = XNone; XVisualInfo *vi = glXChooseVisual(X11->display, X11->defaultScreen, spec); @@ -229,6 +231,7 @@ struct QGLWindowSurfacePrivate int tried_fbo : 1; int tried_pb : 1; + int destructive_swap_buffers : 1; QGLContext *ctx; @@ -252,6 +255,7 @@ QGLWindowSurface::QGLWindowSurface(QWidget *window) d_ptr->ctx = 0; d_ptr->tried_fbo = false; d_ptr->tried_pb = false; + d_ptr->destructive_swap_buffers = qgetenv("QT_GL_SWAPBUFFER_PRESERVE").isNull(); } QGLWindowSurface::~QGLWindowSurface() @@ -342,6 +346,9 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & QWidget *parent = widget->internalWinId() ? widget : widget->nativeParentWidget(); Q_ASSERT(parent); + if (!geometry().isValid()) + return; + hijackWindow(parent); QRect br = rgn.boundingRect().translated(offset); @@ -356,48 +363,50 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & if (context()->format().doubleBuffer()) { #if !defined(QT_OPENGL_ES_2) - glBindTexture(target, d_ptr->tex_id); + if (d_ptr->destructive_swap_buffers) { + glBindTexture(target, d_ptr->tex_id); - QVector rects = d_ptr->paintedRegion.rects(); - for (int i = 0; i < rects.size(); ++i) { - QRect br = rects.at(i); - if (br.isEmpty()) - continue; + QVector rects = d_ptr->paintedRegion.rects(); + for (int i = 0; i < rects.size(); ++i) { + QRect br = rects.at(i); + if (br.isEmpty()) + continue; - const uint bottom = window()->height() - (br.y() + br.height()); - glCopyTexSubImage2D(target, 0, br.x(), bottom, br.x(), bottom, br.width(), br.height()); - } + const uint bottom = window()->height() - (br.y() + br.height()); + glCopyTexSubImage2D(target, 0, br.x(), bottom, br.x(), bottom, br.width(), br.height()); + } - glBindTexture(target, 0); + glBindTexture(target, 0); - QRegion dirtyRegion = QRegion(window()->rect()) - d_ptr->paintedRegion; + QRegion dirtyRegion = QRegion(window()->rect()) - d_ptr->paintedRegion; - if (!dirtyRegion.isEmpty()) { - context()->makeCurrent(); + if (!dirtyRegion.isEmpty()) { + context()->makeCurrent(); - glMatrixMode(GL_MODELVIEW); - glLoadIdentity(); + glMatrixMode(GL_MODELVIEW); + glLoadIdentity(); - glMatrixMode(GL_PROJECTION); - glLoadIdentity(); + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); #ifndef QT_OPENGL_ES - glOrtho(0, window()->width(), window()->height(), 0, -999999, 999999); + glOrtho(0, window()->width(), window()->height(), 0, -999999, 999999); #else - glOrthof(0, window()->width(), window()->height(), 0, -999999, 999999); + glOrthof(0, window()->width(), window()->height(), 0, -999999, 999999); #endif - glViewport(0, 0, window()->width(), window()->height()); + glViewport(0, 0, window()->width(), window()->height()); - QVector rects = dirtyRegion.rects(); - glColor4f(1, 1, 1, 1); - for (int i = 0; i < rects.size(); ++i) { - QRect rect = rects.at(i); - if (rect.isEmpty()) - continue; + QVector rects = dirtyRegion.rects(); + glColor4f(1, 1, 1, 1); + for (int i = 0; i < rects.size(); ++i) { + QRect rect = rects.at(i); + if (rect.isEmpty()) + continue; - drawTexture(rect, d_ptr->tex_id, window()->size(), rect); + drawTexture(rect, d_ptr->tex_id, window()->size(), rect); + } } - } #endif + } d_ptr->paintedRegion = QRegion(); context()->swapBuffers(); @@ -422,7 +431,7 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & } QSize size = widget->rect().size(); - if (ctx->format().doubleBuffer()) { + if (d_ptr->destructive_swap_buffers && ctx->format().doubleBuffer()) { rect = parent->rect(); br = rect.translated(wOffset); size = parent->size(); @@ -501,13 +510,16 @@ void QGLWindowSurface::updateGeometry() d_ptr->size = rect.size(); if (d_ptr->ctx) { - glBindTexture(target, d_ptr->tex_id); - glTexImage2D(target, 0, GL_RGBA, rect.width(), rect.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, 0); - glBindTexture(target, 0); + if (d_ptr->destructive_swap_buffers) { + glBindTexture(target, d_ptr->tex_id); + glTexImage2D(target, 0, GL_RGBA, rect.width(), rect.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, 0); + glBindTexture(target, 0); + } return; } - if ((QGLExtensions::glExtensions & QGLExtensions::FramebufferObject) + if (d_ptr->destructive_swap_buffers + && (QGLExtensions::glExtensions & QGLExtensions::FramebufferObject) #ifdef QT_OPENGL_ES_2 && (QGLExtensions::glExtensions & QGLExtensions::FramebufferBlit) #endif @@ -542,7 +554,7 @@ void QGLWindowSurface::updateGeometry() } #if !defined(QT_OPENGL_ES_2) - if (d_ptr->pb || !d_ptr->tried_pb) { + if (d_ptr->destructive_swap_buffers && (d_ptr->pb || !d_ptr->tried_pb)) { d_ptr->tried_pb = true; if (d_ptr->pb) { @@ -590,13 +602,15 @@ void QGLWindowSurface::updateGeometry() QGLContext *ctx = reinterpret_cast(window()->d_func()->extraData()->glContext); ctx->makeCurrent(); - glGenTextures(1, &d_ptr->tex_id); - glBindTexture(target, d_ptr->tex_id); - glTexImage2D(target, 0, GL_RGBA, rect.width(), rect.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, 0); + if (d_ptr->destructive_swap_buffers) { + glGenTextures(1, &d_ptr->tex_id); + glBindTexture(target, d_ptr->tex_id); + glTexImage2D(target, 0, GL_RGBA, rect.width(), rect.height(), 0, GL_RGB, GL_UNSIGNED_BYTE, 0); - glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glBindTexture(target, 0); + glTexParameterf(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); + glBindTexture(target, 0); + } qDebug() << "QGLWindowSurface: Using plain widget as window surface" << this;; d_ptr->ctx = ctx; -- cgit v0.12 From 7f43bd48595025961989fcd51bee0271a275b475 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Mon, 25 May 2009 17:31:42 +1000 Subject: Add basic client/server debugging support The canvas framerate monitor now uses this support. --- src/declarative/canvas/canvas.pri | 4 +- src/declarative/canvas/monitor/main.cpp | 287 ------------- src/declarative/canvas/monitor/monitor.pro | 8 - src/declarative/canvas/qsimplecanvas.cpp | 18 +- src/declarative/canvas/qsimplecanvas_p.h | 6 +- .../canvas/qsimplecanvasdebugplugin.cpp | 93 +++++ .../canvas/qsimplecanvasdebugplugin_p.h | 68 +++ src/declarative/canvas/qsimplecanvasserver.cpp | 134 ------ src/declarative/canvas/qsimplecanvasserver_p.h | 75 ---- src/declarative/debugger/debugger.pri | 10 +- src/declarative/debugger/qmldebugclient.cpp | 190 +++++++++ src/declarative/debugger/qmldebugclient.h | 97 +++++ src/declarative/debugger/qmldebugserver.cpp | 283 +++++++++++++ src/declarative/debugger/qmldebugserver.h | 81 ++++ src/declarative/debugger/qpacketprotocol.cpp | 462 +++++++++++++++++++++ src/declarative/debugger/qpacketprotocol.h | 81 ++++ tools/qmldebugger/canvasframerate.cpp | 305 ++++++++++++++ tools/qmldebugger/canvasframerate.h | 23 + tools/qmldebugger/main.cpp | 103 +++++ tools/qmldebugger/qmldebugger.pro | 10 + 20 files changed, 1816 insertions(+), 522 deletions(-) delete mode 100644 src/declarative/canvas/monitor/main.cpp delete mode 100644 src/declarative/canvas/monitor/monitor.pro create mode 100644 src/declarative/canvas/qsimplecanvasdebugplugin.cpp create mode 100644 src/declarative/canvas/qsimplecanvasdebugplugin_p.h delete mode 100644 src/declarative/canvas/qsimplecanvasserver.cpp delete mode 100644 src/declarative/canvas/qsimplecanvasserver_p.h create mode 100644 src/declarative/debugger/qmldebugclient.cpp create mode 100644 src/declarative/debugger/qmldebugclient.h create mode 100644 src/declarative/debugger/qmldebugserver.cpp create mode 100644 src/declarative/debugger/qmldebugserver.h create mode 100644 src/declarative/debugger/qpacketprotocol.cpp create mode 100644 src/declarative/debugger/qpacketprotocol.h create mode 100644 tools/qmldebugger/canvasframerate.cpp create mode 100644 tools/qmldebugger/canvasframerate.h create mode 100644 tools/qmldebugger/main.cpp create mode 100644 tools/qmldebugger/qmldebugger.pro diff --git a/src/declarative/canvas/canvas.pri b/src/declarative/canvas/canvas.pri index 8abfd99..9bdd3fa 100644 --- a/src/declarative/canvas/canvas.pri +++ b/src/declarative/canvas/canvas.pri @@ -2,7 +2,7 @@ SOURCES += \ canvas/qsimplecanvas.cpp \ canvas/qsimplecanvasitem.cpp \ canvas/qsimplecanvasfilter.cpp \ - canvas/qsimplecanvasserver.cpp + canvas/qsimplecanvasdebugplugin.cpp HEADERS += \ canvas/qsimplecanvas.h \ @@ -11,7 +11,7 @@ HEADERS += \ canvas/qsimplecanvas_p.h \ canvas/qsimplecanvasitem_p.h \ canvas/qsimplecanvasfilter_p.h \ - canvas/qsimplecanvasserver_p.h + canvas/qsimplecanvasdebugplugin_p.h contains(QT_CONFIG, opengles2): SOURCES += canvas/qsimplecanvas_opengl.cpp else:contains(QT_CONFIG, opengles1): SOURCES += canvas/qsimplecanvas_opengl1.cpp diff --git a/src/declarative/canvas/monitor/main.cpp b/src/declarative/canvas/monitor/main.cpp deleted file mode 100644 index f5f40bd..0000000 --- a/src/declarative/canvas/monitor/main.cpp +++ /dev/null @@ -1,287 +0,0 @@ -#include -#include -#include -#include -#include - -class QLineGraph : public QWidget -{ -Q_OBJECT -public: - QLineGraph(QWidget * = 0); - - void setPosition(int); - -public slots: - void addSample(int, int, int, int, bool); - -protected: - virtual void paintEvent(QPaintEvent *); - virtual void mousePressEvent(QMouseEvent *); - virtual void resizeEvent(QResizeEvent *); - virtual void showEvent(QShowEvent *); - -private slots: - void scrollbarChanged(int); - -private: - void positionScrollbar(); - void updateScrollbar(); - void drawSample(QPainter *, int, const QRect &); - void drawTime(QPainter *, const QRect &); - struct Sample { - int sample[4]; - bool isBreak; - }; - QList _samples; - - QScrollBar sb; - int position; - int samplesPerWidth; - int resolutionForHeight; - bool ignoreScroll; -}; - -QLineGraph::QLineGraph(QWidget *parent) -: QWidget(parent), sb(Qt::Horizontal, this), position(-1), samplesPerWidth(99), resolutionForHeight(50), ignoreScroll(false) -{ - sb.setMaximum(0); - sb.setMinimum(0); - sb.setSingleStep(1); - - QObject::connect(&sb, SIGNAL(valueChanged(int)), this, SLOT(scrollbarChanged(int))); -} - -void QLineGraph::scrollbarChanged(int v) -{ - if(ignoreScroll) - return; - - position = v; - update(); -} - -void QLineGraph::positionScrollbar() -{ - sb.setFixedWidth(width()); - sb.move(0, height() - sb.height()); -} - -void QLineGraph::resizeEvent(QResizeEvent *e) -{ - QWidget::resizeEvent(e); - positionScrollbar(); -} - -void QLineGraph::showEvent(QShowEvent *e) -{ - QWidget::showEvent(e); - positionScrollbar(); -} - -void QLineGraph::mousePressEvent(QMouseEvent *) -{ - if(position == -1) { - position = qMax(0, _samples.count() - samplesPerWidth - 1); - } else { - position = -1; - } - update(); -} - -void QLineGraph::updateScrollbar() -{ - ignoreScroll = true; - sb.setMaximum(qMax(0, _samples.count() - samplesPerWidth - 1)); - - if(position == -1) { - sb.setValue(sb.maximum()); - } else { - sb.setValue(position); - } - ignoreScroll = false; -} - -void QLineGraph::addSample(int a, int b, int c, int d, bool isBreak) -{ - Sample s; - s.isBreak = isBreak; - s.sample[0] = a; - s.sample[1] = b; - s.sample[2] = c; - s.sample[3] = d; - _samples << s; - updateScrollbar(); - update(); -} - -void QLineGraph::drawTime(QPainter *p, const QRect &rect) -{ - if(_samples.isEmpty()) - return; - - int first = position; - if(first == -1) - first = qMax(0, _samples.count() - samplesPerWidth - 1); - int last = qMin(_samples.count() - 1, first + samplesPerWidth); - - qreal scaleX = qreal(rect.width()) / qreal(samplesPerWidth); - - int t = 0; - - for(int ii = first; ii <= last; ++ii) { - int sampleTime = _samples.at(ii).sample[3] / 1000; - if(sampleTime != t) { - - int xEnd = rect.left() + scaleX * (ii - first); - p->drawLine(xEnd, rect.bottom(), xEnd, rect.bottom() + 7); - - QRect text(xEnd - 30, rect.bottom() + 10, 60, 30); - - p->drawText(text, Qt::AlignHCenter | Qt::AlignTop, QString::number(_samples.at(ii).sample[3])); - - t = sampleTime; - } - } - -} - -void QLineGraph::drawSample(QPainter *p, int s, const QRect &rect) -{ - if(_samples.isEmpty()) - return; - - int first = position; - if(first == -1) - first = qMax(0, _samples.count() - samplesPerWidth - 1); - int last = qMin(_samples.count() - 1, first + samplesPerWidth); - - qreal scaleY = rect.height() / resolutionForHeight; - qreal scaleX = qreal(rect.width()) / qreal(samplesPerWidth); - - int xEnd; - int lastXEnd = rect.left(); - - p->save(); - p->setPen(Qt::NoPen); - for(int ii = first + 1; ii <= last; ++ii) { - - xEnd = rect.left() + scaleX * (ii - first); - int yEnd = rect.bottom() - _samples.at(ii).sample[s] * scaleY; - - if (!(s == 0 && _samples.at(ii).isBreak)) - p->drawRect(QRect(lastXEnd, yEnd, scaleX, _samples.at(ii).sample[s] * scaleY)); - - lastXEnd = xEnd; - } - p->restore(); -} - -void QLineGraph::paintEvent(QPaintEvent *) -{ - QPainter p(this); - p.setRenderHint(QPainter::Antialiasing); - - - QRect r(50, 10, width() - 60, height() - 60); - p.setBrush(QColor("lightsteelblue")); - drawSample(&p, 0, r); - - p.setBrush(QColor("pink")); - drawSample(&p, 1, r); - - p.setBrush(QColor("green")); - drawSample(&p, 2, r); - - p.setBrush(Qt::NoBrush); - p.drawRect(r); - - for(int ii = 0; ii <= resolutionForHeight; ++ii) { - int y = 1 + r.bottom() - ii * r.height() / resolutionForHeight; - - if((ii % 10) == 0) { - p.drawLine(r.left() - 20, y, r.left(), y); - QRect text(r.left() - 20 - 53, y - 10, 50, 20); - p.drawText(text, Qt::AlignRight | Qt::AlignVCenter, QString::number(ii)); - } else { - p.drawLine(r.left() - 7, y, r.left(), y); - } - } - - drawTime(&p, r); -} - -class MyReader : public QObject -{ -Q_OBJECT -public: - MyReader(const QString &host, int port); - -signals: - void sample(int, int, int, int, bool); - -private slots: - void readyRead(); - -private: - QTcpSocket *socket; - - int la; - int lb; - int ld; -}; - -MyReader::MyReader(const QString &host, int port) -: socket(0), la(-1) -{ - socket = new QTcpSocket(this); - QObject::connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead())); - socket->connectToHost(host, port); - socket->waitForConnected(); -} - -void MyReader::readyRead() -{ - static int la = -1; - static int lb; - static int ld; - - if(socket->canReadLine()) { - QString line = socket->readLine(); - - int a; - int b; - int c; - int d; - int isBreak; - sscanf(line.toLatin1().constData(), "%d %d %d %d %d", &a, &b, &c, &d, &isBreak); - - if (la != -1) - emit sample(c, lb, la, ld, isBreak); - - la = a; - lb = b; - ld = d; - } -} - -int main(int argc, char ** argv) -{ - if(argc != 3) { - qWarning() << "Usage:" << argv[0] << "host port"; - return -1; - } - - QApplication app(argc, argv); - - MyReader reader(argv[1], atoi(argv[2])); - - QLineGraph graph; - QObject::connect(&reader, SIGNAL(sample(int,int,int,int,bool)), &graph, SLOT(addSample(int,int,int,int,bool))); - graph.setFixedSize(800, 600); - graph.show(); - - return app.exec(); -} - -#include "main.moc" diff --git a/src/declarative/canvas/monitor/monitor.pro b/src/declarative/canvas/monitor/monitor.pro deleted file mode 100644 index e3b0a29..0000000 --- a/src/declarative/canvas/monitor/monitor.pro +++ /dev/null @@ -1,8 +0,0 @@ -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . -QT += network - -# Input -SOURCES += main.cpp diff --git a/src/declarative/canvas/qsimplecanvas.cpp b/src/declarative/canvas/qsimplecanvas.cpp index fbd5014..7d2c9c5 100644 --- a/src/declarative/canvas/qsimplecanvas.cpp +++ b/src/declarative/canvas/qsimplecanvas.cpp @@ -53,7 +53,7 @@ #include #endif #include "qboxlayout.h" -#include "qsimplecanvasserver_p.h" +#include "qsimplecanvasdebugplugin_p.h" #include "qsimplecanvas.h" @@ -533,8 +533,8 @@ void QSimpleCanvasGraphicsView::paintEvent(QPaintEvent *pe) int frametimer = canvas->frameTimer.elapsed(); gfxCanvasTiming.append(QSimpleCanvasTiming(r, frametimer, canvas->lrpTime, tbf)); canvas->lrpTime = 0; - if (canvas->canvasServer) - canvas->canvasServer->addTiming(canvas->lrpTime, frametimer, tbf); + if (canvas->debugPlugin) + canvas->debugPlugin->addTiming(canvas->lrpTime, frametimer, tbf); } void QSimpleCanvasGraphicsView::focusInEvent(QFocusEvent *) @@ -573,12 +573,8 @@ void QSimpleCanvasPrivate::init(QSimpleCanvas::CanvasMode mode) if (continuousUpdate()) qWarning("QSimpleCanvas: Continuous update enabled"); - QByteArray env = qgetenv("GFX_CANVAS_SERVER_PORT"); - if (!env.isEmpty()){ - int port = env.toInt(); - if (port >= 1024) - canvasServer = new QSimpleCanvasServer(port, q); - } + if (QmlDebugServerPlugin::isDebuggingEnabled()) + debugPlugin = new QSimpleCanvasDebugPlugin(q); root = new QSimpleCanvasRootLayer(q); root->setActiveFocusPanel(true); @@ -950,8 +946,8 @@ bool QSimpleCanvas::event(QEvent *e) int frametimer = d->frameTimer.elapsed(); gfxCanvasTiming.append(QSimpleCanvasTiming(r, frametimer, d->lrpTime, tbf)); - if (d->canvasServer) - d->canvasServer->addTiming(d->lrpTime, frametimer, tbf); + if (d->debugPlugin) + d->debugPlugin->addTiming(d->lrpTime, frametimer, tbf); d->lrpTime = 0; if (continuousUpdate()) queueUpdate(); diff --git a/src/declarative/canvas/qsimplecanvas_p.h b/src/declarative/canvas/qsimplecanvas_p.h index 9c3408e..d9ed4ac 100644 --- a/src/declarative/canvas/qsimplecanvas_p.h +++ b/src/declarative/canvas/qsimplecanvas_p.h @@ -101,12 +101,12 @@ private: }; class QGLFramebufferObject; -class QSimpleCanvasServer; +class QSimpleCanvasDebugPlugin; class QSimpleCanvasPrivate { public: QSimpleCanvasPrivate(QSimpleCanvas *canvas) - : q(canvas), timer(0), root(0), lrpTime(0), canvasServer(0), focusItem(0), + : q(canvas), timer(0), root(0), lrpTime(0), debugPlugin(0), focusItem(0), lastFocusItem(0), lastMouseItem(0), isSetup(false), view(0) #if defined(QFX_RENDER_OPENGL) @@ -139,7 +139,7 @@ public: QTime frameTimer; QTime lrpTimer; - QSimpleCanvasServer *canvasServer; + QSimpleCanvasDebugPlugin *debugPlugin; QStack focusPanels; QHash focusPanelData; diff --git a/src/declarative/canvas/qsimplecanvasdebugplugin.cpp b/src/declarative/canvas/qsimplecanvasdebugplugin.cpp new file mode 100644 index 0000000..0ce5378 --- /dev/null +++ b/src/declarative/canvas/qsimplecanvasdebugplugin.cpp @@ -0,0 +1,93 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qsimplecanvasdebugplugin_p.h" +#include "qdebug.h" +#include + +QT_BEGIN_NAMESPACE + +class FrameBreakAnimation : public QAbstractAnimation +{ +public: + FrameBreakAnimation(QSimpleCanvasDebugPlugin *s) + : QAbstractAnimation(s), server(s) + { + start(); + } + + virtual int duration() const { return -1; } + virtual void updateCurrentTime(int msecs) { + server->frameBreak(); + } + +private: + QSimpleCanvasDebugPlugin *server; +}; + +QSimpleCanvasDebugPlugin::QSimpleCanvasDebugPlugin(QObject *parent) +: QmlDebugServerPlugin("CanvasFrameRate", parent), _breaks(0) +{ + _time.start(); + new FrameBreakAnimation(this); +} + +void QSimpleCanvasDebugPlugin::addTiming(quint32 paint, + quint32 repaint, + quint32 timeBetweenFrames) +{ + bool isFrameBreak = _breaks > 1; + _breaks = 0; + int e = _time.elapsed(); + QByteArray data; + QDataStream ds(&data, QIODevice::WriteOnly); + ds << (int)paint << (int)repaint << (int)timeBetweenFrames << (int)e + << (bool)isFrameBreak; + sendMessage(data); +} + +void QSimpleCanvasDebugPlugin::frameBreak() +{ + _breaks++; +} + +QT_END_NAMESPACE + diff --git a/src/declarative/canvas/qsimplecanvasdebugplugin_p.h b/src/declarative/canvas/qsimplecanvasdebugplugin_p.h new file mode 100644 index 0000000..0c76f38 --- /dev/null +++ b/src/declarative/canvas/qsimplecanvasdebugplugin_p.h @@ -0,0 +1,68 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSIMPLECANVASDEBUGPLUGIN_P_H +#define QSIMPLECANVASDEBUGPLUGIN_P_H + +#include "qobject.h" +#include "qtcpserver.h" +#include "qtcpsocket.h" +#include "qdatetime.h" +#include + +QT_BEGIN_NAMESPACE +class QSimpleCanvasDebugPlugin : public QmlDebugServerPlugin +{ +public: + QSimpleCanvasDebugPlugin(QObject *parent = 0); + + void addTiming(quint32, quint32, quint32); + +private: + friend class FrameBreakAnimation; + void frameBreak(); + int _breaks; + QTime _time; +}; +QT_END_NAMESPACE + +#endif // QSIMPLECANVASDEBUGPLUGIN_P_H + diff --git a/src/declarative/canvas/qsimplecanvasserver.cpp b/src/declarative/canvas/qsimplecanvasserver.cpp deleted file mode 100644 index ed781b8..0000000 --- a/src/declarative/canvas/qsimplecanvasserver.cpp +++ /dev/null @@ -1,134 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "qsimplecanvasserver_p.h" -#include "qdebug.h" -#ifndef Q_OS_WIN32 -#include -#endif -#include - -QT_BEGIN_NAMESPACE - -class FrameBreakAnimation : public QAbstractAnimation -{ -public: - FrameBreakAnimation(QSimpleCanvasServer *s) - : QAbstractAnimation(s), server(s) - { - start(); - } - - virtual int duration() const { return -1; } - virtual void updateCurrentTime(int msecs) { - server->frameBreak(); - } - -private: - QSimpleCanvasServer *server; -}; - -QSimpleCanvasServer::QSimpleCanvasServer(int port, QObject *parent) -: QObject(parent), _breaks(0), _tcpServer(new QTcpServer(this)) -{ - QObject::connect(_tcpServer, SIGNAL(newConnection()), - this, SLOT(newConnection())); - - _time.start(); - - new FrameBreakAnimation(this); - if (!_tcpServer->listen(QHostAddress::Any, port)) { - qWarning() << "QSimpleCanvasServer: Cannot listen on port" << port; - return; - } -} - -void QSimpleCanvasServer::newConnection() -{ - QTcpSocket *socket = _tcpServer->nextPendingConnection(); - QObject::connect(socket, SIGNAL(disconnected()), - this, SLOT(disconnected())); - _tcpClients << socket; -} - -void QSimpleCanvasServer::addTiming(quint32 paint, - quint32 repaint, - quint32 timeBetweenFrames) -{ - /* - quint32 data[3]; - data[0] = ::htonl(paint); - data[1] = ::htonl(repaint); - data[2] = ::htonl(timeBetweenFrames); - */ - - bool isFrameBreak = _breaks > 1; - _breaks = 0; - int e = _time.elapsed(); - QString d = QString::number(paint) + QLatin1String(" ") + QString::number(repaint) + QLatin1String(" ") + QString::number(timeBetweenFrames) + QLatin1String(" ") + QString::number(e) + QLatin1String(" ") + QString::number(isFrameBreak) + QLatin1String("\n"); - QByteArray ba = d.toLatin1(); - - // XXX - for (int ii = 0; ii < _tcpClients.count(); ++ii) -// _tcpClients.at(ii)->write((const char *)data, 12); - _tcpClients.at(ii)->write(ba.constData(), ba.length()); -} - -void QSimpleCanvasServer::frameBreak() -{ - _breaks++; -} - -void QSimpleCanvasServer::disconnected() -{ - QTcpSocket *socket = static_cast(sender()); - - for (int ii = 0; ii < _tcpClients.count(); ++ii) { - if (_tcpClients.at(ii) == socket) { - socket->disconnect(); - socket->deleteLater(); - _tcpClients.removeAt(ii); - return; - } - } -} - -QT_END_NAMESPACE diff --git a/src/declarative/canvas/qsimplecanvasserver_p.h b/src/declarative/canvas/qsimplecanvasserver_p.h deleted file mode 100644 index ce04e8d..0000000 --- a/src/declarative/canvas/qsimplecanvasserver_p.h +++ /dev/null @@ -1,75 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QSIMPLECANVASSERVER_P_H -#define QSIMPLECANVASSERVER_P_H - -#include "qobject.h" -#include "qtcpserver.h" -#include "qtcpsocket.h" -#include "qdatetime.h" - - -QT_BEGIN_NAMESPACE -class QSimpleCanvasServer : public QObject -{ -Q_OBJECT -public: - QSimpleCanvasServer(int port, QObject *parent); - - void addTiming(quint32, quint32, quint32); - -private Q_SLOTS: - void newConnection(); - void disconnected(); - -private: - friend class FrameBreakAnimation; - void frameBreak(); - int _breaks; - - QTcpServer *_tcpServer; - QList _tcpClients; - QTime _time; -}; - -QT_END_NAMESPACE -#endif // GFXCANVASSERVER_P_H diff --git a/src/declarative/debugger/debugger.pri b/src/declarative/debugger/debugger.pri index c386d74..121cb98 100644 --- a/src/declarative/debugger/debugger.pri +++ b/src/declarative/debugger/debugger.pri @@ -3,11 +3,17 @@ SOURCES += debugger/qmldebugger.cpp \ debugger/qmlpropertyview.cpp \ debugger/qmlwatches.cpp \ debugger/qmlobjecttree.cpp \ - debugger/qmlcanvasdebugger.cpp + debugger/qmlcanvasdebugger.cpp \ + debugger/qpacketprotocol.cpp \ + debugger/qmldebugserver.cpp \ + debugger/qmldebugclient.cpp HEADERS += debugger/qmldebugger.h \ debugger/qmldebuggerstatus.h \ debugger/qmlpropertyview_p.h \ debugger/qmlwatches_p.h \ debugger/qmlobjecttree_p.h \ - debugger/qmlcanvasdebugger_p.h + debugger/qmlcanvasdebugger_p.h \ + debugger/qpacketprotocol.h \ + debugger/qmldebugserver.h \ + debugger/qmldebugclient.h diff --git a/src/declarative/debugger/qmldebugclient.cpp b/src/declarative/debugger/qmldebugclient.cpp new file mode 100644 index 0000000..7a304ef --- /dev/null +++ b/src/declarative/debugger/qmldebugclient.cpp @@ -0,0 +1,190 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmldebugclient.h" +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QmlDebugClientPrivate : public QObject +{ + Q_OBJECT +public: + QmlDebugClientPrivate(QmlDebugClient *c); + QmlDebugClient *q; + QPacketProtocol *protocol; + + QStringList enabled; + QHash plugins; +public slots: + void connected(); + void readyRead(); +}; + +QmlDebugClientPrivate::QmlDebugClientPrivate(QmlDebugClient *c) +: QObject(c), q(c), protocol(0) +{ + protocol = new QPacketProtocol(q, this); + QObject::connect(c, SIGNAL(connected()), this, SLOT(connected())); + QObject::connect(protocol, SIGNAL(readyRead()), this, SLOT(readyRead())); +} + +void QmlDebugClientPrivate::connected() +{ + QPacket pack; + pack << QString(QLatin1String("QmlDebugServer")) << QStringList(); + protocol->send(pack); +} + +void QmlDebugClientPrivate::readyRead() +{ + QPacket pack = protocol->read(); + QString name; QByteArray message; + pack >> name >> message; + + QHash::Iterator iter = + plugins.find(name); + if (iter == plugins.end()) { + qWarning() << "QmlDebugClient: Message received for missing plugin" << name; + } else { + (*iter)->messageReceived(message); + } +} + +QmlDebugClient::QmlDebugClient(QObject *parent) +: QTcpSocket(parent), d(new QmlDebugClientPrivate(this)) +{ +} + +class QmlDebugClientPluginPrivate : public QObjectPrivate +{ + Q_DECLARE_PUBLIC(QmlDebugClientPlugin); +public: + QmlDebugClientPluginPrivate(); + + QString name; + QmlDebugClient *client; + bool enabled; +}; + +QmlDebugClientPluginPrivate::QmlDebugClientPluginPrivate() +: client(0), enabled(false) +{ +} + +QmlDebugClientPlugin::QmlDebugClientPlugin(const QString &name, + QmlDebugClient *parent) +: QObject(*(new QmlDebugClientPluginPrivate), parent) +{ + Q_D(QmlDebugClientPlugin); + d->name = name; + d->client = parent; + + if (!d->client) + return; + + if (d->client->d->plugins.contains(name)) { + qWarning() << "QmlDebugClientPlugin: Conflicting plugin name" << name; + d->client = 0; + } else { + d->client->d->plugins.insert(name, this); + } +} + +QString QmlDebugClientPlugin::name() const +{ + Q_D(const QmlDebugClientPlugin); + return d->name; +} + +bool QmlDebugClientPlugin::isEnabled() const +{ + Q_D(const QmlDebugClientPlugin); + return d->enabled; +} + +void QmlDebugClientPlugin::setEnabled(bool e) +{ + Q_D(QmlDebugClientPlugin); + if (e == d->enabled) + return; + + d->enabled = e; + + if (d->client) { + if (e) + d->client->d->enabled.append(d->name); + else + d->client->d->enabled.removeAll(d->name); + + if (d->client->state() == QTcpSocket::ConnectedState) { + QPacket pack; + pack << QString(QLatin1String("QmlDebugServer")); + if (e) pack << (int)1; + else pack << (int)2; + pack << d->name; + d->client->d->protocol->send(pack); + } + } +} + +void QmlDebugClientPlugin::sendMessage(const QByteArray &message) +{ + Q_D(QmlDebugClientPlugin); + + if (!d->client || d->client->state() != QTcpSocket::ConnectedState) + return; + + QPacket pack; + pack << d->name << message; + d->client->d_func()->protocol->send(pack); +} + +void QmlDebugClientPlugin::messageReceived(const QByteArray &) +{ +} + +#include "qmldebugclient.moc" + +QT_END_NAMESPACE diff --git a/src/declarative/debugger/qmldebugclient.h b/src/declarative/debugger/qmldebugclient.h new file mode 100644 index 0000000..d765822 --- /dev/null +++ b/src/declarative/debugger/qmldebugclient.h @@ -0,0 +1,97 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLDEBUGCLIENT_H +#define QMLDEBUGCLIENT_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +class QmlDebugClientPrivate; +class Q_DECLARATIVE_EXPORT QmlDebugClient : public QTcpSocket +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QmlDebugClient) + Q_DISABLE_COPY(QmlDebugClient) +public: + QmlDebugClient(QObject * = 0); + +private: + QmlDebugClientPrivate *d; + friend class QmlDebugClientPlugin; + friend class QmlDebugClientPluginPrivate; +}; + +class QmlDebugClientPluginPrivate; +class Q_DECLARATIVE_EXPORT QmlDebugClientPlugin : public QObject +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QmlDebugClientPlugin) + Q_DISABLE_COPY(QmlDebugClientPlugin) + +public: + QmlDebugClientPlugin(const QString &, QmlDebugClient *parent); + + QString name() const; + + bool isEnabled() const; + void setEnabled(bool); + + void sendMessage(const QByteArray &); + +protected: + virtual void messageReceived(const QByteArray &); + +private: + friend class QmlDebugClient; + friend class QmlDebugClientPrivate; +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QMLDEBUGCLIENT_H diff --git a/src/declarative/debugger/qmldebugserver.cpp b/src/declarative/debugger/qmldebugserver.cpp new file mode 100644 index 0000000..bce7e6d --- /dev/null +++ b/src/declarative/debugger/qmldebugserver.cpp @@ -0,0 +1,283 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmldebugserver.h" +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +class QmlDebugServerPrivate; +class QmlDebugServer : public QObject +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QmlDebugServer) + Q_DISABLE_COPY(QmlDebugServer) +public: + static QmlDebugServer *instance(); + +private slots: + void readyRead(); + +private: + friend class QmlDebugServerPlugin; + friend class QmlDebugServerPluginPrivate; + QmlDebugServer(int); +}; + +class QmlDebugServerPrivate : public QObjectPrivate +{ + Q_DECLARE_PUBLIC(QmlDebugServer); +public: + QmlDebugServerPrivate(); + void init(int port); + + QTcpSocket *connection; + QPacketProtocol *protocol; + QHash plugins; + QStringList enabledPlugins; +}; + +class QmlDebugServerPluginPrivate : public QObjectPrivate +{ + Q_DECLARE_PUBLIC(QmlDebugServerPlugin); +public: + QmlDebugServerPluginPrivate(); + + QString name; + QmlDebugServer *server; +}; + +QmlDebugServerPrivate::QmlDebugServerPrivate() +: connection(0), protocol(0) +{ +} + +void QmlDebugServerPrivate::init(int port) +{ + Q_Q(QmlDebugServer); + QTcpServer server; + + if (!server.listen(QHostAddress::Any, port)) { + qWarning("QmlDebugServer: Unable to listen on port %d", port); + return; + } + + qWarning("QmlDebugServer: Waiting for connection on port %d...", port); + + if (!server.waitForNewConnection(-1)) { + qWarning("QmlDebugServer: Connection error"); + return; + } + + connection = server.nextPendingConnection(); + connection->setParent(q); + protocol = new QPacketProtocol(connection, q); + + // ### Wait for hello + while (!protocol->packetsAvailable()) { + connection->waitForReadyRead(); + } + QPacket hello = protocol->read(); + QString name; + hello >> name >> enabledPlugins; + if (name != QLatin1String("QmlDebugServer")) { + qWarning("QmlDebugServer: Invalid hello message"); + delete protocol; delete connection; connection = 0; protocol = 0; + return; + } + + QObject::connect(protocol, SIGNAL(readyRead()), q, SLOT(readyRead())); + q->readyRead(); + + qWarning("QmlDebugServer: Connection established"); +} + +QmlDebugServer *QmlDebugServer::instance() +{ + static bool envTested = false; + static QmlDebugServer *server = 0; + + if (!envTested) { + envTested = true; + QByteArray env = qgetenv("QML_DEBUG_SERVER_PORT"); + + bool ok = false; + int port = env.toInt(&ok); + + if (ok && port > 1024) + server = new QmlDebugServer(port); + } + + if (server && server->d_func()->connection) + return server; + else + return 0; +} + +QmlDebugServer::QmlDebugServer(int port) +: QObject(*(new QmlDebugServerPrivate)) +{ + Q_D(QmlDebugServer); + d->init(port); +} + +void QmlDebugServer::readyRead() +{ + Q_D(QmlDebugServer); + + QString debugServer(QLatin1String("QmlDebugServer")); + + while (d->protocol->packetsAvailable()) { + QPacket pack = d->protocol->read(); + + QString name; + pack >> name; + + if (name == debugServer) { + int op = -1; QString plugin; + pack >> op >> plugin; + + if (op == 1) { + // Enable + if (!d->enabledPlugins.contains(plugin)) { + d->enabledPlugins.append(plugin); + QHash::Iterator iter = + d->plugins.find(plugin); + if (iter != d->plugins.end()) + (*iter)->enabledChanged(true); + } + + } else if (op == 2) { + // Disable + if (d->enabledPlugins.contains(plugin)) { + d->enabledPlugins.removeAll(plugin); + QHash::Iterator iter = + d->plugins.find(plugin); + if (iter != d->plugins.end()) + (*iter)->enabledChanged(false); + } + } else { + qWarning("QmlDebugServer: Invalid control message %d", op); + } + + } else { + QByteArray message; + pack >> message; + + QHash::Iterator iter = + d->plugins.find(name); + if (iter == d->plugins.end()) { + qWarning() << "QmlDebugServer: Message received for missing plugin" << name; + } else { + (*iter)->messageReceived(message); + } + } + } +} + +QmlDebugServerPluginPrivate::QmlDebugServerPluginPrivate() +: server(0) +{ +} + +QmlDebugServerPlugin::QmlDebugServerPlugin(const QString &name, QObject *parent) +: QObject(*(new QmlDebugServerPluginPrivate), parent) +{ + Q_D(QmlDebugServerPlugin); + d->name = name; + d->server = QmlDebugServer::instance(); + + if (!d->server) + return; + + if (d->server->d_func()->plugins.contains(name)) { + qWarning() << "QmlDebugServerPlugin: Conflicting plugin name" << name; + d->server = 0; + } else { + d->server->d_func()->plugins.insert(name, this); + } +} + +QString QmlDebugServerPlugin::name() const +{ + Q_D(const QmlDebugServerPlugin); + return d->name; +} + +bool QmlDebugServerPlugin::isEnabled() const +{ + Q_D(const QmlDebugServerPlugin); + return (d->server && d->server->d_func()->enabledPlugins.contains(d->name)); +} + +bool QmlDebugServerPlugin::isDebuggingEnabled() +{ + return QmlDebugServer::instance() != 0; +} + +void QmlDebugServerPlugin::sendMessage(const QByteArray &message) +{ + Q_D(QmlDebugServerPlugin); + + if (!d->server || !d->server->d_func()->connection) + return; + + QPacket pack; + pack << d->name << message; + d->server->d_func()->protocol->send(pack); +} + +void QmlDebugServerPlugin::enabledChanged(bool) +{ +} + +void QmlDebugServerPlugin::messageReceived(const QByteArray &) +{ +} + +#include "qmldebugserver.moc" + +QT_END_NAMESPACE diff --git a/src/declarative/debugger/qmldebugserver.h b/src/declarative/debugger/qmldebugserver.h new file mode 100644 index 0000000..8ee2cfb --- /dev/null +++ b/src/declarative/debugger/qmldebugserver.h @@ -0,0 +1,81 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLDEBUGSERVER_H +#define QMLDEBUGSERVER_H + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +class QmlDebugServerPluginPrivate; +class QmlDebugServerPlugin : public QObject +{ + Q_OBJECT + Q_DECLARE_PRIVATE(QmlDebugServerPlugin) + Q_DISABLE_COPY(QmlDebugServerPlugin) +public: + QmlDebugServerPlugin(const QString &, QObject *parent = 0); + + QString name() const; + + bool isEnabled() const; + + void sendMessage(const QByteArray &); + + static bool isDebuggingEnabled(); + +protected: + virtual void enabledChanged(bool); + virtual void messageReceived(const QByteArray &); + +private: + friend class QmlDebugServer; +}; + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QMLDEBUGSERVER_H + diff --git a/src/declarative/debugger/qpacketprotocol.cpp b/src/declarative/debugger/qpacketprotocol.cpp new file mode 100644 index 0000000..6911b89 --- /dev/null +++ b/src/declarative/debugger/qpacketprotocol.cpp @@ -0,0 +1,462 @@ +/**************************************************************************** +** +** This file is part of the $PACKAGE_NAME$. +** +** Copyright (C) $THISYEAR$ $COMPANY_NAME$. +** +** $QT_EXTENDED_DUAL_LICENSE$ +** +****************************************************************************/ + +#include "qpacketprotocol.h" +#include + +#define MAX_PACKET_SIZE 0x7FFFFFFF + +/*! + \class QPacketProtocol + + \brief The QPacketProtocol class encapsulates communicating discrete packets + across fragmented IO channels, such as TCP sockets. + + QPacketProtocol makes it simple to send arbitrary sized data "packets" across + fragmented transports such as TCP and UDP. + + As transmission boundaries are not respected, sending packets over protocols + like TCP frequently involves "stitching" them back together at the receiver. + QPacketProtocol makes this easier by performing this task for you. Packet + data sent using QPacketProtocol is prepended with a 4-byte size header + allowing the receiving QPacketProtocol to buffer the packet internally until + it has all been received. QPacketProtocol does not perform any sanity + checking on the size or on the data, so this class should only be used in + prototyping or trusted situations where DOS attacks are unlikely. + + QPacketProtocol does not perform any communications itself. Instead it can + operate on any QIODevice that supports the QIODevice::readyRead() signal. A + logical "packet" is encapsulated by the companion QPacket class. The + following example shows two ways to send data using QPacketProtocol. The + transmitted data is equivalent in both. + + \code + QTcpSocket socket; + // ... connect socket ... + + QPacketProtocol protocol(&socket); + + // Send packet the quick way + protocol.send() << "Hello world" << 123; + + // Send packet the longer way + QPacket packet; + packet << "Hello world" << 123; + protocol.send(packet); + \endcode + + Likewise, the following shows how to read data from QPacketProtocol, assuming + that the QPacketProtocol::readyRead() signal has been emitted. + + \code + // ... QPacketProtocol::readyRead() is emitted ... + + int a; + QByteArray b; + + // Receive packet the quick way + protocol.read() >> a >> b; + + // Receive packet the longer way + QPacket packet = protocol.read(); + p >> a >> b; + \endcode + + \ingroup io + \sa QPacket +*/ + +class QPacketProtocolPrivate : public QObject +{ +Q_OBJECT +public: + QPacketProtocolPrivate(QPacketProtocol * parent, QIODevice * _dev) + : QObject(parent), inProgressSize(-1), maxPacketSize(MAX_PACKET_SIZE), + dev(_dev) + { + Q_ASSERT(4 == sizeof(qint32)); + + QObject::connect(this, SIGNAL(readyRead()), + parent, SIGNAL(readyRead())); + QObject::connect(this, SIGNAL(packetWritten()), + parent, SIGNAL(packetWritten())); + QObject::connect(this, SIGNAL(invalidPacket()), + parent, SIGNAL(invalidPacket())); + QObject::connect(dev, SIGNAL(readyRead()), + this, SLOT(readyToRead())); + QObject::connect(dev, SIGNAL(aboutToClose()), + this, SLOT(aboutToClose())); + QObject::connect(dev, SIGNAL(bytesWritten(qint64)), + this, SLOT(bytesWritten(qint64))); + } + +signals: + void readyRead(); + void packetWritten(); + void invalidPacket(); + +public slots: + void aboutToClose() + { + inProgress.clear(); + sendingPackets.clear(); + inProgressSize = -1; + } + + void bytesWritten(qint64 bytes) + { + Q_ASSERT(!sendingPackets.isEmpty()); + + while(bytes) { + if(sendingPackets.at(0) > bytes) { + sendingPackets[0] -= bytes; + bytes = 0; + } else { + bytes -= sendingPackets.at(0); + sendingPackets.removeFirst(); + emit packetWritten(); + } + } + } + + void readyToRead() + { + if(-1 == inProgressSize) { + // We need a size header of sizeof(qint32) + if(sizeof(qint32) > dev->bytesAvailable()) + return; + + // Read size header + int read = dev->read((char *)&inProgressSize, sizeof(qint32)); + Q_ASSERT(read == sizeof(qint32)); + Q_UNUSED(read); + + // Check sizing constraints + if(inProgressSize > maxPacketSize) { + QObject::disconnect(dev, SIGNAL(readyRead()), + this, SLOT(readyToRead())); + QObject::disconnect(dev, SIGNAL(aboutToClose()), + this, SLOT(aboutToClose())); + QObject::disconnect(dev, SIGNAL(bytesWritten(qint64)), + this, SLOT(bytesWritten(qint64))); + dev = 0; + emit invalidPacket(); + return; + } + + inProgressSize -= sizeof(qint32); + + // Need to get trailing data + readyToRead(); + } else { + inProgress.append(dev->read(inProgressSize - inProgress.size())); + + if(inProgressSize == inProgress.size()) { + // Packet has arrived! + packets.append(inProgress); + inProgressSize = -1; + inProgress.clear(); + + emit readyRead(); + + // Need to get trailing data + readyToRead(); + } + } + } + +public: + QList sendingPackets; + QList packets; + QByteArray inProgress; + qint32 inProgressSize; + qint32 maxPacketSize; + QIODevice * dev; +}; + +/*! + Construct a QPacketProtocol instance that works on \a dev with the + specified \a parent. + */ +QPacketProtocol::QPacketProtocol(QIODevice * dev, QObject * parent) +: QObject(parent), d(new QPacketProtocolPrivate(this, dev)) +{ + Q_ASSERT(dev); +} + +/*! + Destroys the QPacketProtocol instance. + */ +QPacketProtocol::~QPacketProtocol() +{ +} + +/*! + Returns the maximum packet size allowed. By default this is + 2,147,483,647 bytes. + + If a packet claiming to be larger than the maximum packet size is received, + the QPacketProtocol::invalidPacket() signal is emitted. + + \sa QPacketProtocol::setMaximumPacketSize() + */ +qint32 QPacketProtocol::maximumPacketSize() const +{ + return d->maxPacketSize; +} + +/*! + Sets the maximum allowable packet size to \a max. + + \sa QPacketProtocol::maximumPacketSize() + */ +qint32 QPacketProtocol::setMaximumPacketSize(qint32 max) +{ + if(max > (signed)sizeof(qint32)) + d->maxPacketSize = max; + return d->maxPacketSize; +} + +/*! + Returns a streamable object that is transmitted on destruction. For example + + \code + protocol.send() << "Hello world" << 123; + \endcode + + will send a packet containing "Hello world" and 123. To construct more + complex packets, explicitly construct a QPacket instance. + */ +QPacketAutoSend QPacketProtocol::send() +{ + return QPacketAutoSend(this); +} + +/*! + \fn void QPacketProtocol::send(const QPacket & packet) + + Transmit the \a packet. + */ +void QPacketProtocol::send(const QPacket & p) +{ + if(p.b.isEmpty()) + return; // We don't send empty packets + + qint64 sendSize = p.b.size() + sizeof(qint32); + + d->sendingPackets.append(sendSize); + qint32 sendSize32 = sendSize; + qint64 writeBytes = d->dev->write((char *)&sendSize32, sizeof(qint32)); + Q_ASSERT(writeBytes == sizeof(qint32)); + writeBytes = d->dev->write(p.b); + Q_ASSERT(writeBytes == p.b.size()); +} + +/*! + Returns the number of received packets yet to be read. + */ +qint64 QPacketProtocol::packetsAvailable() const +{ + return d->packets.count(); +} + +/*! + Discard any unread packets. + */ +void QPacketProtocol::clear() +{ + d->packets.clear(); +} + +/*! + Return the next unread packet, or an invalid QPacket instance if no packets + are available. This method does NOT block. + */ +QPacket QPacketProtocol::read() +{ + if(0 == d->packets.count()) + return QPacket(); + + QPacket rv(d->packets.at(0)); + d->packets.removeFirst(); + return rv; +} + +/*! + Return the QIODevice passed to the QPacketProtocol constructor. +*/ +QIODevice * QPacketProtocol::device() +{ + return d->dev; +} + +/*! + \fn void QPacketProtocol::readyRead() + + Emitted whenever a new packet is received. Applications may use + QPacketProtocol::read() to retrieve this packet. + */ + +/*! + \fn void QPacketProtocol::invalidPacket() + + A packet larger than the maximum allowable packet size was received. The + packet will be discarded and, as it indicates corruption in the protocol, no + further packets will be received. + */ + +/*! + \fn void QPacketProtocol::packetWritten() + + Emitted each time a packet is completing written to the device. This signal + may be used for communications flow control. + */ + +/*! + \class QPacket + \inpublicgroup QtBaseModule + + \brief The QPacket class encapsulates an unfragmentable packet of data to be + transmitted by QPacketProtocol. + + The QPacket class works together with QPacketProtocol to make it simple to + send arbitrary sized data "packets" across fragmented transports such as TCP + and UDP. + + QPacket provides a QDataStream interface to an unfragmentable packet. + Applications should construct a QPacket, propagate it with data and then + transmit it over a QPacketProtocol instance. For example: + \code + QPacketProtocol protocol(...); + + QPacket myPacket; + myPacket << "Hello world!" << 123; + protocol.send(myPacket); + \endcode + + As long as both ends of the connection are using the QPacketProtocol class, + the data within this packet will be delivered unfragmented at the other end, + ready for extraction. + + \code + QByteArray greeting; + int count; + + QPacket myPacket = protocol.read(); + + myPacket >> greeting >> count; + \endcode + + Only packets returned from QPacketProtocol::read() may be read from. QPacket + instances constructed by directly by applications are for transmission only + and are considered "write only". Attempting to read data from them will + result in undefined behaviour. + + \ingroup io + \sa QPacketProtocol + */ + +/*! + Constructs an empty write-only packet. + */ +QPacket::QPacket() +: QDataStream(), buf(0) +{ + buf = new QBuffer(&b); + buf->open(QIODevice::WriteOnly); + setDevice(buf); +} + +/*! + Destroys the QPacket instance. + */ +QPacket::~QPacket() +{ + if(buf) { + delete buf; + buf = 0; + } +} + +/*! + Creates a copy of \a other. The initial stream positions are shared, but the + two packets are otherwise independant. + */ +QPacket::QPacket(const QPacket & other) +: QDataStream(), b(other.b), buf(0) +{ + buf = new QBuffer(&b); + buf->open(other.buf->openMode()); + setDevice(buf); +} + +/*! + \internal + */ +QPacket::QPacket(const QByteArray & ba) +: QDataStream(), b(ba), buf(0) +{ + buf = new QBuffer(&b); + buf->open(QIODevice::ReadOnly); + setDevice(buf); +} + +/*! + Returns true if this packet is empty - that is, contains no data. + */ +bool QPacket::isEmpty() const +{ + return b.isEmpty(); +} + +/*! + Clears data in the packet. This is useful for reusing one writable packet. + For example + \code + QPacketProtocol protocol(...); + + QPacket packet; + + packet << "Hello world!" << 123; + protocol.send(packet); + + packet.clear(); + packet << "Goodbyte world!" << 789; + protocol.send(packet); + \endcode + */ +void QPacket::clear() +{ + QBuffer::OpenMode oldMode = buf->openMode(); + buf->close(); + b.clear(); + buf->setBuffer(&b); // reset QBuffer internals with new size of b. + buf->open(oldMode); +} + +/*! + \class QPacketAutoSend + \inpublicgroup QtBaseModule + + \internal + */ +QPacketAutoSend::QPacketAutoSend(QPacketProtocol * _p) +: QPacket(), p(_p) +{ +} + +QPacketAutoSend::~QPacketAutoSend() +{ + if(!b.isEmpty()) + p->send(*this); +} + +#include "qpacketprotocol.moc" + diff --git a/src/declarative/debugger/qpacketprotocol.h b/src/declarative/debugger/qpacketprotocol.h new file mode 100644 index 0000000..6dd8bda --- /dev/null +++ b/src/declarative/debugger/qpacketprotocol.h @@ -0,0 +1,81 @@ +/**************************************************************************** +** +** This file is part of the $PACKAGE_NAME$. +** +** Copyright (C) $THISYEAR$ $COMPANY_NAME$. +** +** $QT_EXTENDED_DUAL_LICENSE$ +** +****************************************************************************/ + +#ifndef QPACKETPROTOCOL_H +#define QPACKETPROTOCOL_H + +#include +#include + +class QIODevice; +class QBuffer; +class QPacket; +class QPacketAutoSend; +class QPacketProtocolPrivate; + +class Q_DECLARATIVE_EXPORT QPacketProtocol : public QObject +{ +Q_OBJECT +public: + explicit QPacketProtocol(QIODevice * dev, QObject * parent = 0); + virtual ~QPacketProtocol(); + + qint32 maximumPacketSize() const; + qint32 setMaximumPacketSize(qint32); + + QPacketAutoSend send(); + void send(const QPacket &); + + qint64 packetsAvailable() const; + QPacket read(); + + void clear(); + + QIODevice * device(); + +signals: + void readyRead(); + void invalidPacket(); + void packetWritten(); + +private: + QPacketProtocolPrivate * d; +}; + + +class Q_DECLARATIVE_EXPORT QPacket : public QDataStream +{ +public: + QPacket(); + QPacket(const QPacket &); + virtual ~QPacket(); + + void clear(); + bool isEmpty() const; + +protected: + friend class QPacketProtocol; + QPacket(const QByteArray & ba); + QByteArray b; + QBuffer * buf; +}; + +class Q_DECLARATIVE_EXPORT QPacketAutoSend : public QPacket +{ +public: + virtual ~QPacketAutoSend(); + +private: + friend class QPacketProtocol; + QPacketAutoSend(QPacketProtocol *); + QPacketProtocol * p; +}; + +#endif diff --git a/tools/qmldebugger/canvasframerate.cpp b/tools/qmldebugger/canvasframerate.cpp new file mode 100644 index 0000000..b1f412e --- /dev/null +++ b/tools/qmldebugger/canvasframerate.cpp @@ -0,0 +1,305 @@ +#include "canvasframerate.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class QLineGraph : public QWidget +{ +Q_OBJECT +public: + QLineGraph(QWidget * = 0); + + void setPosition(int); + +public slots: + void addSample(int, int, int, int, bool); + +protected: + virtual void paintEvent(QPaintEvent *); + virtual void mousePressEvent(QMouseEvent *); + virtual void resizeEvent(QResizeEvent *); + virtual void showEvent(QShowEvent *); + +private slots: + void scrollbarChanged(int); + +private: + void updateScrollbar(); + void drawSample(QPainter *, int, const QRect &); + void drawTime(QPainter *, const QRect &); + struct Sample { + int sample[4]; + bool isBreak; + }; + QList _samples; + + QScrollBar sb; + int position; + int samplesPerWidth; + int resolutionForHeight; + bool ignoreScroll; +}; + +QLineGraph::QLineGraph(QWidget *parent) +: QWidget(parent), sb(Qt::Horizontal, this), position(-1), samplesPerWidth(99), resolutionForHeight(50), ignoreScroll(false) +{ + sb.setMaximum(0); + sb.setMinimum(0); + sb.setSingleStep(1); + + QVBoxLayout *layout = new QVBoxLayout; + setLayout(layout); + layout->addStretch(2); + layout->addWidget(&sb); + QObject::connect(&sb, SIGNAL(valueChanged(int)), this, SLOT(scrollbarChanged(int))); +} + +void QLineGraph::scrollbarChanged(int v) +{ + if(ignoreScroll) + return; + + position = v; + update(); +} + +void QLineGraph::resizeEvent(QResizeEvent *e) +{ + QWidget::resizeEvent(e); +} + +void QLineGraph::showEvent(QShowEvent *e) +{ + QWidget::showEvent(e); +} + +void QLineGraph::mousePressEvent(QMouseEvent *) +{ + if(position == -1) { + position = qMax(0, _samples.count() - samplesPerWidth - 1); + } else { + position = -1; + } + update(); +} + +void QLineGraph::updateScrollbar() +{ + ignoreScroll = true; + sb.setMaximum(qMax(0, _samples.count() - samplesPerWidth - 1)); + + if(position == -1) { + sb.setValue(sb.maximum()); + } else { + sb.setValue(position); + } + ignoreScroll = false; +} + +void QLineGraph::addSample(int a, int b, int c, int d, bool isBreak) +{ + Sample s; + s.isBreak = isBreak; + s.sample[0] = a; + s.sample[1] = b; + s.sample[2] = c; + s.sample[3] = d; + _samples << s; + updateScrollbar(); + update(); +} + +void QLineGraph::setPosition(int p) +{ + scrollbarChanged(p); +} + +void QLineGraph::drawTime(QPainter *p, const QRect &rect) +{ + if(_samples.isEmpty()) + return; + + int first = position; + if(first == -1) + first = qMax(0, _samples.count() - samplesPerWidth - 1); + int last = qMin(_samples.count() - 1, first + samplesPerWidth); + + qreal scaleX = qreal(rect.width()) / qreal(samplesPerWidth); + + int t = 0; + + for(int ii = first; ii <= last; ++ii) { + int sampleTime = _samples.at(ii).sample[3] / 1000; + if(sampleTime != t) { + + int xEnd = rect.left() + scaleX * (ii - first); + p->drawLine(xEnd, rect.bottom(), xEnd, rect.bottom() + 7); + + QRect text(xEnd - 30, rect.bottom() + 10, 60, 30); + + p->drawText(text, Qt::AlignHCenter | Qt::AlignTop, QString::number(_samples.at(ii).sample[3])); + + t = sampleTime; + } + } + +} + +void QLineGraph::drawSample(QPainter *p, int s, const QRect &rect) +{ + if(_samples.isEmpty()) + return; + + int first = position; + if(first == -1) + first = qMax(0, _samples.count() - samplesPerWidth - 1); + int last = qMin(_samples.count() - 1, first + samplesPerWidth); + + qreal scaleY = rect.height() / resolutionForHeight; + qreal scaleX = qreal(rect.width()) / qreal(samplesPerWidth); + + int xEnd; + int lastXEnd = rect.left(); + + p->save(); + p->setPen(Qt::NoPen); + for(int ii = first + 1; ii <= last; ++ii) { + + xEnd = rect.left() + scaleX * (ii - first); + int yEnd = rect.bottom() - _samples.at(ii).sample[s] * scaleY; + + if (!(s == 0 && _samples.at(ii).isBreak)) + p->drawRect(QRect(lastXEnd, yEnd, scaleX, _samples.at(ii).sample[s] * scaleY)); + + lastXEnd = xEnd; + } + p->restore(); +} + +void QLineGraph::paintEvent(QPaintEvent *) +{ + QPainter p(this); + p.setRenderHint(QPainter::Antialiasing); + + + QRect r(50, 10, width() - 60, height() - 60); + p.setBrush(QColor("lightsteelblue")); + drawSample(&p, 0, r); + + p.setBrush(QColor("pink")); + drawSample(&p, 1, r); + + p.setBrush(QColor("green")); + drawSample(&p, 2, r); + + p.setBrush(Qt::NoBrush); + p.drawRect(r); + + for(int ii = 0; ii <= resolutionForHeight; ++ii) { + int y = 1 + r.bottom() - ii * r.height() / resolutionForHeight; + + if((ii % 10) == 0) { + p.drawLine(r.left() - 20, y, r.left(), y); + QRect text(r.left() - 20 - 53, y - 10, 50, 20); + p.drawText(text, Qt::AlignRight | Qt::AlignVCenter, QString::number(ii)); + } else { + p.drawLine(r.left() - 7, y, r.left(), y); + } + } + + drawTime(&p, r); +} + +class CanvasFrameRatePlugin : public QmlDebugClientPlugin +{ +Q_OBJECT +public: + CanvasFrameRatePlugin(QmlDebugClient *client); + +signals: + void sample(int, int, int, int, bool); + +protected: + virtual void messageReceived(const QByteArray &); + +private: + int la; + int lb; + int ld; +}; + +CanvasFrameRatePlugin::CanvasFrameRatePlugin(QmlDebugClient *client) +: QmlDebugClientPlugin(QLatin1String("CanvasFrameRate"), client), la(-1) +{ +} + +void CanvasFrameRatePlugin::messageReceived(const QByteArray &data) +{ + QByteArray rwData = data; + QDataStream stream(&rwData, QIODevice::ReadOnly); + + int a; int b; int c; int d; bool isBreak; + stream >> a >> b >> c >> d >> isBreak; + + if (la != -1) + emit sample(c, lb, la, ld, isBreak); + + la = a; + lb = b; + ld = d; +} + +CanvasFrameRate::CanvasFrameRate(QmlDebugClient *client, QWidget *parent) +: QWidget(parent) +{ + m_plugin = new CanvasFrameRatePlugin(client); + + QVBoxLayout *layout = new QVBoxLayout; + layout->setContentsMargins(0,0,0,0); + layout->setSpacing(0); + setLayout(layout); + + m_tabs = new QTabWidget(this); + layout->addWidget(m_tabs); + + QHBoxLayout *bottom = new QHBoxLayout; + layout->addLayout(bottom); + bottom->addStretch(2); + + QPushButton *pb = new QPushButton(tr("New Tab"), this); + QObject::connect(pb, SIGNAL(clicked()), this, SLOT(newTab())); + bottom->addWidget(pb); + + newTab(); +} + +void CanvasFrameRate::newTab() +{ + if (m_tabs->count()) { + QWidget *w = m_tabs->widget(m_tabs->count() - 1); + QObject::disconnect(m_plugin, SIGNAL(sample(int,int,int,int,bool)), + w, SLOT(addSample(int,int,int,int,bool))); + } + + int id = m_tabs->count(); + + QLineGraph *graph = new QLineGraph(this); + QObject::connect(m_plugin, SIGNAL(sample(int,int,int,int,bool)), + graph, SLOT(addSample(int,int,int,int,bool))); + + QString name = QLatin1String("Graph ") + QString::number(id); + m_tabs->addTab(graph, name); + m_tabs->setCurrentIndex(id); +} + +#include "canvasframerate.moc" diff --git a/tools/qmldebugger/canvasframerate.h b/tools/qmldebugger/canvasframerate.h new file mode 100644 index 0000000..c3e88ef --- /dev/null +++ b/tools/qmldebugger/canvasframerate.h @@ -0,0 +1,23 @@ +#ifndef CANVASFRAMERATE_H +#define CANVASFRAMERATE_H + +#include + +class QmlDebugClient; +class QTabWidget; +class CanvasFrameRate : public QWidget +{ + Q_OBJECT +public: + CanvasFrameRate(QmlDebugClient *, QWidget *parent = 0); + +private slots: + void newTab(); + +private: + QTabWidget *m_tabs; + QObject *m_plugin; +}; + +#endif // CANVASFRAMERATE_H + diff --git a/tools/qmldebugger/main.cpp b/tools/qmldebugger/main.cpp new file mode 100644 index 0000000..2c5be6c --- /dev/null +++ b/tools/qmldebugger/main.cpp @@ -0,0 +1,103 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "canvasframerate.h" +#include +#include +#include +#include +#include + +class Shell : public QWidget +{ +Q_OBJECT +public: + Shell(QWidget * = 0); + +private slots: + void connectToHost(); + void disconnectFromHost(); + +private: + QmlDebugClient client; + + QLineEdit *m_host; + QSpinBox *m_port; + QPushButton *m_connectButton; + QPushButton *m_disconnectButton; +}; + +Shell::Shell(QWidget *parent) +: QWidget(parent) +{ + QVBoxLayout *layout = new QVBoxLayout; + setLayout(layout); + + + QHBoxLayout *connectLayout = new QHBoxLayout; + layout->addLayout(connectLayout); + connectLayout->addStretch(2); + + m_host = new QLineEdit(this); + m_host->setText("localhost"); + connectLayout->addWidget(m_host); + m_port = new QSpinBox(this); + m_port->setMinimum(1024); + m_port->setMaximum(20000); + m_port->setValue(3768); + connectLayout->addWidget(m_port); + m_connectButton = new QPushButton(tr("Connect"), this); + QObject::connect(m_connectButton, SIGNAL(clicked()), + this, SLOT(connectToHost())); + connectLayout->addWidget(m_connectButton); + m_disconnectButton = new QPushButton(tr("Disconnect"), this); + QObject::connect(m_disconnectButton, SIGNAL(clicked()), + this, SLOT(disconnectFromHost())); + m_disconnectButton->setEnabled(false); + connectLayout->addWidget(m_disconnectButton); + + QTabWidget *tabs = new QTabWidget(this); + layout->addWidget(tabs); + + CanvasFrameRate *cfr = new CanvasFrameRate(&client, this); + tabs->addTab(cfr, tr("Frame Rate")); +} + +void Shell::connectToHost() +{ + m_connectButton->setEnabled(false); + m_disconnectButton->setEnabled(true); + client.connectToHost(m_host->text(), m_port->value()); +} + +void Shell::disconnectFromHost() +{ + m_connectButton->setEnabled(true); + m_disconnectButton->setEnabled(false); + client.disconnectFromHost(); +} + +int main(int argc, char ** argv) +{ + if(argc != 3) { + qWarning() << "Usage:" << argv[0] << "host port"; + return -1; + } + + QApplication app(argc, argv); + + Shell shell; +// shell.setFixedSize(1024, 768); + shell.show(); + + + return app.exec(); +} + +#include "main.moc" diff --git a/tools/qmldebugger/qmldebugger.pro b/tools/qmldebugger/qmldebugger.pro new file mode 100644 index 0000000..6af2909 --- /dev/null +++ b/tools/qmldebugger/qmldebugger.pro @@ -0,0 +1,10 @@ +DESTDIR = ../../bin +QT += network declarative +# Input +HEADERS += canvasframerate.h +SOURCES += main.cpp canvasframerate.cpp + +target.path=$$[QT_INSTALL_BINS] +INSTALLS += target + +CONFIG += console -- cgit v0.12 From 30ed4ee8cee66bcf3ddf001118ba4905a8bfe644 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 25 May 2009 11:24:40 +0200 Subject: Fixed 'crazy' warnings about using a string instead of a character Wherever I found that we were using a string instead of a single char I fixed the code. Reviewed-by: olivier --- src/corelib/global/qglobal.cpp | 4 ++-- src/corelib/io/qdebug.h | 28 +++++++++++++-------------- src/corelib/io/qdir.cpp | 10 +++++----- src/corelib/io/qfsfileengine_win.cpp | 12 +++++------- src/corelib/io/qiodevice.cpp | 2 +- src/corelib/io/qprocess.cpp | 2 +- src/corelib/io/qprocess_win.cpp | 20 +++++++++---------- src/corelib/io/qresource.cpp | 8 ++++---- src/corelib/io/qsettings_win.cpp | 2 +- src/corelib/io/qtemporaryfile.cpp | 2 +- src/corelib/io/qtextstream.cpp | 2 +- src/corelib/io/qurl.cpp | 6 +++--- src/corelib/io/qurl.h | 2 +- src/corelib/kernel/qabstractitemmodel.cpp | 12 ++++++------ src/corelib/kernel/qcoreapplication.cpp | 4 ++-- src/corelib/kernel/qcoreapplication_win.cpp | 4 ++-- src/corelib/kernel/qobject.cpp | 2 +- src/corelib/statemachine/qstatemachine.cpp | 24 +++++++++++------------ src/corelib/tools/qdatetime.cpp | 6 +++--- src/corelib/tools/qline.cpp | 4 ++-- src/corelib/tools/qlocale.cpp | 4 ++-- src/corelib/tools/qpoint.cpp | 2 +- src/gui/dialogs/qfiledialog.cpp | 10 +++++----- src/gui/dialogs/qfiledialog_win.cpp | 18 ++++++++--------- src/gui/dialogs/qfilesystemmodel.cpp | 4 ++-- src/gui/dialogs/qmessagebox.cpp | 2 +- src/gui/dialogs/qprintpreviewdialog.cpp | 2 +- src/gui/graphicsview/qgraphicsitem.cpp | 6 +++--- src/gui/graphicsview/qgraphicsview.cpp | 2 +- src/gui/graphicsview/qgraphicswidget.cpp | 2 +- src/gui/graphicsview/qgridlayoutengine.cpp | 6 +++--- src/gui/image/qxpmhandler.cpp | 6 +++--- src/gui/itemviews/qdirmodel.cpp | 2 +- src/gui/itemviews/qfileiconprovider.cpp | 3 +-- src/gui/itemviews/qitemselectionmodel.cpp | 2 +- src/gui/itemviews/qtableview.cpp | 2 +- src/gui/kernel/qevent.cpp | 6 +++--- src/gui/kernel/qlayoutengine.cpp | 2 +- src/gui/kernel/qmime_win.cpp | 2 +- src/gui/kernel/qshortcutmap.cpp | 4 ++-- src/gui/kernel/qwidget.cpp | 4 ++-- src/gui/painting/qcolor.cpp | 6 +++--- src/gui/painting/qmatrix.cpp | 2 +- src/gui/painting/qpaintengine_raster.cpp | 4 ++-- src/gui/painting/qpaintengineex.cpp | 2 +- src/gui/painting/qpainterpath.cpp | 2 +- src/gui/painting/qpdf.cpp | 26 ++++++++++++------------- src/gui/painting/qpen.cpp | 2 +- src/gui/painting/qprintengine_pdf.cpp | 4 ++-- src/gui/painting/qprintengine_ps.cpp | 24 +++++++++++------------ src/gui/painting/qregion.cpp | 6 +++--- src/gui/painting/qtessellator.cpp | 12 ++++++------ src/gui/painting/qtransform.cpp | 2 +- src/gui/styles/qcleanlooksstyle.cpp | 6 +++--- src/gui/styles/qcommonstyle.cpp | 4 ++-- src/gui/styles/qplastiquestyle.cpp | 4 ++-- src/gui/styles/qstyle.cpp | 2 +- src/gui/styles/qstyleoption.cpp | 8 ++++---- src/gui/styles/qstylesheetstyle.cpp | 2 +- src/gui/text/qcssparser.cpp | 4 ++-- src/gui/text/qfontdatabase.cpp | 4 ++-- src/gui/text/qfontengine.cpp | 2 +- src/gui/text/qfontsubset.cpp | 30 ++++++++++++++--------------- src/gui/text/qtextcontrol.cpp | 2 +- src/gui/text/qtextdocument.cpp | 2 +- src/gui/text/qtextengine.cpp | 2 +- src/gui/util/qcompleter.cpp | 2 +- src/gui/util/qsystemtrayicon_win.cpp | 2 +- src/gui/widgets/qabstractspinbox.cpp | 4 ++-- src/gui/widgets/qcalendarwidget.cpp | 14 +++++++------- src/gui/widgets/qlabel.cpp | 2 +- src/gui/widgets/qlineedit.cpp | 2 +- src/gui/widgets/qspinbox.cpp | 6 +++--- 73 files changed, 220 insertions(+), 223 deletions(-) diff --git a/src/corelib/global/qglobal.cpp b/src/corelib/global/qglobal.cpp index ce98ec4..564e6a5 100644 --- a/src/corelib/global/qglobal.cpp +++ b/src/corelib/global/qglobal.cpp @@ -1985,7 +1985,7 @@ void qt_message_output(QtMsgType msgType, const char *buf) mac_default_handler(buf); #elif defined(Q_OS_WINCE) QString fstr = QString::fromLatin1(buf); - fstr += QLatin1String("\n"); + fstr += QLatin1Char('\n'); OutputDebugString(reinterpret_cast (fstr.utf16())); #else fprintf(stderr, "%s\n", buf); @@ -2243,7 +2243,7 @@ bool qputenv(const char *varName, const QByteArray& value) return _putenv_s(varName, value.constData()) == 0; #else QByteArray buffer(varName); - buffer += "="; + buffer += '='; buffer += value; return putenv(qstrdup(buffer.constData())) == 0; #endif diff --git a/src/corelib/io/qdebug.h b/src/corelib/io/qdebug.h index 9b0fbe5..54121f6 100644 --- a/src/corelib/io/qdebug.h +++ b/src/corelib/io/qdebug.h @@ -85,11 +85,11 @@ public: delete stream; } } - inline QDebug &space() { stream->space = true; stream->ts << " "; return *this; } + inline QDebug &space() { stream->space = true; stream->ts << ' '; return *this; } inline QDebug &nospace() { stream->space = false; return *this; } - inline QDebug &maybeSpace() { if (stream->space) stream->ts << " "; return *this; } + inline QDebug &maybeSpace() { if (stream->space) stream->ts << ' '; return *this; } - inline QDebug &operator<<(QChar t) { stream->ts << "\'" << t << "\'"; return maybeSpace(); } + inline QDebug &operator<<(QChar t) { stream->ts << '\'' << t << '\''; return maybeSpace(); } inline QDebug &operator<<(QBool t) { stream->ts << (bool(t) ? "true" : "false"); return maybeSpace(); } inline QDebug &operator<<(bool t) { stream->ts << (t ? "true" : "false"); return maybeSpace(); } inline QDebug &operator<<(char t) { stream->ts << t; return maybeSpace(); } @@ -106,10 +106,10 @@ public: inline QDebug &operator<<(float t) { stream->ts << t; return maybeSpace(); } inline QDebug &operator<<(double t) { stream->ts << t; return maybeSpace(); } inline QDebug &operator<<(const char* t) { stream->ts << QString::fromAscii(t); return maybeSpace(); } - inline QDebug &operator<<(const QString & t) { stream->ts << "\"" << t << "\""; return maybeSpace(); } + inline QDebug &operator<<(const QString & t) { stream->ts << '\"' << t << '\"'; return maybeSpace(); } inline QDebug &operator<<(const QStringRef & t) { return operator<<(t.toString()); } - inline QDebug &operator<<(const QLatin1String &t) { stream->ts << "\"" << t.latin1() << "\""; return maybeSpace(); } - inline QDebug &operator<<(const QByteArray & t) { stream->ts << "\"" << t << "\""; return maybeSpace(); } + inline QDebug &operator<<(const QLatin1String &t) { stream->ts << '\"' << t.latin1() << '\"'; return maybeSpace(); } + inline QDebug &operator<<(const QByteArray & t) { stream->ts << '\"' << t << '\"'; return maybeSpace(); } inline QDebug &operator<<(const void * t) { stream->ts << t; return maybeSpace(); } inline QDebug &operator<<(QTextStreamFunction f) { stream->ts << f; @@ -159,13 +159,13 @@ template inline QDebug operator<<(QDebug debug, const QList &list) #endif { - debug.nospace() << "("; + debug.nospace() << '('; for (Q_TYPENAME QList::size_type i = 0; i < list.count(); ++i) { if (i) debug << ", "; debug << list.at(i); } - debug << ")"; + debug << ')'; return debug.space(); } @@ -192,9 +192,9 @@ inline QDebug operator<<(QDebug debug, const QMap &map) debug.nospace() << "QMap("; for (typename QMap::const_iterator it = map.constBegin(); it != map.constEnd(); ++it) { - debug << "(" << it.key() << ", " << it.value() << ")"; + debug << '(' << it.key() << ", " << it.value() << ')'; } - debug << ")"; + debug << ')'; return debug.space(); } @@ -209,8 +209,8 @@ inline QDebug operator<<(QDebug debug, const QHash &hash) debug.nospace() << "QHash("; for (typename QHash::const_iterator it = hash.constBegin(); it != hash.constEnd(); ++it) - debug << "(" << it.key() << ", " << it.value() << ")"; - debug << ")"; + debug << '(' << it.key() << ", " << it.value() << ')'; + debug << ')'; return debug.space(); } @@ -222,7 +222,7 @@ template inline QDebug operator<<(QDebug debug, const QPair &pair) #endif { - debug.nospace() << "QPair(" << pair.first << "," << pair.second << ")"; + debug.nospace() << "QPair(" << pair.first << ',' << pair.second << ')'; return debug.space(); } @@ -247,7 +247,7 @@ inline QDebug operator<<(QDebug debug, const QContiguousCache &cache) if (i != cache.lastIndex()) debug << ", "; } - debug << ")"; + debug << ')'; return debug.space(); } diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp index 0dc8a63..7d330e6 100644 --- a/src/corelib/io/qdir.cpp +++ b/src/corelib/io/qdir.cpp @@ -2417,7 +2417,7 @@ QDebug operator<<(QDebug debug, QDir::Filters filters) if (filters & QDir::System) flags << QLatin1String("System"); if (filters & QDir::CaseSensitive) flags << QLatin1String("CaseSensitive"); } - debug << "QDir::Filters(" << qPrintable(flags.join(QLatin1String("|"))) << ")"; + debug << "QDir::Filters(" << qPrintable(flags.join(QLatin1String("|"))) << ')'; return debug; } @@ -2439,8 +2439,8 @@ QDebug operator<<(QDebug debug, QDir::SortFlags sorting) if (sorting & QDir::LocaleAware) flags << QLatin1String("LocaleAware"); if (sorting & QDir::Type) flags << QLatin1String("Type"); debug << "QDir::SortFlags(" << qPrintable(type) - << "|" - << qPrintable(flags.join(QLatin1String("|"))) << ")"; + << '|' + << qPrintable(flags.join(QLatin1String("|"))) << ')'; } return debug; } @@ -2452,9 +2452,9 @@ QDebug operator<<(QDebug debug, const QDir &dir) << qPrintable(dir.nameFilters().join(QLatin1String(","))) << "}, " << dir.sorting() - << "," + << ',' << dir.filter() - << ")"; + << ')'; return debug.space(); } diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp index 5d6cd06..aee9fde 100644 --- a/src/corelib/io/qfsfileengine_win.cpp +++ b/src/corelib/io/qfsfileengine_win.cpp @@ -433,7 +433,7 @@ static QString nativeAbsoluteFilePathW(const QString &path) if (retLen != 0) ret = QString::fromUtf16((unsigned short *)buf.data(), retLen); #else - if (path.startsWith(QLatin1String("/")) || path.startsWith(QLatin1String("\\"))) + if (path.startsWith(QLatin1Char('/')) || path.startsWith(QLatin1Char('\\'))) ret = QDir::toNativeSeparators(path); else ret = QDir::toNativeSeparators(QDir::cleanPath(qfsPrivateCurrentDir + QLatin1Char('/') + path)); @@ -1240,7 +1240,7 @@ QString QFSFileEngine::rootPath() QString ret = QString::fromLatin1(qgetenv("SystemDrive").constData()); if(ret.isEmpty()) ret = QLatin1String("c:"); - ret += QLatin1String("/"); + ret += QLatin1Char('/'); #elif defined(Q_OS_OS2EMX) char dir[4]; _abspath(dir, QLatin1String("/"), _MAX_PATH); @@ -1288,19 +1288,17 @@ QFileInfoList QFSFileEngine::drives() exit(1); driveBits &= 0x3ffffff; #endif - char driveName[4]; - - qstrcpy(driveName, "A:/"); + char driveName[] = "A:/"; while(driveBits) { if(driveBits & 1) - ret.append(QString::fromLatin1(driveName).toUpper()); + ret.append(QString::fromLatin1(driveName)); driveName[0]++; driveBits = driveBits >> 1; } return ret; #else - ret.append(QString::fromLatin1("/").toUpper()); + ret.append(QLatin1Char('/')); return ret; #endif } diff --git a/src/corelib/io/qiodevice.cpp b/src/corelib/io/qiodevice.cpp index 2ccc6ea..8924b77 100644 --- a/src/corelib/io/qiodevice.cpp +++ b/src/corelib/io/qiodevice.cpp @@ -1745,7 +1745,7 @@ QDebug operator<<(QDebug debug, QIODevice::OpenMode modes) } qSort(modeList); debug << modeList.join(QLatin1String("|")); - debug << ")"; + debug << ')'; return debug; } #endif diff --git a/src/corelib/io/qprocess.cpp b/src/corelib/io/qprocess.cpp index 30f4291..afeaad6 100644 --- a/src/corelib/io/qprocess.cpp +++ b/src/corelib/io/qprocess.cpp @@ -1586,7 +1586,7 @@ void QProcess::start(const QString &program, const QStringList &arguments, OpenM } #if defined QPROCESS_DEBUG - qDebug() << "QProcess::start(" << program << "," << arguments << "," << mode << ")"; + qDebug() << "QProcess::start(" << program << ',' << arguments << ',' << mode << ')'; #endif d->outputReadBuffer.clear(); diff --git a/src/corelib/io/qprocess_win.cpp b/src/corelib/io/qprocess_win.cpp index 5d862e5..179c3d0 100644 --- a/src/corelib/io/qprocess_win.cpp +++ b/src/corelib/io/qprocess_win.cpp @@ -272,12 +272,12 @@ static QString qt_create_commandline(const QString &program, const QStringList & QString args; if (!program.isEmpty()) { QString programName = program; - if (!programName.startsWith(QLatin1Char('\"')) && !programName.endsWith(QLatin1Char('\"')) && programName.contains(QLatin1String(" "))) - programName = QLatin1String("\"") + programName + QLatin1String("\""); - programName.replace(QLatin1String("/"), QLatin1String("\\")); + if (!programName.startsWith(QLatin1Char('\"')) && !programName.endsWith(QLatin1Char('\"')) && programName.contains(QLatin1Char(' '))) + programName = QLatin1Char('\"') + programName + QLatin1Char('\"'); + programName.replace(QLatin1Char('/'), QLatin1Char('\\')); // add the prgram as the first arg ... it works better - args = programName + QLatin1String(" "); + args = programName + QLatin1Char(' '); } for (int i=0; i0 && tmp.at(i-1) == QLatin1Char('\\')) { --i; - endQuote += QLatin1String("\\"); + endQuote += QLatin1Char('\\'); } args += QLatin1String(" \"") + tmp.left(i) + endQuote; } else { @@ -427,7 +427,7 @@ void QProcessPrivate::startProcess() QString fullPathProgram = program; if (!QDir::isAbsolutePath(fullPathProgram)) fullPathProgram = QFileInfo(fullPathProgram).absoluteFilePath(); - fullPathProgram.replace(QLatin1String("/"), QLatin1String("\\")); + fullPathProgram.replace(QLatin1Char('/'), QLatin1Char('\\')); success = CreateProcessW((WCHAR*)fullPathProgram.utf16(), (WCHAR*)args.utf16(), 0, 0, false, 0, 0, 0, 0, pid); @@ -887,8 +887,8 @@ bool QProcessPrivate::startDetached(const QString &program, const QStringList &a #if defined(Q_OS_WINCE) QString fullPathProgram = program; if (!QDir::isAbsolutePath(fullPathProgram)) - fullPathProgram.prepend(QDir::currentPath().append(QLatin1String("/"))); - fullPathProgram.replace(QLatin1String("/"), QLatin1String("\\")); + fullPathProgram.prepend(QDir::currentPath().append(QLatin1Char('/'))); + fullPathProgram.replace(QLatin1Char('/'), QLatin1Char('\\')); success = CreateProcessW((WCHAR*)fullPathProgram.utf16(), (WCHAR*)args.utf16(), 0, 0, false, CREATE_NEW_CONSOLE, 0, 0, 0, &pinfo); diff --git a/src/corelib/io/qresource.cpp b/src/corelib/io/qresource.cpp index 3b704f6..94dfd4d 100644 --- a/src/corelib/io/qresource.cpp +++ b/src/corelib/io/qresource.cpp @@ -623,14 +623,14 @@ int QResourceRoot::findNode(const QString &_path, const QLocale &locale) const QString root = mappingRoot(); if(!root.isEmpty()) { if(root == path) { - path = QLatin1String("/"); + path = QLatin1Char('/'); } else { - if(!root.endsWith(QLatin1String("/"))) - root += QLatin1String("/"); + if(!root.endsWith(QLatin1Char('/'))) + root += QLatin1Char('/'); if(path.size() >= root.size() && path.startsWith(root)) path = path.mid(root.length()-1); if(path.isEmpty()) - path = QLatin1String("/"); + path = QLatin1Char('/'); } } } diff --git a/src/corelib/io/qsettings_win.cpp b/src/corelib/io/qsettings_win.cpp index a08c969..57f65d6 100644 --- a/src/corelib/io/qsettings_win.cpp +++ b/src/corelib/io/qsettings_win.cpp @@ -148,7 +148,7 @@ static QString errorCodeToString(DWORD errorCode) if (data != 0) LocalFree(data); }) - if (result.endsWith(QLatin1String("\n"))) + if (result.endsWith(QLatin1Char('\n'))) result.truncate(result.length() - 1); return result; diff --git a/src/corelib/io/qtemporaryfile.cpp b/src/corelib/io/qtemporaryfile.cpp index b4d8a48..728bf4f 100644 --- a/src/corelib/io/qtemporaryfile.cpp +++ b/src/corelib/io/qtemporaryfile.cpp @@ -203,7 +203,7 @@ static int _gettemp(char *path, int *doopen, int domkdir, int slen) if (QDir::isAbsolutePath(QString::fromLatin1(path))) targetPath = QLatin1String(path); else - targetPath = QDir::currentPath().append(QLatin1String("/")) + QLatin1String(path); + targetPath = QDir::currentPath().append(QLatin1Char('/')) + QLatin1String(path); if ((*doopen = QT_OPEN(targetPath.toLocal8Bit(), O_CREAT|O_EXCL|O_RDWR diff --git a/src/corelib/io/qtextstream.cpp b/src/corelib/io/qtextstream.cpp index 612d7f7..4563e84 100644 --- a/src/corelib/io/qtextstream.cpp +++ b/src/corelib/io/qtextstream.cpp @@ -2292,7 +2292,7 @@ bool QTextStreamPrivate::putNumber(qulonglong number, bool negative) // ShowBase flag set zero should be written as '00' if (number == 0 && base == 8 && numberFlags & QTextStream::ShowBase && result == QLatin1String("0")) { - result.prepend(QLatin1String("0")); + result.prepend(QLatin1Char('0')); } } return putString(result, true); diff --git a/src/corelib/io/qurl.cpp b/src/corelib/io/qurl.cpp index d1a5cdd..94a53f1 100644 --- a/src/corelib/io/qurl.cpp +++ b/src/corelib/io/qurl.cpp @@ -5698,7 +5698,7 @@ QUrl QUrl::fromLocalFile(const QString &localFile) // magic for drives on windows if (deslashified.length() > 1 && deslashified.at(1) == QLatin1Char(':') && deslashified.at(0) != QLatin1Char('/')) { - url.setPath(QLatin1String("/") + deslashified); + url.setPath(QLatin1Char('/') + deslashified); // magic for shared drive on windows } else if (deslashified.startsWith(QLatin1String("//"))) { int indexOfPath = deslashified.indexOf(QLatin1Char('/'), 2); @@ -5728,7 +5728,7 @@ QString QUrl::toLocalFile() const // magic for shared drive on windows if (!d->host.isEmpty()) { tmp = QLatin1String("//") + d->host + (ourPath.length() > 0 && ourPath.at(0) != QLatin1Char('/') - ? QLatin1String("/") + ourPath : ourPath); + ? QLatin1Char('/') + ourPath : ourPath); } else { tmp = ourPath; // magic for drives on windows @@ -5976,7 +5976,7 @@ QDataStream &operator>>(QDataStream &in, QUrl &url) #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug d, const QUrl &url) { - d.maybeSpace() << "QUrl(" << url.toString() << ")"; + d.maybeSpace() << "QUrl(" << url.toString() << ')'; return d.space(); } #endif diff --git a/src/corelib/io/qurl.h b/src/corelib/io/qurl.h index 9242092..e9c4a8d 100644 --- a/src/corelib/io/qurl.h +++ b/src/corelib/io/qurl.h @@ -223,7 +223,7 @@ public: inline QT3_SUPPORT QString ref() const { return fragment(); } inline QT3_SUPPORT void setRef(const QString &txt) { setFragment(txt); } inline QT3_SUPPORT bool hasRef() const { return !fragment().isEmpty(); } - inline QT3_SUPPORT void addPath(const QString &p) { setPath(path() + QLatin1String("/") + p); } + inline QT3_SUPPORT void addPath(const QString &p) { setPath(path() + QLatin1Char('/') + p); } QT3_SUPPORT void setFileName(const QString &txt); QT3_SUPPORT QString fileName() const; QT3_SUPPORT QString dirPath() const; diff --git a/src/corelib/kernel/qabstractitemmodel.cpp b/src/corelib/kernel/qabstractitemmodel.cpp index fd0e105..935c0aa 100644 --- a/src/corelib/kernel/qabstractitemmodel.cpp +++ b/src/corelib/kernel/qabstractitemmodel.cpp @@ -428,8 +428,8 @@ bool QPersistentModelIndex::isValid() const QDebug operator<<(QDebug dbg, const QModelIndex &idx) { #ifndef Q_BROKEN_DEBUG_STREAM - dbg.nospace() << "QModelIndex(" << idx.row() << "," << idx.column() - << "," << idx.internalPointer() << "," << idx.model() << ")"; + dbg.nospace() << "QModelIndex(" << idx.row() << ',' << idx.column() + << ',' << idx.internalPointer() << ',' << idx.model() << ')'; return dbg.space(); #else qWarning("This compiler doesn't support streaming QModelIndex to QDebug"); @@ -525,7 +525,7 @@ void QAbstractItemModelPrivate::rowsInserted(const QModelIndex &parent, if (data->index.isValid()) { persistent.insertMultiAtEnd(data->index, data); } else { - qWarning() << "QAbstractItemModel::endInsertRows: Invalid index (" << old.row() + count << "," << old.column() << ") in model" << q_func(); + qWarning() << "QAbstractItemModel::endInsertRows: Invalid index (" << old.row() + count << ',' << old.column() << ") in model" << q_func(); } } } @@ -574,7 +574,7 @@ void QAbstractItemModelPrivate::rowsRemoved(const QModelIndex &parent, if (data->index.isValid()) { persistent.insertMultiAtEnd(data->index, data); } else { - qWarning() << "QAbstractItemModel::endRemoveRows: Invalid index (" << old.row() - count << "," << old.column() << ") in model" << q_func(); + qWarning() << "QAbstractItemModel::endRemoveRows: Invalid index (" << old.row() - count << ',' << old.column() << ") in model" << q_func(); } } QVector persistent_invalidated = persistent.invalidated.pop(); @@ -619,7 +619,7 @@ void QAbstractItemModelPrivate::columnsInserted(const QModelIndex &parent, if (data->index.isValid()) { persistent.insertMultiAtEnd(data->index, data); } else { - qWarning() << "QAbstractItemModel::endInsertColumns: Invalid index (" << old.row() << "," << old.column() + count << ") in model" << q_func(); + qWarning() << "QAbstractItemModel::endInsertColumns: Invalid index (" << old.row() << ',' << old.column() + count << ") in model" << q_func(); } } } @@ -669,7 +669,7 @@ void QAbstractItemModelPrivate::columnsRemoved(const QModelIndex &parent, if (data->index.isValid()) { persistent.insertMultiAtEnd(data->index, data); } else { - qWarning() << "QAbstractItemModel::endRemoveColumns: Invalid index (" << old.row() << "," << old.column() - count << ") in model" << q_func(); + qWarning() << "QAbstractItemModel::endRemoveColumns: Invalid index (" << old.row() << ',' << old.column() - count << ") in model" << q_func(); } } QVector persistent_invalidated = persistent.invalidated.pop(); diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp index 77ef096..6847173 100644 --- a/src/corelib/kernel/qcoreapplication.cpp +++ b/src/corelib/kernel/qcoreapplication.cpp @@ -1798,7 +1798,7 @@ QString QCoreApplication::applicationFilePath() */ QByteArray pEnv = qgetenv("PATH"); QDir currentDir = QDir::current(); - QStringList paths = QString::fromLocal8Bit(pEnv.constData()).split(QLatin1String(":")); + QStringList paths = QString::fromLocal8Bit(pEnv.constData()).split(QLatin1Char(':')); for (QStringList::const_iterator p = paths.constBegin(); p != paths.constEnd(); ++p) { if ((*p).isEmpty()) continue; @@ -1908,7 +1908,7 @@ QStringList QCoreApplication::arguments() wchar_t tempFilename[MAX_PATH+1]; if (GetModuleFileNameW(0, tempFilename, MAX_PATH)) { tempFilename[MAX_PATH] = 0; - cmdline.prepend(QString(QLatin1String("\"")) + QString::fromUtf16((unsigned short *)tempFilename) + QString(QLatin1String("\" "))); + cmdline.prepend(QLatin1Char('\"') + QString::fromUtf16((unsigned short *)tempFilename) + QString(QLatin1String("\" "))); } #endif // Q_OS_WINCE diff --git a/src/corelib/kernel/qcoreapplication_win.cpp b/src/corelib/kernel/qcoreapplication_win.cpp index 225821f..7ab91c9 100644 --- a/src/corelib/kernel/qcoreapplication_win.cpp +++ b/src/corelib/kernel/qcoreapplication_win.cpp @@ -134,11 +134,11 @@ Q_CORE_EXPORT void qWinMsgHandler(QtMsgType t, const char* str) staticCriticalSection.lock(); QT_WA({ QString s(QString::fromLocal8Bit(str)); - s += QLatin1String("\n"); + s += QLatin1Char('\n'); OutputDebugStringW((TCHAR*)s.utf16()); }, { QByteArray s(str); - s += "\n"; + s += '\n'; OutputDebugStringA(s.data()); }) staticCriticalSection.unlock(); diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index 1e9e284..65d81f1 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -3461,7 +3461,7 @@ QDebug operator<<(QDebug dbg, const QObject *o) { #ifndef Q_BROKEN_DEBUG_STREAM if (!o) return dbg << "QObject(0x0) "; - dbg.nospace() << o->metaObject()->className() << "(" << (void *)o; + dbg.nospace() << o->metaObject()->className() << '(' << (void *)o; if (!o->objectName().isEmpty()) dbg << ", name = " << o->objectName(); dbg << ')'; diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp index 744515b..309c8be 100644 --- a/src/corelib/statemachine/qstatemachine.cpp +++ b/src/corelib/statemachine/qstatemachine.cpp @@ -354,7 +354,7 @@ bool QStateMachinePrivate::isPreempted(const QAbstractState *s, const QSet QStateMachinePrivate::selectTransitions(QEvent *event void QStateMachinePrivate::microstep(QEvent *event, const QList &enabledTransitions) { #ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": begin microstep( enabledTransitions:" << enabledTransitions << ")"; + qDebug() << q_func() << ": begin microstep( enabledTransitions:" << enabledTransitions << ')'; qDebug() << q_func() << ": configuration before exiting states:" << configuration; #endif QList exitedStates = exitStates(event, enabledTransitions); @@ -421,7 +421,7 @@ void QStateMachinePrivate::microstep(QEvent *event, const QList QStateMachinePrivate::exitStates(QEvent *event, const QList &enabledTransitions) { -// qDebug() << "exitStates(" << enabledTransitions << ")"; +// qDebug() << "exitStates(" << enabledTransitions << ')'; QSet statesToExit; // QSet statesToSnapshot; for (int i = 0; i < enabledTransitions.size(); ++i) { @@ -470,7 +470,7 @@ QList QStateMachinePrivate::exitStates(QEvent *event, const QLi } #ifdef QSTATEMACHINE_DEBUG qDebug() << q_func() << ": recorded" << ((QHistoryStatePrivate::get(h)->historyType == QHistoryState::DeepHistory) ? "deep" : "shallow") - << "history for" << s << "in" << h << ":" << QHistoryStatePrivate::get(h)->configuration; + << "history for" << s << "in" << h << ':' << QHistoryStatePrivate::get(h)->configuration; #endif } } @@ -503,7 +503,7 @@ QList QStateMachinePrivate::enterStates(QEvent *event, const QL #ifdef QSTATEMACHINE_DEBUG Q_Q(QStateMachine); #endif -// qDebug() << "enterStates(" << enabledTransitions << ")"; +// qDebug() << "enterStates(" << enabledTransitions << ')'; QSet statesToEnter; QSet statesForDefaultEntry; @@ -609,7 +609,7 @@ void QStateMachinePrivate::addStatesToEnter(QAbstractState *s, QState *root, #ifdef QSTATEMACHINE_DEBUG qDebug() <historyType == QHistoryState::DeepHistory) ? "deep" : "shallow") - << "history from" << s << ":" << hconf; + << "history from" << s << ':' << hconf; #endif } else { QList hlst; @@ -624,7 +624,7 @@ void QStateMachinePrivate::addStatesToEnter(QAbstractState *s, QState *root, addStatesToEnter(s0, root, statesToEnter, statesForDefaultEntry); } #ifdef QSTATEMACHINE_DEBUG - qDebug() << q_func() << ": initial history targets for" << s << ":" << hlst; + qDebug() << q_func() << ": initial history targets for" << s << ':' << hlst; #endif } } @@ -968,7 +968,7 @@ QVariant QStateMachinePrivate::restorableValue(QObject *object, const QByteArray */ void QStateMachinePrivate::unregisterRestorable(QObject *object, const QByteArray &propertyName) { -// qDebug() << "unregisterRestorable(" << object << propertyName << ")"; +// qDebug() << "unregisterRestorable(" << object << propertyName << ')'; RestorableId id(object, propertyName); registeredRestorables.remove(id); } @@ -1341,7 +1341,7 @@ void QStateMachinePrivate::registerSignalTransition(QSignalTransition *transitio #ifdef QSTATEMACHINE_DEBUG qDebug() << q << ": FAILED to add signal transition from" << transition->sourceState() << ": ( sender =" << sender << ", signal =" << (signal.mid(1)) - << ", targets =" << transition->targetStates() << ")"; + << ", targets =" << transition->targetStates() << ')'; #endif return; } @@ -1351,7 +1351,7 @@ void QStateMachinePrivate::registerSignalTransition(QSignalTransition *transitio #ifdef QSTATEMACHINE_DEBUG qDebug() << q << ": added signal transition from" << transition->sourceState() << ": ( sender =" << sender << ", signal =" << (signal.mid(1)) - << ", targets =" << transition->targetStates() << ")"; + << ", targets =" << transition->targetStates() << ')'; #endif } @@ -1412,7 +1412,7 @@ void QStateMachinePrivate::registerEventTransition(QEventTransition *transition) #ifdef QSTATEMACHINE_DEBUG qDebug() << q << ": added event transition from" << transition->sourceState() << ": ( object =" << object << ", event =" << transition->eventType() - << ", targets =" << transition->targetStates() << ")"; + << ", targets =" << transition->targetStates() << ')'; #endif } @@ -1456,7 +1456,7 @@ void QStateMachinePrivate::handleTransitionSignal(const QObject *sender, int sig #ifdef QSTATEMACHINE_DEBUG qDebug() << q_func() << ": sending signal event ( sender =" << sender - << ", signal =" << sender->metaObject()->method(signalIndex).signature() << ")"; + << ", signal =" << sender->metaObject()->method(signalIndex).signature() << ')'; #endif internalEventQueue.append(new QSignalEvent(sender, signalIndex, vargs)); scheduleProcess(); diff --git a/src/corelib/tools/qdatetime.cpp b/src/corelib/tools/qdatetime.cpp index 781514c..090ca61 100644 --- a/src/corelib/tools/qdatetime.cpp +++ b/src/corelib/tools/qdatetime.cpp @@ -3833,19 +3833,19 @@ void QDateTimePrivate::getUTC(QDate &outDate, QTime &outTime) const #if !defined(QT_NO_DEBUG_STREAM) && !defined(QT_NO_DATESTRING) QDebug operator<<(QDebug dbg, const QDate &date) { - dbg.nospace() << "QDate(" << date.toString() << ")"; + dbg.nospace() << "QDate(" << date.toString() << ')'; return dbg.space(); } QDebug operator<<(QDebug dbg, const QTime &time) { - dbg.nospace() << "QTime(" << time.toString() << ")"; + dbg.nospace() << "QTime(" << time.toString() << ')'; return dbg.space(); } QDebug operator<<(QDebug dbg, const QDateTime &date) { - dbg.nospace() << "QDateTime(" << date.toString() << ")"; + dbg.nospace() << "QDateTime(" << date.toString() << ')'; return dbg.space(); } #endif diff --git a/src/corelib/tools/qline.cpp b/src/corelib/tools/qline.cpp index f615dcd..88825a3 100644 --- a/src/corelib/tools/qline.cpp +++ b/src/corelib/tools/qline.cpp @@ -260,7 +260,7 @@ QT_BEGIN_NAMESPACE #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug d, const QLine &p) { - d << "QLine(" << p.p1() << "," << p.p2() << ")"; + d << "QLine(" << p.p1() << ',' << p.p2() << ')'; return d; } #endif @@ -822,7 +822,7 @@ qreal QLineF::angle(const QLineF &l) const #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug d, const QLineF &p) { - d << "QLineF(" << p.p1() << "," << p.p2() << ")"; + d << "QLineF(" << p.p1() << ',' << p.p2() << ')'; return d; } #endif diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp index 66e3921..23c6ffb 100644 --- a/src/corelib/tools/qlocale.cpp +++ b/src/corelib/tools/qlocale.cpp @@ -1136,7 +1136,7 @@ static QString macToQtFormat(const QString &sys_fmt) break; case 'S': // fractional second if (repeat < 3) - result += QLatin1String("z"); + result += QLatin1Char('z'); else result += QLatin1String("zzz"); break; @@ -1150,7 +1150,7 @@ static QString macToQtFormat(const QString &sys_fmt) if (repeat >= 2) result += QLatin1String("dd"); else - result += QLatin1String("d"); + result += QLatin1Char('d'); break; case 'a': result += QLatin1String("AP"); diff --git a/src/corelib/tools/qpoint.cpp b/src/corelib/tools/qpoint.cpp index 5cc71d6..90b44b1 100644 --- a/src/corelib/tools/qpoint.cpp +++ b/src/corelib/tools/qpoint.cpp @@ -373,7 +373,7 @@ QDebug operator<<(QDebug dbg, const QPoint &p) { QDebug operator<<(QDebug d, const QPointF &p) { - d.nospace() << "QPointF(" << p.x() << ", " << p.y() << ")"; + d.nospace() << "QPointF(" << p.x() << ", " << p.y() << ')'; return d; } #endif diff --git a/src/gui/dialogs/qfiledialog.cpp b/src/gui/dialogs/qfiledialog.cpp index 903cd74..3ccae3a 100644 --- a/src/gui/dialogs/qfiledialog.cpp +++ b/src/gui/dialogs/qfiledialog.cpp @@ -837,8 +837,8 @@ QStringList QFileDialogPrivate::addDefaultSuffixToFiles(const QStringList filesT // This check is needed since we might be at the root directory // and on Windows it already ends with slash. QString path = rootPath(); - if (!path.endsWith(QLatin1String("/"))) - path += QLatin1String("/"); + if (!path.endsWith(QLatin1Char('/'))) + path += QLatin1Char('/'); path += name; files.append(path); } @@ -2649,7 +2649,7 @@ void QFileDialogPrivate::_q_deleteCurrent() void QFileDialogPrivate::_q_autoCompleteFileName(const QString &text) { - if (text.startsWith(QLatin1String("//")) || text.startsWith(QLatin1String("\\"))) { + if (text.startsWith(QLatin1String("//")) || text.startsWith(QLatin1Char('\\'))) { qFileDialogUi->listView->selectionModel()->clearSelection(); return; } @@ -2691,7 +2691,7 @@ void QFileDialogPrivate::_q_updateOkButton() QStringList files = q->selectedFiles(); QString lineEditText = lineEdit()->text(); - if (lineEditText.startsWith(QLatin1String("//")) || lineEditText.startsWith(QLatin1String("\\"))) { + if (lineEditText.startsWith(QLatin1String("//")) || lineEditText.startsWith(QLatin1Char('\\'))) { button->setEnabled(true); if (acceptMode == QFileDialog::AcceptSave) button->setText(isOpenDirectory ? QFileDialog::tr("&Open") : acceptLabel); @@ -3197,7 +3197,7 @@ QStringList QFSCompletor::splitPath(const QString &path) const doubleSlash.clear(); #endif - QRegExp re(QLatin1String("[") + QRegExp::escape(sep) + QLatin1String("]")); + QRegExp re(QLatin1Char('[') + QRegExp::escape(sep) + QLatin1Char(']')); #ifdef Q_OS_WIN QStringList parts = pathCopy.split(re, QString::SkipEmptyParts); diff --git a/src/gui/dialogs/qfiledialog_win.cpp b/src/gui/dialogs/qfiledialog_win.cpp index 6962674..75a1820 100644 --- a/src/gui/dialogs/qfiledialog_win.cpp +++ b/src/gui/dialogs/qfiledialog_win.cpp @@ -214,10 +214,10 @@ static OPENFILENAMEA *qt_win_make_OFNA(QWidget *parent, aInitSel = ""; } else { aInitSel = QDir::toNativeSeparators(initialSelection).toLocal8Bit(); - aInitSel.replace("<", ""); - aInitSel.replace(">", ""); - aInitSel.replace("\"", ""); - aInitSel.replace("|", ""); + aInitSel.replace('<', ""); + aInitSel.replace('>', ""); + aInitSel.replace('\"', ""); + aInitSel.replace('|', ""); } int maxLen = mode == QFileDialog::ExistingFiles ? maxMultiLen : maxNameLen; aInitSel.resize(maxLen + 1); // make room for return value @@ -286,10 +286,10 @@ static OPENFILENAME* qt_win_make_OFN(QWidget *parent, tTitle = title; QString initSel = QDir::toNativeSeparators(initialSelection); if (!initSel.isEmpty()) { - initSel.replace(QLatin1String("<"), QLatin1String("")); - initSel.replace(QLatin1String(">"), QLatin1String("")); - initSel.replace(QLatin1String("\""), QLatin1String("")); - initSel.replace(QLatin1String("|"), QLatin1String("")); + initSel.remove(QLatin1Char('<')); + initSel.remove(QLatin1Char('>')); + initSel.remove(QLatin1Char('\"')); + initSel.remove(QLatin1Char('|')); } int maxLen = mode == QFileDialog::ExistingFiles ? maxMultiLen : maxNameLen; @@ -811,7 +811,7 @@ QString qt_win_get_existing_directory(const QFileDialogArgs &args) QDir::setCurrent(currentDir); if (!result.isEmpty()) - result.replace(QLatin1String("\\"), QLatin1String("/")); + result.replace(QLatin1Char('\\'), QLatin1Char('/')); return result; } diff --git a/src/gui/dialogs/qfilesystemmodel.cpp b/src/gui/dialogs/qfilesystemmodel.cpp index 012d3a1..eeca9f9 100644 --- a/src/gui/dialogs/qfilesystemmodel.cpp +++ b/src/gui/dialogs/qfilesystemmodel.cpp @@ -337,7 +337,7 @@ QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QS { Q_Q(const QFileSystemModel); Q_UNUSED(q); - if (path.isEmpty() || path == myComputer() || path.startsWith(QLatin1String(":"))) + if (path.isEmpty() || path == myComputer() || path.startsWith(QLatin1Char(':'))) return const_cast(&root); // Construct the nodes up to the new root path if they need to be built @@ -356,7 +356,7 @@ QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QS QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts); if ((pathElements.isEmpty()) #if !defined(Q_OS_WIN) || defined(Q_OS_WINCE) - && QDir::fromNativeSeparators(longPath) != QLatin1String("/") + && QDir::fromNativeSeparators(longPath) != QLatin1Char('/') #endif ) return const_cast(&root); diff --git a/src/gui/dialogs/qmessagebox.cpp b/src/gui/dialogs/qmessagebox.cpp index 533c538..ae5b4a3 100644 --- a/src/gui/dialogs/qmessagebox.cpp +++ b/src/gui/dialogs/qmessagebox.cpp @@ -1310,7 +1310,7 @@ void QMessageBox::keyPressEvent(QKeyEvent *e) if (e == QKeySequence::Copy) { QString separator = QString::fromLatin1("---------------------------\n"); QString textToCopy = separator; - separator.prepend(QLatin1String("\n")); + separator.prepend(QLatin1Char('\n')); textToCopy += windowTitle() + separator; // title textToCopy += d->label->text() + separator; // text diff --git a/src/gui/dialogs/qprintpreviewdialog.cpp b/src/gui/dialogs/qprintpreviewdialog.cpp index 3580fdc..29a2738 100644 --- a/src/gui/dialogs/qprintpreviewdialog.cpp +++ b/src/gui/dialogs/qprintpreviewdialog.cpp @@ -558,7 +558,7 @@ void QPrintPreviewDialogPrivate::_q_print() suffix = QLatin1String(".ps"); } QString fileName = QFileDialog::getSaveFileName(q, title, printer->outputFileName(), - QLatin1String("*") + suffix); + QLatin1Char('*') + suffix); if (!fileName.isEmpty()) { if (QFileInfo(fileName).suffix().isEmpty()) fileName.append(suffix); diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index bd764b5..0398fac 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -9588,17 +9588,17 @@ QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag) QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlags flags) { - debug << "("; + debug << '('; bool f = false; for (int i = 0; i < 9; ++i) { if (flags & (1 << i)) { if (f) - debug << "|"; + debug << '|'; f = true; debug << QGraphicsItem::GraphicsItemFlag(int(flags & (1 << i))); } } - debug << ")"; + debug << ')'; return debug; } diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 396618c..501aef1 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3389,7 +3389,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) #ifdef QGRAPHICSVIEW_DEBUG QTime stopWatch; stopWatch.start(); - qDebug() << "QGraphicsView::paintEvent(" << exposedRegion << ")"; + qDebug() << "QGraphicsView::paintEvent(" << exposedRegion << ')'; #endif // Find all exposed items diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 702e0b6..a2e55e1 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -2295,7 +2295,7 @@ void QGraphicsWidget::dumpFocusChain() qWarning("Found a focus chain that is not circular, (next == 0)"); break; } - qDebug() << i++ << QString::number(uint(next), 16) << next->className() << next->data(0) << QString::fromAscii("focusItem:%1").arg(next->hasFocus() ? "1" : "0") << QLatin1String("next:") << next->d_func()->focusNext->data(0) << QLatin1String("prev:") << next->d_func()->focusPrev->data(0); + qDebug() << i++ << QString::number(uint(next), 16) << next->className() << next->data(0) << QString::fromAscii("focusItem:%1").arg(next->hasFocus() ? '1' : '0') << QLatin1String("next:") << next->d_func()->focusNext->data(0) << QLatin1String("prev:") << next->d_func()->focusPrev->data(0); if (visited.contains(next)) { qWarning("Already visited this node. However, I expected to dump until I found myself."); break; diff --git a/src/gui/graphicsview/qgridlayoutengine.cpp b/src/gui/graphicsview/qgridlayoutengine.cpp index c150b0e..88712c2 100644 --- a/src/gui/graphicsview/qgridlayoutengine.cpp +++ b/src/gui/graphicsview/qgridlayoutengine.cpp @@ -1131,9 +1131,9 @@ void QGridLayoutEngine::dump(int indent) const QString message = QLatin1String("[ "); for (int column = 0; column < internalGridColumnCount(); ++column) { message += QString::number(q_items.indexOf(itemAt(row, column))).rightJustified(3); - message += QLatin1String(" "); + message += QLatin1Char(' '); } - message += QLatin1String("]"); + message += QLatin1Char(']'); qDebug("%*s %s", indent, "", qPrintable(message)); } @@ -1157,7 +1157,7 @@ void QGridLayoutEngine::dump(int indent) const message += QLatin1String((message.isEmpty() ? "[" : ", ")); message += QString::number(cellPos->at(i)); } - message += QLatin1String("]"); + message += QLatin1Char(']'); qDebug("%*s %s %s", indent, "", (pass == 0 ? "rows:" : "columns:"), qPrintable(message)); cellPos = &q_xx; } diff --git a/src/gui/image/qxpmhandler.cpp b/src/gui/image/qxpmhandler.cpp index 90bd2ab..f4062ad 100644 --- a/src/gui/image/qxpmhandler.cpp +++ b/src/gui/image/qxpmhandler.cpp @@ -1146,7 +1146,7 @@ static bool write_xpm_image(const QImage &sourceImage, QIODevice *device, const QTextStream s(device); s << "/* XPM */" << endl << "static char *" << fbname(fileName) << "[]={" << endl - << "\"" << w << " " << h << " " << ncolors << " " << cpp << "\""; + << '\"' << w << ' ' << h << ' ' << ncolors << ' ' << cpp << '\"'; // write palette QMap::Iterator c = colorMap.begin(); @@ -1162,7 +1162,7 @@ static bool write_xpm_image(const QImage &sourceImage, QIODevice *device, const qGreen(color), qBlue(color)); ++c; - s << "," << endl << line; + s << ',' << endl << line; } // write pixels, limit to 4 characters per pixel @@ -1184,7 +1184,7 @@ static bool write_xpm_image(const QImage &sourceImage, QIODevice *device, const } } } - s << "," << endl << "\"" << line << "\""; + s << ',' << endl << '\"' << line << '\"'; } s << "};" << endl; return (s.status() == QTextStream::Ok); diff --git a/src/gui/itemviews/qdirmodel.cpp b/src/gui/itemviews/qdirmodel.cpp index 65e3032..5cd16c0 100644 --- a/src/gui/itemviews/qdirmodel.cpp +++ b/src/gui/itemviews/qdirmodel.cpp @@ -885,7 +885,7 @@ QModelIndex QDirModel::index(const QString &path, int column) const QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts); if ((pathElements.isEmpty() || !QFileInfo(path).exists()) #if !defined(Q_OS_WIN) || defined(Q_OS_WINCE) - && path != QLatin1String("/") + && path != QLatin1Char('/') #endif ) return QModelIndex(); diff --git a/src/gui/itemviews/qfileiconprovider.cpp b/src/gui/itemviews/qfileiconprovider.cpp index 054f4cf..434bcde 100644 --- a/src/gui/itemviews/qfileiconprovider.cpp +++ b/src/gui/itemviews/qfileiconprovider.cpp @@ -215,8 +215,7 @@ QIcon QFileIconProvider::icon(IconType type) const QIcon QFileIconProviderPrivate::getWinIcon(const QFileInfo &fileInfo) const { QIcon retIcon; - QString fileExtension = fileInfo.suffix().toUpper(); - fileExtension.prepend( QLatin1String(".") ); + const QString fileExtension = QLatin1Char('.') + fileInfo.suffix().toUpper(); QString key; if (fileInfo.isFile() && !fileInfo.isExecutable() && !fileInfo.isSymLink()) diff --git a/src/gui/itemviews/qitemselectionmodel.cpp b/src/gui/itemviews/qitemselectionmodel.cpp index 8baefdf..696b8fa 100644 --- a/src/gui/itemviews/qitemselectionmodel.cpp +++ b/src/gui/itemviews/qitemselectionmodel.cpp @@ -1553,7 +1553,7 @@ QDebug operator<<(QDebug dbg, const QItemSelectionRange &range) { #ifndef Q_BROKEN_DEBUG_STREAM dbg.nospace() << "QItemSelectionRange(" << range.topLeft() - << "," << range.bottomRight() << ")"; + << ',' << range.bottomRight() << ')'; return dbg.space(); #else qWarning("This compiler doesn't support streaming QItemSelectionRange to QDebug"); diff --git a/src/gui/itemviews/qtableview.cpp b/src/gui/itemviews/qtableview.cpp index 757ecf2..0bded54 100644 --- a/src/gui/itemviews/qtableview.cpp +++ b/src/gui/itemviews/qtableview.cpp @@ -282,7 +282,7 @@ void QTableViewPrivate::trimHiddenSelections(QItemSelectionRange *range) const void QTableViewPrivate::setSpan(int row, int column, int rowSpan, int columnSpan) { if (row < 0 || column < 0 || rowSpan <= 0 || columnSpan <= 0) { - qWarning() << "QTableView::setSpan: invalid span given: (" << row << "," << column << "," << rowSpan << "," << columnSpan << ")"; + qWarning() << "QTableView::setSpan: invalid span given: (" << row << ',' << column << ',' << rowSpan << ',' << columnSpan << ')'; return; } QSpanCollection::Span *sp = spans.spanAt(column, row); diff --git a/src/gui/kernel/qevent.cpp b/src/gui/kernel/qevent.cpp index 0ab4423..a59e870 100644 --- a/src/gui/kernel/qevent.cpp +++ b/src/gui/kernel/qevent.cpp @@ -3081,7 +3081,7 @@ QDebug operator<<(QDebug dbg, const QEvent *e) { << ", " << me->button() << ", " << hex << (int)me->buttons() << ", " << hex << (int)me->modifiers() - << ")"; + << ')'; } return dbg.space(); @@ -3102,7 +3102,7 @@ QDebug operator<<(QDebug dbg, const QEvent *e) { #ifndef QT_NO_WHEELEVENT case QEvent::Wheel: dbg.nospace() << "QWheelEvent(" << static_cast(e)->delta() - << ")"; + << ')'; return dbg.space(); #endif case QEvent::KeyPress: @@ -3128,7 +3128,7 @@ QDebug operator<<(QDebug dbg, const QEvent *e) { << ", \"" << ke->text() << "\", " << ke->isAutoRepeat() << ", " << ke->count() - << ")"; + << ')'; } return dbg.space(); case QEvent::FocusIn: diff --git a/src/gui/kernel/qlayoutengine.cpp b/src/gui/kernel/qlayoutengine.cpp index fbaa388..3673f08 100644 --- a/src/gui/kernel/qlayoutengine.cpp +++ b/src/gui/kernel/qlayoutengine.cpp @@ -329,7 +329,7 @@ void qGeomCalc(QVector &chain, int start, int count, qDebug() << "qGeomCalc" << "start" << start << "count" << count << "pos" << pos << "space" << space << "spacer" << spacer; for (i = start; i < start + count; ++i) { - qDebug() << i << ":" << chain[i].minimumSize << chain[i].smartSizeHint() + qDebug() << i << ':' << chain[i].minimumSize << chain[i].smartSizeHint() << chain[i].maximumSize << "stretch" << chain[i].stretch << "empty" << chain[i].empty << "expansive" << chain[i].expansive << "spacing" << chain[i].spacing; diff --git a/src/gui/kernel/qmime_win.cpp b/src/gui/kernel/qmime_win.cpp index cd0aae6..109ce20 100644 --- a/src/gui/kernel/qmime_win.cpp +++ b/src/gui/kernel/qmime_win.cpp @@ -852,7 +852,7 @@ QVariant QWindowsMimeHtml::convertToMime(const QString &mime, IDataObject *pData if (end > start && start > 0) { html = "" + html.mid(start, end - start); html += ""; - html.replace("\r", ""); + html.replace('\r', ""); result = QString::fromUtf8(html); } } diff --git a/src/gui/kernel/qshortcutmap.cpp b/src/gui/kernel/qshortcutmap.cpp index f998bb2..3c2fcdd 100644 --- a/src/gui/kernel/qshortcutmap.cpp +++ b/src/gui/kernel/qshortcutmap.cpp @@ -109,7 +109,7 @@ QDebug &operator<<(QDebug &dbg, const QShortcutEntry *se) { dbg.nospace() << "QShortcutEntry(" << se->keyseq << "), id(" << se->id << "), enabled(" << se->enabled << "), autorepeat(" << se->autorepeat - << "), owner(" << se->owner << ")"; + << "), owner(" << se->owner << ')'; return dbg.space(); } #endif // QT_NO_DEBUGSTREAM @@ -876,7 +876,7 @@ void QShortcutMap::dispatchEvent(QKeyEvent *e) qDebug().nospace() << "QShortcutMap::dispatchEvent(): Sending QShortcutEvent(\"" << (QString)next->keyseq << "\", " << next->id << ", " - << (bool)(enabledShortcuts>1) << ") to object(" << next->owner << ")"; + << (bool)(enabledShortcuts>1) << ") to object(" << next->owner << ')'; #endif QShortcutEvent se(next->keyseq, next->id, enabledShortcuts>1); QApplication::sendEvent(const_cast(next->owner), &se); diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index e186557..d6e5cce 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -5236,7 +5236,7 @@ static QString constructWindowTitleFromFilePath(const QString &filePath) #ifndef Q_WS_MAC QString appName = QApplication::applicationName(); if (!appName.isEmpty()) - windowTitle += QLatin1String(" ") + QChar(0x2014) + QLatin1String(" ") + appName; + windowTitle += QLatin1Char(' ') + QChar(0x2014) + QLatin1Char(' ') + appName; #endif return windowTitle; } @@ -5300,7 +5300,7 @@ QString qt_setWindowTitle_helperHelper(const QString &title, const QWidget *widg && widget->style()->styleHint(QStyle::SH_TitleBar_ModifyNotification, 0, widget)) cap.replace(lastIndex, 3, QWidget::tr("*")); else - cap.replace(lastIndex, 3, QLatin1String("")); + cap.remove(lastIndex, 3); } index = cap.indexOf(placeHolder, index); diff --git a/src/gui/painting/qcolor.cpp b/src/gui/painting/qcolor.cpp index 534a425..6b58f14 100644 --- a/src/gui/painting/qcolor.cpp +++ b/src/gui/painting/qcolor.cpp @@ -2022,12 +2022,12 @@ QDebug operator<<(QDebug dbg, const QColor &c) if (!c.isValid()) dbg.nospace() << "QColor(Invalid)"; else if (c.spec() == QColor::Rgb) - dbg.nospace() << "QColor(ARGB " << c.alphaF() << ", " << c.redF() << ", " << c.greenF() << ", " << c.blueF() << ")"; + dbg.nospace() << "QColor(ARGB " << c.alphaF() << ", " << c.redF() << ", " << c.greenF() << ", " << c.blueF() << ')'; else if (c.spec() == QColor::Hsv) - dbg.nospace() << "QColor(AHSV " << c.alphaF() << ", " << c.hueF() << ", " << c.saturationF() << ", " << c.valueF() << ")"; + dbg.nospace() << "QColor(AHSV " << c.alphaF() << ", " << c.hueF() << ", " << c.saturationF() << ", " << c.valueF() << ')'; else if (c.spec() == QColor::Cmyk) dbg.nospace() << "QColor(ACMYK " << c.alphaF() << ", " << c.cyanF() << ", " << c.magentaF() << ", " << c.yellowF() << ", " - << c.blackF()<< ")"; + << c.blackF()<< ')'; return dbg.space(); #else diff --git a/src/gui/painting/qmatrix.cpp b/src/gui/painting/qmatrix.cpp index 31abcad..030415d 100644 --- a/src/gui/painting/qmatrix.cpp +++ b/src/gui/painting/qmatrix.cpp @@ -1178,7 +1178,7 @@ QDebug operator<<(QDebug dbg, const QMatrix &m) << " 22=" << m.m22() << " dx=" << m.dx() << " dy=" << m.dy() - << ")"; + << ')'; return dbg.space(); } #endif diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 0e8f50a..069f73d 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -1202,12 +1202,12 @@ void QRasterPaintEngine::clip(const QVectorPath &path, Qt::ClipOperation op) if (path.elements()) { for (int i=0; i " << types[p.elementAt(i).type] << "(x=" << p.elementAt(i).x << ", y=" << p.elementAt(i).y << ")" << endl; + s.nospace() << " -> " << types[p.elementAt(i).type] << "(x=" << p.elementAt(i).x << ", y=" << p.elementAt(i).y << ')' << endl; } return s; diff --git a/src/gui/painting/qpdf.cpp b/src/gui/painting/qpdf.cpp index 55006f6..0b2db8c 100644 --- a/src/gui/painting/qpdf.cpp +++ b/src/gui/painting/qpdf.cpp @@ -346,7 +346,7 @@ QByteArray QPdf::generateDashes(const QPen &pen) { QByteArray result; ByteStream s(&result); - s << "["; + s << '['; QVector dasharray = pen.dashPattern(); qreal w = pen.widthF(); @@ -357,7 +357,7 @@ QByteArray QPdf::generateDashes(const QPen &pen) if (dw < 0.0001) dw = 0.0001; s << dw; } - s << "]"; + s << ']'; //qDebug() << "dasharray: pen has" << dasharray; //qDebug() << " => " << result; return result; @@ -915,17 +915,17 @@ const char *QPdf::paperSizeToString(QPrinter::PaperSize paperSize) QByteArray QPdf::stripSpecialCharacters(const QByteArray &string) { QByteArray s = string; - s.replace(" ", ""); - s.replace("(", ""); - s.replace(")", ""); - s.replace("<", ""); - s.replace(">", ""); - s.replace("[", ""); - s.replace("]", ""); - s.replace("{", ""); - s.replace("}", ""); - s.replace("/", ""); - s.replace("%", ""); + s.replace(' ', ""); + s.replace('(', ""); + s.replace(')', ""); + s.replace('<', ""); + s.replace('>', ""); + s.replace('[', ""); + s.replace(']', ""); + s.replace('{', ""); + s.replace('}', ""); + s.replace('/', ""); + s.replace('%', ""); return s; } diff --git a/src/gui/painting/qpen.cpp b/src/gui/painting/qpen.cpp index 1d68520..ab60861 100644 --- a/src/gui/painting/qpen.cpp +++ b/src/gui/painting/qpen.cpp @@ -978,7 +978,7 @@ QDebug operator<<(QDebug dbg, const QPen &p) dbg.nospace() << "QPen(" << p.width() << ',' << p.brush() << ',' << int(p.style()) << ',' << int(p.capStyle()) << ',' << int(p.joinStyle()) << ',' << p.dashPattern() - << "," << p.dashOffset() + << ',' << p.dashOffset() << ',' << p.miterLimit() << ')'; return dbg.space(); #else diff --git a/src/gui/painting/qprintengine_pdf.cpp b/src/gui/painting/qprintengine_pdf.cpp index 2e063b7..e504558 100644 --- a/src/gui/painting/qprintengine_pdf.cpp +++ b/src/gui/painting/qprintengine_pdf.cpp @@ -423,7 +423,7 @@ int QPdfEnginePrivate::addConstantAlphaObject(int brushAlpha, int penAlpha) object = addXrefEntry(-1); QByteArray alphaDef; QPdf::ByteStream s(&alphaDef); - s << "<<\n/ca " << (brushAlpha/qreal(255.)) << "\n"; + s << "<<\n/ca " << (brushAlpha/qreal(255.)) << '\n'; s << "/CA " << (penAlpha/qreal(255.)) << "\n>>"; xprintf("%s\nendobj\n", alphaDef.constData()); alphaCache.insert(QPair(brushAlpha, penAlpha), object); @@ -1010,7 +1010,7 @@ void QPdfEnginePrivate::embedFont(QFontSubset *font) s << (char)('A' + (tag % 26)); tag /= 26; } - s << "+" << properties.postscriptName << "\n" + s << '+' << properties.postscriptName << "\n" "/Flags " << 4 << "\n" "/FontBBox [" << properties.boundingBox.x()*scale diff --git a/src/gui/painting/qprintengine_ps.cpp b/src/gui/painting/qprintengine_ps.cpp index 97ec640..29f364e 100644 --- a/src/gui/painting/qprintengine_ps.cpp +++ b/src/gui/painting/qprintengine_ps.cpp @@ -167,7 +167,7 @@ static QByteArray wrapDSC(const QByteArray &str) } wrapped += "\n%%+" + tmp; } - return wrapped + "\n"; + return wrapped + '\n'; } // ----------------------------- Internal class declarations ----------------------------- @@ -422,7 +422,7 @@ void QPSPrintEnginePrivate::drawImageHelper(qreal x, qreal y, qreal w, qreal h, << size << " string readstring\n"; ps_r7(*currentPage, out, out.size()); *currentPage << " pop def\n"; - *currentPage << width << ' ' << height << "[" << scaleX << " 0 0 " << scaleY << " 0 0]sl " + *currentPage << width << ' ' << height << '[' << scaleX << " 0 0 " << scaleY << " 0 0]sl " << bits << (!mask.isNull() ? "mask " : "false ") << x << ' ' << y << " di\n"; } @@ -529,7 +529,7 @@ void QPSPrintEnginePrivate::emitHeader(bool finished) else s << "\n%%BoundingBox: 0 0 " << w << h; } - s << "\n" << wrapDSC("%%Creator: " + creator.toUtf8()); + s << '\n' << wrapDSC("%%Creator: " + creator.toUtf8()); if (!title.isEmpty()) s << wrapDSC("%%Title: " + title.toUtf8()); #ifndef QT_NO_DATESTRING @@ -549,7 +549,7 @@ void QPSPrintEnginePrivate::emitHeader(bool finished) "% Prolog copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies).\n" "% You may copy this prolog in any way that is directly related to this document.\n" "% For other use of this prolog, see your licensing agreement for Qt.\n" - << ps_header << "\n"; + << ps_header << '\n'; s << "/pageinit {\n"; @@ -560,12 +560,12 @@ void QPSPrintEnginePrivate::emitHeader(bool finished) s << mtop*scale << mleft*scale << "translate\n"; } if (orientation == QPrinter::Portrait) { - s << "% " << printer->widthMM() << "*" << printer->heightMM() + s << "% " << printer->widthMM() << '*' << printer->heightMM() << "mm (portrait)\n0 " << height*scale - << "translate " << scale << "-" << scale << "scale } def\n"; + << "translate " << scale << '-' << scale << "scale } def\n"; } else { - s << "% " << printer->heightMM() << "*" << printer->widthMM() - << " mm (landscape)\n 90 rotate " << scale << "-" << scale << "scale } def\n"; + s << "% " << printer->heightMM() << '*' << printer->widthMM() + << " mm (landscape)\n 90 rotate " << scale << '-' << scale << "scale } def\n"; } s << "%%EndProlog\n"; @@ -619,8 +619,8 @@ void QPSPrintEnginePrivate::flushPage(bool last) QPdf::ByteStream e(&trailer); buffer << "%%Page: " << pageCount << pageCount << "\n" - << "%%BeginPageSetup\n" - << "QI\n"; + "%%BeginPageSetup\n" + "QI\n"; if (hugeDocument) { for (QHash::const_iterator it = fonts.constBegin(); it != fonts.constEnd(); ++it) { @@ -776,8 +776,8 @@ bool QPSPrintEngine::end() d->flushPage(true); QByteArray trailer; QPdf::ByteStream s(&trailer); - s << "%%Trailer\n"; - s << "%%Pages: " << d->pageCount - 1 << "\n" << + s << "%%Trailer\n" + "%%Pages: " << d->pageCount - 1 << '\n' << wrapDSC("%%DocumentFonts: " + d->fontsUsed); s << "%%EOF\n"; d->outDevice->write(trailer); diff --git a/src/gui/painting/qregion.cpp b/src/gui/painting/qregion.cpp index c88af7c..c4cd77a 100644 --- a/src/gui/painting/qregion.cpp +++ b/src/gui/painting/qregion.cpp @@ -450,9 +450,9 @@ QDebug operator<<(QDebug s, const QRegion &r) { QVector rects = r.rects(); s.nospace() << "QRegion(size=" << rects.size() << "), " - << "bounds = " << r.boundingRect() << "\n"; + << "bounds = " << r.boundingRect() << '\n'; for (int i=0; i innerArea) - qDebug() << "selfTest(): innerRect" << innerRect << "<" << r; + qDebug() << "selfTest(): innerRect" << innerRect << '<' << r; } QRect r = rects.first(); diff --git a/src/gui/painting/qtessellator.cpp b/src/gui/painting/qtessellator.cpp index ce5ab74..b743940 100644 --- a/src/gui/painting/qtessellator.cpp +++ b/src/gui/painting/qtessellator.cpp @@ -1081,7 +1081,7 @@ void QTessellatorPrivate::addIntersection(const Edge *e1, const Edge *e2) yi = y; } QDEBUG() << " between edges " << e1->edge << "and" << e2->edge << "at point (" - << Q27Dot5ToDouble(yi) << ")"; + << Q27Dot5ToDouble(yi) << ')'; Intersection i1; i1.y = yi; @@ -1174,7 +1174,7 @@ void QTessellatorPrivate::addIntersections() for (int i = 0; i < scanline.size; ++i) { Edge *e = scanline.edges[i]; QDEBUG() << " " << i << e->edge << "isect=(" << e->intersect_left << e->intersect_right - << ")"; + << ')'; } #endif @@ -1240,8 +1240,8 @@ QRectF QTessellator::tessellate(const QPointF *points, int nPoints) QDEBUG() << " " << i << ": " << "point=" << d->vertices.position(d->vertices.sorted[i]) << "flags=" << d->vertices.sorted[i]->flags - << "pos=(" << Q27Dot5ToDouble(d->vertices.sorted[i]->x) << "/" - << Q27Dot5ToDouble(d->vertices.sorted[i]->y) << ")"; + << "pos=(" << Q27Dot5ToDouble(d->vertices.sorted[i]->x) << '/' + << Q27Dot5ToDouble(d->vertices.sorted[i]->y) << ')'; } #endif @@ -1271,9 +1271,9 @@ QRectF QTessellator::tessellate(const QPointF *points, int nPoints) for (int i = 0; i < d->scanline.size; ++i) { QDEBUG() << " " << d->scanline.edges[i]->edge << "p0= (" << Q27Dot5ToDouble(d->scanline.edges[i]->v0->x) - << "/" << Q27Dot5ToDouble(d->scanline.edges[i]->v0->y) + << '/' << Q27Dot5ToDouble(d->scanline.edges[i]->v0->y) << ") p1= (" << Q27Dot5ToDouble(d->scanline.edges[i]->v1->x) - << "/" << Q27Dot5ToDouble(d->scanline.edges[i]->v1->y) << ")" + << '/' << Q27Dot5ToDouble(d->scanline.edges[i]->v1->y) << ")" << "x=" << Q27Dot5ToDouble(d->scanline.edges[i]->positionAt(d->y)) << "isLeftOfNext=" << ((i < d->scanline.size - 1) diff --git a/src/gui/painting/qtransform.cpp b/src/gui/painting/qtransform.cpp index ec8c1dc..c00012a 100644 --- a/src/gui/painting/qtransform.cpp +++ b/src/gui/painting/qtransform.cpp @@ -1020,7 +1020,7 @@ QDebug operator<<(QDebug dbg, const QTransform &m) << " 31=" << m.m31() << " 32=" << m.m32() << " 33=" << m.m33() - << ")"; + << ')'; return dbg.space(); } #endif diff --git a/src/gui/styles/qcleanlooksstyle.cpp b/src/gui/styles/qcleanlooksstyle.cpp index 3fb63f2..5c37794 100644 --- a/src/gui/styles/qcleanlooksstyle.cpp +++ b/src/gui/styles/qcleanlooksstyle.cpp @@ -1646,8 +1646,8 @@ void QCleanlooksStyle::drawControl(ControlElement element, const QStyleOption *o if (const QStyleOptionHeader *header = qstyleoption_cast(option)) { QPixmap cache; QString pixmapName = QStyleHelper::uniqueName(QLatin1String("headersection"), option, option->rect.size()); - pixmapName += QLatin1String("-") + QString::number(int(header->position)); - pixmapName += QLatin1String("-") + QString::number(int(header->orientation)); + pixmapName += QString::number(- int(header->position)); + pixmapName += QString::number(- int(header->orientation)); QRect r = option->rect; QColor gradientStopColor; QColor gradientStartColor = option->palette.button().color(); @@ -3858,7 +3858,7 @@ void QCleanlooksStyle::polish(QApplication *app) dataDirs = QLatin1String("/usr/local/share/:/usr/share/"); dataDirs.prepend(QDir::homePath() + QLatin1String("/:")); - d->iconDirs = dataDirs.split(QLatin1String(":")); + d->iconDirs = dataDirs.split(QLatin1Char(':')); #endif } diff --git a/src/gui/styles/qcommonstyle.cpp b/src/gui/styles/qcommonstyle.cpp index a46dbd7..1285598 100644 --- a/src/gui/styles/qcommonstyle.cpp +++ b/src/gui/styles/qcommonstyle.cpp @@ -851,7 +851,7 @@ void QCommonStylePrivate::lookupIconTheme() const dataDirs.prepend(QDir::homePath() + QLatin1String("/:")); QStringList kdeDirs = QString::fromLocal8Bit(getenv("KDEDIRS")).split(QLatin1Char(':')); foreach (const QString &dirName, kdeDirs) - dataDirs.append(QLatin1String(":") + dirName + QLatin1String("/share")); + dataDirs.append(QLatin1Char(':') + dirName + QLatin1String("/share")); iconDirs = dataDirs.split(QLatin1Char(':')); QFileInfo fileInfo(QLatin1String("/usr/share/icons/default.kde")); @@ -893,7 +893,7 @@ QIconTheme QCommonStylePrivate::parseIndexFile(const QString &themeName) const parents = line.split(QLatin1Char(',')); } - if (line.startsWith(QLatin1String("["))) { + if (line.startsWith(QLatin1Char('['))) { line = line.trimmed(); line.chop(1); QString dirName = line.right(line.length() - 1); diff --git a/src/gui/styles/qplastiquestyle.cpp b/src/gui/styles/qplastiquestyle.cpp index 587f2b5..91ad64e 100644 --- a/src/gui/styles/qplastiquestyle.cpp +++ b/src/gui/styles/qplastiquestyle.cpp @@ -2845,8 +2845,8 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op if (const QStyleOptionHeader *header = qstyleoption_cast(option)) { QPixmap cache; QString pixmapName = uniqueName(QLatin1String("headersection"), option, option->rect.size()); - pixmapName += QLatin1String("-") + QString::number(int(header->position)); - pixmapName += QLatin1String("-") + QString::number(int(header->orientation)); + pixmapName += QString::number(- int(header->position)); + pixmapName += QString::number(- int(header->orientation)); if (!UsePixmapCache || !QPixmapCache::find(pixmapName, cache)) { cache = QPixmap(option->rect.size()); diff --git a/src/gui/styles/qstyle.cpp b/src/gui/styles/qstyle.cpp index 514f67b..3fab682 100644 --- a/src/gui/styles/qstyle.cpp +++ b/src/gui/styles/qstyle.cpp @@ -2439,7 +2439,7 @@ QDebug operator<<(QDebug debug, QStyle::State state) qSort(states); debug << states.join(QLatin1String(" | ")); - debug << ")"; + debug << ')'; return debug; } #endif diff --git a/src/gui/styles/qstyleoption.cpp b/src/gui/styles/qstyleoption.cpp index 5b1bc61..e441101 100644 --- a/src/gui/styles/qstyleoption.cpp +++ b/src/gui/styles/qstyleoption.cpp @@ -5362,10 +5362,10 @@ QDebug operator<<(QDebug debug, const QStyleOption &option) { debug << "QStyleOption("; debug << QStyleOption::OptionType(option.type); - debug << "," << (option.direction == Qt::RightToLeft ? "RightToLeft" : "LeftToRight"); - debug << "," << option.state; - debug << "," << option.rect; - debug << ")"; + debug << ',' << (option.direction == Qt::RightToLeft ? "RightToLeft" : "LeftToRight"); + debug << ',' << option.state; + debug << ',' << option.rect; + debug << ')'; return debug; } #endif diff --git a/src/gui/styles/qstylesheetstyle.cpp b/src/gui/styles/qstylesheetstyle.cpp index fdd51c3..1231561 100644 --- a/src/gui/styles/qstylesheetstyle.cpp +++ b/src/gui/styles/qstylesheetstyle.cpp @@ -1555,7 +1555,7 @@ QVector QStyleSheetStyle::styleRules(const QWidget *w) const if (widCacheIt == styleSheetCache->constEnd()) { parser.init(wid->styleSheet()); if (!parser.parse(&ss)) { - parser.init(QLatin1String("* {") + wid->styleSheet() + QLatin1String("}")); + parser.init(QLatin1String("* {") + wid->styleSheet() + QLatin1Char('}')); if (!parser.parse(&ss)) qWarning("Could not parse stylesheet of widget %p", wid); } diff --git a/src/gui/text/qcssparser.cpp b/src/gui/text/qcssparser.cpp index 38621c1..0494b72 100644 --- a/src/gui/text/qcssparser.cpp +++ b/src/gui/text/qcssparser.cpp @@ -1508,7 +1508,7 @@ QRect Declaration::rectValue() const QStringList func = v.variant.toStringList(); if (func.count() != 2 || func.at(0).compare(QLatin1String("rect")) != 0) return QRect(); - QStringList args = func[1].split(QLatin1String(" "), QString::SkipEmptyParts); + QStringList args = func[1].split(QLatin1Char(' '), QString::SkipEmptyParts); if (args.count() != 4) return QRect(); QRect rect(args[0].toInt(), args[1].toInt(), args[2].toInt(), args[3].toInt()); @@ -2153,7 +2153,7 @@ void Parser::init(const QString &css, bool isFile) if (isFile) { QFile file(css); if (file.open(QFile::ReadOnly)) { - sourcePath = QFileInfo(styleSheet).absolutePath() + QLatin1String("/"); + sourcePath = QFileInfo(styleSheet).absolutePath() + QLatin1Char('/'); QTextStream stream(&file); styleSheet = stream.readAll(); } else { diff --git a/src/gui/text/qfontdatabase.cpp b/src/gui/text/qfontdatabase.cpp index c3fc9f5..d3020b0 100644 --- a/src/gui/text/qfontdatabase.cpp +++ b/src/gui/text/qfontdatabase.cpp @@ -792,7 +792,7 @@ static void initFontDef(const QtFontDesc &desc, const QFontDef &request, QFontDe if (! desc.foundry->name.isEmpty() && desc.family->count > 1) { fontDef->family += QString::fromLatin1(" ["); fontDef->family += desc.foundry->name; - fontDef->family += QString::fromLatin1("]"); + fontDef->family += QLatin1Char(']'); } if (desc.style->smoothScalable) @@ -1495,7 +1495,7 @@ QStringList QFontDatabase::families(WritingSystem writingSystem) const if (!foundry.isEmpty()) { str += QLatin1String(" ["); str += foundry; - str += QLatin1String("]"); + str += QLatin1Char(']'); } flist.append(str); } diff --git a/src/gui/text/qfontengine.cpp b/src/gui/text/qfontengine.cpp index d7a9c23..97cb1ed 100644 --- a/src/gui/text/qfontengine.cpp +++ b/src/gui/text/qfontengine.cpp @@ -915,7 +915,7 @@ void QFontEngine::loadKerningPairs(QFixed scalingFactor) end: qSort(kerning_pairs); // for (int i = 0; i < kerning_pairs.count(); ++i) -// qDebug() << "i" << i << "left_right" << hex << kerning_pairs.at(i).left_right; +// qDebug() << 'i' << i << "left_right" << hex << kerning_pairs.at(i).left_right; } #else diff --git a/src/gui/text/qfontsubset.cpp b/src/gui/text/qfontsubset.cpp index 0d1a884..e4d813d 100644 --- a/src/gui/text/qfontsubset.cpp +++ b/src/gui/text/qfontsubset.cpp @@ -333,17 +333,17 @@ QByteArray QFontSubset::glyphName(unsigned int glyph, const QVector reverse name[0] = 0; } if (name[0]) { - s << "/" << name; + s << '/' << name; } else #endif #if defined(Q_WS_X11) if (fontEngine->type() == QFontEngine::XLFD) { uint uc = static_cast(fontEngine)->toUnicode(glyphIndex); - s << "/" << glyphName(uc, false /* ### */); + s << '/' << glyphName(uc, false /* ### */); } else #endif if (reverseMap[glyphIndex] && reverseMap[glyphIndex] < 0x10000) { - s << "/" << glyphName(reverseMap[glyphIndex], false); + s << '/' << glyphName(reverseMap[glyphIndex], false); } else { s << "/gl" << (int)glyphIndex; } @@ -395,13 +395,13 @@ QByteArray QFontSubset::widthArray() const int endnonlinear = startLinear ? startLinear : g; // qDebug(" startLinear=%x endnonlinear=%x", startLinear,endnonlinear); if (endnonlinear > start) { - s << start << "["; + s << start << '['; for (int i = start; i < endnonlinear; ++i) s << (widths[i]*scale).toInt(); s << "]\n"; } if (startLinear) - s << startLinear << g - 1 << (widths[startLinear]*scale).toInt() << "\n"; + s << startLinear << g - 1 << (widths[startLinear]*scale).toInt() << '\n'; } s << "]\n"; } @@ -488,14 +488,14 @@ QByteArray QFontSubset::createToUnicodeMap() const int endnonlinear = startLinear ? startLinear : g; // qDebug(" startLinear=%x endnonlinear=%x", startLinear,endnonlinear); if (endnonlinear > start) { - s << "<" << QPdf::toHex((ushort)start, buf) << "> <"; + s << '<' << QPdf::toHex((ushort)start, buf) << "> <"; s << QPdf::toHex((ushort)(endnonlinear - 1), buf) << "> "; if (endnonlinear == start + 1) { - s << "<" << QPdf::toHex((ushort)reverseMap[start], buf) << ">\n"; + s << '<' << QPdf::toHex((ushort)reverseMap[start], buf) << ">\n"; } else { - s << "["; + s << '['; for (int i = start; i < endnonlinear; ++i) { - s << "<" << QPdf::toHex((ushort)reverseMap[i], buf) << "> "; + s << '<' << QPdf::toHex((ushort)reverseMap[i], buf) << "> "; } s << "]\n"; } @@ -508,9 +508,9 @@ QByteArray QFontSubset::createToUnicodeMap() const int uc_end = uc_start + len - 1; if ((uc_end >> 8) != (uc_start >> 8)) len = 256 - (uc_start & 0xff); - s << "<" << QPdf::toHex((ushort)startLinear, buf) << "> <"; + s << '<' << QPdf::toHex((ushort)startLinear, buf) << "> <"; s << QPdf::toHex((ushort)(startLinear + len - 1), buf) << "> "; - s << "<" << QPdf::toHex((ushort)reverseMap[startLinear], buf) << ">\n"; + s << '<' << QPdf::toHex((ushort)reverseMap[startLinear], buf) << ">\n"; checkRanges(ts, ranges, nranges); startLinear += len; } @@ -1655,7 +1655,7 @@ QByteArray QFontSubset::toType1() const QByteArray id = QByteArray::number(object_id); QByteArray psname = properties.postscriptName; - psname.replace(" ", ""); + psname.replace(' ', ""); standard_font = false; @@ -1681,12 +1681,12 @@ QByteArray QFontSubset::toType1() const #endif s << "/F" << id << "-Base\n"; if (standard_font) { - s << "/" << psname << " findfont\n" + s << '/' << psname << " findfont\n" "0 dict copy dup /NumGlyphs 0 put dup /CMap 256 array put def\n"; } else { s << "<<\n"; if(!psname.isEmpty()) - s << "/FontName /" << psname << "\n"; + s << "/FontName /" << psname << '\n'; s << "/FontInfo <fsType << ">>\n" "/FontType 1\n" "/PaintType 0\n" @@ -1722,7 +1722,7 @@ QByteArray QFontSubset::type1AddedGlyphs() const int nGlyphs = glyph_indices.size(); QByteArray id = QByteArray::number(object_id); - s << "F" << id << "-Base [\n"; + s << 'F' << id << "-Base [\n"; for (int i = downloaded_glyphs; i < nGlyphs; ++i) { glyph_t g = glyph_indices.at(i); QPainterPath path; diff --git a/src/gui/text/qtextcontrol.cpp b/src/gui/text/qtextcontrol.cpp index f3d025c..0958b52 100644 --- a/src/gui/text/qtextcontrol.cpp +++ b/src/gui/text/qtextcontrol.cpp @@ -82,7 +82,7 @@ #include "private/qapplication_p.h" #include "private/qshortcutmap_p.h" #include -#define ACCEL_KEY(k) (!qApp->d_func()->shortcutMap.hasShortcutForKeySequence(k) ? QLatin1String("\t") + QString(QKeySequence(k)) : QString()) +#define ACCEL_KEY(k) (!qApp->d_func()->shortcutMap.hasShortcutForKeySequence(k) ? QLatin1Char('\t') + QString(QKeySequence(k)) : QString()) #else #define ACCEL_KEY(k) QString() #endif diff --git a/src/gui/text/qtextdocument.cpp b/src/gui/text/qtextdocument.cpp index 873f846..23c3c20 100644 --- a/src/gui/text/qtextdocument.cpp +++ b/src/gui/text/qtextdocument.cpp @@ -2201,7 +2201,7 @@ void QTextHtmlExporter::emitTextLength(const char *attribute, const QTextLength if (length.type() == QTextLength::PercentageLength) html += QLatin1String("%\""); else - html += QLatin1String("\""); + html += QLatin1Char('\"'); } void QTextHtmlExporter::emitAlignment(Qt::Alignment align) diff --git a/src/gui/text/qtextengine.cpp b/src/gui/text/qtextengine.cpp index ed6205a..a28c655 100644 --- a/src/gui/text/qtextengine.cpp +++ b/src/gui/text/qtextengine.cpp @@ -363,7 +363,7 @@ static bool bidiItemize(QTextEngine *engine, QScriptAnalysis *analysis, QBidiCon #if (BIDI_DEBUG >= 2) // qDebug() << "pos=" << current << " dir=" << directions[dir] // << " current=" << directions[dirCurrent] << " last=" << directions[status.last] -// << " eor=" << eor << "/" << directions[status.eor] +// << " eor=" << eor << '/' << directions[status.eor] // << " sor=" << sor << " lastStrong=" // << directions[status.lastStrong] // << " level=" << (int)control.level << " override=" << (bool)control.override; diff --git a/src/gui/util/qcompleter.cpp b/src/gui/util/qcompleter.cpp index faa4e7b..bed10dc 100644 --- a/src/gui/util/qcompleter.cpp +++ b/src/gui/util/qcompleter.cpp @@ -1664,7 +1664,7 @@ QStringList QCompleter::splitPath(const QString& path) const doubleSlash.clear(); #endif - QRegExp re(QLatin1String("[") + QRegExp::escape(sep) + QLatin1String("]")); + QRegExp re(QLatin1Char('[') + QRegExp::escape(sep) + QLatin1Char(']')); QStringList parts = pathCopy.split(re); #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) diff --git a/src/gui/util/qsystemtrayicon_win.cpp b/src/gui/util/qsystemtrayicon_win.cpp index a6dcea6..c46c929 100644 --- a/src/gui/util/qsystemtrayicon_win.cpp +++ b/src/gui/util/qsystemtrayicon_win.cpp @@ -662,7 +662,7 @@ void QSystemTrayIconPrivate::showMessage_sys(const QString &title, const QString //message is limited to 255 chars + NULL QString messageString; if (message.isEmpty() && !title.isEmpty()) - messageString = QLatin1String(" "); //ensures that the message shows when only title is set + messageString = QLatin1Char(' '); //ensures that the message shows when only title is set else messageString = message.left(255) + QChar(); diff --git a/src/gui/widgets/qabstractspinbox.cpp b/src/gui/widgets/qabstractspinbox.cpp index d640c70..09accc7 100644 --- a/src/gui/widgets/qabstractspinbox.cpp +++ b/src/gui/widgets/qabstractspinbox.cpp @@ -1781,8 +1781,8 @@ void QAbstractSpinBoxPrivate::interpret(EmitPolicy ep) q->fixup(tmp); QASBDEBUG() << "QAbstractSpinBoxPrivate::interpret() text '" << edit->displayText() - << "' >> '" << copy << "'" - << "' >> '" << tmp << "'"; + << "' >> '" << copy << '\'' + << "' >> '" << tmp << '\''; doInterpret = tmp != copy && (q->validate(tmp, pos) == QValidator::Acceptable); if (!doInterpret) { diff --git a/src/gui/widgets/qcalendarwidget.cpp b/src/gui/widgets/qcalendarwidget.cpp index 4436c04..8703139 100644 --- a/src/gui/widgets/qcalendarwidget.cpp +++ b/src/gui/widgets/qcalendarwidget.cpp @@ -198,7 +198,7 @@ QString QCalendarDayValidator::text() const { QString str; if (m_day / 10 == 0) - str += QLatin1String("0"); + str += QLatin1Char('0'); str += QString::number(m_day); return highlightString(str, m_pos); } @@ -210,7 +210,7 @@ QString QCalendarDayValidator::text(const QDate &date, int repeat) const } else if (repeat == 2) { QString str; if (date.day() / 10 == 0) - str += QLatin1String("0"); + str += QLatin1Char('0'); return str + QString::number(date.day()); } else if (repeat == 3) { return m_locale.dayName(date.dayOfWeek(), QLocale::ShortFormat); @@ -316,7 +316,7 @@ QString QCalendarMonthValidator::text() const { QString str; if (m_month / 10 == 0) - str += QLatin1String("0"); + str += QLatin1Char('0'); str += QString::number(m_month); return highlightString(str, m_pos); } @@ -328,7 +328,7 @@ QString QCalendarMonthValidator::text(const QDate &date, int repeat) const } else if (repeat == 2) { QString str; if (date.month() / 10 == 0) - str += QLatin1String("0"); + str += QLatin1Char('0'); return str + QString::number(date.month()); } else if (repeat == 3) { return m_locale.standaloneMonthName(date.month(), QLocale::ShortFormat); @@ -432,7 +432,7 @@ QString QCalendarYearValidator::text() const int pow = 10; for (int i = 0; i < 3; i++) { if (m_year / pow == 0) - str += QLatin1String("0"); + str += QLatin1Char('0'); pow *= 10; } str += QString::number(m_year); @@ -445,7 +445,7 @@ QString QCalendarYearValidator::text(const QDate &date, int repeat) const QString str; int year = date.year() % 100; if (year / 10 == 0) - str = QLatin1String("0"); + str = QLatin1Char('0'); return str + QString::number(year); } return QString::number(date.year()); @@ -577,7 +577,7 @@ void QCalendarDateValidator::setFormat(const QString &format) clear(); int pos = 0; - const QLatin1String quote("'"); + const QLatin1Char quote('\''); bool quoting = false; QString separator; while (pos < format.size()) { diff --git a/src/gui/widgets/qlabel.cpp b/src/gui/widgets/qlabel.cpp index 016b7c1..1aef133 100644 --- a/src/gui/widgets/qlabel.cpp +++ b/src/gui/widgets/qlabel.cpp @@ -1170,7 +1170,7 @@ void QLabelPrivate::updateShortcut() shortcutCursor.deleteChar(); // remove the ampersand shortcutCursor.movePosition(QTextCursor::NextCharacter, QTextCursor::KeepAnchor); } else { - if (!text.contains(QLatin1String("&"))) + if (!text.contains(QLatin1Char('&'))) return; hasShortcut = true; shortcutId = q->grabShortcut(QKeySequence::mnemonic(text)); diff --git a/src/gui/widgets/qlineedit.cpp b/src/gui/widgets/qlineedit.cpp index 128f243..a4b0b4f 100644 --- a/src/gui/widgets/qlineedit.cpp +++ b/src/gui/widgets/qlineedit.cpp @@ -79,7 +79,7 @@ #include "private/qapplication_p.h" #include "private/qshortcutmap_p.h" #include "qkeysequence.h" -#define ACCEL_KEY(k) (!qApp->d_func()->shortcutMap.hasShortcutForKeySequence(k) ? QLatin1String("\t") + QString(QKeySequence(k)) : QString()) +#define ACCEL_KEY(k) (!qApp->d_func()->shortcutMap.hasShortcutForKeySequence(k) ? QLatin1Char('\t') + QString(QKeySequence(k)) : QString()) #else #define ACCEL_KEY(k) QString() #endif diff --git a/src/gui/widgets/qspinbox.cpp b/src/gui/widgets/qspinbox.cpp index c691eaf..b7426f0 100644 --- a/src/gui/widgets/qspinbox.cpp +++ b/src/gui/widgets/qspinbox.cpp @@ -1030,7 +1030,7 @@ QVariant QSpinBoxPrivate::validateAndInterpret(QString &input, int &pos, { if (cachedText == input && !input.isEmpty()) { state = cachedState; - QSBDEBUG() << "cachedText was" << "'" << cachedText << "'" << "state was " + QSBDEBUG() << "cachedText was '" << cachedText << "' state was " << state << " and value was " << cachedValue; return cachedValue; @@ -1048,7 +1048,7 @@ QVariant QSpinBoxPrivate::validateAndInterpret(QString &input, int &pos, || (min >= 0 && copy == QLatin1String("+")))) { state = QValidator::Intermediate; QSBDEBUG() << __FILE__ << __LINE__<< "num is set to" << num; - } else if (copy.startsWith(QLatin1String("-")) && min >= 0) { + } else if (copy.startsWith(QLatin1Char('-')) && min >= 0) { state = QValidator::Invalid; // special-case -0 will be interpreted as 0 and thus not be invalid with a range from 0-100 } else { bool ok = false; @@ -1271,7 +1271,7 @@ QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos, { if (cachedText == input && !input.isEmpty()) { state = cachedState; - QSBDEBUG() << "cachedText was" << "'" << cachedText << "'" << "state was " + QSBDEBUG() << "cachedText was '" << cachedText << "' state was " << state << " and value was " << cachedValue; return cachedValue; } -- cgit v0.12 From fa2371e705621b95307f0dbc1988ba048cec6520 Mon Sep 17 00:00:00 2001 From: axasia Date: Sat, 23 May 2009 23:33:49 +0900 Subject: Update japanese translation of Qt Assistant 4.5 --- translations/assistant_ja.ts | 395 ++++++++++++++++++++++--------------------- 1 file changed, 203 insertions(+), 192 deletions(-) diff --git a/translations/assistant_ja.ts b/translations/assistant_ja.ts index 1853155..5e4d2c9 100644 --- a/translations/assistant_ja.ts +++ b/translations/assistant_ja.ts @@ -1,12 +1,12 @@ - + AboutDialog &Close - + é–‰ã˜ã‚‹(&C) @@ -14,18 +14,19 @@ Warning - + 警告 Unable to launch external application. - + 外部アプリケーションを起動ã§ãã¾ã›ã‚“。 + OK - + OK @@ -37,42 +38,42 @@ Bookmarks - + ブックマーク Add Bookmark - + ブックマークã®è¿½åŠ  Bookmark: - + ブックマーク: Add in Folder: - + 追加先フォルダ: + - + + New Folder - + æ–°ã—ã„フォルダ Delete Folder - + フォルダを削除 Rename Folder - + フォルダã®åå‰å¤‰æ›´ @@ -80,23 +81,23 @@ Bookmarks - + ブックマーク Remove - + 削除 You are going to delete a Folder, this will also<br>remove it's content. Are you sure to continue? - + フォルダを削除ã™ã‚‹ã¨ä¸­èº«ã‚‚削除ã•れã¾ã™ãŒã€ç¶šã‘ã¦ã‚ˆã‚ã—ã„ã§ã™ã‹? New Folder - + æ–°ã—ã„フォルダ @@ -104,47 +105,47 @@ Filter: - + フィルタ: Remove - + 削除 Delete Folder - + フォルダを削除 Rename Folder - + フォルダã®åå‰å¤‰æ›´ Show Bookmark - + ブックマークを開ã Show Bookmark in New Tab - + ブックマークを新ã—ã„タブã§é–‹ã Delete Bookmark - + ブックマークを削除 Rename Bookmark - + ブックマークã®åå‰å¤‰æ›´ Add - + 追加 @@ -152,48 +153,48 @@ Add new page - + æ–°ã—ã„ページã®è¿½åŠ  Close current page - + ç¾åœ¨ã®ãƒšãƒ¼ã‚¸ã‚’é–‰ã˜ã‚‹ Print Document - + ドキュメントをå°åˆ· unknown - + 䏿˜Ž Add New Page - + æ–°ã—ã„ページã®è¿½åŠ  Close This Page - + ã“ã®ãƒšãƒ¼ã‚¸ã‚’é–‰ã˜ã‚‹ Close Other Pages - + ä»–ã®ãƒšãƒ¼ã‚¸ã‚’é–‰ã˜ã‚‹ Add Bookmark for this Page... - + ã“ã®ãƒšãƒ¼ã‚¸ã‚’ブックマークã«è¿½åŠ ... Search - + 検索 @@ -201,12 +202,12 @@ Open Link - + リンクを開ã Open Link in New Tab - + リンクを新ã—ã„タブã§é–‹ã @@ -214,12 +215,12 @@ Add Filter Name - + フィルタåを追加 Filter Name: - + フィルタå: @@ -227,27 +228,27 @@ Previous - + 戻る Next - + 進む Case Sensitive - + 大文字/å°æ–‡å­—を区別ã™ã‚‹ Whole words - + å˜èªžå˜ä½ã§æ¤œç´¢ã™ã‚‹ <img src=":/trolltech/assistant/images/wrap.png">&nbsp;Search wrapped - + <img src=":/trolltech/assistant/images/wrap.png">&nbsp;見ã¤ã‹ã‚‰ãªã‘れã°å…ˆé ­ã‹ã‚‰æ¤œç´¢ã™ã‚‹ @@ -255,27 +256,27 @@ Font - + フォント &Writing system - + 文字セット(&W) &Family - + フォントå(&F) &Style - + スタイル(&S) &Point size - + サイズ(&P) @@ -283,38 +284,39 @@ Help - + ヘルプ OK - + OK <title>Error 404...</title><div align="center"><br><br><h1>The page could not be found</h1><br><h3>'%1'</h3></div> - + <title>Error 404...</title><div align="center"><br><br><h1>ページãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“ã§ã—ãŸ</h1><br><h3>'%1'</h3></div> Copy &Link Location - + リンクã®URLをコピー(&L) Open Link in New Tab Ctrl+LMB - + リンクを新ã—ã„タブã§é–‹ã Ctrl+LMB Open Link in New Tab - + リンクを新ã—ã„タブã§é–‹ã Unable to launch external application. - + 外部アプリケーションを起動ã§ãã¾ã›ã‚“。 + @@ -322,17 +324,17 @@ &Look for: - + 検索文字列(&L): Open Link - + リンクを開ã Open Link in New Tab - + リンクを新ã—ã„タブã§é–‹ã @@ -341,97 +343,98 @@ Install Documentation - + ドキュメントã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ« Downloading documentation info... - + ドキュメント情報をダウンロード中... Download canceled. - + ダウンロードを中止ã—ã¾ã—ãŸã€‚ Done. - + 完了. The file %1 already exists. Do you want to overwrite it? - + %1 ã¯æ—¢ã«å­˜åœ¨ã—ã¾ã™ã€‚上書ãã—ã¾ã™ã‹? Unable to save the file %1: %2. - + ファイルをä¿å­˜ã§ãã¾ã›ã‚“。%1: %2. Downloading %1... - + %1 をダウンロード中... Download failed: %1. - + ダウンロード失敗: %1. Documentation info file is corrupt! - + ドキュメント情報ファイルãŒä¸æ­£ã§ã™! Download failed: Downloaded file is corrupted. - + ダウンロード失敗: ダウンロードã—ãŸãƒ•ァイルãŒä¸æ­£ã§ã™ã€‚ Installing documentation %1... - + %1 ã®ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆã‚’インストール中... Error while installing documentation: %1 - + ドキュメントã®ã‚¤ãƒ³ã‚¹ãƒˆãƒ¼ãƒ«ä¸­ã«ã‚¨ãƒ©ãƒ¼ãŒç™ºç”Ÿã—ã¾ã—ãŸ: +%1 Available Documentation: - + 使用å¯èƒ½ãªãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆ: Install - + インストール Cancel - + キャンセル Close - + é–‰ã˜ã‚‹ Installation Path: - + インストール先ã®ãƒ‘ス: ... - + ... @@ -440,298 +443,298 @@ Index - + インデックス Contents - + コンテンツ Bookmarks - + ブックマーク Search - + 検索 Qt Assistant - + Qt Assistant Unfiltered - + フィルタãªã— Page Set&up... - + ページ設定(&U)... Print Preview... - + å°åˆ·ãƒ—レビュー... &Print... - + å°åˆ·(&P)... New &Tab - + æ–°ã—ã„タブ(&T) &Close Tab - + タブを閉ã˜ã‚‹(&C) &Quit - + 終了(&Q) CTRL+Q - + CTRL+Q &Copy selected Text - + é¸æŠžä¸­ã®æ–‡å­—をコピー(&C) &Find in Text... - + 検索(&F)... Find &Next - + 次を検索(&N) Find &Previous - + å‰ã‚’検索(&P) Preferences... - + 設定... Zoom &in - + 拡大(&I) Zoom &out - + 縮å°(&O) Normal &Size - + 普通ã®å¤§ãã•(&S) Ctrl+0 - + Ctrl+0 ALT+C - + ALT+C ALT+I - + ALT+I ALT+S - + ALT+S &Home - + ホーム(&H) Ctrl+Home - + Ctrl+Home &Back - + 戻る(&B) &Forward - + 進む(&F) Sync with Table of Contents - + 内容ã¨ç›®æ¬¡ã‚’åŒæœŸã™ã‚‹ Next Page - + 次ã®ãƒšãƒ¼ã‚¸ Ctrl+Alt+Right - + Ctrl+Alt+Right Previous Page - + å‰ã®ãƒšãƒ¼ã‚¸ Ctrl+Alt+Left - + Ctrl+Alt+Left Add Bookmark... - + ブックマークã®è¿½åŠ ... About... - + Qt Assistant ã«ã¤ã„ã¦... Navigation Toolbar - + ナビゲーション ツールãƒãƒ¼ Toolbars - + ツールãƒãƒ¼ Filter Toolbar - + フィルター ツールãƒãƒ¼ Filtered by: - + フィルタæ¡ä»¶: Address Toolbar - + アドレス ツールãƒãƒ¼ Address: - + アドレス: Could not find the associated content item. - + 関連付ã„ãŸå†…容ãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“。 About %1 - + %1 ã«ã¤ã„㦠Updating search index - + 検索インデックスを更新中 Looking for Qt Documentation... - + Qt ドキュメントを探ã—ã¦ã„ã¾ã™... &Window - + ウィンドウ(&W) Minimize - + 最å°åŒ– Ctrl+M - + Ctrl+M Zoom - + ズーム &File - + ファイル(&F) &Edit - + 編集(&E) &View - + 表示(&V) &Go - + ジャンプ(&G) &Bookmarks - + ブックマーク(&B) &Help - + ヘルプ(&H) ALT+O - + ALT+O CTRL+D - + CTRL+D @@ -741,47 +744,47 @@ Add Documentation - + ドキュメントã®è¿½åŠ  Qt Compressed Help Files (*.qch) - + 圧縮済㿠Qt ヘルプファイル (*.qch) The specified file is not a valid Qt Help File! - + 指定ã•れãŸãƒ•ã‚¡ã‚¤ãƒ«ã¯æœ‰åŠ¹ãª Qt ヘルプ ファイルã§ã¯ã‚りã¾ã›ã‚“! The namespace %1 is already registered! - + ãƒãƒ¼ãƒ ã‚¹ãƒšãƒ¼ã‚¹ %1 ã¯æ—¢ã«ç™»éŒ²æ¸ˆã¿ã§ã™! Remove Documentation - + ドキュメントã®é™¤åŽ» Some documents currently opened in Assistant reference the documentation you are attempting to remove. Removing the documentation will close those documents. - + 除去ã—よã†ã¨ã—ã¦ã„ã‚‹ã„ãã¤ã‹ã®ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆã¯ Assistant 上ã§å‚ç…§ã•れã¦ã„ã¾ã™ã€‚除去ã™ã‚‹ã¨ã€ã“れらã®ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆã¯é–‰ã˜ã‚‰ã‚Œã¾ã™ã€‚ Cancel - + キャンセル OK - + OK Use custom settings - + 独自設定を使用ã™ã‚‹ @@ -789,92 +792,92 @@ Preferences - + 設定 Fonts - + フォント Font settings: - + フォント設定: Browser - + ブラウザー Application - + アプリケーション Filters - + フィルタ Filter: - + フィルタ: Attributes: - + 属性: 1 - + 1 Add - + 追加 Remove - + 削除 Documentation - + ドキュメント Registered Documentation: - + 登録済ã¿ãƒ‰ã‚­ãƒ¥ãƒ¡ãƒ³ãƒˆ: Add... - + 追加... Options - + オプション Current Page - + ç¾åœ¨ã®ãƒšãƒ¼ã‚¸ Restore to default - + ãƒ‡ãƒ•ã‚©ãƒ«ãƒˆè¨­å®šã«æˆ»ã™ Homepage - + ホームページ @@ -882,64 +885,64 @@ The specified collection file does not exist! - + 指定ã•れãŸã‚³ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ãƒ•ァイルã¯å­˜åœ¨ã—ã¾ã›ã‚“! Missing collection file! - + コレクションファイルãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“! Invalid URL! - + 䏿­£ãªURLã§ã™! Missing URL! - + URLãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“! Unknown widget: %1 - + 䏿˜Žãªã‚¦ã‚£ã‚¸ã‚§ãƒƒãƒˆ: %1 Missing widget! - + ウィジェットãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“! The specified Qt help file does not exist! - + 指定ã•れ㟠Qt ヘルプ ファイルãŒå­˜åœ¨ã—ã¾ã›ã‚“! Missing help file! - + ヘルプファイルãŒè¦‹ã¤ã‹ã‚Šã¾ã›ã‚“! Missing filter argument! - + フィルタ引数ãŒä¸è¶³ã—ã¦ã„ã¾ã™! Unknown option: %1 - + 䏿˜Žãªã‚ªãƒ—ション: %1 Qt Assistant - + Qt Assistant @@ -948,12 +951,16 @@ Reason: %2 - + ドキュメントファイルを登録ã§ãã¾ã›ã‚“ã§ã—ãŸã€‚ +%1 + +原因: +%2 Documentation successfully registered. - + ドキュメントã®ç™»éŒ²ã«æˆåŠŸã—ã¾ã—ãŸã€‚ @@ -962,28 +969,32 @@ Reason: Reason: %2 - + ドキュメントファイルを解除ã§ãã¾ã›ã‚“ã§ã—ãŸã€‚ +%1 + +原因: +%2 Documentation successfully unregistered. - + ドキュメントã®è§£æ”¾ã«æˆåŠŸã—ã¾ã—ãŸã€‚ Cannot load sqlite database driver! - + SQLite データベース ドライãƒãƒ¼ã‚’ロードã§ãã¾ã›ã‚“! The specified collection file could not be read! - + 指定ã•れãŸã‚³ãƒ¬ã‚¯ã‚·ãƒ§ãƒ³ãƒ•ァイルã¯èª­ã¿è¾¼ã‚ã¾ã›ã‚“! Bookmark - + ブックマーク @@ -991,12 +1002,12 @@ Reason: Debugging Remote Control - + リモート コントロールをデãƒãƒƒã‚°ä¸­ Received Command: %1 %2 - + å—ä¿¡ã—ãŸã‚³ãƒžãƒ³ãƒ‰: %1 %2 @@ -1004,28 +1015,28 @@ Reason: &Copy - + コピー(&C) Copy &Link Location - + リンクã®URLをコピー(&L) Open Link in New Tab - + リンクを新ã—ã„タブã§é–‹ã Select All - + ã™ã¹ã¦ã‚’é¸æŠž Open Link - + リンクを開ã @@ -1033,27 +1044,27 @@ Reason: Choose a topic for <b>%1</b>: - + <b>%1</b> ã®æ¤œç´¢å…ˆãƒˆãƒ”ãƒƒã‚¯ã‚’é¸æŠžã—ã¦ãã ã•ã„: Choose Topic - + ãƒˆãƒ”ãƒƒã‚¯ã‚’é¸æŠž &Topics - + トピック(&T) &Display - + 表示(&D) &Close - + é–‰ã˜ã‚‹(&C) -- cgit v0.12 From 9edac0287250ff6da9b6998412dba6a432899518 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 25 May 2009 11:36:11 +0200 Subject: Warnings fixed on MSVC simply added Q_UNUSED for parameters that weren't used in a function --- src/corelib/io/qnoncontiguousbytedevice.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/corelib/io/qnoncontiguousbytedevice.cpp b/src/corelib/io/qnoncontiguousbytedevice.cpp index 6233fde..f50acdb 100644 --- a/src/corelib/io/qnoncontiguousbytedevice.cpp +++ b/src/corelib/io/qnoncontiguousbytedevice.cpp @@ -458,7 +458,9 @@ qint64 QByteDeviceWrappingIoDevice::readData( char * data, qint64 maxSize) qint64 QByteDeviceWrappingIoDevice::writeData( const char* data, qint64 maxSize) { - return -1; + Q_UNUSED(data); + Q_UNUSED(maxSize); + return -1; } /*! -- cgit v0.12 From e5615b9cf4c981bb8d0fec48eacd6c11c124a3b0 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Mon, 25 May 2009 11:57:30 +0200 Subject: qdoc: Added some missing qdoc comments. Task-number: 252491 --- src/corelib/io/qfsfileengine.cpp | 2 +- src/gui/painting/qcolor.cpp | 8 +++++++ src/gui/painting/qcolormap_mac.cpp | 6 ----- src/gui/painting/qcolormap_x11.cpp | 4 ---- src/opengl/qgl.cpp | 48 +++++++++++++++++++++++++++++++++----- src/opengl/qgl_win.cpp | 16 +++---------- src/opengl/qgl_wince.cpp | 3 --- src/opengl/qgl_x11.cpp | 30 +++++------------------- 8 files changed, 60 insertions(+), 57 deletions(-) diff --git a/src/corelib/io/qfsfileengine.cpp b/src/corelib/io/qfsfileengine.cpp index e79d867..07f3c9c 100644 --- a/src/corelib/io/qfsfileengine.cpp +++ b/src/corelib/io/qfsfileengine.cpp @@ -948,7 +948,7 @@ bool QFSFileEngine::supportsExtension(Extension extension) const For Windows, -2 is always returned. */ -/*! \fn QString QFSFileEngine::owner() const +/*! \fn QString QFSFileEngine::owner(FileOwner own) const \reimp */ diff --git a/src/gui/painting/qcolor.cpp b/src/gui/painting/qcolor.cpp index 1723a19..c50004e 100644 --- a/src/gui/painting/qcolor.cpp +++ b/src/gui/painting/qcolor.cpp @@ -2241,4 +2241,12 @@ QDataStream &operator>>(QDataStream &stream, QColor &color) \sa QColor::rgb(), QColor::rgba() */ +/*! \fn void QColormap::initialize() + \internal +*/ + +/*! \fn void QColormap::cleanup() + \internal +*/ + QT_END_NAMESPACE diff --git a/src/gui/painting/qcolormap_mac.cpp b/src/gui/painting/qcolormap_mac.cpp index afe0378..96da90f 100644 --- a/src/gui/painting/qcolormap_mac.cpp +++ b/src/gui/painting/qcolormap_mac.cpp @@ -55,17 +55,11 @@ public: }; static QColormap *qt_mac_global_map = 0; -/*! - Creates the class's internal colormap. - */ void QColormap::initialize() { qt_mac_global_map = new QColormap; } -/*! - Deletes the class's internal colormap. - */ void QColormap::cleanup() { delete qt_mac_global_map; diff --git a/src/gui/painting/qcolormap_x11.cpp b/src/gui/painting/qcolormap_x11.cpp index ccf6955..c9186b1 100644 --- a/src/gui/painting/qcolormap_x11.cpp +++ b/src/gui/painting/qcolormap_x11.cpp @@ -337,8 +337,6 @@ static void init_direct(QColormapPrivate *d, bool ownColormap) static QColormap **cmaps = 0; -/*! \internal -*/ void QColormap::initialize() { Display *display = QX11Info::display(); @@ -578,8 +576,6 @@ void QColormap::initialize() } } -/*! \internal -*/ void QColormap::cleanup() { Display *display = QX11Info::display(); diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 8f963f8..ca5c732 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -2504,6 +2504,42 @@ const QGLContext* QGLContext::currentContext() visual. On other platforms it may work differently. */ +/*! \fn int QGLContext::choosePixelFormat(void* dummyPfd, HDC pdc) + + \bold{Win32 only:} This virtual function chooses a pixel format + that matches the OpenGL \link setFormat() format\endlink. + Reimplement this function in a subclass if you need a custom + context. + + \warning The \a dummyPfd pointer and \a pdc are used as a \c + PIXELFORMATDESCRIPTOR*. We use \c void to avoid using + Windows-specific types in our header files. + + \sa chooseContext() +*/ + +/*! \fn void *QGLContext::chooseVisual() + + \bold{X11 only:} This virtual function tries to find a visual that + matches the format, reducing the demands if the original request + cannot be met. + + The algorithm for reducing the demands of the format is quite + simple-minded, so override this method in your subclass if your + application has spcific requirements on visual selection. + + \sa chooseContext() +*/ + +/*! \fn void *QGLContext::tryVisual(const QGLFormat& f, int bufDepth) + \internal + + \bold{X11 only:} This virtual function chooses a visual that matches + the OpenGL \link format() format\endlink. Reimplement this function + in a subclass if you need a custom visual. + + \sa chooseContext() +*/ /*! \fn void QGLContext::reset() @@ -3020,11 +3056,10 @@ void QGLWidget::setFormat(const QGLFormat &format) */ /* - \obsolete - \fn void QGLWidget::setContext(QGLContext *context, - const QGLContext* shareContext, - bool deleteOldContext) + const QGLContext* shareContext, + bool deleteOldContext) + \obsolete Sets a new context for this widget. The QGLContext \a context must be created using \e new. QGLWidget will delete \a context when @@ -3174,9 +3209,10 @@ void QGLWidget::resizeOverlayGL(int, int) { } - +/*! \fn bool QGLWidget::event(QEvent *e) + \reimp +*/ #if !defined(Q_OS_WINCE) && !defined(Q_WS_QWS) -/*! \reimp */ bool QGLWidget::event(QEvent *e) { Q_D(QGLWidget); diff --git a/src/opengl/qgl_win.cpp b/src/opengl/qgl_win.cpp index bd8569a..217b0fc 100644 --- a/src/opengl/qgl_win.cpp +++ b/src/opengl/qgl_win.cpp @@ -884,19 +884,9 @@ static bool qLogEq(bool a, bool b) return (((!a) && (!b)) || (a && b)); } -/*! - \bold{Win32 only:} This virtual function chooses a pixel - format that matches the OpenGL \link setFormat() format\endlink. - Reimplement this function in a subclass if you need a custom - context. - - \warning The \a dummyPfd pointer and \a pdc are used as a \c - PIXELFORMATDESCRIPTOR*. We use \c void to avoid using - Windows-specific types in our header files. - - \sa chooseContext() -*/ - +/* + See qgl.cpp for qdoc comment. + */ int QGLContext::choosePixelFormat(void* dummyPfd, HDC pdc) { Q_D(QGLContext); diff --git a/src/opengl/qgl_wince.cpp b/src/opengl/qgl_wince.cpp index cb51598..7429071 100644 --- a/src/opengl/qgl_wince.cpp +++ b/src/opengl/qgl_wince.cpp @@ -552,9 +552,6 @@ void QGLWidgetPrivate::updateColormap() ReleaseDC(q->winId(), hdc); } -/*! - \reimp -\*/ bool QGLWidget::event(QEvent *e) { Q_D(QGLWidget); diff --git a/src/opengl/qgl_x11.cpp b/src/opengl/qgl_x11.cpp index 28c34de..7ed7a23 100644 --- a/src/opengl/qgl_x11.cpp +++ b/src/opengl/qgl_x11.cpp @@ -443,19 +443,9 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) return true; } - -/*! - \bold{X11 only:} This virtual function tries to find a - visual that matches the format, reducing the demands if the original - request cannot be met. - - The algorithm for reducing the demands of the format is quite - simple-minded, so override this method in your subclass if your - application has spcific requirements on visual selection. - - \sa chooseContext() -*/ - +/* + See qgl.cpp for qdoc comment. + */ void *QGLContext::chooseVisual() { Q_D(QGLContext); @@ -519,17 +509,9 @@ void *QGLContext::chooseVisual() return vis; } - -/*! - \internal - - \bold{X11 only:} This virtual function chooses a visual - that matches the OpenGL \link format() format\endlink. Reimplement this - function in a subclass if you need a custom visual. - - \sa chooseContext() -*/ - +/* + See qgl.cpp for qdoc comment. + */ void *QGLContext::tryVisual(const QGLFormat& f, int bufDepth) { Q_D(QGLContext); -- cgit v0.12 From c75d55cfbca0a34ae3ecc171178a8c1f0ae76039 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 25 May 2009 12:02:36 +0200 Subject: Added QT_NO_ANIMATION to qfeatures Now you can opt it out to save disk space (for embedded). Also tested it and fixed code in state machine. --- src/corelib/global/qfeatures.txt | 8 ++++++++ src/corelib/statemachine/qstatemachine.cpp | 13 +++++++++---- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/corelib/global/qfeatures.txt b/src/corelib/global/qfeatures.txt index 5d63e46..23ec7b0 100644 --- a/src/corelib/global/qfeatures.txt +++ b/src/corelib/global/qfeatures.txt @@ -1157,6 +1157,14 @@ Requires: PROPERTIES Name: Accessibility SeeAlso: ??? +Feature: ANIMATION +Description: Provides a framework for animations. +Section: Utilities +Requires: PROPERTIES +Name: Animation +SeeAlso: ??? + + # SVG Feature: SVG diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp index 309c8be..757584a 100644 --- a/src/corelib/statemachine/qstatemachine.cpp +++ b/src/corelib/statemachine/qstatemachine.cpp @@ -678,9 +678,11 @@ void QStateMachinePrivate::applyProperties(const QList &tr const QList &exitedStates, const QList &enteredStates) { - Q_Q(QStateMachine); #ifdef QT_NO_ANIMATION Q_UNUSED(transitionList); + Q_UNUSED(exitedStates); +#else + Q_Q(QStateMachine); #endif // Process the property assignments of the entered states. QHash > propertyAssignmentsForState; @@ -851,7 +853,11 @@ void QStateMachinePrivate::applyProperties(const QList &tr // Emit polished signal for entered states that have no animated properties. for (int i = 0; i < enteredStates.size(); ++i) { QState *s = qobject_cast(enteredStates.at(i)); - if (s && !animationsForState.contains(s)) + if (s +#ifndef QT_NO_ANIMATION + && !animationsForState.contains(s) +#endif + ) QStatePrivate::get(s)->emitPolished(); } } @@ -1442,8 +1448,7 @@ void QStateMachinePrivate::unregisterEventTransition(QEventTransition *transitio void QStateMachinePrivate::handleTransitionSignal(const QObject *sender, int signalIndex, void **argv) { - const QVector &connectedSignalIndexes = connections[sender]; - Q_ASSERT(connectedSignalIndexes.at(signalIndex) != 0); + Q_ASSERT(connections[sender].at(signalIndex) != 0); const QMetaObject *meta = sender->metaObject(); QMetaMethod method = meta->method(signalIndex); QList parameterTypes = method.parameterTypes(); -- cgit v0.12 From 44d992ca150d9448cb7b9114b2bc489b441c7b76 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Mon, 25 May 2009 12:25:28 +0200 Subject: qdoc: Added some missing qdoc comments. Task-number: 252489 --- src/gui/text/qfont.cpp | 14 ++++++++++++++ src/gui/text/qfont_x11.cpp | 11 ----------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/src/gui/text/qfont.cpp b/src/gui/text/qfont.cpp index f73ffb5..c5096bf 100644 --- a/src/gui/text/qfont.cpp +++ b/src/gui/text/qfont.cpp @@ -1897,6 +1897,20 @@ void QFont::insertSubstitutions(const QString &familyName, } } +/*! \fn void QFont::initialize() + \internal + + Internal function that initializes the font system. The font cache + and font dict do not alloc the keys. The key is a QString which is + shared between QFontPrivate and QXFontName. +*/ + +/*! \fn void QFont::cleanup() + \internal + + Internal function that cleans up the font system. +*/ + // ### mark: should be called removeSubstitutions() /*! Removes all the substitutions for \a familyName. diff --git a/src/gui/text/qfont_x11.cpp b/src/gui/text/qfont_x11.cpp index 710792c..6b0e46c 100644 --- a/src/gui/text/qfont_x11.cpp +++ b/src/gui/text/qfont_x11.cpp @@ -129,13 +129,6 @@ Q_GUI_EXPORT void qt_x11_set_fallback_font_family(int script, const QString &fam int QFontPrivate::defaultEncodingID = -1; -/*! - Internal function that initializes the font system. - - \internal - The font cache and font dict do not alloc the keys. The key is a QString - which is shared between QFontPrivate and QXFontName. -*/ void QFont::initialize() { extern int qt_encoding_id_for_mib(int mib); // from qfontdatabase_x11.cpp @@ -184,10 +177,6 @@ void QFont::initialize() QFontPrivate::defaultEncodingID = qt_encoding_id_for_mib(mib); } -/*! \internal - - Internal function that cleans up the font system. -*/ void QFont::cleanup() { QFontCache::cleanup(); -- cgit v0.12 From 39f1226e937d49b134f545fc63c776cc460a40ca Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 25 May 2009 12:57:48 +0200 Subject: Compile fix --- src/gui/dialogs/qfilesystemmodel.cpp | 2 +- src/gui/itemviews/qdirmodel.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/dialogs/qfilesystemmodel.cpp b/src/gui/dialogs/qfilesystemmodel.cpp index eeca9f9..825f8b6 100644 --- a/src/gui/dialogs/qfilesystemmodel.cpp +++ b/src/gui/dialogs/qfilesystemmodel.cpp @@ -356,7 +356,7 @@ QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QS QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts); if ((pathElements.isEmpty()) #if !defined(Q_OS_WIN) || defined(Q_OS_WINCE) - && QDir::fromNativeSeparators(longPath) != QLatin1Char('/') + && QDir::fromNativeSeparators(longPath) != QLatin1String("/") #endif ) return const_cast(&root); diff --git a/src/gui/itemviews/qdirmodel.cpp b/src/gui/itemviews/qdirmodel.cpp index 5cd16c0..65e3032 100644 --- a/src/gui/itemviews/qdirmodel.cpp +++ b/src/gui/itemviews/qdirmodel.cpp @@ -885,7 +885,7 @@ QModelIndex QDirModel::index(const QString &path, int column) const QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts); if ((pathElements.isEmpty() || !QFileInfo(path).exists()) #if !defined(Q_OS_WIN) || defined(Q_OS_WINCE) - && path != QLatin1Char('/') + && path != QLatin1String("/") #endif ) return QModelIndex(); -- cgit v0.12 From 7c4735e961fa0e0807d99da1faa2b3fb2a87b6f0 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 25 May 2009 13:23:35 +0200 Subject: Fix a warning on MSVC --- src/gui/painting/qpaintengine_raster.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 069f73d..93e0db0 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -536,8 +536,8 @@ bool QRasterPaintEngine::begin(QPaintDevice *device) */ bool QRasterPaintEngine::end() { - Q_D(QRasterPaintEngine); #ifdef QT_DEBUG_DRAW + Q_D(QRasterPaintEngine); qDebug() << "QRasterPaintEngine::end devRect:" << d->deviceRect; if (d->baseClip) { dumpClip(d->rasterBuffer->width(), d->rasterBuffer->height(), d->baseClip); -- cgit v0.12 From 58253fafc6d3c0a535833e674d8930a46138c25f Mon Sep 17 00:00:00 2001 From: Richard Moe Gustavsen Date: Mon, 25 May 2009 09:30:20 +0200 Subject: BT: Mac: Crash when using QFontDialog If creating a native QFontDialog and delete it, the native dialog will still show. And worse, it will call the deleted QDialog counterpart. This fix will clean up (and close the native dialog) when the QDialog is deleted. Task-number: 254397 Reviewed-by: Trenton Schulz --- src/gui/dialogs/qfontdialog.cpp | 8 ++++++++ src/gui/dialogs/qfontdialog_mac.mm | 1 + 2 files changed, 9 insertions(+) diff --git a/src/gui/dialogs/qfontdialog.cpp b/src/gui/dialogs/qfontdialog.cpp index 4c5bf4f..aa1c553 100644 --- a/src/gui/dialogs/qfontdialog.cpp +++ b/src/gui/dialogs/qfontdialog.cpp @@ -337,6 +337,14 @@ void QFontDialogPrivate::init() QFontDialog::~QFontDialog() { +#ifdef Q_WS_MAC + Q_D(QFontDialog); + if (d->delegate) { + QFontDialogPrivate::closeCocoaFontPanel(d->delegate); + QFontDialogPrivate::sharedFontPanelAvailable = true; + return; + } +#endif } /*! diff --git a/src/gui/dialogs/qfontdialog_mac.mm b/src/gui/dialogs/qfontdialog_mac.mm index 50917a1..13f7149 100644 --- a/src/gui/dialogs/qfontdialog_mac.mm +++ b/src/gui/dialogs/qfontdialog_mac.mm @@ -566,6 +566,7 @@ void *QFontDialogPrivate::openCocoaFontPanel(const QFont &initial, void QFontDialogPrivate::closeCocoaFontPanel(void *delegate) { + QMacCocoaAutoReleasePool pool; QCocoaFontPanelDelegate *theDelegate = static_cast(delegate); NSWindow *ourPanel = [theDelegate actualPanel]; [ourPanel close]; -- cgit v0.12 From 230357435d35a5b379c697723302108dd114585d Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Mon, 25 May 2009 14:05:27 +0200 Subject: qdoc: Moved some qdoc comments to a common cpp file. Task-number: 252488 --- src/gui/image/qpixmap.cpp | 95 +++++++++++++++++++++++++++++++++++++++++++ src/gui/image/qpixmap_qws.cpp | 14 ------- src/gui/image/qpixmap_win.cpp | 45 -------------------- src/gui/image/qpixmap_x11.cpp | 28 ------------- 4 files changed, 95 insertions(+), 87 deletions(-) diff --git a/src/gui/image/qpixmap.cpp b/src/gui/image/qpixmap.cpp index 0f6b649..7fcb2b9 100644 --- a/src/gui/image/qpixmap.cpp +++ b/src/gui/image/qpixmap.cpp @@ -2014,4 +2014,99 @@ QPixmapData* QPixmap::pixmapData() const return data; } +/*! + \enum QPixmap::HBitmapFormat + + \bold{Win32 only:} This enum defines how the conversion between \c + HBITMAP and QPixmap is performed. + + \warning This enum is only available on Windows. + + \value NoAlpha The alpha channel is ignored and always treated as + being set to fully opaque. This is preferred if the \c HBITMAP is + used with standard GDI calls, such as \c BitBlt(). + + \value PremultipliedAlpha The \c HBITMAP is treated as having an + alpha channel and premultiplied colors. This is preferred if the + \c HBITMAP is accessed through the \c AlphaBlend() GDI function. + + \value Alpha The \c HBITMAP is treated as having a plain alpha + channel. This is the preferred format if the \c HBITMAP is going + to be used as an application icon or systray icon. + + \sa fromWinHBITMAP(), toWinHBITMAP() +*/ + +/*! \fn HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const + \bold{Win32 only:} Creates a \c HBITMAP equivalent to the QPixmap, + based on the given \a format. Returns the \c HBITMAP handle. + + It is the caller's responsibility to free the \c HBITMAP data + after use. + + \warning This function is only available on Windows. + + \sa fromWinHBITMAP() +*/ + +/*! \fn QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format) + \bold{Win32 only:} Returns a QPixmap that is equivalent to the + given \a bitmap. The conversion is based on the specified \a + format. + + \warning This function is only available on Windows. + + \sa toWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion} + +*/ + +/*! \fn const QX11Info &QPixmap::x11Info() const + \bold{X11 only:} Returns information about the configuration of + the X display used to display the widget. + + \warning This function is only available on X11. + + \sa {QPixmap#Pixmap Information}{Pixmap Information} +*/ + +/*! \fn Qt::HANDLE QPixmap::x11PictureHandle() const + \bold{X11 only:} Returns the X11 Picture handle of the pixmap for + XRender support. + + This function will return 0 if XRender support is not compiled + into Qt, if the XRender extension is not supported on the X11 + display, or if the handle could not be created. Use of this + function is not portable. + + \warning This function is only available on X11. + + \sa {QPixmap#Pixmap Information}{Pixmap Information} +*/ + +/*! \fn int QPixmap::x11SetDefaultScreen(int screen) + \internal +*/ + +/*! \fn void QPixmap::x11SetScreen(int screen) + \internal +*/ + +/*! \fn QRgb* QPixmap::clut() const + \internal +*/ + +/*! \fn int QPixmap::numCols() const + \internal +*/ + +/*! \fn const uchar* QPixmap::qwsBits() const + \internal + \since 4.1 +*/ + +/*! \fn int QPixmap::qwsBytesPerLine() const + \internal + \since 4.1 +*/ + QT_END_NAMESPACE diff --git a/src/gui/image/qpixmap_qws.cpp b/src/gui/image/qpixmap_qws.cpp index 6cc7981..7e383ab 100644 --- a/src/gui/image/qpixmap_qws.cpp +++ b/src/gui/image/qpixmap_qws.cpp @@ -109,9 +109,6 @@ QPixmap QPixmap::grabWindow(WId window, int x, int y, int w, int h) return QPixmap::fromImage(img); } -/*! - \internal -*/ QRgb* QPixmap::clut() const { if (data->classId() == QPixmapData::RasterClass) { @@ -122,9 +119,6 @@ QRgb* QPixmap::clut() const return 0; } -/*! - \internal -*/ int QPixmap::numCols() const { if (data->classId() == QPixmapData::RasterClass) { @@ -135,10 +129,6 @@ int QPixmap::numCols() const return 0; } -/*! - \internal - \since 4.1 -*/ const uchar* QPixmap::qwsBits() const { if (data->classId() == QPixmapData::RasterClass) { @@ -149,10 +139,6 @@ const uchar* QPixmap::qwsBits() const return 0; } -/*! - \internal - \since 4.1 -*/ int QPixmap::qwsBytesPerLine() const { if (data->classId() == QPixmapData::RasterClass) { diff --git a/src/gui/image/qpixmap_win.cpp b/src/gui/image/qpixmap_win.cpp index cbe9004..6a8b38a 100644 --- a/src/gui/image/qpixmap_win.cpp +++ b/src/gui/image/qpixmap_win.cpp @@ -119,42 +119,6 @@ QPixmap QPixmap::grabWindow(WId winId, int x, int y, int w, int h ) return pixmap; } - - -/*! - \enum QPixmap::HBitmapFormat - - This enum defines how the conversion between \c HBITMAP - and QPixmap is performed. - - \warning This enum is only available on Windows. - - \value NoAlpha The alpha channel is ignored and always treated as - being set to fully opaque. This is preferred if the \c HBITMAP is - used with standard GDI calls, such as \c BitBlt(). - - \value PremultipliedAlpha The \c HBITMAP is treated as having an - alpha channel and premultiplied colors. This is preferred if the - \c HBITMAP is accessed through the \c AlphaBlend() GDI function. - - \value Alpha The \c HBITMAP is treated as having a plain alpha - channel. This is the preferred format if the \c HBITMAP is going - to be used as an application icon or systray icon. - - \sa fromWinHBITMAP(), toWinHBITMAP() -*/ - -/*! - Creates a \c HBITMAP equivalent to the QPixmap, based on the given - \a format. Returns the \c HBITMAP handle. - - It is the caller's responsibility to free the \c HBITMAP data - after use. - - \warning This function is only available on Windows. - - \sa fromWinHBITMAP() -*/ HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const { HBITMAP bitmap = 0; @@ -209,15 +173,6 @@ HBITMAP QPixmap::toWinHBITMAP(HBitmapFormat format) const return bitmap; } -/*! - Returns a QPixmap that is equivalent to the given \a bitmap. The - conversion is based on the specified \a format. - - \warning This function is only available on Windows. - - \sa toWinHBITMAP(), {QPixmap#Pixmap Conversion}{Pixmap Conversion} - -*/ QPixmap QPixmap::fromWinHBITMAP(HBITMAP bitmap, HBitmapFormat format) { // Verify size diff --git a/src/gui/image/qpixmap_x11.cpp b/src/gui/image/qpixmap_x11.cpp index 38916c7..d2e8d84 100644 --- a/src/gui/image/qpixmap_x11.cpp +++ b/src/gui/image/qpixmap_x11.cpp @@ -1914,9 +1914,6 @@ QPixmap QX11PixmapData::transformed(const QTransform &transform, } } -/*! - \internal -*/ int QPixmap::x11SetDefaultScreen(int screen) { int old = defaultScreen; @@ -1924,9 +1921,6 @@ int QPixmap::x11SetDefaultScreen(int screen) return old; } -/*! - \internal -*/ void QPixmap::x11SetScreen(int screen) { if (paintingActive()) { @@ -2034,14 +2028,6 @@ bool QX11PixmapData::hasAlphaChannel() const return d == 32; } -/*! - Returns information about the configuration of the X display used to display - the widget. - - \warning This function is only available on X11. - - \sa {QPixmap#Pixmap Information}{Pixmap Information} -*/ const QX11Info &QPixmap::x11Info() const { if (data->classId() == QPixmapData::X11Class) @@ -2098,20 +2084,6 @@ QPaintEngine* QX11PixmapData::paintEngine() const return that->pengine; } -/*! - Returns the X11 Picture handle of the pixmap for XRender - support. - - This function will return 0 if XRender support is not compiled - into Qt, if the XRender extension is not supported on the X11 - display, or if the handle could not be created. Use of this - function is not portable. - - \warning This function is only available on X11. - - \sa {QPixmap#Pixmap Information}{Pixmap Information} -*/ - Qt::HANDLE QPixmap::x11PictureHandle() const { #ifndef QT_NO_XRENDER -- cgit v0.12 From ee443b7873586592773190457ce8d21bcaae248e Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 25 May 2009 14:21:16 +0200 Subject: qdoc: Fixed non-well-formed XML. Reviewed-by: Martin Smith --- tools/qdoc3/htmlgenerator.cpp | 2 +- tools/qdoc3/test/classic.css | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index e271338..798cbb5 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -2202,7 +2202,7 @@ void HtmlGenerator::generateSectionList(const Section& section, if (name_alignment) { out() << ""; + << "align=\"right\" valign=\"top\">"; } else { if (twoColumn && i == (int) (section.members.count() + 1) / 2) diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index e700e0a..22f1668 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -83,6 +83,7 @@ table td.memItemLeft { border-left-style: none; background-color: #FAFAFA; font-size: 80%; + white-space: nowrap } table td.memItemRight { padding: 1px 8px 0px 8px; -- cgit v0.12 From 1a477dcad1171d2d195422072fce62fc936e56cb Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Mon, 25 May 2009 14:46:20 +0200 Subject: Changed qdoc program to display version from QT_VERSION_STR. Task-number: 251486 --- tools/qdoc3/main.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/qdoc3/main.cpp b/tools/qdoc3/main.cpp index 3e6f832..5c247fa 100644 --- a/tools/qdoc3/main.cpp +++ b/tools/qdoc3/main.cpp @@ -43,6 +43,7 @@ main.cpp */ +#include #include #include #include "apigenerator.h" @@ -136,7 +137,8 @@ static void printHelp() */ static void printVersion() { - Location::information(tr("qdoc version 4.4.1")); + QString s = QString(tr("qdoc version ")) + QString(QT_VERSION_STR); + Location::information(s); } /*! -- cgit v0.12 From b6b251cb8b36be434cf878a916c15019fd65b6f0 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 25 May 2009 14:46:47 +0200 Subject: Removed some export to symbols that don't need it ...hopefully --- examples/animation/sub-attaq/qanimationstate.cpp | 45 +++++++----------------- examples/animation/sub-attaq/qanimationstate.h | 4 +-- src/corelib/concurrent/qfuturewatcher_p.h | 4 +-- src/corelib/kernel/qabstractitemmodel_p.h | 2 +- src/corelib/kernel/qeventdispatcher_unix_p.h | 4 +-- src/corelib/statemachine/qabstractstate_p.h | 3 +- src/corelib/statemachine/qstate.cpp | 14 -------- src/corelib/statemachine/qstate_p.h | 6 ++-- src/corelib/statemachine/qstatemachine_p.h | 5 ++- 9 files changed, 25 insertions(+), 62 deletions(-) diff --git a/examples/animation/sub-attaq/qanimationstate.cpp b/examples/animation/sub-attaq/qanimationstate.cpp index 26e0ef3..d4d109c 100644 --- a/examples/animation/sub-attaq/qanimationstate.cpp +++ b/examples/animation/sub-attaq/qanimationstate.cpp @@ -42,8 +42,6 @@ #include "qanimationstate.h" #include -#include - QT_BEGIN_NAMESPACE @@ -76,25 +74,11 @@ machine.start(); #ifndef QT_NO_ANIMATION -class QAnimationStatePrivate : public QStatePrivate -{ - Q_DECLARE_PUBLIC(QAnimationState) -public: - QAnimationStatePrivate() - : animation(0) - { - - } - ~QAnimationStatePrivate() {} - - QAbstractAnimation *animation; -}; - /*! Constructs a new state with the given \a parent state. */ QAnimationState::QAnimationState(QState *parent) - : QState(*new QAnimationStatePrivate, parent) + : QState(parent), m_animation(0) { } @@ -112,20 +96,18 @@ QAnimationState::~QAnimationState() */ void QAnimationState::setAnimation(QAbstractAnimation *animation) { - Q_D(QAnimationState); - - if (animation == d->animation) + if (animation == m_animation) return; //Disconnect from the previous animation if exist - if(d->animation) - disconnect(d->animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); + if(m_animation) + disconnect(m_animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); - d->animation = animation; + m_animation = animation; - if (d->animation) { + if (m_animation) { //connect the new animation - connect(d->animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); + connect(m_animation, SIGNAL(finished()), this, SIGNAL(animationFinished())); } } @@ -134,8 +116,7 @@ void QAnimationState::setAnimation(QAbstractAnimation *animation) */ QAbstractAnimation* QAnimationState::animation() const { - Q_D(const QAnimationState); - return d->animation; + return m_animation; } /*! @@ -143,9 +124,8 @@ QAbstractAnimation* QAnimationState::animation() const */ void QAnimationState::onEntry(QEvent *) { - Q_D(QAnimationState); - if (d->animation) - d->animation->start(); + if (m_animation) + m_animation->start(); } /*! @@ -153,9 +133,8 @@ void QAnimationState::onEntry(QEvent *) */ void QAnimationState::onExit(QEvent *) { - Q_D(QAnimationState); - if (d->animation) - d->animation->stop(); + if (m_animation) + m_animation->stop(); } /*! diff --git a/examples/animation/sub-attaq/qanimationstate.h b/examples/animation/sub-attaq/qanimationstate.h index 88c0a6d..e5322ad 100644 --- a/examples/animation/sub-attaq/qanimationstate.h +++ b/examples/animation/sub-attaq/qanimationstate.h @@ -58,7 +58,7 @@ QT_MODULE(Gui) #ifndef QT_NO_ANIMATION -class QAnimationStatePrivate; +class QAbstractAnimation; class QAnimationState : public QState { @@ -80,7 +80,7 @@ protected: private: Q_DISABLE_COPY(QAnimationState) - Q_DECLARE_PRIVATE(QAnimationState) + QAbstractAnimation *m_animation; }; #endif diff --git a/src/corelib/concurrent/qfuturewatcher_p.h b/src/corelib/concurrent/qfuturewatcher_p.h index 324839d..d53a1bd 100644 --- a/src/corelib/concurrent/qfuturewatcher_p.h +++ b/src/corelib/concurrent/qfuturewatcher_p.h @@ -63,8 +63,8 @@ QT_BEGIN_NAMESPACE class QFutureWatcherBase; -class Q_CORE_EXPORT QFutureWatcherBasePrivate : public QObjectPrivate, - public QFutureCallOutInterface +class QFutureWatcherBasePrivate : public QObjectPrivate, + public QFutureCallOutInterface { Q_DECLARE_PUBLIC(QFutureWatcherBase) diff --git a/src/corelib/kernel/qabstractitemmodel_p.h b/src/corelib/kernel/qabstractitemmodel_p.h index df1a6ce..27f1b28 100644 --- a/src/corelib/kernel/qabstractitemmodel_p.h +++ b/src/corelib/kernel/qabstractitemmodel_p.h @@ -61,7 +61,7 @@ QT_BEGIN_NAMESPACE -class Q_CORE_EXPORT QPersistentModelIndexData +class QPersistentModelIndexData { public: QPersistentModelIndexData() : model(0) {} diff --git a/src/corelib/kernel/qeventdispatcher_unix_p.h b/src/corelib/kernel/qeventdispatcher_unix_p.h index 41329cf..8c08bd2 100644 --- a/src/corelib/kernel/qeventdispatcher_unix_p.h +++ b/src/corelib/kernel/qeventdispatcher_unix_p.h @@ -153,14 +153,14 @@ public: int activateTimers(); }; -struct Q_CORE_EXPORT QSockNot +struct QSockNot { QSocketNotifier *obj; int fd; fd_set *queue; }; -class Q_CORE_EXPORT QSockNotType +class QSockNotType { public: QSockNotType(); diff --git a/src/corelib/statemachine/qabstractstate_p.h b/src/corelib/statemachine/qabstractstate_p.h index 2aad47e..b4f3108 100644 --- a/src/corelib/statemachine/qabstractstate_p.h +++ b/src/corelib/statemachine/qabstractstate_p.h @@ -60,8 +60,7 @@ QT_BEGIN_NAMESPACE class QStateMachine; class QAbstractState; -class Q_CORE_EXPORT QAbstractStatePrivate - : public QObjectPrivate +class QAbstractStatePrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QAbstractState) diff --git a/src/corelib/statemachine/qstate.cpp b/src/corelib/statemachine/qstate.cpp index e42e463..5463059 100644 --- a/src/corelib/statemachine/qstate.cpp +++ b/src/corelib/statemachine/qstate.cpp @@ -129,20 +129,6 @@ QStatePrivate::~QStatePrivate() { } -QStatePrivate *QStatePrivate::get(QState *q) -{ - if (!q) - return 0; - return q->d_func(); -} - -const QStatePrivate *QStatePrivate::get(const QState *q) -{ - if (!q) - return 0; - return q->d_func(); -} - void QStatePrivate::emitFinished() { Q_Q(QState); diff --git a/src/corelib/statemachine/qstate_p.h b/src/corelib/statemachine/qstate_p.h index 1f913b4..491cb87 100644 --- a/src/corelib/statemachine/qstate_p.h +++ b/src/corelib/statemachine/qstate_p.h @@ -79,15 +79,15 @@ class QAbstractTransition; class QHistoryState; class QState; -class Q_CORE_EXPORT QStatePrivate : public QAbstractStatePrivate +class QStatePrivate : public QAbstractStatePrivate { Q_DECLARE_PUBLIC(QState) public: QStatePrivate(); ~QStatePrivate(); - static QStatePrivate *get(QState *q); - static const QStatePrivate *get(const QState *q); + static QStatePrivate *get(QState *q) { return q ? q->d_func() : 0; } + static const QStatePrivate *get(const QState *q) { return q? q->d_func() : 0; } QList childStates() const; QList historyStates() const; diff --git a/src/corelib/statemachine/qstatemachine_p.h b/src/corelib/statemachine/qstatemachine_p.h index dfa5575..54953b4 100644 --- a/src/corelib/statemachine/qstatemachine_p.h +++ b/src/corelib/statemachine/qstatemachine_p.h @@ -81,8 +81,7 @@ class QAbstractAnimation; #endif class QStateMachine; -class Q_CORE_EXPORT QStateMachinePrivate - : public QObjectPrivate +class QStateMachinePrivate : public QObjectPrivate { Q_DECLARE_PUBLIC(QStateMachine) public: @@ -209,7 +208,7 @@ public: f_cloneEvent cloneEvent; }; - static const Handler *handler; + static Q_CORE_EXPORT const Handler *handler; }; QT_END_NAMESPACE -- cgit v0.12 From e77f2e595d9b9a6f078f37894733c52bbcfeb695 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Mon, 25 May 2009 14:55:33 +0200 Subject: BT: Prevent crash in Designer when using a scroll wheel to change a property. There was some strangeness happening here with parents, but the main problem was the fact that wheel was getting sent to the focusframe and not to the widget below. However, the focusframe has the "transparent for mouse events" flag set and wheel events probably should be transparent as well. Task-number: 253539 Reviewed-by: Richard Moe Gustavsen --- src/gui/kernel/qcocoaview_mac.mm | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/src/gui/kernel/qcocoaview_mac.mm b/src/gui/kernel/qcocoaview_mac.mm index 4ceae3f..f1a7f39 100644 --- a/src/gui/kernel/qcocoaview_mac.mm +++ b/src/gui/kernel/qcocoaview_mac.mm @@ -789,10 +789,22 @@ extern "C" { bool wheelOK = false; Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([theEvent modifierFlags]); + QWidget *widgetToGetMouse = qwidget; + if (widgetToGetMouse->testAttribute(Qt::WA_TransparentForMouseEvents)) { + // Simulate passing the event through since Cocoa doesn't do that for us. + // Start by building a tree up. + NSView *candidateView = [self viewUnderTransparentForMouseView:self + widget:widgetToGetMouse + withWindowPoint:windowPoint]; + if (candidateView != nil) { + widgetToGetMouse = QWidget::find(WId(candidateView)); + } + } + // Mouse wheel deltas seem to tick in at increments of 0.1. Qt widgets - // expect the delta to be a multiple of 120. + // expect the delta to be a multiple of 120. const int ScrollFactor = 10 * 120; - // The qMax(...) factor reduces the + // The qMax(...) factor reduces the // acceleration for large wheel deltas. int deltaX = [theEvent deltaX] * ScrollFactor * qMax(0.6, 1.1 - qAbs([theEvent deltaX])); int deltaY = [theEvent deltaY] * ScrollFactor * qMax(0.6, 1.1 - qAbs([theEvent deltaY])); @@ -800,10 +812,10 @@ extern "C" { if (deltaX != 0) { QWheelEvent qwe(qlocal, qglobal, deltaX, buttons, keyMods, Qt::Horizontal); - qt_sendSpontaneousEvent(qwidget, &qwe); + qt_sendSpontaneousEvent(widgetToGetMouse, &qwe); wheelOK = qwe.isAccepted(); if (!wheelOK && QApplicationPrivate::focus_widget - && QApplicationPrivate::focus_widget != qwidget) { + && QApplicationPrivate::focus_widget != widgetToGetMouse) { QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(qglobal), qglobal, deltaX, buttons, keyMods, Qt::Horizontal); qt_sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2); @@ -813,10 +825,10 @@ extern "C" { if (deltaY) { QWheelEvent qwe(qlocal, qglobal, deltaY, buttons, keyMods, Qt::Vertical); - qt_sendSpontaneousEvent(qwidget, &qwe); + qt_sendSpontaneousEvent(widgetToGetMouse, &qwe); wheelOK = qwe.isAccepted(); if (!wheelOK && QApplicationPrivate::focus_widget - && QApplicationPrivate::focus_widget != qwidget) { + && QApplicationPrivate::focus_widget != widgetToGetMouse) { QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(qglobal), qglobal, deltaY, buttons, keyMods, Qt::Vertical); qt_sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2); @@ -828,10 +840,10 @@ extern "C" { // Qt doesn't explicitly support wheels with a Z component. In a misguided attempt to // try to be ahead of the pack, I'm adding this extra value. QWheelEvent qwe(qlocal, qglobal, deltaZ, buttons, keyMods, (Qt::Orientation)3); - qt_sendSpontaneousEvent(qwidget, &qwe); + qt_sendSpontaneousEvent(widgetToGetMouse, &qwe); wheelOK = qwe.isAccepted(); if (!wheelOK && QApplicationPrivate::focus_widget - && QApplicationPrivate::focus_widget != qwidget) { + && QApplicationPrivate::focus_widget != widgetToGetMouse) { QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(qglobal), qglobal, deltaZ, buttons, keyMods, (Qt::Orientation)3); qt_sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2); -- cgit v0.12 From b57d3f8169c6f1a1aab7203d79043a5f691b7e3e Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Mon, 25 May 2009 15:06:49 +0200 Subject: Changed qdoc to simplify the output for overloaded functions. Task-number: 249222 --- tools/qdoc3/doc.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tools/qdoc3/doc.cpp b/tools/qdoc3/doc.cpp index 61d0ed6..397fbfa 100644 --- a/tools/qdoc3/doc.cpp +++ b/tools/qdoc3/doc.cpp @@ -1265,9 +1265,7 @@ void DocParser::parse(const QString& source, } else { append(Atom::ParaLeft); - append(Atom::String, - "This is an overloaded member function, " - "provided for convenience."); + append(Atom::String,"This is an overloaded function."); append(Atom::ParaRight); x = getMetaCommandArgument(cmdStr); } -- cgit v0.12 From 46bb023374dfd8684cefbe1d1c4ffc37f64f1239 Mon Sep 17 00:00:00 2001 From: Morten Engvoldsen Date: Mon, 25 May 2009 16:25:41 +0200 Subject: Adding details to QSettings functions Adding details to the documentation of custom storage format and related functions. Task-number: 207865 Rev-by: David Boddie Rev-by: Marius Storm-Olsen --- src/corelib/io/qsettings.cpp | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/corelib/io/qsettings.cpp b/src/corelib/io/qsettings.cpp index 14fc2d4..6152518 100644 --- a/src/corelib/io/qsettings.cpp +++ b/src/corelib/io/qsettings.cpp @@ -3468,7 +3468,7 @@ void QSettings::setPath(Format format, Scope scope, const QString &path) \typedef QSettings::SettingsMap Typedef for QMap. - + \sa registerFormat() */ @@ -3479,6 +3479,11 @@ void QSettings::setPath(Format format, Scope scope, const QString &path) \snippet doc/src/snippets/code/src_corelib_io_qsettings.cpp 27 + \c ReadFunc is used in \c registerFormat() as a pointer to a function + that reads a set of key/value pairs. \c ReadFunc should read all the + options in one pass, and return all the settings in the \c SettingsMap + container, which is initially empty. + \sa WriteFunc, registerFormat() */ @@ -3489,6 +3494,10 @@ void QSettings::setPath(Format format, Scope scope, const QString &path) \snippet doc/src/snippets/code/src_corelib_io_qsettings.cpp 28 + \c WriteFunc is used in \c registerFormat() as a pointer to a function + that writes a set of key/value pairs. \c WriteFunc is only called once, + so you need to output the settings in one go. + \sa ReadFunc, registerFormat() */ @@ -3504,7 +3513,7 @@ void QSettings::setPath(Format format, Scope scope, const QString &path) extension associated to the format (without the '.'). The \a readFunc and \a writeFunc parameters are pointers to - functions that read and write a set of (key, value) pairs. The + functions that read and write a set of key/value pairs. The QIODevice parameter to the read and write functions is always opened in binary mode (i.e., without the QIODevice::Text flag). -- cgit v0.12 From 9021113c583cc6b54b3b764e8e74d1448474c773 Mon Sep 17 00:00:00 2001 From: Maurice Kalinowski Date: Mon, 25 May 2009 16:32:25 +0200 Subject: startup crash on WinCE need to deploy the sqlite plugin, otherwise no model gets created, but referenced causing a crash. Task-number: 254435 Reviewed-by: joerg BT: yes --- examples/sql/sqlwidgetmapper/sqlwidgetmapper.pro | 3 +++ 1 file changed, 3 insertions(+) diff --git a/examples/sql/sqlwidgetmapper/sqlwidgetmapper.pro b/examples/sql/sqlwidgetmapper/sqlwidgetmapper.pro index 1881fce..c216a30 100644 --- a/examples/sql/sqlwidgetmapper/sqlwidgetmapper.pro +++ b/examples/sql/sqlwidgetmapper/sqlwidgetmapper.pro @@ -8,3 +8,6 @@ target.path = $$[QT_INSTALL_EXAMPLES]/sql/sqlwidgetmapper sources.files = $$SOURCES $$HEADERS *.pro sources.path = $$[QT_INSTALL_EXAMPLES]/sql/sqlwidgetmapper INSTALLS += target sources + +wince*: DEPLOYMENT_PLUGIN += qsqlite + -- cgit v0.12 From 3d560a498803fadfec9163d7a9695aee60cca8d4 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Mon, 25 May 2009 16:26:13 +0200 Subject: BT: fix systray balloon crash bug on Windows CE Its the context menu handling code... again. Problem is, that during execution of translateMouseEvent, the widget is closed and a modal message box is shown. After that, there's no widget at globalPos and thus, alienWidget is null. This patch just adds a null check for alienWidget. Task-number: 254425 Reviewed-by: mauricek BT: yes --- src/gui/kernel/qapplication_win.cpp | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index f14ad6f..239ee14 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -1675,20 +1675,23 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam // send the context menu event is a different one if (!alienWidget->testAttribute(Qt::WA_NativeWindow) && !alienWidget->testAttribute(Qt::WA_PaintOnScreen)) { alienWidget = QApplication::widgetAt(globalPos); - pos = alienWidget->mapFromGlobal(globalPos); + if (alienWidget) + pos = alienWidget->mapFromGlobal(globalPos); } - SHRGINFO shrg; - shrg.cbSize = sizeof(shrg); - shrg.hwndClient = hwnd; - shrg.ptDown.x = GET_X_LPARAM(lParam); - shrg.ptDown.y = GET_Y_LPARAM(lParam); - shrg.dwFlags = SHRG_RETURNCMD | SHRG_NOANIMATION; - resolveAygLibs(); - if (ptrRecognizeGesture && (ptrRecognizeGesture(&shrg) == GN_CONTEXTMENU)) { - if (qApp->activePopupWidget()) - qApp->activePopupWidget()->close(); - QContextMenuEvent e(QContextMenuEvent::Mouse, pos, globalPos); - result = qt_sendSpontaneousEvent(alienWidget, &e); + if (alienWidget) { + SHRGINFO shrg; + shrg.cbSize = sizeof(shrg); + shrg.hwndClient = hwnd; + shrg.ptDown.x = GET_X_LPARAM(lParam); + shrg.ptDown.y = GET_Y_LPARAM(lParam); + shrg.dwFlags = SHRG_RETURNCMD | SHRG_NOANIMATION; + resolveAygLibs(); + if (ptrRecognizeGesture && (ptrRecognizeGesture(&shrg) == GN_CONTEXTMENU)) { + if (qApp->activePopupWidget()) + qApp->activePopupWidget()->close(); + QContextMenuEvent e(QContextMenuEvent::Mouse, pos, globalPos); + result = qt_sendSpontaneousEvent(alienWidget, &e); + } } } } -- cgit v0.12 From 0f0fc963a7f1691038ee36a27bb63ff3165eefba Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Mon, 25 May 2009 16:45:57 +0200 Subject: BT:Fix a clipping issue in tabbar tabs On XP and Vista where tabs use taboverlap, the currently dragged would loose the outline. We need to compensate for the taboverlap when creating the draggable widget, otherwise the outline will be clipped. Task-number: 254453 Reviewed-by: nrc --- src/gui/widgets/qtabbar.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/gui/widgets/qtabbar.cpp b/src/gui/widgets/qtabbar.cpp index 69221ba..785d772 100644 --- a/src/gui/widgets/qtabbar.cpp +++ b/src/gui/widgets/qtabbar.cpp @@ -1536,9 +1536,10 @@ void QTabBar::paintEvent(QPaintEvent *) } if (!d->dragInProgress) p.drawControl(QStyle::CE_TabBarTab, tab); - else - d->movingTab->setGeometry(tab.rect); - + else { + int taboverlap = style()->pixelMetric(QStyle::PM_TabBarTabOverlap, 0, this); + d->movingTab->setGeometry(tab.rect.adjusted(-taboverlap, 0, taboverlap, 0)); + } } // Only draw the tear indicator if necessary. Most of the time we don't need too. @@ -1805,7 +1806,9 @@ void QTabBarPrivate::setupMovableTab() if (!movingTab) movingTab = new QWidget(q); + int taboverlap = q->style()->pixelMetric(QStyle::PM_TabBarTabOverlap, 0 ,q); QRect grabRect = q->tabRect(pressedIndex); + grabRect.adjust(-taboverlap, 0, taboverlap, 0); QPixmap grabImage(grabRect.size()); grabImage.fill(Qt::transparent); @@ -1813,7 +1816,7 @@ void QTabBarPrivate::setupMovableTab() QStyleOptionTabV3 tab; q->initStyleOption(&tab, pressedIndex); - tab.rect.moveTopLeft(QPoint(0, 0)); + tab.rect.moveTopLeft(QPoint(taboverlap, 0)); p.drawControl(QStyle::CE_TabBarTab, tab); p.end(); -- cgit v0.12 From 313e2719ac75eb6c6ff2d84f5cef9f70433d5943 Mon Sep 17 00:00:00 2001 From: Maurice Kalinowski Date: Mon, 25 May 2009 16:57:43 +0200 Subject: add deployment rules... WinCE needs those files to be able to do something useful Task-number: 254430 Task-number: 254437 Task-number: 254428 Reviewed-by: joerg BT: yes --- examples/itemviews/puzzle/puzzle.pro | 5 +++++ examples/qtconcurrent/imagescaling/imagescaling.pro | 2 ++ examples/widgets/movie/movie.pro | 8 ++++++++ 3 files changed, 15 insertions(+) diff --git a/examples/itemviews/puzzle/puzzle.pro b/examples/itemviews/puzzle/puzzle.pro index deed112..4f5aaad 100644 --- a/examples/itemviews/puzzle/puzzle.pro +++ b/examples/itemviews/puzzle/puzzle.pro @@ -12,3 +12,8 @@ target.path = $$[QT_INSTALL_EXAMPLES]/itemviews/puzzle sources.files = $$SOURCES $$HEADERS $$RESOURCES *.pro *.jpg sources.path = $$[QT_INSTALL_EXAMPLES]/itemviews/puzzle INSTALLS += target sources + +wince* { + DEPLOYMENT_PLUGIN += qjpeg qgif qtiff +} + diff --git a/examples/qtconcurrent/imagescaling/imagescaling.pro b/examples/qtconcurrent/imagescaling/imagescaling.pro index fbf864a..0a25efb 100644 --- a/examples/qtconcurrent/imagescaling/imagescaling.pro +++ b/examples/qtconcurrent/imagescaling/imagescaling.pro @@ -11,3 +11,5 @@ target.path = $$[QT_INSTALL_EXAMPLES]/qtconcurrent/imagescaling sources.files = $$SOURCES $$HEADERS $$FORMS $$RESOURCES *.pro *.png sources.path = $$[QT_INSTALL_EXAMPLES]/qtconcurrent/imagescaling INSTALLS += target sources + +wince*: DEPLOYMENT_PLUGIN += qgif qjpeg qtiff diff --git a/examples/widgets/movie/movie.pro b/examples/widgets/movie/movie.pro index 1c7cbae..6aa5780 100644 --- a/examples/widgets/movie/movie.pro +++ b/examples/widgets/movie/movie.pro @@ -7,3 +7,11 @@ target.path = $$[QT_INSTALL_EXAMPLES]/widgets/movie sources.files = $$SOURCES $$HEADERS $$RESOURCES movie.pro animation.mng sources.path = $$[QT_INSTALL_EXAMPLES]/widgets/movie INSTALLS += target sources + +wince*: { + addFiles.sources += *.mng + addFiles.path = . + DEPLOYMENT += addFiles + DEPLOYMENT_PLUGIN += qmng +} + -- cgit v0.12 From ac2ea04e516fa7818cb7b4dbe7dd2619cec9fbda Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 25 May 2009 17:02:09 +0200 Subject: Some refactoring of windows specific code + a private class of animations --- src/corelib/animation/qabstractanimation.cpp | 26 ----------------- src/corelib/animation/qabstractanimation_p.h | 24 ++++++++++++---- src/corelib/kernel/qcoreapplication_win.cpp | 31 ++++++++++++++------ src/corelib/kernel/qeventdispatcher_win.cpp | 7 ----- src/corelib/tools/qbytearray.cpp | 2 +- src/corelib/tools/qlocale.cpp | 4 +-- src/gui/kernel/qapplication_win.cpp | 42 ++++++++-------------------- src/gui/kernel/qwindowdefs_win.h | 2 +- 8 files changed, 56 insertions(+), 82 deletions(-) diff --git a/src/corelib/animation/qabstractanimation.cpp b/src/corelib/animation/qabstractanimation.cpp index 94a94d1..16307e6 100644 --- a/src/corelib/animation/qabstractanimation.cpp +++ b/src/corelib/animation/qabstractanimation.cpp @@ -188,32 +188,6 @@ void QUnifiedTimer::updateRecentlyStartedAnimations() animationsToStart.clear(); } -/* - defines the timing interval. Default is DEFAULT_TIMER_INTERVAL -*/ -void QUnifiedTimer::setTimingInterval(int interval) -{ - timingInterval = interval; - if (animationTimer.isActive()) { - //we changed the timing interval - animationTimer.start(timingInterval, this); - } -} - -/* - this allows to have a consistent timer interval at each tick from the timer - not taking the real time that passed into account. -*/ -void QUnifiedTimer::setConsistentTiming(bool b) -{ - consistentTiming = b; -} - -int QUnifiedTimer::elapsedTime() const -{ - return lastTick; -} - void QUnifiedTimer::timerEvent(QTimerEvent *event) { //this is simply the time we last received a tick diff --git a/src/corelib/animation/qabstractanimation_p.h b/src/corelib/animation/qabstractanimation_p.h index e64554c..7a4bfcf 100644 --- a/src/corelib/animation/qabstractanimation_p.h +++ b/src/corelib/animation/qabstractanimation_p.h @@ -101,21 +101,35 @@ private: }; -class Q_CORE_EXPORT QUnifiedTimer : public QObject +class QUnifiedTimer : public QObject { private: QUnifiedTimer(); public: - static QUnifiedTimer *instance(); + //XXX this is needed by dui + static Q_CORE_EXPORT QUnifiedTimer *instance(); void registerAnimation(QAbstractAnimation *animation); void unregisterAnimation(QAbstractAnimation *animation); - void setTimingInterval(int interval); - void setConsistentTiming(bool consistent); + //defines the timing interval. Default is DEFAULT_TIMER_INTERVAL + void setTimingInterval(int interval) + { + timingInterval = interval; + if (animationTimer.isActive()) { + //we changed the timing interval + animationTimer.start(timingInterval, this); + } + } + + /* + this allows to have a consistent timer interval at each tick from the timer + not taking the real time that passed into account. + */ + void setConsistentTiming(bool consistent) { consistentTiming = consistent; } - int elapsedTime() const; + int elapsedTime() const { return lastTick; } protected: void timerEvent(QTimerEvent *); diff --git a/src/corelib/kernel/qcoreapplication_win.cpp b/src/corelib/kernel/qcoreapplication_win.cpp index 7ab91c9..9868c23 100644 --- a/src/corelib/kernel/qcoreapplication_win.cpp +++ b/src/corelib/kernel/qcoreapplication_win.cpp @@ -51,12 +51,11 @@ QT_BEGIN_NAMESPACE -// ############### DON'T EXPORT HERE!!! -Q_CORE_EXPORT char appFileName[MAX_PATH+1]; // application file name -Q_CORE_EXPORT char theAppName[MAX_PATH+1]; // application name -Q_CORE_EXPORT HINSTANCE appInst = 0; // handle to app instance -Q_CORE_EXPORT HINSTANCE appPrevInst = 0; // handle to prev app instance -Q_CORE_EXPORT int appCmdShow = 0; +char appFileName[MAX_PATH+1]; // application file name +char theAppName[MAX_PATH+1]; // application name +HINSTANCE appInst = 0; // handle to app instance +HINSTANCE appPrevInst = 0; // handle to prev app instance +int appCmdShow = 0; bool usingWinMain = false; // whether the qWinMain() is used or not Q_CORE_EXPORT HINSTANCE qWinAppInst() // get Windows app handle @@ -69,6 +68,12 @@ Q_CORE_EXPORT HINSTANCE qWinAppPrevInst() // get Windows prev app return appPrevInst; } +Q_CORE_EXPORT int qWinAppCmdShow() // get main window show command +{ + return appCmdShow; +} + + void set_winapp_name() { static bool already_set = false; @@ -89,6 +94,14 @@ void set_winapp_name() int l = qstrlen(theAppName); if ((l > 4) && !qstricmp(theAppName + l - 4, ".exe")) theAppName[l-4] = '\0'; // drop .exe extension + + if (appInst == 0) { + QT_WA({ + appInst = GetModuleHandle(0); + }, { + appInst = GetModuleHandleA(0); + }); + } } } @@ -173,14 +186,14 @@ void qWinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdParam, // Create command line - set_winapp_name(); - argv = qWinCmdLine(cmdParam, int(strlen(cmdParam)), argc); // Get Windows parameters appInst = instance; appPrevInst = prevInstance; appCmdShow = cmdShow; + + set_winapp_name(); } /*! @@ -618,7 +631,7 @@ QString valueCheck(uint actual, ...) #ifdef Q_CC_BOR -Q_CORE_EXPORT QString decodeMSG(const MSG& msg) +QString decodeMSG(const MSG& msg) { return QString::fromLatin1("THis is not supported on Borland"); } diff --git a/src/corelib/kernel/qeventdispatcher_win.cpp b/src/corelib/kernel/qeventdispatcher_win.cpp index c4061f4..2dd5534 100644 --- a/src/corelib/kernel/qeventdispatcher_win.cpp +++ b/src/corelib/kernel/qeventdispatcher_win.cpp @@ -396,13 +396,6 @@ Q_CORE_EXPORT bool winPostMessage(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lPa { return PostMessageA(hWnd, msg, wParam, lParam); }); } -Q_CORE_EXPORT bool winGetMessage(MSG* msg, HWND hWnd, UINT wMsgFilterMin, - UINT wMsgFilterMax) -{ - QT_WA({ return GetMessage(msg, hWnd, wMsgFilterMin, wMsgFilterMax); } , - { return GetMessageA(msg, hWnd, wMsgFilterMin, wMsgFilterMax); }); -} - // This function is called by a workerthread void WINAPI CALLBACK qt_fast_timer_proc(uint timerId, uint /*reserved*/, DWORD_PTR user, DWORD_PTR /*reserved*/, DWORD_PTR /*reserved*/) { diff --git a/src/corelib/tools/qbytearray.cpp b/src/corelib/tools/qbytearray.cpp index 6aa35f3..49dd52d 100644 --- a/src/corelib/tools/qbytearray.cpp +++ b/src/corelib/tools/qbytearray.cpp @@ -579,7 +579,7 @@ static inline char qToLower(char c) return c; } -Q_CORE_EXPORT QByteArray::Data QByteArray::shared_null = {Q_BASIC_ATOMIC_INITIALIZER(1), +QByteArray::Data QByteArray::shared_null = {Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0, shared_null.array, {0} }; QByteArray::Data QByteArray::shared_empty = { Q_BASIC_ATOMIC_INITIALIZER(1), 0, 0, shared_empty.array, {0} }; diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp index 23c6ffb..248137a 100644 --- a/src/corelib/tools/qlocale.cpp +++ b/src/corelib/tools/qlocale.cpp @@ -120,7 +120,7 @@ static char *_qdtoa( NEEDS_VOLATILE double d, int mode, int ndigits, int *decpt, Q_CORE_EXPORT char *qdtoa(double d, int mode, int ndigits, int *decpt, int *sign, char **rve, char **digits_str); Q_CORE_EXPORT double qstrtod(const char *s00, char const **se, bool *ok); -Q_CORE_EXPORT qlonglong qstrtoll(const char *nptr, const char **endptr, register int base, bool *ok); +static qlonglong qstrtoll(const char *nptr, const char **endptr, register int base, bool *ok); static qulonglong qstrtoull(const char *nptr, const char **endptr, register int base, bool *ok); /****************************************************************************** @@ -4671,7 +4671,7 @@ static qulonglong qstrtoull(const char *nptr, const char **endptr, register int * Ignores `locale' stuff. Assumes that the upper and lower case * alphabets and digits are each contiguous. */ -Q_CORE_EXPORT qlonglong qstrtoll(const char *nptr, const char **endptr, register int base, bool *ok) +static qlonglong qstrtoll(const char *nptr, const char **endptr, register int base, bool *ok) { register const char *s; register qulonglong acc; diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 6237657..77625de 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -376,11 +376,6 @@ QRgb qt_colorref2qrgb(COLORREF col) Internal variables and functions *****************************************************************************/ -extern Q_CORE_EXPORT char theAppName[]; -extern Q_CORE_EXPORT char appFileName[]; -extern Q_CORE_EXPORT HINSTANCE appInst; // handle to app instance -extern Q_CORE_EXPORT HINSTANCE appPrevInst; // handle to prev app instance -extern Q_CORE_EXPORT int appCmdShow; // main window show command static HWND curWin = 0; // current window static HDC displayDC = 0; // display device context @@ -752,20 +747,11 @@ void qt_init(QApplicationPrivate *priv, int) priv->argc = j; } - // Get the application name/instance if qWinMain() was not invoked #ifndef Q_WS_WINCE // No message boxes but important ones SetErrorMode(SetErrorMode(0) | SEM_FAILCRITICALERRORS|SEM_NOOPENFILEERRORBOX); #endif - if (appInst == 0) { - QT_WA({ - appInst = GetModuleHandle(0); - }, { - appInst = GetModuleHandleA(0); - }); - } - #ifndef Q_WS_WINCE // Initialize OLE/COM // S_OK means success and S_FALSE means that it has already @@ -790,7 +776,7 @@ void qt_init(QApplicationPrivate *priv, int) #ifndef QT_NO_CURSOR QCursorData::initialize(); #endif - qApp->setObjectName(QLatin1String(theAppName)); + qApp->setObjectName(priv->appName()); #if !defined(Q_WS_WINCE) // default font @@ -888,12 +874,6 @@ void qt_cleanup() Platform specific global and internal functions *****************************************************************************/ -Q_GUI_EXPORT int qWinAppCmdShow() // get main window show command -{ - return appCmdShow; -} - - Q_GUI_EXPORT HDC qt_win_display_dc() // get display DC { Q_ASSERT(qApp && qApp->thread() == QThread::currentThread()); @@ -989,11 +969,11 @@ const QString qt_reg_winclass(QWidget *w) // register window class if (classExists == -1) { QT_WA({ WNDCLASS wcinfo; - classExists = GetClassInfo((HINSTANCE)qWinAppInst(), (TCHAR*)cname.utf16(), &wcinfo); + classExists = GetClassInfo(qWinAppInst(), (TCHAR*)cname.utf16(), &wcinfo); classExists = classExists && wcinfo.lpfnWndProc != QtWndProc; }, { WNDCLASSA wcinfo; - classExists = GetClassInfoA((HINSTANCE)qWinAppInst(), cname.toLatin1(), &wcinfo); + classExists = GetClassInfoA(qWinAppInst(), cname.toLatin1(), &wcinfo); classExists = classExists && wcinfo.lpfnWndProc != QtWndProc; }); } @@ -1013,9 +993,9 @@ const QString qt_reg_winclass(QWidget *w) // register window class wc.lpfnWndProc = (WNDPROC)QtWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; - wc.hInstance = (HINSTANCE)qWinAppInst(); + wc.hInstance = qWinAppInst(); if (icon) { - wc.hIcon = LoadIcon(appInst, L"IDI_ICON1"); + wc.hIcon = LoadIcon(qWinAppInst(), L"IDI_ICON1"); if (!wc.hIcon) wc.hIcon = LoadIcon(0, IDI_APPLICATION); } else { @@ -1032,9 +1012,9 @@ const QString qt_reg_winclass(QWidget *w) // register window class wc.lpfnWndProc = (WNDPROC)QtWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; - wc.hInstance = (HINSTANCE)qWinAppInst(); + wc.hInstance = qWinAppInst(); if (icon) { - wc.hIcon = LoadIconA(appInst, (char*)"IDI_ICON1"); + wc.hIcon = LoadIconA(qWinAppInst(), (char*)"IDI_ICON1"); if (!wc.hIcon) wc.hIcon = LoadIconA(0, (char*)IDI_APPLICATION); } else { @@ -1053,9 +1033,9 @@ const QString qt_reg_winclass(QWidget *w) // register window class wc.lpfnWndProc = (WNDPROC)QtWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; - wc.hInstance = (HINSTANCE)qWinAppInst(); + wc.hInstance = qWinAppInst(); if (icon) { - wc.hIcon = LoadIcon(appInst, L"IDI_ICON1"); + wc.hIcon = LoadIcon(qWinAppInst(), L"IDI_ICON1"); // if (!wc.hIcon) // wc.hIcon = LoadIcon(0, IDI_APPLICATION); } else { @@ -1089,9 +1069,9 @@ static void unregWinClasses() QHash::ConstIterator it = hash->constBegin(); while (it != hash->constEnd()) { QT_WA({ - UnregisterClass((TCHAR*)it.key().utf16(), (HINSTANCE)qWinAppInst()); + UnregisterClass((TCHAR*)it.key().utf16(), qWinAppInst()); } , { - UnregisterClassA(it.key().toLatin1(), (HINSTANCE)qWinAppInst()); + UnregisterClassA(it.key().toLatin1(), qWinAppInst()); }); ++it; } diff --git a/src/gui/kernel/qwindowdefs_win.h b/src/gui/kernel/qwindowdefs_win.h index 3899c23..a24afd4 100644 --- a/src/gui/kernel/qwindowdefs_win.h +++ b/src/gui/kernel/qwindowdefs_win.h @@ -122,7 +122,7 @@ QT_BEGIN_NAMESPACE Q_CORE_EXPORT HINSTANCE qWinAppInst(); Q_CORE_EXPORT HINSTANCE qWinAppPrevInst(); -Q_GUI_EXPORT int qWinAppCmdShow(); +Q_CORE_EXPORT int qWinAppCmdShow(); Q_GUI_EXPORT HDC qt_win_display_dc(); QT_END_NAMESPACE -- cgit v0.12 From 7dbc1327c513823631986ecaea9b2bae8efc53fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thorbj=C3=B8rn=20Lindeijer?= Date: Mon, 25 May 2009 17:20:06 +0200 Subject: Fixed insertion of unnecessary spaces at the end of attribute lists Also makes QDomDocument::toString() consistent with QXmlStreamWriter and xmlTextWriter from libxml2. Reviewed-by: Thiago Macieira --- src/xml/dom/qdom.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/xml/dom/qdom.cpp b/src/xml/dom/qdom.cpp index 550abc9..dc6ff92 100644 --- a/src/xml/dom/qdom.cpp +++ b/src/xml/dom/qdom.cpp @@ -2694,7 +2694,7 @@ void QDomNode::save(QTextStream& str, int indent) const If the document contains invalid XML characters or characters that cannot be encoded in the given encoding, the result and behavior is undefined. - \since 4.2 + \since 4.2 */ void QDomNode::save(QTextStream& str, int indent, EncodingPolicy encodingPolicy) const { @@ -4597,9 +4597,9 @@ void QDomElementPrivate::save(QTextStream& s, int depth, int indent) const /* Write out attributes. */ if (!m_attr->map.isEmpty()) { - s << ' '; QHash::const_iterator it = m_attr->map.constBegin(); for (; it != m_attr->map.constEnd(); ++it) { + s << ' '; if (it.value()->namespaceURI.isNull()) { s << it.value()->name << "=\"" << encodeText(it.value()->value, s, true, true) << '\"'; } else { @@ -4622,7 +4622,6 @@ void QDomElementPrivate::save(QTextStream& s, int depth, int indent) const outputtedPrefixes.insert(it.value()->prefix); } } - s << ' '; } } -- cgit v0.12 From a731cb5c1765bc3ab71469e86ec0533e5a5c18a5 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Mon, 25 May 2009 17:40:35 +0200 Subject: don't build examples/qtconcurrent/qtconcurrent.pro by default on Win CE This examples doesn't make much sense on most Windows CE devices. Task-number: 254433 Reviewed-by: mauricek BT: yes --- examples/qtconcurrent/qtconcurrent.pro | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/examples/qtconcurrent/qtconcurrent.pro b/examples/qtconcurrent/qtconcurrent.pro index 53008f0..5d73533 100644 --- a/examples/qtconcurrent/qtconcurrent.pro +++ b/examples/qtconcurrent/qtconcurrent.pro @@ -1,10 +1,13 @@ TEMPLATE = subdirs SUBDIRS = imagescaling \ map \ - progressdialog \ runfunction \ wordcount +!wince* { + SUBDIRS += progressdialog +} + # install target.path = $$[QT_INSTALL_EXAMPLES]/qtconcurrent sources.files = $$SOURCES $$HEADERS $$RESOURCES $$FORMS qtconcurrent.pro README -- cgit v0.12 From 81a387e7a7136545db39dc536dee739c67c94e6f Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Mon, 25 May 2009 18:03:18 +0200 Subject: Fix all docs warnings and add since 4.6 to new methods Reviewed-by:TrustMe --- src/gui/image/qpixmapcache.cpp | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/gui/image/qpixmapcache.cpp b/src/gui/image/qpixmapcache.cpp index 31d29d6..3cfc191 100644 --- a/src/gui/image/qpixmapcache.cpp +++ b/src/gui/image/qpixmapcache.cpp @@ -128,6 +128,11 @@ bool QPixmapCache::Key::operator ==(const Key &key) const } /*! + \fn bool QPixmapCache::Key::operator !=(const Key &key) const + \internal +*/ + +/*! \internal */ QPixmapCache::Key &QPixmapCache::Key::operator =(const Key &other) @@ -431,8 +436,10 @@ bool QPixmapCache::find(const QString &key, QPixmap& pixmap) /*! Looks for a cached pixmap associated with the \a key in the cache. - If the pixmap is found, the function sets \a pm to that pixmap and - returns true; otherwise it leaves \a pm alone and returns false. + If the pixmap is found, the function sets \a pixmap to that pixmap and + returns true; otherwise it leaves \a pixmap alone and returns false. + + \since 4.6 Example: \snippet doc/src/snippets/code/src_gui_image_qpixmapcache.cpp 1 @@ -448,10 +455,12 @@ bool QPixmapCache::find(const QString &key, QPixmap* pixmap) /*! Looks for a cached pixmap associated with the \a key in the cache. - If the pixmap is found, the function sets \a pm to that pixmap and - returns true; otherwise it leaves \a pm alone and returns false. If + If the pixmap is found, the function sets \a pixmap to that pixmap and + returns true; otherwise it leaves \a pixmap alone and returns false. If the pixmap is not found, it means that the \a key is not valid anymore, so it will be released for the next insertion. + + \since 4.6 */ bool QPixmapCache::find(const Key &key, QPixmap* pixmap) { @@ -465,7 +474,7 @@ bool QPixmapCache::find(const Key &key, QPixmap* pixmap) } /*! - Inserts a copy of the pixmap \a pm associated with the \a key into + Inserts a copy of the pixmap \a pixmap associated with the \a key into the cache. All pixmaps inserted by the Qt library have a key starting with @@ -490,7 +499,7 @@ bool QPixmapCache::insert(const QString &key, const QPixmap &pixmap) } /*! - Inserts a copy of the pixmap \a pm into + Inserts a copy of the pixmap \a pixmap into the cache and return you the key. When a pixmap is inserted and the cache is about to exceed its @@ -501,6 +510,8 @@ bool QPixmapCache::insert(const QString &key, const QPixmap &pixmap) deleted when more space is needed. \sa setCacheLimit(), replace() + + \since 4.6 */ QPixmapCache::Key QPixmapCache::insert(const QPixmap &pixmap) { @@ -509,10 +520,12 @@ QPixmapCache::Key QPixmapCache::insert(const QPixmap &pixmap) /*! Replace the pixmap associated to the \a key into - the cache. It return true if the pixmap \a pm has been correctly + the cache. It return true if the pixmap \a pixmap has been correctly inserted into the cache false otherwise. \sa setCacheLimit(), insert() + + \since 4.6 */ bool QPixmapCache::replace(const Key &key, const QPixmap &pixmap) { @@ -562,6 +575,8 @@ void QPixmapCache::remove(const QString &key) /*! Removes the pixmap associated with \a key from the cache and release the key for a future insertion. + + \since 4.6 */ void QPixmapCache::remove(const Key &key) { -- cgit v0.12 From 305ce9ea67c11826d91c032ead55edfd5e15462f Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Mon, 25 May 2009 18:10:08 +0200 Subject: fix warning in QtSvg if qreal == float Reviewed-by: mauricek --- src/svg/qsvggenerator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/svg/qsvggenerator.cpp b/src/svg/qsvggenerator.cpp index e822da5..fd4c875 100644 --- a/src/svg/qsvggenerator.cpp +++ b/src/svg/qsvggenerator.cpp @@ -261,7 +261,7 @@ public: constantAlpha &= (stops.at(i).second.alpha() == alpha); if (!constantAlpha) { - const qreal spacing = 0.02; + const qreal spacing = qreal(0.02); QGradientStops newStops; QRgb fromColor = PREMUL(stops.at(0).second.rgba()); QRgb toColor; -- cgit v0.12 From 3868c7dacde57c3e929ad72b9c9c42f8ddf4dc62 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Mon, 25 May 2009 18:42:16 +0200 Subject: BT: Namespace compile fixes. This broke again. I Need to get a way to automate this, I'll discuss with QA. --- src/gui/kernel/qcocoaapplicationdelegate_mac.mm | 2 +- src/gui/kernel/qcocoaview_mac_p.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/gui/kernel/qcocoaapplicationdelegate_mac.mm b/src/gui/kernel/qcocoaapplicationdelegate_mac.mm index 9a24645..2ca6a3d 100644 --- a/src/gui/kernel/qcocoaapplicationdelegate_mac.mm +++ b/src/gui/kernel/qcocoaapplicationdelegate_mac.mm @@ -90,6 +90,7 @@ QT_BEGIN_NAMESPACE extern void onApplicationChangedActivation(bool); // qapplication_mac.mm +extern void qt_release_apple_event_handler(); //qapplication_mac.mm QT_END_NAMESPACE QT_FORWARD_DECLARE_CLASS(QDesktopWidgetImplementation) @@ -207,7 +208,6 @@ static void cleanupCocoaApplicationDelegate() { Q_UNUSED(aNotification); inLaunch = false; - extern void qt_release_apple_event_handler(); //qapplication_mac.mm qt_release_apple_event_handler(); } diff --git a/src/gui/kernel/qcocoaview_mac_p.h b/src/gui/kernel/qcocoaview_mac_p.h index 983c762..527b1a6 100644 --- a/src/gui/kernel/qcocoaview_mac_p.h +++ b/src/gui/kernel/qcocoaview_mac_p.h @@ -59,6 +59,7 @@ QT_FORWARD_DECLARE_CLASS(QWidgetPrivate); QT_FORWARD_DECLARE_CLASS(QWidget); QT_FORWARD_DECLARE_CLASS(QEvent); QT_FORWARD_DECLARE_CLASS(QCocoaDropData); +QT_FORWARD_DECLARE_CLASS(QStringList); QT_BEGIN_NAMESPACE struct DnDParams -- cgit v0.12 From b94416a8fe3fae0e9ab01dea9d5a78a21c4affc0 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 25 May 2009 19:43:12 +0200 Subject: Doc: Fixed terminology. Reviewed-by: Trust Me --- src/corelib/tools/qcryptographichash.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/tools/qcryptographichash.cpp b/src/corelib/tools/qcryptographichash.cpp index 7232626..e438179 100644 --- a/src/corelib/tools/qcryptographichash.cpp +++ b/src/corelib/tools/qcryptographichash.cpp @@ -74,7 +74,7 @@ public: QCryptographicHash can be used to generate cryptographic hashes of binary or text data. - Currently MD4, MD5, and SHA1 are supported. + Currently MD4, MD5, and SHA-1 are supported. */ /*! -- cgit v0.12 From 4bee6cac20b52761f39b139c61d5861fe7b68c6f Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 25 May 2009 19:52:30 +0200 Subject: Doc: Fixed links to resources on the qtsoftware.com Web site. Task-number: 254463 Reviewed-by: Denis Dzyubenko --- doc/src/index.qdoc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/doc/src/index.qdoc b/doc/src/index.qdoc index 4ead9e4..5bf3661 100644 --- a/doc/src/index.qdoc +++ b/doc/src/index.qdoc @@ -207,10 +207,10 @@ -- cgit v0.12 From 152d5fb2d97432d92b6b84e6e81c0236d278ac5d Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 25 May 2009 20:00:12 +0200 Subject: Doc: Removed documentation about the non-existent QKeyEvent::standardKey() function. Task-number: 254074 Reviewed-by: Trust Me --- src/gui/kernel/qkeysequence.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/gui/kernel/qkeysequence.cpp b/src/gui/kernel/qkeysequence.cpp index 352d26a..3bcf9e3 100644 --- a/src/gui/kernel/qkeysequence.cpp +++ b/src/gui/kernel/qkeysequence.cpp @@ -629,8 +629,6 @@ const uint QKeySequencePrivate::numberOfKeyBindings = sizeof(QKeySequencePrivate This enum represent standard key bindings. They can be used to assign platform dependent keyboard shortcuts to a QAction. - QKeyEvent also provides the function QKeyEvent::standardKey() to - query if it matches an existing key binding. Note that the key bindings are platform dependent. The currently bound shortcuts can be queried using keyBindings(). -- cgit v0.12 From 675e9e645fb596ae822fb10093bea25a47a78488 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Mon, 25 May 2009 19:54:31 +0200 Subject: remove now unused static function sneak in white space change :) --- tools/linguist/lupdate/java.cpp | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/tools/linguist/lupdate/java.cpp b/tools/linguist/lupdate/java.cpp index 31024f9..658aebf 100644 --- a/tools/linguist/lupdate/java.cpp +++ b/tools/linguist/lupdate/java.cpp @@ -375,22 +375,13 @@ static bool matchString( QString &s ) return true; } -static bool matchInteger( qlonglong *number) -{ - bool matches = (yyTok == Tok_Integer); - if (matches) { - yyTok = getToken(); - *number = yyInteger; - } - return matches; -} - static bool matchStringOrNull(QString &s) { bool matches = matchString(s); if (!matches) { matches = (yyTok == Tok_null); - if (matches) yyTok = getToken(); + if (matches) + yyTok = getToken(); } return matches; } -- cgit v0.12 From ef4c47d8b4dc9b2056541cd29686b0959fd778a4 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Mon, 25 May 2009 19:56:39 +0200 Subject: implement --no-ui-lines option (complementing lupdate) --- tools/linguist/lconvert/main.cpp | 7 +++++++ tools/linguist/shared/translator.cpp | 20 ++++++++++++++++++++ tools/linguist/shared/translator.h | 1 + 3 files changed, 28 insertions(+) diff --git a/tools/linguist/lconvert/main.cpp b/tools/linguist/lconvert/main.cpp index bdc6c9a..52bf91f 100644 --- a/tools/linguist/lconvert/main.cpp +++ b/tools/linguist/lconvert/main.cpp @@ -97,6 +97,8 @@ static int usage(const QStringList &args) " Drop obsolete messages.\n\n" " --no-finished\n" " Drop finished messages.\n\n" + " --no-ui-lines\n" + " Drop line numbers from references to .ui files.\n\n" " --verbose\n" " be a bit more verbose\n\n" "Long options can be specified with only one leading dash, too.\n\n" @@ -129,6 +131,7 @@ int main(int argc, char *argv[]) bool noObsolete = false; bool noFinished = false; bool verbose = false; + bool noUiLines = false; ConversionData cd; Translator tr; @@ -180,6 +183,8 @@ int main(int argc, char *argv[]) noObsolete = true; } else if (args[i] == QLatin1String("-no-finished")) { noFinished = true; + } else if (args[i] == QLatin1String("-no-ui-lines")) { + noUiLines = true; } else if (args[i] == QLatin1String("-verbose")) { verbose = true; } else if (args[i].startsWith(QLatin1Char('-'))) { @@ -224,6 +229,8 @@ int main(int argc, char *argv[]) tr.stripFinishedMessages(); if (dropTranslations) tr.dropTranslations(); + if (noUiLines) + tr.dropUiLines(); if (!tr.save(outFileName, cd, outFormat)) { qWarning("%s", qPrintable(cd.error())); diff --git a/tools/linguist/shared/translator.cpp b/tools/linguist/shared/translator.cpp index 312bb71..c1f242d 100644 --- a/tools/linguist/shared/translator.cpp +++ b/tools/linguist/shared/translator.cpp @@ -416,6 +416,26 @@ void Translator::dropTranslations() } } +void Translator::dropUiLines() +{ + QString uiXt = QLatin1String(".ui"); + QString juiXt = QLatin1String(".jui"); + for (TMM::Iterator it = m_messages.begin(); it != m_messages.end(); ++it) { + QHash have; + QList refs; + foreach (const TranslatorMessage::Reference &itref, it->allReferences()) { + const QString &fn = itref.fileName(); + if (fn.endsWith(uiXt) || fn.endsWith(juiXt)) { + if (++have[fn] == 1) + refs.append(TranslatorMessage::Reference(fn, -1)); + } else { + refs.append(itref); + } + } + it->setReferences(refs); + } +} + QSet Translator::resolveDuplicates() { QSet dups; diff --git a/tools/linguist/shared/translator.h b/tools/linguist/shared/translator.h index 4e97000..3dda41a 100644 --- a/tools/linguist/shared/translator.h +++ b/tools/linguist/shared/translator.h @@ -132,6 +132,7 @@ public: void stripNonPluralForms(); void stripIdenticalSourceTranslations(); void dropTranslations(); + void dropUiLines(); void makeFileNamesAbsolute(const QDir &originalPath); QSet resolveDuplicates(); static void reportDuplicates(const QSet &dupes, -- cgit v0.12 From afcd5b98b1855390e1c5c1308f0beff256391d96 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Mon, 25 May 2009 19:58:02 +0200 Subject: implement --locations option (complementing lupdate) --- tools/linguist/lconvert/main.cpp | 17 +++++++++++++++++ tools/linguist/shared/translator.h | 2 +- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/tools/linguist/lconvert/main.cpp b/tools/linguist/lconvert/main.cpp index 52bf91f..ce17b6f 100644 --- a/tools/linguist/lconvert/main.cpp +++ b/tools/linguist/lconvert/main.cpp @@ -97,6 +97,9 @@ static int usage(const QStringList &args) " Drop obsolete messages.\n\n" " --no-finished\n" " Drop finished messages.\n\n" + " --locations {absolute|relative|none}\n" + " Override how source code references are saved in ts files.\n" + " Default is absolute.\n}n" " --no-ui-lines\n" " Drop line numbers from references to .ui files.\n\n" " --verbose\n" @@ -132,6 +135,7 @@ int main(int argc, char *argv[]) bool noFinished = false; bool verbose = false; bool noUiLines = false; + Translator::LocationsType locations = Translator::DefaultLocations; ConversionData cd; Translator tr; @@ -183,6 +187,17 @@ int main(int argc, char *argv[]) noObsolete = true; } else if (args[i] == QLatin1String("-no-finished")) { noFinished = true; + } else if (args[i] == QLatin1String("-locations")) { + if (++i >= args.size()) + return usage(args); + if (args[i] == QLatin1String("none")) + locations = Translator::NoLocations; + else if (args[i] == QLatin1String("relative")) + locations = Translator::RelativeLocations; + else if (args[i] == QLatin1String("absolute")) + locations = Translator::AbsoluteLocations; + else + return usage(args); } else if (args[i] == QLatin1String("-no-ui-lines")) { noUiLines = true; } else if (args[i] == QLatin1String("-verbose")) { @@ -231,6 +246,8 @@ int main(int argc, char *argv[]) tr.dropTranslations(); if (noUiLines) tr.dropUiLines(); + if (locations != Translator::DefaultLocations) + tr.setLocationsType(locations); if (!tr.save(outFileName, cd, outFormat)) { qWarning("%s", qPrintable(cd.error())); diff --git a/tools/linguist/shared/translator.h b/tools/linguist/shared/translator.h index 3dda41a..5d0549b 100644 --- a/tools/linguist/shared/translator.h +++ b/tools/linguist/shared/translator.h @@ -144,7 +144,7 @@ public: QString languageCode() const { return m_language; } QString sourceLanguageCode() const { return m_sourceLanguage; } - enum LocationsType { NoLocations, RelativeLocations, AbsoluteLocations }; + enum LocationsType { DefaultLocations, NoLocations, RelativeLocations, AbsoluteLocations }; void setLocationsType(LocationsType lt) { m_locationsType = lt; } LocationsType locationsType() const { return m_locationsType; } -- cgit v0.12 From 8b34bd541c6aa201c4d872210228bce8217a5e03 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 25 May 2009 20:10:25 +0200 Subject: Doc: Miscellaneous documentation fixes for Qt 4.5.x and later. Reviewed-by: Trust Me --- doc/src/snippets/picture/picture.cpp | 2 +- src/corelib/tools/qstringlist.cpp | 2 -- src/gui/painting/qpainterpath.cpp | 8 ++++---- src/gui/text/qfontmetrics.cpp | 12 ++++++------ src/network/ssl/qsslcertificate.cpp | 2 +- 5 files changed, 12 insertions(+), 14 deletions(-) diff --git a/doc/src/snippets/picture/picture.cpp b/doc/src/snippets/picture/picture.cpp index 07cedbf..be171c6 100644 --- a/doc/src/snippets/picture/picture.cpp +++ b/doc/src/snippets/picture/picture.cpp @@ -66,7 +66,7 @@ int main() QPicture picture; picture.load("drawing.pic"); // load picture QPainter painter; - painter.begin(&myWidget); // paint in myWidget + painter.begin(&myImage); // paint in myImage painter.drawPicture(0, 0, picture); // draw the picture at (0,0) painter.end(); // painting done //! [1] diff --git a/src/corelib/tools/qstringlist.cpp b/src/corelib/tools/qstringlist.cpp index e22f122..cf1bff8 100644 --- a/src/corelib/tools/qstringlist.cpp +++ b/src/corelib/tools/qstringlist.cpp @@ -621,8 +621,6 @@ int QtPrivate::QStringList_lastIndexOf(const QStringList *that, QRegExp &rx, int the list, searching forward from index position \a from. Returns -1 if no item matched. - By default, this function is case sensitive. - \sa lastIndexOf(), contains(), QList::indexOf() */ diff --git a/src/gui/painting/qpainterpath.cpp b/src/gui/painting/qpainterpath.cpp index 9ce16d3..1b2c4e3 100644 --- a/src/gui/painting/qpainterpath.cpp +++ b/src/gui/painting/qpainterpath.cpp @@ -2695,7 +2695,7 @@ qreal QPainterPath::length() const /*! Returns percentage of the whole path at the specified length \a len. - Note that similarly to other percent methods, the percentage measurment + Note that similarly to other percent methods, the percentage measurement is not linear with regards to the length, if curves are present in the path. When curves are present the percentage argument is mapped to the t parameter of the Bezier equations. @@ -2812,7 +2812,7 @@ static inline QBezier bezierAtT(const QPainterPath &path, qreal t, qreal *starti Returns the point at at the percentage \a t of the current path. The argument \a t has to be between 0 and 1. - Note that similarly to other percent methods, the percentage measurment + Note that similarly to other percent methods, the percentage measurement is not linear with regards to the length, if curves are present in the path. When curves are present the percentage argument is mapped to the t parameter of the Bezier equations. @@ -2843,7 +2843,7 @@ QPointF QPainterPath::pointAtPercent(qreal t) const Positive values for the angles mean counter-clockwise while negative values mean the clockwise direction. Zero degrees is at the 3 o'clock position. - Note that similarly to the other percent methods, the percentage measurment + Note that similarly to the other percent methods, the percentage measurement is not linear with regards to the length if curves are present in the path. When curves are present the percentage argument is mapped to the t parameter of the Bezier equations. @@ -2875,7 +2875,7 @@ qreal QPainterPath::angleAtPercent(qreal t) const Returns the slope of the path at the percentage \a t. The argument \a t has to be between 0 and 1. - Note that similarly to other percent methods, the percentage measurment + Note that similarly to other percent methods, the percentage measurement is not linear with regards to the length, if curves are present in the path. When curves are present the percentage argument is mapped to the t parameter of the Bezier equations. diff --git a/src/gui/text/qfontmetrics.cpp b/src/gui/text/qfontmetrics.cpp index 88d0610..87da628 100644 --- a/src/gui/text/qfontmetrics.cpp +++ b/src/gui/text/qfontmetrics.cpp @@ -670,8 +670,8 @@ QRect QFontMetrics::boundingRect(const QString &text) const Returns the rectangle that is covered by ink if character \a ch were to be drawn at the origin of the coordinate system. - Note that the bounding rectangle may extend to the left of (0, 0), - e.g. for italicized fonts, and that the text output may cover \e + Note that the bounding rectangle may extend to the left of (0, 0) + (e.g., for italicized fonts), and that the text output may cover \e all pixels in the bounding rectangle. For a space character the rectangle will usually be empty. @@ -724,7 +724,7 @@ QRect QFontMetrics::boundingRect(QChar ch) const \o Qt::AlignCenter (== \c{Qt::AlignHCenter | Qt::AlignVCenter}) \o Qt::TextSingleLine ignores newline characters in the text. \o Qt::TextExpandTabs expands tabs (see below) - \o Qt::TextShowMnemonic interprets "&x" as \underline{x}, i.e. underlined. + \o Qt::TextShowMnemonic interprets "&x" as \underline{x}; i.e., underlined. \o Qt::TextWordWrap breaks the text to fit the rectangle. \endlist @@ -781,7 +781,7 @@ QRect QFontMetrics::boundingRect(const QRect &rect, int flags, const QString &te \list \o Qt::TextSingleLine ignores newline characters. \o Qt::TextExpandTabs expands tabs (see below) - \o Qt::TextShowMnemonic interprets "&x" as \underline{x}, i.e. underlined. + \o Qt::TextShowMnemonic interprets "&x" as \underline{x}; i.e., underlined. \o Qt::TextWordBreak breaks the text to fit the rectangle. \endlist @@ -1500,7 +1500,7 @@ QRectF QFontMetricsF::boundingRect(QChar ch) const \o Qt::AlignCenter (== \c{Qt::AlignHCenter | Qt::AlignVCenter}) \o Qt::TextSingleLine ignores newline characters in the text. \o Qt::TextExpandTabs expands tabs (see below) - \o Qt::TextShowMnemonic interprets "&x" as \underline{x}, i.e. underlined. + \o Qt::TextShowMnemonic interprets "&x" as \underline{x}; i.e., underlined. \o Qt::TextWordWrap breaks the text to fit the rectangle. \endlist @@ -1559,7 +1559,7 @@ QRectF QFontMetricsF::boundingRect(const QRectF &rect, int flags, const QString& \list \o Qt::TextSingleLine ignores newline characters. \o Qt::TextExpandTabs expands tabs (see below) - \o Qt::TextShowMnemonic interprets "&x" as \underline{x}, i.e. underlined. + \o Qt::TextShowMnemonic interprets "&x" as \underline{x}; i.e., underlined. \o Qt::TextWordBreak breaks the text to fit the rectangle. \endlist diff --git a/src/network/ssl/qsslcertificate.cpp b/src/network/ssl/qsslcertificate.cpp index a2ba644..7b554dc 100644 --- a/src/network/ssl/qsslcertificate.cpp +++ b/src/network/ssl/qsslcertificate.cpp @@ -267,7 +267,7 @@ QByteArray QSslCertificate::serialNumber() const /*! Returns a cryptographic digest of this certificate. By default, - and MD5 digest will be generated, but you can also specify a + an MD5 digest will be generated, but you can also specify a custom \a algorithm. */ QByteArray QSslCertificate::digest(QCryptographicHash::Algorithm algorithm) const -- cgit v0.12 From 23820c30052ea23ecf2226c300fc4819dd294306 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 25 May 2009 20:13:34 +0200 Subject: Doc: Fixed custom graphics item snippet. As reported on qt-interest: http://lists.trolltech.com/pipermail/qt-interest/2009-May/007036.html Reviewed-by: Trust Me --- doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp index a57de9d..d9e38ed 100644 --- a/doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp +++ b/doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp @@ -6,7 +6,7 @@ public: { qreal penWidth = 1; return QRectF(-10 - penWidth / 2, -10 - penWidth / 2, - 20 + penWidth / 2, 20 + penWidth / 2); + 20 + penWidth, 20 + penWidth); } void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, -- cgit v0.12 From bbefe9e67366151e2286a2ff6bee0d1009b2a12c Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 25 May 2009 20:24:22 +0200 Subject: Doc: Removed the incorrect figures for Thumb builds of libraries. We need to resolve the issues around the use of Thumb code in Qt and automate the building and comparison of libraries. Reviewed-by: Trust Me --- doc/src/installation.qdoc | 2 -- 1 file changed, 2 deletions(-) diff --git a/doc/src/installation.qdoc b/doc/src/installation.qdoc index 925a195..6a689f9 100644 --- a/doc/src/installation.qdoc +++ b/doc/src/installation.qdoc @@ -738,8 +738,6 @@ in the \l{Qt for Windows CE Requirements} document. \header \o Minimal \o Normal \o Minimal \o Normal \o Minimal \o Normal \o Minimal \o Normal \row \o linux-x86-g++ \o GCC 4.2.4 \o 1.7M \o 2.7M \o 3.3M \o 9.9M \o 653K \o 1.1M \o N/A \o 17M \row \o linux-arm-g++ \o GCC 4.1.1 \o 1.9M \o 3.2M \o 4.1M \o 11M \o 507K \o 1.0M \o N/A \o 17M - \row \o linux-arm-g++ (thumb) - \o GCC 4.1.1 \o 1.7M \o 2.8M \o 4.0M \o 9.8M \o 409K \o 796K \o N/A \o 17M \row \o linux-mips-g++ (MIPS32) \o GCC 4.2.4 \o 2.0M \o 3.2M \o 4.5M \o 12M \o 505K \o 1003K \o N/A \o 21M \endtable -- cgit v0.12 From a4ca38bab521e1f0095b9c90c4623ca9d41d219b Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 25 May 2009 20:27:19 +0200 Subject: Doc: Clarified what close(), abort() and disconnectFromHost() really do to the socket connection. (Reviewed - see below.) Also included corrections to the description of how to send SocketError and SocketState values via signals. (Trust me - as part of an earlier revision of the custom types documentation.) Task-number: 222907 Reviewed-by: Andy Shaw --- src/network/socket/qabstractsocket.cpp | 28 ++++++++++++++++++---------- 1 file changed, 18 insertions(+), 10 deletions(-) diff --git a/src/network/socket/qabstractsocket.cpp b/src/network/socket/qabstractsocket.cpp index 336a7e7..4bb12e6 100644 --- a/src/network/socket/qabstractsocket.cpp +++ b/src/network/socket/qabstractsocket.cpp @@ -99,7 +99,7 @@ the client has read the data). Note that Qt does not limit the write buffer size. You can monitor its size by listening to this signal. - + The readyRead() signal is emitted every time a new chunk of data has arrived. bytesAvailable() then returns the number of bytes that are available for reading. Typically, you would connect the @@ -199,9 +199,10 @@ parameter describes the type of error that occurred. QAbstractSocket::SocketError is not a registered metatype, so for queued - connections, you will have to register it with Q_REGISTER_METATYPE. + connections, you will have to register it with Q_DECLARE_METATYPE() and + qRegisterMetaType(). - \sa error(), errorString() + \sa error(), errorString(), {Creating Custom Qt Types} */ /*! @@ -211,9 +212,10 @@ The \a socketState parameter is the new state. QAbstractSocket::SocketState is not a registered metatype, so for queued - connections, you will have to register it with Q_REGISTER_METATYPE. + connections, you will have to register it with Q_REGISTER_METATYPE() and + qRegisterMetaType(). - \sa state() + \sa state(), {Creating Custom Qt Types} */ /*! @@ -1864,9 +1866,9 @@ bool QAbstractSocket::waitForDisconnected(int msecs) } /*! - Aborts the current connection and resets the socket. Unlike - disconnectFromHost(), this function immediately closes the socket, discarding - any pending data in the write buffer. + Aborts the current connection and resets the socket. Unlike disconnectFromHost(), + this function immediately closes the socket, discarding any pending data in the + write buffer. \sa disconnectFromHost(), close() */ @@ -2163,7 +2165,12 @@ void QAbstractSocket::setPeerName(const QString &name) } /*! - Disconnects the socket's connection with the host. + Closes the I/O device for the socket, disconnects the socket's connection with the + host, closes the socket, and resets the name, address, port number and underlying + socket descriptor. + + See QIODevice::close() for a description of the actions that occur when an I/O + device is closed. \sa abort() */ @@ -2456,7 +2463,8 @@ QNetworkProxy QAbstractSocket::proxy() const #endif // QT_NO_NETWORKPROXY #ifdef QT3_SUPPORT -/*! \enum QAbstractSocket::Error +/*! + \enum QAbstractSocket::Error \compat Use QAbstractSocket::SocketError instead. -- cgit v0.12 From 07929fef22cb9cffc059f949e216ec585e0e7466 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Tue, 26 May 2009 09:01:50 +1000 Subject: Switch from QImage to QPixmap, to allow OpenVG optimization. Switch QFxPixmap to use QPixmapCache, not own partial QImage cache. OpenGL prefers QImage for optimization, but that optimization is only partially preserved (QFxPixmap deals ONLY with QPixmap now). Opaque QFxPixmap no longer available. --- src/declarative/canvas/qsimplecanvas.h | 16 -- src/declarative/canvas/qsimplecanvas_opengl.cpp | 6 +- src/declarative/canvas/qsimplecanvas_opengl1.cpp | 8 +- src/declarative/canvas/qsimplecanvasitem.cpp | 6 +- src/declarative/canvas/qsimplecanvasitem.h | 6 +- src/declarative/fx/qfxblendedimage.cpp | 8 +- src/declarative/fx/qfxblendedimage.h | 4 +- src/declarative/fx/qfxhighlightfilter.cpp | 2 +- src/declarative/fx/qfximage.cpp | 37 ++-- src/declarative/fx/qfximage_p.h | 2 +- src/declarative/fx/qfxpainteditem.cpp | 14 +- src/declarative/fx/qfxpainteditem_p.h | 2 +- src/declarative/fx/qfxparticles.cpp | 6 +- src/declarative/fx/qfxpixmap.cpp | 220 +++++++++-------------- src/declarative/fx/qfxpixmap.h | 8 +- src/declarative/fx/qfxrect.cpp | 32 ++-- src/declarative/fx/qfxrect_p.h | 2 +- src/declarative/fx/qfxscalegrid.h | 1 - src/declarative/fx/qfxtext.cpp | 54 +++--- src/declarative/fx/qfxtext_p.h | 8 +- src/declarative/fx/qfxtextedit_p.h | 4 +- src/declarative/fx/qfxwebview.cpp | 2 +- 22 files changed, 180 insertions(+), 268 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvas.h b/src/declarative/canvas/qsimplecanvas.h index 880fae0..1cbd3c7 100644 --- a/src/declarative/canvas/qsimplecanvas.h +++ b/src/declarative/canvas/qsimplecanvas.h @@ -88,27 +88,11 @@ namespace QSimpleCanvasConfig #elif defined(QFX_RENDER_QPAINTER) typedef QTransform Matrix; - typedef QImage Image; inline Matrix transformToMatrix(const QTransform &t) { return t; } inline QTransform matrixToTransform(const Matrix &t) { return t; } - inline bool needConvert(ImageType type, const Image &img) { - QImage::Format f = img.format(); - return !((type == Opaque && f == QImage::Format_RGB16) || - (type == Translucent && f == QImage::Format_ARGB32_Premultiplied)); - } - inline Image convert(ImageType type, const Image &img) { - if (type == Opaque) - return img.convertToFormat(QImage::Format_RGB16); - else - return img.convertToFormat(QImage::Format_ARGB32_Premultiplied); - } - inline Image create(const QSize &s) - { return QImage(s, QImage::Format_ARGB32_Premultiplied); } - inline const Image &toImage(const QImage &i) - { return i; } #endif } diff --git a/src/declarative/canvas/qsimplecanvas_opengl.cpp b/src/declarative/canvas/qsimplecanvas_opengl.cpp index 98f92d7..72f8324 100644 --- a/src/declarative/canvas/qsimplecanvas_opengl.cpp +++ b/src/declarative/canvas/qsimplecanvas_opengl.cpp @@ -416,13 +416,13 @@ QGLShaderProgram *QSimpleCanvasItem::GLPainter::useColorShader(const QColor &col return item->basicShaders()->constantColor(); } -void QSimpleCanvasItem::GLPainter::drawImage(const QPointF &point, +void QSimpleCanvasItem::GLPainter::drawPixmap(const QPointF &point, const GLTexture &texture) { - drawImage(QRectF(point, QSizeF(texture.width(), texture.height())), texture); + drawPixmap(QRectF(point, QSizeF(texture.width(), texture.height())), texture); } -void QSimpleCanvasItem::GLPainter::drawImage(const QRectF &rect, +void QSimpleCanvasItem::GLPainter::drawPixmap(const QRectF &rect, const GLTexture &img) { QGLShaderProgram *shader = useTextureShader(); diff --git a/src/declarative/canvas/qsimplecanvas_opengl1.cpp b/src/declarative/canvas/qsimplecanvas_opengl1.cpp index 3fd8490..6e50ef8 100644 --- a/src/declarative/canvas/qsimplecanvas_opengl1.cpp +++ b/src/declarative/canvas/qsimplecanvas_opengl1.cpp @@ -386,16 +386,16 @@ void QSimpleCanvasPrivate::release(QGLFramebufferObject *) { } -void QSimpleCanvasItem::GLPainter::drawImage(const QPointF &point, +void QSimpleCanvasItem::GLPainter::drawPixmap(const QPointF &point, const GLTexture &texture) { - drawImage(QRectF(point, QSizeF(texture.width(), texture.height())), texture); + drawPixmap(QRectF(point, QSizeF(texture.width(), texture.height())), texture); } -void QSimpleCanvasItem::GLPainter::drawImage(const QRectF &rect, +void QSimpleCanvasItem::GLPainter::drawPixmap(const QRectF &rect, const GLTexture &img) { - qFatal("Cannot call QSimpleCanvasItem::GLPainter::drawImage() when using OpenGL ES 1.1"); + qFatal("Cannot call QSimpleCanvasItem::GLPainter::drawPixmap() when using OpenGL ES 1.1"); } QT_END_NAMESPACE diff --git a/src/declarative/canvas/qsimplecanvasitem.cpp b/src/declarative/canvas/qsimplecanvasitem.cpp index 3666b82..f2222a9 100644 --- a/src/declarative/canvas/qsimplecanvasitem.cpp +++ b/src/declarative/canvas/qsimplecanvasitem.cpp @@ -1852,12 +1852,12 @@ QSimpleCanvasItem *QSimpleCanvasItem::findNextFocus(QSimpleCanvasItem *item) return 0; } -QImage QSimpleCanvasItem::string(const QString &str, const QColor &c, const QFont &f) +QPixmap QSimpleCanvasItem::string(const QString &str, const QColor &c, const QFont &f) { QFontMetrics fm(f); QSize size(fm.width(str), fm.height()*(str.count(QLatin1Char('\n'))+1)); //fm.boundingRect(str).size(); - QImage img(size, QImage::Format_ARGB32_Premultiplied); - img.fill(0); + QPixmap img(size); + img.fill(Qt::transparent); QPainter p(&img); p.setPen(c); p.setFont(f); diff --git a/src/declarative/canvas/qsimplecanvasitem.h b/src/declarative/canvas/qsimplecanvasitem.h index cf23fc6..77ac52e 100644 --- a/src/declarative/canvas/qsimplecanvasitem.h +++ b/src/declarative/canvas/qsimplecanvasitem.h @@ -175,8 +175,8 @@ public: QGLShaderProgram *useTextureShader(); QGLShaderProgram *useColorShader(const QColor &); - void drawImage(const QPointF &, const GLTexture &); - void drawImage(const QRectF &, const GLTexture &); + void drawPixmap(const QPointF &, const GLTexture &); + void drawPixmap(const QRectF &, const GLTexture &); private: GLPainter(const GLPainter &); GLPainter &operator=(const GLPainter &); @@ -228,7 +228,7 @@ public: GLBasicShaders *basicShaders() const; - static QImage string(const QString &, const QColor & = Qt::black, const QFont & = QFont()); + static QPixmap string(const QString &, const QColor & = Qt::black, const QFont & = QFont()); protected: virtual void geometryChanged(const QRectF &newGeometry, diff --git a/src/declarative/fx/qfxblendedimage.cpp b/src/declarative/fx/qfxblendedimage.cpp index 79b8e41..56b25ea 100644 --- a/src/declarative/fx/qfxblendedimage.cpp +++ b/src/declarative/fx/qfxblendedimage.cpp @@ -192,9 +192,9 @@ void QFxBlendedImage::paintContents(QPainter &p) } if (_blend < 0.75) - p.drawImage(0, 0, primPix); + p.drawPixmap(0, 0, primPix); else - p.drawImage(0, 0, secPix); + p.drawPixmap(0, 0, secPix); if (_smooth) { p.restore(); @@ -212,8 +212,8 @@ void QFxBlendedImage::paintGLContents(GLPainter &p) if (dirty) { prim.clear(); sec.clear(); - prim.setImage(primPix); - sec.setImage(secPix); + prim.setImage(primPix.toImage()); + sec.setImage(secPix.toImage()); dirty = false; } diff --git a/src/declarative/fx/qfxblendedimage.h b/src/declarative/fx/qfxblendedimage.h index 2fdf15b..352e559 100644 --- a/src/declarative/fx/qfxblendedimage.h +++ b/src/declarative/fx/qfxblendedimage.h @@ -99,8 +99,8 @@ private: GLTexture prim; GLTexture sec; #endif - QFxPixmap primPix; - QFxPixmap secPix; + QPixmap primPix; + QPixmap secPix; }; QML_DECLARE_TYPE(QFxBlendedImage); diff --git a/src/declarative/fx/qfxhighlightfilter.cpp b/src/declarative/fx/qfxhighlightfilter.cpp index a22ad98..32264b1 100644 --- a/src/declarative/fx/qfxhighlightfilter.cpp +++ b/src/declarative/fx/qfxhighlightfilter.cpp @@ -135,7 +135,7 @@ QString QFxHighlightFilter::source() const void QFxHighlightFilter::imageLoaded() { - QImage img = QFxPixmap(d->url); + QPixmap img = QFxPixmap(d->url); #if defined(QFX_RENDER_OPENGL2) if (!img.isNull()) d->tex.setImage(img); diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 064580e..9cbd607 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -141,16 +141,15 @@ QFxImage::~QFxImage() QPixmap QFxImage::pixmap() const { Q_D(const QFxImage); - return d->_pix.pixmap(); + return d->_pix; } void QFxImage::setPixmap(const QPixmap &pix) { Q_D(QFxImage); d->url = QUrl(); - d->_pix.setPixmap(pix); + d->_pix = pix; d->_opaque=false; - d->_pix.setOpaque(false); setImplicitWidth(d->_pix.width()); setImplicitHeight(d->_pix.height()); @@ -255,7 +254,6 @@ void QFxImage::setOpaque(bool o) if (o == d->_opaque) return; d->_opaque = o; - d->_pix.setOpaque(o); update(); } @@ -327,21 +325,21 @@ void QFxImage::paintContents(QPainter &p) p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->_smooth); } - QSimpleCanvasConfig::Image pix = d->_pix; + QPixmap pix = d->_pix; if (d->_tiled) { p.save(); p.setClipRect(0, 0, width(), height(), Qt::IntersectClip); QRect me = QRect(0, 0, width(), height()); - int pw = d->_pix.width(); - int ph = d->_pix.height(); + int pw = pix.width(); + int ph = pix.height(); int yy = 0; while(yy < height()) { int xx = 0; while(xx < width()) { - p.drawImage(xx, yy, d->_pix); + p.drawPixmap(xx, yy, pix); xx += pw; } yy += ph; @@ -355,10 +353,10 @@ void QFxImage::paintContents(QPainter &p) height() / qreal(pix.height())); QTransform old = p.transform(); p.setWorldTransform(scale * old); - p.drawImage(0, 0, pix); + p.drawPixmap(0, 0, pix); p.setWorldTransform(old); } else { - p.drawImage(0, 0, pix); + p.drawPixmap(0, 0, pix); } } else { int sgl = d->_scaleGrid->left(); @@ -378,40 +376,40 @@ void QFxImage::paintContents(QPainter &p) // Upper left if (sgt && sgl) - p.drawImage(QRect(0, 0, sgl, sgt), pix, QRect(0, 0, sgl, sgt)); + p.drawPixmap(QRect(0, 0, sgl, sgt), pix, QRect(0, 0, sgl, sgt)); // Upper middle if (pix.width() - xSide && sgt) - p.drawImage(QRect(sgl, 0, w - xSide, sgt), pix, + p.drawPixmap(QRect(sgl, 0, w - xSide, sgt), pix, QRect(sgl, 0, pix.width() - xSide, sgt)); // Upper right if (sgt && pix.width() - sgr) - p.drawImage(QPoint(w-sgr, 0), pix, + p.drawPixmap(QPoint(w-sgr, 0), pix, QRect(pix.width()-sgr, 0, sgr, sgt)); // Middle left if (sgl && pix.height() - ySide) - p.drawImage(QRect(0, sgt, sgl, h - ySide), pix, + p.drawPixmap(QRect(0, sgt, sgl, h - ySide), pix, QRect(0, sgt, sgl, pix.height() - ySide)); // Middle if (pix.width() - xSide && pix.height() - ySide) - p.drawImage(QRect(sgl, sgt, w - xSide, h - ySide), + p.drawPixmap(QRect(sgl, sgt, w - xSide, h - ySide), pix, QRect(sgl, sgt, pix.width() - xSide, pix.height() - ySide)); // Middle right if (sgr && pix.height() - ySide) - p.drawImage(QRect(w-sgr, sgt, sgr, h - ySide), pix, + p.drawPixmap(QRect(w-sgr, sgt, sgr, h - ySide), pix, QRect(pix.width()-sgr, sgt, sgr, pix.height() - ySide)); // Lower left if (sgl && sgr) - p.drawImage(QPoint(0, h - sgb), pix, + p.drawPixmap(QPoint(0, h - sgb), pix, QRect(0, pix.height() - sgb, sgl, sgb)); // Lower Middle if (pix.width() - xSide && sgb) - p.drawImage(QRect(sgl, h - sgb, w - xSide, sgb), pix, + p.drawPixmap(QRect(sgl, h - sgb, w - xSide, sgb), pix, QRect(sgl, pix.height() - sgb, pix.width() - xSide, sgb)); // Lower Right if (sgr && sgb) - p.drawImage(QPoint(w-sgr, h - sgb), pix, + p.drawPixmap(QPoint(w-sgr, h - sgb), pix, QRect(pix.width()-sgr, pix.height() - sgb, sgr, sgb)); } @@ -947,7 +945,6 @@ void QFxImage::requestFinished() d->status = Error; } d->_pix = QFxPixmap(d->url); - d->_pix.setOpaque(d->_opaque); setOptions(QFxImage::SimpleItem, true); } setImplicitWidth(d->_pix.width()); diff --git a/src/declarative/fx/qfximage_p.h b/src/declarative/fx/qfximage_p.h index 8227ce4..b3cccf9 100644 --- a/src/declarative/fx/qfximage_p.h +++ b/src/declarative/fx/qfximage_p.h @@ -95,7 +95,7 @@ public: } QFxScaleGrid *_scaleGrid; - QFxPixmap _pix; + QPixmap _pix; bool _tiled : 1; bool _smooth : 1; bool _opaque : 1; diff --git a/src/declarative/fx/qfxpainteditem.cpp b/src/declarative/fx/qfxpainteditem.cpp index 4d2e327..7fd74a6 100644 --- a/src/declarative/fx/qfxpainteditem.cpp +++ b/src/declarative/fx/qfxpainteditem.cpp @@ -271,7 +271,7 @@ void QFxPaintedItem::paintGLContents(GLPainter &p) QRect area = d->imagecache[i]->area; if (topaint.contains(area)) { QRectF target(area.x(), area.y(), area.width(), area.height()); - p.drawImage(target.toRect(), d->imagecache[i]->image); + p.drawPixmap(target.toRect(), d->imagecache[i]->image); topaint -= area; d->imagecache[i]->age=0; } else { @@ -303,12 +303,8 @@ void QFxPaintedItem::paintGLContents(GLPainter &p) const QVector rects = bigger.rects(); for (int i = 0; i < rects.count(); ++i) { const QRect &r = rects.at(i); -#if defined(QFX_RENDER_QPAINTER) - QImage img(r.size(),QImage::Format_ARGB32_Premultiplied); -#else - QImage img(r.size(),QImage::Format_ARGB32); -#endif - img.fill(0); + QPixmap img(r.size()); + img.fill(Qt::transparent); { QPainter qp(&img); qp.translate(-r.x(),-r.y()); @@ -317,13 +313,13 @@ void QFxPaintedItem::paintGLContents(GLPainter &p) QFxPaintedItemPrivate::ImageCacheItem *newitem = new QFxPaintedItemPrivate::ImageCacheItem; newitem->area = r; #if defined(QFX_RENDER_QPAINTER) - newitem->image = QSimpleCanvasConfig::Image(QSimpleCanvasConfig::toImage(img)); + newitem->image = img; #else newitem->image.setImage(img); #endif d->imagecache.append(newitem); QRectF target(r.x(), r.y(), r.width(), r.height()); - p.drawImage(target.toRect(), newitem->image); + p.drawPixmap(target.toRect(), newitem->image); } } #if defined(QFX_RENDER_OPENGL2) diff --git a/src/declarative/fx/qfxpainteditem_p.h b/src/declarative/fx/qfxpainteditem_p.h index 5d5da6b..d8d1a2a 100644 --- a/src/declarative/fx/qfxpainteditem_p.h +++ b/src/declarative/fx/qfxpainteditem_p.h @@ -78,7 +78,7 @@ public: int age; QRect area; #if defined(QFX_RENDER_QPAINTER) - QSimpleCanvasConfig::Image image; + QPixmap image; #else GLTexture image; #endif diff --git a/src/declarative/fx/qfxparticles.cpp b/src/declarative/fx/qfxparticles.cpp index 67c1208..83c7694 100644 --- a/src/declarative/fx/qfxparticles.cpp +++ b/src/declarative/fx/qfxparticles.cpp @@ -397,7 +397,7 @@ public: QString source; QUrl url; - QSimpleCanvasConfig::Image image; + QPixmap image; int count; int lifeSpan; int lifeSpanDev; @@ -671,7 +671,7 @@ void QFxParticles::setSource(const QString &name) if (name.isEmpty()) { d->source = name; d->url = QUrl(); - d->image = QSimpleCanvasConfig::Image(); + d->image = QPixmap(); #if defined(QFX_RENDER_OPENGL) d->texDirty = true; d->tex.clear(); @@ -1124,7 +1124,7 @@ void QFxParticlesPainter::paintContents(QPainter &p) for (int i = 0; i < d->particles.count(); ++i) { const QFxParticle &particle = d->particles.at(i); p.setOpacity(particle.opacity); - p.drawImage(particle.x - myX, particle.y - myY, d->image); + p.drawPixmap(particle.x - myX, particle.y - myY, d->image); } update();//Should I need this? (GV does) } diff --git a/src/declarative/fx/qfxpixmap.cpp b/src/declarative/fx/qfxpixmap.cpp index 0e5a10f..0ea94f5 100644 --- a/src/declarative/fx/qfxpixmap.cpp +++ b/src/declarative/fx/qfxpixmap.cpp @@ -42,44 +42,49 @@ #include "qfxpixmap.h" #include #include +#include #include #include #include - QT_BEGIN_NAMESPACE -class QFxPixmapCacheItem; -typedef QHash QFxPixmapCache; -static QFxPixmapCache qfxPixmapCache; +class QSharedNetworkReply; +typedef QHash QFxSharedNetworkReplyHash; +static QFxSharedNetworkReplyHash qfxActiveNetworkReplies; -class QFxPixmapCacheItem +class QSharedNetworkReply { public: - QFxPixmapCacheItem() : reply(0), refCount(1) {} - QString key; + QSharedNetworkReply(QNetworkReply *r) : reply(r), refCount(1) {} + ~QSharedNetworkReply() + { + reply->deleteLater(); + } QNetworkReply *reply; -#if defined(QFX_RENDER_OPENGL) - QImage image; -#else - QImage image; - QImage opaqueImage; -#endif int refCount; - void addRef() { ++refCount; } - void release() { Q_ASSERT(refCount > 0); --refCount; if (refCount == 0) { qfxPixmapCache.remove(key); delete this; } } + void addRef() + { + ++refCount; + } + void release() + { + Q_ASSERT(refCount > 0); + --refCount; + if (refCount == 0) { + QString key = reply->url().toString(); + qfxActiveNetworkReplies.remove(key); + delete this; + } + } }; -static QFxPixmapCacheItem qfxPixmapCacheDummyItem; - class QFxPixmapPrivate { public: - QFxPixmapPrivate() - : opaque(false), pixmap(&qfxPixmapCacheDummyItem) { pixmap->addRef(); } + QFxPixmapPrivate() {} - bool opaque; - QFxPixmapCacheItem *pixmap; + QPixmap pixmap; }; /*! @@ -102,131 +107,71 @@ QFxPixmap::QFxPixmap(const QUrl &url) #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer perf; #endif - QString key = url.toString(); - QFxPixmapCache::Iterator iter = qfxPixmapCache.find(key); - if (iter == qfxPixmapCache.end()) { - qWarning() << "QFxPixmap: URL not loaded" << url; - } else { - QNetworkReply *reply = (*iter)->reply; - if (reply) { - if (reply->error()) { - qWarning() << "Error loading" << url << reply->errorString(); +#ifndef QT_NO_LOCALFILE_OPTIMIZED_QML + if (url.scheme()==QLatin1String("file")) { + d->pixmap.load(url.toLocalFile()); + } else +#endif + { + QString key = url.toString(); + if (!QPixmapCache::find(key,&d->pixmap)) { + QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key); + if (iter == qfxActiveNetworkReplies.end()) { + // API usage error + qWarning() << "QFxPixmap: URL not loaded" << url; } else { - (*iter)->image.load(reply, 0); + if ((*iter)->reply->error()) { + qWarning() << "Network error loading" << url << (*iter)->reply->errorString(); + } else { + QImage img; + if (img.load((*iter)->reply, 0)) { + d->pixmap = QPixmap::fromImage(img); + QPixmapCache::insert(key, d->pixmap); + } else { + qWarning() << "Format error loading" << url; + } + } + (*iter)->release(); } - reply->deleteLater(); - (*iter)->reply = 0; } - (*iter)->addRef(); } - - d->pixmap = *iter; } QFxPixmap::QFxPixmap(const QFxPixmap &o) : d(new QFxPixmapPrivate) { - d->opaque = o.d->opaque; - o.d->pixmap->addRef(); - d->pixmap->release(); d->pixmap = o.d->pixmap; } QFxPixmap::~QFxPixmap() { - d->pixmap->release(); delete d; } QFxPixmap &QFxPixmap::operator=(const QFxPixmap &o) { - d->opaque = o.d->opaque; - o.d->pixmap->addRef(); - d->pixmap->release(); d->pixmap = o.d->pixmap; return *this; } bool QFxPixmap::isNull() const { - return d->pixmap->image.isNull(); -} - -bool QFxPixmap::opaque() const -{ - return d->opaque; -} - -void QFxPixmap::setOpaque(bool o) -{ - d->opaque = o; + return d->pixmap.isNull(); } int QFxPixmap::width() const { - return d->pixmap->image.width(); + return d->pixmap.width(); } int QFxPixmap::height() const { - return d->pixmap->image.height(); -} - -QPixmap QFxPixmap::pixmap() const -{ - return QPixmap::fromImage(d->pixmap->image); + return d->pixmap.height(); } -void QFxPixmap::setPixmap(const QPixmap &pix) +QFxPixmap::operator const QPixmap &() const { - QFxPixmapCache::Iterator iter = qfxPixmapCache.find(QString::number(pix.cacheKey())); - if (iter == qfxPixmapCache.end()) { - QFxPixmapCacheItem *item = new QFxPixmapCacheItem; - item->key = QString::number(pix.cacheKey()); - if (d->pixmap) - d->pixmap->release(); - d->pixmap = item; - d->pixmap->image = pix.toImage(); - qfxPixmapCache.insert(QString::number(pix.cacheKey()), item); - } else { - (*iter)->addRef(); - d->pixmap = *iter; - } - -#if 0 - int size = 0; - for (QFxPixmapCache::Iterator iter = qfxPixmapCache.begin(); iter != qfxPixmapCache.end(); ++iter) { - size += (*iter)->image.width() * (*iter)->image.height(); - } - qWarning() << qfxPixmapCache.count() << size; -#endif -} - -QFxPixmap::operator const QSimpleCanvasConfig::Image &() const -{ -#if defined(QFX_RENDER_OPENGL) - return d->pixmap->image; -#else - if (d->opaque) { - if (!d->pixmap->image.isNull() && d->pixmap->opaqueImage.isNull()) { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif - d->pixmap->opaqueImage = d->pixmap->image.convertToFormat(QPixmap::defaultDepth() == 16 ? - QImage::Format_RGB16 : - QImage::Format_RGB32); - } - return d->pixmap->opaqueImage; - } else { - if (!d->pixmap->image.isNull() && d->pixmap->image.format() != QImage::Format_ARGB32_Premultiplied) { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif - d->pixmap->image = d->pixmap->image.convertToFormat(QImage::Format_ARGB32_Premultiplied); - } - return d->pixmap->image; - } -#endif + return d->pixmap; } /*! @@ -239,37 +184,33 @@ QFxPixmap::operator const QSimpleCanvasConfig::Image &() const */ QNetworkReply *QFxPixmap::get(QmlEngine *engine, const QUrl& url, QObject* obj, const char* slot) { - QString key = url.toString(); - QFxPixmapCache::Iterator iter = qfxPixmapCache.find(key); - if (iter == qfxPixmapCache.end()) { - QFxPixmapCacheItem *item = new QFxPixmapCacheItem; - item->addRef(); // XXX - will never get deleted. Need to revisit caching - item->key = key; #ifndef QT_NO_LOCALFILE_OPTIMIZED_QML - if (url.scheme()==QLatin1String("file")) { - item->image.load(url.toLocalFile(), 0); - } else -#endif - { - QNetworkRequest req(url); - req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); - item->reply = engine->networkAccessManager()->get(req); - } - iter = qfxPixmapCache.insert(item->key, item); - } else { - (*iter)->addRef(); + if (url.scheme()==QLatin1String("file")) { + QObject dummy; + QObject::connect(&dummy, SIGNAL(destroyed()), obj, slot); + return 0; } - if ((*iter)->reply) { - // still loading - QObject::connect((*iter)->reply, SIGNAL(finished()), obj, slot); - return (*iter)->reply; - } else { - // already loaded +#endif + + QString key = url.toString(); + if (QPixmapCache::find(key,0)) { QObject dummy; QObject::connect(&dummy, SIGNAL(destroyed()), obj, slot); + return 0; + } + + QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key); + if (iter == qfxActiveNetworkReplies.end()) { + QNetworkRequest req(url); + req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); + QSharedNetworkReply *item = new QSharedNetworkReply(engine->networkAccessManager()->get(req)); + iter = qfxActiveNetworkReplies.insert(key, item); + } else { + (*iter)->addRef(); } - return 0; + QObject::connect((*iter)->reply, SIGNAL(finished()), obj, slot); + return (*iter)->reply; } /*! @@ -282,12 +223,11 @@ QNetworkReply *QFxPixmap::get(QmlEngine *engine, const QUrl& url, QObject* obj, void QFxPixmap::cancelGet(const QUrl& url, QObject* obj) { QString key = url.toString(); - QFxPixmapCache::Iterator iter = qfxPixmapCache.find(key); - if (iter == qfxPixmapCache.end()) + QFxSharedNetworkReplyHash::Iterator iter = qfxActiveNetworkReplies.find(key); + if (iter == qfxActiveNetworkReplies.end()) return; - if ((*iter)->reply) - QObject::disconnect((*iter)->reply, 0, obj, 0); - // XXX - loading not cancelled. Need to revisit caching + QObject::disconnect((*iter)->reply, 0, obj, 0); + (*iter)->release(); } QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxpixmap.h b/src/declarative/fx/qfxpixmap.h index fd56ee4..ae693c1 100644 --- a/src/declarative/fx/qfxpixmap.h +++ b/src/declarative/fx/qfxpixmap.h @@ -71,16 +71,10 @@ public: bool isNull() const; - bool opaque() const; - void setOpaque(bool); - int width() const; int height() const; - QPixmap pixmap() const; - void setPixmap(const QPixmap &pix); - - operator const QSimpleCanvasConfig::Image &() const; + operator const QPixmap &() const; private: QFxPixmapPrivate *d; diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index f81f9b3..c5ee60b 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -187,7 +187,7 @@ void QFxRect::doUpdate() { #if defined(QFX_RENDER_QPAINTER) Q_D(QFxRect); - d->_rectImage = QSimpleCanvasConfig::Image(); + d->_rectImage = QPixmap(); #endif #if defined(QFX_RENDER_OPENGL) Q_D(QFxRect); @@ -241,7 +241,7 @@ void QFxRect::setRadius(qreal radius) d->_radius = radius; #if defined(QFX_RENDER_QPAINTER) - d->_rectImage = QSimpleCanvasConfig::Image(); + d->_rectImage = QPixmap(); #elif defined(QFX_RENDER_OPENGL) d->_rectTexture.clear(); #endif @@ -287,7 +287,7 @@ void QFxRect::setColor(const QColor &c) d->_color = c; #if defined(QFX_RENDER_QPAINTER) - d->_rectImage = QSimpleCanvasConfig::Image(); + d->_rectImage = QPixmap(); #endif #if defined(QFX_RENDER_OPENGL) d->_rectTexture.clear(); @@ -401,8 +401,8 @@ void QFxRect::generateRoundedRect() Q_D(QFxRect); if (d->_rectImage.isNull()) { const int pw = d->_pen && d->_pen->isValid() ? d->_pen->width() : 0; - d->_rectImage = QImage(d->_radius*2 + 3 + pw*2, d->_radius*2 + 3 + pw*2, QImage::Format_ARGB32_Premultiplied); - d->_rectImage.fill(0); + d->_rectImage = QPixmap(d->_radius*2 + 3 + pw*2, d->_radius*2 + 3 + pw*2); + d->_rectImage.fill(Qt::transparent); QPainter p(&(d->_rectImage)); p.setRenderHint(QPainter::Antialiasing); if (d->_pen && d->_pen->isValid()) { @@ -421,8 +421,8 @@ void QFxRect::generateBorderedRect() Q_D(QFxRect); if (d->_rectImage.isNull()) { const int pw = d->_pen && d->_pen->isValid() ? d->_pen->width() : 0; - d->_rectImage = QImage(d->pen()->width()*2 + 3 + pw*2, d->pen()->width()*2 + 3 + pw*2, QImage::Format_ARGB32_Premultiplied); - d->_rectImage.fill(0); + d->_rectImage = QPixmap(d->pen()->width()*2 + 3 + pw*2, d->pen()->width()*2 + 3 + pw*2); + d->_rectImage.fill(Qt::transparent); QPainter p(&(d->_rectImage)); p.setRenderHint(QPainter::Antialiasing); if (d->_pen && d->_pen->isValid()) { @@ -560,39 +560,39 @@ void QFxRect::drawRect(QPainter &p) } // Upper left - p.drawImage(QRect(-pw/2, -pw/2, xOffset, yOffset), d->_rectImage, QRect(0, 0, xOffset, yOffset)); + p.drawPixmap(QRect(-pw/2, -pw/2, xOffset, yOffset), d->_rectImage, QRect(0, 0, xOffset, yOffset)); // Upper middle if (xMiddles) - p.drawImage(QRect(xOffset-pw/2, -pw/2, width() - xSide + pw, yOffset), d->_rectImage, + p.drawPixmap(QRect(xOffset-pw/2, -pw/2, width() - xSide + pw, yOffset), d->_rectImage, QRect(d->_rectImage.width()/2, 0, 1, yOffset)); // Upper right - p.drawImage(QPoint(width()-xOffset+pw/2, -pw/2), d->_rectImage, + p.drawPixmap(QPoint(width()-xOffset+pw/2, -pw/2), d->_rectImage, QRect(d->_rectImage.width()-xOffset, 0, xOffset, yOffset)); // Middle left if (yMiddles) - p.drawImage(QRect(-pw/2, yOffset-pw/2, xOffset, height() - ySide + pw), d->_rectImage, + p.drawPixmap(QRect(-pw/2, yOffset-pw/2, xOffset, height() - ySide + pw), d->_rectImage, QRect(0, d->_rectImage.height()/2, xOffset, 1)); // Middle if (xMiddles && yMiddles) // XXX paint errors in animation example //p.fillRect(xOffset-pw/2, yOffset-pw/2, width() - xSide + pw, height() - ySide + pw, d->getColor()); - p.drawImage(QRect(xOffset-pw/2, yOffset-pw/2, width() - xSide + pw, height() - ySide + pw), d->_rectImage, + p.drawPixmap(QRect(xOffset-pw/2, yOffset-pw/2, width() - xSide + pw, height() - ySide + pw), d->_rectImage, QRect(d->_rectImage.width()/2, d->_rectImage.height()/2, 1, 1)); // Middle right if (yMiddles) - p.drawImage(QRect(width()-xOffset+pw/2, yOffset-pw/2, xOffset, height() - ySide + pw), d->_rectImage, + p.drawPixmap(QRect(width()-xOffset+pw/2, yOffset-pw/2, xOffset, height() - ySide + pw), d->_rectImage, QRect(d->_rectImage.width()-xOffset, d->_rectImage.height()/2, xOffset, 1)); // Lower left - p.drawImage(QPoint(-pw/2, height() - yOffset + pw/2), d->_rectImage, QRect(0, d->_rectImage.height() - yOffset, xOffset, yOffset)); + p.drawPixmap(QPoint(-pw/2, height() - yOffset + pw/2), d->_rectImage, QRect(0, d->_rectImage.height() - yOffset, xOffset, yOffset)); // Lower Middle if (xMiddles) - p.drawImage(QRect(xOffset-pw/2, height() - yOffset +pw/2, width() - xSide + pw, yOffset), d->_rectImage, + p.drawPixmap(QRect(xOffset-pw/2, height() - yOffset +pw/2, width() - xSide + pw, yOffset), d->_rectImage, QRect(d->_rectImage.width()/2, d->_rectImage.height() - yOffset, 1, yOffset)); // Lower Right - p.drawImage(QPoint(width()-xOffset+pw/2, height() - yOffset+pw/2), d->_rectImage, + p.drawPixmap(QPoint(width()-xOffset+pw/2, height() - yOffset+pw/2), d->_rectImage, QRect(d->_rectImage.width()-xOffset, d->_rectImage.height() - yOffset, xOffset, yOffset)); } } diff --git a/src/declarative/fx/qfxrect_p.h b/src/declarative/fx/qfxrect_p.h index 2fd555f..60eaf1d 100644 --- a/src/declarative/fx/qfxrect_p.h +++ b/src/declarative/fx/qfxrect_p.h @@ -98,7 +98,7 @@ public: QFxPen *_pen; qreal _radius; #if defined(QFX_RENDER_QPAINTER) - QSimpleCanvasConfig::Image _rectImage; + QPixmap _rectImage; #endif }; diff --git a/src/declarative/fx/qfxscalegrid.h b/src/declarative/fx/qfxscalegrid.h index d0f735f..e2bcf88 100644 --- a/src/declarative/fx/qfxscalegrid.h +++ b/src/declarative/fx/qfxscalegrid.h @@ -44,7 +44,6 @@ #include #include -#include #include #include #include diff --git a/src/declarative/fx/qfxtext.cpp b/src/declarative/fx/qfxtext.cpp index 315b451..b7ae50c 100644 --- a/src/declarative/fx/qfxtext.cpp +++ b/src/declarative/fx/qfxtext.cpp @@ -525,42 +525,44 @@ QString QFxText::propertyInfo() const void QFxTextPrivate::drawOutline() { - QImage img = QImage(imgCache.size(), QImage::Format_ARGB32_Premultiplied); + QPixmap img = QPixmap(imgCache.size()); + img.fill(Qt::transparent); + QPainter ppm(&img); - img.fill(qRgba(0, 0, 0, 0)); QPoint pos(imgCache.rect().topLeft()); pos += QPoint(-1, 0); - ppm.drawImage(pos, imgStyleCache); + ppm.drawPixmap(pos, imgStyleCache); pos += QPoint(2, 0); - ppm.drawImage(pos, imgStyleCache); + ppm.drawPixmap(pos, imgStyleCache); pos += QPoint(-1, -1); - ppm.drawImage(pos, imgStyleCache); + ppm.drawPixmap(pos, imgStyleCache); pos += QPoint(0, 2); - ppm.drawImage(pos, imgStyleCache); + ppm.drawPixmap(pos, imgStyleCache); pos += QPoint(0, -1); - QPainter &p = ppm; - p.drawImage(pos, imgCache); + ppm.drawPixmap(pos, imgCache); + ppm.end(); - imgCache = QSimpleCanvasConfig::toImage(img); + imgCache = img; } void QFxTextPrivate::drawOutline(int yOffset) { - QImage img = QImage(imgCache.size(), QImage::Format_ARGB32_Premultiplied); + QPixmap img = QPixmap(imgCache.size()); + img.fill(Qt::transparent); + QPainter ppm(&img); - img.fill(qRgba(0, 0, 0, 0)); QPoint pos(imgCache.rect().topLeft()); pos += QPoint(0, yOffset); - ppm.drawImage(pos, imgStyleCache); + ppm.drawPixmap(pos, imgStyleCache); pos += QPoint(0, -yOffset); - QPainter &p = ppm; - p.drawImage(pos, imgCache); + ppm.drawPixmap(pos, imgCache); + ppm.end(); - imgCache = QSimpleCanvasConfig::toImage(img); + imgCache = img; } QSize QFxTextPrivate::setupTextLayout(QTextLayout *layout) @@ -600,7 +602,7 @@ QSize QFxTextPrivate::setupTextLayout(QTextLayout *layout) return QSize((int)widthUsed, height); } -QImage QFxTextPrivate::wrappedTextImage(bool drawStyle) +QPixmap QFxTextPrivate::wrappedTextImage(bool drawStyle) { //do layout QFont f; if (_font) f = _font->font(); @@ -620,8 +622,8 @@ QImage QFxTextPrivate::wrappedTextImage(bool drawStyle) } //paint text - QImage img(size, QImage::Format_ARGB32_Premultiplied); - img.fill(0); + QPixmap img(size); + img.fill(Qt::transparent); QPainter p(&img); if (drawStyle) { p.setPen(styleColor); @@ -633,13 +635,13 @@ QImage QFxTextPrivate::wrappedTextImage(bool drawStyle) return img; } -QImage QFxTextPrivate::richTextImage(bool drawStyle) +QPixmap QFxTextPrivate::richTextImage(bool drawStyle) { QSize size = doc->size().toSize(); //paint text - QImage img(size, QImage::Format_ARGB32_Premultiplied); - img.fill(0); + QPixmap img(size); + img.fill(Qt::transparent); QPainter p(&img); if (drawStyle) { @@ -667,14 +669,14 @@ void QFxTextPrivate::checkImgCache() bool empty = text.isEmpty(); if (empty) { - imgCache = QSimpleCanvasConfig::Image(); - imgStyleCache = QImage(); + imgCache = QPixmap(); + imgStyleCache = QPixmap(); } else if (richText) { - imgCache = QSimpleCanvasConfig::toImage(richTextImage(false)); + imgCache = richTextImage(false); if (style != QFxText::Normal) imgStyleCache = richTextImage(true); //### should use styleColor } else { - imgCache = QSimpleCanvasConfig::toImage(wrappedTextImage(false)); + imgCache = wrappedTextImage(false); if (style != QFxText::Normal) imgStyleCache = wrappedTextImage(true); //### should use styleColor } @@ -745,7 +747,7 @@ void QFxText::paintContents(QPainter &p) p.save(); p.setClipRect(boundingRect()); } - p.drawImage(x, y, d->imgCache); + p.drawPixmap(x, y, d->imgCache); if (needClip) p.restore(); } diff --git a/src/declarative/fx/qfxtext_p.h b/src/declarative/fx/qfxtext_p.h index 8bb3142..dfaef63 100644 --- a/src/declarative/fx/qfxtext_p.h +++ b/src/declarative/fx/qfxtext_p.h @@ -94,8 +94,8 @@ public: void drawOutline(); void drawOutline(int yOffset); - QImage wrappedTextImage(bool drawStyle); - QImage richTextImage(bool drawStyle); + QPixmap wrappedTextImage(bool drawStyle); + QPixmap richTextImage(bool drawStyle); QSize setupTextLayout(QTextLayout *layout); QString text; @@ -118,8 +118,8 @@ public: #if defined(QFX_RENDER_OPENGL) GLTexture tex; #endif - QSimpleCanvasConfig::Image imgCache; - QImage imgStyleCache; + QPixmap imgCache; + QPixmap imgStyleCache; QFxText::HAlignment hAlign; QFxText::VAlignment vAlign; Qt::TextElideMode elideMode; diff --git a/src/declarative/fx/qfxtextedit_p.h b/src/declarative/fx/qfxtextedit_p.h index 78b0018..9f26b10 100644 --- a/src/declarative/fx/qfxtextedit_p.h +++ b/src/declarative/fx/qfxtextedit_p.h @@ -89,8 +89,8 @@ public: #if defined(QFX_RENDER_OPENGL) GLTexture texture; #endif - QSimpleCanvasConfig::Image imgCache; - QImage imgStyleCache; + QPixmap imgCache; + QPixmap imgStyleCache; QFxTextEdit::HAlignment hAlign; QFxTextEdit::VAlignment vAlign; bool dirty; diff --git a/src/declarative/fx/qfxwebview.cpp b/src/declarative/fx/qfxwebview.cpp index 7998711..0e86249 100644 --- a/src/declarative/fx/qfxwebview.cpp +++ b/src/declarative/fx/qfxwebview.cpp @@ -161,7 +161,7 @@ public: int age; QRect area; #if defined(QFX_RENDER_QPAINTER) - QSimpleCanvasConfig::Image image; + QPixmap image; #else GLTexture image; #endif -- cgit v0.12 From a106ba14b7ed630f5d7941462ba9271dd83acea3 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Tue, 26 May 2009 09:11:05 +1000 Subject: correct path doc --- doc/src/tutorials/declarative.qdoc | 3 --- 1 file changed, 3 deletions(-) diff --git a/doc/src/tutorials/declarative.qdoc b/doc/src/tutorials/declarative.qdoc index 75d0c06..3fad672 100644 --- a/doc/src/tutorials/declarative.qdoc +++ b/doc/src/tutorials/declarative.qdoc @@ -381,10 +381,7 @@ \list \o Any imported directories. These are listed at the start of the file using \c { import "path" }. - \o The run directory - \o The run directory + "/qml" \o the directory of the QML code file - \o the directory of the QML code file + "/qml" \endlist All the properties of the button are -- cgit v0.12 From f8cb8f242817c94a3f368b01243a88918d211f1e Mon Sep 17 00:00:00 2001 From: Ian Walters Date: Tue, 26 May 2009 09:50:16 +1000 Subject: Protect dump function by ifdef. Use the same pattern for protecting the dump function as qmap.h and qhash.h employ. --- src/corelib/tools/qcontiguouscache.cpp | 4 ++++ src/corelib/tools/qcontiguouscache.h | 8 +++++++- 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/corelib/tools/qcontiguouscache.cpp b/src/corelib/tools/qcontiguouscache.cpp index 7db3a5a..996ac18 100644 --- a/src/corelib/tools/qcontiguouscache.cpp +++ b/src/corelib/tools/qcontiguouscache.cpp @@ -40,10 +40,13 @@ ****************************************************************************/ #include "qcontiguouscache.h" +#ifdef QT_QCONTIGUOUSCACHE_DEBUG #include +#endif QT_BEGIN_NAMESPACE +#ifdef QT_QCONTIGUOUSCACHE_DEBUG void QContiguousCacheData::dump() const { qDebug() << "capacity:" << alloc; @@ -51,6 +54,7 @@ void QContiguousCacheData::dump() const qDebug() << "start:" << start; qDebug() << "offset:" << offset; } +#endif /*! \class QContiguousCache \brief The QContiguousCache class is a template class that provides a contiguous cache. diff --git a/src/corelib/tools/qcontiguouscache.h b/src/corelib/tools/qcontiguouscache.h index 5cd1582..2437f63 100644 --- a/src/corelib/tools/qcontiguouscache.h +++ b/src/corelib/tools/qcontiguouscache.h @@ -49,8 +49,10 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE +#undef QT_QCONTIGUOUSCACHE_DEBUG QT_MODULE(Core) + struct Q_CORE_EXPORT QContiguousCacheData { QBasicAtomicInt ref; @@ -60,7 +62,9 @@ struct Q_CORE_EXPORT QContiguousCacheData int offset; uint sharable : 1; +#ifdef QT_QCONTIGUOUSCACHE_DEBUG void dump() const; +#endif }; template @@ -131,8 +135,10 @@ public: { return d->offset >= 0 && d->offset < INT_MAX - d->count && (d->offset % d->alloc) == d->start; } inline void normalizeIndexes() { d->offset = d->start; } - // debug + +#ifdef QT_QCONTIGUOUSCACHE_DEBUG void dump() const { p->dump(); } +#endif private: void detach_helper(); -- cgit v0.12 From abb9a3b5031e86bdd89a9338c4f12d703e6f385b Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 10:03:08 +1000 Subject: Move canvas scene snapshot out of in-process debugger --- src/declarative/canvas/qsimplecanvas.cpp | 4 +- .../canvas/qsimplecanvasdebugplugin.cpp | 56 +++++ .../canvas/qsimplecanvasdebugplugin_p.h | 17 ++ src/declarative/debugger/debugger.pri | 2 - src/declarative/debugger/qmlcanvasdebugger.cpp | 240 -------------------- src/declarative/debugger/qmlcanvasdebugger_p.h | 89 -------- src/declarative/debugger/qmldebugclient.cpp | 4 +- src/declarative/debugger/qmldebugclient.h | 1 - src/declarative/debugger/qmldebugger.cpp | 9 +- src/declarative/debugger/qmldebugger.h | 2 - src/declarative/debugger/qmldebugserver.cpp | 15 ++ src/declarative/debugger/qmldebugserver.h | 1 + tools/qmldebugger/canvasframerate.cpp | 45 ++-- tools/qmldebugger/canvasframerate.h | 1 + tools/qmldebugger/canvasscene.cpp | 245 +++++++++++++++++++++ tools/qmldebugger/canvasscene.h | 39 ++++ tools/qmldebugger/main.cpp | 56 ++++- tools/qmldebugger/qmldebugger.pro | 4 +- 18 files changed, 449 insertions(+), 381 deletions(-) delete mode 100644 src/declarative/debugger/qmlcanvasdebugger.cpp delete mode 100644 src/declarative/debugger/qmlcanvasdebugger_p.h create mode 100644 tools/qmldebugger/canvasscene.cpp create mode 100644 tools/qmldebugger/canvasscene.h diff --git a/src/declarative/canvas/qsimplecanvas.cpp b/src/declarative/canvas/qsimplecanvas.cpp index 7d2c9c5..e582226 100644 --- a/src/declarative/canvas/qsimplecanvas.cpp +++ b/src/declarative/canvas/qsimplecanvas.cpp @@ -573,8 +573,10 @@ void QSimpleCanvasPrivate::init(QSimpleCanvas::CanvasMode mode) if (continuousUpdate()) qWarning("QSimpleCanvas: Continuous update enabled"); - if (QmlDebugServerPlugin::isDebuggingEnabled()) + if (QmlDebugServerPlugin::isDebuggingEnabled()) { debugPlugin = new QSimpleCanvasDebugPlugin(q); + new QSimpleCanvasSceneDebugPlugin(q); + } root = new QSimpleCanvasRootLayer(q); root->setActiveFocusPanel(true); diff --git a/src/declarative/canvas/qsimplecanvasdebugplugin.cpp b/src/declarative/canvas/qsimplecanvasdebugplugin.cpp index 0ce5378..f5f4f53 100644 --- a/src/declarative/canvas/qsimplecanvasdebugplugin.cpp +++ b/src/declarative/canvas/qsimplecanvasdebugplugin.cpp @@ -42,6 +42,8 @@ #include "qsimplecanvasdebugplugin_p.h" #include "qdebug.h" #include +#include +#include QT_BEGIN_NAMESPACE @@ -74,6 +76,9 @@ void QSimpleCanvasDebugPlugin::addTiming(quint32 paint, quint32 repaint, quint32 timeBetweenFrames) { + if (!isEnabled()) + return; + bool isFrameBreak = _breaks > 1; _breaks = 0; int e = _time.elapsed(); @@ -89,5 +94,56 @@ void QSimpleCanvasDebugPlugin::frameBreak() _breaks++; } +QSimpleCanvasSceneDebugPlugin::QSimpleCanvasSceneDebugPlugin(QSimpleCanvas *parent) +: QmlDebugServerPlugin("CanvasScene", parent), m_canvas(parent) +{ +} + +void QSimpleCanvasSceneDebugPlugin::messageReceived(const QByteArray &) +{ + refresh(); +} + +void QSimpleCanvasSceneDebugPlugin::refresh() +{ + QByteArray data; + QDataStream ds(&data, QIODevice::WriteOnly); + const QList &children = m_canvas->root()->children(); + ds << children.count(); + for (int ii = 0; ii < children.count(); ++ii) + refresh(ds, children.at(ii)); + + sendMessage(data); +} + +void QSimpleCanvasSceneDebugPlugin::refresh(QDataStream &ds, + QSimpleCanvasItem *item) +{ + ds << QmlDebugServerPlugin::objectToString(item) << item->x() << item->y() + << item->z() << item->width() << item->height() + << (int)item->transformOrigin() << item->scale() << (int)item->flip() + << item->transform() << item->hasActiveFocus() << (int)item->options(); + + QPixmap pix; + + if(item->options() & QSimpleCanvasItem::HasContents && + item->width() > 0 && item->height() > 0) { + + pix = QPixmap(item->width(), item->height()); + pix.fill(QColor(0,0,0,0)); + QPainter p(&pix); + item->paintContents(p); + + } + + ds << pix; + + const QList &children = item->children(); + ds << children.count(); + + for(int ii = 0; ii < children.count(); ++ii) + refresh(ds, children.at(ii)); +} + QT_END_NAMESPACE diff --git a/src/declarative/canvas/qsimplecanvasdebugplugin_p.h b/src/declarative/canvas/qsimplecanvasdebugplugin_p.h index 0c76f38..270b78c 100644 --- a/src/declarative/canvas/qsimplecanvasdebugplugin_p.h +++ b/src/declarative/canvas/qsimplecanvasdebugplugin_p.h @@ -62,6 +62,23 @@ private: int _breaks; QTime _time; }; + +class QSimpleCanvas; +class QSimpleCanvasItem; +class QSimpleCanvasSceneDebugPlugin : public QmlDebugServerPlugin +{ +public: + QSimpleCanvasSceneDebugPlugin(QSimpleCanvas *parent = 0); + + virtual void messageReceived(const QByteArray &); + +private: + void refresh(); + void refresh(QDataStream &, QSimpleCanvasItem *); + QSimpleCanvas *m_canvas; +}; + + QT_END_NAMESPACE #endif // QSIMPLECANVASDEBUGPLUGIN_P_H diff --git a/src/declarative/debugger/debugger.pri b/src/declarative/debugger/debugger.pri index 121cb98..aa36675 100644 --- a/src/declarative/debugger/debugger.pri +++ b/src/declarative/debugger/debugger.pri @@ -3,7 +3,6 @@ SOURCES += debugger/qmldebugger.cpp \ debugger/qmlpropertyview.cpp \ debugger/qmlwatches.cpp \ debugger/qmlobjecttree.cpp \ - debugger/qmlcanvasdebugger.cpp \ debugger/qpacketprotocol.cpp \ debugger/qmldebugserver.cpp \ debugger/qmldebugclient.cpp @@ -13,7 +12,6 @@ HEADERS += debugger/qmldebugger.h \ debugger/qmlpropertyview_p.h \ debugger/qmlwatches_p.h \ debugger/qmlobjecttree_p.h \ - debugger/qmlcanvasdebugger_p.h \ debugger/qpacketprotocol.h \ debugger/qmldebugserver.h \ debugger/qmldebugclient.h diff --git a/src/declarative/debugger/qmlcanvasdebugger.cpp b/src/declarative/debugger/qmlcanvasdebugger.cpp deleted file mode 100644 index 21abd2d..0000000 --- a/src/declarative/debugger/qmlcanvasdebugger.cpp +++ /dev/null @@ -1,240 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -QmlCanvasDebugger::QmlCanvasDebugger(QmlWatches *w, QWidget *parent) -: QWidget(parent), m_watches(w), m_tree(0), m_canvas(0), m_canvasRoot(0), m_debugCanvas(0), - m_selected(0) -{ - QVBoxLayout *layout = new QVBoxLayout; - layout->setContentsMargins(0,0,0,0); - layout->setSpacing(0); - setLayout(layout); - QHBoxLayout *hlayout = new QHBoxLayout; - hlayout->setContentsMargins(0,0,0,0); - hlayout->addStretch(2); - hlayout->setSpacing(0); - layout->addLayout(hlayout); - QSpinBox *x = new QSpinBox(this); - x->setSingleStep(50); - x->setMaximum(10000); - x->setMinimum(-10000); - QObject::connect(x, SIGNAL(valueChanged(int)), this, SLOT(setX(int))); - QSpinBox *y = new QSpinBox(this); - y->setSingleStep(50); - y->setMaximum(10000); - y->setMinimum(-10000); - QObject::connect(y, SIGNAL(valueChanged(int)), this, SLOT(setY(int))); - hlayout->addWidget(x); - hlayout->addWidget(y); - QPushButton *pb = new QPushButton(tr("Refresh"), this); - QObject::connect(pb, SIGNAL(clicked()), this, SLOT(refresh())); - hlayout->addWidget(pb); - - QSplitter *splitter = new QSplitter(this); - - m_tree = new QTreeWidget(this); - QObject::connect(m_tree, SIGNAL(itemExpanded(QTreeWidgetItem*)), - this, SLOT(itemExpanded(QTreeWidgetItem*))); - QObject::connect(m_tree, SIGNAL(itemCollapsed(QTreeWidgetItem*)), - this, SLOT(itemCollapsed(QTreeWidgetItem*))); - QObject::connect(m_tree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), - this, SLOT(itemClicked(QTreeWidgetItem*))); - m_canvas = new QSimpleCanvas(QSimpleCanvas::SimpleCanvas, this); - m_canvasRoot = new QSimpleCanvasItem; - m_canvasRoot->setParent(m_canvas->root()); - splitter->addWidget(m_tree); - splitter->addWidget(m_canvas); - splitter->setStretchFactor(1, 2); - layout->addWidget(splitter); -} - -void QmlCanvasDebugger::refresh() -{ - setCanvas(m_debugCanvas); -} - -class QmlCanvasDebuggerItem : public QTreeWidgetItem -{ -public: - QmlCanvasDebuggerItem(QTreeWidget *tree) - : QTreeWidgetItem(tree), me(0), img(0) - { - } - - QmlCanvasDebuggerItem(QTreeWidgetItem *item) - : QTreeWidgetItem(item), me(0), img(0) - { - } - - QPointer them; - QFxRect *me; - QFxImage *img; -}; - -void QmlCanvasDebugger::itemExpanded(QTreeWidgetItem *i) -{ - QmlCanvasDebuggerItem *item = static_cast(i); - if(item->me) - item->me->setOpacity(1); -} - -void QmlCanvasDebugger::setOpacityRecur(QTreeWidgetItem *i, qreal op) -{ - QmlCanvasDebuggerItem *item = static_cast(i); - if(item->img) - item->img->setOpacity(op); - - for(int ii = 0; ii < item->childCount(); ++ii) - setOpacityRecur(item->child(ii), op); -} - -void QmlCanvasDebugger::itemClicked(QTreeWidgetItem *i) -{ - QmlCanvasDebuggerItem *item = static_cast(i); - if(item->them) - emit objectClicked(m_watches->objectId(item->them)); - - if(m_selected) { - setOpacityRecur(m_selected, 0); - m_selected = 0; - } - - m_selected = item; - setOpacityRecur(m_selected, 1); -} - -void QmlCanvasDebugger::itemCollapsed(QTreeWidgetItem *i) -{ - QmlCanvasDebuggerItem *item = static_cast(i); - if(item->me) - item->me->setOpacity(0); -} - -void QmlCanvasDebugger::clone(QTreeWidgetItem *item, QSimpleCanvasItem *me, QSimpleCanvasItem *them) -{ - const QList &children = them->children(); - - foreach(QSimpleCanvasItem *child, children) { - QmlCanvasDebuggerItem *childItem = new QmlCanvasDebuggerItem(item); - childItem->setText(0, QmlWatches::objectToString(child)); - childItem->setExpanded(true); - - QFxRect *rect = new QFxRect; - rect->setParent(me); - rect->setX(child->x()); - rect->setY(child->y()); - rect->setZ(child->z()); - rect->setWidth(child->width()); - rect->setHeight(child->height()); - rect->setTransformOrigin(child->transformOrigin()); - rect->setScale(child->scale()); - rect->setFlip(child->flip()); - rect->setTransform(child->transform()); - - if(child->hasActiveFocus()) - rect->setColor(QColor(0, 0, 0, 10)); - else if(child->options() & QSimpleCanvasItem::IsFocusPanel) - rect->setColor(QColor(0, 255, 0, 10)); - else if(child->options() & QSimpleCanvasItem::IsFocusRealm) - rect->setColor(QColor(0, 0, 255, 10)); - else - rect->setColor(QColor(255, 0, 0, 10)); - - if(child->width() > 0 && child->height() > 0) { - QPixmap pix(child->width(), child->height()); - pix.fill(QColor(0,0,0,0)); - QPainter p(&pix); - child->paintContents(p); - QFxImage *img = new QFxImage; - img->setParent(rect); - img->setWidth(child->width()); - img->setHeight(child->height()); - img->setPixmap(pix); - img->setOpacity(0); - childItem->img = img; - } - - childItem->them = child; - childItem->me = rect; - - clone(childItem, rect, child); - } -} - -void QmlCanvasDebugger::setX(int x) -{ - m_canvasRoot->setX(x); -} - -void QmlCanvasDebugger::setY(int y) -{ - m_canvasRoot->setY(y); -} - -void QmlCanvasDebugger::setCanvas(QSimpleCanvas *canvas) -{ - QList children = m_canvasRoot->children(); - qDeleteAll(children); - m_tree->clear(); - m_selected = 0; - - m_debugCanvas = canvas; - if(!m_debugCanvas) - return; - - QTreeWidgetItem *root = new QmlCanvasDebuggerItem(m_tree); - root->setText(0, tr("Root")); - root->setExpanded(true); - clone(root, m_canvasRoot, m_debugCanvas->root()); -} - diff --git a/src/declarative/debugger/qmlcanvasdebugger_p.h b/src/declarative/debugger/qmlcanvasdebugger_p.h deleted file mode 100644 index 80a2322..0000000 --- a/src/declarative/debugger/qmlcanvasdebugger_p.h +++ /dev/null @@ -1,89 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtDeclarative module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef QMLCANVASDEBUGGER_P_H -#define QMLCANVASDEBUGGER_P_H - -#include -#include - -QT_BEGIN_NAMESPACE - -class QSimpleCanvas; -class QSimpleCanvasItem; -class QTreeWidget; -class QTreeWidgetItem; -class QmlWatches; -class QmlCanvasDebugger : public QWidget -{ - Q_OBJECT -public: - QmlCanvasDebugger(QmlWatches *, QWidget *parent = 0); - - void setCanvas(QSimpleCanvas *); - -signals: - void objectClicked(quint32); - -private slots: - void refresh(); - void itemClicked(QTreeWidgetItem *); - void itemExpanded(QTreeWidgetItem *); - void itemCollapsed(QTreeWidgetItem *); - void setX(int); - void setY(int); - -private: - void setOpacityRecur(QTreeWidgetItem *, qreal); - void clone(QTreeWidgetItem *, QSimpleCanvasItem *me, QSimpleCanvasItem *them); - - QmlWatches *m_watches; - QTreeWidget *m_tree; - QSimpleCanvas *m_canvas; - QSimpleCanvasItem *m_canvasRoot; - QPointer m_debugCanvas; - QTreeWidgetItem *m_selected; -}; - -QT_END_NAMESPACE - -#endif // QMLCANVASDEBUGGER_P_H - diff --git a/src/declarative/debugger/qmldebugclient.cpp b/src/declarative/debugger/qmldebugclient.cpp index 7a304ef..85ccf0b 100644 --- a/src/declarative/debugger/qmldebugclient.cpp +++ b/src/declarative/debugger/qmldebugclient.cpp @@ -73,7 +73,7 @@ QmlDebugClientPrivate::QmlDebugClientPrivate(QmlDebugClient *c) void QmlDebugClientPrivate::connected() { QPacket pack; - pack << QString(QLatin1String("QmlDebugServer")) << QStringList(); + pack << QString(QLatin1String("QmlDebugServer")) << enabled; protocol->send(pack); } @@ -178,7 +178,7 @@ void QmlDebugClientPlugin::sendMessage(const QByteArray &message) QPacket pack; pack << d->name << message; - d->client->d_func()->protocol->send(pack); + d->client->d->protocol->send(pack); } void QmlDebugClientPlugin::messageReceived(const QByteArray &) diff --git a/src/declarative/debugger/qmldebugclient.h b/src/declarative/debugger/qmldebugclient.h index d765822..3fbf534 100644 --- a/src/declarative/debugger/qmldebugclient.h +++ b/src/declarative/debugger/qmldebugclient.h @@ -54,7 +54,6 @@ class QmlDebugClientPrivate; class Q_DECLARATIVE_EXPORT QmlDebugClient : public QTcpSocket { Q_OBJECT - Q_DECLARE_PRIVATE(QmlDebugClient) Q_DISABLE_COPY(QmlDebugClient) public: QmlDebugClient(QObject * = 0); diff --git a/src/declarative/debugger/qmldebugger.cpp b/src/declarative/debugger/qmldebugger.cpp index 0bbcb2c..c925148 100644 --- a/src/declarative/debugger/qmldebugger.cpp +++ b/src/declarative/debugger/qmldebugger.cpp @@ -61,11 +61,10 @@ #include #include #include -#include QmlDebugger::QmlDebugger(QWidget *parent) : QWidget(parent), m_tree(0), m_warnings(0), m_watchTable(0), m_watches(0), - m_canvas(0), m_properties(0), m_text(0), m_highlightedItem(0) + m_properties(0), m_text(0), m_highlightedItem(0) { QHBoxLayout *layout = new QHBoxLayout; setLayout(layout); @@ -111,11 +110,6 @@ QmlDebugger::QmlDebugger(QWidget *parent) tabs->addTab(m_properties, tr("Properties")); tabs->setCurrentWidget(m_properties); - m_canvas = new QmlCanvasDebugger(m_watches, this); - QObject::connect(m_canvas, SIGNAL(objectClicked(quint32)), - this, SLOT(highlightObject(quint32))); - tabs->addTab(m_canvas, tr("Canvas")); - splitter->addWidget(tabs); splitter->setStretchFactor(1, 2); @@ -339,7 +333,6 @@ bool operator<(const QPair > &lhs, void QmlDebugger::setCanvas(QSimpleCanvas *c) { - m_canvas->setCanvas(c); } void QmlDebugger::setDebugObject(QObject *obj) diff --git a/src/declarative/debugger/qmldebugger.h b/src/declarative/debugger/qmldebugger.h index 4641bce..10b2f9a 100644 --- a/src/declarative/debugger/qmldebugger.h +++ b/src/declarative/debugger/qmldebugger.h @@ -61,7 +61,6 @@ class QmlPropertyView; class QmlWatches; class QmlObjectTree; class QmlContext; -class QmlCanvasDebugger; class QSimpleCanvas; class QmlDebugger : public QWidget { @@ -88,7 +87,6 @@ private: QTreeWidget *m_warnings; QTableView *m_watchTable; QmlWatches *m_watches; - QmlCanvasDebugger *m_canvas; QmlPropertyView *m_properties; QPlainTextEdit *m_text; QPointer m_object; diff --git a/src/declarative/debugger/qmldebugserver.cpp b/src/declarative/debugger/qmldebugserver.cpp index bce7e6d..a253e8c 100644 --- a/src/declarative/debugger/qmldebugserver.cpp +++ b/src/declarative/debugger/qmldebugserver.cpp @@ -258,6 +258,21 @@ bool QmlDebugServerPlugin::isDebuggingEnabled() return QmlDebugServer::instance() != 0; } +QString QmlDebugServerPlugin::objectToString(QObject *obj) +{ + if(!obj) + return QLatin1String("NULL"); + + QString objectName = obj->objectName(); + if(objectName.isEmpty()) + objectName = QLatin1String(""); + + QString rv = QLatin1String(obj->metaObject()->className()) + + QLatin1String(": ") + objectName; + + return rv; +} + void QmlDebugServerPlugin::sendMessage(const QByteArray &message) { Q_D(QmlDebugServerPlugin); diff --git a/src/declarative/debugger/qmldebugserver.h b/src/declarative/debugger/qmldebugserver.h index 8ee2cfb..02fe7d1 100644 --- a/src/declarative/debugger/qmldebugserver.h +++ b/src/declarative/debugger/qmldebugserver.h @@ -64,6 +64,7 @@ public: void sendMessage(const QByteArray &); static bool isDebuggingEnabled(); + static QString objectToString(QObject *obj); protected: virtual void enabledChanged(bool); diff --git a/tools/qmldebugger/canvasframerate.cpp b/tools/qmldebugger/canvasframerate.cpp index b1f412e..022aed5 100644 --- a/tools/qmldebugger/canvasframerate.cpp +++ b/tools/qmldebugger/canvasframerate.cpp @@ -12,6 +12,7 @@ #include #include #include +#include class QLineGraph : public QWidget { @@ -26,9 +27,7 @@ public slots: protected: virtual void paintEvent(QPaintEvent *); - virtual void mousePressEvent(QMouseEvent *); - virtual void resizeEvent(QResizeEvent *); - virtual void showEvent(QShowEvent *); + virtual QSize sizeHint() const; private slots: void scrollbarChanged(int); @@ -64,32 +63,20 @@ QLineGraph::QLineGraph(QWidget *parent) QObject::connect(&sb, SIGNAL(valueChanged(int)), this, SLOT(scrollbarChanged(int))); } -void QLineGraph::scrollbarChanged(int v) +QSize QLineGraph::sizeHint() const { - if(ignoreScroll) - return; - - position = v; - update(); + return QSize(800, 600); } -void QLineGraph::resizeEvent(QResizeEvent *e) -{ - QWidget::resizeEvent(e); -} - -void QLineGraph::showEvent(QShowEvent *e) +void QLineGraph::scrollbarChanged(int v) { - QWidget::showEvent(e); -} + if(ignoreScroll) + return; -void QLineGraph::mousePressEvent(QMouseEvent *) -{ - if(position == -1) { - position = qMax(0, _samples.count() - samplesPerWidth - 1); - } else { + if (v == sb.maximum()) position = -1; - } + else + position = v; update(); } @@ -276,6 +263,11 @@ CanvasFrameRate::CanvasFrameRate(QmlDebugClient *client, QWidget *parent) layout->addLayout(bottom); bottom->addStretch(2); + QCheckBox *check = new QCheckBox("Enable", this); + bottom->addWidget(check); + QObject::connect(check, SIGNAL(stateChanged(int)), + this, SLOT(stateChanged(int))); + QPushButton *pb = new QPushButton(tr("New Tab"), this); QObject::connect(pb, SIGNAL(clicked()), this, SLOT(newTab())); bottom->addWidget(pb); @@ -302,4 +294,11 @@ void CanvasFrameRate::newTab() m_tabs->setCurrentIndex(id); } +void CanvasFrameRate::stateChanged(int s) +{ + bool checked = s != 0; + + static_cast(m_plugin)->setEnabled(checked); +} + #include "canvasframerate.moc" diff --git a/tools/qmldebugger/canvasframerate.h b/tools/qmldebugger/canvasframerate.h index c3e88ef..543f233 100644 --- a/tools/qmldebugger/canvasframerate.h +++ b/tools/qmldebugger/canvasframerate.h @@ -13,6 +13,7 @@ public: private slots: void newTab(); + void stateChanged(int); private: QTabWidget *m_tabs; diff --git a/tools/qmldebugger/canvasscene.cpp b/tools/qmldebugger/canvasscene.cpp new file mode 100644 index 0000000..2d5b764 --- /dev/null +++ b/tools/qmldebugger/canvasscene.cpp @@ -0,0 +1,245 @@ +#include "canvasscene.h" +#include +#include +#include +#include +#include +#include +#include +#include + +class CanvasSceneClientPlugin : public QmlDebugClientPlugin +{ +public: + CanvasSceneClientPlugin(QmlDebugClient *, CanvasScene *s); + +protected: + void messageReceived(const QByteArray &); + +private: + void dump(QDataStream &, int indent); + CanvasScene *scene; +}; + +class QmlCanvasDebuggerItem : public QTreeWidgetItem +{ +public: + QmlCanvasDebuggerItem(QTreeWidget *tree) + : QTreeWidgetItem(tree), me(0), img(0) + { + } + + QmlCanvasDebuggerItem(QTreeWidgetItem *item) + : QTreeWidgetItem(item), me(0), img(0) + { + } + + QFxRect *me; + QFxImage *img; +}; + +CanvasSceneClientPlugin::CanvasSceneClientPlugin(QmlDebugClient *c, + CanvasScene *s) +: QmlDebugClientPlugin(QLatin1String("CanvasScene"), c), scene(s) +{ +} + +void CanvasSceneClientPlugin::messageReceived(const QByteArray &data) +{ + QByteArray d = data; + QDataStream ds(&d, QIODevice::ReadOnly); + + scene->message(ds); +} + +void CanvasScene::message(QDataStream &ds) +{ + QList children = m_canvasRoot->children(); + qDeleteAll(children); + m_tree->clear(); + m_selected = 0; + + QTreeWidgetItem *root = new QmlCanvasDebuggerItem(m_tree); + root->setText(0, tr("Root")); + root->setExpanded(true); + clone(root, m_canvasRoot, ds); +} + +void CanvasScene::clone(QTreeWidgetItem *item, QSimpleCanvasItem *me, + QDataStream &ds) +{ + int children; + ds >> children; + + for (int ii = 0; ii < children; ++ii) { + QString name; + qreal x, y, z, width, height, scale; + QTransform transform; + bool activeFocus; + int transformOrigin, flip, options; + QPixmap pix; + + ds >> name >> x >> y >> z >> width >> height >> transformOrigin >> scale + >> flip >> transform >> activeFocus >> options >> pix; + + QmlCanvasDebuggerItem *childItem = new QmlCanvasDebuggerItem(item); + childItem->setText(0, name); + childItem->setExpanded(true); + + QFxRect *rect = new QFxRect; + rect->setParent(me); + rect->setX(x); + rect->setY(y); + rect->setZ(z); + rect->setWidth(width); + rect->setHeight(height); + rect->setTransformOrigin((QSimpleCanvasItem::TransformOrigin)transformOrigin); + rect->setScale(scale); + rect->setFlip((QSimpleCanvasItem::Flip)flip); + rect->setTransform(transform); + + if (activeFocus) + rect->setColor(QColor(0, 0, 0, 10)); + else if(options & QSimpleCanvasItem::IsFocusPanel) + rect->setColor(QColor(0, 255, 0, 10)); + else if(options & QSimpleCanvasItem::IsFocusRealm) + rect->setColor(QColor(0, 0, 255, 10)); + else + rect->setColor(QColor(255, 0, 0, 10)); + + if (pix.width() > 0 || pix.height() > 0) { + QFxImage *img = new QFxImage; + img->setParent(rect); + img->setWidth(width); + img->setHeight(height); + img->setPixmap(pix); + img->setOpacity(0); + childItem->img = img; + } + + childItem->me = rect; + + clone(childItem, rect, ds); + } +} + +void CanvasSceneClientPlugin::dump(QDataStream &ds, int indent) +{ + QString name; + qreal x, y, z, width, height, scale; + QTransform transform; + bool activeFocus; + int transformOrigin, flip, options, count; + QPixmap pix; + + ds >> name >> x >> y >> z >> width >> height >> transformOrigin >> scale + >> flip >> transform >> activeFocus >> options >> pix >> count; + + QByteArray ba(indent * 4, ' '); + qWarning() << ba.constData() << name << x << y; + + for(int ii = 0; ii < count; ++ii) + dump(ds, indent + 1); +} + +CanvasScene::CanvasScene(QmlDebugClient *c, QWidget *parent) +: QWidget(parent) +{ + client = new CanvasSceneClientPlugin(c, this); + + QVBoxLayout *layout = new QVBoxLayout; + layout->setContentsMargins(0,0,0,0); + layout->setSpacing(0); + setLayout(layout); + QSplitter *splitter = new QSplitter(this); + + m_tree = new QTreeWidget(this); + m_tree->setHeaderHidden(true); + QObject::connect(m_tree, SIGNAL(itemExpanded(QTreeWidgetItem*)), + this, SLOT(itemExpanded(QTreeWidgetItem*))); + QObject::connect(m_tree, SIGNAL(itemCollapsed(QTreeWidgetItem*)), + this, SLOT(itemCollapsed(QTreeWidgetItem*))); + QObject::connect(m_tree, SIGNAL(itemClicked(QTreeWidgetItem*,int)), + this, SLOT(itemClicked(QTreeWidgetItem*))); + m_canvas = new QSimpleCanvas(QSimpleCanvas::SimpleCanvas, this); + m_canvasRoot = new QSimpleCanvasItem; + m_canvasRoot->setParent(m_canvas->root()); + splitter->addWidget(m_tree); + splitter->addWidget(m_canvas); + splitter->setStretchFactor(1, 2); + layout->addWidget(splitter); + + QHBoxLayout *hlayout = new QHBoxLayout; + hlayout->setContentsMargins(0,0,0,0); + hlayout->addStretch(2); + hlayout->setSpacing(0); + layout->addLayout(hlayout); + QSpinBox *x = new QSpinBox(this); + x->setSingleStep(50); + x->setMaximum(10000); + x->setMinimum(-10000); + QObject::connect(x, SIGNAL(valueChanged(int)), this, SLOT(setX(int))); + QSpinBox *y = new QSpinBox(this); + y->setSingleStep(50); + y->setMaximum(10000); + y->setMinimum(-10000); + QObject::connect(y, SIGNAL(valueChanged(int)), this, SLOT(setY(int))); + hlayout->addWidget(x); + hlayout->addWidget(y); + QPushButton *pb = new QPushButton(tr("Refresh"), this); + QObject::connect(pb, SIGNAL(clicked()), this, SLOT(refresh())); + hlayout->addWidget(pb); +} + +void CanvasScene::refresh() +{ + client->sendMessage(QByteArray()); +} + +void CanvasScene::itemExpanded(QTreeWidgetItem *i) +{ + QmlCanvasDebuggerItem *item = static_cast(i); + if(item->me) + item->me->setOpacity(1); +} + +void CanvasScene::setOpacityRecur(QTreeWidgetItem *i, qreal op) +{ + QmlCanvasDebuggerItem *item = static_cast(i); + if(item->img) + item->img->setOpacity(op); + + for(int ii = 0; ii < item->childCount(); ++ii) + setOpacityRecur(item->child(ii), op); +} + +void CanvasScene::itemClicked(QTreeWidgetItem *i) +{ + QmlCanvasDebuggerItem *item = static_cast(i); + + if(m_selected) { + setOpacityRecur(m_selected, 0); + m_selected = 0; + } + + m_selected = item; + setOpacityRecur(m_selected, 1); +} + +void CanvasScene::itemCollapsed(QTreeWidgetItem *i) +{ + QmlCanvasDebuggerItem *item = static_cast(i); + if(item->me) + item->me->setOpacity(0); +} + +void CanvasScene::setX(int x) +{ + m_canvasRoot->setX(x); +} + +void CanvasScene::setY(int y) +{ + m_canvasRoot->setY(y); +} + diff --git a/tools/qmldebugger/canvasscene.h b/tools/qmldebugger/canvasscene.h new file mode 100644 index 0000000..d980241 --- /dev/null +++ b/tools/qmldebugger/canvasscene.h @@ -0,0 +1,39 @@ +#ifndef CANVASSCENE_H +#define CANVASSCENE_H + +#include +#include +#include +#include + +class QmlDebugClient; +class CanvasSceneClient; +class QmlDebugClientPlugin; +class CanvasScene : public QWidget +{ +Q_OBJECT +public: + CanvasScene(QmlDebugClient *, QWidget *parent = 0); + + void message(QDataStream &); +private slots: + void refresh(); + void itemClicked(QTreeWidgetItem *); + void itemExpanded(QTreeWidgetItem *); + void itemCollapsed(QTreeWidgetItem *); + void setX(int); + void setY(int); + +private: + void setOpacityRecur(QTreeWidgetItem *, qreal); + void clone(QTreeWidgetItem *item, QSimpleCanvasItem *me, QDataStream &); + QmlDebugClientPlugin *client; + + QTreeWidget *m_tree; + QSimpleCanvas *m_canvas; + QSimpleCanvasItem *m_canvasRoot; + QTreeWidgetItem *m_selected; +}; + +#endif // CANVASSCENE_H + diff --git a/tools/qmldebugger/main.cpp b/tools/qmldebugger/main.cpp index 2c5be6c..5b94cbb 100644 --- a/tools/qmldebugger/main.cpp +++ b/tools/qmldebugger/main.cpp @@ -8,11 +8,13 @@ #include #include #include "canvasframerate.h" +#include "canvasscene.h" #include #include #include #include #include +#include class Shell : public QWidget { @@ -23,10 +25,12 @@ public: private slots: void connectToHost(); void disconnectFromHost(); + void connectionStateChanged(); private: QmlDebugClient client; + QLabel *m_connectionState; QLineEdit *m_host; QSpinBox *m_port; QPushButton *m_connectButton; @@ -44,8 +48,10 @@ Shell::Shell(QWidget *parent) layout->addLayout(connectLayout); connectLayout->addStretch(2); + m_connectionState = new QLabel(this); + connectLayout->addWidget(m_connectionState); m_host = new QLineEdit(this); - m_host->setText("localhost"); + m_host->setText("127.0.0.1"); connectLayout->addWidget(m_host); m_port = new QSpinBox(this); m_port->setMinimum(1024); @@ -67,33 +73,61 @@ Shell::Shell(QWidget *parent) CanvasFrameRate *cfr = new CanvasFrameRate(&client, this); tabs->addTab(cfr, tr("Frame Rate")); + + CanvasScene *cs = new CanvasScene(&client, this); + tabs->addTab(cs, tr("Scene")); + + QObject::connect(&client, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(connectionStateChanged())); + connectionStateChanged(); +} + +void Shell::connectionStateChanged() +{ + switch (client.state()) { + default: + case QAbstractSocket::UnconnectedState: + m_connectionState->setText(tr("Disconnected")); + m_connectButton->setEnabled(true); + m_disconnectButton->setEnabled(false); + break; + case QAbstractSocket::HostLookupState: + m_connectionState->setText(tr("Resolving")); + m_connectButton->setEnabled(false); + m_disconnectButton->setEnabled(true); + break; + case QAbstractSocket::ConnectingState: + m_connectionState->setText(tr("Connecting")); + m_connectButton->setEnabled(false); + m_disconnectButton->setEnabled(true); + break; + case QAbstractSocket::ConnectedState: + m_connectionState->setText(tr("Connected")); + m_connectButton->setEnabled(false); + m_disconnectButton->setEnabled(true); + break; + case QAbstractSocket::ClosingState: + m_connectionState->setText(tr("Closing")); + m_connectButton->setEnabled(false); + m_disconnectButton->setEnabled(false); + break; + } } void Shell::connectToHost() { - m_connectButton->setEnabled(false); - m_disconnectButton->setEnabled(true); client.connectToHost(m_host->text(), m_port->value()); } void Shell::disconnectFromHost() { - m_connectButton->setEnabled(true); - m_disconnectButton->setEnabled(false); client.disconnectFromHost(); } int main(int argc, char ** argv) { - if(argc != 3) { - qWarning() << "Usage:" << argv[0] << "host port"; - return -1; - } - QApplication app(argc, argv); Shell shell; -// shell.setFixedSize(1024, 768); shell.show(); diff --git a/tools/qmldebugger/qmldebugger.pro b/tools/qmldebugger/qmldebugger.pro index 6af2909..757ba12 100644 --- a/tools/qmldebugger/qmldebugger.pro +++ b/tools/qmldebugger/qmldebugger.pro @@ -1,8 +1,8 @@ DESTDIR = ../../bin QT += network declarative # Input -HEADERS += canvasframerate.h -SOURCES += main.cpp canvasframerate.cpp +HEADERS += canvasframerate.h canvasscene.h +SOURCES += main.cpp canvasframerate.cpp canvasscene.cpp target.path=$$[QT_INSTALL_BINS] INSTALLS += target -- cgit v0.12 From 4058b501914216bf28ab62c02b78abcbf7f5a3c9 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 11:17:20 +1000 Subject: roberto: Added support for CSS like numeric literals e.g. 10p --- src/declarative/qml/parser/javascript.g | 6 +- src/declarative/qml/parser/javascriptast.cpp | 38 +++++ src/declarative/qml/parser/javascriptast_p.h | 37 ++++- src/declarative/qml/parser/javascriptlexer.cpp | 57 +++++++- src/declarative/qml/parser/javascriptlexer_p.h | 19 +++ src/declarative/qml/parser/javascriptparser.cpp | 6 +- src/declarative/qml/parser/parser.pri | 2 + src/declarative/qml/qml.pri | 13 +- src/declarative/qml/qmlscriptparser.cpp | 74 ++++++++-- src/declarative/qml/rewriter/rewriter.cpp | 55 ++++++++ src/declarative/qml/rewriter/rewriter.pri | 4 + src/declarative/qml/rewriter/rewriter_p.h | 112 +++++++++++++++ src/declarative/qml/rewriter/textwriter.cpp | 176 ++++++++++++++++++++++++ src/declarative/qml/rewriter/textwriter_p.h | 60 ++++++++ 14 files changed, 624 insertions(+), 35 deletions(-) create mode 100644 src/declarative/qml/rewriter/rewriter.cpp create mode 100644 src/declarative/qml/rewriter/rewriter.pri create mode 100644 src/declarative/qml/rewriter/rewriter_p.h create mode 100644 src/declarative/qml/rewriter/textwriter.cpp create mode 100644 src/declarative/qml/rewriter/textwriter_p.h diff --git a/src/declarative/qml/parser/javascript.g b/src/declarative/qml/parser/javascript.g index 155630b..8cabeea 100644 --- a/src/declarative/qml/parser/javascript.g +++ b/src/declarative/qml/parser/javascript.g @@ -875,7 +875,7 @@ case $rule_number: { PrimaryExpression: T_NUMERIC_LITERAL ; /. case $rule_number: { - AST::NumericLiteral *node = makeAstNode (driver->nodePool(), sym(1).dval); + AST::NumericLiteral *node = makeAstNode (driver->nodePool(), sym(1).dval, lexer->flags); node->literalToken = loc(1); sym(1).Node = node; } break; @@ -2830,7 +2830,7 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ; yytoken = *tk; yylval = 0; yylloc = token_buffer[0].loc; - yylloc.length = 0; + yylloc.length = 0; first_token = &token_buffer[0]; last_token = &token_buffer[2]; @@ -2852,7 +2852,7 @@ PropertyNameAndValueListOpt: PropertyNameAndValueList ; yytoken = tk; yylval = 0; yylloc = token_buffer[0].loc; - yylloc.length = 0; + yylloc.length = 0; action = errorState; goto _Lcheck_token; diff --git a/src/declarative/qml/parser/javascriptast.cpp b/src/declarative/qml/parser/javascriptast.cpp index 083dd28..130229b 100644 --- a/src/declarative/qml/parser/javascriptast.cpp +++ b/src/declarative/qml/parser/javascriptast.cpp @@ -49,6 +49,44 @@ QT_BEGIN_NAMESPACE namespace JavaScript { namespace AST { +int NumericLiteral::suffixLength[] = { + 0, // noSuffix + 2, // emSuffix + 2, // exSuffix + 2, // pxSuffix + 2, // cmSuffix + 2, // mmSuffix + 2, // inSuffix + 2, // ptSuffix + 2, // pcSuffix + 3, // degSuffix + 3, // radSuffix + 4, // gradSuffix + 2, // msSuffix + 1, // sSuffix + 2, // hzSuffix + 3 // khzSuffix +}; + +const char *const NumericLiteral::suffixSpell[] = { + "", + "em", + "ex", + "px", + "cm", + "mm", + "in", + "pt", + "pc", + "deg", + "rad", + "grad", + "ms", + "s", + "hz", + "khz" +}; + ExpressionNode *Node::expressionCast() { return 0; diff --git a/src/declarative/qml/parser/javascriptast_p.h b/src/declarative/qml/parser/javascriptast_p.h index 134f3cc..b5fd922 100644 --- a/src/declarative/qml/parser/javascriptast_p.h +++ b/src/declarative/qml/parser/javascriptast_p.h @@ -398,8 +398,30 @@ class NumericLiteral: public ExpressionNode public: JAVASCRIPT_DECLARE_AST_NODE(NumericLiteral) - NumericLiteral(double v): - value (v) { kind = K; } + enum Suffix { // ### keep it in sync with the Suffix enum in javascriptlexer_p.h + noSuffix, + emSuffix, + exSuffix, + pxSuffix, + cmSuffix, + mmSuffix, + inSuffix, + ptSuffix, + pcSuffix, + degSuffix, + radSuffix, + gradSuffix, + msSuffix, + sSuffix, + hzSuffix, + khzSuffix + }; + + static int suffixLength[]; + static const char *const suffixSpell[]; + + NumericLiteral(double v, int suffix): + value(v), suffix(suffix) { kind = K; } virtual ~NumericLiteral() {} virtual void accept0(Visitor *visitor); @@ -412,6 +434,7 @@ public: // attributes: double value; + int suffix; SourceLocation literalToken; }; @@ -2314,7 +2337,7 @@ public: virtual SourceLocation firstSourceLocation() const { if (defaultToken.isValid()) - return defaultToken; + return defaultToken; return propertyToken; } @@ -2375,9 +2398,9 @@ public: virtual SourceLocation firstSourceLocation() const { if (FunctionDeclaration *funDecl = cast(sourceElement)) - return funDecl->firstSourceLocation(); + return funDecl->firstSourceLocation(); else if (VariableStatement *varStmt = cast(sourceElement)) - return varStmt->firstSourceLocation(); + return varStmt->firstSourceLocation(); return SourceLocation(); } @@ -2385,9 +2408,9 @@ public: virtual SourceLocation lastSourceLocation() const { if (FunctionDeclaration *funDecl = cast(sourceElement)) - return funDecl->lastSourceLocation(); + return funDecl->lastSourceLocation(); else if (VariableStatement *varStmt = cast(sourceElement)) - return varStmt->lastSourceLocation(); + return varStmt->lastSourceLocation(); return SourceLocation(); } diff --git a/src/declarative/qml/parser/javascriptlexer.cpp b/src/declarative/qml/parser/javascriptlexer.cpp index 7455b87..fda6ad2 100644 --- a/src/declarative/qml/parser/javascriptlexer.cpp +++ b/src/declarative/qml/parser/javascriptlexer.cpp @@ -377,7 +377,7 @@ int Lexer::findReservedWord(const QChar *c, int size) const else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r') && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('p') && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('r') - && c[6] == QLatin1Char('t') && c[7] == QLatin1Char('y')) + && c[6] == QLatin1Char('t') && c[7] == QLatin1Char('y')) return JavaScriptGrammar::T_PROPERTY; else if (check_reserved) { if (c[0] == QLatin1Char('a') && c[1] == QLatin1Char('b') @@ -753,12 +753,65 @@ int Lexer::lex() bol = false; } + if (state == Number) { + // CSS-style suffix for numeric literals + + flags = noSuffix; + + if (current == 'e' && next1 == 'm') { + flags = emSuffix; + shift(2); + } else if (current == 'e' && next1 == 'x') { + flags = exSuffix; + shift(2); + } else if (current == 'p' && next1 == 'x') { + flags = pxSuffix; + shift(2); + } else if (current == 'c' && next1 == 'm') { + flags = cmSuffix; + shift(2); + } else if (current == 'm' && next1 == 'm') { + flags = mmSuffix; + shift(2); + } else if (current == 'i' && next1 == 'n') { + flags = inSuffix; + shift(2); + } else if (current == 'p' && next1 == 't') { + flags = ptSuffix; + shift(2); + } else if (current == 'p' && next1 == 'c') { + flags = pcSuffix; + shift(1); + } else if (current == 'd' && next1 == 'e' && next2 == 'g') { + flags = degSuffix; + shift(3); + } else if (current == 'r' && next1 == 'a' && next2 == 'd') { + flags = radSuffix; + shift(3); + } else if (current == 'g' && next1 == 'r' && next2 == 'a' && next3 == 'd') { + flags = gradSuffix; + shift(4); + } else if (current == 'm' && next1 == 's') { + flags = msSuffix; + shift(2); + } else if (current == 's') { + flags = sSuffix; + shift(1); + } else if (current == 'h' && next1 == 'z') { + flags = hzSuffix; + shift(2); + } else if (current == 'k' && next1 == 'h' && next2 == 'z') { + flags = khzSuffix; + shift(3); + } + } + // no identifiers allowed directly after numeric literal, e.g. "3in" is bad if ((state == Number || state == Octal || state == Hex) && isIdentLetter(current)) { state = Bad; err = IllegalIdentifier; - errmsg = QLatin1String("Identifier cannot start with numeric literal"); + errmsg = QLatin1String("Identifier cannot start with numeric literal `%1'"); } // terminate string diff --git a/src/declarative/qml/parser/javascriptlexer_p.h b/src/declarative/qml/parser/javascriptlexer_p.h index 092609c..a47c1ae 100644 --- a/src/declarative/qml/parser/javascriptlexer_p.h +++ b/src/declarative/qml/parser/javascriptlexer_p.h @@ -112,6 +112,25 @@ public: Other, Bad }; + enum Suffix { + noSuffix, + emSuffix, + exSuffix, + pxSuffix, + cmSuffix, + mmSuffix, + inSuffix, + ptSuffix, + pcSuffix, + degSuffix, + radSuffix, + gradSuffix, + msSuffix, + sSuffix, + hzSuffix, + khzSuffix + }; + enum Error { NoError, IllegalCharacter, diff --git a/src/declarative/qml/parser/javascriptparser.cpp b/src/declarative/qml/parser/javascriptparser.cpp index 7ff438e..34ecd0e 100644 --- a/src/declarative/qml/parser/javascriptparser.cpp +++ b/src/declarative/qml/parser/javascriptparser.cpp @@ -430,7 +430,7 @@ case 51: { } break; case 52: { - AST::NumericLiteral *node = makeAstNode (driver->nodePool(), sym(1).dval); + AST::NumericLiteral *node = makeAstNode (driver->nodePool(), sym(1).dval, lexer->flags); node->literalToken = loc(1); sym(1).Node = node; } break; @@ -1675,7 +1675,7 @@ case 320: { yytoken = *tk; yylval = 0; yylloc = token_buffer[0].loc; - yylloc.length = 0; + yylloc.length = 0; first_token = &token_buffer[0]; last_token = &token_buffer[2]; @@ -1697,7 +1697,7 @@ case 320: { yytoken = tk; yylval = 0; yylloc = token_buffer[0].loc; - yylloc.length = 0; + yylloc.length = 0; action = errorState; goto _Lcheck_token; diff --git a/src/declarative/qml/parser/parser.pri b/src/declarative/qml/parser/parser.pri index b4d226a..72bd46c 100644 --- a/src/declarative/qml/parser/parser.pri +++ b/src/declarative/qml/parser/parser.pri @@ -1,4 +1,6 @@ +INCLUDEPATH += $$PWD + HEADERS += $$PWD/javascriptast_p.h \ $$PWD/javascriptastfwd_p.h \ $$PWD/javascriptastvisitor_p.h \ diff --git a/src/declarative/qml/qml.pri b/src/declarative/qml/qml.pri index 99e30e4..b6ac30e 100644 --- a/src/declarative/qml/qml.pri +++ b/src/declarative/qml/qml.pri @@ -22,7 +22,8 @@ SOURCES += qml/qmlparser.cpp \ qml/qmlparserstatus.cpp \ qml/qmlcompositetypemanager.cpp \ qml/qmlinfo.cpp \ - qml/qmlerror.cpp + qml/qmlerror.cpp \ + qml/qmlscriptparser.cpp HEADERS += qml/qmlparser_p.h \ qml/qmlinstruction_p.h \ @@ -59,15 +60,13 @@ HEADERS += qml/qmlparser_p.h \ qml/qmlcompositetypemanager_p.h \ qml/qmllist.h \ qml/qmldeclarativedata_p.h \ - qml/qmlerror.h + qml/qmlerror.h \ + qml/qmlscriptparser_p.h # for qtscript debugger QT += scripttools -include(script/script.pri) -# new language front-end +include(script/script.pri) include(parser/parser.pri) +include(rewriter/rewriter.pri) -HEADERS += qml/qmlscriptparser_p.h - -SOURCES += qml/qmlscriptparser.cpp diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index 5b3564f..07f6b17 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -9,6 +9,8 @@ #include "parser/javascriptastvisitor_p.h" #include "parser/javascriptast_p.h" +#include "rewriter/textwriter_p.h" + #include #include #include @@ -22,6 +24,46 @@ using namespace QmlParser; namespace { +class RewriteNumericLiterals: protected AST::Visitor +{ + unsigned _position; + TextWriter _writer; + +public: + QString operator()(QString code, unsigned position, AST::Node *node) + { + _position = position; + + AST::Node::acceptChild(node, this); + + _writer.write(&code); + + return code; + } + +protected: + using AST::Visitor::visit; + + virtual bool visit(AST::NumericLiteral *node) + { + if (node->suffix != AST::NumericLiteral::noSuffix) { + const int suffixLength = AST::NumericLiteral::suffixLength[node->suffix]; + const char *suffixSpell = AST::NumericLiteral::suffixSpell[node->suffix]; + QString pre; + pre += QLatin1String("qmlNumberFrom"); + pre += QChar(QLatin1Char(suffixSpell[0])).toUpper(); + pre += QLatin1String(&suffixSpell[1]); + pre += QLatin1Char('('); + _writer.replace(node->literalToken.begin() - _position, 0, pre); + _writer.replace(node->literalToken.end() - _position - suffixLength, + suffixLength, + QLatin1String(")")); + } + + return false; + } +}; + class ProcessAST: protected AST::Visitor { struct State { @@ -107,24 +149,30 @@ protected: QString textAt(const AST::SourceLocation &loc) const { return _contents.mid(loc.offset, loc.length); } + QString textAt(const AST::SourceLocation &first, const AST::SourceLocation &last) const { return _contents.mid(first.offset, last.offset + last.length - first.offset); } - QString asString(AST::ExpressionNode *expr) const + RewriteNumericLiterals rewriteNumericLiterals; + + QString asString(AST::ExpressionNode *expr) { if (! expr) return QString(); - return textAt(expr->firstSourceLocation(), expr->lastSourceLocation()); + return rewriteNumericLiterals(textAt(expr->firstSourceLocation(), expr->lastSourceLocation()), + expr->firstSourceLocation().offset, expr); } - QString asString(AST::Statement *stmt) const + QString asString(AST::Statement *stmt) { if (! stmt) return QString(); - QString s = textAt(stmt->firstSourceLocation(), stmt->lastSourceLocation()); + QString s = rewriteNumericLiterals(textAt(stmt->firstSourceLocation(), stmt->lastSourceLocation()), + stmt->firstSourceLocation().offset, stmt); + s += QLatin1Char('\n'); return s; } @@ -214,7 +262,7 @@ ProcessAST::defineObjectBinding_helper(AST::UiQualifiedId *propertyName, int propertyCount = 0; for (; propertyName; propertyName = propertyName->next){ ++propertyCount; - _stateStack.pushProperty(propertyName->name->asString(), + _stateStack.pushProperty(propertyName->name->asString(), this->location(propertyName)); } @@ -322,7 +370,7 @@ Object *ProcessAST::defineObjectBinding(AST::UiQualifiedId *qualifiedId, script = asString(scriptBinding->statement); } - LocationSpan l = this->location(scriptBinding->statement->firstSourceLocation(), + LocationSpan l = this->location(scriptBinding->statement->firstSourceLocation(), scriptBinding->statement->lastSourceLocation()); _stateStack.pushProperty(QLatin1String("script"), l); @@ -414,7 +462,7 @@ bool ProcessAST::visit(AST::UiPublicMember *node) { "var", Object::DynamicProperty::Variant }, { "variant", Object::DynamicProperty::Variant } }; - const int propTypeNameToTypesCount = sizeof(propTypeNameToTypes) / + const int propTypeNameToTypesCount = sizeof(propTypeNameToTypes) / sizeof(propTypeNameToTypes[0]); bool typeFound = false; @@ -425,7 +473,7 @@ bool ProcessAST::visit(AST::UiPublicMember *node) typeFound = true; } } - + if(!typeFound) { QmlError error; error.setDescription(QCoreApplication::translate("QmlParser","Expected property type")); @@ -515,7 +563,7 @@ bool ProcessAST::visit(AST::UiScriptBinding *node) AST::UiQualifiedId *propertyName = node->qualifiedId; for (; propertyName; propertyName = propertyName->next){ ++propertyCount; - _stateStack.pushProperty(propertyName->name->asString(), + _stateStack.pushProperty(propertyName->name->asString(), location(propertyName)); } @@ -526,7 +574,7 @@ bool ProcessAST::visit(AST::UiScriptBinding *node) if (AST::ExpressionStatement *stmt = AST::cast(node->statement)) { primitive = getVariant(stmt->expression); } else { // do binding - primitive = QmlParser::Variant(asString(node->statement), + primitive = QmlParser::Variant(asString(node->statement), QmlParser::Variant::Script); } @@ -550,7 +598,7 @@ bool ProcessAST::visit(AST::UiArrayBinding *node) AST::UiQualifiedId *propertyName = node->qualifiedId; for (; propertyName; propertyName = propertyName->next){ ++propertyCount; - _stateStack.pushProperty(propertyName->name->asString(), + _stateStack.pushProperty(propertyName->name->asString(), location(propertyName)); } @@ -608,7 +656,7 @@ bool ProcessAST::visit(AST::UiSourceElement *node) } Value *value = new Value; - value->location = location(node->firstSourceLocation(), + value->location = location(node->firstSourceLocation(), node->lastSourceLocation()); value->value = QmlParser::Variant(source); @@ -673,7 +721,7 @@ bool QmlScriptParser::parse(const QByteArray &data, const QUrl &url) process(code, parser.ast()); // Set the url for process errors - for(int ii = 0; ii < _errors.count(); ++ii) + for(int ii = 0; ii < _errors.count(); ++ii) _errors[ii].setUrl(url); } diff --git a/src/declarative/qml/rewriter/rewriter.cpp b/src/declarative/qml/rewriter/rewriter.cpp new file mode 100644 index 0000000..ec504fa --- /dev/null +++ b/src/declarative/qml/rewriter/rewriter.cpp @@ -0,0 +1,55 @@ +#include "rewriter_p.h" +#include "javascriptast_p.h" + +QT_BEGIN_NAMESPACE + +using namespace JavaScript; + +void Rewriter::replace(const AST::SourceLocation &loc, const QString &text) +{ replace(loc.offset, loc.length, text); } + +void Rewriter::remove(const AST::SourceLocation &loc) +{ return replace(loc.offset, loc.length, QString()); } + +void Rewriter::remove(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc) +{ return replace(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset, QString()); } + +void Rewriter::insertTextBefore(const AST::SourceLocation &loc, const QString &text) +{ replace(loc.offset, 0, text); } + +void Rewriter::insertTextAfter(const AST::SourceLocation &loc, const QString &text) +{ replace(loc.offset + loc.length, 0, text); } + +void Rewriter::replace(int offset, int length, const QString &text) +{ textWriter.replace(offset, length, text); } + +void Rewriter::insertText(int offset, const QString &text) +{ replace(offset, 0, text); } + +void Rewriter::removeText(int offset, int length) +{ replace(offset, length, QString()); } + +QString Rewriter::textAt(const AST::SourceLocation &loc) const +{ return _code.mid(loc.offset, loc.length); } + +QString Rewriter::textAt(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc) const +{ return _code.mid(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset); } + +void Rewriter::accept(JavaScript::AST::Node *node) +{ JavaScript::AST::Node::acceptChild(node, this); } + +void Rewriter::moveTextBefore(const AST::SourceLocation &firstLoc, + const AST::SourceLocation &lastLoc, + const AST::SourceLocation &loc) +{ + textWriter.move(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset, loc.offset); +} + +void Rewriter::moveTextAfter(const AST::SourceLocation &firstLoc, + const AST::SourceLocation &lastLoc, + const AST::SourceLocation &loc) +{ + textWriter.move(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset, loc.offset + loc.length); +} + +QT_END_NAMESPACE diff --git a/src/declarative/qml/rewriter/rewriter.pri b/src/declarative/qml/rewriter/rewriter.pri new file mode 100644 index 0000000..987e26d --- /dev/null +++ b/src/declarative/qml/rewriter/rewriter.pri @@ -0,0 +1,4 @@ + +INCLUDEPATH += $$PWD +HEADERS += $$PWD/rewriter_p.h $$PWD/textwriter_p.h +SOURCES += $$PWD/rewriter.cpp $$PWD/textwriter.cpp diff --git a/src/declarative/qml/rewriter/rewriter_p.h b/src/declarative/qml/rewriter/rewriter_p.h new file mode 100644 index 0000000..892c006 --- /dev/null +++ b/src/declarative/qml/rewriter/rewriter_p.h @@ -0,0 +1,112 @@ +#ifndef REWRITER_H +#define REWRITER_H + +#include +#include + +#include "textwriter_p.h" +#include "javascriptastvisitor_p.h" + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +namespace JavaScript { + +//////////////////////////////////////////////////////////////////////////////// +// Replacement +//////////////////////////////////////////////////////////////////////////////// +class Replacement +{ + int _offset; + int _length; + QString _text; + +public: + Replacement(int offset = 0, int length = 0, const QString &text = QString()) + : _offset(offset), _length(length), _text(text) + { } + + bool isNull() const { return _offset == _length; } + operator bool() const { return ! isNull(); } + + int offset() const { return _offset; } + int length() const { return _length; } + QString text() const { return _text; } +}; + + + +//////////////////////////////////////////////////////////////////////////////// +// Rewriter +//////////////////////////////////////////////////////////////////////////////// +class Rewriter: public AST::Visitor +{ +protected: + TextWriter textWriter; +public: + // + // Token based API + // + + /// Returns the text of the token at the given \a location. + QString textAt(const AST::SourceLocation &location) const; + + QString textAt(const AST::SourceLocation &firstLoc, + const AST::SourceLocation &lastLoc) const; + + /// Replace the token at \a loc with the given \a text. + void replace(const AST::SourceLocation &loc, const QString &text); + + /// Remove the token at the given \a location. + void remove(const AST::SourceLocation &location); + + /// Remove all tokens in the range [\a firstLoc, \a lastLoc]. + void remove(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc); + + /// Insert \a text before the token at the given \a location. + void insertTextBefore(const AST::SourceLocation &location, const QString &text); + + /// Insert \a text after the token at the given \a location. + void insertTextAfter(const AST::SourceLocation &loc, const QString &text); + + void moveTextBefore(const AST::SourceLocation &firstLoc, + const AST::SourceLocation &lastLoc, + const AST::SourceLocation &loc); + + void moveTextAfter(const AST::SourceLocation &firstLoc, + const AST::SourceLocation &lastLoc, + const AST::SourceLocation &loc); + + // + // low-level offset based API + // + void replace(int offset, int length, const QString &text); + void insertText(int offset, const QString &text); + void removeText(int offset, int length); + + /// Visit the given \a node. + void accept(AST::Node *node); + + /// Returns the original unchanged source code. + QString code() const { return _code; } + + /// Returns the list of replacements. + QList replacementList() const { return _replacementList; } + +protected: + /// \internal + void setCode(const QString &code) { _code = code; } + +private: + QString _code; + QList _replacementList; +}; + +} // end of namespace JavaScript + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // REWRITER_H diff --git a/src/declarative/qml/rewriter/textwriter.cpp b/src/declarative/qml/rewriter/textwriter.cpp new file mode 100644 index 0000000..d56c9a1 --- /dev/null +++ b/src/declarative/qml/rewriter/textwriter.cpp @@ -0,0 +1,176 @@ +#include "textwriter_p.h" + +QT_BEGIN_NAMESPACE + +using namespace JavaScript; + +TextWriter::TextWriter() + :string(0), cursor(0) +{ +} + +static bool overlaps(int posA, int lengthA, int posB, int lengthB) { + return (posA < posB + lengthB && posA + lengthA > posB + lengthB) + || (posA < posB && posA + lengthA > posB); +} + +bool TextWriter::hasOverlap(int pos, int length) +{ + { + QListIterator i(replaceList); + while (i.hasNext()) { + const Replace &cmd = i.next(); + if (overlaps(pos, length, cmd.pos, cmd.length)) + return true; + } + } + { + QListIterator i(moveList); + while (i.hasNext()) { + const Move &cmd = i.next(); + if (overlaps(pos, length, cmd.pos, cmd.length)) + return true; + } + return false; + } +} + +bool TextWriter::hasMoveInto(int pos, int length) +{ + QListIterator i(moveList); + while (i.hasNext()) { + const Move &cmd = i.next(); + if (cmd.to >= pos && cmd.to < pos + length) + return true; + } + return false; +} + +void TextWriter::replace(int pos, int length, const QString &replacement) +{ + Q_ASSERT(!hasOverlap(pos, length)); + Q_ASSERT(!hasMoveInto(pos, length)); + + Replace cmd; + cmd.pos = pos; + cmd.length = length; + cmd.replacement = replacement; + replaceList += cmd; +} + +void TextWriter::move(int pos, int length, int to) +{ + Q_ASSERT(!hasOverlap(pos, length)); + + Move cmd; + cmd.pos = pos; + cmd.length = length; + cmd.to = to; + moveList += cmd; +} + +void TextWriter::doReplace(const Replace &replace) +{ + int diff = replace.replacement.size() - replace.length; + { + QMutableListIterator i(replaceList); + while (i.hasNext()) { + Replace &c = i.next(); + if (replace.pos < c.pos) + c.pos += diff; + else if (replace.pos + replace.length < c.pos + c.length) + c.length += diff; + } + } + { + QMutableListIterator i(moveList); + while (i.hasNext()) { + Move &c = i.next(); + if (replace.pos < c.pos) + c.pos += diff; + else if (replace.pos + replace.length < c.pos + c.length) + c.length += diff; + + if (replace.pos < c.to) + c.to += diff; + } + } + + if (string) { + string->replace(replace.pos, replace.length, replace.replacement); + } else if (cursor) { + cursor->setPosition(replace.pos); + cursor->setPosition(replace.pos + replace.length, QTextCursor::KeepAnchor); + cursor->insertText(replace.replacement); + } +} + +void TextWriter::doMove(const Move &move) +{ + QString text; + if (string) { + text = string->mid(move.pos, move.length); + } else if (cursor) { + cursor->setPosition(move.pos); + cursor->setPosition(move.pos + move.length, QTextCursor::KeepAnchor); + text = cursor->selectedText(); + } + + Replace cut; + cut.pos = move.pos; + cut.length = move.length; + Replace paste; + paste.pos = move.to; + paste.length = 0; + paste.replacement = text; + + replaceList.append(cut); + replaceList.append(paste); + + Replace cmd; + while (!replaceList.isEmpty()) { + cmd = replaceList.first(); + replaceList.removeFirst(); + doReplace(cmd); + } +} + +void TextWriter::write(QString *s) +{ + string = s; + write_helper(); + string = 0; +} + +void TextWriter::write(QTextCursor *textCursor) +{ + cursor = textCursor; + write_helper(); + cursor = 0; +} + +void TextWriter::write_helper() +{ + if (cursor) + cursor->beginEditBlock(); + { + Replace cmd; + while (!replaceList.isEmpty()) { + cmd = replaceList.first(); + replaceList.removeFirst(); + doReplace(cmd); + } + } + { + Move cmd; + while (!moveList.isEmpty()) { + cmd = moveList.first(); + moveList.removeFirst(); + doMove(cmd); + } + } + if (cursor) + cursor->endEditBlock(); +} + +QT_END_NAMESPACE diff --git a/src/declarative/qml/rewriter/textwriter_p.h b/src/declarative/qml/rewriter/textwriter_p.h new file mode 100644 index 0000000..52d18d3 --- /dev/null +++ b/src/declarative/qml/rewriter/textwriter_p.h @@ -0,0 +1,60 @@ +#ifndef TEXTWRITER_H +#define TEXTWRITER_H + +#include +#include +#include + +QT_BEGIN_HEADER +QT_BEGIN_NAMESPACE + +QT_MODULE(Declarative) + +namespace JavaScript { + +class TextWriter +{ + QString *string; + QTextCursor *cursor; + + struct Replace { + int pos; + int length; + QString replacement; + }; + + QList replaceList; + + struct Move { + int pos; + int length; + int to; + }; + + QList moveList; + + bool hasOverlap(int pos, int length); + bool hasMoveInto(int pos, int length); + + void doReplace(const Replace &replace); + void doMove(const Move &move); + + void write_helper(); + +public: + TextWriter(); + + void replace(int pos, int length, const QString &replacement); + void move(int pos, int length, int to); + + void write(QString *s); + void write(QTextCursor *textCursor); + +}; + +} // end of namespace JavaScript + +QT_END_NAMESPACE +QT_END_HEADER + +#endif // TEXTWRITER_H -- cgit v0.12 From 2248d63c1a32ae84bb6d0bde9021a8074db1b4c9 Mon Sep 17 00:00:00 2001 From: Rohan McGovern Date: Tue, 26 May 2009 10:46:54 +1000 Subject: Fixed qmake writing targets into the root of the current drive when DESTDIR=./ and using Windows, nmake and shadow builds. qmake would canonicalize the DESTDIR of "./" to "". Then it would check if the original DESTDIR ended with "/", and if so, append it to the new DESTDIR, resulting in a DESTDIR of "/" - the root of the current drive. Don't do that. This bug doesn't occur with in-source builds because qmake detects that the source and build directories are the same directory and replaces the DESTDIR of "./" with "" before it reaches the buggy code. Autotest: included Reviewed-by: Lincoln Ramsay --- qmake/generators/win32/winmakefile.cpp | 2 +- tests/auto/qmake/tst_qmake.cpp | 16 ++++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/qmake/generators/win32/winmakefile.cpp b/qmake/generators/win32/winmakefile.cpp index 87f55cf..c7f00dd 100644 --- a/qmake/generators/win32/winmakefile.cpp +++ b/qmake/generators/win32/winmakefile.cpp @@ -626,7 +626,7 @@ void Win32MakefileGenerator::writeStandardParts(QTextStream &t) // do this here so we can set DEST_TARGET to be the complete path to the final target if it is needed. QString orgDestDir = var("DESTDIR"); QString destDir = Option::fixPathToTargetOS(orgDestDir, false); - if (orgDestDir.endsWith('/') || orgDestDir.endsWith(Option::dir_sep)) + if (!destDir.isEmpty() && (orgDestDir.endsWith('/') || orgDestDir.endsWith(Option::dir_sep))) destDir += Option::dir_sep; QString target = QString(project->first("TARGET")+project->first("TARGET_EXT")); target.remove("\""); diff --git a/tests/auto/qmake/tst_qmake.cpp b/tests/auto/qmake/tst_qmake.cpp index 70f1f3c..1178c81 100644 --- a/tests/auto/qmake/tst_qmake.cpp +++ b/tests/auto/qmake/tst_qmake.cpp @@ -63,6 +63,7 @@ public slots: private slots: void simple_app(); + void simple_app_shadowbuild(); void simple_lib(); void simple_dll(); void subdirs(); @@ -143,6 +144,21 @@ void tst_qmake::simple_app() QVERIFY( test_compiler.removeMakefile( workDir ) ); } +void tst_qmake::simple_app_shadowbuild() +{ + QString workDir = base_path + "/testdata/simple_app"; + QString buildDir = base_path + "/testdata/simple_app_build"; + + QVERIFY( test_compiler.qmake( workDir, "simple_app", buildDir )); + QVERIFY( test_compiler.make( buildDir )); + QVERIFY( test_compiler.exists( buildDir, "simple_app", Exe, "1.0.0" )); + QVERIFY( test_compiler.makeClean( buildDir )); + QVERIFY( test_compiler.exists( buildDir, "simple_app", Exe, "1.0.0" )); // Should still exist after a make clean + QVERIFY( test_compiler.makeDistClean( buildDir )); + QVERIFY( !test_compiler.exists( buildDir, "simple_app", Exe, "1.0.0" )); // Should not exist after a make distclean + QVERIFY( test_compiler.removeMakefile( buildDir ) ); +} + void tst_qmake::simple_dll() { QString workDir = base_path + "/testdata/simple_dll"; -- cgit v0.12 From 7fc5d5e693a6a7f4c2bd040b8d6f29fd33a01712 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 11:22:34 +1000 Subject: Always treat CSS-like suffix's as bindings --- src/declarative/qml/qmlscriptparser.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index 07f6b17..fde2771 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -542,7 +542,11 @@ QmlParser::Variant ProcessAST::getVariant(AST::ExpressionNode *expr) } else if (expr->kind == AST::Node::Kind_FalseLiteral) { return QmlParser::Variant(false); } else if (AST::NumericLiteral *lit = AST::cast(expr)) { - return QmlParser::Variant(lit->value, asString(expr)); + if (lit->suffix == AST::NumericLiteral::noSuffix) + return QmlParser::Variant(lit->value, asString(expr)); + else + return QmlParser::Variant(asString(expr), QmlParser::Variant::Script); + } else { if (AST::UnaryMinusExpression *unaryMinus = AST::cast(expr)) { -- cgit v0.12 From 682b854872c26d7408d79131217825fb8ddace6a Mon Sep 17 00:00:00 2001 From: Michael Goddard Date: Tue, 26 May 2009 10:39:36 +1000 Subject: BT:Fix access of deleted memory with a static QCursor. If a QCursor with a predefined shape is declared static, it could be destroyed after the application dtor has already cleaned up QCursor memory. Task-number: 254467 Reviewed-by: Rhys Weatherley --- src/gui/kernel/qcursor.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gui/kernel/qcursor.cpp b/src/gui/kernel/qcursor.cpp index ed7e020..598f4ba 100644 --- a/src/gui/kernel/qcursor.cpp +++ b/src/gui/kernel/qcursor.cpp @@ -375,7 +375,9 @@ void QCursorData::cleanup() return; for (int shape = 0; shape <= Qt::LastCursor; ++shape) { - delete qt_cursorTable[shape]; + // In case someone has a static QCursor defined with this shape + if (!qt_cursorTable[shape]->ref.deref()) + delete qt_cursorTable[shape]; qt_cursorTable[shape] = 0; } QCursorData::initialized = false; -- cgit v0.12 From 4c1cdb0bf25847a8ebf42cf573faf5b2386000b9 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 15:13:43 +1000 Subject: Ensure tests pass --- src/declarative/qml/qmlcompiler.cpp | 49 +++++++++++++--------- src/declarative/qml/qmlcompiler_p.h | 5 +-- src/declarative/qml/qmlcompositetypemanager.cpp | 2 + .../qmlparser/failingComponent.errors.txt | 4 +- .../qmlparser/fakeDotProperty.errors.txt | 2 +- tests/auto/declarative/qmlparser/tst_qmlparser.cpp | 8 ++-- 6 files changed, 40 insertions(+), 30 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 5f92721..a247f8b 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -154,28 +154,18 @@ int QmlCompiledData::indexForLocation(const QmlParser::LocationSpan &l) } QmlCompiler::QmlCompiler() -: exceptionLine(-1), exceptionColumn(-1), output(0) +: output(0) { } bool QmlCompiler::isError() const { - return exceptionLine != -1; + return !exceptions.isEmpty(); } QList QmlCompiler::errors() const { - QList rv; - - if(isError()) { - QmlError error; - error.setDescription(exceptionDescription); - error.setLine(exceptionLine); - error.setColumn(exceptionColumn); - rv << error; - } - - return rv; + return exceptions; } bool QmlCompiler::isValidId(const QString &val) @@ -436,21 +426,29 @@ void QmlCompiler::reset(QmlCompiledComponent *cc, bool deleteMemory) #define COMPILE_EXCEPTION2(token, desc) \ { \ - exceptionLine = token->location.start.line; \ - exceptionColumn = token->location.start.column; \ + QString exceptionDescription; \ + QmlError error; \ + error.setUrl(output->url); \ + error.setLine(token->location.start.line); \ + error.setColumn(token->location.start.column); \ QDebug d(&exceptionDescription); \ d << desc; \ - exceptionDescription = exceptionDescription.trimmed(); \ + error.setDescription(exceptionDescription.trimmed()); \ + exceptions << error; \ return false; \ } #define COMPILE_EXCEPTION(desc) \ { \ - exceptionLine = obj->location.start.line; \ - exceptionColumn = obj->location.start.column; \ + QString exceptionDescription; \ + QmlError error; \ + error.setUrl(output->url); \ + error.setLine(obj->location.start.line); \ + error.setColumn(obj->location.start.column); \ QDebug d(&exceptionDescription); \ d << desc; \ - exceptionDescription = exceptionDescription.trimmed(); \ + error.setDescription(exceptionDescription.trimmed()); \ + exceptions << error; \ return false; \ } @@ -466,7 +464,7 @@ bool QmlCompiler::compile(QmlEngine *engine, #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer pc; #endif - exceptionLine = -1; + exceptions.clear(); Q_ASSERT(out); reset(out, true); @@ -481,6 +479,17 @@ bool QmlCompiler::compile(QmlEngine *engine, ref.type = tref.type; else if (tref.unit) { ref.component = tref.unit->toComponent(engine); + + if (ref.component->isError()) { + QmlError error; + error.setUrl(output->url); + error.setDescription(QLatin1String("Unable to create type ") + + unit->data.types().at(ii)); + exceptions << error; + exceptions << ref.component->errors(); + reset(out, true); + return false; + } ref.ref = tref.unit; ref.ref->addref(); } diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index bc04cfa..5ada98a 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -170,9 +170,8 @@ private: int optimizeExpressions(int start, int end, int patch = -1); QSet ids; - qint64 exceptionLine; - qint64 exceptionColumn; - QString exceptionDescription; + + QList exceptions; QmlCompiledData *output; }; diff --git a/src/declarative/qml/qmlcompositetypemanager.cpp b/src/declarative/qml/qmlcompositetypemanager.cpp index 0da1a92..a5e302c 100644 --- a/src/declarative/qml/qmlcompositetypemanager.cpp +++ b/src/declarative/qml/qmlcompositetypemanager.cpp @@ -86,6 +86,8 @@ QmlComponent *QmlCompositeTypeData::toComponent(QmlEngine *engine) component = new QmlComponent(engine, cc, -1, -1, 0); } else { component = new QmlComponent(engine, 0); + component->d_func()->url = QUrl(url); + component->d_func()->errors = errors; } } diff --git a/tests/auto/declarative/qmlparser/failingComponent.errors.txt b/tests/auto/declarative/qmlparser/failingComponent.errors.txt index 0db1271..12fb4e7 100644 --- a/tests/auto/declarative/qmlparser/failingComponent.errors.txt +++ b/tests/auto/declarative/qmlparser/failingComponent.errors.txt @@ -1,2 +1,2 @@ -2:-1:Unknown property "a" -2:-1:Unable to create object of type "FailingComponent" +-1:-1:Unable to create type FailingComponent +2:5:Cannot assign value to non-existant property "a" diff --git a/tests/auto/declarative/qmlparser/fakeDotProperty.errors.txt b/tests/auto/declarative/qmlparser/fakeDotProperty.errors.txt index 6c42157..a94b38e 100644 --- a/tests/auto/declarative/qmlparser/fakeDotProperty.errors.txt +++ b/tests/auto/declarative/qmlparser/fakeDotProperty.errors.txt @@ -1 +1 @@ -2:-1:Cannot set properties on value as it is of unknown type +2:11:Cannot assign value to non-existant property "something" diff --git a/tests/auto/declarative/qmlparser/tst_qmlparser.cpp b/tests/auto/declarative/qmlparser/tst_qmlparser.cpp index 91433ba..0852d35 100644 --- a/tests/auto/declarative/qmlparser/tst_qmlparser.cpp +++ b/tests/auto/declarative/qmlparser/tst_qmlparser.cpp @@ -70,8 +70,8 @@ private: error.description().toUtf8(); \ actual << errorStr; \ } \ - if (qgetenv("DEBUG") != "") \ - qWarning() << expected << actual; \ + if (qgetenv("DEBUG") != "" && expected != actual) \ + qWarning() << "Expected:" << expected << "Actual:" << actual; \ QCOMPARE(expected, actual); \ } @@ -129,12 +129,12 @@ void tst_qmlparser::errors_data() QTest::newRow("unsupportedProperty") << "unsupportedProperty.txt" << "unsupportedProperty.errors.txt" << false; QTest::newRow("nullDotProperty") << "nullDotProperty.txt" << "nullDotProperty.errors.txt" << true; - QTest::newRow("fakeDotProperty") << "fakeDotProperty.txt" << "fakeDotProperty.errors.txt" << true; + QTest::newRow("fakeDotProperty") << "fakeDotProperty.txt" << "fakeDotProperty.errors.txt" << false; QTest::newRow("duplicateIDs") << "duplicateIDs.txt" << "duplicateIDs.errors.txt" << false; QTest::newRow("unregisteredObject") << "unregisteredObject.txt" << "unregisteredObject.errors.txt" << false; QTest::newRow("empty") << "empty.txt" << "empty.errors.txt" << false; QTest::newRow("missingObject") << "missingObject.txt" << "missingObject.errors.txt" << false; - QTest::newRow("failingComponent") << "failingComponent.txt" << "failingComponent.errors.txt" << true; + QTest::newRow("failingComponent") << "failingComponent.txt" << "failingComponent.errors.txt" << false; QTest::newRow("missingSignal") << "missingSignal.txt" << "missingSignal.errors.txt" << false; } -- cgit v0.12 From 3aff93a5bba79bdf45f13e4c9f8c66c9a9ed47b4 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 15:31:09 +1000 Subject: Remove Try*Object instructions --- src/declarative/qml/qmlcompiler.cpp | 60 +++++++++++++++------------------- src/declarative/qml/qmlinstruction.cpp | 6 ---- src/declarative/qml/qmlinstruction_p.h | 2 -- src/declarative/qml/qmlvme.cpp | 42 ------------------------ 4 files changed, 27 insertions(+), 83 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index a247f8b..73c50e8 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -561,23 +561,28 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) COMPILE_CHECK(compileDynamicMeta(obj)); + int parserStatusCast = -1; if (obj->type != -1) { - if (output->types.at(obj->type).component) { - QmlInstruction begin; - begin.type = QmlInstruction::TryBeginObject; - begin.line = obj->location.start.line; - output->bytecode << begin; - } else { - int cast = QmlMetaType::qmlParserStatusCast(QmlMetaType::type(output->types.at(obj->type).className)); - if (cast != -1) { - QmlInstruction begin; - begin.type = QmlInstruction::BeginObject; - begin.begin.castValue = cast; - begin.line = obj->location.start.line; - output->bytecode << begin; - } + // ### Optimize + const QMetaObject *mo = obj->metatype; + QmlType *type = 0; + while (!type && mo) { + type = QmlMetaType::qmlType(mo); + mo = mo->superClass(); } - } + + Q_ASSERT(type); + + parserStatusCast = type->parserStatusCast(); + } + + if (parserStatusCast != -1) { + QmlInstruction begin; + begin.type = QmlInstruction::BeginObject; + begin.begin.castValue = parserStatusCast; + begin.line = obj->location.start.line; + output->bytecode << begin; + } bool isCustomParser = output->types.at(obj->type).type && output->types.at(obj->type).type->customParser() != 0; @@ -620,22 +625,12 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) output->indexForByteArray(customData); } - if (obj->type != -1) { - if (output->types.at(obj->type).component) { - QmlInstruction complete; - complete.type = QmlInstruction::TryCompleteObject; - complete.line = obj->location.start.line; - output->bytecode << complete; - } else { - int cast = QmlMetaType::qmlParserStatusCast(QmlMetaType::type(output->types.at(obj->type).className)); - if (cast != -1) { - QmlInstruction complete; - complete.type = QmlInstruction::CompleteObject; - complete.complete.castValue = cast; - complete.line = obj->location.start.line; - output->bytecode << complete; - } - } + if (parserStatusCast != -1) { + QmlInstruction complete; + complete.type = QmlInstruction::CompleteObject; + complete.complete.castValue = parserStatusCast; + complete.line = obj->location.start.line; + output->bytecode << complete; } return true; @@ -1419,8 +1414,7 @@ int QmlCompiler::optimizeExpressions(int start, int end, int patch) if (instr.type == QmlInstruction::StoreBinding || instr.type == QmlInstruction::StoreCompiledBinding) { ++bindingsCount; - } else if (instr.type == QmlInstruction::TryBeginObject || - instr.type == QmlInstruction::BeginObject) { + } else if (instr.type == QmlInstruction::BeginObject) { ++parserStatusCount; } diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index 923d36f..143dc9b 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -139,15 +139,9 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) case QmlInstruction::StoreValueSource: qWarning() << idx << "\t" << line << "\t" << "STORE_VALUE_SOURCE\t" << instr->assignValueSource.property; break; - case QmlInstruction::TryBeginObject: - qWarning() << idx << "\t" << line << "\t" << "TRY_BEGIN"; - break; case QmlInstruction::BeginObject: qWarning() << idx << "\t" << line << "\t" << "BEGIN\t\t\t" << instr->begin.castValue; break; - case QmlInstruction::TryCompleteObject: - qWarning() << idx << "\t" << line << "\t" << "TRY_COMPLETE"; - break; case QmlInstruction::CompleteObject: qWarning() << idx << "\t" << line << "\t" << "COMPLETE\t\t" << instr->complete.castValue; break; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index a21ccee..a2f7ede 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -118,9 +118,7 @@ public: StoreCompiledBinding, /* assignBinding */ StoreValueSource, /* assignValueSource */ - TryBeginObject, BeginObject, /* begin */ - TryCompleteObject, CompleteObject, /* complete */ AssignObject, /* assignObject */ diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index a5cc649..2a5a042 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -92,9 +92,7 @@ Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { Q_DECLARE_PERFORMANCE_METRIC(InstrStoreBinding); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreCompiledBinding); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreValueSource); - Q_DECLARE_PERFORMANCE_METRIC(InstrTryBeginObject); Q_DECLARE_PERFORMANCE_METRIC(InstrBeginObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrTryCompleteObject); Q_DECLARE_PERFORMANCE_METRIC(InstrCompleteObject); Q_DECLARE_PERFORMANCE_METRIC(InstrAssignObject); Q_DECLARE_PERFORMANCE_METRIC(InstrAssignObjectList); @@ -138,9 +136,7 @@ Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { Q_DEFINE_PERFORMANCE_METRIC(InstrStoreBinding, "StoreBinding"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreCompiledBinding, "StoreCompiledBinding"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreValueSource, "StoreValueSource"); - Q_DEFINE_PERFORMANCE_METRIC(InstrTryBeginObject, "TryBeginObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrBeginObject, "BeginObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrTryCompleteObject, "TryCompleteObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrCompleteObject, "CompleteObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrAssignObject, "AssignObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrAssignObjectList, "AssignObjectList"); @@ -403,25 +399,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; - case QmlInstruction::TryBeginObject: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - QmlParserStatus *status = - qobject_cast(target); - - if (status) { - instr.type = QmlInstruction::BeginObject; - instr.begin.castValue = int(reinterpret_cast(status) - reinterpret_cast(target)); - --ii; - } else { - instr.type = QmlInstruction::NoOp; - } - } - break; - case QmlInstruction::BeginObject: { #ifdef Q_ENABLE_PERFORMANCE_LOG @@ -436,25 +413,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; - case QmlInstruction::TryCompleteObject: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - QmlParserStatus *status = - qobject_cast(target); - - if (status) { - instr.type = QmlInstruction::CompleteObject; - instr.complete.castValue = int(reinterpret_cast(status) - reinterpret_cast(target)); - --ii; - } else { - instr.type = QmlInstruction::NoOp; - } - } - break; - case QmlInstruction::CompleteObject: { #ifdef Q_ENABLE_PERFORMANCE_LOG -- cgit v0.12 From 6fb3a8884701b3a08607d0d8ec2e67fabf56d468 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 16:39:12 +1000 Subject: Remove AssignObject instruction --- src/declarative/qml/qmlcompiler.cpp | 65 +++++----- src/declarative/qml/qmlinstruction.cpp | 3 - src/declarative/qml/qmlinstruction_p.h | 3 +- src/declarative/qml/qmlvme.cpp | 142 +++++---------------- .../qmlparser/assignObjectToVariant.txt | 4 + tests/auto/declarative/qmlparser/tst_qmlparser.cpp | 10 ++ 6 files changed, 85 insertions(+), 142 deletions(-) create mode 100644 tests/auto/declarative/qmlparser/assignObjectToVariant.txt diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 73c50e8..1022028 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -1102,8 +1102,40 @@ bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, { if (v->object->type != -1) v->object->metatype = output->types.at(v->object->type).metaObject(); + Q_ASSERT(v->object->metaObject()); - if (v->object->metaObject()) { + if (prop->index == -1) + COMPILE_EXCEPTION2(prop, "Cannot assign object to non-existant property" << prop->name); + + + if (QmlMetaType::isInterface(prop->type)) { + + COMPILE_CHECK(compileObject(v->object, ctxt)); + + QmlInstruction assign; + assign.type = QmlInstruction::StoreInterface; + assign.line = v->object->location.start.line; + assign.storeObject.propertyIndex = prop->index; + assign.storeObject.cast = 0; + output->bytecode << assign; + + v->type = Value::CreatedObject; + + } else if (prop->type == -1) { + + // Variant + // ### Is it always? + COMPILE_CHECK(compileObject(v->object, ctxt)); + + QmlInstruction assign; + assign.type = QmlInstruction::StoreVariantObject; + assign.line = v->object->location.start.line; + assign.storeObject.propertyIndex = prop->index; + assign.storeObject.cast = 0; + output->bytecode << assign; + + v->type = Value::CreatedObject; + } else { const QMetaObject *propmo = QmlMetaType::rawMetaObjectForType(prop->type); @@ -1128,22 +1160,7 @@ bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, } } - if (!propmo && !isPropertyValue) { - COMPILE_CHECK(compileObject(v->object, ctxt)); - - QmlInstruction assign; - assign.type = QmlInstruction::AssignObject; - assign.line = v->object->location.start.line; - assign.assignObject.castValue = 0; - if (prop->isDefault) - assign.assignObject.property = -1; - else - assign.assignObject.property = - output->indexForByteArray(prop->name); - output->bytecode << assign; - - v->type = Value::CreatedObject; - } else if (isAssignable) { + if (isAssignable) { COMPILE_CHECK(compileObject(v->object, ctxt)); QmlInstruction assign; @@ -1187,20 +1204,8 @@ bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, v->type = Value::ValueSource; } else { - COMPILE_EXCEPTION("Unassignable object"); + COMPILE_EXCEPTION2(v->object, "Unassignable object"); } - - } else { - COMPILE_CHECK(compileObject(v->object, ctxt)); - - QmlInstruction assign; - assign.type = QmlInstruction::AssignObject; - assign.line = v->object->location.start.line; - assign.assignObject.property = output->indexForByteArray(prop->name); - assign.assignObject.castValue = 0; - output->bytecode << assign; - - v->type = Value::CreatedObject; } return true; diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index 143dc9b..99f6253 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -145,9 +145,6 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) case QmlInstruction::CompleteObject: qWarning() << idx << "\t" << line << "\t" << "COMPLETE\t\t" << instr->complete.castValue; break; - case QmlInstruction::AssignObject: - qWarning() << idx << "\t" << line << "\t" << "ASSIGN_OBJECT\t\t" << instr->assignObject.property << "\t" << instr->assignObject.castValue << "\t\t" << ((instr->assignObject.property == -1)?QByteArray("default"):datas.at(instr->assignObject.property)); - break; case QmlInstruction::AssignObjectList: qWarning() << idx << "\t" << line << "\t" << "ASSIGN_OBJECT_LIST\t" << instr->assignObject.property << "\t" << instr->assignObject.castValue << "\t\t" << ((instr->assignObject.property == -1)?QByteArray("default"):datas.at(instr->assignObject.property)); break; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index a2f7ede..8959794 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -100,6 +100,8 @@ public: StoreVariant, /* storeString */ StoreObject, /* storeObject */ StoreInstructionsEnd = StoreObject, + StoreVariantObject, /* storeObject */ + StoreInterface, /* storeObject */ StoreSignal, /* storeSignal */ @@ -121,7 +123,6 @@ public: BeginObject, /* begin */ CompleteObject, /* complete */ - AssignObject, /* assignObject */ AssignObjectList, /* assignObject */ FetchAttached, /* fetchAttached */ diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 2a5a042..299b969 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -94,7 +94,6 @@ Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { Q_DECLARE_PERFORMANCE_METRIC(InstrStoreValueSource); Q_DECLARE_PERFORMANCE_METRIC(InstrBeginObject); Q_DECLARE_PERFORMANCE_METRIC(InstrCompleteObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrAssignObject); Q_DECLARE_PERFORMANCE_METRIC(InstrAssignObjectList); Q_DECLARE_PERFORMANCE_METRIC(InstrFetchAttached); Q_DECLARE_PERFORMANCE_METRIC(InstrFetchQmlList); @@ -138,7 +137,6 @@ Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { Q_DEFINE_PERFORMANCE_METRIC(InstrStoreValueSource, "StoreValueSource"); Q_DEFINE_PERFORMANCE_METRIC(InstrBeginObject, "BeginObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrCompleteObject, "CompleteObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrAssignObject, "AssignObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrAssignObjectList, "AssignObjectList"); Q_DEFINE_PERFORMANCE_METRIC(InstrFetchAttached, "FetchAttached"); Q_DEFINE_PERFORMANCE_METRIC(InstrFetchQmlList, "FetchQmlList"); @@ -369,10 +367,14 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QMetaObject::connect(target, prop.coreIndex(), assign, method.methodIndex()); } else if (prop.type() & QmlMetaProperty::Property) { + // ### FIXME + /* instr.type = QmlInstruction::AssignObject; instr.assignObject.castValue = 0; instr.assignObject.property = sigIdx; --ii; + */ + VME_EXCEPTION("Cannot assign an object to signal property" << pr); } else { VME_EXCEPTION("Cannot assign an object to signal property" << pr); } @@ -589,122 +591,46 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; - case QmlInstruction::AssignObject: + case QmlInstruction::StoreVariantObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *assign = stack.pop(); QObject *target = stack.top(); - QByteArray property; - if (instr.assignObject.property == -1) { - // XXX - optimize! - property = - QmlMetaType::defaultProperty(target).name(); - } else { - property = datas.at(instr.assignObject.property); - } - - int coreIdx = qIndexOfProperty(target, property); - - if (coreIdx != -1) { - QMetaProperty prop = - target->metaObject()->property(coreIdx); - int t = prop.userType(); - // XXX - optimize! - if (QmlMetaType::isList(t)) { - QVariant list = prop.read(target); - int listtype = QmlMetaType::listType(t); - QVariant v = QmlMetaType::fromObject(assign, listtype); - QmlMetaType::append(list, v); - } else if (QmlMetaType::isQmlList(t)) { - - // XXX - optimize! - QVariant list = prop.read(target); - QmlPrivate::ListInterface *li = - *(QmlPrivate::ListInterface **)list.constData(); - - int type = li->type(); - - const QMetaObject *mo = - QmlMetaType::rawMetaObjectForType(type); - - const QMetaObject *assignMo = assign->metaObject(); - bool found = false; - while(!found && assignMo) { - if (assignMo == mo) - found = true; - else - assignMo = assignMo->superClass(); - } - - if (!found) - VME_EXCEPTION("Cannot assign object to list"); - - // NOTE: This assumes a cast to QObject does not alter - // the object pointer - void *d = (void *)&assign; - li->append(d); - - } else if (QmlMetaType::isInterface(t)) { - const char *iid = QmlMetaType::interfaceIId(t); - bool ok = false; - if (iid) { - void *ptr = assign->qt_metacast(iid); - if (ptr) { - void *a[1]; - a[0] = &ptr; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - coreIdx, a); - ok = true; - } - } - - if (!ok) - VME_EXCEPTION("Cannot assign object to interface property" << property); - - } else if (prop.userType() == -1 /* means qvariant */) { - prop.write(target, qVariantFromValue(assign)); - } else { - const QMetaObject *propmo = - QmlMetaType::rawMetaObjectForType(t); - - bool isPropertyValue = false; - bool isAssignable = false; - const QMetaObject *c = assign->metaObject(); - while(c) { - isPropertyValue = isPropertyValue || (c == &QmlPropertyValueSource::staticMetaObject); - isAssignable = isAssignable || (c == propmo); - c = c->superClass(); - } - - if (isAssignable) { - // XXX - optimize! - QVariant v = QmlMetaType::fromObject(assign, t); - prop.write(target, v); - } else if (isPropertyValue) { - QmlPropertyValueSource *vs = - static_cast(assign); - vs->setParent(target); - vs->setTarget(QmlMetaProperty(target, coreIdx)); - } else { - VME_EXCEPTION("Cannot assign to" << property); - } - } + QVariant v = QVariant::fromValue(assign); + void *a[1]; + a[0] = (void *)&v; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeObject.propertyIndex, a); + } + break; + case QmlInstruction::StoreInterface: + { + QObject *assign = stack.pop(); + QObject *target = stack.top(); - } else { - if (instr.assignObject.property == -1) { - VME_EXCEPTION("Cannot assign to default property"); - } else { - VME_EXCEPTION("Cannot assign to non-existant property" << property); + int coreIdx = instr.storeObject.propertyIndex; + QMetaProperty prop = target->metaObject()->property(coreIdx); + int t = prop.userType(); + const char *iid = QmlMetaType::interfaceIId(t); + bool ok = false; + if (iid) { + void *ptr = assign->qt_metacast(iid); + if (ptr) { + void *a[1]; + a[0] = &ptr; + QMetaObject::metacall(target, + QMetaObject::WriteProperty, + coreIdx, a); + ok = true; } - } + } + if (!ok) + VME_EXCEPTION("Cannot assign object to interface property"); } break; - + case QmlInstruction::FetchAttached: { #ifdef Q_ENABLE_PERFORMANCE_LOG diff --git a/tests/auto/declarative/qmlparser/assignObjectToVariant.txt b/tests/auto/declarative/qmlparser/assignObjectToVariant.txt new file mode 100644 index 0000000..180221d --- /dev/null +++ b/tests/auto/declarative/qmlparser/assignObjectToVariant.txt @@ -0,0 +1,4 @@ +Object { + property var a; + a: MyQmlObject {} +} diff --git a/tests/auto/declarative/qmlparser/tst_qmlparser.cpp b/tests/auto/declarative/qmlparser/tst_qmlparser.cpp index 0852d35..cdc2a72 100644 --- a/tests/auto/declarative/qmlparser/tst_qmlparser.cpp +++ b/tests/auto/declarative/qmlparser/tst_qmlparser.cpp @@ -26,6 +26,7 @@ private slots: void interfaceQmlList(); void interfaceQList(); void assignObjectToSignal(); + void assignObjectToVariant(); void assignLiteralSignalProperty(); void assignQmlComponent(); void assignBasicTypes(); @@ -208,6 +209,15 @@ void tst_qmlparser::assignObjectToSignal() emit object->basicSignal(); } +void tst_qmlparser::assignObjectToVariant() +{ + QmlComponent component(&engine, TEST_FILE("assignObjectToVariant.txt")); + QObject *object = component.create(); + QVERIFY(object != 0); + QVariant v = object->property("a"); + QVERIFY(v.userType() == qMetaTypeId()); +} + void tst_qmlparser::assignLiteralSignalProperty() { QmlComponent component(&engine, TEST_FILE("assignLiteralSignalProperty.txt")); -- cgit v0.12 From 34163a31908ac00cf20ba3c8c885e767bdfbc0e0 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 16:48:12 +1000 Subject: Unify the store instructions into the main VME switch --- src/declarative/qml/qmlinstruction_p.h | 2 - src/declarative/qml/qmlvme.cpp | 517 ++++++++++++++++----------------- src/declarative/qml/qmlvme_p.h | 3 - 3 files changed, 249 insertions(+), 273 deletions(-) diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index 8959794..190cab5 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -83,7 +83,6 @@ public: // StoreObject - Pop the object on the top of the object stack and // store it in a core property StoreReal, /* storeReal */ - StoreInstructionsStart = StoreReal, StoreInteger, /* storeInteger */ StoreBool, /* storeBool */ StoreString, /* storeString */ @@ -99,7 +98,6 @@ public: StoreRectF, /* storeRect */ StoreVariant, /* storeString */ StoreObject, /* storeObject */ - StoreInstructionsEnd = StoreObject, StoreVariantObject, /* storeObject */ StoreInterface, /* storeObject */ diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 299b969..e9649c5 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -204,6 +204,9 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in const QList &datas = comp->datas; const QList &synthesizedMetaObjects = comp->synthesizedMetaObjects;; const QList &customTypeData = comp->customTypeData; + const QList &intData = comp->intData; + const QList &floatData = comp->floatData; + #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer cr; @@ -225,13 +228,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in for (int ii = start; !isError() && ii < (start + count); ++ii) { QmlInstruction &instr = comp->bytecode[ii]; - if (instr.type >= QmlInstruction::StoreInstructionsStart && - instr.type <= QmlInstruction::StoreInstructionsEnd) { - - runStoreInstruction(stack, instr, comp); - - } else { - switch(instr.type) { case QmlInstruction::Init: { @@ -321,6 +317,252 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; + case QmlInstruction::StoreVariant: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + // XXX - can be more efficient + QVariant v = QmlStringConverters::variantFromString(primitives.at(instr.storeString.value)); + a[0] = (void *)&v; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeString.propertyIndex, a); + } + break; + + case QmlInstruction::StoreString: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + a[0] = (void *)&primitives.at(instr.storeString.value); + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeString.propertyIndex, a); + } + break; + + case QmlInstruction::StoreReal: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + //### moc treats qreal properties as having type double + double r = static_cast(instr.storeReal.value); + void *a[1]; + a[0] = &r; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeReal.propertyIndex, a); + } + break; + + case QmlInstruction::StoreBool: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + a[0] = (void *)&instr.storeBool.value; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeBool.propertyIndex, a); + } + break; + + case QmlInstruction::StoreInteger: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + a[0] = (void *)&instr.storeInteger.value; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeReal.propertyIndex, a); + } + break; + + case QmlInstruction::StoreColor: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QColor c = QColor::fromRgba(instr.storeColor.value); + a[0] = (void *)&c; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeColor.propertyIndex, a); + } + break; + + case QmlInstruction::StoreDate: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QDate d = QDate::fromJulianDay(instr.storeDate.value); + a[0] = (void *)&d; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeDate.propertyIndex, a); + } + break; + + case QmlInstruction::StoreTime: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + //QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QTime t; + t.setHMS(intData.at(instr.storeTime.valueIndex), + intData.at(instr.storeTime.valueIndex+1), + intData.at(instr.storeTime.valueIndex+2), + intData.at(instr.storeTime.valueIndex+3)); + a[0] = (void *)&t; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeTime.propertyIndex, a); + } + break; + + case QmlInstruction::StoreDateTime: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + //QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QTime t; + t.setHMS(intData.at(instr.storeDateTime.valueIndex+1), + intData.at(instr.storeDateTime.valueIndex+2), + intData.at(instr.storeDateTime.valueIndex+3), + intData.at(instr.storeDateTime.valueIndex+4)); + QDateTime dt(QDate::fromJulianDay(intData.at(instr.storeDateTime.valueIndex)), t); + a[0] = (void *)&dt; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeDateTime.propertyIndex, a); + } + break; + + case QmlInstruction::StorePoint: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QPoint p = QPointF(floatData.at(instr.storeRealPair.valueIndex), + floatData.at(instr.storeRealPair.valueIndex+1)).toPoint(); + a[0] = (void *)&p; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeRealPair.propertyIndex, a); + } + break; + + case QmlInstruction::StorePointF: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QPointF p(floatData.at(instr.storeRealPair.valueIndex), + floatData.at(instr.storeRealPair.valueIndex+1)); + a[0] = (void *)&p; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeRealPair.propertyIndex, a); + } + break; + + case QmlInstruction::StoreSize: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QSize p = QSizeF(floatData.at(instr.storeRealPair.valueIndex), + floatData.at(instr.storeRealPair.valueIndex+1)).toSize(); + a[0] = (void *)&p; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeRealPair.propertyIndex, a); + } + break; + + case QmlInstruction::StoreSizeF: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QSizeF s(floatData.at(instr.storeRealPair.valueIndex), + floatData.at(instr.storeRealPair.valueIndex+1)); + a[0] = (void *)&s; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeRealPair.propertyIndex, a); + } + break; + + case QmlInstruction::StoreRect: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + //QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QRect r = QRectF(floatData.at(instr.storeRect.valueIndex), + floatData.at(instr.storeRect.valueIndex+1), + floatData.at(instr.storeRect.valueIndex+2), + floatData.at(instr.storeRect.valueIndex+3)).toRect(); + a[0] = (void *)&r; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeRect.propertyIndex, a); + } + break; + + case QmlInstruction::StoreRectF: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + //QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QRectF r(floatData.at(instr.storeRect.valueIndex), + floatData.at(instr.storeRect.valueIndex+1), + floatData.at(instr.storeRect.valueIndex+2), + floatData.at(instr.storeRect.valueIndex+3)); + a[0] = (void *)&r; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeRect.propertyIndex, a); + } + break; + + case QmlInstruction::StoreObject: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *assignObj = stack.pop(); + QObject *target = stack.top(); + + void *a[1]; + void *obj = (void *)(((char *)assignObj) + instr.storeObject.cast); + a[0] = (void *)&obj; + + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeObject.propertyIndex, a); + } + break; + + case QmlInstruction::AssignCustomType: { QObject *target = stack.top(); @@ -817,7 +1059,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in qFatal("QmlCompiledComponent: Internal error - unknown instruction %d", instr.type); break; } - } } if (isError()) { @@ -858,264 +1099,4 @@ QList QmlVME::errors() const return vmeErrors; } -void QmlVME::runStoreInstruction(QStack &stack, - QmlInstruction &instr, - QmlCompiledData *comp) -{ - const QList &primitives = comp->primitives; - const QList &intData = comp->intData; - const QList &floatData = comp->floatData; - - switch(instr.type) { - case QmlInstruction::StoreVariant: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - // XXX - can be more efficient - QVariant v = QmlStringConverters::variantFromString(primitives.at(instr.storeString.value)); - a[0] = (void *)&v; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeString.propertyIndex, a); - } - break; - - case QmlInstruction::StoreString: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - a[0] = (void *)&primitives.at(instr.storeString.value); - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeString.propertyIndex, a); - } - break; - - case QmlInstruction::StoreReal: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - //### moc treats qreal properties as having type double - double r = static_cast(instr.storeReal.value); - void *a[1]; - a[0] = &r; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeReal.propertyIndex, a); - } - break; - - case QmlInstruction::StoreBool: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - a[0] = (void *)&instr.storeBool.value; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeBool.propertyIndex, a); - } - break; - - case QmlInstruction::StoreInteger: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - a[0] = (void *)&instr.storeInteger.value; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeReal.propertyIndex, a); - } - break; - - case QmlInstruction::StoreColor: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QColor c = QColor::fromRgba(instr.storeColor.value); - a[0] = (void *)&c; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeColor.propertyIndex, a); - } - break; - - case QmlInstruction::StoreDate: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QDate d = QDate::fromJulianDay(instr.storeDate.value); - a[0] = (void *)&d; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeDate.propertyIndex, a); - } - break; - - case QmlInstruction::StoreTime: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - //QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QTime t; - t.setHMS(intData.at(instr.storeTime.valueIndex), - intData.at(instr.storeTime.valueIndex+1), - intData.at(instr.storeTime.valueIndex+2), - intData.at(instr.storeTime.valueIndex+3)); - a[0] = (void *)&t; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeTime.propertyIndex, a); - } - break; - - case QmlInstruction::StoreDateTime: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - //QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QTime t; - t.setHMS(intData.at(instr.storeDateTime.valueIndex+1), - intData.at(instr.storeDateTime.valueIndex+2), - intData.at(instr.storeDateTime.valueIndex+3), - intData.at(instr.storeDateTime.valueIndex+4)); - QDateTime dt(QDate::fromJulianDay(intData.at(instr.storeDateTime.valueIndex)), t); - a[0] = (void *)&dt; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeDateTime.propertyIndex, a); - } - break; - - case QmlInstruction::StorePoint: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QPoint p = QPointF(floatData.at(instr.storeRealPair.valueIndex), - floatData.at(instr.storeRealPair.valueIndex+1)).toPoint(); - a[0] = (void *)&p; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeRealPair.propertyIndex, a); - } - break; - - case QmlInstruction::StorePointF: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QPointF p(floatData.at(instr.storeRealPair.valueIndex), - floatData.at(instr.storeRealPair.valueIndex+1)); - a[0] = (void *)&p; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeRealPair.propertyIndex, a); - } - break; - - case QmlInstruction::StoreSize: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QSize p = QSizeF(floatData.at(instr.storeRealPair.valueIndex), - floatData.at(instr.storeRealPair.valueIndex+1)).toSize(); - a[0] = (void *)&p; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeRealPair.propertyIndex, a); - } - break; - - case QmlInstruction::StoreSizeF: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QSizeF s(floatData.at(instr.storeRealPair.valueIndex), - floatData.at(instr.storeRealPair.valueIndex+1)); - a[0] = (void *)&s; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeRealPair.propertyIndex, a); - } - break; - - case QmlInstruction::StoreRect: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - //QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QRect r = QRectF(floatData.at(instr.storeRect.valueIndex), - floatData.at(instr.storeRect.valueIndex+1), - floatData.at(instr.storeRect.valueIndex+2), - floatData.at(instr.storeRect.valueIndex+3)).toRect(); - a[0] = (void *)&r; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeRect.propertyIndex, a); - } - break; - - case QmlInstruction::StoreRectF: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - //QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - void *a[1]; - QRectF r(floatData.at(instr.storeRect.valueIndex), - floatData.at(instr.storeRect.valueIndex+1), - floatData.at(instr.storeRect.valueIndex+2), - floatData.at(instr.storeRect.valueIndex+3)); - a[0] = (void *)&r; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeRect.propertyIndex, a); - } - break; - - case QmlInstruction::StoreObject: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *assignObj = stack.pop(); - QObject *target = stack.top(); - - void *a[1]; - void *obj = (void *)(((char *)assignObj) + instr.storeObject.cast); - a[0] = (void *)&obj; - - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeObject.propertyIndex, a); - } - break; - default: - qFatal("QmlCompiledComponent: Internal error - unknown instruction %d", instr.type); - break; - } - -} - QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlvme_p.h b/src/declarative/qml/qmlvme_p.h index 4e5c6c1..f2ed576 100644 --- a/src/declarative/qml/qmlvme_p.h +++ b/src/declarative/qml/qmlvme_p.h @@ -64,9 +64,6 @@ public: QList errors() const; private: - void runStoreInstruction(QStack &stack, - QmlInstruction &, QmlCompiledData *); - QList vmeErrors; }; -- cgit v0.12 From e52247f16e608134d1ff663774f930a00a431eb5 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 16:56:18 +1000 Subject: Remove AssignValueSource instruction --- src/declarative/qml/qmlcompiler.cpp | 18 +++++------------- src/declarative/qml/qmlinstruction.cpp | 3 --- src/declarative/qml/qmlinstruction_p.h | 1 - src/declarative/qml/qmlvme.cpp | 26 -------------------------- 4 files changed, 5 insertions(+), 43 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 1022028..0712136 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -1188,19 +1188,11 @@ bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, } else if (isPropertyValue) { COMPILE_CHECK(compileObject(v->object, ctxt)); - if (prop->index != -1) { - QmlInstruction assign; - assign.type = QmlInstruction::StoreValueSource; - assign.line = v->object->location.start.line; - assign.assignValueSource.property = prop->index; - output->bytecode << assign; - } else { - QmlInstruction assign; - assign.type = QmlInstruction::AssignValueSource; - assign.line = v->object->location.start.line; - assign.assignValueSource.property = output->indexForByteArray(prop->name);; - output->bytecode << assign; - } + QmlInstruction assign; + assign.type = QmlInstruction::StoreValueSource; + assign.line = v->object->location.start.line; + assign.assignValueSource.property = prop->index; + output->bytecode << assign; v->type = Value::ValueSource; } else { diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index 99f6253..5197b7b 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -127,9 +127,6 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) case QmlInstruction::AssignSignalObject: qWarning() << idx << "\t" << line << "\t" << "ASSIGN_SIGNAL_OBJECT\t" << instr->assignSignalObject.signal << "\t\t\t" << datas.at(instr->assignSignalObject.signal); break; - case QmlInstruction::AssignValueSource: - qWarning() << idx << "\t" << line << "\t" << "ASSIGN_VALUE_SOURCE\t" << instr->assignValueSource.property << "\t\t\t" << datas.at(instr->assignValueSource.property); - break; case QmlInstruction::StoreBinding: qWarning() << idx << "\t" << line << "\t" << "STORE_BINDING\t\t" << instr->assignBinding.property << "\t" << instr->assignBinding.value << "\t\t" << instr->assignBinding.context << primitives.at(instr->assignBinding.value); break; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index 190cab5..cd66d66 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -113,7 +113,6 @@ public: AssignSignalObject, /* assignSignalObject */ AssignCustomType, /* assignCustomType */ - AssignValueSource, /* assignValueSource */ StoreBinding, /* assignBinding */ StoreCompiledBinding, /* assignBinding */ StoreValueSource, /* assignValueSource */ diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index e9649c5..6d46422 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -88,7 +88,6 @@ Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { Q_DECLARE_PERFORMANCE_METRIC(InstrStoreSignal); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreObjectQmlList); Q_DECLARE_PERFORMANCE_METRIC(InstrAssignSignalObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrAssignValueSource); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreBinding); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreCompiledBinding); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreValueSource); @@ -131,7 +130,6 @@ Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { Q_DEFINE_PERFORMANCE_METRIC(InstrStoreSignal, "StoreSignal"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreObjectQmlList, "StoreObjectQmlList"); Q_DEFINE_PERFORMANCE_METRIC(InstrAssignSignalObject, "AssignSignalObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrAssignValueSource, "AssignValueSource"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreBinding, "StoreBinding"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreCompiledBinding, "StoreCompiledBinding"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreValueSource, "StoreValueSource"); @@ -668,30 +666,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; - case QmlInstruction::AssignValueSource: - { - QObject *target = stack.at(stack.count() - 2); - int propIdx = instr.assignValueSource.property; - QByteArray pr; - if (propIdx == -1) { - pr = QmlMetaType::defaultProperty(target).name(); - if (pr.isEmpty()) - VME_EXCEPTION("Unable to resolve default property"); - } else { - pr = datas.at(propIdx); - } - - int coreIdx = qIndexOfProperty(target, pr); - if (coreIdx != -1) { - instr.type = QmlInstruction::StoreValueSource; - instr.assignValueSource.property = coreIdx; - ii--; - } else { - VME_EXCEPTION("Unknown property" << pr); - } - } - break; - case QmlInstruction::PushProperty: { #ifdef Q_ENABLE_PERFORMANCE_LOG -- cgit v0.12 From a04c23c7731c5c96d066fccdccec6b738265b774 Mon Sep 17 00:00:00 2001 From: Kai Koehne Date: Tue, 26 May 2009 09:07:33 +0200 Subject: Do not expect QListModelInterface::data to return ONLY the roles requested It is often convenient to always return the full set of data, even if only some roles are requested. Reviewed-by: Martin Jones --- src/declarative/fx/qfxvisualitemmodel.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/declarative/fx/qfxvisualitemmodel.cpp b/src/declarative/fx/qfxvisualitemmodel.cpp index 039998a..3e06ff8 100644 --- a/src/declarative/fx/qfxvisualitemmodel.cpp +++ b/src/declarative/fx/qfxvisualitemmodel.cpp @@ -235,7 +235,7 @@ QFxVisualItemModelDataMetaObject::propertyCreated(int, QMetaPropertyBuilder &pro if (values.isEmpty()) return QVariant(); else - return *values.begin(); + return values.value(iter.key()); } } } else if (data->m_model->m_abstractItemModel) { @@ -644,7 +644,7 @@ void QFxVisualItemModel::_q_itemsChanged(int index, int count, int role = data->role(prop); if (roles.contains(role)) { if (d->m_listModelInterface) { - data->setValue(prop, *d->m_listModelInterface->data(ii, QList() << role).begin()); + data->setValue(prop, d->m_listModelInterface->data(ii, QList() << role).value(role)); } else if (d->m_abstractItemModel) { QModelIndex index = d->m_abstractItemModel->index(ii, 0); data->setValue(prop, d->m_abstractItemModel->data(index, role)); -- cgit v0.12 From 51167b0f2f7b3989ed448160fda3209e9382663a Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Tue, 26 May 2009 08:40:54 +0200 Subject: Fix build failure on MacOS 10.4 It seems GLint is typedefed to long on 10.4. Reviewed-By: Rhys Weatherley --- src/opengl/qglframebufferobject.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 8af9f63..2b7ad4f 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -288,7 +288,7 @@ public: ~QGLFramebufferObjectPrivate() {} void init(const QSize& sz, QGLFramebufferObject::Attachment attachment, - GLenum internal_format, GLenum texture_target, int samples = 0); + GLenum internal_format, GLenum texture_target, GLint samples = 0); bool checkFramebufferStatus() const; GLuint texture; GLuint fbo; @@ -350,7 +350,7 @@ bool QGLFramebufferObjectPrivate::checkFramebufferStatus() const } void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::Attachment attachment, - GLenum texture_target, GLenum internal_format, int samples) + GLenum texture_target, GLenum internal_format, GLint samples) { ctx = const_cast(QGLContext::currentContext()); bool ext_detected = (QGLExtensions::glExtensions & QGLExtensions::FramebufferObject); @@ -490,7 +490,7 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At QT_CHECK_GLERROR(); format.setTextureTarget(target); - format.setSamples(samples); + format.setSamples(int(samples)); format.setAttachment(fbo_attachment); format.setInternalFormat(internal_format); } -- cgit v0.12 From b227da8a17cd7b0facc3491d645209e277cb64b7 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 17:18:07 +1000 Subject: Remove ResolveFetchObject instruction --- src/declarative/qml/qmlcompiler.cpp | 18 +++++++++--------- src/declarative/qml/qmlinstruction.cpp | 3 --- src/declarative/qml/qmlinstruction_p.h | 1 - src/declarative/qml/qmlvme.cpp | 26 -------------------------- 4 files changed, 9 insertions(+), 39 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 0712136..ae915db 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -976,16 +976,16 @@ bool QmlCompiler::compileNestedProperty(QmlParser::Property *prop, if (prop->type != 0) prop->value->metatype = QmlMetaType::metaObjectForType(prop->type); + if (prop->index == -1) + COMPILE_EXCEPTION2(prop, "Cannot access non-existant property" << prop->name); + + if (!QmlMetaType::isObject(prop->value->metatype)) + COMPILE_EXCEPTION2(prop, "Cannot nest non-QObject property" << prop->name); + QmlInstruction fetch; - if (prop->index != -1 && - QmlMetaType::isObject(prop->value->metatype)) { - fetch.type = QmlInstruction::FetchObject; - fetch.fetch.property = prop->index; - fetch.fetch.isObject = true; - } else { - fetch.type = QmlInstruction::ResolveFetchObject; - fetch.fetch.property = output->indexForByteArray(prop->name); - } + fetch.type = QmlInstruction::FetchObject; + fetch.fetch.property = prop->index; + fetch.fetch.isObject = true; fetch.line = prop->location.start.line; output->bytecode << fetch; diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index 5197b7b..7103d87 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -157,9 +157,6 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) case QmlInstruction::FetchObject: qWarning() << idx << "\t" << line << "\t" << "FETCH\t\t\t" << instr->fetch.property; break; - case QmlInstruction::ResolveFetchObject: - qWarning() << idx << "\t" << line << "\t" << "RESOLVE_FETCH\t\t" << instr->fetch.property << "\t\t\t" << datas.at(instr->fetch.property); - break; case QmlInstruction::PopFetchedObject: qWarning() << idx << "\t" << line << "\t" << "POP"; break; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index cd66d66..bc696b1 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -126,7 +126,6 @@ public: FetchQmlList, /* fetchQmlList */ FetchQList, /* fetch */ FetchObject, /* fetch */ - ResolveFetchObject, /* fetch */ // // Stack manipulation diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 6d46422..348a706 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -98,7 +98,6 @@ Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { Q_DECLARE_PERFORMANCE_METRIC(InstrFetchQmlList); Q_DECLARE_PERFORMANCE_METRIC(InstrFetchQList); Q_DECLARE_PERFORMANCE_METRIC(InstrFetchObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrResolveFetchObject); Q_DECLARE_PERFORMANCE_METRIC(InstrPopFetchedObject); Q_DECLARE_PERFORMANCE_METRIC(InstrPopQList); Q_DECLARE_PERFORMANCE_METRIC(InstrPushProperty); @@ -140,7 +139,6 @@ Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { Q_DEFINE_PERFORMANCE_METRIC(InstrFetchQmlList, "FetchQmlList"); Q_DEFINE_PERFORMANCE_METRIC(InstrFetchQList, "FetchQList"); Q_DEFINE_PERFORMANCE_METRIC(InstrFetchObject, "FetchObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrResolveFetchObject, "ResolveFetchObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrPopFetchedObject, "PopFetchedObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrPopQList, "PopQList"); Q_DEFINE_PERFORMANCE_METRIC(InstrPushProperty, "PushProperty"); @@ -897,30 +895,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; - case QmlInstruction::ResolveFetchObject: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - QObject *target = stack.top(); - const QByteArray &pr = datas.at(instr.fetch.property); - int idx = qIndexOfProperty(target, pr); - if (idx == -1) - VME_EXCEPTION("Cannot resolve property" << pr); - QMetaProperty prop = target->metaObject()->property(idx); - instr.type = QmlInstruction::FetchObject; - instr.fetch.property = idx; - if (QmlMetaType::isObject(prop.userType())) { - instr.fetch.isObject = true; - } else if (prop.userType() == -1) { - instr.fetch.isObject = false; - } else { - VME_EXCEPTION("Cannot set properties on" << prop.name() << "as it is of unknown type"); - } - ii--; - } - break; - case QmlInstruction::FetchObject: { #ifdef Q_ENABLE_PERFORMANCE_LOG -- cgit v0.12 From 59c3a7ca89742992e3737e8bb03c7e3eacf578e1 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 17:23:16 +1000 Subject: Remove unnecessary condition --- src/declarative/qml/qmlvme.cpp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 348a706..07165ec 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -604,15 +604,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QMetaObject::connect(target, prop.coreIndex(), assign, method.methodIndex()); - } else if (prop.type() & QmlMetaProperty::Property) { - // ### FIXME - /* - instr.type = QmlInstruction::AssignObject; - instr.assignObject.castValue = 0; - instr.assignObject.property = sigIdx; - --ii; - */ - VME_EXCEPTION("Cannot assign an object to signal property" << pr); } else { VME_EXCEPTION("Cannot assign an object to signal property" << pr); } -- cgit v0.12 From baec0ecd314c6e9563bd56cf19571ca71d7d11cd Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 26 May 2009 09:23:55 +0200 Subject: Fixed docs warnings for Animation API --- src/corelib/animation/qanimationgroup.cpp | 2 +- src/corelib/animation/qpropertyanimation.h | 4 ++-- src/corelib/animation/qvariantanimation.cpp | 15 ++++++++++++--- 3 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/corelib/animation/qanimationgroup.cpp b/src/corelib/animation/qanimationgroup.cpp index ed06eff..839b522 100644 --- a/src/corelib/animation/qanimationgroup.cpp +++ b/src/corelib/animation/qanimationgroup.cpp @@ -236,7 +236,7 @@ void QAnimationGroup::removeAnimation(QAbstractAnimation *animation) \note The ownership of the animation is transferred to the caller. - \sa removeAnimation(), addAnimation(), insertAnimation(), indexOfAnimation() + \sa removeAnimation(), addAnimation(), insertAnimationAt(), indexOfAnimation() */ QAbstractAnimation *QAnimationGroup::takeAnimationAt(int index) { diff --git a/src/corelib/animation/qpropertyanimation.h b/src/corelib/animation/qpropertyanimation.h index 5b06bd2..39317ba 100644 --- a/src/corelib/animation/qpropertyanimation.h +++ b/src/corelib/animation/qpropertyanimation.h @@ -72,11 +72,11 @@ public: protected: bool event(QEvent *event); - void updateCurrentValue(const QVariant &value); void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); - Q_PRIVATE_SLOT(d_func(), void _q_targetDestroyed()); + private: + Q_PRIVATE_SLOT(d_func(), void _q_targetDestroyed()); Q_DISABLE_COPY(QPropertyAnimation) Q_DECLARE_PRIVATE(QPropertyAnimation) }; diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp index a6834bb..4542a86 100644 --- a/src/corelib/animation/qvariantanimation.cpp +++ b/src/corelib/animation/qvariantanimation.cpp @@ -63,9 +63,8 @@ QT_BEGIN_NAMESPACE shared functionality. QVariantAnimation cannot be used directly as it is an abstract - class; it does not implement - \l{QAbstractAnimation::}{updateCurrentValue()} from - QAbstractAnimation. The class performs interpolation over + class; it has a pure virtual method called updateCurrentValue(). + The class performs interpolation over \l{QVariant}s, but leaves using the interpolated values to its subclasses. Currently, Qt provides QPropertyAnimation, which animates Qt \l{Qt's Property System}{properties}. See the @@ -130,6 +129,16 @@ QT_BEGIN_NAMESPACE \sa currentValue, startValue, endValue */ +/*! + \fn void QVariantAnimation::updateCurrentValue(const QVariant &value) = 0; + + This pure virtual function is called every time the animation's current + value changes. The \a value argument is the new current value. + + \sa currentValue +*/ + + static bool animationValueLessThan(const QVariantAnimation::KeyValue &p1, const QVariantAnimation::KeyValue &p2) { return p1.first < p2.first; -- cgit v0.12 From d010e6e53c1f3c2704eb3c548e58e8f37febcc29 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 17:46:40 +1000 Subject: Remove the NoOp instruction --- src/declarative/qml/qmlinstruction.cpp | 3 --- src/declarative/qml/qmlinstruction_p.h | 11 ++--------- src/declarative/qml/qmlvme.cpp | 10 ---------- 3 files changed, 2 insertions(+), 22 deletions(-) diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index 7103d87..31bd2f5 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -163,9 +163,6 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) case QmlInstruction::PopQList: qWarning() << idx << "\t" << line << "\t" << "POP_QLIST"; break; - case QmlInstruction::NoOp: - qWarning() << idx << "\t" << line << "\t" << "NOOP"; - break; case QmlInstruction::PushProperty: qWarning() << idx << "\t" << line << "\t" << "PUSH_PROPERTY" << "\t\t" << instr->pushProperty.property; break; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index bc696b1..47a8d76 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -143,17 +143,10 @@ public: // StoreStackObject - Assign the stack object (no checks) PushProperty, /* pushProperty */ AssignStackObject, /* assignStackObject */ - StoreStackObject, /* assignStackObject */ - - - // - // Miscellaneous - // - // NoOp - Do nothing - NoOp + StoreStackObject /* assignStackObject */ }; QmlInstruction() - : type(NoOp), line(0) {} + : line(0) {} Type type; unsigned short line; diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 07165ec..e2441c6 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -103,7 +103,6 @@ Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { Q_DECLARE_PERFORMANCE_METRIC(InstrPushProperty); Q_DECLARE_PERFORMANCE_METRIC(InstrAssignStackObject); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreStackObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrNoOp); Q_DECLARE_PERFORMANCE_METRIC(Dummy); } @@ -144,7 +143,6 @@ Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { Q_DEFINE_PERFORMANCE_METRIC(InstrPushProperty, "PushProperty"); Q_DEFINE_PERFORMANCE_METRIC(InstrAssignStackObject, "AssignStackObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreStackObject, "StoreStackObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrNoOp, "NoOp"); Q_DEFINE_PERFORMANCE_METRIC(Dummy, "Dummy"); } @@ -986,14 +984,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; - case QmlInstruction::NoOp: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - } - break; - default: qFatal("QmlCompiledComponent: Internal error - unknown instruction %d", instr.type); break; -- cgit v0.12 From 02b49e3bf1556c76cd59d205529f04a390cfa433 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 26 May 2009 09:48:09 +0200 Subject: Fix doc warnings for Phonon --- doc/src/phonon-api.qdoc | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/doc/src/phonon-api.qdoc b/doc/src/phonon-api.qdoc index dd37fe2..5deb64e 100644 --- a/doc/src/phonon-api.qdoc +++ b/doc/src/phonon-api.qdoc @@ -1032,6 +1032,7 @@ \value Stream The MediaSource object describes a data stream. This is the type used for \l{QIODevice}s. Note that a stream opened with a QUrl, will still be of the Url type. + \value Empty The media source doesn't have a source. \sa MediaSource::type() */ @@ -2026,6 +2027,15 @@ */ /*! + \fn void Phonon::MediaObject::clear() + + Stops and removes all playing and enqueued media sources. + + \sa setCurrentSource() +*/ + + +/*! \fn void Phonon::MediaObject::stateChanged(Phonon::State newstate, Phonon::State oldstate) This signal is emitted when the state of the MediaObject has changed. @@ -3027,6 +3037,12 @@ */ /*! + \typedef Phonon::AudioOutputInterface + \inmodule Phonon + \internal +*/ + +/*! \class Phonon::AudioOutputInterface40 \inmodule Phonon \since 4.4 @@ -3251,7 +3267,19 @@ /*! \fn bool Phonon::Path::operator!=(const Path &p) const; - Returns true if this Path is not equal to \a p; otherwise returns false; + Returns true if this Path is not equal to \a p; otherwise returns false. +*/ + +/*! + \fn MediaNode *Phonon::Path::source() const; + + Returns the source MediaNode used by the path. +*/ + +/*! + \fn MediaNode *Phonon::Path::sink() const; + + Returns the sink MediaNode used by the path. */ /*! @@ -4878,7 +4906,7 @@ */ /*! - \typedef typedef void (*CleanUpFunction)() + \typedef Phonon::CleanUpFunction \inmodule Phonon \internal */ -- cgit v0.12 From 5839b16a73c36ff7636c13f841d26e6a5e0c5435 Mon Sep 17 00:00:00 2001 From: Maurice Kalinowski Date: Tue, 28 Apr 2009 17:37:52 +0200 Subject: fix double slash prepending causing troubles on WinCE Before adding a / to the path one should check if it doesn't end with one already. Otherwise one might get paths like //My Documents on WinCE causing the native call to crash the filesystem service on that system. Reviewed-by: alexis --- src/gui/dialogs/qfilesystemmodel_p.h | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/gui/dialogs/qfilesystemmodel_p.h b/src/gui/dialogs/qfilesystemmodel_p.h index 0a1265a..61e8b4c 100644 --- a/src/gui/dialogs/qfilesystemmodel_p.h +++ b/src/gui/dialogs/qfilesystemmodel_p.h @@ -164,9 +164,12 @@ public: QHash::const_iterator iterator; for(iterator = children.constBegin() ; iterator != children.constEnd() ; ++iterator) { //On windows the root (My computer) has no path so we don't want to add a / for nothing (e.g. /C:/) - if (!path.isEmpty()) - iterator.value()->updateIcon(iconProvider, path + QLatin1Char('/') + iterator.value()->fileName); - else + if (!path.isEmpty()) { + if (path.endsWith(QLatin1Char('/'))) + iterator.value()->updateIcon(iconProvider, path + iterator.value()->fileName); + else + iterator.value()->updateIcon(iconProvider, path + QLatin1Char('/') + iterator.value()->fileName); + } else iterator.value()->updateIcon(iconProvider, iterator.value()->fileName); } } @@ -177,9 +180,12 @@ public: QHash::const_iterator iterator; for(iterator = children.constBegin() ; iterator != children.constEnd() ; ++iterator) { //On windows the root (My computer) has no path so we don't want to add a / for nothing (e.g. /C:/) - if (!path.isEmpty()) - iterator.value()->retranslateStrings(iconProvider, path + QLatin1Char('/') + iterator.value()->fileName); - else + if (!path.isEmpty()) { + if (path.endsWith(QLatin1Char('/'))) + iterator.value()->retranslateStrings(iconProvider, path + iterator.value()->fileName); + else + iterator.value()->retranslateStrings(iconProvider, path + QLatin1Char('/') + iterator.value()->fileName); + } else iterator.value()->retranslateStrings(iconProvider, iterator.value()->fileName); } } -- cgit v0.12 From a06c0fe5a2c9eebf5e7cceb06f64e725b42715bd Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 18:13:44 +1000 Subject: Remove AssignStackObject instruction --- src/declarative/qml/qmlcompiler.cpp | 26 +++++++++++++++++++++++++- src/declarative/qml/qmlcompiler_p.h | 2 ++ src/declarative/qml/qmlinstruction.cpp | 3 --- src/declarative/qml/qmlinstruction_p.h | 2 -- src/declarative/qml/qmlvme.cpp | 33 --------------------------------- 5 files changed, 27 insertions(+), 39 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index ae915db..89a1774 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -675,6 +675,9 @@ bool QmlCompiler::compileComponent(Object *obj, int ctxt) id.line = idProp->location.start.line; id.setId.value = pref; id.setId.save = -1; + + savedTypes.insert(output->bytecode.count(), -1); + output->bytecode << id; } @@ -936,6 +939,7 @@ bool QmlCompiler::compileIdProperty(QmlParser::Property *prop, id.line = prop->values.at(0)->location.start.line; id.setId.value = pref; id.setId.save = -1; + savedTypes.insert(output->bytecode.count(), obj->type); output->bytecode << id; obj->id = val.toLatin1(); @@ -1369,6 +1373,7 @@ bool QmlCompiler::compileBinding(const QString &bind, QmlParser::Property *prop, assign.assignBinding.category = QmlMetaProperty::propertyCategory(mp); } + savedTypes.insert(output->bytecode.count(), prop->type); output->bytecode << assign; } else { @@ -1427,6 +1432,25 @@ int QmlCompiler::optimizeExpressions(int start, int end, int patch) if (ids.contains(slt) && instr.assignBinding.category == QmlMetaProperty::Object) { int id = ids[slt]; + + int idType = savedTypes.value(id); + int storeType = savedTypes.value(ii); + + const QMetaObject *idMo = (idType == -1)?&QmlComponent::staticMetaObject:output->types.at(idType).metaObject(); + const QMetaObject *storeMo = + QmlMetaType::rawMetaObjectForType(storeType); + + bool canAssign = false; + while (!canAssign && idMo) { + if (idMo == storeMo) + canAssign = true; + else + idMo = idMo->superClass(); + } + + if (!canAssign) + continue; + int saveId = -1; if (output->bytecode.at(id).setId.save != -1) { @@ -1444,7 +1468,7 @@ int QmlCompiler::optimizeExpressions(int start, int end, int patch) rwinstr.pushProperty.property = prop; QmlInstruction instr; - instr.type = QmlInstruction::AssignStackObject; + instr.type = QmlInstruction::StoreStackObject; instr.line = 0; instr.assignStackObject.property = newInstrs; instr.assignStackObject.object = saveId; diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index 5ada98a..3280866 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -173,6 +173,8 @@ private: QList exceptions; QmlCompiledData *output; + + QHash savedTypes; }; QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index 31bd2f5..bb40063 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -166,9 +166,6 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) case QmlInstruction::PushProperty: qWarning() << idx << "\t" << line << "\t" << "PUSH_PROPERTY" << "\t\t" << instr->pushProperty.property; break; - case QmlInstruction::AssignStackObject: - qWarning() << idx << "\t" << line << "\t" << "ASSIGN_STACK_OBJ" << "\t" << instr->assignStackObject.property << "\t" << instr->assignStackObject.object; - break; case QmlInstruction::StoreStackObject: qWarning() << idx << "\t" << line << "\t" << "STORE_STACK_OBJ" << "\t" << instr->assignStackObject.property << "\t" << instr->assignStackObject.object; break; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index 47a8d76..abefd6c 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -139,10 +139,8 @@ public: // Expression optimizations // // PushProperty - Save the property for later use - // AssignStackObject - Assign the stack object // StoreStackObject - Assign the stack object (no checks) PushProperty, /* pushProperty */ - AssignStackObject, /* assignStackObject */ StoreStackObject /* assignStackObject */ }; QmlInstruction() diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index e2441c6..991c7ad 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -101,7 +101,6 @@ Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { Q_DECLARE_PERFORMANCE_METRIC(InstrPopFetchedObject); Q_DECLARE_PERFORMANCE_METRIC(InstrPopQList); Q_DECLARE_PERFORMANCE_METRIC(InstrPushProperty); - Q_DECLARE_PERFORMANCE_METRIC(InstrAssignStackObject); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreStackObject); Q_DECLARE_PERFORMANCE_METRIC(Dummy); } @@ -141,7 +140,6 @@ Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { Q_DEFINE_PERFORMANCE_METRIC(InstrPopFetchedObject, "PopFetchedObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrPopQList, "PopQList"); Q_DEFINE_PERFORMANCE_METRIC(InstrPushProperty, "PushProperty"); - Q_DEFINE_PERFORMANCE_METRIC(InstrAssignStackObject, "AssignStackObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreStackObject, "StoreStackObject"); Q_DEFINE_PERFORMANCE_METRIC(Dummy, "Dummy"); } @@ -934,37 +932,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; - case QmlInstruction::AssignStackObject: - { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - - QObject *obj = savedObjects[instr.assignStackObject.object]; - const QmlMetaProperty &prop = - pushedProperties.at(instr.assignStackObject.property); - - - const QMetaObject *mo = - QmlMetaType::rawMetaObjectForType(prop.propertyType()); - const QMetaObject *assignMo = obj->metaObject(); - - bool found = false; - while(!found && assignMo) { - if (assignMo == mo) - found = true; - else - assignMo = assignMo->superClass(); - } - - if (!found) - VME_EXCEPTION("Unable to assign object"); - - instr.type = QmlInstruction::StoreStackObject; - --ii; - } - break; - case QmlInstruction::StoreStackObject: { #ifdef Q_ENABLE_PERFORMANCE_LOG -- cgit v0.12 From e7a607f0f1f7837a26bf95248504497b0534e357 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 26 May 2009 10:19:02 +0200 Subject: qdoc: Indicate that qAbs(T& v) compares v to a 0 of type T. Task-number: 246789 --- doc/src/index.qdoc | 1 + src/corelib/global/qglobal.cpp | 49 +++++++++++++++++++++++++++++++----------- 2 files changed, 38 insertions(+), 12 deletions(-) diff --git a/doc/src/index.qdoc b/doc/src/index.qdoc index 4ead9e4..9846ac4 100644 --- a/doc/src/index.qdoc +++ b/doc/src/index.qdoc @@ -153,6 +153,7 @@
  • All Overviews and HOWTOs
  • Qt Widget Gallery
  • Class Chart
  • +
  • Qt Global Declarations
  • diff --git a/src/corelib/global/qglobal.cpp b/src/corelib/global/qglobal.cpp index 8324d05..f767bb9 100644 --- a/src/corelib/global/qglobal.cpp +++ b/src/corelib/global/qglobal.cpp @@ -125,7 +125,8 @@ QT_BEGIN_NAMESPACE If you want to use QFlags for your own enum types, use the Q_DECLARE_FLAGS() and Q_DECLARE_OPERATORS_FOR_FLAGS(). - For example: + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 1 @@ -442,14 +443,18 @@ QT_BEGIN_NAMESPACE function. You can retrieve the minimum and maximum of two given objects using qMin() and qMax() respectively. All these functions return a corresponding template type; the template types can be - replaced by any other type. For example: + replaced by any other type. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 3 also contains functions that generate messages from the given string argument: qCritical(), qDebug(), qFatal() and qWarning(). These functions call the message handler with the - given message. For example: + given message. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 4 @@ -694,7 +699,9 @@ QT_BEGIN_NAMESPACE \relates Wraps the signed 64-bit integer \a literal in a - platform-independent way. For example: + platform-independent way. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 8 @@ -705,7 +712,9 @@ QT_BEGIN_NAMESPACE \relates Wraps the unsigned 64-bit integer \a literal in a - platform-independent way. For example: + platform-independent way. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 9 @@ -734,7 +743,11 @@ QT_BEGIN_NAMESPACE /*! \fn const T &qAbs(const T &value) \relates - Returns the absolute value of \a value. For example: + Compares \a value to the 0 of type T and returns the absolute + value. Thus if T is \e {double}, then \a value is compared to + \e{(double) 0}. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 10 */ @@ -742,7 +755,9 @@ QT_BEGIN_NAMESPACE /*! \fn int qRound(qreal value) \relates - Rounds \a value to the nearest integer. For example: + Rounds \a value to the nearest integer. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 11 */ @@ -750,7 +765,9 @@ QT_BEGIN_NAMESPACE /*! \fn qint64 qRound64(qreal value) \relates - Rounds \a value to the nearest 64-bit integer. For example: + Rounds \a value to the nearest 64-bit integer. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 12 */ @@ -758,7 +775,9 @@ QT_BEGIN_NAMESPACE /*! \fn const T &qMin(const T &value1, const T &value2) \relates - Returns the minimum of \a value1 and \a value2. For example: + Returns the minimum of \a value1 and \a value2. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 13 @@ -768,7 +787,9 @@ QT_BEGIN_NAMESPACE /*! \fn const T &qMax(const T &value1, const T &value2) \relates - Returns the maximum of \a value1 and \a value2. For example: + Returns the maximum of \a value1 and \a value2. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 14 @@ -779,7 +800,9 @@ QT_BEGIN_NAMESPACE \relates Returns \a value bounded by \a min and \a max. This is equivalent - to qMax(\a min, qMin(\a value, \a max)). For example: + to qMax(\a min, qMin(\a value, \a max)). + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 15 @@ -925,7 +948,9 @@ QT_BEGIN_NAMESPACE 4.1.2, the QT_VERSION macro will expand to 0x040102. You can use QT_VERSION to use the latest Qt features where - available. For example: + available. + + Example: \snippet doc/src/snippets/code/src_corelib_global_qglobal.cpp 16 -- cgit v0.12 From 2a390bb481a2433a239a9198e463c9337a26db59 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Mon, 25 May 2009 18:32:46 +0200 Subject: Fixed: QSortFilterProxyModel setDynamicSortFilter doesn't works when setting the model initially This was caused by two different bug: - In the QSortFilterProxyModel, we need to re-sort when setting the source model change the sorting column (happen when setting a model initially) - In the treeview, we need to activate the sorting even if there is no column yet (because the initial model is empty Task-number: 254234 Reviewed-by: Thierry BT: --- src/gui/itemviews/qheaderview.cpp | 4 ++- src/gui/itemviews/qsortfilterproxymodel.cpp | 3 ++- src/gui/itemviews/qtreeview.cpp | 8 +++--- .../tst_qsortfilterproxymodel.cpp | 10 ++++++++ tests/auto/qtreeview/tst_qtreeview.cpp | 29 +++++++++++++++++++++- 5 files changed, 48 insertions(+), 6 deletions(-) diff --git a/src/gui/itemviews/qheaderview.cpp b/src/gui/itemviews/qheaderview.cpp index dc63b25..86ece40 100644 --- a/src/gui/itemviews/qheaderview.cpp +++ b/src/gui/itemviews/qheaderview.cpp @@ -1267,8 +1267,10 @@ void QHeaderView::setSortIndicator(int logicalIndex, Qt::SortOrder order) d->sortIndicatorSection = logicalIndex; d->sortIndicatorOrder = order; - if (logicalIndex >= d->sectionCount) + if (logicalIndex >= d->sectionCount) { + emit sortIndicatorChanged(logicalIndex, order); return; // nothing to do + } if (old != logicalIndex && ((logicalIndex >= 0 && resizeMode(logicalIndex) == ResizeToContents) diff --git a/src/gui/itemviews/qsortfilterproxymodel.cpp b/src/gui/itemviews/qsortfilterproxymodel.cpp index 43feda8..92dfd19 100644 --- a/src/gui/itemviews/qsortfilterproxymodel.cpp +++ b/src/gui/itemviews/qsortfilterproxymodel.cpp @@ -1518,7 +1518,8 @@ void QSortFilterProxyModel::setSourceModel(QAbstractItemModel *sourceModel) d->clear_mapping(); reset(); - d->update_source_sort_column(); + if (d->update_source_sort_column() && d->dynamic_sortfilter) + d->sort(); } /*! diff --git a/src/gui/itemviews/qtreeview.cpp b/src/gui/itemviews/qtreeview.cpp index 62c1277..1070648 100644 --- a/src/gui/itemviews/qtreeview.cpp +++ b/src/gui/itemviews/qtreeview.cpp @@ -246,7 +246,7 @@ void QTreeView::setModel(QAbstractItemModel *model) connect(d->model, SIGNAL(modelAboutToBeReset()), SLOT(_q_modelAboutToBeReset())); if (d->sortingEnabled) - sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder()); + d->_q_sortIndicatorChanged(header()->sortIndicatorSection(), header()->sortIndicatorOrder()); } /*! @@ -846,17 +846,19 @@ void QTreeView::setExpanded(const QModelIndex &index, bool expanded) void QTreeView::setSortingEnabled(bool enable) { Q_D(QTreeView); - d->sortingEnabled = enable; header()->setSortIndicatorShown(enable); header()->setClickable(enable); if (enable) { + //sortByColumn has to be called before we connect or set the sortingEnabled flag + // because otherwise it will not call sort on the model. + sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder()); connect(header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(_q_sortIndicatorChanged(int, Qt::SortOrder))); - sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder()); } else { disconnect(header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(_q_sortIndicatorChanged(int, Qt::SortOrder))); } + d->sortingEnabled = enable; } bool QTreeView::isSortingEnabled() const diff --git a/tests/auto/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp b/tests/auto/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp index bd66fdf..80d90a6 100644 --- a/tests/auto/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp +++ b/tests/auto/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp @@ -2585,6 +2585,16 @@ void tst_QSortFilterProxyModel::task248868_dynamicSorting() QModelIndex index = proxy1.index(row, 0, QModelIndex()); QCOMPARE(proxy1.data(index, Qt::DisplayRole).toString(), expected.at(row)); } + + //set up the sorting before seting the model up + QSortFilterProxyModel proxy2; + proxy2.setDynamicSortFilter(true); + proxy2.sort(0); + proxy2.setSourceModel(&model2); + for (int row = 0; row < proxy2.rowCount(QModelIndex()); ++row) { + QModelIndex index = proxy2.index(row, 0, QModelIndex()); + QCOMPARE(proxy2.data(index, Qt::DisplayRole).toString(), expected.at(row)); + } } class QtTestModel: public QAbstractItemModel diff --git a/tests/auto/qtreeview/tst_qtreeview.cpp b/tests/auto/qtreeview/tst_qtreeview.cpp index 655ea4e..54d6619 100644 --- a/tests/auto/qtreeview/tst_qtreeview.cpp +++ b/tests/auto/qtreeview/tst_qtreeview.cpp @@ -225,6 +225,7 @@ private slots: void task238873_avoidAutoReopening(); void task244304_clickOnDecoration(); void task246536_scrollbarsNotWorking(); + void task254234_proxySort(); }; class QtTestModel: public QAbstractItemModel @@ -2493,7 +2494,6 @@ void tst_QTreeView::sortByColumn() QCOMPARE(view.header()->sortIndicatorSection(), 0); QCOMPARE(view.model()->data(view.model()->index(0,0)).toString(), QString::fromLatin1("a")); QCOMPARE(view.model()->data(view.model()->index(1,0)).toString(), QString::fromLatin1("b")); - } /* @@ -3272,5 +3272,32 @@ void tst_QTreeView::task246536_scrollbarsNotWorking() QVERIFY(o.count > 0); } +void tst_QTreeView::task254234_proxySort() +{ + //based on tst_QTreeView::sortByColumn + // it used not to work when setting the source of a proxy after enabling sorting + QTreeView view; + QStandardItemModel model(4,2); + model.setItem(0,0,new QStandardItem("b")); + model.setItem(1,0,new QStandardItem("d")); + model.setItem(2,0,new QStandardItem("c")); + model.setItem(3,0,new QStandardItem("a")); + model.setItem(0,1,new QStandardItem("e")); + model.setItem(1,1,new QStandardItem("g")); + model.setItem(2,1,new QStandardItem("h")); + model.setItem(3,1,new QStandardItem("f")); + + view.sortByColumn(1); + view.setSortingEnabled(true); + + QSortFilterProxyModel proxy; + proxy.setDynamicSortFilter(true); + view.setModel(&proxy); + proxy.setSourceModel(&model); + QCOMPARE(view.header()->sortIndicatorSection(), 1); + QCOMPARE(view.model()->data(view.model()->index(0,1)).toString(), QString::fromLatin1("h")); + QCOMPARE(view.model()->data(view.model()->index(1,1)).toString(), QString::fromLatin1("g")); +} + QTEST_MAIN(tst_QTreeView) #include "tst_qtreeview.moc" -- cgit v0.12 From e33415a700a7d1de706633970ed69936e3b2145e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Arve=20S=C3=A6ther?= Date: Tue, 26 May 2009 10:18:46 +0200 Subject: Fix the previous fix. The previous fix fails on msvc-2005, since QString::setNum() does not handle rounding of numbers such as 0.015625 consistently. --- tests/auto/qeasingcurve/tst_qeasingcurve.cpp | 182 +-------------------------- 1 file changed, 5 insertions(+), 177 deletions(-) diff --git a/tests/auto/qeasingcurve/tst_qeasingcurve.cpp b/tests/auto/qeasingcurve/tst_qeasingcurve.cpp index 8fe15b1..b25cdc7 100644 --- a/tests/auto/qeasingcurve/tst_qeasingcurve.cpp +++ b/tests/auto/qeasingcurve/tst_qeasingcurve.cpp @@ -371,182 +371,6 @@ void tst_QEasingCurve::valueForProgress_data() << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) << (RealList() << 0.5 << 0.7939 << 0.9755 << 0.9755 << 0.7939 << 0.5 << 0.2061 << 0.02447 << 0.02447 << 0.2061 << 0.5); - /* - QTest::newRow("InQuad") << int(QEasingCurve::InQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (RealList() << 0 << 0.01 << 0.04 << 0.09 << 0.16 << 0.25 << 0.36 << 0.49 << 0.64 << 0.81 << 1); - QTest::newRow("OutQuad") << int(QEasingCurve::OutQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0.19 << 0.36 << 0.51 << 0.64 << 0.75 << 0.84 << 0.91 << 0.96 << 0.99 << 1); - - QTest::newRow("InOutQuad") << int(QEasingCurve::InOutQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 2 << 8 << 18 << 32 << 50 << 68 << 82 << 92 << 98 << 100); - - QTest::newRow("OutInQuad") << int(QEasingCurve::OutInQuad) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 18 << 32 << 42 << 48 << 50 << 52 << 57 << 68 << 82 << 100); - - QTest::newRow("InCubic") << int(QEasingCurve::InCubic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 2 << 6 << 12 << 21 << 34 << 51 << 72 << 100); - - QTest::newRow("OutCubic") << int(QEasingCurve::OutCubic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 27 << 48 << 65 << 78 << 87 << 93 << 97 << 99 << 99 << 100); - - QTest::newRow("InOutCubic") << int(QEasingCurve::InOutCubic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 3 << 10 << 25 << 50 << 74 << 89 << 96 << 99 << 100); - - QTest::newRow("OutInCubic") << int(QEasingCurve::OutInCubic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 24 << 39 << 46 << 49 << 50 << 50 << 53 << 60 << 75 << 100); - - QTest::newRow("InQuart") << int(QEasingCurve::InQuart) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 0 << 2 << 6 << 12 << 24 << 40 << 65 << 100); - - QTest::newRow("OutQuart") << int(QEasingCurve::OutQuart) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 34 << 59 << 75 << 87 << 93 << 97 << 99 << 99 << 99 << 100); - - QTest::newRow("InOutQuart") << int(QEasingCurve::InOutQuart) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 1 << 6 << 20 << 50 << 79 << 93 << 98 << 99 << 100); - - QTest::newRow("OutInQuart") << int(QEasingCurve::OutInQuart) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 29 << 43 << 48 << 49 << 50 << 50 << 51 << 56 << 70 << 100); - - QTest::newRow("InQuint") << int(QEasingCurve::InQuint) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 0 << 1 << 3 << 7 << 16 << 32 << 59 << 100); - - QTest::newRow("OutQuint") << int(QEasingCurve::OutQuint) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 40 << 67 << 83 << 92 << 96 << 98 << 99 << 99 << 99 << 100); - - QTest::newRow("InOutQuint") << int(QEasingCurve::InOutQuint) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 3 << 16 << 50 << 83 << 96 << 99 << 99 << 100); - - QTest::newRow("OutInQuint") << int(QEasingCurve::OutInQuint) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 33 << 46 << 49 << 49 << 50 << 50 << 50 << 53 << 66 << 100); - - QTest::newRow("InSine") << int(QEasingCurve::InSine) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 1 << 4 << 10 << 19 << 29 << 41 << 54 << 69 << 84 << 100); - - QTest::newRow("OutSine") << int(QEasingCurve::OutSine) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 15 << 30 << 45 << 58 << 70 << 80 << 89 << 95 << 98 << 100); - - QTest::newRow("InOutSine") << int(QEasingCurve::InOutSine) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 2 << 9 << 20 << 34 << 49 << 65 << 79 << 90 << 97 << 100); - - QTest::newRow("OutInSine") << int(QEasingCurve::OutInSine) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 15 << 29 << 40 << 47 << 50 << 52 << 59 << 70 << 84 << 100); - - QTest::newRow("InExpo") << int(QEasingCurve::InExpo) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 0 << 1 << 3 << 6 << 12 << 24 << 49 << 100); - - QTest::newRow("OutExpo") << int(QEasingCurve::OutExpo) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 50 << 75 << 87 << 93 << 96 << 98 << 99 << 99 << 99 << 100); - - QTest::newRow("InOutExpo") << int(QEasingCurve::InOutExpo) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 3 << 12 << 50 << 87 << 96 << 99 << 99 << 100); - - QTest::newRow("OutInExpo") << int(QEasingCurve::OutInExpo) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 37 << 46 << 49 << 49 << 50 << 50 << 50 << 53 << 62 << 100); - - QTest::newRow("InCirc") << int(QEasingCurve::InCirc) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 2 << 4 << 8 << 13 << 19 << 28 << 40 << 56 << 100); - - QTest::newRow("OutCirc") << int(QEasingCurve::OutCirc) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 43 << 59 << 71 << 80 << 86 << 91 << 95 << 97 << 99 << 100); - - QTest::newRow("InOutCirc") << int(QEasingCurve::InOutCirc) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 1 << 4 << 9 << 20 << 50 << 80 << 89 << 95 << 98 << 100); - - QTest::newRow("OutInCirc") << int(QEasingCurve::OutInCirc) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 29 << 40 << 45 << 48 << 50 << 51 << 54 << 60 << 70 << 100); - - QTest::newRow("InElastic") << int(QEasingCurve::InElastic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << 0 << 1 << -1 << -3 << 12 << -12 << -25 << 100); - - QTest::newRow("OutElastic") << int(QEasingCurve::OutElastic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 125 << 112 << 87 << 103 << 101 << 98 << 100 << 100 << 99 << 100); - - QTest::newRow("InOutElastic") << int(QEasingCurve::InOutElastic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 0 << 0 << -1 << -6 << 50 << 106 << 101 << 99 << 100 << 100); - - QTest::newRow("OutInElastic") << int(QEasingCurve::OutInElastic) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 37 << 56 << 49 << 49 << 50 << 49 << 50 << 53 << 24 << 100); - - QTest::newRow("InBack") << int(QEasingCurve::InBack) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << -1 << -4 << -8 << -9 << -8 << -2 << 9 << 29 << 59 << 100); - - QTest::newRow("OutBack") << int(QEasingCurve::OutBack) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 40 << 70 << 90 << 102 << 108 << 109 << 108 << 104 << 101 << 100); - - QTest::newRow("InOutBack") << int(QEasingCurve::InOutBack) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << -3 << -9 << -7 << 8 << 50 << 91 << 107 << 109 << 103 << 100); - - QTest::newRow("OutInBack") << int(QEasingCurve::OutInBack) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 35 << 51 << 54 << 52 << 50 << 47 << 45 << 48 << 64 << 100); - - QTest::newRow("InBounce") << int(QEasingCurve::InBounce) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 1 << 6 << 6 << 22 << 23 << 9 << 31 << 69 << 92 << 100); - - QTest::newRow("OutBounce") << int(QEasingCurve::OutBounce) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 7 << 30 << 68 << 90 << 76 << 77 << 93 << 94 << 98 << 100); - - QTest::newRow("InOutBounce") << int(QEasingCurve::InOutBounce) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 3 << 11 << 4 << 34 << 50 << 65 << 95 << 88 << 97 << 100); - - QTest::newRow("OutInBounce") << int(QEasingCurve::OutInBounce) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 15 << 40 << 27 << 43 << 50 << 56 << 72 << 58 << 84 << 100); - - QTest::newRow("InCurve") << int(QEasingCurve::InCurve) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 2 << 10 << 23 << 37 << 50 << 60 << 70 << 80 << 90 << 100); - - QTest::newRow("OutCurve") << int(QEasingCurve::OutCurve) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 10 << 20 << 30 << 39 << 50 << 62 << 76 << 89 << 97 << 100); - - QTest::newRow("SineCurve") << int(QEasingCurve::SineCurve) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 0 << 9 << 34 << 65 << 90 << 100 << 90 << 65 << 34 << 9 << 0); - - QTest::newRow("CosineCurve") << int(QEasingCurve::CosineCurve) - << (IntList() << 0 << 10 << 20 << 30 << 40 << 50 << 60 << 70 << 80 << 90 << 100) - << (IntList() << 50 << 79 << 97 << 97 << 79 << 50 << 20 << 2 << 2 << 20 << 49); -*/ } @@ -590,7 +414,11 @@ void tst_QEasingCurve::valueForProgress() // converting ease to 4 precision qreal to match the generated samples qreal easeConv = qreal(QString().setNum(ease, 'g', 4).toDouble()); qreal ex = expected.at(i); - QVERIFY(qFuzzyCompare(easeConv, ex)); + + // the least significant digit it is still subject to rounding errors + qreal error = easeConv - ex; + // accept the potential rounding error in the least significant digit + QVERIFY(error <= 0.00001 ); } #endif } -- cgit v0.12 From b29a83e5070410359ebed2d99b18f86bbe2d2939 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Tue, 26 May 2009 18:32:28 +1000 Subject: Remove extraneous semicolons. Caused massive number of warnings with winscw --- src/declarative/extra/qfxintegermodel.h | 2 +- src/declarative/extra/qmlnumberformatter.h | 2 +- src/declarative/extra/qmlsqlconnection.h | 2 +- src/declarative/extra/qmlsqlquery.h | 4 +- src/declarative/extra/qmlxmllistmodel.h | 4 +- src/declarative/extra/qnumberformat.h | 2 +- src/declarative/fx/qfxanchors.cpp | 2 +- src/declarative/fx/qfxanchors.h | 4 +- src/declarative/fx/qfxanimatedimageitem.cpp | 2 +- src/declarative/fx/qfxanimatedimageitem.h | 2 +- src/declarative/fx/qfxblendedimage.cpp | 2 +- src/declarative/fx/qfxblendedimage.h | 2 +- src/declarative/fx/qfxblurfilter.cpp | 2 +- src/declarative/fx/qfxblurfilter.h | 2 +- src/declarative/fx/qfxcomponentinstance.cpp | 2 +- src/declarative/fx/qfxcomponentinstance.h | 2 +- src/declarative/fx/qfxcontentwrapper.cpp | 4 +- src/declarative/fx/qfxcontentwrapper.h | 4 +- src/declarative/fx/qfxevents.cpp | 4 +- src/declarative/fx/qfxevents_p.h | 4 +- src/declarative/fx/qfxflickable.cpp | 2 +- src/declarative/fx/qfxflickable.h | 2 +- src/declarative/fx/qfxflickable_p.h | 2 +- src/declarative/fx/qfxflipable.cpp | 2 +- src/declarative/fx/qfxflipable.h | 2 +- src/declarative/fx/qfxfocuspanel.cpp | 2 +- src/declarative/fx/qfxfocuspanel.h | 2 +- src/declarative/fx/qfxfocusrealm.cpp | 2 +- src/declarative/fx/qfxfocusrealm.h | 2 +- src/declarative/fx/qfxgridview.cpp | 2 +- src/declarative/fx/qfxgridview.h | 2 +- src/declarative/fx/qfxhighlightfilter.cpp | 2 +- src/declarative/fx/qfxhighlightfilter.h | 2 +- src/declarative/fx/qfximage.cpp | 2 +- src/declarative/fx/qfximage.h | 2 +- src/declarative/fx/qfxitem.cpp | 6 +-- src/declarative/fx/qfxitem.h | 8 ++-- src/declarative/fx/qfxitem_p.h | 6 +-- src/declarative/fx/qfxkeyactions.cpp | 2 +- src/declarative/fx/qfxkeyactions.h | 2 +- src/declarative/fx/qfxkeyproxy.cpp | 2 +- src/declarative/fx/qfxkeyproxy.h | 2 +- src/declarative/fx/qfxlayouts.cpp | 6 +-- src/declarative/fx/qfxlayouts.h | 6 +-- src/declarative/fx/qfxlistview.cpp | 2 +- src/declarative/fx/qfxlistview.h | 2 +- src/declarative/fx/qfxmouseregion.cpp | 4 +- src/declarative/fx/qfxmouseregion.h | 4 +- src/declarative/fx/qfxpainteditem.h | 2 +- src/declarative/fx/qfxparticles.cpp | 10 ++--- src/declarative/fx/qfxparticles.h | 10 ++--- src/declarative/fx/qfxpath.cpp | 16 ++++---- src/declarative/fx/qfxpath.h | 16 ++++---- src/declarative/fx/qfxpathview.cpp | 2 +- src/declarative/fx/qfxpathview.h | 2 +- src/declarative/fx/qfxrect.cpp | 4 +- src/declarative/fx/qfxrect.h | 4 +- src/declarative/fx/qfxreflectionfilter.cpp | 2 +- src/declarative/fx/qfxreflectionfilter.h | 2 +- src/declarative/fx/qfxrepeater.cpp | 2 +- src/declarative/fx/qfxrepeater.h | 2 +- src/declarative/fx/qfxscalegrid.h | 2 +- src/declarative/fx/qfxshadowfilter.cpp | 2 +- src/declarative/fx/qfxshadowfilter.h | 2 +- src/declarative/fx/qfxtext.cpp | 2 +- src/declarative/fx/qfxtext.h | 2 +- src/declarative/fx/qfxtextedit.cpp | 2 +- src/declarative/fx/qfxtextedit.h | 2 +- src/declarative/fx/qfxtransform.cpp | 12 +++--- src/declarative/fx/qfxtransform.h | 14 +++---- src/declarative/fx/qfxvisualitemmodel.cpp | 4 +- src/declarative/fx/qfxvisualitemmodel.h | 2 +- src/declarative/fx/qfxwebview.cpp | 2 +- src/declarative/fx/qfxwebview.h | 2 +- src/declarative/fx/qfxwidgetcontainer.cpp | 2 +- src/declarative/fx/qfxwidgetcontainer.h | 2 +- src/declarative/qml/qml.h | 14 +++---- src/declarative/qml/qmlbindablevalue.h | 2 +- src/declarative/qml/qmlcomponent.h | 2 +- src/declarative/qml/qmlpropertyvaluesource.h | 2 +- src/declarative/util/qfxperf.h | 54 +++++++++++++-------------- src/declarative/util/qmlanimation.cpp | 20 +++++----- src/declarative/util/qmlanimation.h | 20 +++++----- src/declarative/util/qmlbehaviour.cpp | 2 +- src/declarative/util/qmlbehaviour.h | 2 +- src/declarative/util/qmlbind.cpp | 2 +- src/declarative/util/qmlbind.h | 2 +- src/declarative/util/qmlconnection.cpp | 2 +- src/declarative/util/qmlconnection.h | 2 +- src/declarative/util/qmldatetimeformatter.cpp | 2 +- src/declarative/util/qmldatetimeformatter.h | 2 +- src/declarative/util/qmlfollow.cpp | 2 +- src/declarative/util/qmlfollow.h | 2 +- src/declarative/util/qmlfont.cpp | 2 +- src/declarative/util/qmlfont.h | 2 +- src/declarative/util/qmllistmodel.cpp | 8 ++-- src/declarative/util/qmlpackage.cpp | 2 +- src/declarative/util/qmlpackage.h | 2 +- src/declarative/util/qmlscript.cpp | 2 +- src/declarative/util/qmlscript.h | 2 +- src/declarative/util/qmlsetproperties.cpp | 2 +- src/declarative/util/qmlsetproperties.h | 2 +- src/declarative/util/qmlstate.cpp | 4 +- src/declarative/util/qmlstate.h | 4 +- src/declarative/util/qmlstategroup.cpp | 2 +- src/declarative/util/qmlstategroup.h | 2 +- src/declarative/util/qmlstateoperations.cpp | 6 +-- src/declarative/util/qmlstateoperations.h | 6 +-- src/declarative/util/qmltransition.cpp | 2 +- src/declarative/util/qmltransition.h | 2 +- src/declarative/widgets/graphicslayouts.cpp | 6 +-- src/declarative/widgets/graphicslayouts.h | 10 ++--- src/declarative/widgets/graphicswidgets.h | 8 ++-- 113 files changed, 237 insertions(+), 237 deletions(-) diff --git a/src/declarative/extra/qfxintegermodel.h b/src/declarative/extra/qfxintegermodel.h index 2f5c756..a715949 100644 --- a/src/declarative/extra/qfxintegermodel.h +++ b/src/declarative/extra/qfxintegermodel.h @@ -77,7 +77,7 @@ private: QFxIntegerModelPrivate *d; }; -QML_DECLARE_TYPE(QFxIntegerModel); +QML_DECLARE_TYPE(QFxIntegerModel) QT_END_NAMESPACE diff --git a/src/declarative/extra/qmlnumberformatter.h b/src/declarative/extra/qmlnumberformatter.h index cdd6b58..e4efc03 100644 --- a/src/declarative/extra/qmlnumberformatter.h +++ b/src/declarative/extra/qmlnumberformatter.h @@ -83,7 +83,7 @@ private: Q_DECLARE_PRIVATE(QmlNumberFormatter) }; -QML_DECLARE_TYPE(QmlNumberFormatter); +QML_DECLARE_TYPE(QmlNumberFormatter) QT_END_NAMESPACE diff --git a/src/declarative/extra/qmlsqlconnection.h b/src/declarative/extra/qmlsqlconnection.h index 0fff1b0..dd0e5b5 100644 --- a/src/declarative/extra/qmlsqlconnection.h +++ b/src/declarative/extra/qmlsqlconnection.h @@ -108,7 +108,7 @@ private: Q_DECLARE_PRIVATE(QmlSqlConnection) }; -QML_DECLARE_TYPE(QmlSqlConnection); +QML_DECLARE_TYPE(QmlSqlConnection) QT_END_NAMESPACE diff --git a/src/declarative/extra/qmlsqlquery.h b/src/declarative/extra/qmlsqlquery.h index 3fff127..5f750ee 100644 --- a/src/declarative/extra/qmlsqlquery.h +++ b/src/declarative/extra/qmlsqlquery.h @@ -82,7 +82,7 @@ private: Q_DECLARE_PRIVATE(QmlSqlBind) }; -QML_DECLARE_TYPE(QmlSqlBind); +QML_DECLARE_TYPE(QmlSqlBind) class QSqlQuery; class QmlSqlQueryPrivate; @@ -134,7 +134,7 @@ private: Q_DECLARE_PRIVATE(QmlSqlQuery) }; -QML_DECLARE_TYPE(QmlSqlQuery); +QML_DECLARE_TYPE(QmlSqlQuery) QT_END_NAMESPACE diff --git a/src/declarative/extra/qmlxmllistmodel.h b/src/declarative/extra/qmlxmllistmodel.h index cf2f5f4..052a0c2 100644 --- a/src/declarative/extra/qmlxmllistmodel.h +++ b/src/declarative/extra/qmlxmllistmodel.h @@ -82,7 +82,7 @@ private: bool m_isList; bool m_isCData; }; -QML_DECLARE_TYPE(XmlListModelRole); +QML_DECLARE_TYPE(XmlListModelRole) class QmlXmlListModelPrivate; class Q_DECLARATIVE_EXPORT QmlXmlListModel : public QListModelInterface, public QmlParserStatus @@ -141,7 +141,7 @@ private: Q_DISABLE_COPY(QmlXmlListModel) }; -QML_DECLARE_TYPE(QmlXmlListModel); +QML_DECLARE_TYPE(QmlXmlListModel) QT_END_NAMESPACE diff --git a/src/declarative/extra/qnumberformat.h b/src/declarative/extra/qnumberformat.h index 75224ec..aa1e447 100644 --- a/src/declarative/extra/qnumberformat.h +++ b/src/declarative/extra/qnumberformat.h @@ -163,7 +163,7 @@ private: QString _text; }; -QML_DECLARE_TYPE(QNumberFormat); +QML_DECLARE_TYPE(QNumberFormat) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxanchors.cpp b/src/declarative/fx/qfxanchors.cpp index 681a9fa..bd5520a 100644 --- a/src/declarative/fx/qfxanchors.cpp +++ b/src/declarative/fx/qfxanchors.cpp @@ -48,7 +48,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxAnchors,Anchors); +QML_DEFINE_TYPE(QFxAnchors,Anchors) //TODO: should we cache relationships, so we don't have to check each time (parent-child or sibling)? //TODO: baseline support diff --git a/src/declarative/fx/qfxanchors.h b/src/declarative/fx/qfxanchors.h index 3f142c4..8c3fe89 100644 --- a/src/declarative/fx/qfxanchors.h +++ b/src/declarative/fx/qfxanchors.h @@ -78,7 +78,7 @@ public: AnchorLine anchorLine; }; -Q_DECLARE_METATYPE(QFxAnchorLine); +Q_DECLARE_METATYPE(QFxAnchorLine) class QFxAnchorsPrivate; class Q_DECLARATIVE_EXPORT QFxAnchors : public QObject @@ -188,7 +188,7 @@ private: Q_DECLARE_PRIVATE(QFxAnchors) }; -QML_DECLARE_TYPE(QFxAnchors); +QML_DECLARE_TYPE(QFxAnchors) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxanimatedimageitem.cpp b/src/declarative/fx/qfxanimatedimageitem.cpp index 7a1cb7f..029206b 100644 --- a/src/declarative/fx/qfxanimatedimageitem.cpp +++ b/src/declarative/fx/qfxanimatedimageitem.cpp @@ -77,7 +77,7 @@ Item { \endqml \endtable */ -QML_DEFINE_TYPE(QFxAnimatedImageItem, AnimatedImage); +QML_DEFINE_TYPE(QFxAnimatedImageItem, AnimatedImage) QFxAnimatedImageItem::QFxAnimatedImageItem(QFxItem *parent) : QFxImage(*(new QFxAnimatedImageItemPrivate), parent) diff --git a/src/declarative/fx/qfxanimatedimageitem.h b/src/declarative/fx/qfxanimatedimageitem.h index a332c8b..a0d14c4 100644 --- a/src/declarative/fx/qfxanimatedimageitem.h +++ b/src/declarative/fx/qfxanimatedimageitem.h @@ -91,7 +91,7 @@ private: Q_DECLARE_PRIVATE(QFxAnimatedImageItem) }; -QML_DECLARE_TYPE(QFxAnimatedImageItem); +QML_DECLARE_TYPE(QFxAnimatedImageItem) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxblendedimage.cpp b/src/declarative/fx/qfxblendedimage.cpp index 79b8e41..73eb3c4 100644 --- a/src/declarative/fx/qfxblendedimage.cpp +++ b/src/declarative/fx/qfxblendedimage.cpp @@ -292,6 +292,6 @@ void QFxBlendedImage::paintGLContents(GLPainter &p) } #endif -QML_DEFINE_TYPE(QFxBlendedImage,BlendedImage); +QML_DEFINE_TYPE(QFxBlendedImage,BlendedImage) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxblendedimage.h b/src/declarative/fx/qfxblendedimage.h index 2fdf15b..4e6204d 100644 --- a/src/declarative/fx/qfxblendedimage.h +++ b/src/declarative/fx/qfxblendedimage.h @@ -102,7 +102,7 @@ private: QFxPixmap primPix; QFxPixmap secPix; }; -QML_DECLARE_TYPE(QFxBlendedImage); +QML_DECLARE_TYPE(QFxBlendedImage) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxblurfilter.cpp b/src/declarative/fx/qfxblurfilter.cpp index baa2253..84799ec 100644 --- a/src/declarative/fx/qfxblurfilter.cpp +++ b/src/declarative/fx/qfxblurfilter.cpp @@ -463,5 +463,5 @@ void QFxBlurFilter::filterGL(QSimpleCanvasItem::GLPainter &p) } -QML_DEFINE_TYPE(QFxBlurFilter,Blur); +QML_DEFINE_TYPE(QFxBlurFilter,Blur) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxblurfilter.h b/src/declarative/fx/qfxblurfilter.h index 576debf..90285de 100644 --- a/src/declarative/fx/qfxblurfilter.h +++ b/src/declarative/fx/qfxblurfilter.h @@ -73,7 +73,7 @@ protected: private: QFxBlurFilterPrivate *d; }; -QML_DECLARE_TYPE(QFxBlurFilter); +QML_DECLARE_TYPE(QFxBlurFilter) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxcomponentinstance.cpp b/src/declarative/fx/qfxcomponentinstance.cpp index 472b98b..d3f7061 100644 --- a/src/declarative/fx/qfxcomponentinstance.cpp +++ b/src/declarative/fx/qfxcomponentinstance.cpp @@ -47,7 +47,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxComponentInstance,ComponentInstance); +QML_DEFINE_TYPE(QFxComponentInstance,ComponentInstance) /*! \internal diff --git a/src/declarative/fx/qfxcomponentinstance.h b/src/declarative/fx/qfxcomponentinstance.h index 9f84043..4b8c142 100644 --- a/src/declarative/fx/qfxcomponentinstance.h +++ b/src/declarative/fx/qfxcomponentinstance.h @@ -80,7 +80,7 @@ protected: private: Q_DECLARE_PRIVATE(QFxComponentInstance) }; -QML_DECLARE_TYPE(QFxComponentInstance); +QML_DECLARE_TYPE(QFxComponentInstance) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxcontentwrapper.cpp b/src/declarative/fx/qfxcontentwrapper.cpp index d493990..482442b 100644 --- a/src/declarative/fx/qfxcontentwrapper.cpp +++ b/src/declarative/fx/qfxcontentwrapper.cpp @@ -44,7 +44,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxContentWrapper,ContentWrapper); +QML_DEFINE_TYPE(QFxContentWrapper,ContentWrapper) /*! \qmlclass ContentWrapper QFxContentWrapper @@ -129,7 +129,7 @@ QFxItem *QFxContentWrapper::findContent(QList &nodes) return findContent(nodes); } -QML_DEFINE_TYPE(QFxContent,Content); +QML_DEFINE_TYPE(QFxContent,Content) /*! \qmlclass Content QFxContent diff --git a/src/declarative/fx/qfxcontentwrapper.h b/src/declarative/fx/qfxcontentwrapper.h index 0b7253e..d8fe0b8 100644 --- a/src/declarative/fx/qfxcontentwrapper.h +++ b/src/declarative/fx/qfxcontentwrapper.h @@ -73,7 +73,7 @@ protected: private: Q_DECLARE_PRIVATE(QFxContentWrapper) }; -QML_DECLARE_TYPE(QFxContentWrapper); +QML_DECLARE_TYPE(QFxContentWrapper) class Q_DECLARATIVE_EXPORT QFxContent : public QFxItem { @@ -81,7 +81,7 @@ class Q_DECLARATIVE_EXPORT QFxContent : public QFxItem public: QFxContent(QFxItem *parent=0) : QFxItem(parent) {} }; -QML_DECLARE_TYPE(QFxContent); +QML_DECLARE_TYPE(QFxContent) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxevents.cpp b/src/declarative/fx/qfxevents.cpp index 195d1e5..94c2d2e 100644 --- a/src/declarative/fx/qfxevents.cpp +++ b/src/declarative/fx/qfxevents.cpp @@ -176,7 +176,7 @@ MouseRegion { \endqml */ -QML_DEFINE_NOCREATE_TYPE(QFxKeyEvent); -QML_DEFINE_NOCREATE_TYPE(QFxMouseEvent); +QML_DEFINE_NOCREATE_TYPE(QFxKeyEvent) +QML_DEFINE_NOCREATE_TYPE(QFxMouseEvent) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxevents_p.h b/src/declarative/fx/qfxevents_p.h index bcd9f2d..2eb29af 100644 --- a/src/declarative/fx/qfxevents_p.h +++ b/src/declarative/fx/qfxevents_p.h @@ -78,7 +78,7 @@ private: QKeyEvent event; }; -QML_DECLARE_TYPE(QFxKeyEvent); +QML_DECLARE_TYPE(QFxKeyEvent) class QFxMouseEvent : public QObject { @@ -120,7 +120,7 @@ private: bool _accepted; }; -QML_DECLARE_TYPE(QFxMouseEvent); +QML_DECLARE_TYPE(QFxMouseEvent) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxflickable.cpp b/src/declarative/fx/qfxflickable.cpp index 4248ebb..bc4a5fc 100644 --- a/src/declarative/fx/qfxflickable.cpp +++ b/src/declarative/fx/qfxflickable.cpp @@ -228,7 +228,7 @@ void QFxFlickablePrivate::updateBeginningEnd() static const int FlickThreshold = 5; -QML_DEFINE_TYPE(QFxFlickable,Flickable); +QML_DEFINE_TYPE(QFxFlickable,Flickable) /*! \qmlclass Flickable diff --git a/src/declarative/fx/qfxflickable.h b/src/declarative/fx/qfxflickable.h index 3857017..dcbc6bb 100644 --- a/src/declarative/fx/qfxflickable.h +++ b/src/declarative/fx/qfxflickable.h @@ -186,7 +186,7 @@ private: Q_DISABLE_COPY(QFxFlickable) Q_DECLARE_PRIVATE(QFxFlickable) }; -QML_DECLARE_TYPE(QFxFlickable); +QML_DECLARE_TYPE(QFxFlickable) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxflickable_p.h b/src/declarative/fx/qfxflickable_p.h index ebd0327..a3b1500 100644 --- a/src/declarative/fx/qfxflickable_p.h +++ b/src/declarative/fx/qfxflickable_p.h @@ -162,7 +162,7 @@ public: void data_insert(int, QObject *); QObject *data_at(int) const; void data_clear(); - QML_DECLARE_LIST_PROXY(QFxFlickablePrivate, QObject *, data); + QML_DECLARE_LIST_PROXY(QFxFlickablePrivate, QObject *, data) }; QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxflipable.cpp b/src/declarative/fx/qfxflipable.cpp index edcc7cb..4c02e74 100644 --- a/src/declarative/fx/qfxflipable.cpp +++ b/src/declarative/fx/qfxflipable.cpp @@ -44,7 +44,7 @@ #include "qfxtransform.h" #include -QML_DEFINE_TYPE(QFxFlipable,Flipable); +QML_DEFINE_TYPE(QFxFlipable,Flipable) class QFxFlipablePrivate : public QFxItemPrivate { diff --git a/src/declarative/fx/qfxflipable.h b/src/declarative/fx/qfxflipable.h index 62b62a5..be9e755 100644 --- a/src/declarative/fx/qfxflipable.h +++ b/src/declarative/fx/qfxflipable.h @@ -97,7 +97,7 @@ private: Q_DISABLE_COPY(QFxFlipable) Q_DECLARE_PRIVATE(QFxFlipable) }; -QML_DECLARE_TYPE(QFxFlipable); +QML_DECLARE_TYPE(QFxFlipable) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxfocuspanel.cpp b/src/declarative/fx/qfxfocuspanel.cpp index 5d62e66..6da8564 100644 --- a/src/declarative/fx/qfxfocuspanel.cpp +++ b/src/declarative/fx/qfxfocuspanel.cpp @@ -43,7 +43,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxFocusPanel,FocusPanel); +QML_DEFINE_TYPE(QFxFocusPanel,FocusPanel) /*! \qmlclass FocusPanel diff --git a/src/declarative/fx/qfxfocuspanel.h b/src/declarative/fx/qfxfocuspanel.h index cec12a1..60f9118 100644 --- a/src/declarative/fx/qfxfocuspanel.h +++ b/src/declarative/fx/qfxfocuspanel.h @@ -72,7 +72,7 @@ private: Q_DISABLE_COPY(QFxFocusPanel) }; -QML_DECLARE_TYPE(QFxFocusPanel); +QML_DECLARE_TYPE(QFxFocusPanel) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxfocusrealm.cpp b/src/declarative/fx/qfxfocusrealm.cpp index 07849fa..9270bb2 100644 --- a/src/declarative/fx/qfxfocusrealm.cpp +++ b/src/declarative/fx/qfxfocusrealm.cpp @@ -43,7 +43,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxFocusRealm,FocusRealm); +QML_DEFINE_TYPE(QFxFocusRealm,FocusRealm) /*! \qmlclass FocusRealm diff --git a/src/declarative/fx/qfxfocusrealm.h b/src/declarative/fx/qfxfocusrealm.h index fdf1525..d2aadce 100644 --- a/src/declarative/fx/qfxfocusrealm.h +++ b/src/declarative/fx/qfxfocusrealm.h @@ -58,7 +58,7 @@ public: virtual ~QFxFocusRealm(); }; -QML_DECLARE_TYPE(QFxFocusRealm); +QML_DECLARE_TYPE(QFxFocusRealm) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxgridview.cpp b/src/declarative/fx/qfxgridview.cpp index db54aea..dde8fcf 100644 --- a/src/declarative/fx/qfxgridview.cpp +++ b/src/declarative/fx/qfxgridview.cpp @@ -1421,7 +1421,7 @@ QObject *QFxGridView::qmlAttachedProperties(QObject *obj) return QFxGridViewAttached::properties(obj); } -QML_DEFINE_TYPE(QFxGridView,GridView); +QML_DEFINE_TYPE(QFxGridView,GridView) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxgridview.h b/src/declarative/fx/qfxgridview.h index 99c7cff..73f3046 100644 --- a/src/declarative/fx/qfxgridview.h +++ b/src/declarative/fx/qfxgridview.h @@ -139,7 +139,7 @@ private: void refill(); }; -QML_DECLARE_TYPE(QFxGridView); +QML_DECLARE_TYPE(QFxGridView) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxhighlightfilter.cpp b/src/declarative/fx/qfxhighlightfilter.cpp index a22ad98..9807e21 100644 --- a/src/declarative/fx/qfxhighlightfilter.cpp +++ b/src/declarative/fx/qfxhighlightfilter.cpp @@ -314,6 +314,6 @@ void QFxHighlightFilter::filterGL(QSimpleCanvasItem::GLPainter &p) #endif } -QML_DEFINE_TYPE(QFxHighlightFilter,Highlight); +QML_DEFINE_TYPE(QFxHighlightFilter,Highlight) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxhighlightfilter.h b/src/declarative/fx/qfxhighlightfilter.h index 92a3dc7..19e95ac 100644 --- a/src/declarative/fx/qfxhighlightfilter.h +++ b/src/declarative/fx/qfxhighlightfilter.h @@ -89,7 +89,7 @@ protected: private: QFxHighlightFilterPrivate *d; }; -QML_DECLARE_TYPE(QFxHighlightFilter); +QML_DECLARE_TYPE(QFxHighlightFilter) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 064580e..6226e45 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -53,7 +53,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxImage,Image); +QML_DEFINE_TYPE(QFxImage,Image) /*! \qmlclass Image QFxImage diff --git a/src/declarative/fx/qfximage.h b/src/declarative/fx/qfximage.h index 1436551..4d5f134 100644 --- a/src/declarative/fx/qfximage.h +++ b/src/declarative/fx/qfximage.h @@ -120,7 +120,7 @@ private: Q_DECLARE_PRIVATE(QFxImage) void setGridScaledImage(const QFxGridScaledImage& sci); }; -QML_DECLARE_TYPE(QFxImage); +QML_DECLARE_TYPE(QFxImage) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxitem.cpp b/src/declarative/fx/qfxitem.cpp index 3e29f13..7129757 100644 --- a/src/declarative/fx/qfxitem.cpp +++ b/src/declarative/fx/qfxitem.cpp @@ -71,9 +71,9 @@ QT_BEGIN_NAMESPACE #define INT_MAX 2147483647 #endif -QML_DEFINE_NOCREATE_TYPE(QFxContents); -QML_DEFINE_TYPE(QFxItem,Item); -QML_DEFINE_NOCREATE_TYPE(QSimpleCanvasFilter); +QML_DEFINE_NOCREATE_TYPE(QFxContents) +QML_DEFINE_TYPE(QFxItem,Item) +QML_DEFINE_NOCREATE_TYPE(QSimpleCanvasFilter) /*! \group group_animation diff --git a/src/declarative/fx/qfxitem.h b/src/declarative/fx/qfxitem.h index 0b4f897..778c10f 100644 --- a/src/declarative/fx/qfxitem.h +++ b/src/declarative/fx/qfxitem.h @@ -87,8 +87,8 @@ private: int _height; int _width; }; -QML_DECLARE_TYPE(QFxContents); -Q_DECLARE_OPERATORS_FOR_FLAGS(QFxAnchors::UsedAnchors); +QML_DECLARE_TYPE(QFxContents) +Q_DECLARE_OPERATORS_FOR_FLAGS(QFxAnchors::UsedAnchors) class QmlState; class QmlTransition; @@ -267,9 +267,9 @@ private: Q_DISABLE_COPY(QFxItem) Q_DECLARE_PRIVATE(QFxItem) }; -QML_DECLARE_TYPE(QFxItem); +QML_DECLARE_TYPE(QFxItem) -QML_DECLARE_TYPE(QSimpleCanvasFilter); +QML_DECLARE_TYPE(QSimpleCanvasFilter) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxitem_p.h b/src/declarative/fx/qfxitem_p.h index b5f9554..a54f523 100644 --- a/src/declarative/fx/qfxitem_p.h +++ b/src/declarative/fx/qfxitem_p.h @@ -100,7 +100,7 @@ public: void data_insert(int, QObject *); QObject *data_at(int) const; void data_clear(); - QML_DECLARE_LIST_PROXY(QFxItemPrivate, QObject *, data); + QML_DECLARE_LIST_PROXY(QFxItemPrivate, QObject *, data) // resources property void resources_removeAt(int); @@ -109,7 +109,7 @@ public: void resources_insert(int, QObject *); QObject *resources_at(int) const; void resources_clear(); - QML_DECLARE_LIST_PROXY(QFxItemPrivate, QObject *, resources); + QML_DECLARE_LIST_PROXY(QFxItemPrivate, QObject *, resources) // children property void children_removeAt(int); @@ -118,7 +118,7 @@ public: void children_insert(int, QFxItem *); QFxItem *children_at(int) const; void children_clear(); - QML_DECLARE_LIST_PROXY(QFxItemPrivate, QFxItem *, children); + QML_DECLARE_LIST_PROXY(QFxItemPrivate, QFxItem *, children) QList _transform; QFxAnchors *anchors() { diff --git a/src/declarative/fx/qfxkeyactions.cpp b/src/declarative/fx/qfxkeyactions.cpp index a07f047..5a1fd7d 100644 --- a/src/declarative/fx/qfxkeyactions.cpp +++ b/src/declarative/fx/qfxkeyactions.cpp @@ -44,7 +44,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxKeyActions,KeyActions); +QML_DEFINE_TYPE(QFxKeyActions,KeyActions) class QFxKeyActionsPrivate { diff --git a/src/declarative/fx/qfxkeyactions.h b/src/declarative/fx/qfxkeyactions.h index a5aec2e..cea992a 100644 --- a/src/declarative/fx/qfxkeyactions.h +++ b/src/declarative/fx/qfxkeyactions.h @@ -310,7 +310,7 @@ private: QFxKeyActionsPrivate *d; }; -QML_DECLARE_TYPE(QFxKeyActions); +QML_DECLARE_TYPE(QFxKeyActions) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxkeyproxy.cpp b/src/declarative/fx/qfxkeyproxy.cpp index 848b2d9..e80f2c7 100644 --- a/src/declarative/fx/qfxkeyproxy.cpp +++ b/src/declarative/fx/qfxkeyproxy.cpp @@ -43,7 +43,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxKeyProxy,KeyProxy); +QML_DEFINE_TYPE(QFxKeyProxy,KeyProxy) /*! \qmlclass KeyProxy diff --git a/src/declarative/fx/qfxkeyproxy.h b/src/declarative/fx/qfxkeyproxy.h index 6cf0c0d..38cff7a 100644 --- a/src/declarative/fx/qfxkeyproxy.h +++ b/src/declarative/fx/qfxkeyproxy.h @@ -69,7 +69,7 @@ private: QFxKeyProxyPrivate *d; }; -QML_DECLARE_TYPE(QFxKeyProxy); +QML_DECLARE_TYPE(QFxKeyProxy) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxlayouts.cpp b/src/declarative/fx/qfxlayouts.cpp index 53b367a..a975778 100644 --- a/src/declarative/fx/qfxlayouts.cpp +++ b/src/declarative/fx/qfxlayouts.cpp @@ -450,7 +450,7 @@ void QFxBaseLayout::applyRemove(const QList >& changes, applyTransition(changes,target, remove()); } -QML_DEFINE_TYPE(QFxVerticalLayout, VerticalLayout); +QML_DEFINE_TYPE(QFxVerticalLayout, VerticalLayout) /*! \qmlclass VerticalLayout \brief The VerticalLayout item arranges its children in a vertical layout. @@ -651,7 +651,7 @@ void QFxVerticalLayout::doLayout() setMovingItem(0); } -QML_DEFINE_TYPE(QFxHorizontalLayout,HorizontalLayout); +QML_DEFINE_TYPE(QFxHorizontalLayout,HorizontalLayout) /*! \qmlclass HorizontalLayout \brief The HorizontalLayout item arranges its children in a horizontal layout. @@ -815,7 +815,7 @@ void QFxHorizontalLayout::doLayout() setWidth(hoffset); } -QML_DEFINE_TYPE(QFxGridLayout,GridLayout); +QML_DEFINE_TYPE(QFxGridLayout,GridLayout) /*! \qmlclass GridLayout QFxGridLayout diff --git a/src/declarative/fx/qfxlayouts.h b/src/declarative/fx/qfxlayouts.h index 35e41d8..b119d6f 100644 --- a/src/declarative/fx/qfxlayouts.h +++ b/src/declarative/fx/qfxlayouts.h @@ -128,7 +128,7 @@ protected Q_SLOTS: private: Q_DISABLE_COPY(QFxVerticalLayout) }; -QML_DECLARE_TYPE(QFxVerticalLayout); +QML_DECLARE_TYPE(QFxVerticalLayout) class Q_DECLARATIVE_EXPORT QFxHorizontalLayout: public QFxBaseLayout { @@ -140,7 +140,7 @@ protected Q_SLOTS: private: Q_DISABLE_COPY(QFxHorizontalLayout) }; -QML_DECLARE_TYPE(QFxHorizontalLayout); +QML_DECLARE_TYPE(QFxHorizontalLayout) class Q_DECLARATIVE_EXPORT QFxGridLayout : public QFxBaseLayout { @@ -163,7 +163,7 @@ private: int _columns; Q_DISABLE_COPY(QFxGridLayout) }; -QML_DECLARE_TYPE(QFxGridLayout); +QML_DECLARE_TYPE(QFxGridLayout) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxlistview.cpp b/src/declarative/fx/qfxlistview.cpp index 247f64b..432c6ac 100644 --- a/src/declarative/fx/qfxlistview.cpp +++ b/src/declarative/fx/qfxlistview.cpp @@ -1643,7 +1643,7 @@ QObject *QFxListView::qmlAttachedProperties(QObject *obj) return QFxListViewAttached::properties(obj); } -QML_DEFINE_TYPE(QFxListView,ListView); +QML_DEFINE_TYPE(QFxListView,ListView) QT_END_NAMESPACE #include "qfxlistview.moc" diff --git a/src/declarative/fx/qfxlistview.h b/src/declarative/fx/qfxlistview.h index 87a851b..4aa9810 100644 --- a/src/declarative/fx/qfxlistview.h +++ b/src/declarative/fx/qfxlistview.h @@ -145,7 +145,7 @@ private Q_SLOTS: void destroyingItem(QFxItem *item); }; -QML_DECLARE_TYPE(QFxListView); +QML_DECLARE_TYPE(QFxListView) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxmouseregion.cpp b/src/declarative/fx/qfxmouseregion.cpp index a60ddc4..6eb358b 100644 --- a/src/declarative/fx/qfxmouseregion.cpp +++ b/src/declarative/fx/qfxmouseregion.cpp @@ -49,7 +49,7 @@ QT_BEGIN_NAMESPACE static const int DragThreshold = 5; static const int PressAndHoldDelay = 800; -QML_DEFINE_TYPE(QFxDrag,Drag); +QML_DEFINE_TYPE(QFxDrag,Drag) QFxDrag::QFxDrag(QObject *parent) : QObject(parent), _target(0), _xmin(0), _xmax(0), _ymin(0), _ymax(0) { @@ -249,7 +249,7 @@ void QFxDrag::setYmax(int m) position of the release of the click, and whether the click wasHeld. */ -QML_DEFINE_TYPE(QFxMouseRegion,MouseRegion); +QML_DEFINE_TYPE(QFxMouseRegion,MouseRegion) /*! \internal diff --git a/src/declarative/fx/qfxmouseregion.h b/src/declarative/fx/qfxmouseregion.h index 1d1ec93..d7db1dc 100644 --- a/src/declarative/fx/qfxmouseregion.h +++ b/src/declarative/fx/qfxmouseregion.h @@ -86,7 +86,7 @@ private: int _ymax; Q_DISABLE_COPY(QFxDrag) }; -QML_DECLARE_TYPE(QFxDrag); +QML_DECLARE_TYPE(QFxDrag) class QFxMouseEvent; class QFxMouseRegionPrivate; @@ -154,7 +154,7 @@ private: Q_DISABLE_COPY(QFxMouseRegion) Q_DECLARE_PRIVATE(QFxMouseRegion) }; -QML_DECLARE_TYPE(QFxMouseRegion); +QML_DECLARE_TYPE(QFxMouseRegion) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxpainteditem.h b/src/declarative/fx/qfxpainteditem.h index 6cd21e6..997c324 100644 --- a/src/declarative/fx/qfxpainteditem.h +++ b/src/declarative/fx/qfxpainteditem.h @@ -88,7 +88,7 @@ private: Q_DISABLE_COPY(QFxPaintedItem) Q_DECLARE_PRIVATE(QFxPaintedItem) }; -QML_DECLARE_TYPE(QFxPaintedItem); +QML_DECLARE_TYPE(QFxPaintedItem) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxparticles.cpp b/src/declarative/fx/qfxparticles.cpp index 67c1208..e9f38b0 100644 --- a/src/declarative/fx/qfxparticles.cpp +++ b/src/declarative/fx/qfxparticles.cpp @@ -105,7 +105,7 @@ public: //--------------------------------------------------------------------------- -QML_DEFINE_TYPE(QFxParticleMotion,ParticleMotion); +QML_DEFINE_TYPE(QFxParticleMotion,ParticleMotion) /*! \class QFxParticleMotion @@ -165,7 +165,7 @@ void QFxParticleMotion::destroy(QFxParticle &particle) \brief The QFxParticleMotionLinear class moves the particles linearly. */ -QML_DEFINE_TYPE(QFxParticleMotionLinear,ParticleMotionLinear); +QML_DEFINE_TYPE(QFxParticleMotionLinear,ParticleMotionLinear) void QFxParticleMotionLinear::advance(QFxParticle &p, int interval) { @@ -187,7 +187,7 @@ void QFxParticleMotionLinear::advance(QFxParticle &p, int interval) \brief The QFxParticleMotionGravity class moves the particles towards a point. */ -QML_DEFINE_TYPE(QFxParticleMotionGravity,ParticleMotionGravity); +QML_DEFINE_TYPE(QFxParticleMotionGravity,ParticleMotionGravity) /*! \qmlproperty int ParticleMotionGravity::xattractor @@ -289,7 +289,7 @@ Rect { This property holds how quickly the paricles will move from side to side. */ -QML_DEFINE_TYPE(QFxParticleMotionWander,ParticleMotionWander); +QML_DEFINE_TYPE(QFxParticleMotionWander,ParticleMotionWander) void QFxParticleMotionWander::advance(QFxParticle &p, int interval) { @@ -546,7 +546,7 @@ void QFxParticlesPrivate::updateOpacity(QFxParticle &p, int age) } } -QML_DEFINE_TYPE(QFxParticles,Particles); +QML_DEFINE_TYPE(QFxParticles,Particles) /*! \qmlclass Particles diff --git a/src/declarative/fx/qfxparticles.h b/src/declarative/fx/qfxparticles.h index 31a00fb..9f0d04c 100644 --- a/src/declarative/fx/qfxparticles.h +++ b/src/declarative/fx/qfxparticles.h @@ -66,7 +66,7 @@ public: virtual void created(QFxParticle &); virtual void destroy(QFxParticle &); }; -QML_DECLARE_TYPE(QFxParticleMotion); +QML_DECLARE_TYPE(QFxParticleMotion) class Q_DECLARATIVE_EXPORT QFxParticleMotionLinear : public QFxParticleMotion { @@ -77,7 +77,7 @@ public: virtual void advance(QFxParticle &, int interval); }; -QML_DECLARE_TYPE(QFxParticleMotionLinear); +QML_DECLARE_TYPE(QFxParticleMotionLinear) class Q_DECLARATIVE_EXPORT QFxParticleMotionGravity : public QFxParticleMotion { @@ -106,7 +106,7 @@ private: int _yAttr; qreal _accel; }; -QML_DECLARE_TYPE(QFxParticleMotionGravity); +QML_DECLARE_TYPE(QFxParticleMotionGravity) class Q_DECLARATIVE_EXPORT QFxParticleMotionWander : public QFxParticleMotion { @@ -146,7 +146,7 @@ private: qreal _yvariance; qreal _pace; }; -QML_DECLARE_TYPE(QFxParticleMotionWander); +QML_DECLARE_TYPE(QFxParticleMotionWander) class QFxParticlesPrivate; class Q_DECLARATIVE_EXPORT QFxParticles : public QFxItem @@ -231,7 +231,7 @@ private: Q_DISABLE_COPY(QFxParticles) Q_DECLARE_PRIVATE(QFxParticles) }; -QML_DECLARE_TYPE(QFxParticles); +QML_DECLARE_TYPE(QFxParticles) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxpath.cpp b/src/declarative/fx/qfxpath.cpp index 5bbdf64..5deaaa5 100644 --- a/src/declarative/fx/qfxpath.cpp +++ b/src/declarative/fx/qfxpath.cpp @@ -46,14 +46,14 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxPath,Path); -QML_DEFINE_NOCREATE_TYPE(QFxPathElement); -QML_DEFINE_NOCREATE_TYPE(QFxCurve); -QML_DEFINE_TYPE(QFxPathAttribute,PathAttribute); -QML_DEFINE_TYPE(QFxPathPercent,PathPercent); -QML_DEFINE_TYPE(QFxPathLine,PathLine); -QML_DEFINE_TYPE(QFxPathQuad,PathQuad); -QML_DEFINE_TYPE(QFxPathCubic,PathCubic); +QML_DEFINE_TYPE(QFxPath,Path) +QML_DEFINE_NOCREATE_TYPE(QFxPathElement) +QML_DEFINE_NOCREATE_TYPE(QFxCurve) +QML_DEFINE_TYPE(QFxPathAttribute,PathAttribute) +QML_DEFINE_TYPE(QFxPathPercent,PathPercent) +QML_DEFINE_TYPE(QFxPathLine,PathLine) +QML_DEFINE_TYPE(QFxPathQuad,PathQuad) +QML_DEFINE_TYPE(QFxPathCubic,PathCubic) /*! \qmlclass PathElement diff --git a/src/declarative/fx/qfxpath.h b/src/declarative/fx/qfxpath.h index 10cf252..5c17fcb 100644 --- a/src/declarative/fx/qfxpath.h +++ b/src/declarative/fx/qfxpath.h @@ -61,7 +61,7 @@ public: Q_SIGNALS: void changed(); }; -QML_DECLARE_TYPE(QFxPathElement); +QML_DECLARE_TYPE(QFxPathElement) class Q_DECLARATIVE_EXPORT QFxPathAttribute : public QFxPathElement { @@ -83,7 +83,7 @@ private: QString _name; qreal _value; }; -QML_DECLARE_TYPE(QFxPathAttribute); +QML_DECLARE_TYPE(QFxPathAttribute) class Q_DECLARATIVE_EXPORT QFxCurve : public QFxPathElement { @@ -106,7 +106,7 @@ private: qreal _x; qreal _y; }; -QML_DECLARE_TYPE(QFxCurve); +QML_DECLARE_TYPE(QFxCurve) class Q_DECLARATIVE_EXPORT QFxPathLine : public QFxCurve { @@ -116,7 +116,7 @@ public: void addToPath(QPainterPath &path); }; -QML_DECLARE_TYPE(QFxPathLine); +QML_DECLARE_TYPE(QFxPathLine) class Q_DECLARATIVE_EXPORT QFxPathQuad : public QFxCurve { @@ -139,7 +139,7 @@ private: qreal _controlX; qreal _controlY; }; -QML_DECLARE_TYPE(QFxPathQuad); +QML_DECLARE_TYPE(QFxPathQuad) class Q_DECLARATIVE_EXPORT QFxPathCubic : public QFxCurve { @@ -172,7 +172,7 @@ private: int _control2X; int _control2Y; }; -QML_DECLARE_TYPE(QFxPathCubic); +QML_DECLARE_TYPE(QFxPathCubic) class Q_DECLARATIVE_EXPORT QFxPathPercent : public QFxPathElement { @@ -187,7 +187,7 @@ public: private: qreal _value; }; -QML_DECLARE_TYPE(QFxPathPercent); +QML_DECLARE_TYPE(QFxPathPercent) class QFxPathPrivate; class Q_DECLARATIVE_EXPORT QFxPath : public QObject, public QmlParserStatus @@ -249,7 +249,7 @@ private: Q_DISABLE_COPY(QFxPath) Q_DECLARE_PRIVATE(QFxPath) }; -QML_DECLARE_TYPE(QFxPath); +QML_DECLARE_TYPE(QFxPath) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxpathview.cpp b/src/declarative/fx/qfxpathview.cpp index 3f2e77a..625d778 100644 --- a/src/declarative/fx/qfxpathview.cpp +++ b/src/declarative/fx/qfxpathview.cpp @@ -55,7 +55,7 @@ static const int FlickThreshold = 5; QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxPathView,PathView); +QML_DEFINE_TYPE(QFxPathView,PathView) class QFxPathViewAttached : public QObject { diff --git a/src/declarative/fx/qfxpathview.h b/src/declarative/fx/qfxpathview.h index 33db566..cbdafa8 100644 --- a/src/declarative/fx/qfxpathview.h +++ b/src/declarative/fx/qfxpathview.h @@ -127,7 +127,7 @@ private: Q_DISABLE_COPY(QFxPathView) Q_DECLARE_PRIVATE(QFxPathView) }; -QML_DECLARE_TYPE(QFxPathView); +QML_DECLARE_TYPE(QFxPathView) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index f81f9b3..90170da 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -44,7 +44,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxPen,Pen); +QML_DEFINE_TYPE(QFxPen,Pen) /*! \internal @@ -118,7 +118,7 @@ void QFxPen::setWidth(int w) -QML_DEFINE_TYPE(QFxRect,Rect); +QML_DEFINE_TYPE(QFxRect,Rect) /*! \qmlclass Rect QFxRect diff --git a/src/declarative/fx/qfxrect.h b/src/declarative/fx/qfxrect.h index 420ec44..209a8ef 100644 --- a/src/declarative/fx/qfxrect.h +++ b/src/declarative/fx/qfxrect.h @@ -77,7 +77,7 @@ private: QColor _color; bool _valid; }; -QML_DECLARE_TYPE(QFxPen); +QML_DECLARE_TYPE(QFxPen) class QFxRectPrivate; class Q_DECLARATIVE_EXPORT QFxRect : public QFxItem @@ -131,7 +131,7 @@ private: Q_DISABLE_COPY(QFxRect) Q_DECLARE_PRIVATE(QFxRect) }; -QML_DECLARE_TYPE(QFxRect); +QML_DECLARE_TYPE(QFxRect) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxreflectionfilter.cpp b/src/declarative/fx/qfxreflectionfilter.cpp index 0bc01a7..2e57aa7 100644 --- a/src/declarative/fx/qfxreflectionfilter.cpp +++ b/src/declarative/fx/qfxreflectionfilter.cpp @@ -348,5 +348,5 @@ QRectF QFxReflectionFilter::itemBoundingRect(const QRectF &r) const return rv; } -QML_DEFINE_TYPE(QFxReflectionFilter,Reflection); +QML_DEFINE_TYPE(QFxReflectionFilter,Reflection) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxreflectionfilter.h b/src/declarative/fx/qfxreflectionfilter.h index 383e12f..6e56b5e 100644 --- a/src/declarative/fx/qfxreflectionfilter.h +++ b/src/declarative/fx/qfxreflectionfilter.h @@ -87,7 +87,7 @@ private: Q_DISABLE_COPY(QFxReflectionFilter) QFxReflectionFilterPrivate *d; }; -QML_DECLARE_TYPE(QFxReflectionFilter); +QML_DECLARE_TYPE(QFxReflectionFilter) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxrepeater.cpp b/src/declarative/fx/qfxrepeater.cpp index 23b4e01..0211ebb 100644 --- a/src/declarative/fx/qfxrepeater.cpp +++ b/src/declarative/fx/qfxrepeater.cpp @@ -71,7 +71,7 @@ QFxItem *QFxRepeaterPrivate::addItem(QmlContext *ctxt, QFxItem *lastItem) return item; } -QML_DEFINE_TYPE(QFxRepeater,Repeater); +QML_DEFINE_TYPE(QFxRepeater,Repeater) /*! \qmlclass Repeater diff --git a/src/declarative/fx/qfxrepeater.h b/src/declarative/fx/qfxrepeater.h index 362242b..c1b194a 100644 --- a/src/declarative/fx/qfxrepeater.h +++ b/src/declarative/fx/qfxrepeater.h @@ -80,7 +80,7 @@ private: Q_DISABLE_COPY(QFxRepeater) Q_DECLARE_PRIVATE(QFxRepeater) }; -QML_DECLARE_TYPE(QFxRepeater); +QML_DECLARE_TYPE(QFxRepeater) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxscalegrid.h b/src/declarative/fx/qfxscalegrid.h index d0f735f..2a20de7 100644 --- a/src/declarative/fx/qfxscalegrid.h +++ b/src/declarative/fx/qfxscalegrid.h @@ -111,7 +111,7 @@ private: int _b; QString _pix; }; -QML_DECLARE_TYPE(QFxScaleGrid); +QML_DECLARE_TYPE(QFxScaleGrid) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxshadowfilter.cpp b/src/declarative/fx/qfxshadowfilter.cpp index 83c1b47..10c332c 100644 --- a/src/declarative/fx/qfxshadowfilter.cpp +++ b/src/declarative/fx/qfxshadowfilter.cpp @@ -209,6 +209,6 @@ void QFxShadowFilter::filterGL(QSimpleCanvasItem::GLPainter &p) #endif } -QML_DEFINE_TYPE(QFxShadowFilter,Shadow); +QML_DEFINE_TYPE(QFxShadowFilter,Shadow) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxshadowfilter.h b/src/declarative/fx/qfxshadowfilter.h index fc54e01..67d165a 100644 --- a/src/declarative/fx/qfxshadowfilter.h +++ b/src/declarative/fx/qfxshadowfilter.h @@ -77,7 +77,7 @@ protected: private: QFxShadowFilterPrivate *d; }; -QML_DECLARE_TYPE(QFxShadowFilter); +QML_DECLARE_TYPE(QFxShadowFilter) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxtext.cpp b/src/declarative/fx/qfxtext.cpp index 315b451..94a1712 100644 --- a/src/declarative/fx/qfxtext.cpp +++ b/src/declarative/fx/qfxtext.cpp @@ -57,7 +57,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxText,Text); +QML_DEFINE_TYPE(QFxText,Text) /*! \qmlclass Text QFxText diff --git a/src/declarative/fx/qfxtext.h b/src/declarative/fx/qfxtext.h index ee9082b..158aece 100644 --- a/src/declarative/fx/qfxtext.h +++ b/src/declarative/fx/qfxtext.h @@ -144,7 +144,7 @@ private: Q_DISABLE_COPY(QFxText) Q_DECLARE_PRIVATE(QFxText) }; -QML_DECLARE_TYPE(QFxText); +QML_DECLARE_TYPE(QFxText) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxtextedit.cpp b/src/declarative/fx/qfxtextedit.cpp index f59e0ae..fc73ecd 100644 --- a/src/declarative/fx/qfxtextedit.cpp +++ b/src/declarative/fx/qfxtextedit.cpp @@ -58,7 +58,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxTextEdit, TextEdit); +QML_DEFINE_TYPE(QFxTextEdit, TextEdit) /*! \qmlclass TextEdit diff --git a/src/declarative/fx/qfxtextedit.h b/src/declarative/fx/qfxtextedit.h index 1456cd8..37bc327 100644 --- a/src/declarative/fx/qfxtextedit.h +++ b/src/declarative/fx/qfxtextedit.h @@ -198,7 +198,7 @@ private: Q_DISABLE_COPY(QFxTextEdit) Q_DECLARE_PRIVATE(QFxTextEdit) }; -QML_DECLARE_TYPE(QFxTextEdit); +QML_DECLARE_TYPE(QFxTextEdit) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxtransform.cpp b/src/declarative/fx/qfxtransform.cpp index d99af27..a4c5d22 100644 --- a/src/declarative/fx/qfxtransform.cpp +++ b/src/declarative/fx/qfxtransform.cpp @@ -99,7 +99,7 @@ void QFxTransform::update() \endqml */ -QML_DEFINE_TYPE(QFxAxis, Axis); +QML_DEFINE_TYPE(QFxAxis, Axis) QFxAxis::QFxAxis(QObject *parent) : QObject(parent), _startX(0), _startY(0), _endX(0), _endY(0), _endZ(0) @@ -286,7 +286,7 @@ void QFxRotation::update() QFxTransform::update(); } -QML_DEFINE_TYPE(QFxRotation, Rotation); +QML_DEFINE_TYPE(QFxRotation, Rotation) /*! \qmlclass Rotation3D @@ -298,7 +298,7 @@ QML_DEFINE_TYPE(QFxRotation, Rotation); \image axisrotation.png */ -QML_DEFINE_TYPE(QFxRotation3D,Rotation3D); +QML_DEFINE_TYPE(QFxRotation3D,Rotation3D) QFxRotation3D::QFxRotation3D(QObject *parent) : QFxTransform(parent), _angle(0), _dirty(true) @@ -448,7 +448,7 @@ Image { \endqml */ -QML_DEFINE_TYPE(QFxTranslation3D,Translation3D); +QML_DEFINE_TYPE(QFxTranslation3D,Translation3D) QFxTranslation3D::QFxTranslation3D(QObject *parent) : QFxTransform(parent), _distance(0), _dirty(true) @@ -568,7 +568,7 @@ void QFxTranslation3D::update() OpenGL. When running under software rasterization it has no effect. */ -QML_DEFINE_TYPE(QFxPerspective,Perspective); +QML_DEFINE_TYPE(QFxPerspective,Perspective) QFxPerspective::QFxPerspective(QObject *parent) : QFxTransform(parent) @@ -683,7 +683,7 @@ QMatrix4x4 QFxPerspective::transform() const \image squish.png */ -QML_DEFINE_TYPE(QFxSquish,Squish); +QML_DEFINE_TYPE(QFxSquish,Squish) QFxSquish::QFxSquish(QObject *parent) : QFxTransform(parent) diff --git a/src/declarative/fx/qfxtransform.h b/src/declarative/fx/qfxtransform.h index 31374df..7be8adc 100644 --- a/src/declarative/fx/qfxtransform.h +++ b/src/declarative/fx/qfxtransform.h @@ -67,7 +67,7 @@ public: virtual bool isIdentity() const; virtual QSimpleCanvas::Matrix transform() const; }; -QML_DECLARE_TYPE(QFxTransform); +QML_DECLARE_TYPE(QFxTransform) class Q_DECLARATIVE_EXPORT QFxAxis : public QObject { @@ -107,7 +107,7 @@ private: qreal _endY; qreal _endZ; }; -QML_DECLARE_TYPE(QFxAxis); +QML_DECLARE_TYPE(QFxAxis) class Q_DECLARATIVE_EXPORT QFxRotation : public QFxTransform { @@ -145,7 +145,7 @@ private: mutable bool _dirty; mutable QSimpleCanvas::Matrix _transform; }; -QML_DECLARE_TYPE(QFxRotation); +QML_DECLARE_TYPE(QFxRotation) class Q_DECLARATIVE_EXPORT QFxRotation3D : public QFxTransform { @@ -174,7 +174,7 @@ private: mutable bool _dirty; mutable QSimpleCanvas::Matrix _transform; }; -QML_DECLARE_TYPE(QFxRotation3D); +QML_DECLARE_TYPE(QFxRotation3D) class Q_DECLARATIVE_EXPORT QFxTranslation3D : public QFxTransform { @@ -203,7 +203,7 @@ private: mutable bool _dirty; mutable QSimpleCanvas::Matrix _transform; }; -QML_DECLARE_TYPE(QFxTranslation3D); +QML_DECLARE_TYPE(QFxTranslation3D) class Q_DECLARATIVE_EXPORT QFxPerspective : public QFxTransform { @@ -244,7 +244,7 @@ private: qreal _angle; qreal _aspect; }; -QML_DECLARE_TYPE(QFxPerspective); +QML_DECLARE_TYPE(QFxPerspective) class Q_DECLARATIVE_EXPORT QFxSquish : public QFxTransform { @@ -310,7 +310,7 @@ private: QSizeF s; QPointF p1, p2, p3, p4; }; -QML_DECLARE_TYPE(QFxSquish); +QML_DECLARE_TYPE(QFxSquish) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxvisualitemmodel.cpp b/src/declarative/fx/qfxvisualitemmodel.cpp index 039998a..cac5d59 100644 --- a/src/declarative/fx/qfxvisualitemmodel.cpp +++ b/src/declarative/fx/qfxvisualitemmodel.cpp @@ -54,7 +54,7 @@ QT_BEGIN_NAMESPACE -QML_DECLARE_TYPE(QListModelInterface); +QML_DECLARE_TYPE(QListModelInterface) class QFxVisualItemModelParts; class QFxVisualItemModelData; @@ -765,7 +765,7 @@ void QFxVisualItemModel::_q_destroyingPackage(QmlPackage *package) emit destroyingItem(qobject_cast(package->part(d->m_part))); } -QML_DEFINE_TYPE(QFxVisualItemModel,VisualModel); +QML_DEFINE_TYPE(QFxVisualItemModel,VisualModel) QT_END_NAMESPACE #include "qfxvisualitemmodel.moc" diff --git a/src/declarative/fx/qfxvisualitemmodel.h b/src/declarative/fx/qfxvisualitemmodel.h index 622065c..968cc2e 100644 --- a/src/declarative/fx/qfxvisualitemmodel.h +++ b/src/declarative/fx/qfxvisualitemmodel.h @@ -123,7 +123,7 @@ private Q_SLOTS: private: Q_DISABLE_COPY(QFxVisualItemModel) }; -QML_DECLARE_TYPE(QFxVisualItemModel); +QML_DECLARE_TYPE(QFxVisualItemModel) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxwebview.cpp b/src/declarative/fx/qfxwebview.cpp index 7998711..4c35cae 100644 --- a/src/declarative/fx/qfxwebview.cpp +++ b/src/declarative/fx/qfxwebview.cpp @@ -71,7 +71,7 @@ #include QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxWebView,WebView); +QML_DEFINE_TYPE(QFxWebView,WebView) static const int MAX_DOUBLECLICK_TIME=500; // XXX need better gesture system diff --git a/src/declarative/fx/qfxwebview.h b/src/declarative/fx/qfxwebview.h index 6a3dad5..28ef6c3 100644 --- a/src/declarative/fx/qfxwebview.h +++ b/src/declarative/fx/qfxwebview.h @@ -207,7 +207,7 @@ private: Q_DISABLE_COPY(QFxWebView) Q_DECLARE_PRIVATE(QFxWebView) }; -QML_DECLARE_TYPE(QFxWebView); +QML_DECLARE_TYPE(QFxWebView) QT_END_NAMESPACE diff --git a/src/declarative/fx/qfxwidgetcontainer.cpp b/src/declarative/fx/qfxwidgetcontainer.cpp index fccdad1..421c2f7 100644 --- a/src/declarative/fx/qfxwidgetcontainer.cpp +++ b/src/declarative/fx/qfxwidgetcontainer.cpp @@ -56,7 +56,7 @@ QT_BEGIN_NAMESPACE \brief The QFxWidgetContainer class allows you to add QGraphicsWidgets into Fluid UI applications. */ -QML_DEFINE_TYPE(QFxWidgetContainer, WidgetContainer); +QML_DEFINE_TYPE(QFxWidgetContainer, WidgetContainer) QFxWidgetContainer::QFxWidgetContainer(QFxItem *parent) : QFxItem(parent), _graphicsWidget(0) diff --git a/src/declarative/fx/qfxwidgetcontainer.h b/src/declarative/fx/qfxwidgetcontainer.h index 3b1f016..cc36010 100644 --- a/src/declarative/fx/qfxwidgetcontainer.h +++ b/src/declarative/fx/qfxwidgetcontainer.h @@ -72,7 +72,7 @@ protected: private: QGraphicsWidget *_graphicsWidget; }; -QML_DECLARE_TYPE(QFxWidgetContainer); +QML_DECLARE_TYPE(QFxWidgetContainer) QT_END_NAMESPACE diff --git a/src/declarative/qml/qml.h b/src/declarative/qml/qml.h index b435e94..370bb58 100644 --- a/src/declarative/qml/qml.h +++ b/src/declarative/qml/qml.h @@ -59,13 +59,13 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) #define QML_DECLARE_TYPE(TYPE) \ - Q_DECLARE_METATYPE(TYPE *); \ - Q_DECLARE_METATYPE(QList *); \ - Q_DECLARE_METATYPE(QmlList *); + Q_DECLARE_METATYPE(TYPE *) \ + Q_DECLARE_METATYPE(QList *) \ + Q_DECLARE_METATYPE(QmlList *) #define QML_DECLARE_TYPE_HASMETATYPE(TYPE) \ - Q_DECLARE_METATYPE(QList *); \ - Q_DECLARE_METATYPE(QmlList *); + Q_DECLARE_METATYPE(QList *) \ + Q_DECLARE_METATYPE(QmlList *) #define QML_DECLARE_INTERFACE(INTERFACE) \ QML_DECLARE_TYPE(INTERFACE) @@ -109,8 +109,8 @@ QObject *qmlAttachedPropertiesObject(const QObject *obj) return qmlAttachedPropertiesObjectById(idx, obj); } -QML_DECLARE_TYPE(QObject); -Q_DECLARE_METATYPE(QVariant); +QML_DECLARE_TYPE(QObject) +Q_DECLARE_METATYPE(QVariant) QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlbindablevalue.h b/src/declarative/qml/qmlbindablevalue.h index 7831177..e50c154 100644 --- a/src/declarative/qml/qmlbindablevalue.h +++ b/src/declarative/qml/qmlbindablevalue.h @@ -85,7 +85,7 @@ protected: private: Q_DECLARE_PRIVATE(QmlBindableValue) }; -QML_DECLARE_TYPE(QmlBindableValue); +QML_DECLARE_TYPE(QmlBindableValue) QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlcomponent.h b/src/declarative/qml/qmlcomponent.h index 90f7467..3369de3 100644 --- a/src/declarative/qml/qmlcomponent.h +++ b/src/declarative/qml/qmlcomponent.h @@ -101,7 +101,7 @@ private: friend class QmlVME; friend struct QmlCompositeTypeData; }; -QML_DECLARE_TYPE(QmlComponent); +QML_DECLARE_TYPE(QmlComponent) QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlpropertyvaluesource.h b/src/declarative/qml/qmlpropertyvaluesource.h index 736b25f..9cef150 100644 --- a/src/declarative/qml/qmlpropertyvaluesource.h +++ b/src/declarative/qml/qmlpropertyvaluesource.h @@ -69,7 +69,7 @@ protected: private: Q_DISABLE_COPY(QmlPropertyValueSource) }; -QML_DECLARE_TYPE(QmlPropertyValueSource); +QML_DECLARE_TYPE(QmlPropertyValueSource) #endif // QMLPROPERTYVALUESOURCE_H diff --git a/src/declarative/util/qfxperf.h b/src/declarative/util/qfxperf.h index 3430658..23de8b5 100644 --- a/src/declarative/util/qfxperf.h +++ b/src/declarative/util/qfxperf.h @@ -50,33 +50,33 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) Q_DECLARE_PERFORMANCE_LOG(QFxPerf) { - Q_DECLARE_PERFORMANCE_METRIC(QmlParsing); - Q_DECLARE_PERFORMANCE_METRIC(Compile); - Q_DECLARE_PERFORMANCE_METRIC(CompileRun); - Q_DECLARE_PERFORMANCE_METRIC(CreateComponent); - Q_DECLARE_PERFORMANCE_METRIC(BindInit); - Q_DECLARE_PERFORMANCE_METRIC(BindCompile); - Q_DECLARE_PERFORMANCE_METRIC(BindValue); - Q_DECLARE_PERFORMANCE_METRIC(BindValueSSE); - Q_DECLARE_PERFORMANCE_METRIC(BindValueQt); - Q_DECLARE_PERFORMANCE_METRIC(ContextQuery); - Q_DECLARE_PERFORMANCE_METRIC(ContextProperty); - Q_DECLARE_PERFORMANCE_METRIC(ObjectQuery); - Q_DECLARE_PERFORMANCE_METRIC(ObjectProperty); - Q_DECLARE_PERFORMANCE_METRIC(ObjectSetProperty); - Q_DECLARE_PERFORMANCE_METRIC(BindableValueUpdate); - Q_DECLARE_PERFORMANCE_METRIC(PixmapLoad); - Q_DECLARE_PERFORMANCE_METRIC(MetaProperty); - Q_DECLARE_PERFORMANCE_METRIC(PathCache); - Q_DECLARE_PERFORMANCE_METRIC(CreateParticle); - Q_DECLARE_PERFORMANCE_METRIC(FontDatabase); - Q_DECLARE_PERFORMANCE_METRIC(ItemComponentComplete); - Q_DECLARE_PERFORMANCE_METRIC(ImageComponentComplete); - Q_DECLARE_PERFORMANCE_METRIC(ComponentInstanceComponentComplete); - Q_DECLARE_PERFORMANCE_METRIC(BaseLayoutComponentComplete); - Q_DECLARE_PERFORMANCE_METRIC(TextComponentComplete); - Q_DECLARE_PERFORMANCE_METRIC(QFxText_setText); - Q_DECLARE_PERFORMANCE_METRIC(AddScript); + Q_DECLARE_PERFORMANCE_METRIC(QmlParsing) + Q_DECLARE_PERFORMANCE_METRIC(Compile) + Q_DECLARE_PERFORMANCE_METRIC(CompileRun) + Q_DECLARE_PERFORMANCE_METRIC(CreateComponent) + Q_DECLARE_PERFORMANCE_METRIC(BindInit) + Q_DECLARE_PERFORMANCE_METRIC(BindCompile) + Q_DECLARE_PERFORMANCE_METRIC(BindValue) + Q_DECLARE_PERFORMANCE_METRIC(BindValueSSE) + Q_DECLARE_PERFORMANCE_METRIC(BindValueQt) + Q_DECLARE_PERFORMANCE_METRIC(ContextQuery) + Q_DECLARE_PERFORMANCE_METRIC(ContextProperty) + Q_DECLARE_PERFORMANCE_METRIC(ObjectQuery) + Q_DECLARE_PERFORMANCE_METRIC(ObjectProperty) + Q_DECLARE_PERFORMANCE_METRIC(ObjectSetProperty) + Q_DECLARE_PERFORMANCE_METRIC(BindableValueUpdate) + Q_DECLARE_PERFORMANCE_METRIC(PixmapLoad) + Q_DECLARE_PERFORMANCE_METRIC(MetaProperty) + Q_DECLARE_PERFORMANCE_METRIC(PathCache) + Q_DECLARE_PERFORMANCE_METRIC(CreateParticle) + Q_DECLARE_PERFORMANCE_METRIC(FontDatabase) + Q_DECLARE_PERFORMANCE_METRIC(ItemComponentComplete) + Q_DECLARE_PERFORMANCE_METRIC(ImageComponentComplete) + Q_DECLARE_PERFORMANCE_METRIC(ComponentInstanceComponentComplete) + Q_DECLARE_PERFORMANCE_METRIC(BaseLayoutComponentComplete) + Q_DECLARE_PERFORMANCE_METRIC(TextComponentComplete) + Q_DECLARE_PERFORMANCE_METRIC(QFxText_setText) + Q_DECLARE_PERFORMANCE_METRIC(AddScript) } #endif // _QFXPERF_H_ diff --git a/src/declarative/util/qmlanimation.cpp b/src/declarative/util/qmlanimation.cpp index 24bcac98..d4aea81 100644 --- a/src/declarative/util/qmlanimation.cpp +++ b/src/declarative/util/qmlanimation.cpp @@ -137,7 +137,7 @@ QEasingCurve stringToCurve(const QString &curve) return easingCurve; } -QML_DEFINE_NOCREATE_TYPE(QmlAbstractAnimation); +QML_DEFINE_NOCREATE_TYPE(QmlAbstractAnimation) /*! \qmlclass Animation @@ -554,7 +554,7 @@ void QmlAbstractAnimation::timelineComplete() \l{xmlPauseAnimation} {<PauseAnimation>}. */ -QML_DEFINE_TYPE(QmlPauseAnimation,PauseAnimation); +QML_DEFINE_TYPE(QmlPauseAnimation,PauseAnimation) QmlPauseAnimation::QmlPauseAnimation(QObject *parent) : QmlAbstractAnimation(*(new QmlPauseAnimationPrivate), parent) { @@ -924,7 +924,7 @@ void QmlColorAnimationPrivate::valueChanged(qreal v) property.write(newColor); } } -QML_DEFINE_TYPE(QmlColorAnimation,ColorAnimation); +QML_DEFINE_TYPE(QmlColorAnimation,ColorAnimation) /*! \qmlclass RunScriptAction QmlRunScriptAction @@ -1018,7 +1018,7 @@ QAbstractAnimation *QmlRunScriptAction::qtAnimation() return d->rsa; } -QML_DEFINE_TYPE(QmlRunScriptAction, RunScriptAction); +QML_DEFINE_TYPE(QmlRunScriptAction, RunScriptAction) /*! \qmlclass SetPropertyAction QmlSetPropertyAction @@ -1215,7 +1215,7 @@ void QmlSetPropertyAction::transition(QmlStateActions &actions, } } -QML_DEFINE_TYPE(QmlSetPropertyAction,SetPropertyAction); +QML_DEFINE_TYPE(QmlSetPropertyAction,SetPropertyAction) /*! \qmlclass ParentChangeAction QmlParentChangeAction @@ -1325,7 +1325,7 @@ void QmlParentChangeAction::transition(QmlStateActions &actions, } } -QML_DEFINE_TYPE(QmlParentChangeAction,ParentChangeAction); +QML_DEFINE_TYPE(QmlParentChangeAction,ParentChangeAction) /*! \qmlclass NumericAnimation QmlNumericAnimation @@ -1707,7 +1707,7 @@ void QmlNumericAnimation::transition(QmlStateActions &actions, } } -QML_DEFINE_TYPE(QmlNumericAnimation,NumericAnimation); +QML_DEFINE_TYPE(QmlNumericAnimation,NumericAnimation) QmlAnimationGroup::QmlAnimationGroup(QObject *parent) : QmlAbstractAnimation(*(new QmlAnimationGroupPrivate), parent) @@ -1799,7 +1799,7 @@ void QmlSequentialAnimation::transition(QmlStateActions &actions, //d->ag->setDirection(direction == Backward ? QAbstractAnimation::Backward : QAbstractAnimation::Forward); } -QML_DEFINE_TYPE(QmlSequentialAnimation,SequentialAnimation); +QML_DEFINE_TYPE(QmlSequentialAnimation,SequentialAnimation) /*! \qmlclass ParallelAnimation QmlParallelAnimation @@ -1875,7 +1875,7 @@ void QmlParallelAnimation::transition(QmlStateActions &actions, } } -QML_DEFINE_TYPE(QmlParallelAnimation,ParallelAnimation); +QML_DEFINE_TYPE(QmlParallelAnimation,ParallelAnimation) QVariant QmlVariantAnimationPrivate::interpolateVariant(const QVariant &from, const QVariant &to, qreal progress) { @@ -2262,6 +2262,6 @@ void QmlVariantAnimation::transition(QmlStateActions &actions, } //XXX whats the best name for this? (just Animation?) -QML_DEFINE_TYPE(QmlVariantAnimation,VariantAnimation); +QML_DEFINE_TYPE(QmlVariantAnimation,VariantAnimation) QT_END_NAMESPACE diff --git a/src/declarative/util/qmlanimation.h b/src/declarative/util/qmlanimation.h index 8bd53e2..74cf1b4 100644 --- a/src/declarative/util/qmlanimation.h +++ b/src/declarative/util/qmlanimation.h @@ -124,7 +124,7 @@ private Q_SLOTS: void timelineComplete(); }; -QML_DECLARE_TYPE(QmlAbstractAnimation); +QML_DECLARE_TYPE(QmlAbstractAnimation) class QmlPauseAnimationPrivate; class QmlPauseAnimation : public QmlAbstractAnimation @@ -148,7 +148,7 @@ protected: virtual QAbstractAnimation *qtAnimation(); virtual void prepare(QmlMetaProperty &); }; -QML_DECLARE_TYPE(QmlPauseAnimation); +QML_DECLARE_TYPE(QmlPauseAnimation) class QmlColorAnimationPrivate; class QmlColorAnimation : public QmlAbstractAnimation @@ -195,7 +195,7 @@ Q_SIGNALS: void toChanged(const QColor &); void easingChanged(const QString &); }; -QML_DECLARE_TYPE(QmlColorAnimation); +QML_DECLARE_TYPE(QmlColorAnimation) class QmlRunScriptActionPrivate; class QmlRunScriptAction : public QmlAbstractAnimation @@ -223,7 +223,7 @@ Q_SIGNALS: protected: virtual QAbstractAnimation *qtAnimation(); }; -QML_DECLARE_TYPE(QmlRunScriptAction); +QML_DECLARE_TYPE(QmlRunScriptAction) class QmlSetPropertyActionPrivate; class QmlSetPropertyAction : public QmlAbstractAnimation @@ -260,7 +260,7 @@ protected: virtual QAbstractAnimation *qtAnimation(); virtual void prepare(QmlMetaProperty &); }; -QML_DECLARE_TYPE(QmlSetPropertyAction); +QML_DECLARE_TYPE(QmlSetPropertyAction) class QmlParentChangeActionPrivate; class QmlParentChangeAction : public QmlAbstractAnimation @@ -281,7 +281,7 @@ protected: virtual QAbstractAnimation *qtAnimation(); virtual void prepare(QmlMetaProperty &); }; -QML_DECLARE_TYPE(QmlParentChangeAction); +QML_DECLARE_TYPE(QmlParentChangeAction) class QmlNumericAnimationPrivate; class QmlNumericAnimation : public QmlAbstractAnimation @@ -333,7 +333,7 @@ Q_SIGNALS: void easingChanged(const QString &); void propertiesChanged(const QString &); }; -QML_DECLARE_TYPE(QmlNumericAnimation); +QML_DECLARE_TYPE(QmlNumericAnimation) #if 0 class QmlDiscreteAnimation : public QmlAbstractAnimation @@ -374,7 +374,7 @@ protected: virtual QAbstractAnimation *qtAnimation(); virtual void prepare(QmlMetaProperty &); }; -QML_DECLARE_TYPE(QmlSequentialAnimation); +QML_DECLARE_TYPE(QmlSequentialAnimation) class QmlParallelAnimation : public QmlAnimationGroup { @@ -392,7 +392,7 @@ protected: virtual QAbstractAnimation *qtAnimation(); virtual void prepare(QmlMetaProperty &); }; -QML_DECLARE_TYPE(QmlParallelAnimation); +QML_DECLARE_TYPE(QmlParallelAnimation) class QmlVariantAnimationPrivate; class QmlVariantAnimation : public QmlAbstractAnimation @@ -444,7 +444,7 @@ Q_SIGNALS: void easingChanged(const QString &); void propertiesChanged(const QString &); }; -QML_DECLARE_TYPE(QmlVariantAnimation); +QML_DECLARE_TYPE(QmlVariantAnimation) #endif // QMLANIMATION_H diff --git a/src/declarative/util/qmlbehaviour.cpp b/src/declarative/util/qmlbehaviour.cpp index 354c7e3..077f666 100644 --- a/src/declarative/util/qmlbehaviour.cpp +++ b/src/declarative/util/qmlbehaviour.cpp @@ -47,7 +47,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QmlBehaviour,Behaviour); +QML_DEFINE_TYPE(QmlBehaviour,Behaviour) class QmlBehaviourData : public QObject diff --git a/src/declarative/util/qmlbehaviour.h b/src/declarative/util/qmlbehaviour.h index 7a54d63..584b96d 100644 --- a/src/declarative/util/qmlbehaviour.h +++ b/src/declarative/util/qmlbehaviour.h @@ -86,7 +86,7 @@ protected: private Q_SLOTS: void propertyValueChanged(); }; -QML_DECLARE_TYPE(QmlBehaviour); +QML_DECLARE_TYPE(QmlBehaviour) #endif // QMLBEHAVIOUR_H diff --git a/src/declarative/util/qmlbind.cpp b/src/declarative/util/qmlbind.cpp index 59bfd75..b45d07d 100644 --- a/src/declarative/util/qmlbind.cpp +++ b/src/declarative/util/qmlbind.cpp @@ -63,7 +63,7 @@ public: QmlNullableValue value; }; -QML_DEFINE_TYPE(QmlBind,Bind); +QML_DEFINE_TYPE(QmlBind,Bind) /*! \qmlclass Bind QmlBind \brief The Bind element allows arbitrary property bindings to be created. diff --git a/src/declarative/util/qmlbind.h b/src/declarative/util/qmlbind.h index 5576957..9d4ae8d 100644 --- a/src/declarative/util/qmlbind.h +++ b/src/declarative/util/qmlbind.h @@ -81,7 +81,7 @@ public: private: void eval(); }; -QML_DECLARE_TYPE(QmlBind); +QML_DECLARE_TYPE(QmlBind) QT_END_NAMESPACE diff --git a/src/declarative/util/qmlconnection.cpp b/src/declarative/util/qmlconnection.cpp index 8f6c908..6c7b158 100644 --- a/src/declarative/util/qmlconnection.cpp +++ b/src/declarative/util/qmlconnection.cpp @@ -294,6 +294,6 @@ void QmlConnection::setSignal(const QString& sig) connectIfValid(); } -QML_DEFINE_TYPE(QmlConnection,Connection); +QML_DEFINE_TYPE(QmlConnection,Connection) QT_END_NAMESPACE diff --git a/src/declarative/util/qmlconnection.h b/src/declarative/util/qmlconnection.h index c943092..c776dac 100644 --- a/src/declarative/util/qmlconnection.h +++ b/src/declarative/util/qmlconnection.h @@ -81,7 +81,7 @@ private: void connectIfValid(); void componentComplete(); }; -QML_DECLARE_TYPE(QmlConnection); +QML_DECLARE_TYPE(QmlConnection) #endif diff --git a/src/declarative/util/qmldatetimeformatter.cpp b/src/declarative/util/qmldatetimeformatter.cpp index 94b87ee..ad0e473 100644 --- a/src/declarative/util/qmldatetimeformatter.cpp +++ b/src/declarative/util/qmldatetimeformatter.cpp @@ -364,5 +364,5 @@ void QmlDateTimeFormatter::classComplete() d->updateText(); } -QML_DEFINE_TYPE(QmlDateTimeFormatter, DateTimeFormatter); +QML_DEFINE_TYPE(QmlDateTimeFormatter, DateTimeFormatter) QT_END_NAMESPACE diff --git a/src/declarative/util/qmldatetimeformatter.h b/src/declarative/util/qmldatetimeformatter.h index 3421f8c..5d11dab 100644 --- a/src/declarative/util/qmldatetimeformatter.h +++ b/src/declarative/util/qmldatetimeformatter.h @@ -107,7 +107,7 @@ private: Q_DECLARE_PRIVATE(QmlDateTimeFormatter) }; -QML_DECLARE_TYPE(QmlDateTimeFormatter); +QML_DECLARE_TYPE(QmlDateTimeFormatter) QT_END_NAMESPACE diff --git a/src/declarative/util/qmlfollow.cpp b/src/declarative/util/qmlfollow.cpp index 8e5ae69..d1ecac4 100644 --- a/src/declarative/util/qmlfollow.cpp +++ b/src/declarative/util/qmlfollow.cpp @@ -47,7 +47,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QmlFollow,Follow); +QML_DEFINE_TYPE(QmlFollow,Follow) class QmlFollowPrivate : public QObjectPrivate { diff --git a/src/declarative/util/qmlfollow.h b/src/declarative/util/qmlfollow.h index fa0bff8..1c7275d 100644 --- a/src/declarative/util/qmlfollow.h +++ b/src/declarative/util/qmlfollow.h @@ -92,7 +92,7 @@ Q_SIGNALS: void valueChanged(qreal); }; -QML_DECLARE_TYPE(QmlFollow); +QML_DECLARE_TYPE(QmlFollow) #endif // QFXFOLLOW_H diff --git a/src/declarative/util/qmlfont.cpp b/src/declarative/util/qmlfont.cpp index 9f3225a..c537a83 100644 --- a/src/declarative/util/qmlfont.cpp +++ b/src/declarative/util/qmlfont.cpp @@ -51,7 +51,7 @@ public: QFont font; }; -QML_DEFINE_TYPE(QmlFont,Font); +QML_DEFINE_TYPE(QmlFont,Font) /*! \internal diff --git a/src/declarative/util/qmlfont.h b/src/declarative/util/qmlfont.h index 3a21c34..1fee6cb 100644 --- a/src/declarative/util/qmlfont.h +++ b/src/declarative/util/qmlfont.h @@ -83,7 +83,7 @@ public: Q_SIGNALS: void updated(); }; -QML_DECLARE_TYPE(QmlFont); +QML_DECLARE_TYPE(QmlFont) QT_END_NAMESPACE diff --git a/src/declarative/util/qmllistmodel.cpp b/src/declarative/util/qmllistmodel.cpp index 80eb9c3..5dc3fda 100644 --- a/src/declarative/util/qmllistmodel.cpp +++ b/src/declarative/util/qmllistmodel.cpp @@ -519,16 +519,16 @@ void ListModelParser::setCustomData(QObject *obj, const QByteArray &d) } } -QML_DECLARE_TYPE(ListModel); -QML_DEFINE_CUSTOM_TYPE(ListModel, ListModel, ListModelParser); +QML_DECLARE_TYPE(ListModel) +QML_DEFINE_CUSTOM_TYPE(ListModel, ListModel, ListModelParser) // ### FIXME class ListElement : public QObject { Q_OBJECT }; -QML_DECLARE_TYPE(ListElement); -QML_DEFINE_TYPE(ListElement,ListElement); +QML_DECLARE_TYPE(ListElement) +QML_DEFINE_TYPE(ListElement,ListElement) static void dump(ModelNode *node, int ind) { diff --git a/src/declarative/util/qmlpackage.cpp b/src/declarative/util/qmlpackage.cpp index 107bcdb..e527c1f 100644 --- a/src/declarative/util/qmlpackage.cpp +++ b/src/declarative/util/qmlpackage.cpp @@ -147,7 +147,7 @@ QmlPackageAttached *QmlPackage::qmlAttachedProperties(QObject *o) return new QmlPackageAttached(o); } -QML_DEFINE_TYPE(QmlPackage, Package); +QML_DEFINE_TYPE(QmlPackage, Package) QT_END_NAMESPACE #include "qmlpackage.moc" diff --git a/src/declarative/util/qmlpackage.h b/src/declarative/util/qmlpackage.h index f4167fd..763ba6a 100644 --- a/src/declarative/util/qmlpackage.h +++ b/src/declarative/util/qmlpackage.h @@ -77,7 +77,7 @@ public: static QmlPackageAttached *qmlAttachedProperties(QObject *); }; -QML_DECLARE_TYPE(QmlPackage); +QML_DECLARE_TYPE(QmlPackage) #endif // QMLPACKAGE_H diff --git a/src/declarative/util/qmlscript.cpp b/src/declarative/util/qmlscript.cpp index d6d610a..45370e2 100644 --- a/src/declarative/util/qmlscript.cpp +++ b/src/declarative/util/qmlscript.cpp @@ -101,7 +101,7 @@ public: avoided. */ -QML_DEFINE_TYPE(QmlScript,Script); +QML_DEFINE_TYPE(QmlScript,Script) QmlScript::QmlScript(QObject *parent) : QObject(*(new QmlScriptPrivate), parent) { } diff --git a/src/declarative/util/qmlscript.h b/src/declarative/util/qmlscript.h index b739fd7..35a935b 100644 --- a/src/declarative/util/qmlscript.h +++ b/src/declarative/util/qmlscript.h @@ -73,7 +73,7 @@ public: private Q_SLOTS: void replyFinished(); }; -QML_DECLARE_TYPE(QmlScript); +QML_DECLARE_TYPE(QmlScript) QT_END_NAMESPACE QT_END_HEADER diff --git a/src/declarative/util/qmlsetproperties.cpp b/src/declarative/util/qmlsetproperties.cpp index c986864..cb97ed9 100644 --- a/src/declarative/util/qmlsetproperties.cpp +++ b/src/declarative/util/qmlsetproperties.cpp @@ -357,6 +357,6 @@ QmlSetProperties::ActionList QmlSetProperties::actions() return list; } -QML_DEFINE_CUSTOM_TYPE(QmlSetProperties,SetProperties,QmlSetPropertiesParser); +QML_DEFINE_CUSTOM_TYPE(QmlSetProperties,SetProperties,QmlSetPropertiesParser) QT_END_NAMESPACE diff --git a/src/declarative/util/qmlsetproperties.h b/src/declarative/util/qmlsetproperties.h index 24ad99a..6dc5993 100644 --- a/src/declarative/util/qmlsetproperties.h +++ b/src/declarative/util/qmlsetproperties.h @@ -71,7 +71,7 @@ public: virtual ActionList actions(); }; -QML_DECLARE_TYPE(QmlSetProperties); +QML_DECLARE_TYPE(QmlSetProperties) QT_END_NAMESPACE diff --git a/src/declarative/util/qmlstate.cpp b/src/declarative/util/qmlstate.cpp index 6261003..abe8301 100644 --- a/src/declarative/util/qmlstate.cpp +++ b/src/declarative/util/qmlstate.cpp @@ -104,7 +104,7 @@ QmlStateOperation::QmlStateOperation(QObjectPrivate &dd, QObject *parent) \sa {states-transitions}{States and Transitions} */ -QML_DEFINE_TYPE(QmlState,State); +QML_DEFINE_TYPE(QmlState,State) QmlState::QmlState(QObject *parent) : QObject(*(new QmlStatePrivate), parent) { @@ -463,7 +463,7 @@ void QmlState::apply(QmlStateGroup *group, QmlTransition *trans, QmlState *rever d->applyBindings(); //### merge into above foreach? } -QML_DEFINE_TYPE(QmlStateOperation,StateOperation); +QML_DEFINE_TYPE(QmlStateOperation,StateOperation) QmlStateOperation::ActionList QmlStateOperation::actions() { return ActionList(); diff --git a/src/declarative/util/qmlstate.h b/src/declarative/util/qmlstate.h index aa8871f..39a9f19 100644 --- a/src/declarative/util/qmlstate.h +++ b/src/declarative/util/qmlstate.h @@ -116,7 +116,7 @@ public: protected: QmlStateOperation(QObjectPrivate &dd, QObject *parent = 0); }; -QML_DECLARE_TYPE(QmlStateOperation); +QML_DECLARE_TYPE(QmlStateOperation) typedef QmlStateOperation::ActionList QmlStateActions; @@ -166,7 +166,7 @@ private: Q_DISABLE_COPY(QmlState) friend class QmlTransitionPrivate; }; -QML_DECLARE_TYPE(QmlState); +QML_DECLARE_TYPE(QmlState) QT_END_NAMESPACE diff --git a/src/declarative/util/qmlstategroup.cpp b/src/declarative/util/qmlstategroup.cpp index cabef63..57ccd37 100644 --- a/src/declarative/util/qmlstategroup.cpp +++ b/src/declarative/util/qmlstategroup.cpp @@ -49,7 +49,7 @@ QT_BEGIN_NAMESPACE DEFINE_BOOL_CONFIG_OPTION(stateChangeDebug, STATECHANGE_DEBUG); -QML_DEFINE_TYPE(QmlStateGroup,StateGroup); +QML_DEFINE_TYPE(QmlStateGroup,StateGroup) class QmlStateGroupPrivate : public QObjectPrivate { diff --git a/src/declarative/util/qmlstategroup.h b/src/declarative/util/qmlstategroup.h index cca1015..ac9b8c3 100644 --- a/src/declarative/util/qmlstategroup.h +++ b/src/declarative/util/qmlstategroup.h @@ -85,7 +85,7 @@ private: friend class QmlState; void updateAutoState(); }; -QML_DECLARE_TYPE(QmlStateGroup); +QML_DECLARE_TYPE(QmlStateGroup) #endif // QMLSTATEGROUP_H diff --git a/src/declarative/util/qmlstateoperations.cpp b/src/declarative/util/qmlstateoperations.cpp index 01f9cdd..02b54f8 100644 --- a/src/declarative/util/qmlstateoperations.cpp +++ b/src/declarative/util/qmlstateoperations.cpp @@ -64,7 +64,7 @@ public: \brief The ParentChange element allows you to reparent an object in a state. */ -QML_DEFINE_TYPE(QmlParentChange,ParentChange); +QML_DEFINE_TYPE(QmlParentChange,ParentChange) QmlParentChange::QmlParentChange(QObject *parent) : QmlStateOperation(*(new QmlParentChangePrivate), parent) { @@ -147,7 +147,7 @@ public: \qmlclass RunScript QmlRunScript \brief The RunScript element allows you to run a script in a state. */ -QML_DEFINE_TYPE(QmlRunScript,RunScript); +QML_DEFINE_TYPE(QmlRunScript,RunScript) QmlRunScript::QmlRunScript(QObject *parent) : QmlStateOperation(*(new QmlRunScriptPrivate), parent) { @@ -268,7 +268,7 @@ public: QString binding; }; -QML_DEFINE_TYPE(QmlSetProperty,SetProperty); +QML_DEFINE_TYPE(QmlSetProperty,SetProperty) QmlSetProperty::QmlSetProperty(QObject *parent) : QmlStateOperation(*(new QmlSetPropertyPrivate), parent) diff --git a/src/declarative/util/qmlstateoperations.h b/src/declarative/util/qmlstateoperations.h index 720c639..ef36ab2 100644 --- a/src/declarative/util/qmlstateoperations.h +++ b/src/declarative/util/qmlstateoperations.h @@ -70,7 +70,7 @@ public: virtual ActionList actions(); }; -QML_DECLARE_TYPE(QmlParentChange); +QML_DECLARE_TYPE(QmlParentChange) class QmlRunScriptPrivate; class Q_DECLARATIVE_EXPORT QmlRunScript : public QmlStateOperation, public ActionEvent @@ -95,7 +95,7 @@ public: virtual void execute(); }; -QML_DECLARE_TYPE(QmlRunScript); +QML_DECLARE_TYPE(QmlRunScript) class QmlSetPropertyPrivate; class Q_DECLARATIVE_EXPORT QmlSetProperty : public QmlStateOperation @@ -123,7 +123,7 @@ public: virtual ActionList actions(); }; -QML_DECLARE_TYPE(QmlSetProperty); +QML_DECLARE_TYPE(QmlSetProperty) QT_END_NAMESPACE diff --git a/src/declarative/util/qmltransition.cpp b/src/declarative/util/qmltransition.cpp index 26ed8b1..5931075 100644 --- a/src/declarative/util/qmltransition.cpp +++ b/src/declarative/util/qmltransition.cpp @@ -135,7 +135,7 @@ void ParallelAnimationWrapper::updateState(QAbstractAnimation::State oldState, Q } -QML_DEFINE_TYPE(QmlTransition,Transition); +QML_DEFINE_TYPE(QmlTransition,Transition) QmlTransition::QmlTransition(QObject *parent) : QObject(*(new QmlTransitionPrivate), parent) { diff --git a/src/declarative/util/qmltransition.h b/src/declarative/util/qmltransition.h index 646746e..4462b4c 100644 --- a/src/declarative/util/qmltransition.h +++ b/src/declarative/util/qmltransition.h @@ -88,7 +88,7 @@ public: void setReversed(bool r); void stop(); }; -QML_DECLARE_TYPE(QmlTransition); +QML_DECLARE_TYPE(QmlTransition) QT_END_NAMESPACE diff --git a/src/declarative/widgets/graphicslayouts.cpp b/src/declarative/widgets/graphicslayouts.cpp index d6c4ac2..21acbcd 100644 --- a/src/declarative/widgets/graphicslayouts.cpp +++ b/src/declarative/widgets/graphicslayouts.cpp @@ -89,7 +89,7 @@ private: Qt::Alignment _alignment; }; -QML_DEFINE_TYPE(QGraphicsLinearLayoutStretchItemObject,QGraphicsLinearLayoutStretchItem); +QML_DEFINE_TYPE(QGraphicsLinearLayoutStretchItemObject,QGraphicsLinearLayoutStretchItem) QGraphicsLinearLayoutStretchItemObject::QGraphicsLinearLayoutStretchItemObject(QObject *parent) : QObject(parent) @@ -103,7 +103,7 @@ QSizeF QGraphicsLinearLayoutStretchItemObject::sizeHint(Qt::SizeHint which, cons return QSizeF(); } -QML_DEFINE_TYPE(QGraphicsLinearLayoutObject,QGraphicsLinearLayout); +QML_DEFINE_TYPE(QGraphicsLinearLayoutObject,QGraphicsLinearLayout) QGraphicsLinearLayoutObject::QGraphicsLinearLayoutObject(QObject *parent) : QObject(parent), _children(this) @@ -246,7 +246,7 @@ private: Qt::Alignment _alignment; }; -QML_DEFINE_TYPE(QGraphicsGridLayoutObject,QGraphicsGridLayout); +QML_DEFINE_TYPE(QGraphicsGridLayoutObject,QGraphicsGridLayout) QGraphicsGridLayoutObject::QGraphicsGridLayoutObject(QObject *parent) diff --git a/src/declarative/widgets/graphicslayouts.h b/src/declarative/widgets/graphicslayouts.h index e9930f1..303f749 100644 --- a/src/declarative/widgets/graphicslayouts.h +++ b/src/declarative/widgets/graphicslayouts.h @@ -52,8 +52,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) -QML_DECLARE_INTERFACE(QGraphicsLayoutItem); -QML_DECLARE_INTERFACE(QGraphicsLayout); +QML_DECLARE_INTERFACE(QGraphicsLayoutItem) +QML_DECLARE_INTERFACE(QGraphicsLayout) class QGraphicsLinearLayoutStretchItemObject : public QObject, public QGraphicsLayoutItem { @@ -64,7 +64,7 @@ public: virtual QSizeF sizeHint(Qt::SizeHint, const QSizeF &) const; }; -QML_DECLARE_TYPE(QGraphicsLinearLayoutStretchItemObject); +QML_DECLARE_TYPE(QGraphicsLinearLayoutStretchItemObject) //TODO: // -content margins @@ -120,7 +120,7 @@ private: ChildList _children; }; -QML_DECLARE_TYPE(QGraphicsLinearLayoutObject); +QML_DECLARE_TYPE(QGraphicsLinearLayoutObject) //TODO: // -content margins @@ -181,7 +181,7 @@ private: ChildList _children; }; -QML_DECLARE_TYPE(QGraphicsGridLayoutObject); +QML_DECLARE_TYPE(QGraphicsGridLayoutObject) #endif // GRAPHICSLAYOUTS_H diff --git a/src/declarative/widgets/graphicswidgets.h b/src/declarative/widgets/graphicswidgets.h index cec15b6..e29f1d6 100644 --- a/src/declarative/widgets/graphicswidgets.h +++ b/src/declarative/widgets/graphicswidgets.h @@ -50,10 +50,10 @@ QT_BEGIN_NAMESPACE -QML_DECLARE_TYPE(QGraphicsView); -QML_DECLARE_TYPE_HASMETATYPE(QGraphicsScene); -QML_DECLARE_TYPE(QGraphicsWidget); -QML_DECLARE_INTERFACE_HASMETATYPE(QGraphicsItem); +QML_DECLARE_TYPE(QGraphicsView) +QML_DECLARE_TYPE_HASMETATYPE(QGraphicsScene) +QML_DECLARE_TYPE(QGraphicsWidget) +QML_DECLARE_INTERFACE_HASMETATYPE(QGraphicsItem) QT_END_NAMESPACE -- cgit v0.12 From ba2f5f0c0d0ae594e391e95f7b05d0d29348e1e5 Mon Sep 17 00:00:00 2001 From: Roberto Raggi Date: Tue, 26 May 2009 10:33:39 +0200 Subject: Create a new TextWriter when rewriting the CSS literals. --- src/declarative/qml/qmlscriptparser.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index fde2771..b99f0ff 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -1,4 +1,3 @@ - #include "qmlscriptparser_p.h" #include "qmlparser_p.h" @@ -27,16 +26,18 @@ namespace { class RewriteNumericLiterals: protected AST::Visitor { unsigned _position; - TextWriter _writer; + TextWriter *_writer; public: QString operator()(QString code, unsigned position, AST::Node *node) { + TextWriter w; + _writer = &w; _position = position; AST::Node::acceptChild(node, this); - _writer.write(&code); + w.write(&code); return code; } @@ -54,10 +55,10 @@ protected: pre += QChar(QLatin1Char(suffixSpell[0])).toUpper(); pre += QLatin1String(&suffixSpell[1]); pre += QLatin1Char('('); - _writer.replace(node->literalToken.begin() - _position, 0, pre); - _writer.replace(node->literalToken.end() - _position - suffixLength, - suffixLength, - QLatin1String(")")); + _writer->replace(node->literalToken.begin() - _position, 0, pre); + _writer->replace(node->literalToken.end() - _position - suffixLength, + suffixLength, + QLatin1String(")")); } return false; -- cgit v0.12 From 73cbad1189172eba4cb824f264fa1e17d17939f2 Mon Sep 17 00:00:00 2001 From: Roberto Raggi Date: Tue, 26 May 2009 10:34:57 +0200 Subject: Added missing copyright headers. --- src/declarative/qml/qmlscriptparser.cpp | 41 +++++++++++++++++++++++++++++ src/declarative/qml/qmlscriptparser_p.h | 40 ++++++++++++++++++++++++++++ src/declarative/qml/rewriter/rewriter.cpp | 41 +++++++++++++++++++++++++++++ src/declarative/qml/rewriter/rewriter_p.h | 41 +++++++++++++++++++++++++++++ src/declarative/qml/rewriter/textwriter.cpp | 41 +++++++++++++++++++++++++++++ src/declarative/qml/rewriter/textwriter_p.h | 41 +++++++++++++++++++++++++++++ 6 files changed, 245 insertions(+) diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index b99f0ff..5c5b25e 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "qmlscriptparser_p.h" #include "qmlparser_p.h" diff --git a/src/declarative/qml/qmlscriptparser_p.h b/src/declarative/qml/qmlscriptparser_p.h index 8a5466f..a9ffa47 100644 --- a/src/declarative/qml/qmlscriptparser_p.h +++ b/src/declarative/qml/qmlscriptparser_p.h @@ -1,3 +1,43 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ #ifndef QMLSCRIPTPARSER_P_H #define QMLSCRIPTPARSER_P_H diff --git a/src/declarative/qml/rewriter/rewriter.cpp b/src/declarative/qml/rewriter/rewriter.cpp index ec504fa..fce4fdf 100644 --- a/src/declarative/qml/rewriter/rewriter.cpp +++ b/src/declarative/qml/rewriter/rewriter.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "rewriter_p.h" #include "javascriptast_p.h" diff --git a/src/declarative/qml/rewriter/rewriter_p.h b/src/declarative/qml/rewriter/rewriter_p.h index 892c006..287df7a 100644 --- a/src/declarative/qml/rewriter/rewriter_p.h +++ b/src/declarative/qml/rewriter/rewriter_p.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef REWRITER_H #define REWRITER_H diff --git a/src/declarative/qml/rewriter/textwriter.cpp b/src/declarative/qml/rewriter/textwriter.cpp index d56c9a1..21122ff 100644 --- a/src/declarative/qml/rewriter/textwriter.cpp +++ b/src/declarative/qml/rewriter/textwriter.cpp @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #include "textwriter_p.h" QT_BEGIN_NAMESPACE diff --git a/src/declarative/qml/rewriter/textwriter_p.h b/src/declarative/qml/rewriter/textwriter_p.h index 52d18d3..07e8f15 100644 --- a/src/declarative/qml/rewriter/textwriter_p.h +++ b/src/declarative/qml/rewriter/textwriter_p.h @@ -1,3 +1,44 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + #ifndef TEXTWRITER_H #define TEXTWRITER_H -- cgit v0.12 From f98c79c40892ed5c2047c6bd15e36a2e9d9583ba Mon Sep 17 00:00:00 2001 From: Roberto Raggi Date: Tue, 26 May 2009 10:41:34 +0200 Subject: Made the suffix for CSS literals case insensitve. --- src/declarative/qml/parser/javascriptlexer.cpp | 37 +++++++++++++++----------- 1 file changed, 21 insertions(+), 16 deletions(-) diff --git a/src/declarative/qml/parser/javascriptlexer.cpp b/src/declarative/qml/parser/javascriptlexer.cpp index fda6ad2..ea36a7a 100644 --- a/src/declarative/qml/parser/javascriptlexer.cpp +++ b/src/declarative/qml/parser/javascriptlexer.cpp @@ -758,49 +758,54 @@ int Lexer::lex() flags = noSuffix; - if (current == 'e' && next1 == 'm') { + const ushort c = QChar::toLower(current); + const ushort n1 = QChar::toLower(next1); + const ushort n2 = QChar::toLower(next2); + const ushort n3 = QChar::toLower(next3); + + if (c == 'e' && n1 == 'm') { flags = emSuffix; shift(2); - } else if (current == 'e' && next1 == 'x') { + } else if (c == 'e' && n1 == 'x') { flags = exSuffix; shift(2); - } else if (current == 'p' && next1 == 'x') { + } else if (c == 'p' && n1 == 'x') { flags = pxSuffix; shift(2); - } else if (current == 'c' && next1 == 'm') { + } else if (c == 'c' && n1 == 'm') { flags = cmSuffix; shift(2); - } else if (current == 'm' && next1 == 'm') { + } else if (c == 'm' && n1 == 'm') { flags = mmSuffix; shift(2); - } else if (current == 'i' && next1 == 'n') { + } else if (c == 'i' && n1 == 'n') { flags = inSuffix; shift(2); - } else if (current == 'p' && next1 == 't') { + } else if (c == 'p' && n1 == 't') { flags = ptSuffix; shift(2); - } else if (current == 'p' && next1 == 'c') { + } else if (c == 'p' && n1 == 'c') { flags = pcSuffix; shift(1); - } else if (current == 'd' && next1 == 'e' && next2 == 'g') { + } else if (c == 'd' && n1 == 'e' && n2 == 'g') { flags = degSuffix; shift(3); - } else if (current == 'r' && next1 == 'a' && next2 == 'd') { + } else if (c == 'r' && n1 == 'a' && n2 == 'd') { flags = radSuffix; shift(3); - } else if (current == 'g' && next1 == 'r' && next2 == 'a' && next3 == 'd') { + } else if (c == 'g' && n1 == 'r' && n2 == 'a' && n3 == 'd') { flags = gradSuffix; shift(4); - } else if (current == 'm' && next1 == 's') { + } else if (c == 'm' && n1 == 's') { flags = msSuffix; shift(2); - } else if (current == 's') { + } else if (c == 's') { flags = sSuffix; shift(1); - } else if (current == 'h' && next1 == 'z') { + } else if (c == 'h' && n1 == 'z') { flags = hzSuffix; shift(2); - } else if (current == 'k' && next1 == 'h' && next2 == 'z') { + } else if (c == 'k' && n1 == 'h' && n2 == 'z') { flags = khzSuffix; shift(3); } @@ -811,7 +816,7 @@ int Lexer::lex() && isIdentLetter(current)) { state = Bad; err = IllegalIdentifier; - errmsg = QLatin1String("Identifier cannot start with numeric literal `%1'"); + errmsg = QLatin1String("Identifier cannot start with numeric literal"); } // terminate string -- cgit v0.12 From 86598234d8c055fe8dbc474d292619d453cc9f56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Tue, 26 May 2009 11:03:24 +0200 Subject: BT: Google suggest example not launching from the Qt Demo app. The example was installed in the wrong directory. Task-number: 254452 Reviewed-by: Kim --- examples/network/googlesuggest/googlesuggest.pro | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/network/googlesuggest/googlesuggest.pro b/examples/network/googlesuggest/googlesuggest.pro index afd600f..33b79de 100644 --- a/examples/network/googlesuggest/googlesuggest.pro +++ b/examples/network/googlesuggest/googlesuggest.pro @@ -3,7 +3,7 @@ SOURCES = main.cpp searchbox.cpp googlesuggest.cpp HEADERS = searchbox.h googlesuggest.h # install -target.path = $$[QT_INSTALL_EXAMPLES]/webkit/googlesuggest +target.path = $$[QT_INSTALL_EXAMPLES]/network/googlesuggest sources.files = $$SOURCES $$HEADERS *.pro -sources.path = $$[QT_INSTALL_EXAMPLES]/webkit/googlesuggest +sources.path = $$[QT_INSTALL_EXAMPLES]/network/googlesuggest INSTALLS += target sources -- cgit v0.12 From a1730a096a2ca44ef2fc1530a141ecbb9b3157ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Tue, 26 May 2009 11:35:00 +0200 Subject: Add qmldebugger sub dir to the pro file. --- tools/tools.pro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/tools.pro b/tools/tools.pro index 7493aec..7caef83 100644 --- a/tools/tools.pro +++ b/tools/tools.pro @@ -24,7 +24,7 @@ mac { embedded:SUBDIRS += kmap2qmap -contains(QT_CONFIG, declarative):SUBDIRS += qmlviewer +contains(QT_CONFIG, declarative):SUBDIRS += qmlviewer qmldebugger contains(QT_CONFIG, dbus):SUBDIRS += qdbus !wince*:contains(QT_CONFIG, xmlpatterns): SUBDIRS += xmlpatterns embedded: SUBDIRS += makeqpf -- cgit v0.12 From 7733f81af953a1ddaa7debc12bb29b101c5bc101 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 26 May 2009 10:40:26 +0200 Subject: Fixed keywords signals and slots to Q_SIGNALS and Q_SLOTS --- src/corelib/io/qfilesystemwatcher.cpp | 2 +- src/corelib/io/qnoncontiguousbytedevice_p.h | 2 +- src/corelib/io/qtextstream.cpp | 2 +- src/corelib/kernel/qtimer.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/corelib/io/qfilesystemwatcher.cpp b/src/corelib/io/qfilesystemwatcher.cpp index e073a08..65cfb71 100644 --- a/src/corelib/io/qfilesystemwatcher.cpp +++ b/src/corelib/io/qfilesystemwatcher.cpp @@ -118,7 +118,7 @@ public: void stop(); -private slots: +private Q_SLOTS: void timeout(); }; diff --git a/src/corelib/io/qnoncontiguousbytedevice_p.h b/src/corelib/io/qnoncontiguousbytedevice_p.h index 2a7e40b..acfc6eb 100644 --- a/src/corelib/io/qnoncontiguousbytedevice_p.h +++ b/src/corelib/io/qnoncontiguousbytedevice_p.h @@ -77,7 +77,7 @@ protected: virtual ~QNonContiguousByteDevice(); bool resetDisabled; -signals: +Q_SIGNALS: void readyRead(); void readProgress(qint64 current, qint64 total); }; diff --git a/src/corelib/io/qtextstream.cpp b/src/corelib/io/qtextstream.cpp index 4563e84..7c925f1 100644 --- a/src/corelib/io/qtextstream.cpp +++ b/src/corelib/io/qtextstream.cpp @@ -333,7 +333,7 @@ public: this->stream = stream; } -public slots: +public Q_SLOTS: inline void flushStream() { stream->flush(); } private: diff --git a/src/corelib/kernel/qtimer.cpp b/src/corelib/kernel/qtimer.cpp index 4b3feb0..08821d4 100644 --- a/src/corelib/kernel/qtimer.cpp +++ b/src/corelib/kernel/qtimer.cpp @@ -269,7 +269,7 @@ class QSingleShotTimer : public QObject public: ~QSingleShotTimer(); QSingleShotTimer(int msec, QObject *r, const char * m); -signals: +Q_SIGNALS: void timeout(); protected: void timerEvent(QTimerEvent *); -- cgit v0.12 From 5345306c9a0a3b10dbf640253b8b2287c762b081 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 26 May 2009 11:36:16 +0200 Subject: Fixed a bug in animation when you set a start value that doesn't have the same type as the property For example, if you set a start value of 0 (integer) for a qreal animation, it would not work. Reviewed-by: janarve --- src/corelib/animation/qvariantanimation.cpp | 10 ++- .../qpropertyanimation/tst_qpropertyanimation.cpp | 77 ++++++++++++++++------ 2 files changed, 65 insertions(+), 22 deletions(-) diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp index 4542a86..239add9 100644 --- a/src/corelib/animation/qvariantanimation.cpp +++ b/src/corelib/animation/qvariantanimation.cpp @@ -179,10 +179,14 @@ void QVariantAnimationPrivate::convertValues(int t) //this ensures that all the keyValues are of type t for (int i = 0; i < keyValues.count(); ++i) { QVariantAnimation::KeyValue &pair = keyValues[i]; - if (pair.second.userType() != t) - pair.second.convert(static_cast(t)); + pair.second.convert(static_cast(t)); } - interpolator = 0; // if the type changed we need to update the interpolator + //we also need update to the current interval if needed + currentInterval.start.second.convert(static_cast(t)); + currentInterval.end.second.convert(static_cast(t)); + + //... and the interpolator + interpolator = 0; } /*! diff --git a/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp b/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp index 7e910d4..0aeac91 100644 --- a/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp +++ b/tests/auto/qpropertyanimation/tst_qpropertyanimation.cpp @@ -63,6 +63,18 @@ protected: } }; +class MyObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(qreal x READ x WRITE setX) +public: + MyObject() : m_x(0) { } + qreal x() const { return m_x; } + void setX(qreal x) { m_x = x; } +private: + qreal m_x; +}; + class tst_QPropertyAnimation : public QObject { Q_OBJECT @@ -92,6 +104,7 @@ private slots: void startWithoutStartValue(); void playForwardBackward(); void interpolated(); + void setStartEndValues_data(); void setStartEndValues(); void zeroDurationStart(); void operationsInStates_data(); @@ -283,7 +296,7 @@ void tst_QPropertyAnimation::statesAndSignals() void tst_QPropertyAnimation::deletion1() { QObject *object = new QWidget; - QPointer anim = new QPropertyAnimation(object,"minimumWidth"); + QPointer anim = new QPropertyAnimation(object, "minimumWidth"); //test that the animation is deleted correctly depending of the deletion flag passed in start() QSignalSpy runningSpy(anim, SIGNAL(stateChanged(QAbstractAnimation::State, QAbstractAnimation::State))); @@ -686,52 +699,78 @@ void tst_QPropertyAnimation::interpolated() } } +Q_DECLARE_METATYPE(QVariant) + +void tst_QPropertyAnimation::setStartEndValues_data() +{ + QTest::addColumn("propertyName"); + QTest::addColumn("initialValue"); + QTest::addColumn("startValue"); + QTest::addColumn("endValue"); + + QTest::newRow("dynamic property") << QByteArray("ole") << QVariant(42) << QVariant(0) << QVariant(10); + QTest::newRow("real property, with unmatching types") << QByteArray("x") << QVariant(42.) << QVariant(0) << QVariant(10.); +} + void tst_QPropertyAnimation::setStartEndValues() { + MyObject object; + QFETCH(QByteArray, propertyName); + QFETCH(QVariant, initialValue); + QFETCH(QVariant, startValue); + QFETCH(QVariant, endValue); + //this tests the start value, end value and default start value - QObject o; - o.setProperty("ole", 42); - QPropertyAnimation anim(&o, "ole"); + object.setProperty(propertyName, initialValue); + QPropertyAnimation anim(&object, propertyName); QVariantAnimation::KeyValues values; QCOMPARE(anim.keyValues(), values); //let's add a start value - anim.setStartValue(0); - values << QVariantAnimation::KeyValue(0, 0); + anim.setStartValue(startValue); + values << QVariantAnimation::KeyValue(0, startValue); QCOMPARE(anim.keyValues(), values); - anim.setEndValue(10); - values << QVariantAnimation::KeyValue(1, 10); + anim.setEndValue(endValue); + values << QVariantAnimation::KeyValue(1, endValue); QCOMPARE(anim.keyValues(), values); //now we can play with objects - QCOMPARE(o.property("ole").toInt(), 42); - QCOMPARE(o.property("ole").toInt(), 42); + QCOMPARE(object.property(propertyName).toDouble(), initialValue.toDouble()); anim.start(); QVERIFY(anim.startValue().isValid()); - QCOMPARE(o.property("ole"), anim.startValue()); + QCOMPARE(object.property(propertyName), anim.startValue()); + anim.setCurrentTime(anim.duration()/2); + QCOMPARE(object.property(propertyName).toDouble(), (startValue.toDouble() + endValue.toDouble())/2 ); //just in the middle of the animation + anim.setCurrentTime(anim.duration()); //we go to the end of the animation + QCOMPARE(anim.state(), QAnimationGroup::Stopped); //it should have stopped + QVERIFY(anim.endValue().isValid()); + QCOMPARE(object.property(propertyName), anim.endValue()); //end of the animations //now we remove the explicit start value and test the implicit one anim.stop(); - o.setProperty("ole", 42); + object.setProperty(propertyName, initialValue); + + //let's reset the start value values.remove(0); - anim.setStartValue(QVariant()); //reset the start value + anim.setStartValue(QVariant()); QCOMPARE(anim.keyValues(), values); QVERIFY(!anim.startValue().isValid()); + anim.start(); - QCOMPARE(o.property("ole").toInt(), 42); + QCOMPARE(object.property(propertyName), initialValue); anim.setCurrentTime(anim.duration()/2); - QCOMPARE(o.property("ole").toInt(), 26); //just in the middle of the animation - anim.setCurrentTime(anim.duration()); + QCOMPARE(object.property(propertyName).toDouble(), (initialValue.toDouble() + endValue.toDouble())/2 ); //just in the middle of the animation + anim.setCurrentTime(anim.duration()); //we go to the end of the animation QCOMPARE(anim.state(), QAnimationGroup::Stopped); //it should have stopped QVERIFY(anim.endValue().isValid()); - QCOMPARE(o.property("ole"), anim.endValue()); //end of the animations + QCOMPARE(object.property(propertyName), anim.endValue()); //end of the animations //now we set back the startValue - anim.setStartValue(5); + anim.setStartValue(startValue); QVERIFY(anim.startValue().isValid()); anim.start(); - QCOMPARE(o.property("ole").toInt(), 5); + QCOMPARE(object.property(propertyName), startValue); } void tst_QPropertyAnimation::zeroDurationStart() -- cgit v0.12 From 72ecfb3eb9b65ed2617942510fa0c9af5075f209 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Tue, 26 May 2009 12:03:13 +0200 Subject: Doc - more screenshots and adding better description Details: Work in progress --- doc/src/designer-manual.qdoc | 28 ++++++++++++++------------- doc/src/images/designer-choosing-form.png | Bin 38078 -> 39080 bytes doc/src/images/rgbController-arrangement.png | Bin 0 -> 10813 bytes 3 files changed, 15 insertions(+), 13 deletions(-) create mode 100644 doc/src/images/rgbController-arrangement.png diff --git a/doc/src/designer-manual.qdoc b/doc/src/designer-manual.qdoc index 03b74e6..77b208b 100644 --- a/doc/src/designer-manual.qdoc +++ b/doc/src/designer-manual.qdoc @@ -235,6 +235,7 @@ \page designer-to-know.html \contentspage {Qt Designer Manual}{Contents} + \title Getting to Know Qt Designer \tableofcontents @@ -408,6 +409,7 @@ \page designer-quick-start.html \contentspage {Qt Designer Manual}{Contents} + \title A Quick Start to Qt Designer Using \QD involves \bold four basic steps: @@ -419,16 +421,14 @@ \o Preview the form \endlist - \omit \image rgbController-screenshot.png - \endomit - Suppose you would like to design a small widget (see screenshot above) - that contains the controls needed to manipulate Red, Green and Blue (RGB) - values -- a type of widget that can be seen everywhere in image - manipulation programs. + Suppose you would like to design a small widget (see screenshot above) that + contains the controls needed to manipulate Red, Green and Blue (RGB) values + -- a type of widget that can be seen everywhere in image manipulation + programs. - \table + \table \row \i \inlineimage designer-choosing-form.png \i \bold{Choosing a Form} @@ -436,20 +436,22 @@ You start by choosing \gui Widget from the \gui{New Form} dialog. \endtable - Then you drag three labels, three spin boxes and three vertical sliders - on to your form. You can roughly arrange them according to how you would - like them to be laid out. + Then you drag three labels, three spin boxes and three vertical sliders on + to your form. To change the label's default text, simply double-click on + it. The screenshot below shows the form after all three labels have been + renamed. + + You can roughly arrange them according to how you would like them to be + laid out. - \omit \table \row \o \inlineimage rgbController-widgetBox.png \o \inlineimage rgbController-arrangement.png \endtable - \endomit To ensure that they are laid out exactly like this in your program, you need to place these widgets into a layout. We will do this in groups of - three. Select the "RED" label. Then, hold down \key Shift while you select + three. Select the "RED" label. Then, hold down \key Ctrl while you select its corresponding spin box and slider. In the \gui{Form} menu, select \gui{Lay Out in a Grid}. diff --git a/doc/src/images/designer-choosing-form.png b/doc/src/images/designer-choosing-form.png index fa6e470..bee4b29 100644 Binary files a/doc/src/images/designer-choosing-form.png and b/doc/src/images/designer-choosing-form.png differ diff --git a/doc/src/images/rgbController-arrangement.png b/doc/src/images/rgbController-arrangement.png new file mode 100644 index 0000000..d9e8bab Binary files /dev/null and b/doc/src/images/rgbController-arrangement.png differ -- cgit v0.12 From 57df8bc3ddd2bc5aaf5c25cf3e311fe56ad50ffb Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 26 May 2009 12:07:01 +0200 Subject: qdoc: Indicate what iterator_categor means for container classes. Task-number: 245501 --- doc/src/qset.qdoc | 9 +++++---- src/corelib/tools/qlistdata.cpp | 6 ++++-- src/corelib/tools/qmap.cpp | 6 ++++-- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/doc/src/qset.qdoc b/doc/src/qset.qdoc index afbedc3..6326219 100644 --- a/doc/src/qset.qdoc +++ b/doc/src/qset.qdoc @@ -685,11 +685,12 @@ */ /*! - \typedef QSet::iterator::iterator_category - \typedef QSet::const_iterator::iterator_category + \typedef QSet::iterator::iterator_category + \typedef QSet::const_iterator::iterator_category - \internal -*/ + Synonyms for \e {std::bidirectional_iterator_tag} indicating + these iterators are bidirectional iterators. + */ /*! \typedef QSet::iterator::difference_type diff --git a/src/corelib/tools/qlistdata.cpp b/src/corelib/tools/qlistdata.cpp index d40b6b6..34a5d80 100644 --- a/src/corelib/tools/qlistdata.cpp +++ b/src/corelib/tools/qlistdata.cpp @@ -1173,7 +1173,8 @@ void **QListData::erase(void **xi) /*! \typedef QList::iterator::iterator_category - \internal + A synonym for \e {std::random_access_iterator_tag} indicating + this iterator is a random access iterator. */ /*! \typedef QList::iterator::difference_type @@ -1432,7 +1433,8 @@ void **QListData::erase(void **xi) /*! \typedef QList::const_iterator::iterator_category - \internal + A synonym for \e {std::random_access_iterator_tag} indicating + this iterator is a random access iterator. */ /*! \typedef QList::const_iterator::difference_type diff --git a/src/corelib/tools/qmap.cpp b/src/corelib/tools/qmap.cpp index 0699400..07df28d 100644 --- a/src/corelib/tools/qmap.cpp +++ b/src/corelib/tools/qmap.cpp @@ -902,7 +902,8 @@ void QMapData::dump() /*! \typedef QMap::iterator::iterator_category - \internal + A synonym for \e {std::bidirectional_iterator_tag} indicating + this iterator is a bidirectional iterator. */ /*! \typedef QMap::iterator::pointer @@ -1123,7 +1124,8 @@ void QMapData::dump() /*! \typedef QMap::const_iterator::iterator_category - \internal + A synonym for \e {std::bidirectional_iterator_tag} indicating + this iterator is a bidirectional iterator. */ /*! \typedef QMap::const_iterator::pointer -- cgit v0.12 From 337ffb38e35ca43e4119ac0634499b226137692e Mon Sep 17 00:00:00 2001 From: David Boddie Date: Tue, 26 May 2009 12:08:45 +0200 Subject: Doc: Removed irrelevant links from the Qt for Windows CE documentation. Reviewed-by: Maurice Kalinowski --- doc/src/topics.qdoc | 2 -- 1 file changed, 2 deletions(-) diff --git a/doc/src/topics.qdoc b/doc/src/topics.qdoc index 301f0d4..6ef3a89 100644 --- a/doc/src/topics.qdoc +++ b/doc/src/topics.qdoc @@ -286,11 +286,9 @@ including ARM, Intel x86, MIPS and SH-4. \o \l {Qt for Windows CE Requirements} \o \l {Installing Qt on Windows CE} \o \l {Windows CE - Introduction to using Qt}{Introduction to using Qt} - \o \l {Qt Examples#Qt for Embedded Linux}{Examples} \endlist \o \list - \o \l {Qt for Embedded Linux Classes}{Classes} \o \l {Windows CE - Using shadow builds}{Using shadow builds} \o \l {Windows CE - Working with Custom SDKs}{Working with Custom SDKs} \endlist -- cgit v0.12 From 678ae4a4226a4dc6f93ea394d8bdd7422dbb503c Mon Sep 17 00:00:00 2001 From: Roberto Raggi Date: Tue, 26 May 2009 12:04:47 +0200 Subject: Don't check the QT_MODULE in the text rewriter, there's no need since it's private code. --- src/declarative/qml/rewriter/rewriter_p.h | 104 ++++++++++++++-------------- src/declarative/qml/rewriter/textwriter_p.h | 50 +++++++------ 2 files changed, 75 insertions(+), 79 deletions(-) diff --git a/src/declarative/qml/rewriter/rewriter_p.h b/src/declarative/qml/rewriter/rewriter_p.h index 287df7a..02b4ee4 100644 --- a/src/declarative/qml/rewriter/rewriter_p.h +++ b/src/declarative/qml/rewriter/rewriter_p.h @@ -51,8 +51,6 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE -QT_MODULE(Declarative) - namespace JavaScript { //////////////////////////////////////////////////////////////////////////////// @@ -60,21 +58,21 @@ namespace JavaScript { //////////////////////////////////////////////////////////////////////////////// class Replacement { - int _offset; - int _length; - QString _text; + int _offset; + int _length; + QString _text; public: - Replacement(int offset = 0, int length = 0, const QString &text = QString()) - : _offset(offset), _length(length), _text(text) - { } + Replacement(int offset = 0, int length = 0, const QString &text = QString()) + : _offset(offset), _length(length), _text(text) + { } - bool isNull() const { return _offset == _length; } - operator bool() const { return ! isNull(); } + bool isNull() const { return _offset == _length; } + operator bool() const { return ! isNull(); } - int offset() const { return _offset; } - int length() const { return _length; } - QString text() const { return _text; } + int offset() const { return _offset; } + int length() const { return _length; } + QString text() const { return _text; } }; @@ -85,64 +83,64 @@ public: class Rewriter: public AST::Visitor { protected: - TextWriter textWriter; + TextWriter textWriter; public: - // - // Token based API - // + // + // Token based API + // - /// Returns the text of the token at the given \a location. - QString textAt(const AST::SourceLocation &location) const; + /// Returns the text of the token at the given \a location. + QString textAt(const AST::SourceLocation &location) const; - QString textAt(const AST::SourceLocation &firstLoc, - const AST::SourceLocation &lastLoc) const; + QString textAt(const AST::SourceLocation &firstLoc, + const AST::SourceLocation &lastLoc) const; - /// Replace the token at \a loc with the given \a text. - void replace(const AST::SourceLocation &loc, const QString &text); + /// Replace the token at \a loc with the given \a text. + void replace(const AST::SourceLocation &loc, const QString &text); - /// Remove the token at the given \a location. - void remove(const AST::SourceLocation &location); + /// Remove the token at the given \a location. + void remove(const AST::SourceLocation &location); - /// Remove all tokens in the range [\a firstLoc, \a lastLoc]. - void remove(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc); + /// Remove all tokens in the range [\a firstLoc, \a lastLoc]. + void remove(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc); - /// Insert \a text before the token at the given \a location. - void insertTextBefore(const AST::SourceLocation &location, const QString &text); + /// Insert \a text before the token at the given \a location. + void insertTextBefore(const AST::SourceLocation &location, const QString &text); - /// Insert \a text after the token at the given \a location. - void insertTextAfter(const AST::SourceLocation &loc, const QString &text); + /// Insert \a text after the token at the given \a location. + void insertTextAfter(const AST::SourceLocation &loc, const QString &text); - void moveTextBefore(const AST::SourceLocation &firstLoc, - const AST::SourceLocation &lastLoc, - const AST::SourceLocation &loc); + void moveTextBefore(const AST::SourceLocation &firstLoc, + const AST::SourceLocation &lastLoc, + const AST::SourceLocation &loc); - void moveTextAfter(const AST::SourceLocation &firstLoc, - const AST::SourceLocation &lastLoc, - const AST::SourceLocation &loc); + void moveTextAfter(const AST::SourceLocation &firstLoc, + const AST::SourceLocation &lastLoc, + const AST::SourceLocation &loc); - // - // low-level offset based API - // - void replace(int offset, int length, const QString &text); - void insertText(int offset, const QString &text); - void removeText(int offset, int length); + // + // low-level offset based API + // + void replace(int offset, int length, const QString &text); + void insertText(int offset, const QString &text); + void removeText(int offset, int length); - /// Visit the given \a node. - void accept(AST::Node *node); + /// Visit the given \a node. + void accept(AST::Node *node); - /// Returns the original unchanged source code. - QString code() const { return _code; } + /// Returns the original unchanged source code. + QString code() const { return _code; } - /// Returns the list of replacements. - QList replacementList() const { return _replacementList; } + /// Returns the list of replacements. + QList replacementList() const { return _replacementList; } protected: - /// \internal - void setCode(const QString &code) { _code = code; } + /// \internal + void setCode(const QString &code) { _code = code; } private: - QString _code; - QList _replacementList; + QString _code; + QList _replacementList; }; } // end of namespace JavaScript diff --git a/src/declarative/qml/rewriter/textwriter_p.h b/src/declarative/qml/rewriter/textwriter_p.h index 07e8f15..57800bf 100644 --- a/src/declarative/qml/rewriter/textwriter_p.h +++ b/src/declarative/qml/rewriter/textwriter_p.h @@ -49,47 +49,45 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE -QT_MODULE(Declarative) - namespace JavaScript { class TextWriter { - QString *string; - QTextCursor *cursor; + QString *string; + QTextCursor *cursor; - struct Replace { - int pos; - int length; - QString replacement; - }; + struct Replace { + int pos; + int length; + QString replacement; + }; - QList replaceList; + QList replaceList; - struct Move { - int pos; - int length; - int to; - }; + struct Move { + int pos; + int length; + int to; + }; - QList moveList; + QList moveList; - bool hasOverlap(int pos, int length); - bool hasMoveInto(int pos, int length); + bool hasOverlap(int pos, int length); + bool hasMoveInto(int pos, int length); - void doReplace(const Replace &replace); - void doMove(const Move &move); + void doReplace(const Replace &replace); + void doMove(const Move &move); - void write_helper(); + void write_helper(); public: - TextWriter(); + TextWriter(); - void replace(int pos, int length, const QString &replacement); - void move(int pos, int length, int to); + void replace(int pos, int length, const QString &replacement); + void move(int pos, int length, int to); - void write(QString *s); - void write(QTextCursor *textCursor); + void write(QString *s); + void write(QTextCursor *textCursor); }; -- cgit v0.12 From 451c2361bca1c4419b25c1c5fe088d3315924fa5 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 26 May 2009 20:17:48 +1000 Subject: Improve error messages --- src/declarative/qml/qmlcompiler.cpp | 182 ++++++++++++++++-------------------- src/declarative/qml/qmlcompiler_p.h | 13 +-- 2 files changed, 87 insertions(+), 108 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 89a1774..c5ffeda 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -194,45 +194,76 @@ bool QmlCompiler::isAttachedProperty(const QByteArray &name) return !name.isEmpty() && name.at(0) >= 'A' && name.at(0) <= 'Z'; } -QmlCompiler::StoreInstructionResult -QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, - QmlInstruction &instr, - const QMetaProperty &prop, - int coreIdx, int primitive, - const QString *string) +#define COMPILE_EXCEPTION2(token, desc) \ + { \ + QString exceptionDescription; \ + QmlError error; \ + error.setUrl(output->url); \ + error.setLine(token->location.start.line); \ + error.setColumn(token->location.start.column); \ + QDebug d(&exceptionDescription); \ + d << desc; \ + error.setDescription(exceptionDescription.trimmed()); \ + exceptions << error; \ + return false; \ + } + +#define COMPILE_EXCEPTION(desc) \ + { \ + QString exceptionDescription; \ + QmlError error; \ + error.setUrl(output->url); \ + error.setLine(obj->location.start.line); \ + error.setColumn(obj->location.start.column); \ + QDebug d(&exceptionDescription); \ + d << desc; \ + error.setDescription(exceptionDescription.trimmed()); \ + exceptions << error; \ + return false; \ + } + +#define COMPILE_CHECK(a) \ + { \ + if (!a) return false; \ + } + +bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, + const QMetaProperty &prop, + int coreIdx, + QmlParser::Value *v) { + QString string = v->value.asScript(); + if (!prop.isWritable()) - return ReadOnly; + COMPILE_EXCEPTION2(v, "Cannot assign literal value to read-only property" << prop.name()); + if (prop.isEnumType()) { int value; if (prop.isFlagType()) { - value = prop.enumerator().keysToValue(string->toLatin1().constData()); + value = prop.enumerator().keysToValue(string.toLatin1().constData()); } else - value = prop.enumerator().keyToValue(string->toLatin1().constData()); + value = prop.enumerator().keyToValue(string.toLatin1().constData()); if (value == -1) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot assign unknown enumeration to property" << prop.name()); instr.type = QmlInstruction::StoreInteger; instr.storeInteger.propertyIndex = coreIdx; instr.storeInteger.value = value; - return Ok; + return true; } int type = prop.type(); switch(type) { case -1: + { instr.type = QmlInstruction::StoreVariant; instr.storeString.propertyIndex = coreIdx; - if (primitive == -1) - primitive = cdata.indexForString(*string); - instr.storeString.value = primitive; - break; + instr.storeString.value = output->indexForString(string); + } break; case QVariant::String: { instr.type = QmlInstruction::StoreString; instr.storeString.propertyIndex = coreIdx; - if (primitive == -1) - primitive = cdata.indexForString(*string); - instr.storeString.value = primitive; + instr.storeString.value = output->indexForString(string); } break; case QVariant::UInt: @@ -240,9 +271,9 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, instr.type = QmlInstruction::StoreInteger; instr.storeInteger.propertyIndex = coreIdx; bool ok; - int value = string->toUInt(&ok); + int value = string.toUInt(&ok); if (!ok) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to unsigned integer"); instr.storeInteger.value = value; } break; @@ -251,9 +282,9 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, instr.type = QmlInstruction::StoreInteger; instr.storeInteger.propertyIndex = coreIdx; bool ok; - int value = string->toInt(&ok); + int value = string.toInt(&ok); if (!ok) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to integer"); instr.storeInteger.value = value; } break; @@ -263,17 +294,17 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, instr.type = QmlInstruction::StoreReal; instr.storeReal.propertyIndex = coreIdx; bool ok; - float value = string->toFloat(&ok); + float value = string.toFloat(&ok); if (!ok) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to real number"); instr.storeReal.value = value; } break; case QVariant::Color: { - QColor c = QmlStringConverters::colorFromString(*string); + QColor c = QmlStringConverters::colorFromString(string); if (!c.isValid()) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to color"); instr.type = QmlInstruction::StoreColor; instr.storeColor.propertyIndex = coreIdx; instr.storeColor.value = c.rgba(); @@ -281,9 +312,9 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, break; case QVariant::Date: { - QDate d = QDate::fromString(*string, Qt::ISODate); + QDate d = QDate::fromString(string, Qt::ISODate); if (!d.isValid()) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to date"); instr.type = QmlInstruction::StoreDate; instr.storeDate.propertyIndex = coreIdx; instr.storeDate.value = d.toJulianDay(); @@ -291,11 +322,11 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, break; case QVariant::Time: { - QTime time = QTime::fromString(*string, Qt::ISODate); + QTime time = QTime::fromString(string, Qt::ISODate); if (!time.isValid()) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to time"); int data[] = { time.hour(), time.minute(), time.second(), time.msec() }; - int index = cdata.indexForInt(data, 4); + int index = output->indexForInt(data, 4); instr.type = QmlInstruction::StoreTime; instr.storeTime.propertyIndex = coreIdx; instr.storeTime.valueIndex = index; @@ -303,15 +334,15 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, break; case QVariant::DateTime: { - QDateTime dateTime = QDateTime::fromString(*string, Qt::ISODate); + QDateTime dateTime = QDateTime::fromString(string, Qt::ISODate); if (!dateTime.isValid()) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to date and time"); int data[] = { dateTime.date().toJulianDay(), dateTime.time().hour(), dateTime.time().minute(), dateTime.time().second(), dateTime.time().msec() }; - int index = cdata.indexForInt(data, 5); + int index = output->indexForInt(data, 5); instr.type = QmlInstruction::StoreDateTime; instr.storeDateTime.propertyIndex = coreIdx; instr.storeDateTime.valueIndex = index; @@ -321,11 +352,11 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, case QVariant::PointF: { bool ok; - QPointF point = QmlStringConverters::pointFFromString(*string, &ok); + QPointF point = QmlStringConverters::pointFFromString(string, &ok); if (!ok) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to point"); float data[] = { point.x(), point.y() }; - int index = cdata.indexForFloat(data, 2); + int index = output->indexForFloat(data, 2); if (type == QVariant::PointF) instr.type = QmlInstruction::StorePointF; else @@ -338,11 +369,11 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, case QVariant::SizeF: { bool ok; - QSizeF size = QmlStringConverters::sizeFFromString(*string, &ok); + QSizeF size = QmlStringConverters::sizeFFromString(string, &ok); if (!ok) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to size"); float data[] = { size.width(), size.height() }; - int index = cdata.indexForFloat(data, 2); + int index = output->indexForFloat(data, 2); if (type == QVariant::SizeF) instr.type = QmlInstruction::StoreSizeF; else @@ -355,12 +386,12 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, case QVariant::RectF: { bool ok; - QRectF rect = QmlStringConverters::rectFFromString(*string, &ok); + QRectF rect = QmlStringConverters::rectFFromString(string, &ok); if (!ok) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to rect"); float data[] = { rect.x(), rect.y(), rect.width(), rect.height() }; - int index = cdata.indexForFloat(data, 4); + int index = output->indexForFloat(data, 4); if (type == QVariant::RectF) instr.type = QmlInstruction::StoreRectF; else @@ -372,9 +403,9 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, case QVariant::Bool: { bool ok; - bool b = QmlStringConverters::boolFromString(*string, &ok); + bool b = QmlStringConverters::boolFromString(string, &ok); if (!ok) - return InvalidData; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to boolean"); instr.type = QmlInstruction::StoreBool; instr.storeBool.propertyIndex = coreIdx; instr.storeBool.value = b; @@ -388,24 +419,22 @@ QmlCompiler::generateStoreInstruction(QmlCompiledData &cdata, QmlMetaType::StringConverter converter = QmlMetaType::customStringConverter(t); if (converter) { - int index = cdata.customTypeData.count(); + int index = output->customTypeData.count(); instr.type = QmlInstruction::AssignCustomType; instr.assignCustomType.propertyIndex = coreIdx; instr.assignCustomType.valueIndex = index; QmlCompiledData::CustomTypeData data; - if (primitive == -1) - primitive = cdata.indexForString(*string); - data.index = primitive; + data.index = output->indexForString(string); data.type = t; - cdata.customTypeData << data; + output->customTypeData << data; break; } } - return UnknownType; + COMPILE_EXCEPTION2(v, "Cannot assign to property" << prop.name() << "of unknown type" << prop.type()); break; } - return Ok; + return true; } void QmlCompiler::reset(QmlCompiledComponent *cc, bool deleteMemory) @@ -424,39 +453,6 @@ void QmlCompiler::reset(QmlCompiledComponent *cc, bool deleteMemory) cc->bytecode.clear(); } -#define COMPILE_EXCEPTION2(token, desc) \ - { \ - QString exceptionDescription; \ - QmlError error; \ - error.setUrl(output->url); \ - error.setLine(token->location.start.line); \ - error.setColumn(token->location.start.column); \ - QDebug d(&exceptionDescription); \ - d << desc; \ - error.setDescription(exceptionDescription.trimmed()); \ - exceptions << error; \ - return false; \ - } - -#define COMPILE_EXCEPTION(desc) \ - { \ - QString exceptionDescription; \ - QmlError error; \ - error.setUrl(output->url); \ - error.setLine(obj->location.start.line); \ - error.setColumn(obj->location.start.column); \ - QDebug d(&exceptionDescription); \ - d << desc; \ - error.setDescription(exceptionDescription.trimmed()); \ - exceptions << error; \ - return false; \ - } - -#define COMPILE_CHECK(a) \ - { \ - if (!a) return false; \ - } - bool QmlCompiler::compile(QmlEngine *engine, QmlCompositeTypeData *unit, QmlCompiledComponent *out) @@ -1226,21 +1222,7 @@ bool QmlCompiler::compilePropertyLiteralAssignment(QmlParser::Property *prop, assign.line = v->location.start.line; if (prop->index != -1) { - QString value = v->primitive(); - StoreInstructionResult r = - generateStoreInstruction(*output, assign, obj->metaObject()->property(prop->index), prop->index, -1, &value); - - if (r == Ok) { - } else if (r == InvalidData) { - //### we are restricted to a rather generic message here. If we can find a way to move - // the exception into generateStoreInstruction we could potentially have better messages. - // (the problem is that both compile and run exceptions can be generated, though) - COMPILE_EXCEPTION2(v, "Cannot assign value" << v->primitive() << "to property" << obj->metaObject()->property(prop->index).name()); - } else if (r == ReadOnly) { - COMPILE_EXCEPTION2(v, "Cannot assign value" << v->primitive() << "to the read-only property" << obj->metaObject()->property(prop->index).name()); - } else { - COMPILE_EXCEPTION2(prop, "Cannot assign value to property" << obj->metaObject()->property(prop->index).name() << "of unknown type"); - } + COMPILE_CHECK(generateStoreInstruction(assign, obj->metaObject()->property(prop->index), prop->index, v)); } else { COMPILE_EXCEPTION2(prop, "Cannot assign value to non-existant property" << prop->name); } diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index 3280866..27c4dd2 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -121,14 +121,6 @@ public: static bool isValidId(const QString &); static bool isAttachedProperty(const QByteArray &); - enum StoreInstructionResult { Ok, UnknownType, InvalidData, ReadOnly }; - static StoreInstructionResult - generateStoreInstruction(QmlCompiledData &data, - QmlInstruction &instr, - const QMetaProperty &prop, - int index, - int primitive, - const QString *string); private: void reset(QmlCompiledComponent *, bool); @@ -163,6 +155,11 @@ private: QmlParser::Value *value, int ctxt); + bool generateStoreInstruction(QmlInstruction &instr, + const QMetaProperty &prop, + int index, + QmlParser::Value *value); + bool compileDynamicMeta(QmlParser::Object *obj); bool compileBinding(const QString &, QmlParser::Property *prop, int ctxt, const QMetaObject *, qint64); -- cgit v0.12 From b5a56055d76992cab6c226c29fed8ac791564728 Mon Sep 17 00:00:00 2001 From: Roberto Raggi Date: Tue, 26 May 2009 12:32:34 +0200 Subject: Added no_ast_rewriter to rewriter.pri. --- src/declarative/qml/rewriter/rewriter.pri | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/declarative/qml/rewriter/rewriter.pri b/src/declarative/qml/rewriter/rewriter.pri index 987e26d..de3c298 100644 --- a/src/declarative/qml/rewriter/rewriter.pri +++ b/src/declarative/qml/rewriter/rewriter.pri @@ -1,4 +1,9 @@ INCLUDEPATH += $$PWD -HEADERS += $$PWD/rewriter_p.h $$PWD/textwriter_p.h -SOURCES += $$PWD/rewriter.cpp $$PWD/textwriter.cpp +HEADERS += $$PWD/textwriter_p.h +SOURCES += $$PWD/textwriter.cpp + +!no_ast_rewriter { + HEADERS += $$PWD/rewriter_p.h + SOURCES += $$PWD/rewriter.cpp +} -- cgit v0.12 From 3037e466ebf21aa4a47a722a1e2ff497690cbef5 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Tue, 26 May 2009 12:31:23 +0200 Subject: Fix a crash in Phonon::EffectWidget When creating a UI based on double types we only assigned the control pointer in certain cases. This would crash because the tooltip did not check for the pointer, but the real issue was that we didnt assign the control in the first place. Task-number: 249710 Reviewed-by: Richard Moe Gustavsen --- src/3rdparty/phonon/phonon/effectwidget.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/3rdparty/phonon/phonon/effectwidget.cpp b/src/3rdparty/phonon/phonon/effectwidget.cpp index da5a51a..d5c6c81 100644 --- a/src/3rdparty/phonon/phonon/effectwidget.cpp +++ b/src/3rdparty/phonon/phonon/effectwidget.cpp @@ -165,6 +165,7 @@ void EffectWidgetPrivate::autogenerateUi() if (minValue == -1. && maxValue == 1.) { //Special case values between -1 and 1.0 to use a slider for improved usability QSlider *slider = new QSlider(Qt::Horizontal, q); + control = slider; slider->setRange(-SLIDER_RANGE, +SLIDER_RANGE); slider->setValue(int(SLIDER_RANGE * value.toDouble())); slider->setTickPosition(QSlider::TicksBelow); @@ -188,10 +189,10 @@ void EffectWidgetPrivate::autogenerateUi() break; } + if (control) { #ifndef QT_NO_TOOLTIP control->setToolTip(para.description()); #endif - if (control) { #ifndef QT_NO_SHORTCUT label->setBuddy(control); #endif -- cgit v0.12 From c666b88abcb2c5c120054ac3b0d304cd8225ded7 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Tue, 26 May 2009 12:34:03 +0200 Subject: Windows CE compile fix QFileInfo doesn't have a constructor for QLatin1Char and implicit conversion didn't work. Reviewed-by: Thierry --- src/corelib/io/qfsfileengine_win.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp index aee9fde..82cde8b 100644 --- a/src/corelib/io/qfsfileengine_win.cpp +++ b/src/corelib/io/qfsfileengine_win.cpp @@ -1298,7 +1298,7 @@ QFileInfoList QFSFileEngine::drives() } return ret; #else - ret.append(QLatin1Char('/')); + ret.append(QFileInfo(QLatin1Char('/'))); return ret; #endif } -- cgit v0.12 From 54f92419b23b425e32ad573db17f608a67936df1 Mon Sep 17 00:00:00 2001 From: Morten Engvoldsen Date: Tue, 26 May 2009 12:40:02 +0200 Subject: Clearifying QWebFrame docs Adding docs to toHtml() and toPlainText() Task-number: 253088 Rev-by: Ariya Hidayat Rev-by: David Boddie --- src/3rdparty/webkit/WebKit/qt/Api/qwebframe.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/3rdparty/webkit/WebKit/qt/Api/qwebframe.cpp b/src/3rdparty/webkit/WebKit/qt/Api/qwebframe.cpp index 5dc6363..e565476 100644 --- a/src/3rdparty/webkit/WebKit/qt/Api/qwebframe.cpp +++ b/src/3rdparty/webkit/WebKit/qt/Api/qwebframe.cpp @@ -268,7 +268,7 @@ void QWebFrame::addToJavaScriptWindowObject(const QString &name, QObject *object } /*! - Returns the frame's content, converted to HTML. + Returns the frame's content as HTML, enclosed in HTML and BODY tags. \sa setHtml(), toPlainText() */ @@ -280,7 +280,8 @@ QString QWebFrame::toHtml() const } /*! - Returns the content of this frame converted to plain text. + Returns the content of this frame converted to plain text, completely + stripped of all HTML formatting. \sa toHtml() */ -- cgit v0.12 From f640eca34f63631f938817b1254d0caf92cc9143 Mon Sep 17 00:00:00 2001 From: Richard Moe Gustavsen Date: Tue, 26 May 2009 10:04:53 +0200 Subject: Carbon, QFontDialog::getFont() ignore the "initial" parameter Seems like no code was written to handle other font engines than CoreText. Unfortunatly the engine on Carbon is ATSUI. This patch adds general code for converting a QFont to an NSFont so the dialog can support other engines than CoreText Task-number: 251957 Reviewed-by: Trenton Schulz --- src/gui/dialogs/qfontdialog_mac.mm | 39 ++++++++++++++++++++++++++++++-------- 1 file changed, 31 insertions(+), 8 deletions(-) diff --git a/src/gui/dialogs/qfontdialog_mac.mm b/src/gui/dialogs/qfontdialog_mac.mm index 13f7149..3be53db 100644 --- a/src/gui/dialogs/qfontdialog_mac.mm +++ b/src/gui/dialogs/qfontdialog_mac.mm @@ -47,6 +47,7 @@ #include #include #include +#include #include #include #import @@ -123,16 +124,16 @@ static QFont qfontForCocoaFont(NSFont *cocoaFont, const QFont &resolveFont) QFont newFont; if (cocoaFont) { int pSize = qRound([cocoaFont pointSize]); - QString family(QCFString::toQString(reinterpret_cast([cocoaFont familyName]))); - QString typeface(QCFString::toQString(reinterpret_cast([cocoaFont fontName]))); -// qDebug() << "original family" << family << "typeface" << typeface << "psize" << pSize; + QString family(qt_mac_NSStringToQString([cocoaFont familyName])); + QString typeface(qt_mac_NSStringToQString([cocoaFont fontName])); + int hyphenPos = typeface.indexOf(QLatin1Char('-')); if (hyphenPos != -1) { typeface.remove(0, hyphenPos + 1); } else { typeface = QLatin1String("Normal"); } -// qDebug() << " massaged family" << family << "typeface" << typeface << "psize" << pSize; + newFont = QFontDatabase().font(family, typeface, pSize); newFont.setUnderline(resolveFont.underline()); newFont.setStrikeOut(resolveFont.strikeOut()); @@ -598,15 +599,37 @@ QFont QFontDialogPrivate::execCocoaFontPanel(bool *ok, const QFont &initial, } } -void QFontDialogPrivate::setFont(void * delegate, const QFont &font) +void QFontDialogPrivate::setFont(void *delegate, const QFont &font) { + QMacCocoaAutoReleasePool pool; QFontEngine *fe = font.d->engineForScript(QUnicodeTables::Common); + NSFontManager *mgr = [NSFontManager sharedFontManager]; + NSFont *nsFont = 0; + #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5 if (qstrcmp(fe->name(), "CoreText") == 0) { - const NSFont *nsFont = reinterpret_cast(static_cast(fe)->ctfont); - [[NSFontManager sharedFontManager] setSelectedFont:nsFont isMultiple:NO]; - } + nsFont = reinterpret_cast(static_cast(fe)->ctfont); + } else #endif + { + int weight = 5; + NSFontTraitMask mask = 0; + if (font.style() == QFont::StyleItalic) { + mask |= NSItalicFontMask; + } + if (font.weight() == QFont::Bold) { + weight = 9; + mask |= NSBoldFontMask; + } + + NSFontManager *mgr = [NSFontManager sharedFontManager]; + nsFont = [mgr fontWithFamily:qt_mac_QStringToNSString(font.family()) + traits:mask + weight:weight + size:font.pointSize()]; + } + + [mgr setSelectedFont:nsFont isMultiple:NO]; [static_cast(delegate) setQtFont:font]; } -- cgit v0.12 From f552dc200d857505df500b3ce0b99d5f7c74c951 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Tue, 26 May 2009 13:26:14 +0200 Subject: We first remove the pixmap from the cache and then release the key If we don't remove the pixmap from QCache first then the key is invalid and the removal failed Reviewed-by: sroedal --- src/gui/image/qpixmapcache.cpp | 4 +++- tests/auto/qpixmapcache/tst_qpixmapcache.cpp | 8 ++++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/src/gui/image/qpixmapcache.cpp b/src/gui/image/qpixmapcache.cpp index 3cfc191..82b42b4 100644 --- a/src/gui/image/qpixmapcache.cpp +++ b/src/gui/image/qpixmapcache.cpp @@ -342,8 +342,10 @@ bool QPMCache::remove(const QString &key) bool QPMCache::remove(const QPixmapCache::Key &key) { + bool result = QCache::remove(key); + //We release the key after we removed it from the cache releaseKey(key); - return QCache::remove(key); + return result; } void QPMCache::resizeKeyArray(int size) diff --git a/tests/auto/qpixmapcache/tst_qpixmapcache.cpp b/tests/auto/qpixmapcache/tst_qpixmapcache.cpp index 405ac34..fb5998a 100644 --- a/tests/auto/qpixmapcache/tst_qpixmapcache.cpp +++ b/tests/auto/qpixmapcache/tst_qpixmapcache.cpp @@ -369,6 +369,14 @@ void tst_QPixmapCache::remove() key = QPixmapCache::insert(p1); QCOMPARE(getPrivate(key)->key, 1); + //Test if pixmaps are correctly deleted + QPixmapCache::clear(); + key = QPixmapCache::insert(p1); + QCOMPARE(getPrivate(key)->key, 1); + QVERIFY(QPixmapCache::find(key, &p1) != 0); + QPixmapCache::remove(key); + QCOMPARE(p1.isDetached(), true); + //We mix both part of the API QPixmapCache::clear(); p1.fill(Qt::red); -- cgit v0.12 From c37c8370e4897d2e6191df2d1ccde43830ffb8d0 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Tue, 26 May 2009 13:42:33 +0200 Subject: Doc - more screenshots and better description --- doc/src/designer-manual.qdoc | 35 ++++++++--------------- doc/src/images/rgbController-final-layout.png | Bin 0 -> 11275 bytes doc/src/images/rgbController-form-gridLayout.png | Bin 0 -> 11235 bytes doc/src/images/rgbController-selectForLayout.png | Bin 0 -> 20981 bytes 4 files changed, 12 insertions(+), 23 deletions(-) create mode 100644 doc/src/images/rgbController-final-layout.png create mode 100644 doc/src/images/rgbController-form-gridLayout.png create mode 100644 doc/src/images/rgbController-selectForLayout.png diff --git a/doc/src/designer-manual.qdoc b/doc/src/designer-manual.qdoc index 77b208b..452782f 100644 --- a/doc/src/designer-manual.qdoc +++ b/doc/src/designer-manual.qdoc @@ -436,41 +436,32 @@ You start by choosing \gui Widget from the \gui{New Form} dialog. \endtable - Then you drag three labels, three spin boxes and three vertical sliders on - to your form. To change the label's default text, simply double-click on - it. The screenshot below shows the form after all three labels have been - renamed. - - You can roughly arrange them according to how you would like them to be - laid out. \table - \row \o \inlineimage rgbController-widgetBox.png - \o \inlineimage rgbController-arrangement.png - \endtable + \row + \i \inlineimage rgbController-arrangement.png + \i \bold{Placing Widgets on a Form} + Drag three labels, three spin boxes and three vertical sliders on to your + form. To change the label's default text, simply double-click on it. You + can arrange them according to how you would like them to be laid out. + \endtable + To ensure that they are laid out exactly like this in your program, you need to place these widgets into a layout. We will do this in groups of three. Select the "RED" label. Then, hold down \key Ctrl while you select its corresponding spin box and slider. In the \gui{Form} menu, select \gui{Lay Out in a Grid}. - \omit \table \row \i \inlineimage rgbController-form-gridLayout.png \i \inlineimage rgbController-selectForLayout.png \endtable - \endomit Repeat the step for the other two labels along with their corresponding - spin boxes and sliders as well. Your form will now look similar to the - screenshot below. - - \omit - \image rgbController-almostLaidOut.png - \endomit + spin boxes and sliders as well. The next step is to combine all three layouts into one \bold{main layout}. It is important that your form has a main layout; otherwise, the widgets @@ -478,7 +469,9 @@ layout, \gui{Right click} anywhere on your form, outside of the three separate layouts, and select \gui{Lay Out Horizontally}. Alternatively, you could also select \gui{Lay Out in a Grid} -- you will still see the same - arrangement. + arrangement (shown below). + + \image rgbController-final-layout.png \note Main layouts cannot be seen on the form. To check if you have a main layout installed, try resizing your form; your widgets should resize @@ -495,7 +488,6 @@ pressing \key{F4} or something \gui{Edit Signals/Slots} from the \gui{Edit} menu. - \omit \table \row \i \inlineimage rgbController-signalsAndSlots.png @@ -505,11 +497,8 @@ \gui{Configure Connection} dialog, shown below, will pop up. Select the correct signal and slot and click \gui OK. \endtable - \endomit - \omit \image rgbController-configureConnection.png - \endomit Repeat the step (in reverse order), clicking on the spin box and dragging the cursor towards the slider, to connect the spin box's diff --git a/doc/src/images/rgbController-final-layout.png b/doc/src/images/rgbController-final-layout.png new file mode 100644 index 0000000..d32a93e Binary files /dev/null and b/doc/src/images/rgbController-final-layout.png differ diff --git a/doc/src/images/rgbController-form-gridLayout.png b/doc/src/images/rgbController-form-gridLayout.png new file mode 100644 index 0000000..c8f3dcf Binary files /dev/null and b/doc/src/images/rgbController-form-gridLayout.png differ diff --git a/doc/src/images/rgbController-selectForLayout.png b/doc/src/images/rgbController-selectForLayout.png new file mode 100644 index 0000000..7a8e184 Binary files /dev/null and b/doc/src/images/rgbController-selectForLayout.png differ -- cgit v0.12 From aec18b0eea741da58a02f7ad95ab5ee9dccfce6c Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Tue, 26 May 2009 13:44:35 +0200 Subject: Doc - whitespace cleaning --- doc/src/designer-manual.qdoc | 48 ++++++++++++++++++++++---------------------- 1 file changed, 24 insertions(+), 24 deletions(-) diff --git a/doc/src/designer-manual.qdoc b/doc/src/designer-manual.qdoc index 452782f..9c13d79 100644 --- a/doc/src/designer-manual.qdoc +++ b/doc/src/designer-manual.qdoc @@ -299,12 +299,12 @@ \row \i \inlineimage designer-widget-box.png \i \bold{Qt Designer's Widget Box} - + The widget box provides a selection of standard Qt widgets, layouts, and other objects that can be used to create user interfaces on forms. Each of the categories in the widget box contain widgets with similar uses or related features. - + \note Since Qt 4.4, new widgets have been included, e.g., QPlainTextEdit, QCommandLinkButton, QScrollArea, QMdiArea, and QWebView. @@ -358,7 +358,7 @@ using a grid. The coordinates on the screenshot show the position of each widget within the grid. - \image addressbook-tutorial-part3-labeled-layout.png + \image addressbook-tutorial-part3-labeled-layout.png \note Inside the grid, the QPushButton objects are actually nested. The buttons on the right are first placed in a QVBoxLayout; the buttons at the @@ -367,7 +367,7 @@ To visualize, imagine the layout as a box that shrinks as much as possible, attempting to \e squeeze your widgets in a neat arrangement, and, at the - same time, maximize the use of available space. + same time, maximize the use of available space. Qt's layouts help when you: @@ -446,7 +446,7 @@ form. To change the label's default text, simply double-click on it. You can arrange them according to how you would like them to be laid out. \endtable - + To ensure that they are laid out exactly like this in your program, you need to place these widgets into a layout. We will do this in groups of three. Select the "RED" label. Then, hold down \key Ctrl while you select @@ -779,11 +779,11 @@ have a \c text property that can also be edited by double-clicking on the widget or by pressing \gui F2. \QD interprets the backslash (\\) character specially, enabling newline (\\n) characters to be - inserted into the text; the \\\\ character sequence is used to + inserted into the text; the \\\\ character sequence is used to insert a single backslash into the text. A context menu can also be opened while editing, providing another way to insert special characters and newlines into the text. - \endlist + \endlist \section2 Dynamic Properties @@ -795,12 +795,12 @@ \image designer-property-editor-toolbar.png - To add a dynamic property, clcik on the \gui Add button + To add a dynamic property, clcik on the \gui Add button \inlineimage designer-property-editor-add-dynamic.png - . To remove it, click on the \gui Remove button + . To remove it, click on the \gui Remove button \inlineimage designer-property-editor-remove-dynamic.png instead. You can also sort the properties alphabetically and change the - color groups by clickinig on the \gui Configure button + color groups by clickinig on the \gui Configure button \inlineimage designer-property-editor-configure.png . @@ -902,7 +902,7 @@ \section2 Horizontal and Vertical Layouts - + The simplest way to arrange objects on a form is to place them in a horizontal or vertical layout. Horizontal layouts ensure that the widgets within are aligned horizontally; vertical layouts ensure that they are @@ -1129,7 +1129,7 @@ spacers just provide spacing hints to layouts, so they cannot be connected to other objects. - + \target HighlightedObjects \table \row @@ -1168,7 +1168,7 @@ \image designer-connection-dialog.png - To complete the connection, select a signal from the source object and a + To complete the connection, select a signal from the source object and a slot from the destination object, then click \key OK. Click \key Cancel if you wish to abandon the connection. @@ -1711,22 +1711,22 @@ \i \bold{Resource Files} Within the resource browser, you can open existing resource files or - create new ones. Click the \gui{Edit Resources} button + create new ones. Click the \gui{Edit Resources} button \inlineimage designer-edit-resources-button.png to edit your resources. To reload resources, click on the \gui Reload - button + button \inlineimage designer-reload-resources-button.png . \endtable Once a resource file is loaded, you can create or remove entries in it - using the given \gui{Add Files} - \inlineimage designer-add-resource-entry-button.png - and \gui{Remove Files} + using the given \gui{Add Files} + \inlineimage designer-add-resource-entry-button.png + and \gui{Remove Files} \inlineimage designer-remove-resource-entry-button.png buttons, and specify resources (e.g., images) using the \gui{Add Files} - button + button \inlineimage designer-add-files-button.png . Note that these resources must reside within the current resource file's directory or one of its subdirectories. @@ -1738,15 +1738,15 @@ \i \inlineimage designer-edit-resource.png \i \bold{Editing Resource Files} - Press the + Press the \inlineimage designer-add-resource-entry-button.png button to add a new resource entry to the file. Then use the - \gui{Add Files} button + \gui{Add Files} button \inlineimage designer-add-files-button.png to specify the resource. You can remove resources by selecting the corresponding entry in the - resource editor, and pressing the + resource editor, and pressing the \inlineimage designer-remove-resource-entry-button.png button. \endtable @@ -2554,7 +2554,7 @@ pixmap property in the property editor. QDesignerTaskMenuExtension is useful for custom widgets. It provides an extension that allows you to add custom menu entries to \QD's task menu. - + The \l{designer/taskmenuextension}{Task Menu Extension} example illustrates how to use this class. @@ -2655,7 +2655,7 @@ pixmap property in the property editor. function, making it able to create your extension, such as a \l{designer/containerextension}{MultiPageWidget} container extension. - You can either create a new QExtensionFactory and reimplement the + You can either create a new QExtensionFactory and reimplement the QExtensionFactory::createExtension() function: \snippet doc/src/snippets/code/doc_src_designer-manual.qdoc 8 -- cgit v0.12 From 2c8348f5ccf62be31479dcd78282395a98eed76f Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Tue, 26 May 2009 14:13:21 +0200 Subject: BT: opening datetimepicker in a cell in spreadsheet demo resets the date That was a bug in the exemple. Reviewed-by: Kavindra Palaraja --- demos/spreadsheet/spreadsheetdelegate.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/demos/spreadsheet/spreadsheetdelegate.cpp b/demos/spreadsheet/spreadsheetdelegate.cpp index 465c92f..2916757 100644 --- a/demos/spreadsheet/spreadsheetdelegate.cpp +++ b/demos/spreadsheet/spreadsheetdelegate.cpp @@ -51,7 +51,7 @@ QWidget *SpreadSheetDelegate::createEditor(QWidget *parent, { if (index.column() == 1) { QDateTimeEdit *editor = new QDateTimeEdit(parent); - editor->setDisplayFormat("dd/M/yyy"); + editor->setDisplayFormat("dd/M/yyyy"); editor->setCalendarPopup(true); return editor; } @@ -93,7 +93,7 @@ void SpreadSheetDelegate::setEditorData(QWidget *editor, if (dateEditor) { dateEditor->setDate(QDate::fromString( index.model()->data(index, Qt::EditRole).toString(), - "d/M/yy")); + "d/M/yyyy")); } } } @@ -107,7 +107,7 @@ void SpreadSheetDelegate::setModelData(QWidget *editor, } else { QDateTimeEdit *dateEditor = qobject_cast(editor); if (dateEditor) { - model->setData(index, dateEditor->date().toString("dd/M/yyy")); + model->setData(index, dateEditor->date().toString("dd/M/yyyy")); } } } -- cgit v0.12 From 1536b02ed1633555e306bec02398a2a7c1bdabf7 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Tue, 26 May 2009 14:19:27 +0200 Subject: Test for QDate::fromDate with string format. Note that two digit years are always in the year 19xx This is excepted for compatibility reason as discussed with Peter --- tests/auto/qdate/tst_qdate.cpp | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/tests/auto/qdate/tst_qdate.cpp b/tests/auto/qdate/tst_qdate.cpp index d4273d0..4d6c80c 100644 --- a/tests/auto/qdate/tst_qdate.cpp +++ b/tests/auto/qdate/tst_qdate.cpp @@ -82,6 +82,8 @@ private slots: void operator_gt_eq(); void fromString_data(); void fromString(); + void fromString_format_data(); + void fromString_format(); void toString_format_data(); void toString_format(); void isLeapYear(); @@ -618,6 +620,30 @@ void tst_QDate::fromString() QCOMPARE( QDate::fromString( str2, Qt::ISODate ), d1 ); } +void tst_QDate::fromString_format_data() +{ + QTest::addColumn("string"); + QTest::addColumn("format"); + QTest::addColumn("date"); + + //year with yy is always 19xx for compatibility + QTest::newRow( "data0" ) << QString("21052006") << QString("ddMMyyyy") << QDate(2006,5,21); + QTest::newRow( "data1" ) << QString("210506") << QString("ddMMyy") << QDate(1906,5,21); + QTest::newRow( "data2" ) << QString("21/5/2006") << QString("d/M/yyyy") << QDate(2006,5,21); + QTest::newRow( "data3" ) << QString("21/5/06") << QString("d/M/yy") << QDate(1906,5,21); + QTest::newRow( "data4" ) << QString("20060521") << QString("yyyyMMdd") << QDate(2006,5,21); + QTest::newRow( "data5" ) << QString("060521") << QString("yyMMdd") << QDate(1906,5,21); +} + +void tst_QDate::fromString_format() +{ + QFETCH( QString, string ); + QFETCH( QString, format ); + QFETCH( QDate, date ); + + QCOMPARE( QDate::fromString( string, format ), date ); +} + void tst_QDate::toString_format_data() { QTest::addColumn("t"); -- cgit v0.12 From 8a2ca9b0d8ed23cec44e40f61c0f4983fbc55282 Mon Sep 17 00:00:00 2001 From: Morten Engvoldsen Date: Tue, 26 May 2009 14:06:56 +0200 Subject: Correcting bugs in classic.css Correcting invalid padding values. none is not a valid padding value. Rev-by: David Boddie --- tools/qdoc3/test/classic.css | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index 6cf7377..f22a77a 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -77,10 +77,10 @@ table.annotated td { table tr pre { - padding-top: none; - padding-bottom: none; - padding-left: none; - padding-right: none; + padding-top: 0px; + padding-bottom: 0px; + padding-left: 0px; + padding-right: 0px; border: none; background: none } -- cgit v0.12 From 871b730da203cef773e159960532888522f16a0b Mon Sep 17 00:00:00 2001 From: Trond Kjernaasen Date: Tue, 26 May 2009 14:20:34 +0200 Subject: BT: Fixed GL textdrawing in the Boxes demo. Reworked the 85f98acaa3a38079071bea711e43c9a86edec1f6 fix, since it broke glyph positioning in the GL engine under Windows. Instead of changing the glyph cache margin, which impacts where the glyph is positioned, we just make the image the glyph is drawn into 4 pixels bigger in width/heigth. The margin in QImageTextureGlyphCache needs to be reworked.. Task-number: 254450 Reviewed-by: Eskil --- src/gui/painting/qtextureglyphcache.cpp | 8 ++++++-- src/gui/text/qfontengine_win.cpp | 6 +++--- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/gui/painting/qtextureglyphcache.cpp b/src/gui/painting/qtextureglyphcache.cpp index 3fd1ffb..89df869 100644 --- a/src/gui/painting/qtextureglyphcache.cpp +++ b/src/gui/painting/qtextureglyphcache.cpp @@ -92,8 +92,8 @@ void QTextureGlyphCache::populate(const QTextItemInt &ti, int glyph_height = metrics.height.ceil().toInt(); if (glyph_height == 0 || glyph_width == 0) continue; - glyph_width += margin * 2 + 2; - glyph_height += margin * 2 + 2; + glyph_width += margin * 2 + 4; + glyph_height += margin * 2 + 4; // align to 8-bit boundary if (m_type == QFontEngineGlyphCache::Raster_Mono) glyph_width = (glyph_width+7)&~7; @@ -189,7 +189,11 @@ void QImageTextureGlyphCache::createTextureData(int width, int height) int QImageTextureGlyphCache::glyphMargin() const { +#ifdef Q_WS_MAC return 2; +#else + return m_type == QFontEngineGlyphCache::Raster_RGBMask ? 2 : 0; +#endif } void QImageTextureGlyphCache::fillTexture(const Coord &c, glyph_t g) diff --git a/src/gui/text/qfontengine_win.cpp b/src/gui/text/qfontengine_win.cpp index bf3a176..7341665 100644 --- a/src/gui/text/qfontengine_win.cpp +++ b/src/gui/text/qfontengine_win.cpp @@ -1406,8 +1406,8 @@ QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin #endif #endif - QNativeImage *ni = new QNativeImage(iw + 2 * margin + 2, - ih + 2 * margin + 2, + QNativeImage *ni = new QNativeImage(iw + 2 * margin + 4, + ih + 2 * margin + 4, QNativeImage::systemFormat(), true); ni->image.fill(0xffffffff); @@ -1449,7 +1449,7 @@ QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph, const QTransform &xform) font = CreateFontIndirectW(&lf); } - QNativeImage *mask = drawGDIGlyph(font, glyph, 2, xform); + QNativeImage *mask = drawGDIGlyph(font, glyph, 0, xform); if (mask == 0) return QImage(); -- cgit v0.12 From c17f27a9a14c353c6149f2c15f6a0ff6afe3dedd Mon Sep 17 00:00:00 2001 From: Markus Goetz Date: Tue, 26 May 2009 13:22:00 +0200 Subject: SSL: Remove broken system certificate loading code Task-number: 254365 Reviewed-by: Peter Hartmann --- src/network/ssl/qsslsocket_openssl.cpp | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/src/network/ssl/qsslsocket_openssl.cpp b/src/network/ssl/qsslsocket_openssl.cpp index 6f8cf42..cb101af 100644 --- a/src/network/ssl/qsslsocket_openssl.cpp +++ b/src/network/ssl/qsslsocket_openssl.cpp @@ -482,30 +482,7 @@ void QSslSocketPrivate::resetDefaultCiphers() QList QSslSocketPrivate::systemCaCertificates() { -#ifdef QQ_OS_UNIX - // Check known locations for the system's default bundle. ### On Windows, - // we should use CAPI to find the bundle, and not rely on default unix - // locations. - const char *standardLocations[] = {"/etc/ssl/certs/", -#if 0 - // KDE uses KConfig for its SSL store, - // but it also stores the bundle at - // this location - "$HOME/.kde/share/apps/kssl/ca-bundle.crt", -#endif - 0}; - const char **it = standardLocations; - QStringList nameFilter; - nameFilter << QLatin1String("*.pem") << QLatin1String("*.crt"); - while (*it) { - if (QDirIterator(QLatin1String(*it), nameFilter).hasNext()) - return certificatesFromPath(QLatin1String(*it)); - ++it; - } -#endif - - // Qt provides a default bundle when we cannot detect the system's default - // bundle. + // Qt provides a default bundle of certificates QFile caBundle(QLatin1String(":/trolltech/network/ssl/qt-ca-bundle.crt")); if (caBundle.open(QIODevice::ReadOnly | QIODevice::Text)) return QSslCertificate::fromDevice(&caBundle); -- cgit v0.12 From a670315152bf0914b8661b584d20752fd4da5b95 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 26 May 2009 14:40:40 +0200 Subject: A GLint is converted to int for passing to qBound(). --- src/opengl/qglframebufferobject.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 2b7ad4f..338ce1f 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -395,7 +395,7 @@ void QGLFramebufferObjectPrivate::init(const QSize &sz, QGLFramebufferObject::At GLint maxSamples; glGetIntegerv(GL_MAX_SAMPLES_EXT, &maxSamples); - samples = qBound(1, samples, int(maxSamples)); + samples = qBound(1, int(samples), int(maxSamples)); glGenRenderbuffers(1, &color_buffer); glBindRenderbuffer(GL_RENDERBUFFER_EXT, color_buffer); -- cgit v0.12 From 7c383fc79510276439deeb706d48ad5543fb54e7 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Tue, 26 May 2009 14:46:15 +0200 Subject: Fix a painting issue in the QGtkStyle statusbar We should use the "statusbar" string when we draw the sizegrip. Since gtkstatusbar is the only gtk widget using the paint_resize_grip and it uses the "statusbar" string itself it should be safe to assume this. Task-number: 254535 Reviewed-by: rosch --- src/gui/styles/qgtkstyle.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index 86653df..14be518 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -2344,7 +2344,7 @@ void QGtkStyle::drawControl(ControlElement element, case CE_SizeGrip: { GtkWidget *gtkStatusbar = QGtk::gtkWidget(QLS("GtkStatusbar.GtkFrame")); QRect gripRect = option->rect.adjusted(0, 0, -gtkStatusbar->style->xthickness, -gtkStatusbar->style->ythickness); - gtkPainter.paintResizeGrip( gtkStatusbar, "window", gripRect, GTK_STATE_NORMAL, + gtkPainter.paintResizeGrip( gtkStatusbar, "statusbar", gripRect, GTK_STATE_NORMAL, GTK_SHADOW_OUT, QApplication::isRightToLeft() ? GDK_WINDOW_EDGE_SOUTH_WEST : GDK_WINDOW_EDGE_SOUTH_EAST, gtkStatusbar->style); -- cgit v0.12 From 0ae04e9d7872d170974d15e8fbae8da1949c94df Mon Sep 17 00:00:00 2001 From: Richard Moe Gustavsen Date: Tue, 26 May 2009 15:33:47 +0200 Subject: Mac: Prefix sat in qt.conf is ignored on Mac Fix: Make sure to add the prefix to the value we return in QLibraryInfo Task-number: 254545 Reviewed-by: Trenton Schulz --- src/corelib/global/qlibraryinfo.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/corelib/global/qlibraryinfo.cpp b/src/corelib/global/qlibraryinfo.cpp index 29e356e..7f6ff20 100644 --- a/src/corelib/global/qlibraryinfo.cpp +++ b/src/corelib/global/qlibraryinfo.cpp @@ -434,14 +434,14 @@ QLibraryInfo::location(LibraryLocation loc) #else if (QCoreApplication::instance()) { #ifdef Q_OS_MAC - CFBundleRef bundleRef = CFBundleGetMainBundle(); - if (bundleRef) { - QCFType urlRef = CFBundleCopyBundleURL(bundleRef); - if (urlRef) { - QCFString path = CFURLCopyFileSystemPath(urlRef, kCFURLPOSIXPathStyle); - return QDir::cleanPath(path + QLatin1String("/Contents")); - } - } + CFBundleRef bundleRef = CFBundleGetMainBundle(); + if (bundleRef) { + QCFType urlRef = CFBundleCopyBundleURL(bundleRef); + if (urlRef) { + QCFString path = CFURLCopyFileSystemPath(urlRef, kCFURLPOSIXPathStyle); + return QDir::cleanPath(path + QLatin1String("/Contents/") + ret); + } + } #endif return QDir(QCoreApplication::applicationDirPath()).absoluteFilePath(ret); } else { -- cgit v0.12 From 1164e61393349fc3d6bf06d0789fa6ea2cfb5909 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Tue, 26 May 2009 15:37:45 +0200 Subject: Doc - more images and additional description --- doc/src/designer-manual.qdoc | 24 +++++++++++---------- .../images/rgbController-configure-connection1.png | Bin 0 -> 29210 bytes .../images/rgbController-configure-connection2.png | Bin 0 -> 28655 bytes doc/src/images/rgbController-property-editing.png | Bin 0 -> 9158 bytes doc/src/images/rgbController-screenshot.png | Bin 0 -> 8995 bytes doc/src/images/rgbController-signalsAndSlots.png | Bin 0 -> 10050 bytes 6 files changed, 13 insertions(+), 11 deletions(-) create mode 100644 doc/src/images/rgbController-configure-connection1.png create mode 100644 doc/src/images/rgbController-configure-connection2.png create mode 100644 doc/src/images/rgbController-property-editing.png create mode 100644 doc/src/images/rgbController-screenshot.png create mode 100644 doc/src/images/rgbController-signalsAndSlots.png diff --git a/doc/src/designer-manual.qdoc b/doc/src/designer-manual.qdoc index 9c13d79..58d0f71 100644 --- a/doc/src/designer-manual.qdoc +++ b/doc/src/designer-manual.qdoc @@ -478,11 +478,12 @@ accordingly. When you click on the slider and drag it to a certain value, you want the - spin box to display the slider's position. To do this, you need to connect - the slider's \l{QAbstractSlider::}{valueChanged()} signal to the spin box's - \l{QSpinBox::}{setValue()} slot. You also need to make the reverse - connections, e.g., connect the spin box's \l{QSpinBox::}{valueChanged()} - signal to the slider's \l{QAbstractSlider::value()}{setValue()} slot. + spin box to display the slider's position. To accomplish this behavior, you + need to connect the slider's \l{QAbstractSlider::}{valueChanged()} signal + to the spin box's \l{QSpinBox::}{setValue()} slot. You also need to make + the reverse connections, e.g., connect the spin box's \l{QSpinBox::} + {valueChanged()} signal to the slider's \l{QAbstractSlider::value()} + {setValue()} slot. To do this, you have to switch to \gui{Edit Signals/Slots} mode, either by pressing \key{F4} or something \gui{Edit Signals/Slots} from the \gui{Edit} @@ -498,13 +499,18 @@ correct signal and slot and click \gui OK. \endtable - \image rgbController-configureConnection.png + \image rgbController-configureConnection1.png Repeat the step (in reverse order), clicking on the spin box and dragging the cursor towards the slider, to connect the spin box's \l{QSpinBox::}{valueChanged()} signal to the slider's \l{QAbstractSlider::value()}{setValue()} slot. + You can use the screenshot below as a guide to selecting the correct signal + and slot. + + \image rgbController-configure-connection2.png + Now that you have successfully connected the objects for the "RED" component of the RGB Controller, do the same for the "GREEN" and "BLUE" components as well. @@ -512,7 +518,6 @@ Since RGB values range between 0 and 255, we need to limit the spin box and slider to that particular range. - \omit \table \row \i \inlineimage rgbController-property-editing.png @@ -523,17 +528,14 @@ \l{QSpinBox::}{maximum} property. Then, click on the first vertical slider, you will see \l{QAbstractSlider}'s properties. Enter "255" for the \l{QAbstractSlider::}{maximum} property as well. Repeat this - process for the remaining spin boxes and sliders. + process for the remaining spin boxes and sliders. \endtable - \endomit Now, we preview your form to see how it would look in your application. To preview your form, press \key{Ctrl + R} or select \gui Preview from the \gui Form menu. - \omit \image rgbController-preview.png - \endomit Try dragging the slider - the spin box will mirror its value too (and vice versa). Also, you can resize it to see how the layouts used to manage the diff --git a/doc/src/images/rgbController-configure-connection1.png b/doc/src/images/rgbController-configure-connection1.png new file mode 100644 index 0000000..0798184 Binary files /dev/null and b/doc/src/images/rgbController-configure-connection1.png differ diff --git a/doc/src/images/rgbController-configure-connection2.png b/doc/src/images/rgbController-configure-connection2.png new file mode 100644 index 0000000..f3fcc62 Binary files /dev/null and b/doc/src/images/rgbController-configure-connection2.png differ diff --git a/doc/src/images/rgbController-property-editing.png b/doc/src/images/rgbController-property-editing.png new file mode 100644 index 0000000..64fc500 Binary files /dev/null and b/doc/src/images/rgbController-property-editing.png differ diff --git a/doc/src/images/rgbController-screenshot.png b/doc/src/images/rgbController-screenshot.png new file mode 100644 index 0000000..6019233 Binary files /dev/null and b/doc/src/images/rgbController-screenshot.png differ diff --git a/doc/src/images/rgbController-signalsAndSlots.png b/doc/src/images/rgbController-signalsAndSlots.png new file mode 100644 index 0000000..2ba3aba Binary files /dev/null and b/doc/src/images/rgbController-signalsAndSlots.png differ -- cgit v0.12 From a088a3e5698881b0466cd072380fc7347ea68fba Mon Sep 17 00:00:00 2001 From: kh Date: Tue, 26 May 2009 15:53:52 +0200 Subject: Fix broken search inside search results. Reviewed-by: kh --- tools/assistant/tools/assistant/centralwidget.cpp | 131 ++++++++++------------ tools/assistant/tools/assistant/centralwidget.h | 5 +- 2 files changed, 66 insertions(+), 70 deletions(-) diff --git a/tools/assistant/tools/assistant/centralwidget.cpp b/tools/assistant/tools/assistant/centralwidget.cpp index b78f346..98245c0 100644 --- a/tools/assistant/tools/assistant/centralwidget.cpp +++ b/tools/assistant/tools/assistant/centralwidget.cpp @@ -848,60 +848,64 @@ void CentralWidget::keyPressEvent(QKeyEvent *e) QWidget::keyPressEvent(e); } -void CentralWidget::find(QString ttf, bool forward, bool backward) +void CentralWidget::find(const QString &ttf, bool forward, bool backward) { - QTextCursor cursor; - QTextDocument *doc = 0; - QTextBrowser *browser = 0; - - HelpViewer *viewer = currentHelpViewer(); QPalette p = findWidget->editFind->palette(); p.setColor(QPalette::Active, QPalette::Base, Qt::white); -#if !defined(QT_NO_WEBKIT) - Q_UNUSED(forward) - Q_UNUSED(doc) - Q_UNUSED(browser) - - if (viewer) { - QWebPage::FindFlags options; - if (backward) - options |= QWebPage::FindBackward; + if (!ttf.isEmpty()) { + HelpViewer *viewer = currentHelpViewer(); - if (findWidget->checkCase->isChecked()) - options |= QWebPage::FindCaseSensitively; + bool found = false; +#if !defined(QT_NO_WEBKIT) + if (viewer) { + QWebPage::FindFlags options; + if (backward) + options |= QWebPage::FindBackward; - bool found = viewer->findText(ttf, options); - findWidget->labelWrapped->hide(); + if (findWidget->checkCase->isChecked()) + options |= QWebPage::FindCaseSensitively; - if (!found) { - options |= QWebPage::FindWrapsAroundDocument; found = viewer->findText(ttf, options); + findWidget->labelWrapped->hide(); if (!found) { - p.setColor(QPalette::Active, QPalette::Base, QColor(255, 102, 102)); - } else { - findWidget->labelWrapped->show(); + options |= QWebPage::FindWrapsAroundDocument; + found = viewer->findText(ttf, options); + if (found) + findWidget->labelWrapped->show(); } + } else if (tabWidget->currentWidget() == m_searchWidget) { + QTextBrowser *browser = qFindChild(m_searchWidget); + found = findInTextBrowser(browser, ttf, forward, backward); } - } #else - if (viewer) { - doc = viewer->document(); - cursor = viewer->textCursor(); - browser = qobject_cast(viewer); - } + QTextBrowser *browser = qobject_cast(viewer); + if (tabWidget->currentWidget() == m_searchWidget) + browser = qFindChild(m_searchWidget); + found = findInTextBrowser(browser, ttf, forward, backward); +#endif - if (tabWidget->currentWidget() == m_searchWidget) { - QTextBrowser *browser = qFindChild(m_searchWidget); - if (browser) { - doc = browser->document(); - cursor = browser->textCursor(); - } + if (!found) + p.setColor(QPalette::Active, QPalette::Base, QColor(255, 102, 102)); } - if (!browser || !doc || cursor.isNull()) - return; + if (!findWidget->isVisible()) + findWidget->show(); + findWidget->editFind->setPalette(p); +} + +bool CentralWidget::findInTextBrowser(QTextBrowser* browser, const QString &ttf, + bool forward, bool backward) +{ + if (!browser) + return false; + + QTextDocument *doc = browser->document(); + QTextCursor cursor = browser->textCursor(); + + if (!doc || cursor.isNull()) + return false; QTextDocument::FindFlags options; @@ -910,44 +914,33 @@ void CentralWidget::find(QString ttf, bool forward, bool backward) QTextCursor::MoveAnchor); } - QTextCursor newCursor = cursor; + if (backward) + options |= QTextDocument::FindBackward; - if (!ttf.isEmpty()) { - if (backward) - options |= QTextDocument::FindBackward; - - if (findWidget->checkCase->isChecked()) - options |= QTextDocument::FindCaseSensitively; + if (findWidget->checkCase->isChecked()) + options |= QTextDocument::FindCaseSensitively; - if (findWidget->checkWholeWords->isChecked()) - options |= QTextDocument::FindWholeWords; + if (findWidget->checkWholeWords->isChecked()) + options |= QTextDocument::FindWholeWords; - newCursor = doc->find(ttf, cursor, options); - findWidget->labelWrapped->hide(); + findWidget->labelWrapped->hide(); + bool found = true; + QTextCursor newCursor = doc->find(ttf, cursor, options); + if (newCursor.isNull()) { + QTextCursor ac(doc); + ac.movePosition(options & QTextDocument::FindBackward + ? QTextCursor::End : QTextCursor::Start); + newCursor = doc->find(ttf, ac, options); if (newCursor.isNull()) { - QTextCursor ac(doc); - ac.movePosition(options & QTextDocument::FindBackward - ? QTextCursor::End : QTextCursor::Start); - newCursor = doc->find(ttf, ac, options); - if (newCursor.isNull()) { - p.setColor(QPalette::Active, QPalette::Base, QColor(255, 102, 102)); - newCursor = cursor; - } else { - findWidget->labelWrapped->show(); - } + found = false; + newCursor = cursor; + } else { + findWidget->labelWrapped->show(); } } -#endif - - if (!findWidget->isVisible()) - findWidget->show(); - -#if defined(QT_NO_WEBKIT) - if (browser) - browser->setTextCursor(newCursor); -#endif - findWidget->editFind->setPalette(p); + browser->setTextCursor(newCursor); + return found; } void CentralWidget::updateBrowserFont() diff --git a/tools/assistant/tools/assistant/centralwidget.h b/tools/assistant/tools/assistant/centralwidget.h index e3ce200..1342a75 100644 --- a/tools/assistant/tools/assistant/centralwidget.h +++ b/tools/assistant/tools/assistant/centralwidget.h @@ -55,6 +55,7 @@ class QLabel; class QAction; class QCheckBox; class QLineEdit; +class QTextBrowser; class QToolButton; class HelpViewer; @@ -176,7 +177,9 @@ private slots: private: void connectSignals(); bool eventFilter(QObject *object, QEvent *e); - void find(QString ttf, bool forward, bool backward); + void find(const QString &ttf, bool forward, bool backward); + bool findInTextBrowser(QTextBrowser* browser, const QString &ttf, + bool forward, bool backward); void initPrinter(); QString quoteTabTitle(const QString &title) const; void highlightSearchTerms(); -- cgit v0.12 From b03f598df2aa4037815eab9249ba1213236216c5 Mon Sep 17 00:00:00 2001 From: kh Date: Tue, 26 May 2009 15:57:45 +0200 Subject: Workaround the palette issue, set it only when we search is open. --- tools/assistant/tools/assistant/centralwidget.cpp | 35 +++++++++++++++++++++-- tools/assistant/tools/assistant/centralwidget.h | 5 ++++ 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/tools/assistant/tools/assistant/centralwidget.cpp b/tools/assistant/tools/assistant/centralwidget.cpp index 98245c0..52d48d5 100644 --- a/tools/assistant/tools/assistant/centralwidget.cpp +++ b/tools/assistant/tools/assistant/centralwidget.cpp @@ -87,6 +87,7 @@ namespace { FindWidget::FindWidget(QWidget *parent) : QWidget(parent) + , appPalette(qApp->palette()) { QHBoxLayout *hboxLayout = new QHBoxLayout(this); QString resourcePath = QLatin1String(":/trolltech/assistant/images/"); @@ -148,6 +149,34 @@ FindWidget::~FindWidget() { } +void FindWidget::hideEvent(QHideEvent* event) +{ +#if !defined(QT_NO_WEBKIT) + // TODO: remove this once webkit supports setting the palette + if (!event->spontaneous()) + qApp->setPalette(appPalette); +#else + Q_UNUSED(event); +#endif +} + +void FindWidget::showEvent(QShowEvent* event) +{ +#if !defined(QT_NO_WEBKIT) + // TODO: remove this once webkit supports setting the palette + if (!event->spontaneous()) { + QPalette p = appPalette; + p.setColor(QPalette::Inactive, QPalette::Highlight, + p.color(QPalette::Active, QPalette::Highlight)); + p.setColor(QPalette::Inactive, QPalette::HighlightedText, + p.color(QPalette::Active, QPalette::HighlightedText)); + qApp->setPalette(p); + } +#else + Q_UNUSED(event); +#endif +} + void FindWidget::updateButtons() { if (editFind->text().isEmpty()) { @@ -245,12 +274,14 @@ CentralWidget::CentralWidget(QHelpEngine *engine, MainWindow *parent) SLOT(showTabBarContextMenu(QPoint))); } - QPalette p = qApp->palette(); +#if defined(QT_NO_WEBKIT) + QPalette p = palette(); p.setColor(QPalette::Inactive, QPalette::Highlight, p.color(QPalette::Active, QPalette::Highlight)); p.setColor(QPalette::Inactive, QPalette::HighlightedText, p.color(QPalette::Active, QPalette::HighlightedText)); - qApp->setPalette(p); + setPalette(p); +#endif } CentralWidget::~CentralWidget() diff --git a/tools/assistant/tools/assistant/centralwidget.h b/tools/assistant/tools/assistant/centralwidget.h index 1342a75..d59dbe5 100644 --- a/tools/assistant/tools/assistant/centralwidget.h +++ b/tools/assistant/tools/assistant/centralwidget.h @@ -80,6 +80,10 @@ signals: void findNext(); void findPrevious(); +protected: + void hideEvent(QHideEvent* event); + void showEvent(QShowEvent * event); + private slots: void updateButtons(); @@ -95,6 +99,7 @@ private: QToolButton *toolPrevious; QCheckBox *checkWholeWords; + QPalette appPalette; friend class CentralWidget; }; -- cgit v0.12 From f61056a556259c12a6de23f12756e45737345111 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Tue, 26 May 2009 16:08:59 +0200 Subject: Doc: Updated the list of tools to include makeqpf and qvfb. Reviewed-by: Marcel Schuette --- doc/src/emb-fonts.qdoc | 2 +- doc/src/emb-makeqpf.qdoc | 9 ++++++--- doc/src/tools-list.qdoc | 6 ++---- 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/doc/src/emb-fonts.qdoc b/doc/src/emb-fonts.qdoc index 3ed23c3..86e169d 100644 --- a/doc/src/emb-fonts.qdoc +++ b/doc/src/emb-fonts.qdoc @@ -131,7 +131,7 @@ The Qt Prerendered Font (QPF2) is an architecture-independent, light-weight and non-scalable font format specific to \l{Qt for Embedded Linux}. - Nokia provides the cross-platform \c makeqpf tool, included in the + Nokia provides the cross-platform \l makeqpf tool, included in the \c tools directory of both \l {Qt} and \l{Qt for Embedded Linux}, which allows generation of QPF2 files from system fonts. diff --git a/doc/src/emb-makeqpf.qdoc b/doc/src/emb-makeqpf.qdoc index ca33eda..8f5d10b 100644 --- a/doc/src/emb-makeqpf.qdoc +++ b/doc/src/emb-makeqpf.qdoc @@ -44,7 +44,10 @@ \title makeqpf \ingroup qt-embedded-linux - \c makeqpf is not part of Qt 4. However, Qt 4 can still read QPF - files generated by Qt 2 or 3. To generate QPF files, use makeqpf from Qt 2 - or 3. + \c makeqpf is a tool to generate pre-rendered fonts in QPF2 format for use on Embedded Linux. + + Qt 4 can read files in QPF2 format in addition to QPF files generated by older versions of + \c makeqpf from Qt 2 or 3. + + \sa {Qt for Embedded Linux Fonts} */ diff --git a/doc/src/tools-list.qdoc b/doc/src/tools-list.qdoc index 7af9936..caef268 100644 --- a/doc/src/tools-list.qdoc +++ b/doc/src/tools-list.qdoc @@ -58,12 +58,10 @@ \o Translate applications to reach international markets. \row \o \l{qmake Manual}{qmake} \o Create makefiles from simple platform-independent project files (\c .pro files). - \omit - \row \o \l{emb-qvfb.html}{qvfb} + \row \o \l{The Virtual Framebuffer}{qvfb} \o Run and test embedded applications on the desktop. - \row \o \l{emb-makeqpf.html}{makeqpf} + \row \o \l{makeqpf} \o Create pre-rendered fonts for embedded devices. - \endomit \row \o \l{moc}{Meta-Object Compiler (moc)} \o Generate meta-object information for QObject subclasses. \row \o \l{User Interface Compiler (uic)} -- cgit v0.12 From bcd23411c8e22e15b863212a544bd64b78fe04b9 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 26 May 2009 17:13:57 +0200 Subject: some cleanups on private exported symbols --- src/gui/accessible/qaccessiblewidget.cpp | 19 +------------------ src/gui/image/qpixmapdatafactory_p.h | 2 +- src/gui/kernel/qapplication_win.cpp | 2 +- src/gui/kernel/qdnd_p.h | 2 +- src/gui/kernel/qkeysequence.cpp | 2 +- src/gui/painting/qgraphicssystemfactory_p.h | 2 +- src/gui/painting/qgraphicssystemplugin_p.h | 2 +- src/gui/text/qfontengine.cpp | 6 ------ src/gui/text/qfontengine_p.h | 6 ++++-- src/gui/text/qtextcontrol_p.h | 2 +- src/gui/text/qtextimagehandler_p.h | 4 ++-- src/opengl/qpaintengine_opengl.cpp | 1 - src/qt3support/other/q3dragobject.cpp | 5 ----- 13 files changed, 14 insertions(+), 41 deletions(-) diff --git a/src/gui/accessible/qaccessiblewidget.cpp b/src/gui/accessible/qaccessiblewidget.cpp index 753ac57..1c2fcef 100644 --- a/src/gui/accessible/qaccessiblewidget.cpp +++ b/src/gui/accessible/qaccessiblewidget.cpp @@ -102,24 +102,7 @@ static QString buddyString(const QWidget *widget) QString Q_GUI_EXPORT qt_accStripAmp(const QString &text) { - if (text.isEmpty()) - return text; - - const QChar *ch = text.unicode(); - int length = text.length(); - QString str; - while (length > 0) { - if (*ch == QLatin1Char('&')) { - ++ch; - --length; - if (!ch) - --ch; - } - str += *ch; - ++ch; - --length; - } - return str; + return QString(text).remove(QLatin1Char('&')); } QString Q_GUI_EXPORT qt_accHotKey(const QString &text) diff --git a/src/gui/image/qpixmapdatafactory_p.h b/src/gui/image/qpixmapdatafactory_p.h index 65e3f11..9604346 100644 --- a/src/gui/image/qpixmapdatafactory_p.h +++ b/src/gui/image/qpixmapdatafactory_p.h @@ -65,7 +65,7 @@ QT_MODULE(Gui) class QPixmapData; -class Q_GUI_EXPORT QPixmapDataFactory +class QPixmapDataFactory { public: static QPixmapDataFactory* instance(int screen = 0); diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 77625de..f264d12 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -1106,7 +1106,7 @@ void qWinRequestConfig(WId id, int req, int x, int y, int w, int h) configRequests->append(r); // store request in queue } -Q_GUI_EXPORT void qWinProcessConfigRequests() // perform requests in queue +static void qWinProcessConfigRequests() // perform requests in queue { if (!configRequests) return; diff --git a/src/gui/kernel/qdnd_p.h b/src/gui/kernel/qdnd_p.h index 7a0cb7a..9871658 100644 --- a/src/gui/kernel/qdnd_p.h +++ b/src/gui/kernel/qdnd_p.h @@ -202,7 +202,7 @@ public: #endif }; -class Q_GUI_EXPORT QDragManager: public QObject { +class QDragManager: public QObject { Q_OBJECT QDragManager(); diff --git a/src/gui/kernel/qkeysequence.cpp b/src/gui/kernel/qkeysequence.cpp index d1cb572..21f8859 100644 --- a/src/gui/kernel/qkeysequence.cpp +++ b/src/gui/kernel/qkeysequence.cpp @@ -145,7 +145,7 @@ static int qtkeyForMacSymbol(const QChar ch) #else static bool qt_sequence_no_mnemonics = false; #endif -void Q_GUI_EXPORT qt_set_sequence_auto_mnemonic(bool b) { qt_sequence_no_mnemonics = !b; } +void Q_AUTOTEST_EXPORT qt_set_sequence_auto_mnemonic(bool b) { qt_sequence_no_mnemonics = !b; } /*! \class QKeySequence diff --git a/src/gui/painting/qgraphicssystemfactory_p.h b/src/gui/painting/qgraphicssystemfactory_p.h index 9e95324..523b908 100644 --- a/src/gui/painting/qgraphicssystemfactory_p.h +++ b/src/gui/painting/qgraphicssystemfactory_p.h @@ -63,7 +63,7 @@ QT_MODULE(Gui) class QGraphicsSystem; -class Q_GUI_EXPORT QGraphicsSystemFactory +class QGraphicsSystemFactory { public: static QStringList keys(); diff --git a/src/gui/painting/qgraphicssystemplugin_p.h b/src/gui/painting/qgraphicssystemplugin_p.h index 2e70333..ea7aa2d 100644 --- a/src/gui/painting/qgraphicssystemplugin_p.h +++ b/src/gui/painting/qgraphicssystemplugin_p.h @@ -64,7 +64,7 @@ QT_MODULE(Gui) class QGraphicsSystem; -struct Q_GUI_EXPORT QGraphicsSystemFactoryInterface : public QFactoryInterface +struct QGraphicsSystemFactoryInterface : public QFactoryInterface { virtual QGraphicsSystem *create(const QString &key) = 0; }; diff --git a/src/gui/text/qfontengine.cpp b/src/gui/text/qfontengine.cpp index 97cb1ed..6e8adcf 100644 --- a/src/gui/text/qfontengine.cpp +++ b/src/gui/text/qfontengine.cpp @@ -1646,12 +1646,6 @@ bool QFontEngineMulti::canRender(const QChar *string, int len) return allExist; } -QFontEngine *QFontEngineMulti::engine(int at) const -{ - Q_ASSERT(at < engines.size()); - return engines.at(at); -} - QImage QFontEngineMulti::alphaMapForGlyph(glyph_t) { Q_ASSERT(false); diff --git a/src/gui/text/qfontengine_p.h b/src/gui/text/qfontengine_p.h index 92efb6c..0f8d81c 100644 --- a/src/gui/text/qfontengine_p.h +++ b/src/gui/text/qfontengine_p.h @@ -353,7 +353,7 @@ private: int _size; }; -class Q_GUI_EXPORT QFontEngineMulti : public QFontEngine +class QFontEngineMulti : public QFontEngine { public: explicit QFontEngineMulti(int engineCount); @@ -389,7 +389,9 @@ public: inline virtual const char *name() const { return "Multi"; } - QFontEngine *engine(int at) const; + QFontEngine *engine(int at) const + {Q_ASSERT(at < engines.size()); return engines.at(at); } + protected: friend class QPSPrintEnginePrivate; diff --git a/src/gui/text/qtextcontrol_p.h b/src/gui/text/qtextcontrol_p.h index e50540a..4dac4f7 100644 --- a/src/gui/text/qtextcontrol_p.h +++ b/src/gui/text/qtextcontrol_p.h @@ -83,7 +83,7 @@ class QAbstractScrollArea; class QEvent; class QTimerEvent; -class Q_GUI_EXPORT QTextControl : public QObject +class Q_AUTOTEST_EXPORT QTextControl : public QObject { Q_OBJECT Q_DECLARE_PRIVATE(QTextControl) diff --git a/src/gui/text/qtextimagehandler_p.h b/src/gui/text/qtextimagehandler_p.h index f5426b5..1f29642 100644 --- a/src/gui/text/qtextimagehandler_p.h +++ b/src/gui/text/qtextimagehandler_p.h @@ -60,7 +60,7 @@ QT_BEGIN_NAMESPACE class QTextImageFormat; -class Q_GUI_EXPORT QTextImageHandler : public QObject, +class QTextImageHandler : public QObject, public QTextObjectInterface { Q_OBJECT @@ -72,7 +72,7 @@ public: virtual void drawObject(QPainter *p, const QRectF &rect, QTextDocument *doc, int posInDocument, const QTextFormat &format); typedef QImage (*ExternalImageLoaderFunction)(const QString &name, const QString &context); - static ExternalImageLoaderFunction externalLoader; + static Q_GUI_EXPORT ExternalImageLoaderFunction externalLoader; //this is needed by Qt3Support }; QT_END_NAMESPACE diff --git a/src/opengl/qpaintengine_opengl.cpp b/src/opengl/qpaintengine_opengl.cpp index 6f7078a..d98cd7c 100644 --- a/src/opengl/qpaintengine_opengl.cpp +++ b/src/opengl/qpaintengine_opengl.cpp @@ -39,7 +39,6 @@ ** ****************************************************************************/ -#include #include #include #include diff --git a/src/qt3support/other/q3dragobject.cpp b/src/qt3support/other/q3dragobject.cpp index fb57220..50b75a4 100644 --- a/src/qt3support/other/q3dragobject.cpp +++ b/src/qt3support/other/q3dragobject.cpp @@ -208,11 +208,6 @@ void Q3DragObject::setPixmap(QPixmap pm, const QPoint& hotspot) Q_D(Q3DragObject); d->pixmap = pm; d->hot = hotspot; -#if 0 - QDragManager *manager = QDragManager::self(); - if (manager && manager->object == d->data) - manager->updatePixmap(); -#endif } /*! -- cgit v0.12 From 702a50367b13a137a9a87b499e4ab397be61383a Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 26 May 2009 16:26:33 +0200 Subject: doc update no more warnings while generating the docs --- src/gui/graphicsview/qgraphicsitem.cpp | 176 ++++++++++++++++++++++++------- src/gui/graphicsview/qgraphicswidget.cpp | 50 ++++++++- 2 files changed, 186 insertions(+), 40 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 0398fac..58b01cb 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -130,7 +130,7 @@ \img graphicsview-parentchild.png - \section Transformation + \section1 Transformation QGraphicsItem supports affine transformations in addition to its base position, pos(). To change the item's transformation, you can either pass @@ -166,7 +166,7 @@ .shear(horizontalShear, verticalShear).scale(xScale, yScale).translate(-xOrigin, -yOrigin); \endcode - \section Painting + \section1 Painting The paint() function is called by QGraphicsView to paint the item's contents. The item has no background or default fill of its own; whatever @@ -183,7 +183,7 @@ high z-values. Stacking order applies to sibling items; parents are always drawn before their children. - \section Events + \section1 Events QGraphicsItem receives events from QGraphicsScene through the virtual function sceneEvent(). This function distributes the most common events @@ -210,7 +210,7 @@ by the virtual function sceneEventFilter(). You can remove item event filters by calling removeSceneEventFilter(). - \section Custom Data + \section1 Custom Data Sometimes it's useful to register custom data with an item, be it a custom item, or a standard item. You can call setData() on any item to store data @@ -2614,24 +2614,32 @@ QTransform QGraphicsItem::transform() const } /*! - \property QGraphicsItem::xRotation - \since 4.6 - This property holds the rotation angle in degrees around the X axis + Returns the rotation around the X axis. The default is 0 \warning setting this property is conflicting with calling setTransform. If a transform has been set, this function return the default value. - \sa {Transformations} + \sa setXRotation(), {Transformations} */ qreal QGraphicsItem::xRotation() const { return d_ptr->decomposedTransform()->xRotation; } +/*! + \since 4.6 + + Sets the rotation around the X axis to \a angle degrees. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, it will be overwritten. + + \sa xRotation(), {Transformations} +*/ void QGraphicsItem::setXRotation(qreal angle) { if (!d_ptr->dirtyTransform) { @@ -2647,24 +2655,32 @@ void QGraphicsItem::setXRotation(qreal angle) } /*! - \property QGraphicsItem::yRotation - \since 4.6 - This property holds the rotation angle in degrees around the Y axis + Returns the rotation around the Y axis. The default is 0 \warning setting this property is conflicting with calling setTransform. If a transform has been set, this function return the default value. - \sa {Transformations} + \sa setYRotation(), {Transformations} */ qreal QGraphicsItem::yRotation() const { return d_ptr->decomposedTransform()->yRotation; } +/*! + \since 4.6 + + Sets the rotation around the Y axis to \a angle degrees. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, it will be overwritten. + + \sa yRotation(), {Transformations} +*/ void QGraphicsItem::setYRotation(qreal angle) { if (!d_ptr->dirtyTransform) { @@ -2680,24 +2696,32 @@ void QGraphicsItem::setYRotation(qreal angle) } /*! - \property QGraphicsItem::zRotation - \since 4.6 - This property holds the rotation angle in degrees around the Z axis + Returns the rotation around the Z axis. The default is 0 \warning setting this property is conflicting with calling setTransform. If a transform has been set, this function return the default value. - \sa {Transformations} + \sa setZRotation(), {Transformations} */ qreal QGraphicsItem::zRotation() const { return d_ptr->decomposedTransform()->zRotation; } +/*! + \since 4.6 + + Sets the rotation around the Z axis to \a angle degrees. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, it will be overwritten. + + \sa zRotation(), {Transformations} +*/ void QGraphicsItem::setZRotation(qreal angle) { if (!d_ptr->dirtyTransform) { @@ -2712,6 +2736,14 @@ void QGraphicsItem::setZRotation(qreal angle) d_ptr->hasTransform = 1; } +/*! + \since 4.6 + + This convenience function set the rotation angles around the 3 axes + to \a x, \a y and \a z. + + \sa setXRotation(), setYRotation(), setZRotation() +*/ void QGraphicsItem::setRotation(qreal x, qreal y, qreal z) { setXRotation(x); @@ -2720,24 +2752,32 @@ void QGraphicsItem::setRotation(qreal x, qreal y, qreal z) } /*! - \property QGraphicsItem::xScale - \since 4.6 - This property holds the scale factor on the X axis. + Returns the scale factor on the X axis. The default is 1 \warning setting this property is conflicting with calling setTransform. If a transform has been set, this function return the default value. - \sa {Transformations} + \sa setXScale(), {Transformations} */ qreal QGraphicsItem::xScale() const { return d_ptr->decomposedTransform()->xScale; } +/*! + \since 4.6 + + Sets the scale factor on the X axis to \a factor. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, it will be overwritten. + + \sa xScale(), {Transformations} +*/ void QGraphicsItem::setXScale(qreal factor) { if (!d_ptr->dirtyTransform) { @@ -2753,24 +2793,32 @@ void QGraphicsItem::setXScale(qreal factor) } /*! - \property QGraphicsItem::yScale - \since 4.6 - This property holds the scale factor on the Y axis. + Returns the scale factor on the Y axis. The default is 1 \warning setting this property is conflicting with calling setTransform. If a transform has been set, this function return the default value. - \sa {Transformations} + \sa setYScale(), {Transformations} */ qreal QGraphicsItem::yScale() const { return d_ptr->decomposedTransform()->yScale; } +/*! + \since 4.6 + + Sets the scale factor on the Y axis to \a factor. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, it will be overwritten. + + \sa yScale(), {Transformations} +*/ void QGraphicsItem::setYScale(qreal factor) { if (!d_ptr->dirtyTransform) { @@ -2785,6 +2833,13 @@ void QGraphicsItem::setYScale(qreal factor) d_ptr->hasTransform = 1; } +/*! + \since 4.6 + + This convenience function set the scaling factors on X and Y axis to \a sx and \a sy. + + \sa setXScale(), setYScale() +*/ void QGraphicsItem::setScale(qreal sx, qreal sy) { setXScale(sx); @@ -2792,24 +2847,32 @@ void QGraphicsItem::setScale(qreal sx, qreal sy) } /*! - \property QGraphicsItem::horizontalShear - \since 4.6 - This property holds the horizontal shear. + Returns the horizontal shear. - The default is 0. + The default is 0 \warning setting this property is conflicting with calling setTransform. If a transform has been set, this function return the default value. - \sa {Transformations} + \sa setHorizontalShear(), {Transformations} */ qreal QGraphicsItem::horizontalShear() const { return d_ptr->decomposedTransform()->horizontalShear; } +/*! + \since 4.6 + + Sets the horizontal shear to \a shear. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, it will be overwritten. + + \sa horizontalShear(), {Transformations} +*/ void QGraphicsItem::setHorizontalShear(qreal shear) { if (!d_ptr->dirtyTransform) { @@ -2825,24 +2888,32 @@ void QGraphicsItem::setHorizontalShear(qreal shear) } /*! - \property QGraphicsItem::verticalShear - \since 4.6 - This property holds the vertical shear. + Returns the vertical shear. - The default is 0. + The default is 0 \warning setting this property is conflicting with calling setTransform. If a transform has been set, this function return the default value. - \sa {Transformations} + \sa setHorizontalShear(), {Transformations} */ qreal QGraphicsItem::verticalShear() const { return d_ptr->decomposedTransform()->verticalShear; } +/*! + \since 4.6 + + Sets the vertical shear to \a shear. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, it will be overwritten. + + \sa verticalShear(), {Transformations} +*/ void QGraphicsItem::setVerticalShear(qreal shear) { if (!d_ptr->dirtyTransform) { @@ -2857,6 +2928,13 @@ void QGraphicsItem::setVerticalShear(qreal shear) d_ptr->hasTransform = 1; } +/*! + \since 4.6 + + This convenience function sets the horizontal shear to \a sh and the vertical shear to \a sv. + + \sa setHorizontalShear(), setVerticalShear() +*/ void QGraphicsItem::setShear(qreal sh, qreal sv) { setHorizontalShear(sh); @@ -2864,19 +2942,16 @@ void QGraphicsItem::setShear(qreal sh, qreal sv) } /*! - \property QGraphicsItem::transformOrigin - \since 4.6 - This property holds the transformation origin for the transformation properties. - This does not apply to the transformation set by setTransform. + Returns the transformation origin for the transformation properties. The default is QPointF(0,0). \warning setting this property is conflicting with calling setTransform. If a transform has been set, this function return the default value. - \sa {Transformations} + \sa setTransformOrigin(), {Transformations} */ QPointF QGraphicsItem::transformOrigin() const { @@ -2884,6 +2959,29 @@ QPointF QGraphicsItem::transformOrigin() const return QPointF(decomposed->xOrigin, decomposed->yOrigin); } +/*! + \fn inline void setTransformOrigin(qreal x, qreal y) + + \since 4.6 + + This is an overloaded member function, provided for convenience. + Sets the transformation origin for the transformation + properties to the point(\a x, \a y). + + \sa setTransformOrigin(), {Transformations} +*/ + +/*! + \since 4.6 + + Sets the transformation origin for the transformation properties to \a origin. + This does not apply to the transformation set by setTransform. + + \warning setting this property is conflicting with calling setTransform. + If a transform has been set, it will be overwritten. + + \sa transformOrigin(), {Transformations} +*/ void QGraphicsItem::setTransformOrigin(const QPointF &origin) { if (!d_ptr->dirtyTransform) { diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index a2e55e1..341f9a2 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -200,7 +200,55 @@ QT_BEGIN_NAMESPACE /*! \property QGraphicsWidget::pos \brief the position of the widget -*/ +*/ + +/*! + \property QGraphicsWidget::xRotation + \since 4.6 + \brief the rotation angle in degrees around the X axis +*/ + +/*! + \property QGraphicsWidget::yRotation + \since 4.6 + \brief the rotation angle in degrees around the Y axis +*/ + +/*! + \property QGraphicsWidget::zRotation + \since 4.6 + \brief the rotation angle in degrees around the Z axis +*/ + +/*! + \property QGraphicsWidget::xScale + \since 4.6 + \brief the scale factor on the X axis. +*/ + +/*! + \property QGraphicsWidget::yScale + \since 4.6 + \brief the scale factor on the Y axis. +*/ + +/*! + \property QGraphicsWidget::horizontalShear + \since 4.6 + \brief the horizontal shear. +*/ + +/*! + \property QGraphicsWidget::verticalShear + \since 4.6 + \brief the vertical shear. +*/ + +/*! + \property QGraphicsWidget::transformOrigin + \since 4.6 + \brief the transformation origin for the transformation properties. +*/ /*! Constructs a QGraphicsWidget instance. The optional \a parent argument is -- cgit v0.12 From 8bf5a6986db852525582713cc2f2a760df4fdc60 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Tue, 26 May 2009 16:50:48 +0200 Subject: QFileDialog selection bug when calling it multiple times. The problem was that we don't clear the selection model if the previous selection was valid. Task-number:251341 Reviewed-by:jasplin --- src/gui/dialogs/qfiledialog.cpp | 11 +++++----- tests/auto/qfiledialog/tst_qfiledialog.cpp | 33 ++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/src/gui/dialogs/qfiledialog.cpp b/src/gui/dialogs/qfiledialog.cpp index eeb2743..d42775a 100644 --- a/src/gui/dialogs/qfiledialog.cpp +++ b/src/gui/dialogs/qfiledialog.cpp @@ -776,6 +776,7 @@ void QFileDialog::selectFile(const QString &filename) } QModelIndex index = d->model->index(filename); + QString file; if (!index.isValid()) { // save as dialog where we want to input a default value QString text = filename; @@ -790,13 +791,13 @@ void QFileDialog::selectFile(const QString &filename) ) text = text.remove(0,1); } - if (!isVisible() || !d->lineEdit()->hasFocus()) - d->lineEdit()->setText(text); + file = text; } else { - d->qFileDialogUi->listView->selectionModel()->clear(); - if (!isVisible() || !d->lineEdit()->hasFocus()) - d->lineEdit()->setText(index.data().toString()); + file = index.data().toString(); } + d->qFileDialogUi->listView->selectionModel()->clear(); + if (!isVisible() || !d->lineEdit()->hasFocus()) + d->lineEdit()->setText(file); } /** diff --git a/tests/auto/qfiledialog/tst_qfiledialog.cpp b/tests/auto/qfiledialog/tst_qfiledialog.cpp index 689f73d..16c84d8 100644 --- a/tests/auto/qfiledialog/tst_qfiledialog.cpp +++ b/tests/auto/qfiledialog/tst_qfiledialog.cpp @@ -159,6 +159,7 @@ private slots: void task218353_relativePaths(); void task251321_sideBarHiddenEntries(); void task251341_sideBarRemoveEntries(); + void task254490_selectFileMultipleTimes(); private: QByteArray userSettings; @@ -1981,5 +1982,37 @@ void tst_QFiledialog::task251341_sideBarRemoveEntries() current.rmdir("testDir"); } +void tst_QFiledialog::task254490_selectFileMultipleTimes() +{ + QString tempPath = QDir::tempPath(); + QTemporaryFile *t; + t = new QTemporaryFile; + t->open(); + QNonNativeFileDialog fd(0, "TestFileDialog"); + + fd.setDirectory(tempPath); + fd.setViewMode(QFileDialog::List); + fd.setAcceptMode(QFileDialog::AcceptSave); + fd.setFileMode(QFileDialog::AnyFile); + + //This should select the file in the QFileDialog + fd.selectFile(t->fileName()); + + //This should clear the selection and write it into the filename line edit + fd.selectFile("new_file.txt"); + + fd.show(); + QTest::qWait(250); + + QLineEdit *lineEdit = qFindChild(&fd, "fileNameEdit"); + QVERIFY(lineEdit); + QCOMPARE(lineEdit->text(),QLatin1String("new_file.txt")); + QListView *list = qFindChild(&fd, "listView"); + QVERIFY(list); + QCOMPARE(list->selectionModel()->selectedRows(0).count(), 0); + + t->deleteLater(); +} + QTEST_MAIN(tst_QFiledialog) #include "tst_qfiledialog.moc" -- cgit v0.12 From 639557d7e2df5fc1b3ffdc76188b3084c13a8fc3 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Tue, 26 May 2009 17:23:22 +0200 Subject: Fixed crash when encountering invalid forms. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Crash when replacing the QDockWidget contents widget by a widget using a container extension. Task-number: 254553 --- tools/designer/src/components/formeditor/formwindow.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tools/designer/src/components/formeditor/formwindow.cpp b/tools/designer/src/components/formeditor/formwindow.cpp index 07d785a..66bab9b 100644 --- a/tools/designer/src/components/formeditor/formwindow.cpp +++ b/tools/designer/src/components/formeditor/formwindow.cpp @@ -2136,7 +2136,10 @@ void FormWindow::layoutContainer(QWidget *w, int type) bool FormWindow::hasInsertedChildren(QWidget *widget) const // ### move { if (QDesignerContainerExtension *container = qt_extension(core()->extensionManager(), widget)) { - widget = container->widget(container->currentIndex()); + const int index = container->currentIndex(); + if (index < 0) + return false; + widget = container->widget(index); } const QWidgetList l = widgets(widget); -- cgit v0.12 From cfe54548131d78db9d58366e35e9b29e5d3ba238 Mon Sep 17 00:00:00 2001 From: Thomas Sondergaard Date: Fri, 22 May 2009 20:26:46 +0200 Subject: Updated danish translations. Added them to relevant project files. --- tools/assistant/translations/qt_help.pro | 3 +- tools/assistant/translations/translations.pro | 3 +- translations/assistant_da.ts | 606 ++++---- translations/qt_da.ts | 1978 +++++++++++++++++++++---- translations/qt_help_da.ts | 177 ++- translations/translations.pri | 2 +- 6 files changed, 2132 insertions(+), 637 deletions(-) diff --git a/tools/assistant/translations/qt_help.pro b/tools/assistant/translations/qt_help.pro index efad6bf..e6208a6 100644 --- a/tools/assistant/translations/qt_help.pro +++ b/tools/assistant/translations/qt_help.pro @@ -44,5 +44,6 @@ TRANSLATIONS=$$[QT_INSTALL_TRANSLATIONS]/qt_help_de.ts \ $$[QT_INSTALL_TRANSLATIONS]/qt_help_pl.ts \ $$[QT_INSTALL_TRANSLATIONS]/qt_help_untranslated.ts \ $$[QT_INSTALL_TRANSLATIONS]/qt_help_zh_CN.ts \ - $$[QT_INSTALL_TRANSLATIONS]/qt_help_zh_TW.ts + $$[QT_INSTALL_TRANSLATIONS]/qt_help_zh_TW.ts \ + $$[QT_INSTALL_TRANSLATIONS]/qt_help_da.ts error("This is a dummy profile to be used for translations ONLY.") diff --git a/tools/assistant/translations/translations.pro b/tools/assistant/translations/translations.pro index 58de554..8572123 100644 --- a/tools/assistant/translations/translations.pro +++ b/tools/assistant/translations/translations.pro @@ -45,4 +45,5 @@ TRANSLATIONS=$$[QT_INSTALL_TRANSLATIONS]/assistant_de.ts \ $$[QT_INSTALL_TRANSLATIONS]/assistant_pl.ts \ $$[QT_INSTALL_TRANSLATIONS]/assistant_untranslated.ts \ $$[QT_INSTALL_TRANSLATIONS]/assistant_zh_CN.ts \ - $$[QT_INSTALL_TRANSLATIONS]/assistant_zh_TW.ts + $$[QT_INSTALL_TRANSLATIONS]/assistant_zh_TW.ts \ + $$[QT_INSTALL_TRANSLATIONS]/assistant_da.ts diff --git a/translations/assistant_da.ts b/translations/assistant_da.ts index d039248..8d134fc 100644 --- a/translations/assistant_da.ts +++ b/translations/assistant_da.ts @@ -1,58 +1,77 @@ - AboutDialog - + &Close &Luk + AboutLabel + + + Warning + Advarsel + + + + Unable to launch external application. + + Kunne ikke starte ekstern applikation. + + + + + OK + + + + BookmarkDialog - - - - - + + + + + Bookmarks Favoritter - + Add Bookmark Føj til Favoritter - + Bookmark: Favorit: - + Add in Folder: Føj til mappen: - + + - + New Folder Ny mappe - + Delete Folder Slet mappe - + Rename Folder Omdøb mappe @@ -60,75 +79,79 @@ BookmarkManager - + Bookmarks Favoritter - + Remove Fjern + You are going to delete a Folder, this will also<br>remove it's content. Are you sure to continue? - Ved at slette denne mappe fjernes hele mappens<br>indhold. Ønsker du alligevel at slette? + Ved at slette denne mappe fjernes hele mappens<br>indhold. Ønsker du alligevel at slette? - - + + New Folder Ny mappe - You are about to delete a folder which means that its content<br>will also be removed. Do you want to continue? - Ved at slette denne mappe fjernes hele mappens indhold.<br>Ønsker du alligevel at slette? + Ved at slette denne mappe fjernes hele mappens indhold.<br>Ønsker du alligevel at slette? BookmarkWidget - + + Filter: + Filter: + + + Remove Fjern - + Delete Folder Slet mappe - + Rename Folder Omdøb mappe - + Show Bookmark Vis favorit - + Show Bookmark in New Tab Vis favorit pÃ¥ ny fane - + Delete Bookmark Slet favorit - + Rename Bookmark Omdøb favorit - Search for: - Søg efter: + Søg efter: - + Add Tilføj @@ -136,48 +159,48 @@ CentralWidget - + Add new page Tilføj ny side - + Close current page Luk nuværende side - + Print Document Udskriv dokument - - + + unknown ukendt - + Add New Page Tilføj ny side - + Close This Page Luk denne side - + Close Other Pages Luk de andre sider - + Add Bookmark for this Page... Føj denne side til Favoritter... - + Search Søg @@ -185,12 +208,12 @@ ContentWindow - + Open Link Ã…bn link - + Open Link in New Tab Ã…bn link pÃ¥ ny fane @@ -198,69 +221,77 @@ FilterNameDialogClass - FilterNameDialog - FilterNavnDialog + FilterNavnDialog - + Filter Name: Filternavn: + + + Add Filter Name + Tilføj filternavn + FindWidget - + + <img src=":/trolltech/assistant/images/wrap.png">&nbsp;Search wrapped + <img src=":/trolltech/assistant/images/wrap.png">&nbsp;Søgning gentaget fra start + + + Previous Forrige - + Next Næste - + Case Sensitive Der skelnes mellem store og smÃ¥ bogstaver - + Whole words Hele ord - <img src="%1">&nbsp;Search wrapped <img src=":/trolltech/assistant/images/wrap.png">&nbsp;Search wrapped - <img src="%1">&nbsp;Søgning startet forfra + <img src="%1">&nbsp;Søgning startet forfra FontPanel - + Font Skrifttype - + &Writing system &Skrivesystem - + &Family &Familie - + &Style &Stil - + &Point size &Punktstørrelse @@ -268,42 +299,41 @@ HelpViewer - + Help Hjælp - + OK - + <title>Error 404...</title><div align="center"><br><br><h1>The page could not be found</h1><br><h3>'%1'</h3></div> <title>Fejl 404...</title><div align="center"><br><br><h1>Siden blev ikke fundet</h1><br><h3>'%1'</h3></div> - + Copy &Link Location Kopiér &linkets placering - + Open Link in New Tab Ctrl+LMB Ã…bn link pÃ¥ ny fane Ctrl+LMB - + Open Link in New Tab Ã…bn link pÃ¥ ny fane - <b>Page not found:<p>%1.</p></b> - <b>Kunne ikke finde siden:<p>%1.</p></b> + <b>Kunne ikke finde siden:<p>%1.</p></b> - + Unable to launch external application. Kunne ikke starte ekstern applikation. @@ -313,17 +343,17 @@ IndexWindow - + &Look for: &Søg efter: - + Open Link Ã…bn link - + Open Link in New Tab Ã…bn link pÃ¥ ny fane @@ -331,99 +361,99 @@ InstallDialog - - + + Install Documentation Installér dokumentation - + Downloading documentation info... Downloader dokumentationsinformation... - + Download canceled. Download blev annulleret. - - - + + + Done. Færdig. - + The file %1 already exists. Do you want to overwrite it? Filen %1 findes allerede. Ønsker du at overskrive? - + Unable to save the file %1: %2. Kunne ikke gemme filen %1: %2. - + Downloading %1... Downloader %1... - - - + + + Download failed: %1. Download mislykkedes: %1. - + Documentation info file is corrupt! Dokumentationsinformationsfilen er ødelagt! - + Download failed: Downloaded file is corrupted. Download mislykkedes: Den downloadede fil er ødelagt. - + Installing documentation %1... Installerer dokumentation %1... - + Error while installing documentation: %1 Der opstod fejl under installation af dokumentation: %1 - + Available Documentation: Tilgængeligt dokumentation: - + Install Installér - + Cancel Annuller - + Close Luk - + Installation Path: Installationssti: - + ... @@ -431,60 +461,62 @@ MainWindow - - + + Index Indeks - - + + Contents Indhold - - + + Bookmarks Favoritter - - + Search Søg - - - + + + Qt Assistant - - + + Unfiltered Ufiltreret + Page Set&up... - Side&opsætning... + Side&opsætning... + Print Preview... - Vis udskrift... + Vis udskrift... + &Print... - &Udskriv... + &Udskriv... CTRL+P Ctrl+U - + New &Tab &Ny Fane @@ -493,7 +525,7 @@ Ctrl+N - + &Close Tab &Luk fane @@ -502,340 +534,326 @@ Ctrl+L - + &Quit &Afslut + CTRL+Q - Ctrl+A + Ctrl+A + &Copy selected Text - &Kopiér markeret tekst + &Kopiér markeret tekst Ctrl+C Ctrl+K - + &Find in Text... &Find i tekst... - - Ctrl+F - - - - + Find &Next Find N&æste - - F3 - - - - + Find &Previous Find fo&rrige - - Shift+F3 - - - - + Preferences... Indstillinger... - + Zoom &in Zoom &ind - - Ctrl++ - - - - + Zoom &out Zoom u&d - - Ctrl+- - - - - + Normal &Size Normal &størrelse - + Ctrl+0 - + + ALT+C + + + + + ALT+I + + + + + ALT+S + + + + &Home &Hjem - + Ctrl+Home - + &Back &Tilbage - + &Forward Fr&em + Sync with Table of Contents - Synkronisér med Indholdsfortegnelse + Synkronisér med Indholdsfortegnelse - + Next Page Næste side - + Ctrl+Alt+Right Ctrl+Alt+Højre - + Previous Page Forrige side - + Ctrl+Alt+Left Ctrl+Alt+Venstre - + Add Bookmark... Føj til Favoritter... - + About... Om... - + Navigation Toolbar Navigationsværktøjslinie - + Toolbars Værktøjslinier - + Filter Toolbar Filtrer værktøjslinie - + Filtered by: Filtreret efter: - + Address Toolbar Adresseværktøjslinie - + Address: Adresse: - + Could not find the associated content item. Det tilhørende indholdselement kunne ikke findes. - - Open Source Edition - - - - This version of Qt Assistant is part of the Qt Open Source Edition, for use in the development of Open Source applications. Qt is a comprehensive C++ framework for cross-platform application development. - Denne version af Qt Assistant er en del af Qt Open Source Edition til brug med henblik pÃ¥ udvikling af Open Source-applikationer. Qt er et omfattende C++ framework for cross-platform applikationsudvikling. + Denne version af Qt Assistant er en del af Qt Open Source Edition til brug med henblik pÃ¥ udvikling af Open Source-applikationer. Qt er et omfattende C++ framework for cross-platform applikationsudvikling. - This program is licensed to you under the terms of the Qt Commercial License Agreement. For details, see the file LICENSE that came with this software distribution. - Dette program er omfattet af Qt Commercial License Agreement. Se filen LICENCE, der var vedlagt denne software-distribution, for yderligere detaljer. + Dette program er omfattet af Qt Commercial License Agreement. Se filen LICENCE, der var vedlagt denne software-distribution, for yderligere detaljer. - + About %1 Om %1 - + Updating search index Opdaterer søgeindeks - + Looking for Qt Documentation... Søger efter Qt-dokumentation... - + &Window &Vindue - + Minimize Minimér - + Ctrl+M Ctrl+M - + Zoom - + &File &Filer - + &Edit &Redigér - + &View &Vis - + &Go &GÃ¥ til - + &Bookmarks F&avoritter - + &Help &Hjælp - - You need a commercial Qt license for development of proprietary (closed source) applications. Please see <a href="http://trolltech.com/company/about/businessmodel">http://trolltech.com/company/about/businessmodel</a> for an overview of Qt licensing. - - - + ALT+O - Alt+F + Alt+F + CTRL+D - Ctrl+Ø + Ctrl+Ø Ctrl+P Ctrl+U - Ctrl+T - Ctrl+N + Ctrl+N - Ctrl+W - Ctrl+L + Ctrl+L - Ctrl+Q - Ctrl+A + Ctrl+A - Alt+C - Alt+L - - - - Alt+I - + Alt+L - Alt+O - Alt+F - - - - Alt+S - + Alt+F - Ctrl+D - Ctrl+Ø + Ctrl+Ø PreferencesDialog - - - + + Add Documentation Tilføj dokumentation - + Qt Compressed Help Files (*.qch) Qt komprimeret hjælpefil (*.qch) - + The specified file is not a valid Qt Help File! Den anførte fil er ikke en gyldig Qt hjælpefil! - + The namespace %1 is already registered! Navnerummet %1 er allerede registreret! - + + Remove Documentation + Fjern dokumentation + + + + Some documents currently opened in Assistant reference the documentation you are attempting to remove. Removing the documentation will close those documents. + Nogle dokumenter der pt er Ã¥bne i Assistant refererer til den dokumentation du prøver at fjerne. Fjernelse af dokumentation vil resultere i lukning af disse dokumenter. + + + + Cancel + Annuller + + + + OK + + + + Use custom settings Benyt brugerdefineret opsætning @@ -843,158 +861,170 @@ PreferencesDialogClass - + Preferences Indstillinger - + Fonts Skrifttyper - + Font settings: Indstillinger for skrifttype: - + Browser - + Application Applikation - + Filters Filtre - + Filter: Filter: - + Attributes: Attributter: - + 1 - + Add Tilføj - - + Remove Fjern - + Documentation Dokumentation - + Registered Documentation: Registreret dokumentation: - + Add... Tilføj... - Network - Netværk + Netværk - Use Http Proxy - Benyt Http Proxy + Benyt Http Proxy - - Http Proxy: - + + Options + Indstillinger - - Port: - + + Homepage + Hjemmeside + + + + Current Page + Nuværende side + + + + Restore to default + Nulstil til default QObject - + The specified collection file does not exist! Den angivne hjælpesamling findes ikke! - + Missing collection file! Hjælpesamling mangler! - + Invalid URL! Ugyldig URL! - + Missing URL! URL mangler! - - - + + + Unknown widget: %1 Ukendt widget: %1 - - - + + + Missing widget! Widget mangler! - - + + The specified Qt help file does not exist! Den angivne Qt-hjælpefil findes ikke! - - + + Missing help file! Hjælpefilen mangler! - + + Missing filter argument! + Manglende filterargument! + + + Unknown option: %1 Ukendt parameter: %1 - - + + Qt Assistant - + Could not register documentation file %1 @@ -1007,12 +1037,12 @@ Reason: %2 - + Documentation successfully registered. Dokumentationen blev registreret. - + Could not unregister documentation file %1 @@ -1025,18 +1055,23 @@ Reason: %2 - + Documentation successfully unregistered. Dokumentationen blev afregistreret. - + + Cannot load sqlite database driver! + Kan ikke indlæse sqlite database-driver! + + + The specified collection file could not be read! Den angivne hjælpesamling kunne ikke læses! - - + + Bookmark Favorit @@ -1044,11 +1079,10 @@ Reason: QtDocInstaller - The file %1 could not be registered successfully! Reason: %2 - Filen %1 kunne ikke registreres! + Filen %1 kunne ikke registreres! Ã…rsag: %2 @@ -1056,12 +1090,12 @@ Reason: %2 RemoteControl - + Debugging Remote Control - + Received Command: %1 %2 Modtaget kommando: %1 %2 @@ -1069,56 +1103,54 @@ Reason: %2 SearchWidget - + &Copy &Kopiér - + Copy &Link Location Kopiér &linkets placering - - + Open Link in New Tab Ã…bn link pÃ¥ ny fane - + Select All Markér alt - Open Link - Ã…bn link + Ã…bn link TopicChooser - + Choose a topic for <b>%1</b>: Vælg et emne for <b>%1</b>: - + Choose Topic Vælg emne - + &Topics &Emner - + &Display &Vis - + &Close &Luk diff --git a/translations/qt_da.ts b/translations/qt_da.ts index 9350687..105b572 100644 --- a/translations/qt_da.ts +++ b/translations/qt_da.ts @@ -4,15 +4,17 @@ AudioOutput - + <html>The audio playback device <b>%1</b> does not work.<br/>Falling back to <b>%2</b>.</html> <html>Audio-playback-enheden<b>%1</b> virker ikke.<br/>Falder tilbage til <b>%2</b>.</html> + <html>Switching to the audio playback device <b>%1</b><br/>which just became available and has higher preference.</html> - <html>Skifter til audio-playback-enheden, <b>%1</b><br/>der lige er blevet tilgængeligt og har en højere præference.</html> + <html>Skifter til audio-playback-enheden, <b>%1</b><br/>der lige er blevet tilgængelig og har en højere præference.</html> + Revert back to device '%1' GÃ¥ tilbage til enheden '%1' @@ -20,7 +22,7 @@ CloseButton - + Close Tab Luk fane @@ -28,27 +30,32 @@ Phonon:: - + Notifications Meddelelser + Music Musik + Video + Communication Kommunikation + Games Spil + Accessibility Tilgængelighed @@ -56,13 +63,14 @@ Phonon::Gstreamer::Backend - + Warning: You do not seem to have the package gstreamer0.10-plugins-good installed. Some video features have been disabled. Advarsel: Det ser ikke ud til, at gstreamer0.10-plugins-good pakken er installeret. Nogle videofunktioner er deaktiveret. + Warning: You do not seem to have the base GStreamer plugins installed. All audio and video support has been disabled Advarsel: Det ser ikke ud til, at base GStreamer plugins er installeret. @@ -72,7 +80,7 @@ Phonon::Gstreamer::MediaObject - + Cannot start playback. Check your Gstreamer installation and make sure you @@ -83,26 +91,39 @@ Tjek Gstreamer-installationen og kontrollér, at libgstreamer-plugins-base er installeret. + A required codec is missing. You need to install the following codec(s) to play this content: %0 Der mangler et codec. Følgende codecs skal installeres for at afspille dette indhold: %0 + + + + + + + + Could not open media source. Kunne ikke Ã¥bne mediekilden. + Invalid source type. Ugyldig kilde. + Could not locate media source. Kunne ikke lokalisere mediekilden. + Could not open audio device. The device is already in use. Kunne ikke Ã¥bne lydenheden. Enheden er allerede i brug. + Could not decode media source. Kunne ikke afkode mediekilden. @@ -110,10 +131,15 @@ libgstreamer-plugins-base er installeret. Phonon::VolumeSlider + + Volume: %1% + + + Use this slider to adjust the volume. The leftmost position is 0%, the rightmost is %1% Anvend denne skyder til at indstille lydstyrken. Længst til venstre er 0% og længst til højre er %1% @@ -121,11 +147,12 @@ libgstreamer-plugins-base er installeret. Q3Accel - + %1, %2 not defined %1, %2 ikke definerede + Ambiguous %1 not handled Tvetydig %1 ikke behandlet @@ -133,23 +160,27 @@ libgstreamer-plugins-base er installeret. Q3DataTable - + True Sandt + False Falsk + Insert Indsæt + Update Opdater + Delete Slet @@ -157,242 +188,313 @@ libgstreamer-plugins-base er installeret. Q3FileDialog - + Copy or Move a File Kopiér eller flyt en fil + Read: %1 Læs: %1 + + Write: %1 Skriv: %1 + + Cancel Annuller - + + + + All Files (*) Alle filer (*) + Name Navn + Size Størrelse + Type + Date Dato + Attributes Attributter + + &OK &OK + Look &in: Kig &i: + + + File &name: Fil&navn: + File &type: Fil&type: + Back Tilbage + One directory up En mappe op + Create New Folder Opret ny folder + List View Listevisning + Detail View Detaljevisning + Preview File Info Vis filinformation + Preview File Contents Vis filindhold + Read-write Læs-skriv + Read-only Skrivebeskyttet + Write-only Write-only + Inaccessible Utilgængelig + Symlink to File Symlink til Fil + Symlink to Directory Symlink til katalog + Symlink to Special Symlink til Speciel + File Fil + Dir Katalog + Special Speciel - + + + Open Ã…bn - + + Save As Gem som + + + &Open &Ã…bn + + &Save &Gem + &Rename &Omdøb + &Delete &Slet + R&eload Gen&indlæs + Sort by &Name Sortér efter n&avn + Sort by &Size Sortér efter s&tørrelse + Sort by &Date Sortér efter &dato + &Unsorted &Usorteret + Sort Sortér + Show &hidden files Vis s&kjulte filer + the file filen + the directory kataloget + the symlink symlinket + Delete %1 Slet %1 + <qt>Are you sure you wish to delete %1 "%2"?</qt> <qt>Er du sikker pÃ¥, at du vil slette %1 "%2"?</qt> + &Yes &Ja + &No &Nej + New Folder 1 Ny folder 1 + New Folder Ny folder + New Folder %1 Ny folder %1 + Find Directory Find katalog + + Directories Kataloger + Directory: Katalog: + + Error Fejl + %1 File not found. Check path and filename. @@ -401,14 +503,17 @@ Filen blev ikke fundet. Kontrollér sti og filnavn. + All Files (*.*) Alle filer (*.*) + Open Ã…bn + Select a Directory Vælg et katalog @@ -416,24 +521,29 @@ Kontrollér sti og filnavn. Q3LocalFs + + Could not read directory %1 Kunne ikke læse katalog %1 + Could not create directory %1 Kunne ikke oprette katalog %1 + Could not remove file or directory %1 Kunne ikke fjerne fil eller katalog %1 + Could not rename %1 to @@ -444,12 +554,14 @@ to %2 + Could not open %1 Kunne ikke Ã¥bne %1 + Could not write %1 Kunne ikke skrive @@ -459,11 +571,12 @@ to Q3MainWindow - + Line up Linie op + Customize... Tilpas... @@ -471,7 +584,7 @@ to Q3NetworkProtocol - + Operation stopped by the user Brugeren stoppede handlingen @@ -479,6 +592,8 @@ to Q3ProgressDialog + + Cancel Annuller @@ -486,22 +601,28 @@ to Q3TabDialog + + OK + Apply Udfør + Help Hjælp + Defaults Standarder + Cancel Annuller @@ -509,31 +630,38 @@ to Q3TextEdit - + &Undo &Fortryd + &Redo &Gendan + Cu&t &Klip + &Copy K&opiér + &Paste &Sæt ind + Clear Ryd + + Select All Markér alt @@ -541,55 +669,67 @@ to Q3TitleBar - + System + Restore up Gendan op + Minimize Minimer + Restore down Gendan ned + Maximize Maksimér + Close Luk + Contains commands to manipulate the window Indeholder kommandoer til indstilling af vinduet + Puts a minimized back to normal Sætter et minimeret vindue til normal størrelse + Moves the window out of the way Flytter vinduet væk + Puts a maximized window back to normal Sætter et maksimeret vindue til normal størrelse + Makes the window full screen Gør vinduet til fuld skærm + Closes the window Lukker vinduet + Displays the name of the window and contains controls to manipulate it Viser vinduets navn og indeholder kontroller til indstilling af vinduet @@ -597,7 +737,7 @@ to Q3ToolBar - + More... Mere... @@ -605,38 +745,51 @@ to Q3UrlOperator + + + The protocol `%1' is not supported Protokollen '%1' understøttes ikke + The protocol `%1' does not support listing directories Protokollen '%1' understøtter ikke opremsning af kataloger + The protocol `%1' does not support creating new directories Protokollen '%1' understøtter ikke oprettelse af nye kataloger + The protocol `%1' does not support removing files or directories Protokollen '%1' understøtter ikke, at filer eller kataloger fjernes + The protocol `%1' does not support renaming files or directories Protokollen '%1' understøtter ikke, at filer eller kataloger omdøbes + The protocol `%1' does not support getting files Protokollen '%1' understøtter ikke hentning af filer + The protocol `%1' does not support putting files Protokollen '%1' understøtter ikke upload af filer + + The protocol `%1' does not support copying or moving files or directories Protokollen '%1' understøtter ikke kopiering eller flytning af filer eller kataloger + + (unknown) (ukendt) @@ -644,23 +797,27 @@ to Q3Wizard - + &Cancel &Annuller + < &Back < &Tilbage + &Next > &Næste > + &Finish &Udfør + &Help &Hjælp @@ -668,31 +825,44 @@ to QAbstractSocket + + + + Host not found Host blev ikke fundet - + + + Connection refused Forbindelse afvist + Connection timed out Forbindelsen timed out + + + Operation on socket is not supported Socket-operation ikke understøttet + Socket operation timed out Socket-operation timed out + Socket is not connected Socket ikke forbundet + Network unreachable Netværket er ikke tilgængeligt @@ -700,15 +870,17 @@ to QAbstractSpinBox - + &Step up &Trin op + Step &down Trin &ned + &Select All &Vælg alle @@ -716,27 +888,28 @@ to QApplication - + Activate Aktivér - + Executable '%1' requires Qt %2, found Qt %3. Eksekverbar '%1' kræver Qt %2, ikke fundet Qt %3. + Incompatible Qt Library Error Inkompatibel Qt Library fejl - + QT_LAYOUT_DIRECTION Translate this string to the string 'LTR' in left-to-right languages or to 'RTL' in right-to-left languages (such as Hebrew and Arabic) to get proper widget layout. - + Activates the program's main window Aktiverer programmets hovedvindue @@ -744,18 +917,22 @@ to QAxSelect + Select ActiveX Control Vælg ActiveX-kontrol + OK + &Cancel &Annuller + COM &Object: COM &Objekt: @@ -763,15 +940,17 @@ to QCheckBox - + Uncheck Fjern markering + Check Kryds af + Toggle SlÃ¥ til/fra @@ -779,47 +958,57 @@ to QColorDialog - + Hu&e: Ton&e: + &Sat: &Mæt: + &Val: &Vær: + &Red: &Rød: + &Green: &Grøn: + Bl&ue: Bl&Ã¥: + A&lpha channel: Al&fa-kanal: + Select Color Vælg farve + &Basic colors &Basisfarver + &Custom colors &Egne farver + &Add to Custom Colors &Føj til egne farver @@ -827,20 +1016,23 @@ to QComboBox + + Open Ã…bn - + False Falsk + True Sandt - + Close Luk @@ -848,17 +1040,19 @@ to QCoreApplication - + %1: key is empty QSystemSemaphore %1: nøgle er tom + %1: unable to make key QSystemSemaphore %1: kunne ikke lave nøgle + %1: ftok failed QSystemSemaphore %1: ftok mislykkedes @@ -867,19 +1061,22 @@ to QDB2Driver - + Unable to connect Kunne ikke skabe forbindelse + Unable to commit transaction Kunne ikke gennemføre transaktion + Unable to rollback transaction Kunne ikke tilbagetrække transaktion + Unable to set autocommit Kunne ikke aktivere autocommit @@ -887,26 +1084,33 @@ to QDB2Result + + Unable to execute statement Kunne ikke udføre statement + Unable to prepare statement Kunne ikke forberede udsagn + Unable to bind variable Kunne ikke binde variabel + Unable to fetch record %1 Kunne ikke hente post %1 + Unable to fetch next Kunne ikke hente næste + Unable to fetch first Kunne ikke hente første @@ -914,19 +1118,22 @@ to QDateTimeEdit - + AM + am + PM + pm @@ -934,15 +1141,17 @@ to QDial - + QDial + SpeedoMeter Speedometer + SliderHandle @@ -950,11 +1159,12 @@ to QDialog - + What's This? Hvad er dette? + Done Udført @@ -962,100 +1172,124 @@ to QDialogButtonBox - + + + OK - + &OK + &Save &Gem + Save Gem + Open Ã…bn + &Cancel &Annuller + Cancel Annuller + &Close &Luk + Close Luk + Apply Udfør + Reset Nulstil + Help Hjælp + Don't Save Gem ikke + Discard Kassér + &Yes &Ja + Yes to &All Ja til &alle + &No &Nej + N&o to All Ne&j til alle + Save All Gem alle + Abort Afbryd + Retry Prøv igen + Ignore Ignorer + Restore Defaults Gendan standardværdier + Close without Saving Luk uden at gemme @@ -1063,25 +1297,29 @@ to QDirModel - + Name Navn + Size Størrelse + Kind Match OS X Finder Type + Type All other platforms + Date Modified Ændringsdato @@ -1089,15 +1327,17 @@ to QDockWidget - + Close Luk + Dock LÃ¥st + Float Flydende @@ -1105,10 +1345,12 @@ to QDoubleSpinBox + More Mere + Less Mindre @@ -1116,23 +1358,27 @@ to QErrorMessage - + Debug Message: Debug-besked: + Warning: Advarsel: + Fatal Error: Fatal fejl: + &Show this message again &Vis denne besked igen + &OK @@ -1140,22 +1386,33 @@ to QFile + + Destination file exists Destinationsfil findes + + Cannot remove source file + Kan ikke fjerne kildefil + + + Cannot open %1 for input Kan ikke Ã¥bne %1 til input + Cannot open for output Kan ikke Ã¥bne til output + Failure to write block Kunne ikke skrive blok + Cannot create %1 for output Kunne ikke oprette %1 til output @@ -1163,32 +1420,44 @@ to QFileDialog + + All Files (*) Alle filer (*) + Directories Kataloger + + + + &Open &Ã…bn + + &Save &Gem + Open Ã…bn + %1 already exists. Do you want to replace it? %1 findes allerede. Ønsker du at erstatte den? + %1 File not found. Please verify the correct file name was given. @@ -1197,47 +1466,64 @@ Filen kunne ikke findes. Kontrollér, at det rigtige filnavn er indtastet. - + My Computer Min computer + &Rename &Omdøb + &Delete &Slet + Show &hidden files Vis s&kjulte filer + + Back Tilbage + + Parent Directory Ovenliggende katalog + + List View Listevisning + + Detail View Detaljevisning + + Files of type: Filer af typen: + + Directory: Katalog: + + %1 Directory not found. Please verify the correct directory name was given. @@ -1246,84 +1532,105 @@ Katalog kunne ikke findes. Kontrollér, at det rigtige katalognavn er indtastet. + '%1' is write protected. Do you want to delete it anyway? '%1' er skrivebeskyttet. Ønsker du alligevel at slette? + Are sure you want to delete '%1'? Er du sikker pÃ¥, at '%1' skal slettes? + Could not delete directory. Kunne ikke slette kataloget. + Recent Places Aktuelle steder - + All Files (*.*) Alle filer (*.*) + Save As Gem som - + Drive Drev + + File Fil + Unknown Ukendt + Find Directory Find katalog + Show Vis + + Forward Frem - + New Folder Ny folder + &New Folder &Ny folder + + &Choose &Vælg - + Remove Fjern + + File &name: &Filnavn: + + Look in: Søg i: + + Create New Folder Opret ny folder @@ -1331,62 +1638,74 @@ Do you want to delete it anyway? QFileSystemModel - + Invalid filename Ugyldigt filnavn + <b>The name "%1" can not be used.</b><p>Try using another name, with fewer characters or no punctuations marks. <b>Navnet, %1, kan ikke benyttes.</b><p>Brug et andet navn med færre tegn og ingen kommatering. + Name Navn + Size Størrelse + Kind Match OS X Finder Type + Type All other platforms + Date Modified Ændringsdato - + My Computer Min computer + Computer + %1 TB %1 TB + %1 GB %1 GB + %1 MB %1 MB + %1 KB %1 KB' + %1 bytes %1 bytes @@ -1394,166 +1713,216 @@ Do you want to delete it anyway? QFontDatabase + + Normal + + + Bold Fed + + Demi Bold + + + Black Sort + Demi + + Light Lys + + Italic Kursiv + + Oblique SkrÃ¥t + Any Alle + Latin + Greek Græsk + Cyrillic Kyrillisk + Armenian Armensk + Hebrew Hebræisk + Arabic Arabisk + Syriac Syrisk + Thaana + Devanagari + Bengali Bengalsk + Gurmukhi + Gujarati + Oriya + Tamil + Telugu + Kannada + Malayalam + Sinhala + Thai Thailandsk + Lao + Tibetan Tibetansk + Myanmar + Georgian georgisk + Khmer + Simplified Chinese Forenklet kinesisk + Traditional Chinese Traditionelt kinesisk + Japanese Japansk + Korean Koreansk + Vietnamese Vietnamesisk + Symbol + Ogham + Runic @@ -1561,39 +1930,48 @@ Do you want to delete it anyway? QFontDialog - + &Font S&krifttype + Font st&yle S&til + &Size &Størrelse + Effects Effekter + Stri&keout &Overstreget + &Underline &Understreg + Sample Eksempel + Wr&iting System Skr&ivesystem + + Select Font Vælg skrifttype @@ -1601,116 +1979,145 @@ Do you want to delete it anyway? QFtp - + + Not connected Ingen forbindelse - + + Host %1 not found Vært %1 ikke fundet - + + Connection refused to host %1 Forbindelse til vært %1 afvist + Connection timed out to host %1 Forbindelsen timed out til host %1 + + + Connected to host %1 Tilsluttet vært %1 + + Connection refused for data connection Dataforbindelse afvist + + + + Unknown error Ukendt fejl - + + Connecting to host failed: %1 Forbindelse til vært mislykkedes: %1 - + + Login failed: %1 Login mislykkedes: %1 - + + Listing directory failed: %1 Opremsning af katalogindhold mislykkedes: %1 - + + Changing directory failed: %1 Ændring af katalog mislykkedes: %1 - + + Downloading file failed: %1 Downloading af fil mislykkedes: %1 - + + Uploading file failed: %1 Uploading af fil mislykkedes: %1 - + + Removing file failed: %1 Det mislykkedes at fjerne fil: %1 - + + Creating directory failed: %1 Oprettelse af katalog mislykkedes: %1 - + + Removing directory failed: %1 Det mislykkedes at fjerne katalog: %1 + + + Connection closed Forbindelse lukket + Host %1 found Vært %1 fundet + Connection to %1 closed Forbindelse til %1 lukket + Host found Vært fundet + Connected to host Tilsluttet vært @@ -1718,7 +2125,7 @@ Do you want to delete it anyway? QHostInfo - + Unknown error Ukendt fejl @@ -1726,14 +2133,29 @@ Do you want to delete it anyway? QHostInfoAgent + + + + + + + + Host not found Vært ikke fundet + + + + Unknown address type Ukendt adressetype + + + Unknown error Ukendt fejl @@ -1741,116 +2163,155 @@ Do you want to delete it anyway? QHttp + + + + Unknown error Ukendt fejl + + Request aborted Forespørgsel blev annulleret - + + No server set to connect to Ingen server at forbinde til - + + Wrong content length Forkert indholdslængde - + + Server closed connection unexpectedly Serveren afsluttede uventet forbindelsen + + Unknown authentication method + Ukendt autentifikationsmetode + + + Error writing response to device Skrivefejl mens der blev skrevet til enheden - + + Connection refused Forbindelse afvist - + + + Host %1 not found Vært %1 ikke fundet - + + + + HTTP request failed HTTP anmodning mislykkedes - + + Invalid HTTP response header Ugyldig HTTP-svar-header + + + + Invalid HTTP chunked body Ugyldig HTTP chunked body - + Host %1 found Vært %1 fundet + Connected to host %1 Tilsluttet vært %1 + Connection to %1 closed Forbindelse til %1 lukket + Host found Vært fundet + Connected to host Tilsluttet vært - + + Connection closed Forbindelse lukket + Proxy authentication required Kræver proxy-autentificering + Authentication required Autentificering pÃ¥krævet + Connection refused (or timed out) Forbindelse blev afvist (eller tid udløb) - + Proxy requires authentication Proxy kræver autentificering + Host requires authentication Vært kræver autentificering + Data corrupted Data er ødelagt + Unknown protocol specified En ukendt protokol blev angivet + SSL handshake failed SSL handshake mislykkedes + HTTPS connection requested but SSL support not compiled in Der blevet anmodet om en HTTPS-forbindelse, men SSL understøttelse er ikke kompileret ind @@ -1858,38 +2319,47 @@ Do you want to delete it anyway? QHttpSocketEngine + Did not receive HTTP response from proxy Modtog ikke HTTP-svar fra proxy + Error parsing authentication request from proxy Fejl under fortolking af autentificeringsanmodning fra proxy + Authentication required Autentificering pÃ¥krævet + Proxy denied connection Proxy nægtede forbindelse + Error communicating with HTTP proxy Fejl under kommunikation med HTTP-proxy + Proxy server not found Proxy-server kunne ikke findes + Proxy connection refused Proxy-forbindelse nægtede + Proxy server connection timed out Proxy-serverforbindelse timed out + Proxy connection closed prematurely Proxy-forbindelse afsluttede i utide @@ -1897,19 +2367,22 @@ Do you want to delete it anyway? QIBaseDriver - + Error opening database Der opstod fejl ved Ã¥bning af database + Could not start transaction Kunne ikke pÃ¥begynde transaktionen + Unable to commit transaction Kunne ikke gennemføre transaktionen + Unable to rollback transaction Kunne ikke tilbagetrække transaktionen @@ -1917,70 +2390,89 @@ Do you want to delete it anyway? QIBaseResult + Unable to create BLOB Kunne ikke oprette BLOB + Unable to write BLOB Kunne ikke skrive BLOB + Unable to open BLOB Kunne ikke Ã¥bne BLOB + Unable to read BLOB Kunne ikke læse BLOB + + Could not find array Kunne ikke finde array + Could not get array data Kunne ikke hente arraydata + Could not get query info Kunne ikke hente forespørgselsinfo + Could not start transaction Kunne ikke pÃ¥begynde transaktionen + Unable to commit transaction Kunne ikke gennemføre transaktionen + Could not allocate statement Kunne ikke allokere statement + Could not prepare statement Kunne ikke forberede udsagn + + Could not describe input statement Kunne ikke beskrive input-statement + Could not describe statement Kunne ikke beskrive statement + Unable to close statement Kunne ikke lukke udsagn + Unable to execute query Kunne ikke udføre forespørgsel + Could not fetch next item Kunne ikke hente næste element + Could not get statement info Kunne ikke hente udsagnsinformation @@ -1988,24 +2480,27 @@ Do you want to delete it anyway? QIODevice - + Permission denied Tilladelse nægtet + Too many open files Der er for mange Ã¥bne filer + No such file or directory Fil eller katalog findes ikke + No space left on device Ingen plads tilbage pÃ¥ enheden - + Unknown error Ukendt fejl @@ -2013,19 +2508,22 @@ Do you want to delete it anyway? QInputContext - + XIM + XIM input method XIM input-metode + Windows input method Windows input-metode + Mac OS X input method Mac OS X input-metode @@ -2033,7 +2531,7 @@ Do you want to delete it anyway? QInputDialog - + Enter a value: Indtast en værdi: @@ -2041,55 +2539,66 @@ Do you want to delete it anyway? QLibrary - + Could not mmap '%1': %2 + Plugin verification data mismatch in '%1' Plugin-verifikationsdata er sat forkert sammen i '%1' + Could not unmap '%1': %2 Der var ikke muligt at lave unmap pÃ¥ '%1': %2 + The plugin '%1' uses incompatible Qt library. (%2.%3.%4) [%5] Plugin '%1' bruger inkompatibelt Qt-bibliotek. (%2.%3.%4) [%5] + The plugin '%1' uses incompatible Qt library. Expected build key "%2", got "%3" Plugin '%1' bruger inkompatibelt Qt-bibliotek. Forventet build key "%2", hentede "%3"' + Unknown error Ukendt fejl' - + + The shared library was not found. DSO blev ikke fundet. + The file '%1' is not a valid Qt plugin. Filen '%1' er ikke et gyldigt Qt-plugin. + The plugin '%1' uses incompatible Qt library. (Cannot mix debug and release libraries.) Plugin '%1' bruger inkompatibelt Qt-bibliotek. (Ikke muligt at mikse debug og release-biblioteker) - + + Cannot load library %1: %2 Kan ikke indlæse bibliotek %1: %2 - + + Cannot unload library %1: %2 Kan ikke afregistrere bibliotek %1: %2 - + + Cannot resolve symbol "%1" in %2: %3 Kan ikke løse symbol "%1" i %2: %3 @@ -2097,31 +2606,37 @@ Do you want to delete it anyway? QLineEdit - + &Undo &Fortryd + &Redo &Gendan + Cu&t K&lip + &Copy &Kopiér + &Paste &Sæt ind + Delete Slet + Select All Markér alt @@ -2129,20 +2644,24 @@ Do you want to delete it anyway? QLocalServer - + + %1: Name error %1: Navnefejl + %1: Permission denied %1: Tilladelse nægtet + %1: Address in use %1: Adresse i brug - + + %1: Unknown error %2 %1: Ukendt fejl %2 @@ -2150,54 +2669,70 @@ Do you want to delete it anyway? QLocalSocket - + + %1: Connection refused %1: Forbindelse afvist - + + %1: Remote closed %1: Den anden ende lukkede + + + + %1: Invalid name %1: Ugyldigt navn - + + %1: Socket access error %1: Fejl i socket-adgang - + + %1: Socket resource error %1: Fejl i socket-ressource - + + %1: Socket operation timed out %1: Socket-handling timed out - + + %1: Datagram too large %1: Datagram er for stort + + + %1: Connection error %1: Forbindelsesfejl - + + %1: The socket operation is not supported %1: Socket-handlingen understøttes ikke + %1: Unknown error %1: Ukendt fejl - + + %1: Unknown error %2 %1: Ukendt fejl %2 @@ -2205,23 +2740,27 @@ Do you want to delete it anyway? QMYSQLDriver - + Unable to open database ' Kunne ikke Ã¥bne databasen ' + Unable to connect Kunne ikke forbinde + Unable to begin transaction Kunne ikke pÃ¥begynde transaktionen + Unable to commit transaction Kunne ikke gennemføre transaktionen + Unable to rollback transaction Kunne ikke tilbagetrække transaktionen @@ -2229,46 +2768,59 @@ Do you want to delete it anyway? QMYSQLResult + Unable to fetch data Kunne ikke hente data + Unable to execute query Kunne ikke udføre forespørgsel + Unable to store result Kunne ikke gemme resultatet + + Unable to prepare statement Kunne ikke forberede udsagn + Unable to reset statement Kunne ikke nulstille udsagn + Unable to bind value Kunne ikke tildele værdi + Unable to execute statement Kunne ikke udføre udsagn + + Unable to bind outvalues Kunne ikke binde udværdier + Unable to store statement results Kunne ikke gemme udsagnsresultater + Unable to execute next query Kunne ikke udføre næste forespørgsel + Unable to store next result Kunne ikke gemme næste resultat @@ -2276,7 +2828,7 @@ Do you want to delete it anyway? QMdiArea - + (Untitled) (Uden titel) @@ -2284,75 +2836,92 @@ Do you want to delete it anyway? QMdiSubWindow - + %1 - [%2] + Close Luk + Minimize Minimér + Restore Down Gendan Ned + &Restore &Gendan + &Move &Flyt + &Size &Størrelse + Mi&nimize Mi&nimér + Ma&ximize Ma&ksimér + Stay on &Top Bliv &oppe + &Close &Luk + - [%1] + Maximize Maksimér + Unshade Fjern skygge + Shade Skygge + Restore Gendan + Help Hjælp + Menu @@ -2360,14 +2929,21 @@ Do you want to delete it anyway? QMenu + + Close Luk + + Open Ã…bn + + + Execute Udfør @@ -2375,42 +2951,55 @@ Do you want to delete it anyway? QMessageBox + Help Hjælp + + + + OK + + <h3>About Qt</h3><p>This program uses Qt version %1.</p><p>Qt is a C++ toolkit for cross-platform application development.</p><p>Qt provides single-source portability across MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, and all major commercial Unix variants. Qt is also available for embedded devices as Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt is available under three different licensing options designed to accommodate the needs of our various users.</p>Qt licensed under our commercial license agreement is appropriate for development of proprietary/commercial software where you do not want to share any source code with third parties or otherwise cannot comply with the terms of the GNU LGPL version 2.1 or GNU GPL version 3.0.</p><p>Qt licensed under the GNU LGPL version 2.1 is appropriate for the development of Qt applications (proprietary or open source) provided you can comply with the terms and conditions of the GNU LGPL version 2.1.</p><p>Qt licensed under the GNU General Public License version 3.0 is appropriate for the development of Qt applications where you wish to use such applications in combination with software subject to the terms of the GNU GPL version 3.0 or where you are otherwise willing to comply with the terms of the GNU GPL version 3.0.</p><p>Please see <a href="http://www.qtsoftware.com/products/licensing">www.qtsoftware.com/products/licensing</a> for an overview of Qt licensing.</p><p>Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).</p><p>Qt is a Nokia product. See <a href="http://www.qtsoftware.com/qt/">www.qtsoftware.com/qt</a> for more information.</p> + <h3>Om Qt</h3><p>Dette program anvender Qt version %1.</p><p>Qt er et C++ toolkit til cross-platform applikationsudvikling.</p><p>Qt tilbyder single-source portabilitet til MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, og alle større kommercielle Unix-varianter. Qt er ogsÃ¥ tilgængeligt til indlejrede systemer som Qt for Embedded Linux and Qt for Windows CE.</p>Qt er tilgængeligt under tre forskellige licenser skabt med henblik pÃ¥ at imødekomme forskellige brugeres behov.</p><p>Qt licenseret under vores kommercielle licensaftale er passende for udvikling af proprietær/kommerciel software, hvor du ikke ønsker at dele sourcekode med tredie part, eller pÃ¥ anden vis ikke kan tiltræde vilkÃ¥rerne i GNU LGPL version 2.1 eller GNU GPL version 3.0</p><p>Qt licenseret under GLU General Public License version 3.0 er passende for udvikling af Qt applikationer, hvor du ønsker at bruge softwaren i kombination med software under vilkÃ¥rerne i GNU GPL version 3.0, eller hvor du ellers er villig til at overholde vilkÃ¥rerne i GNU GPL version 3.0</p><p>See venligst <a href="http://www.qtsoftware.com/products/licensing">www.qtsoftware.com/products/licensing</a> for et overblik over Qt licensforhold.</p><p>Qt er et Nokia produkt. Se <a href="http://qtsoftware.com/qt/">qtsoftware.com/qt/</a> for yderligere information.</p> + + + About Qt Om Qt <p>This program uses Qt version %1.</p> - <p>Dette program bruger Qt-version %1.</p> + <p>Dette program bruger Qt-version %1.</p> + Show Details... Vis detaljer... + Hide Details... Skjul detaljer... <h3>About Qt</h3>%1<p>Qt is a C++ toolkit for cross-platform application development.</p><p>Qt provides single-source portability across MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, and all major commercial Unix variants. Qt is also available for embedded devices as Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt is a Nokia product. See <a href="http://qtsoftware.com/qt/">qtsoftware.com/qt/</a> for more information.</p> - <h3>Om Qt</h3>%1<p>Qt er et C++ toolkit til cross-platform applikationsudvikling.</p><p>Qt tilbyder single-source portabilitet til MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, og alle større kommercielle Unix-varianter. Qt er ogsÃ¥ tilgængeligt til indlejrede systemer som Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt er et Nokia produkt. Se <a href="http://qtsoftware.com/qt/">qtsoftware.com/qt/</a> for yderligere information.</p> + <h3>Om Qt</h3>%1<p>Qt er et C++ toolkit til cross-platform applikationsudvikling.</p><p>Qt tilbyder single-source portabilitet til MS&nbsp;Windows, Mac&nbsp;OS&nbsp;X, Linux, og alle større kommercielle Unix-varianter. Qt er ogsÃ¥ tilgængeligt til indlejrede systemer som Qt for Embedded Linux and Qt for Windows CE.</p><p>Qt er et Nokia produkt. Se <a href="http://qtsoftware.com/qt/">qtsoftware.com/qt/</a> for yderligere information.</p> <p>This program uses Qt Open Source Edition version %1.</p><p>Qt Open Source Edition is intended for the development of Open Source applications. You need a commercial Qt license for development of proprietary (closed source) applications.</p><p>Please see <a href="http://qtsoftware.com/company/model/">qtsoftware.com/company/model/</a> for an overview of Qt licensing.</p> - <p>Dette program bruger Qt Open Source Edition version %1.</p><p>Qt Open Source Edition er beregnet til udvikling af Open Source applikationer. En kommerciel Qt licens er nødvendig til udvikling af proprietære (lukket sourcekode) applikationer.</p><p>Se venligst <a href="http://qtsoftware.com/company/model/">qtsoftware.com/company/model/</a> for et overblik over Qt licensforhold.</p> + <p>Dette program bruger Qt Open Source Edition version %1.</p><p>Qt Open Source Edition er beregnet til udvikling af Open Source applikationer. En kommerciel Qt licens er nødvendig til udvikling af proprietære (lukket sourcekode) applikationer.</p><p>Se venligst <a href="http://qtsoftware.com/company/model/">qtsoftware.com/company/model/</a> for et overblik over Qt licensforhold.</p> QMultiInputContext - + Select IM Markér IM @@ -2418,11 +3007,12 @@ Do you want to delete it anyway? QMultiInputContextPlugin - + Multiple input method switcher Multiple input metode-switcher + Multiple input method switcher that uses the context menu of the text widgets Multiple input metode-switcher, der benytter tekstkontrollernes kontekstmenuer @@ -2430,107 +3020,132 @@ Do you want to delete it anyway? QNativeSocketEngine - + The remote host closed the connection Fjern-hosten lukkede forbindelsen + Network operation timed out Netværksoperationen timed out + Out of resources Ikke flere ressourcer + Unsupported socket operation Socket-operation ikke understøttet + Protocol type not supported Protokoltypen understøttes ikke + Invalid socket descriptor Ugyldig socket-deskriptor + Network unreachable Netværket er ikke tilgængeligt + Permission denied Tilladelse nægtet + Connection timed out Forbindelsen timed out + Connection refused Forbindelse afvist + The bound address is already in use Den bundne adresse er allerede i brug + The address is not available Adressen er ikke tilgængelig + The address is protected Adressen er beskyttet + Unable to send a message Kunne ikke sende en besked + Unable to receive a message Kunne ikke modtage en besked + Unable to write Kunne ikke skrive + Network error Netværksfejl + Another socket is already listening on the same port En anden socket lytter allerede pÃ¥ samme port + Unable to initialize non-blocking socket Kunne ikke initialisere non-blocking socket + Unable to initialize broadcast socket Kunne ikke initialisere broadcast-socket + Attempt to use IPv6 socket on a platform with no IPv6 support Forsøg pÃ¥ at bruge IPv6-socket pÃ¥ en platform uden IPv6-support + Host unreachable Vært er ikke tilgængelig + Datagram was too large to send Datagrammet var for stort til at blive sendt + Operation on non-socket Handling pÃ¥ non-socket + Unknown error Ukendt fejl + The proxy type is invalid for this operation Proxytypen er ugyldig til denne handling @@ -2538,7 +3153,7 @@ Do you want to delete it anyway? QNetworkAccessCacheBackend - + Error opening %1 Der opstod fejl i at Ã¥bne %1 @@ -2546,23 +3161,27 @@ Do you want to delete it anyway? QNetworkAccessFileBackend - + Request for opening non-local file %1 Anmodning om at Ã¥bne ikke-lokal fil %1 + Error opening %1: %2 Der opstod fejl i at Ã¥bne %1: %2 + Write error writing to %1: %2 Skrivefejl mens der blev skrevet til %1: %2 + Cannot open %1: Path is a directory Kan ikke Ã¥bne %1: Stien er et katalog + Read error reading from %1: %2 Læsefejl mens der blev læst fra %1: %2 @@ -2570,23 +3189,27 @@ Do you want to delete it anyway? QNetworkAccessFtpBackend - + No suitable proxy found Ingen passende proxy blev fundet + Cannot open %1: is a directory Kan ikke Ã¥bne %1: Er et katalog + Logging in to %1 failed: authentication required Der opstod fejl i at logge pÃ¥ %1: Autentificering kræves + Error while downloading %1: %2 Der opstod fejl i at downloade %1: %2 + Error while uploading %1: %2 Der opstod fejl i at uploade %1: %2 @@ -2594,7 +3217,7 @@ Do you want to delete it anyway? QNetworkAccessHttpBackend - + No suitable proxy found Ingen passende proxy blev fundet @@ -2602,11 +3225,12 @@ Do you want to delete it anyway? QNetworkReply + Error downloading %1 - server replied: %2 Der opstod fejl i at downloade %1 - serveren svarede: %2 - + Protocol "%1" is unknown Protokollen "%1" er ukendt @@ -2614,6 +3238,8 @@ Do you want to delete it anyway? QNetworkReplyImpl + + Operation canceled Handling blev annulleret @@ -2621,24 +3247,28 @@ Do you want to delete it anyway? QOCIDriver - + Unable to logon Kunne ikke logge pÃ¥ + Unable to initialize QOCIDriver Kunne ikke initialisere + Unable to begin transaction Kunne ikke pÃ¥begynde transaktionen + Unable to commit transaction Kunne ikke gennemføre transaktionen + Unable to rollback transaction Kunne ikke tilbagetrække transaktionen @@ -2646,34 +3276,43 @@ Do you want to delete it anyway? QOCIResult + + + Unable to bind column for batch execute Kunne ikke tildele kolonne til batch-udførsel + Unable to execute batch statement Kunne ikke udføre batch-udsagn + Unable to goto next Kunne ikke gÃ¥ til den næste + Unable to alloc statement Kunne ikke allokere udsagn + Unable to prepare statement Kunne ikke forberede udsagn + Unable to bind value Kunne ikke tildele værdi Unable to execute select statement - Kunne ikke udføre det valgte udsagn + Kunne ikke udføre det valgte udsagn + Unable to execute statement Kunne ikke udføre udsagn @@ -2681,27 +3320,32 @@ Do you want to delete it anyway? QODBCDriver - + Unable to connect Kunne ikke forbinde + Unable to connect - Driver doesn't support all needed functionality Kunne ikke forbinde. Driveren understøtter ikke alle de nødvendige funktionaliteter + Unable to disable autocommit Kunne ikke slÃ¥ auto-udfør fra + Unable to commit transaction Kunne ikke gennemføre transaktionen + Unable to rollback transaction Kunne ikke tilbagetrække transaktionen + Unable to enable autocommit Kunne ikke slÃ¥ auto-udfør til @@ -2709,38 +3353,51 @@ Do you want to delete it anyway? QODBCResult + + QODBCResult::reset: Unable to set 'SQL_CURSOR_STATIC' as statement attribute. Please check your ODBC driver configuration QODBCResult::reset: Kunne ikke indstille 'SQL_CURSOR_STATIC' til udsagnsattribut. Kontrollér ODBC-driver-konfigurationen + + Unable to execute statement Kunne ikke udføre udsagn + Unable to fetch next Kunne ikke hente den næste + Unable to prepare statement Kunne ikke forberede udsagn + Unable to bind variable Kunne ikke tildele variabel + + + Unable to fetch last Kunne ikke hente den sidste + Unable to fetch Kunne ikke hente + Unable to fetch first Kunne ikke hente den første + Unable to fetch previous Kunne ikke hente den forrige @@ -2748,41 +3405,48 @@ Do you want to delete it anyway? QObject - + Home Hjem - + Operation not supported on %1 Handling blev ikke understøttet pÃ¥ %1 + Invalid URI: %1 Ugyldig URI: %1 - + Write error writing to %1: %2 Skrivefejl mens der blev skrevet til %1: %2 + Read error reading from %1: %2 Læsefejl mens der blev læst fra %1: %2 + Socket error on %1: %2 Socket-fejl pÃ¥ %1: %2 + Remote host closed the connection prematurely on %1 Fjern-host lukkede forbindelsen for tidligt pÃ¥ %1 + Protocol error: packet of size 0 received Protokolfejl: Pakke pÃ¥ størrelsen 0 modtaget + + No host name given Hostnavn mangler @@ -2790,11 +3454,12 @@ Do you want to delete it anyway? QPPDOptionsModel - + Name Navn + Value Værdi @@ -2802,27 +3467,32 @@ Do you want to delete it anyway? QPSQLDriver - + Unable to connect Kunne ikke skabe forbindelse + Could not begin transaction Kunne ikke pÃ¥begynde transaktion + Could not commit transaction Kunne ikke gennemføre transaktion + Could not rollback transaction Kunne ikke tilbagetrække transaktion + Unable to subscribe Kunne ikke tilmelde + Unable to unsubscribe Kunne ikke afmelde @@ -2830,10 +3500,12 @@ Do you want to delete it anyway? QPSQLResult + Unable to create query Kunne ikke oprette forespørgsel + Unable to prepare statement Kunne ikke forberede udsagn @@ -2841,83 +3513,102 @@ Do you want to delete it anyway? QPageSetupWidget - + Centimeters (cm) Centimeter (cm) + Millimeters (mm) Millimeter (mm) + Inches (in) + Points (pt) Point (pt) + Form + Paper Papir + Page size: Sidestørrelse: + Width: Vidde: + Height: Højde: + Paper source: Papirkilde: + Orientation + Portrait Portræt + Landscape Landskab + Reverse landscape Omvendt landskab + Reverse portrait Omvendt portræt + Margins Margener + top margin Margen - øverst + left margin Margen - venstre + right margin Margen - højre + bottom margin Margen - bund @@ -2925,11 +3616,12 @@ Do you want to delete it anyway? QPluginLoader - + Unknown error Ukendt fejl + The plugin was not loaded. Plugin blev ikke indlæst. @@ -2937,346 +3629,428 @@ Do you want to delete it anyway? QPrintDialog - + locally connected lokalt forbundet + + Aliases: %1 Aliasser: %1 + + unknown Ukendt - + A0 (841 x 1189 mm) + A1 (594 x 841 mm) + A2 (420 x 594 mm) + A3 (297 x 420 mm) + A4 (210 x 297 mm, 8.26 x 11.7 inches) + A5 (148 x 210 mm) + A6 (105 x 148 mm) + A7 (74 x 105 mm) + A8 (52 x 74 mm) + A9 (37 x 52 mm) + B0 (1000 x 1414 mm) + B1 (707 x 1000 mm) + B2 (500 x 707 mm) + B3 (353 x 500 mm) + B4 (250 x 353 mm) + B5 (176 x 250 mm, 6.93 x 9.84 inches) + B6 (125 x 176 mm) + B7 (88 x 125 mm) + B8 (62 x 88 mm) + B9 (44 x 62 mm) + B10 (31 x 44 mm) + C5E (163 x 229 mm) + DLE (110 x 220 mm) + Executive (7.5 x 10 inches, 191 x 254 mm) + Folio (210 x 330 mm) + Ledger (432 x 279 mm) + Legal (8.5 x 14 inches, 216 x 356 mm) + Letter (8.5 x 11 inches, 216 x 279 mm) + Tabloid (279 x 432 mm) + US Common #10 Envelope (105 x 241 mm) - + OK + + + Print Udskriv + Print To File ... Udskriv til fil... - + Print range UdskriftsomrÃ¥de + Print all Udskriv alle - + File %1 is not writable. Please choose a different file name. Filen %1 kan ikke skrives. Vælg et andet filnavn. + %1 already exists. Do you want to overwrite it? %1 findes allerede. Ønsker du at overskrive? + File exists Fil findes + <qt>Do you want to overwrite it?</qt> <qt>Ønsker du at overskrive?</qt> + Print selection Udskriv markerede + %1 is a directory. Please choose a different file name. %1 er et katalog. Vælg et andet filnavn. + A0 + A1 + A2 + A3 + A4 + A5 + A6 + A7 + A8 + A9 + B0 + B1 + B2 + B3 + B4 + B5 + B6 + B7 + B8 + B9 + B10 + C5E + DLE + Executive + Folio + Ledger + Legal + Letter + Tabloid + US Common #10 Envelope + Custom Brugerdefineret + + &Options >> &Indstillinger>> + &Print &Udskriv + &Options << &Indstillinger<< + Print to File (PDF) Udskriv til fil (PDF) + Print to File (Postscript) Udskriv til fil (Postscript) + Local file Lokal fil + Write %1 file Skriv %1 fil - + The 'From' value cannot be greater than the 'To' value. 'Fra'-værdien kan ikke være større end 'til'-værdien. @@ -3284,87 +4058,108 @@ Vælg et andet filnavn. QPrintPreviewDialog + + Page Setup Sideopsætning - + %1% + Print Preview Vis udskrift + Next page Næste side + Previous page Forrige side + First page Første side + Last page Sidste side + Fit width Tilpas bredde + Fit page Tilpas siden + Zoom in Zoom ind + Zoom out Zoom ud + Portrait Portræt + Landscape Landskab + Show single page Vis enkelt side + Show facing pages Vis sideopslag + Show overview of all pages Vis oversigt af alle sider + Print Udskriv + Page setup Sideopsætning + Close Luk + Export to PDF Eksportér til PDF + Export to PostScript Eksportér til PostScript @@ -3372,14 +4167,17 @@ Vælg et andet filnavn. QPrintPropertiesWidget + Form Form + Page Side + Advanced Avanceret @@ -3387,78 +4185,97 @@ Vælg et andet filnavn. QPrintSettingsOutput + Form + Copies Kopier + Print range Udskriv sider + Print all Udskriv alle + Pages from Sider fra + to til + Selection Valg + Output Settings Udskriftsindstillinger + Copies: Kopier: + Collate Samordne + Reverse Omvendt + Options Valgmuligheder + Color Mode Farvetilstand + Color Farve + Grayscale GrÃ¥skala + Duplex Printing Dobbelsidet + None Ingen + Long side Bog + Short side Tavle @@ -3466,38 +4283,47 @@ Vælg et andet filnavn. QPrintWidget + Form + Printer ' + &Name: &Navn: + P&roperties &Egenskaber + Location: Placering: + Preview Vis udskrift + Type: + Output &file: Udskrifts&fil: + ... @@ -3505,37 +4331,62 @@ Vælg et andet filnavn. QProcess - + + Could not open input redirection for reading Kunne ikke Ã¥bne input redirection for læsning - + + Could not open output redirection for writing Kunne ikke Ã¥bne output redirection for skrivning + Resource error (fork failure): %1 Ressource fejl (fork fejl): %1 + + + + + + + + + Process operation timed out Proces-operation time out + + + + Error reading from process Fejl ved læsning fra proces - + + + Error writing to process Fejl ved skrivning til proces + Process crashed Proces crashede + + No program defined + Intet program defineret + + + Process failed to start Processen kunne ikke starte @@ -3543,7 +4394,7 @@ Vælg et andet filnavn. QProgressDialog - + Cancel Annuller @@ -3551,6 +4402,7 @@ Vælg et andet filnavn. QPushButton + Open Ã…bn @@ -3558,6 +4410,7 @@ Vælg et andet filnavn. QRadioButton + Check Kontrollér @@ -3565,39 +4418,47 @@ Vælg et andet filnavn. QRegExp - + no error occurred der opstod ingen fejl + disabled feature used deaktiveret funktion blev brugt + bad char class syntax dÃ¥rlig char class syntaks + bad lookahead syntax dÃ¥rlig lookahead syntaks + bad repetition syntax dÃ¥rlig gentagelsessyntaks + invalid octal value ugyldigt oktal-tal + missing left delim Manglende venstre delimiter + unexpected end uventet afslutning + met internal limit nÃ¥ede interne grænse @@ -3605,19 +4466,22 @@ Vælg et andet filnavn. QSQLite2Driver - + Error to open database Der opstod fejl ved Ã¥bning af database + Unable to begin transaction Kunne ikke pÃ¥begynde transaktionen + Unable to commit transaction Kunne ikke gennemføre transaktionen + Unable to rollback Transaction Kunne ikke tilbagetrække transaktion @@ -3625,10 +4489,12 @@ Vælg et andet filnavn. QSQLite2Result + Unable to fetch results Kunne ikke hente resultater + Unable to execute statement Kunne ikke udføre statement @@ -3636,23 +4502,27 @@ Vælg et andet filnavn. QSQLiteDriver - + Error opening database Der opstod fejl ved Ã¥bning af database + Error closing database Der opstod fejl ved lukning af database + Unable to begin transaction Kunne ikke pÃ¥begynde transaktionen + Unable to commit transaction Kunne ikke gennemføre transaktion + Unable to rollback transaction Kunne ikke tilbagetrække transaktion @@ -3660,26 +4530,34 @@ Vælg et andet filnavn. QSQLiteResult + + + Unable to fetch row Kunne ikke hente række + Unable to execute statement Kunne ikke udføre udsagn + Unable to reset statement Kunne ikke nulstille udsagn + Unable to bind parameters Unable to bind parameters + Parameter count mismatch Misforhold i parametertælling + No query Ingen forespørgesel @@ -3687,69 +4565,84 @@ Vælg et andet filnavn. QScrollBar - + Scroll here Scroll her + Left edge Venstre kant + Top Øverst + Right edge Højre kant + Bottom Bund + Page left Side venstre - + + Page up Side øverst + Page right Side højre - + + Page down Side ned + Scroll left Scroll til venstre + Scroll up Scroll op + Scroll right Scroll til højre + Scroll down Scroll ned + Line up Linie op + Position Placering + Line down Linie ned @@ -3757,81 +4650,99 @@ Vælg et andet filnavn. QSharedMemory - + %1: unable to set key on lock %1: Kunne ikke oprette nøgle + %1: create size is less then 0 %1: create size is less then 0 - + + %1: unable to lock %1: Kunne ikke lÃ¥se + %1: unable to unlock %1: Kunne ikke oprette nøgle - + + %1: permission denied %1: Tilladelse nægtet + + %1: already exists %1: Findes allerede - + + %1: doesn't exists %1: Findes ikke - + + %1: out of resources %1: Ikke flere ressourcer - + + %1: unknown error %2 %1: ukendt fejl %2 + %1: key is empty %1: nøgle er tom + %1: unix key file doesn't exists %1: Kunne ikke oprette nøgle + %1: ftok failed %1: ftok mislykkedes - + + %1: unable to make key %1: Kunne ikke oprette nøgle + %1: system-imposed size restrictions %1: System-pÃ¥lagte størrelsesrestriktioner + %1: not attached %1: Ikke vedhæftet + %1: invalid size %1: Ugyldig størrelse + %1: key error %1: Nøglefejl + %1: size query failed %1: Størrelsesforespørgsel mislykkedes @@ -3839,371 +4750,466 @@ Vælg et andet filnavn. QShortcut - + Space + Esc + Tab + Backtab Tilbage-tabulator + Backspace Tilbage + Return + Enter + Ins + Del + Pause + Print Udskriv + SysReq + Home + End + Left Venstre + Up Op + Right Højre + Down Ned + PgUp + PgDown + CapsLock ' + NumLock + ScrollLock + Menu + Help Hjælp + Back Tilbage + Forward Frem + Stop + Refresh Opdater + Volume Down Lydstyrke ned + Volume Mute Lydstyrke mute + Volume Up Lydstyrke op + Bass Boost + Bass Up Bass op + Bass Down Bass ned + Treble Up Diskant op + Treble Down Diskant ned + Media Play + Media Stop + Media Previous Media forrige + Media Next Media næste + Media Record + Favorites + Search Søg + Standby + Open URL Ã…bn URL + Launch Mail Start mail + Launch Media Start Media + Launch (0) Start (0) + Launch (1) Start (1) + Launch (2) Start (2) + Launch (3) Start (3) + Launch (4) Start (4) + Launch (5) Start (5) + Launch (6) Start (6) + Launch (7) Start (7) + Launch (8) Start (8) + Launch (9) Start (9) + Launch (A) Start (A) + Launch (B) Start (B) + Launch (C) Start (C) + Launch (D) Start (D) + Launch (E) Start (E) + Launch (F) Start (F) + Print Screen + Page Up + Page Down + Caps Lock + Num Lock + Number Lock + Scroll Lock + Insert + Delete + Escape + System Request + Select Væg + Yes Ja + No Nej + Context1 Kontekst1 + Context2 Kontekst2 + Context3 Kontekst3 + Context4 Kontekst4 + Call Ring til + Hangup Læg pÃ¥ + Flip Vend + + Ctrl + + Shift + + Alt + + Meta + + + F%1 + Home Page Startside @@ -4211,23 +5217,27 @@ Vælg et andet filnavn. QSlider - + Page left Side venstre + Page up Side op + Position Placering + Page right Side højre + Page down Side ned @@ -4235,58 +5245,72 @@ Vælg et andet filnavn. QSocks5SocketEngine + Connection to proxy refused Proxy-forbindelse nægtede + Connection to proxy closed prematurely Proxy-forbindelse afsluttede i utide + Proxy host not found Proxy-host kunne ikke findes + Connection to proxy timed out Proxy-serverforbindelse timed out + Proxy authentication failed Proxy autentificering mislykkedes + Proxy authentication failed: %1 Proxy autentificering mislykkedes: %1 + SOCKS version 5 protocol error SOCKS version 5 protokolfejl + General SOCKSv5 server failure General SOCKSv5 serverfejl + Connection not allowed by SOCKSv5 server Forbindelse ikke tilladt a SOCKSv5-server + TTL expired TTL udløbet + SOCKSv5 command not supported SOCKSv5-kommando ikke understøttet + Address type not supported Adressetype understøttes ikke + Unknown SOCKSv5 proxy error code 0x%1 Ukendt SOCKSv5 proxy fejlkode 0x%1 + Network operation timed out Netværksoperationen timed out @@ -4294,10 +5318,12 @@ Vælg et andet filnavn. QSpinBox + More Mere + Less Mindre @@ -4305,43 +5331,56 @@ Vælg et andet filnavn. QSql - + Delete Slet + Delete this record? Slet denne post? + + + Yes Ja + + + No Nej + Insert Indsæt + Update Opdater + Save edits? Gem ændringer? + Cancel Annuller + Confirm Bekræft + Cancel your edits? Skal dine ændringer annulleres? @@ -4349,47 +5388,57 @@ Vælg et andet filnavn. QSslSocket - + Unable to write data: %1 Kunne ikke skrive data: %1 + Error while reading: %1 Der opstod en fejl under læsning af: %1 + Error during SSL handshake: %1 Der opstod en fejl under SSL handshake: %1 + Error creating SSL context (%1) Der opstod fejl under oprettelse af SSL-kontekst (%1) + Invalid or empty cipher list (%1) Ugyldig eller tom chifferliste (%1) + Error creating SSL session, %1 Der opstod fejl under oprettelse af SSL-session, %1 + Error creating SSL session: %1 Der opstod fejl under oprettelse af SSL-session, %1 + Cannot provide a certificate with no key, %1 Kan ikke give et certifikat uden nøgle, %1 + Error loading local certificate, %1 Der opstod fejl under indlæsning af lokalt certifikat, %1 + Error loading private key, %1 Der opstod fejl under indlæsning af privat nøgle, %1 + Private key does not certificate public key, %1 Privat-nøgle autoriserer ikke offentlig-nøgle, %1 @@ -4397,25 +5446,30 @@ Vælg et andet filnavn. QSystemSemaphore - + + %1: out of resources %1: Ikke flere ressourcer - + + %1: permission denied %1: Tilladelse nægtet + %1: already exists %1: Findes allerede + %1: does not exist %1: Findes ikke - + + %1: unknown error %2 %1: Ukendt fejl %2 @@ -4423,11 +5477,12 @@ Vælg et andet filnavn. QTDSDriver - + Unable to open connection Kunne ikke etablere forbindelsen + Unable to use database Kunne ikke bruge databasen @@ -4435,10 +5490,12 @@ Vælg et andet filnavn. QTabBar + Scroll Left Scroll til venstre + Scroll Right Scroll til højre @@ -4446,7 +5503,7 @@ Vælg et andet filnavn. QTcpServer - + Operation on socket is not supported Socket-operation ikke understøttet @@ -4454,35 +5511,42 @@ Vælg et andet filnavn. QTextControl - + &Undo &Fortryd + &Redo &Gendan + Cu&t K&lip + &Copy &Kopiér + Copy &Link Location Kopiér l&ink + &Paste &Sæt ind + Delete Slet + Select All Markér alt @@ -4490,10 +5554,14 @@ Vælg et andet filnavn. QToolButton + + Press Tryk pÃ¥ + + Open Ã…bn @@ -4501,7 +5569,7 @@ Vælg et andet filnavn. QUdpSocket - + This platform does not support IPv6 Denne platform understøtter ikke IPv6 @@ -4509,11 +5577,12 @@ Vælg et andet filnavn. QUndoGroup - + Undo Fortryd + Redo Gendan @@ -4521,7 +5590,7 @@ Vælg et andet filnavn. QUndoModel - + <empty> <tom> @@ -4529,11 +5598,12 @@ Vælg et andet filnavn. QUndoStack - + Undo Fortryd + Redo Gendan @@ -4541,47 +5611,57 @@ Vælg et andet filnavn. QUnicodeControlCharacterMenu - + LRM Left-to-right mark + RLM Right-to-left mark + ZWJ Zero width joiner + ZWNJ Zero width non-joiner + ZWSP Zero width space + LRE Start of left-to-right embedding + RLE Start of right-to-left embedding + LRO Start of left-to-right override + RLO Start of right-to-left override + PDF Pop directional formatting + Insert Unicode control character @@ -4589,27 +5669,32 @@ Vælg et andet filnavn. QWebFrame - + Request cancelled Anmodning annulleret + Request blocked Anmodning blokeret + Cannot show URL Kan ikke vise URL + Frame load interruped by policy change Billedindlæsning afbrudt af ændringer i retningslinier + Cannot show mimetype Kan ikke vise MIME-type + File does not exist Filen findes ikke @@ -4617,316 +5702,376 @@ Vælg et andet filnavn. QWebPage - + Bad HTTP request DÃ¥rlig HTTP-anmodning - + Submit default label for Submit buttons in forms on web pages Send + Submit Submit (input element) alt text for <input> elements with no alt, title, or value Send + Reset default label for Reset buttons in forms on web pages Nulstil + This is a searchable index. Enter search keywords: text that appears at the start of nearly-obsolete web pages in the form of a 'searchable index' Dette er et søgeindeks. Indtast søgeord: + Choose File title for file button used in HTML forms Vælg fil + No file selected text to display in file button used in HTML forms when no file is selected Der er ikke valgt en fil + Open in New Window Open in New Window context menu item Ã…bn i nyt vindue + Save Link... Download Linked File context menu item Gem link... + Copy Link Copy Link context menu item Kopiér link + Open Image Open Image in New Window context menu item Ã…bn billede + Save Image Download Image context menu item Gem billede + Copy Image Copy Link context menu item Kopiér billede + Open Frame Open Frame in New Window context menu item Ã…bn faneblad + Copy Copy context menu item Kopiér + Go Back Back context menu item GÃ¥ tilbage + Go Forward Forward context menu item GÃ¥ frem + Stop Stop context menu item Stop + Reload Reload context menu item Genindlæs + Cut Cut context menu item Klip + Paste Paste context menu item Sæt ind + No Guesses Found No Guesses Found context menu item Der er ikke fundet nogen gæt + Ignore Ignore Spelling context menu item Ignorér + Add To Dictionary Learn Spelling context menu item Tilføj til ordbog + Search The Web Search The Web context menu item Søg pÃ¥ nettet + Look Up In Dictionary Look Up in Dictionary context menu item SlÃ¥ op i ordbog + Open Link Open Link context menu item Ã…bn link + Ignore Ignore Grammar context menu item Ignorér + Spelling Spelling and Grammar context sub-menu item Stavekontrol + Show Spelling and Grammar menu item title Vis stave- og grammatikkontrol + Hide Spelling and Grammar menu item title Skjul stave- og grammatikkontrol + Check Spelling Check spelling context menu item Kør stavekontrol + Check Spelling While Typing Check spelling while typing context menu item Kør stavekontrol mens der tastes + Check Grammar With Spelling Check grammar with spelling context menu item Kør grammatikkontrol sammen med stavekontrol + Fonts Font context sub-menu item Skrifttyper + Bold Bold context menu item Fed + Italic Italic context menu item Kursiv + Underline Underline context menu item Understreget + Outline Outline context menu item Kontur + Direction Writing direction context sub-menu item Retning + Text Direction Text direction context sub-menu item Tekstretning + Default Default writing direction context menu item Standard + LTR Left to Right context menu item + RTL Right to Left context menu item + Inspect Inspect Element context menu item Inspicér + No recent searches Label for only item in menu that appears when clicking on the search field image, when no searches have been performed Ingen aktuelle søgninger + Recent searches label for first item in the menu that appears when clicking on the search field image, used as embedded menu title Aktuelle søgninger + Clear recent searches menu item in Recent Searches menu that empties menu's contents Ryd aktuelle søgninger + Unknown Unknown filesize FTP directory listing item Ukendt + %1 (%2x%3 pixels) Title string for images %1 (%2x%3 pixels) - + Web Inspector - %2 Web-inspektør - %2 - + Scroll here Scroll her + Left edge Venstre kant + Top + Right edge Højre kant + Bottom Bund + Page left Side venstre + Page up Side øverst + Page right Side højre + Page down Side ned + Scroll left Scroll til venstre + Scroll up Scroll op + Scroll right Scroll til højre + Scroll down Scroll ned - + %n file(s) number of chosen file @@ -4935,127 +6080,170 @@ Vælg et andet filnavn. - + JavaScript Alert - %1 JavaScript alert - %1 + JavaScript Confirm - %1 JavaScript Bekræft - %1 + JavaScript Prompt - %1 JavaScript Prompt - %1 + Move the cursor to the next character Flyt markør til næste tegn + Move the cursor to the previous character Flyt markør til forrige tegn + Move the cursor to the next word Flyt markør til næste ord + Move the cursor to the previous word Flyt markør til forrige ord + Move the cursor to the next line Flyt markør til næste linie + Move the cursor to the previous line Flyt markør til forrige linie + Move the cursor to the start of the line Flyt markør til starten af linien + Move the cursor to the end of the line Flyt markør til slutningen af linien + Move the cursor to the start of the block Flyt markør til starten af sektionen + Move the cursor to the end of the block Flyt markør til slutningen af sektionen + Move the cursor to the start of the document Flyt markør til starten af dokumentet + Move the cursor to the end of the document Flyt markør til slutningen af dokumentet + + Select all + Markér alt + + + Select to the next character Vælg til næste tegn + Select to the previous character Vælg til forrige tegn + Select to the next word Vælg til næste ord + Select to the previous word Vælg til forrige ord + Select to the next line Vælg til næste linie + Select to the previous line Vælg til forrige linie + Select to the start of the line Vælg til starten af linien + Select to the end of the line Vælg til slutningen af linien + Select to the start of the block Vælg til starten af sektionen + Select to the end of the block Vælg til slutningen af sektionen + Select to the start of the document Vælg til starten af dokumentet + Select to the end of the document Vælg til slutningen af dokumentet + Delete to the start of the word Slet til starten af ordet + Delete to the end of the word Slet til slutningen af ordet + + + Insert a new paragraph + Indsæt et nyt afsnit + + + + Insert a new line + Insert ny linie + QWhatsThisAction - + What's This? Hvad er dette? @@ -5063,7 +6251,7 @@ Vælg et andet filnavn. QWidget - + * @@ -5071,47 +6259,57 @@ Vælg et andet filnavn. QWizard - + Go Back GÃ¥ tilbage + Continue Fortsæt + Commit Udfør + Done Færdig + Help Hjælp + < &Back < &Tilbage + &Finish &Afslut + Cancel Annuller + &Help &Hjælp + &Next &Næste + &Next > &Næste > @@ -5119,55 +6317,69 @@ Vælg et andet filnavn. QWorkspace - + &Restore &Gendan + &Move &Flyt + &Size &Størrelse + Mi&nimize Mi&nimér + Ma&ximize Ma&ksimér + &Close &Luk + Stay on &Top Bliv pÃ¥ &toppen + + Sh&ade Sk&ygge + + %1 - [%2] + Minimize Minimer + Restore Down Gendan ned + Close Luk + &Unshade &Fjern skygge @@ -5175,95 +6387,117 @@ Vælg et andet filnavn. QXml - + no error occurred der opstod ingen fejl + error triggered by consumer - + Fejltilstand rejst af datamodtager + unexpected end of file uventet afslutning pÃ¥ fil + more than one document type definition mere end én definition pÃ¥ dokumenttype + error occurred while parsing element der opstod fejl under fortolking af element + tag mismatch + error occurred while parsing content der opstod fejl under fortolking af indhold + unexpected character uventet tegn + invalid name for processing instruction - + Ugyldigt navn for processing instruction + version expected while reading the XML declaration version forventet under læsning af XML-deklaration + wrong value for standalone declaration - + Forkert værdi for fri deklaration + encoding declaration or standalone declaration expected while reading the XML declaration - + Enkodningsdeklaration eller fri deklaration forventet ved læsning af XML-deklaration + standalone declaration expected while reading the XML declaration - + fri deklaration forventet ved læsning af XML-deklaration + error occurred while parsing document type definition der opstod fejl under fortolking af dokumenttypedefinition + letter is expected - + bogstav forventet + error occurred while parsing comment der opstod fejl under fortolking af kommentar + error occurred while parsing reference der opstod fejl under fortolking af reference + internal general entity reference not allowed in DTD - + intern generel entitetsreference ikke tilladt i DTD + external parsed general entity reference not allowed in attribute value - + Eksternt parset generel entitetsreference ikke tilladt i attributværdi + external parsed general entity reference not allowed in DTD - + Eksternt parset generel entitetsreference ikke tilladt i DTD + unparsed entity reference in wrong context ufortolket enhedsreference i forkert kontekst + recursive entities - + rekursive entiteter + error in the text declaration of an external entity fejl i tekstdeklaration pÃ¥ en ekstern enhed @@ -5271,412 +6505,485 @@ Vælg et andet filnavn. QXmlStream - + + Extra content at end of document. Ekstra indhold sidst i dokumentet. + Invalid entity value. Ugyldig enhedsværdi. + Invalid XML character. Ugyldigt XML-tegn. + Sequence ']]>' not allowed in content. Sekvens ']]>' ikke tilladt i indhold. + Namespace prefix '%1' not declared Navnerumspræfiks '%1' ikke deklareret + Attribute redefined. - + Attribut redefineret. + Unexpected character '%1' in public id literal. - + Uventet tegn '%1' i public id værdi. + Invalid XML version string. Ugyldigt XML-versionsstreng. + Unsupported XML version. XML-version understøttes ikke. + %1 is an invalid encoding name. - + %1 er et ugyldigt enkodningsnavn. + Encoding %1 is unsupported - + Enkodning %1 er ikke understøttet + Standalone accepts only yes or no. + Invalid attribute in XML declaration. - + Ugyldig attribut i XML-deklaration. + Premature end of document. - + Dokument sluttede for tidligt. + Invalid document. Ugyldigt dokument. + Expected Forventet + , but got ' , men fik ' + Unexpected ' Uventet ' + Expected character data. Forventet tegndata. + Recursive entity detected. - + Rekursiv entitet opdaget. + Start tag expected. Start-tag forventet. + XML declaration not at start of document. XML-deklaration ikke i starten af dokumentet. + NDATA in parameter entity declaration. - + NDATA i parameterentitetsdeklaration. + %1 is an invalid processing instruction name. - + %1 er et ugyldigt processing-instruction-navn. + Invalid processing instruction name. - + Ugyldigt processing-instruction-navn. + + + + Illegal namespace declaration. Ulovligt navnerumsdeklaration. - + Invalid XML name. Ugyldigt XML-navn. + Opening and ending tag mismatch. Ã…bner og afslutter tag-mismatch. + Reference to unparsed entity '%1'. Reference to ufortolket enhed '%1'. + + + Entity '%1' not declared. Enheden '%1' ikke deklareret. + Reference to external entity '%1' in attribute value. Reference til ekstern enhed '%1' i attributværdi. + Invalid character reference. Ugyldig tegnreference. + + Encountered incorrectly encoded content. - + Indhold med forkert enkodning læst. + The standalone pseudo attribute must appear after the encoding. - + Den frie pseudo-attribut skal optræde efter enkodningen. - + %1 is an invalid PUBLIC identifier. - + %1 er en ugyldig PUBLIC identifier. QtXmlPatterns - + An %1-attribute with value %2 has already been declared. - + En %1-attribut med værdi %2 er allerede erklæret. + An %1-attribute must have a valid %2 as value, which %3 isn't. - + En %1-attribut skal have en gyldig %2 som værdi, hvilket %3 ikke er. - + Network timeout. - + Netværk timeout. - + Element %1 can't be serialized because it appears outside the document element. - + Element %1 kan ikke serialiseres fordi det optræder udenfor dokument-elementet. - + Year %1 is invalid because it begins with %2. - + Ã…r %1 er ugyldigt da det begynder med %2. + Day %1 is outside the range %2..%3. - + Dag %1 er udenfor intervallet %2..%3. + Month %1 is outside the range %2..%3. - + MÃ¥ned %1 er udenfor intervallet %2..%3. + Overflow: Can't represent date %1. - + Overflow: Kan ikke repræsentere dato %1. + Day %1 is invalid for month %2. - + Dag %1 er ugyldig for mÃ¥net %2. + Time 24:%1:%2.%3 is invalid. Hour is 24, but minutes, seconds, and milliseconds are not all 0; - + Tidspunkt 24:%1:%2.%3 er ugyldigt. Timetal er 24, men minutter, sekunder og millisekunder er ikke alle 0; + Time %1:%2:%3.%4 is invalid. - + Tidspunkt %1:%2:%3.%4 er ugyldigt. + Overflow: Date can't be represented. - + Overflow: Dato kan ikke repræsenteres. + + At least one component must be present. - + Mindst en komponent skal være tilstede. + At least one time component must appear after the %1-delimiter. - + Mindst en tidskomponent skal optræde efter %1-skillemærket. - + No operand in an integer division, %1, can be %2. - + Ingen operand i en heltalsdivision, %1, kan være %2. + The first operand in an integer division, %1, cannot be infinity (%2). - + Den første operand i en heltalsdivision, %1, kan ikke være uendeligt (%2). + The second operand in a division, %1, cannot be zero (%2). - + Den anden operand i en division, %1, kan ikke være nul (%2). - + %1 is not a valid value of type %2. - + %1 er ikke en gyldig værdi af typen %2. - + When casting to %1 from %2, the source value cannot be %3. - + Ved cast til %1 fra %2, kan kildeværdien ikke være %3. - + Integer division (%1) by zero (%2) is undefined. - + Heltalsdivision (%1) med nul (%2) er udefineret. + Division (%1) by zero (%2) is undefined. - + Division (%1) med nul (%2) er udefineret. + Modulus division (%1) by zero (%2) is undefined. - + Modulusdivision (%1) med nul (%2) er udefineret. + + Dividing a value of type %1 by %2 (not-a-number) is not allowed. - + Division af værdi af typen %1 med %2 (ikke et tal) er ikke tilladt. + Dividing a value of type %1 by %2 or %3 (plus or minus zero) is not allowed. + Multiplication of a value of type %1 by %2 or %3 (plus or minus infinity) is not allowed. - + A value of type %1 cannot have an Effective Boolean Value. - + Effective Boolean Value cannot be calculated for a sequence containing two or more atomic values. - + Value %1 of type %2 exceeds maximum (%3). + Value %1 of type %2 is below minimum (%3). - + A value of type %1 must contain an even number of digits. The value %2 does not. + %1 is not valid as a value of type %2. - + Operator %1 cannot be used on type %2. + Operator %1 cannot be used on atomic values of type %2 and %3. - + The namespace URI in the name for a computed attribute cannot be %1. + The name for a computed attribute cannot have the namespace URI %1 with the local name %2. - + Type error in cast, expected %1, received %2. + When casting to %1 or types derived from it, the source value must be of the same type, or it must be a string literal. Type %2 is not allowed. - + No casting is possible with %1 as the target type. + It is not possible to cast from %1 to %2. + Casting to %1 is not possible because it is an abstract type, and can therefore never be instantiated. + It's not possible to cast the value %1 of type %2 to %3 + Failure when casting from %1 to %2: %3 - + A comment cannot contain %1 + A comment cannot end with a %1. - + No comparisons can be done involving the type %1. + Operator %1 is not available between atomic values of type %2 and %3. - + An attribute node cannot be a child of a document node. Therefore, the attribute %1 is out of place. - + A library module cannot be evaluated directly. It must be imported from a main module. + No template by name %1 exists. - + A value of type %1 cannot be a predicate. A predicate must have either a numeric type or an Effective Boolean Value type. + A positional predicate must evaluate to a single numeric value. - + The target name in a processing instruction cannot be %1 in any combination of upper and lower case. Therefore, is %2 invalid. + %1 is not a valid target name in a processing instruction. It must be a %2 value, e.g. %3. - + The last step in a path must contain either nodes or atomic values. It cannot be a mixture between the two. - + The data of a processing instruction cannot contain the string %1 - + No namespace binding exists for the prefix %1 - + No namespace binding exists for the prefix %1 in %2 - + + %1 is an invalid %2 - + %1 takes at most %n argument(s). %2 is therefore invalid. @@ -5684,6 +6991,7 @@ Vælg et andet filnavn. + %1 requires at least %n argument(s). %2 is therefore invalid. @@ -5691,613 +6999,731 @@ Vælg et andet filnavn. - + The first argument to %1 cannot be of type %2. It must be a numeric type, xs:yearMonthDuration or xs:dayTimeDuration. + The first argument to %1 cannot be of type %2. It must be of type %3, %4, or %5. + The second argument to %1 cannot be of type %2. It must be of type %3, %4, or %5. - + %1 is not a valid XML 1.0 character. - + The first argument to %1 cannot be of type %2. - + If both values have zone offsets, they must have the same zone offset. %1 and %2 are not the same. - + %1 was called. - + %1 must be followed by %2 or %3, not at the end of the replacement string. + In the replacement string, %1 must be followed by at least one digit when not escaped. + In the replacement string, %1 can only be used to escape itself or %2, not %3 - + %1 matches newline characters + %1 and %2 match the start and end of a line. + Matches are case insensitive + Whitespace characters are removed, except when they appear in character classes + %1 is an invalid regular expression pattern: %2 + %1 is an invalid flag for regular expressions. Valid flags are: - + If the first argument is the empty sequence or a zero-length string (no namespace), a prefix cannot be specified. Prefix %1 was specified. - + It will not be possible to retrieve %1. - + The root node of the second argument to function %1 must be a document node. %2 is not a document node. - + The default collection is undefined + %1 cannot be retrieved - + The normalization form %1 is unsupported. The supported forms are %2, %3, %4, and %5, and none, i.e. the empty string (no normalization). - + A zone offset must be in the range %1..%2 inclusive. %3 is out of range. + %1 is not a whole number of minutes. - + Required cardinality is %1; got cardinality %2. - + The item %1 did not match the required type %2. + + %1 is an unknown schema type. + Only one %1 declaration can occur in the query prolog. + The initialization of variable %1 depends on itself + No variable by name %1 exists - + The variable %1 is unused - + Version %1 is not supported. The supported XQuery version is 1.0. + The encoding %1 is invalid. It must contain Latin characters only, must not contain whitespace, and must match the regular expression %2. + No function with signature %1 is available + + A default namespace declaration must occur before function, variable, and option declarations. + Namespace declarations must occur before function, variable, and option declarations. + Module imports must occur before function, variable, and option declarations. + It is not possible to redeclare prefix %1. + Prefix %1 is already declared in the prolog. + The name of an option must have a prefix. There is no default namespace for options. + The Schema Import feature is not supported, and therefore %1 declarations cannot occur. + The target namespace of a %1 cannot be empty. + The module import feature is not supported + No value is available for the external variable by name %1. + A construct was encountered which only is allowed in XQuery. + A template by name %1 has already been declared. + The keyword %1 cannot occur with any other mode name. + The value of attribute %1 must of type %2, which %3 isn't. + The prefix %1 can not be bound. By default, it is already bound to the namespace %2. + A variable by name %1 has already been declared. + A stylesheet function must have a prefixed name. + The namespace for a user defined function cannot be empty (try the predefined prefix %1 which exists for cases like this) + The namespace %1 is reserved; therefore user defined functions may not use it. Try the predefined prefix %2, which exists for these cases. + The namespace of a user defined function in a library module must be equivalent to the module namespace. In other words, it should be %1 instead of %2 + A function already exists with the signature %1. + No external functions are supported. All supported functions can be used directly, without first declaring them as external + An argument by name %1 has already been declared. Every argument name must be unique. + When function %1 is used for matching inside a pattern, the argument must be a variable reference or a string literal. + In an XSL-T pattern, the first argument to function %1 must be a string literal, when used for matching. + In an XSL-T pattern, the first argument to function %1 must be a literal or a variable reference, when used for matching. + In an XSL-T pattern, function %1 cannot have a third argument. + In an XSL-T pattern, only function %1 and %2, not %3, can be used for matching. + In an XSL-T pattern, axis %1 cannot be used, only axis %2 or %3 can. + %1 is an invalid template mode name. + The name of a variable bound in a for-expression must be different from the positional variable. Hence, the two variables named %1 collide. + The Schema Validation Feature is not supported. Hence, %1-expressions may not be used. + None of the pragma expressions are supported. Therefore, a fallback expression must be present + Each name of a template parameter must be unique; %1 is duplicated. + The %1-axis is unsupported in XQuery + %1 is not a valid name for a processing-instruction. + %1 is not a valid numeric literal. + No function by name %1 is available. + The namespace URI cannot be the empty string when binding to a prefix, %1. + %1 is an invalid namespace URI. + It is not possible to bind to the prefix %1 + Namespace %1 can only be bound to %2 (and it is, in either case, pre-declared). + Prefix %1 can only be bound to %2 (and it is, in either case, pre-declared). + Two namespace declaration attributes have the same name: %1. + The namespace URI must be a constant and cannot use enclosed expressions. + An attribute by name %1 has already appeared on this element. + A direct element constructor is not well-formed. %1 is ended with %2. + The name %1 does not refer to any schema type. + %1 is an complex type. Casting to complex types is not possible. However, casting to atomic types such as %2 works. + %1 is not an atomic type. Casting is only possible to atomic types. + + %1 is not in the in-scope attribute declarations. Note that the schema import feature is not supported. + The name of an extension expression must be in a namespace. - + empty + zero or one + exactly one + one or more + zero or more - + Required type is %1, but %2 was found. + Promoting %1 to %2 may cause loss of precision. + The focus is undefined. - + It's not possible to add attributes after any other kind of node. + An attribute by name %1 has already been created. - + Only the Unicode Codepoint Collation is supported(%1). %2 is unsupported. - + Attribute %1 can't be serialized because it appears at the top level. - + %1 is an unsupported encoding. + %1 contains octets which are disallowed in the requested encoding %2. + The codepoint %1, occurring in %2 using encoding %3, is an invalid XML character. - + Ambiguous rule match. - - In a namespace constructor, the value for a namespace value cannot be an empty string. + + In a namespace constructor, the value for a namespace cannot be an empty string. + The prefix must be a valid %1, which %2 is not. + The prefix %1 cannot be bound. + Only the prefix %1 can be bound to %2 and vice versa. - + Circularity detected - + The parameter %1 is required, but no corresponding %2 is supplied. + The parameter %1 is passed, but no corresponding %2 exists. - + The URI cannot have a fragment - + Element %1 is not allowed at this location. + Text nodes are not allowed at this location. + Parse error: %1 + The value of the XSL-T version attribute must be a value of type %1, which %2 isn't. + Running an XSL-T 1.0 stylesheet with a 2.0 processor. + Unknown XSL-T attribute %1. + Attribute %1 and %2 are mutually exclusive. + In a simplified stylesheet module, attribute %1 must be present. + If element %1 has no attribute %2, it cannot have attribute %3 or %4. + Element %1 must have at least one of the attributes %2 or %3. + At least one mode must be specified in the %1-attribute on element %2. - + Attribute %1 cannot appear on the element %2. Only the standard attributes can appear. + Attribute %1 cannot appear on the element %2. Only %3 is allowed, and the standard attributes. + Attribute %1 cannot appear on the element %2. Allowed is %3, %4, and the standard attributes. + Attribute %1 cannot appear on the element %2. Allowed is %3, and the standard attributes. + XSL-T attributes on XSL-T elements must be in the null namespace, not in the XSL-T namespace which %1 is. + The attribute %1 must appear on element %2. + The element with local name %1 does not exist in XSL-T. - + Element %1 must come last. + At least one %1-element must occur before %2. + Only one %1-element can appear. + At least one %1-element must occur inside %2. + When attribute %1 is present on %2, a sequence constructor cannot be used. + Element %1 must have either a %2-attribute or a sequence constructor. + When a parameter is required, a default value cannot be supplied through a %1-attribute or a sequence constructor. + Element %1 cannot have children. + Element %1 cannot have a sequence constructor. + + The attribute %1 cannot appear on %2, when it is a child of %3. + A parameter in a function cannot be declared to be a tunnel. + This processor is not Schema-aware and therefore %1 cannot be used. + Top level stylesheet elements must be in a non-null namespace, which %1 isn't. + The value for attribute %1 on element %2 must either be %3 or %4, not %5. + Attribute %1 cannot have the value %2. + The attribute %1 can only appear on the first %2 element. + At least one %1 element must appear as child of %2. @@ -6305,11 +7731,13 @@ Vælg et andet filnavn. VolumeSlider - + Muted + + Volume: %1% Lydstyrke: %1% diff --git a/translations/qt_help_da.ts b/translations/qt_help_da.ts index 0e4a362..73609a1 100644 --- a/translations/qt_help_da.ts +++ b/translations/qt_help_da.ts @@ -4,27 +4,27 @@ QCLuceneResultWidget - + Search Results Søgeresultater - + Note: Bemærk: - + The search results may not be complete since the documentation is still being indexed! Søgeresultaterne kan være ufuldstændige, fordi dokumentationen stadig indekseres! - + Your search did not match any documents. Søgningen matchede ikke nogen dokumenter. - + (The reason for this might be that the documentation is still being indexed.) (Ã…rsagen kan være, at dokumentationen stadig indekseres.) @@ -32,72 +32,78 @@ QHelpCollectionHandler - + The collection file is not set up yet! Hjælpesamlingen er ikke konfigureret endnu! - + + Cannot load sqlite database driver! + Kan ikke indlæse sqlite database-driver! + + + + Cannot open collection file: %1 Kan ikke Ã¥bne hjælpesamlingen: %1 - + Cannot create tables in file %1! Kan ikke oprette tabler i filen %1! - + The specified collection file already exists! Den angivne hjælpesamling findes allerede! - + Cannot create directory: %1 Kan ikke oprette kataloget: %1 - + Cannot copy collection file: %1 Kan ikke kopiere hjælpesamling: %1 - + Unknown filter! Ukendt filter! - + Cannot register filter %1! Kan ikke registrere filteret %1! - + Cannot open documentation file %1! Kan ikke Ã¥bne dokumentationsfilen %1! - + Invalid documentation file! Ugyldig dokumentationsfil! - + The namespace %1 was not registered! Navnerummet %1 blev ikke registreret! - + Namespace %1 already exists! Navnerummet %1 findes allerede! - + Cannot register namespace! Kan ikke registrere navnerummet! - + Cannot open database to optimize! Kan ikke Ã¥bne den database, der skal optimeres! @@ -105,15 +111,19 @@ QHelpDBReader - Cannot open DB! - Kan ikke Ã¥bne DB! + Kan ikke Ã¥bne DB! + + + + Cannot open database '%1' '%2': %3 + Kan ikke Ã¥bne database '%1' '%2': %3 QHelpEngineCore - + The specified namespace does not exist! Det angivne navnerum findes ikke! @@ -121,125 +131,135 @@ QHelpEngineCorePrivate - + + Cannot open documentation file %1: %2! + Kan ikke Ã¥bne dokumentationsfil %1: %2! + + Cannot open collection file %1! - Kan ikke Ã¥bne hjælpesamlingen %1! + Kan ikke Ã¥bne hjælpesamlingen %1! - Cannot open documentation file %1! - Kan ikke Ã¥bne dokumentationsfilen %1! + Kan ikke Ã¥bne dokumentationsfilen %1! QHelpGenerator - + Invalid help data! Ugyldigt hjælpedata! - + No output file name specified! Der er ikke anført et output-filnavn! - The file %1 already exists! - Filen %1 findes allerede! + Filen %1 findes allerede! - + Building up file structure... Bygger filstruktur... - Cannot open DB! - Kan ikke Ã¥bne DB! + Kan ikke Ã¥bne DB! + + + + The file %1 cannot be overwritten! + Filen %1 kan ikke overskrives! - + + Cannot open data base file %1! + Kan ikke Ã¥bne databasefil %1! + + + Cannot register namespace %1! Kan ikke registrere navnerummet %1! - + Insert custom filters... Indsæt brugerdefinerede filtre... - + Insert help data for filter section (%1 of %2)... Indsæt hjælpedata til filtersektion (%1 af %2)... - + Documentation successfully generated. Dokumentationen blev genereret. - + Some tables already exist! Nogle af tabellerne findes allerede! - + Cannot create tables! Kan ikke oprette tabeller! - + Cannot register virtual folder! Kan ikke registrere virtuel mappe! - + Insert files... Indsæt filer... - + The file %1 does not exist! Skipping it. Filen %1 findes ikke, og den springes over. - + Cannot open file %1! Skipping it. Kan ikke Ã¥bne filen %1, og den springes over. - Cannot insert file data into database! - Kan ikke indsætte fildata i databasen! + Kan ikke indsætte fildata i databasen! - + The filter %1 is already registered! Filtret %1 er allerede registreret! - + Cannot register filter %1! Kan ikke registrere filtret %1! - + Insert indices... Indsæt indeks... - + Insert contents... Indsæt indhold... - + Cannot insert contents! Kan ikke indsætte indhold! - + Cannot register contents! Kan ikke registrere indhold! @@ -247,42 +267,42 @@ QHelpSearchQueryWidget - + Search for: Søg efter: - + Search Søg - + Advanced search Avanceret søgning - + words <B>similar</B> to: ord <B>tilsvarende</B>: - + <B>without</B> the words: <B>uden</B> ordene: - + with <B>exact phrase</B>: med den <B>eksakte sætning</B>: - + with <B>all</B> of the words: med <B>alle</B> ordene: - + with <B>at least one</B> of the words: med <B>mindst ét</B> af ordene: @@ -290,7 +310,7 @@ QHelpSearchResultWidget - + 0 - 0 of 0 Hits 0 - 0 af 0 Hits @@ -298,7 +318,7 @@ QHelpSearchResultWidgetPrivate - + %1 - %2 of %3 Hits %1 - %2 af %3 Hits @@ -306,47 +326,60 @@ QObject - + Untitled Ingen titel - Unknown token at line %1. - Ukendt symbol pÃ¥ linie %1. + Ukendt symbol pÃ¥ linie %1. - Unknown token at line %1. Expected "QtHelpProject"! - Ukendt symbol pÃ¥ linie %1. Forventet "QtHelpProject"! + Ukendt symbol pÃ¥ linie %1. Forventet "QtHelpProject"! + + + + Unknown token. + Ukendt token. + + + + Unknown token. Expected "QtHelpProject"! + Ukendt token. Forventede "QtHelpProject"! + + + + Error in line %1: %2 + Fejl i linie %1: %2 - + A virtual folder must not contain a '/' character! En virtuel mappe mÃ¥ ikke indholde tegnet '/'! - + A namespace must not contain a '/' character! Et navnerum mÃ¥ ikke indeholde tegnet '/'! - + Missing namespace in QtHelpProject. Navnerum i +++ mangler. - + Missing virtual folder in QtHelpProject Virtuel mappe i QtHelpProject mangler - + Missing attribute in keyword at line %1. Attribut i nøgleord pÃ¥ linie %1 mangler. - + The input file %1 could not be opened! Input-filen %1 kunne ikke Ã¥bnes! diff --git a/translations/translations.pri b/translations/translations.pri index efefa09..0c5c1ee 100644 --- a/translations/translations.pri +++ b/translations/translations.pri @@ -21,7 +21,7 @@ LRELEASE = $$fixPath($$QT_BUILD_TREE/bin/lrelease) ###### Qt Libraries -QT_TS = de fr zh_CN untranslated ar es iw ja_JP pl pt ru sk sv uk zh_TW +QT_TS = de fr zh_CN untranslated ar es iw ja_JP pl pt ru sk sv uk zh_TW da ts-qt.commands = (cd $$QT_SOURCE_TREE/src && $$LUPDATE \ 3rdparty/phonon \ -- cgit v0.12 From a43ea2e6f5feffa44119a54e25a9fffdd435c389 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 27 May 2009 08:24:13 +1000 Subject: Remove more unneeded semicolons. --- src/declarative/extra/qfxintegermodel.cpp | 2 +- src/declarative/extra/qmlsqlconnection.cpp | 2 +- src/declarative/extra/qmlsqlquery.cpp | 4 ++-- src/declarative/extra/qmlxmllistmodel.cpp | 4 ++-- src/declarative/extra/qnumberformat.cpp | 2 +- src/declarative/fx/qfxscalegrid.cpp | 2 +- src/declarative/qml/qmlengine.cpp | 6 +++--- src/declarative/qml/qmlprivate.h | 2 +- src/declarative/qml/qmlpropertyvaluesource.cpp | 2 +- src/declarative/util/qmlbind.h | 8 ++++---- src/declarative/widgets/graphicslayouts.cpp | 4 ++-- src/declarative/widgets/graphicswidgets.cpp | 8 ++++---- 12 files changed, 23 insertions(+), 23 deletions(-) diff --git a/src/declarative/extra/qfxintegermodel.cpp b/src/declarative/extra/qfxintegermodel.cpp index 3c4d0d9..2a85ee1 100644 --- a/src/declarative/extra/qfxintegermodel.cpp +++ b/src/declarative/extra/qfxintegermodel.cpp @@ -43,7 +43,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QFxIntegerModel, IntegerModel); +QML_DEFINE_TYPE(QFxIntegerModel, IntegerModel) class QFxIntegerModelPrivate { diff --git a/src/declarative/extra/qmlsqlconnection.cpp b/src/declarative/extra/qmlsqlconnection.cpp index 25ab033..b65fe35 100644 --- a/src/declarative/extra/qmlsqlconnection.cpp +++ b/src/declarative/extra/qmlsqlconnection.cpp @@ -51,7 +51,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QmlSqlConnection, SqlConnection); +QML_DEFINE_TYPE(QmlSqlConnection, SqlConnection) class QmlSqlConnectionPrivate: public QObjectPrivate { diff --git a/src/declarative/extra/qmlsqlquery.cpp b/src/declarative/extra/qmlsqlquery.cpp index 5bd1459..0e2e91b 100644 --- a/src/declarative/extra/qmlsqlquery.cpp +++ b/src/declarative/extra/qmlsqlquery.cpp @@ -52,8 +52,8 @@ #include QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QmlSqlBind, SqlBind); -QML_DEFINE_TYPE(QmlSqlQuery, SqlQuery); +QML_DEFINE_TYPE(QmlSqlBind, SqlBind) +QML_DEFINE_TYPE(QmlSqlQuery, SqlQuery) class QmlSqlBindPrivate : public QObjectPrivate { diff --git a/src/declarative/extra/qmlxmllistmodel.cpp b/src/declarative/extra/qmlxmllistmodel.cpp index 9259c83..a7f5d72 100644 --- a/src/declarative/extra/qmlxmllistmodel.cpp +++ b/src/declarative/extra/qmlxmllistmodel.cpp @@ -58,8 +58,8 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(XmlListModelRole, Role); -QML_DEFINE_TYPE(QmlXmlListModel, XmlListModel); +QML_DEFINE_TYPE(XmlListModelRole, Role) +QML_DEFINE_TYPE(QmlXmlListModel, XmlListModel) class QmlXmlListModelPrivate; diff --git a/src/declarative/extra/qnumberformat.cpp b/src/declarative/extra/qnumberformat.cpp index 79e328a..424c125 100644 --- a/src/declarative/extra/qnumberformat.cpp +++ b/src/declarative/extra/qnumberformat.cpp @@ -43,7 +43,7 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QNumberFormat,NumberFormat); +QML_DEFINE_TYPE(QNumberFormat,NumberFormat) QNumberFormat::QNumberFormat(QObject *parent) : QObject(parent), _number(0), _type(Decimal), _groupingSize(0) diff --git a/src/declarative/fx/qfxscalegrid.cpp b/src/declarative/fx/qfxscalegrid.cpp index 325f7d9..abe8e0d 100644 --- a/src/declarative/fx/qfxscalegrid.cpp +++ b/src/declarative/fx/qfxscalegrid.cpp @@ -71,7 +71,7 @@ QT_BEGIN_NAMESPACE imageFile: picture.png \endcode */ -QML_DEFINE_NOCREATE_TYPE(QFxScaleGrid); +QML_DEFINE_NOCREATE_TYPE(QFxScaleGrid) QFxScaleGrid::QFxScaleGrid() : QObject(), _left(0), _top(0), _right(0), _bottom(0) { diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index c0ea463..3db8d92 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -75,11 +75,11 @@ QT_BEGIN_NAMESPACE -DEFINE_BOOL_CONFIG_OPTION(qmlDebugger, QML_DEBUGGER); +DEFINE_BOOL_CONFIG_OPTION(qmlDebugger, QML_DEBUGGER) -Q_DECLARE_METATYPE(QmlMetaProperty); +Q_DECLARE_METATYPE(QmlMetaProperty) -QML_DEFINE_TYPE(QObject,Object); +QML_DEFINE_TYPE(QObject,Object) static QScriptValue qmlMetaProperty_emit(QScriptContext *ctx, QScriptEngine *engine) { diff --git a/src/declarative/qml/qmlprivate.h b/src/declarative/qml/qmlprivate.h index 2a9c503..62524aa 100644 --- a/src/declarative/qml/qmlprivate.h +++ b/src/declarative/qml/qmlprivate.h @@ -237,7 +237,7 @@ namespace QmlPrivate return new T(other); } }; -}; +} template int QmlPrivate::list_op(QmlPrivate::ListOp op, int val, diff --git a/src/declarative/qml/qmlpropertyvaluesource.cpp b/src/declarative/qml/qmlpropertyvaluesource.cpp index 4770929..18092c8 100644 --- a/src/declarative/qml/qmlpropertyvaluesource.cpp +++ b/src/declarative/qml/qmlpropertyvaluesource.cpp @@ -48,7 +48,7 @@ QT_BEGIN_NAMESPACE \class QmlPropertyValueSource \brief The QmlPropertyValueSource class is inherited by property value sources such as animations and bindings. */ -QML_DEFINE_NOCREATE_TYPE(QmlPropertyValueSource); +QML_DEFINE_NOCREATE_TYPE(QmlPropertyValueSource) /*! Constructs a QmlPropertyValueSource with parent \a parent. diff --git a/src/declarative/util/qmlbind.h b/src/declarative/util/qmlbind.h index 9d4ae8d..8ff4152 100644 --- a/src/declarative/util/qmlbind.h +++ b/src/declarative/util/qmlbind.h @@ -55,11 +55,11 @@ class QmlBindPrivate; class Q_DECLARATIVE_EXPORT QmlBind : public QObject { Q_OBJECT - Q_DECLARE_PRIVATE(QmlBind); + Q_DECLARE_PRIVATE(QmlBind) - Q_PROPERTY(QObject *target READ object WRITE setObject); - Q_PROPERTY(QString property READ property WRITE setProperty); - Q_PROPERTY(QVariant value READ value WRITE setValue); + Q_PROPERTY(QObject *target READ object WRITE setObject) + Q_PROPERTY(QString property READ property WRITE setProperty) + Q_PROPERTY(QVariant value READ value WRITE setValue) public: QmlBind(QObject *parent=0); diff --git a/src/declarative/widgets/graphicslayouts.cpp b/src/declarative/widgets/graphicslayouts.cpp index 21acbcd..f2d8dbc 100644 --- a/src/declarative/widgets/graphicslayouts.cpp +++ b/src/declarative/widgets/graphicslayouts.cpp @@ -45,8 +45,8 @@ QT_BEGIN_NAMESPACE -QML_DEFINE_INTERFACE(QGraphicsLayoutItem); -QML_DEFINE_INTERFACE(QGraphicsLayout); +QML_DEFINE_INTERFACE(QGraphicsLayoutItem) +QML_DEFINE_INTERFACE(QGraphicsLayout) class LinearLayoutAttached : public QObject { diff --git a/src/declarative/widgets/graphicswidgets.cpp b/src/declarative/widgets/graphicswidgets.cpp index b808807..86509f5 100644 --- a/src/declarative/widgets/graphicswidgets.cpp +++ b/src/declarative/widgets/graphicswidgets.cpp @@ -59,7 +59,7 @@ public: static_cast(parent())->setScene(scene); } }; -QML_DEFINE_EXTENDED_TYPE(QGraphicsView,QGraphicsView,QGraphicsViewDeclarativeUI); +QML_DEFINE_EXTENDED_TYPE(QGraphicsView,QGraphicsView,QGraphicsViewDeclarativeUI) class QGraphicsSceneDeclarativeUI : public QObject { @@ -111,7 +111,7 @@ private: }; Children _children; }; -QML_DEFINE_EXTENDED_TYPE(QGraphicsScene,QGraphicsScene,QGraphicsSceneDeclarativeUI); +QML_DEFINE_EXTENDED_TYPE(QGraphicsScene,QGraphicsScene,QGraphicsSceneDeclarativeUI) class QGraphicsWidgetDeclarativeUI : public QObject { @@ -164,9 +164,9 @@ private: QmlConcreteList _data; }; -QML_DEFINE_EXTENDED_TYPE(QGraphicsWidget,QGraphicsWidget,QGraphicsWidgetDeclarativeUI); +QML_DEFINE_EXTENDED_TYPE(QGraphicsWidget,QGraphicsWidget,QGraphicsWidgetDeclarativeUI) -QML_DEFINE_INTERFACE(QGraphicsItem); +QML_DEFINE_INTERFACE(QGraphicsItem) #include "graphicswidgets.moc" -- cgit v0.12 From d15db788de792815a35547059921d3305d48c119 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 27 May 2009 09:05:28 +1000 Subject: Remove more unneeded semicolons. --- src/declarative/canvas/qsimplecanvasfilter.h | 2 +- src/declarative/canvas/qsimplecanvasitem.h | 2 +- src/declarative/extra/qmlsqlconnection.h | 20 +++---- src/declarative/extra/qnumberformat.h | 16 ++--- src/declarative/fx/qfxanchors.h | 30 +++++----- src/declarative/fx/qfxcomponentinstance.h | 2 +- src/declarative/fx/qfxflickable.h | 26 ++++---- src/declarative/fx/qfxflipable.h | 2 +- src/declarative/fx/qfxgridview.h | 30 +++++----- src/declarative/fx/qfxitem.h | 4 +- src/declarative/fx/qfxlistview.h | 36 ++++++------ src/declarative/fx/qfxpainteditem.h | 4 +- src/declarative/fx/qfxparticles.h | 34 +++++------ src/declarative/fx/qfxtext.h | 2 +- src/declarative/qml/qmlbindablevalue.h | 4 +- src/declarative/util/qmlanimation.h | 88 ++++++++++++++-------------- src/declarative/util/qmlbehaviour.h | 8 +-- src/declarative/util/qmlbind.h | 2 +- src/declarative/util/qmlconnection.h | 10 ++-- src/declarative/util/qmlfollow.h | 16 ++--- src/declarative/util/qmlpackage.h | 4 +- src/declarative/util/qmlscript.h | 8 +-- src/declarative/util/qmlsetproperties.h | 6 +- src/declarative/util/qmlstate.h | 10 ++-- src/declarative/util/qmlstategroup.h | 8 +-- src/declarative/util/qmlstateoperations.h | 14 ++--- 26 files changed, 194 insertions(+), 194 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvasfilter.h b/src/declarative/canvas/qsimplecanvasfilter.h index d05dc7e..14bb765 100644 --- a/src/declarative/canvas/qsimplecanvasfilter.h +++ b/src/declarative/canvas/qsimplecanvasfilter.h @@ -70,7 +70,7 @@ public: ChildrenAboveItem = 0x04, All = 0x07 }; - Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged); + Q_PROPERTY(bool enabled READ enabled WRITE setEnabled NOTIFY enabledChanged) bool enabled() const; void setEnabled(bool); diff --git a/src/declarative/canvas/qsimplecanvasitem.h b/src/declarative/canvas/qsimplecanvasitem.h index cf23fc6..e8f1ee8 100644 --- a/src/declarative/canvas/qsimplecanvasitem.h +++ b/src/declarative/canvas/qsimplecanvasitem.h @@ -74,7 +74,7 @@ class Q_DECLARATIVE_EXPORT QSimpleCanvasItem : public QObject Q_CAST_INTERFACES(QmlDebuggerStatus) Q_DECLARE_PRIVATE(QSimpleCanvasItem) Q_ENUMS(TransformOrigin) - Q_PROPERTY(TransformOrigin transformOrigin READ transformOrigin WRITE setTransformOrigin); + Q_PROPERTY(TransformOrigin transformOrigin READ transformOrigin WRITE setTransformOrigin) public: enum ClipType { NoClip = 0x00, diff --git a/src/declarative/extra/qmlsqlconnection.h b/src/declarative/extra/qmlsqlconnection.h index dd0e5b5..306db8d 100644 --- a/src/declarative/extra/qmlsqlconnection.h +++ b/src/declarative/extra/qmlsqlconnection.h @@ -57,16 +57,16 @@ class Q_DECLARATIVE_EXPORT QmlSqlConnection : public QObject, public QmlParserSt Q_OBJECT Q_INTERFACES(QmlParserStatus) - Q_PROPERTY(QString name READ name WRITE setName); - Q_PROPERTY(QStringList tables READ tables); - Q_PROPERTY(QString databaseName READ databaseName WRITE setDatabaseName); - Q_PROPERTY(QString driver READ driver WRITE setDriver); - Q_PROPERTY(QString connectOptions READ connectOptions WRITE setConnectOptions); - Q_PROPERTY(QString hostName READ hostName WRITE setHostName); - Q_PROPERTY(int port READ port WRITE setPort); - Q_PROPERTY(QString userName READ userName WRITE setUserName); - Q_PROPERTY(QString password READ password WRITE setPassword); - Q_PROPERTY(QString lastError READ lastError); + Q_PROPERTY(QString name READ name WRITE setName) + Q_PROPERTY(QStringList tables READ tables) + Q_PROPERTY(QString databaseName READ databaseName WRITE setDatabaseName) + Q_PROPERTY(QString driver READ driver WRITE setDriver) + Q_PROPERTY(QString connectOptions READ connectOptions WRITE setConnectOptions) + Q_PROPERTY(QString hostName READ hostName WRITE setHostName) + Q_PROPERTY(int port READ port WRITE setPort) + Q_PROPERTY(QString userName READ userName WRITE setUserName) + Q_PROPERTY(QString password READ password WRITE setPassword) + Q_PROPERTY(QString lastError READ lastError) Q_CLASSINFO("DefaultProperty", "name") public: QmlSqlConnection(QObject *parent = 0); diff --git a/src/declarative/extra/qnumberformat.h b/src/declarative/extra/qnumberformat.h index aa1e447..fba9872 100644 --- a/src/declarative/extra/qnumberformat.h +++ b/src/declarative/extra/qnumberformat.h @@ -74,18 +74,18 @@ public: }; //external property, only visible - Q_PROPERTY(QString text READ text NOTIFY textChanged); + Q_PROPERTY(QString text READ text NOTIFY textChanged) //mutatable properties to modify the output (text) - Q_PROPERTY(qreal number READ number WRITE setNumber); - Q_PROPERTY(QString format READ format WRITE setFormat); - Q_PROPERTY(QLocale locale READ locale WRITE setLocale); + Q_PROPERTY(qreal number READ number WRITE setNumber) + Q_PROPERTY(QString format READ format WRITE setFormat) + Q_PROPERTY(QLocale locale READ locale WRITE setLocale) //Format specific settings - Q_PROPERTY(unsigned short groupingSeparator READ groupingSeparator WRITE setGroupingSeparator); - Q_PROPERTY(unsigned short decimalSeperator READ decimalSeparator WRITE setDecimalSeparator); - Q_PROPERTY(unsigned int groupingSize READ groupingSize WRITE setGroupingSize); - Q_PROPERTY(unsigned short currencySymbol READ currencySymbol WRITE setCurrencySymbol); + Q_PROPERTY(unsigned short groupingSeparator READ groupingSeparator WRITE setGroupingSeparator) + Q_PROPERTY(unsigned short decimalSeperator READ decimalSeparator WRITE setDecimalSeparator) + Q_PROPERTY(unsigned int groupingSize READ groupingSize WRITE setGroupingSize) + Q_PROPERTY(unsigned short currencySymbol READ currencySymbol WRITE setCurrencySymbol) QString text() const { return _text; } diff --git a/src/declarative/fx/qfxanchors.h b/src/declarative/fx/qfxanchors.h index 8c3fe89..b3f2d3f 100644 --- a/src/declarative/fx/qfxanchors.h +++ b/src/declarative/fx/qfxanchors.h @@ -85,21 +85,21 @@ class Q_DECLARATIVE_EXPORT QFxAnchors : public QObject { Q_OBJECT - Q_PROPERTY(QFxAnchorLine left READ left WRITE setLeft RESET resetLeft); - Q_PROPERTY(QFxAnchorLine right READ right WRITE setRight RESET resetRight); - Q_PROPERTY(QFxAnchorLine horizontalCenter READ horizontalCenter WRITE setHorizontalCenter RESET resetHorizontalCenter); - Q_PROPERTY(QFxAnchorLine top READ top WRITE setTop RESET resetTop); - Q_PROPERTY(QFxAnchorLine bottom READ bottom WRITE setBottom RESET resetBottom); - Q_PROPERTY(QFxAnchorLine verticalCenter READ verticalCenter WRITE setVerticalCenter RESET resetVerticalCenter); - Q_PROPERTY(QFxAnchorLine baseline READ baseline WRITE setBaseline RESET resetBaseline); - Q_PROPERTY(int leftMargin READ leftMargin WRITE setLeftMargin NOTIFY leftMarginChanged); - Q_PROPERTY(int rightMargin READ rightMargin WRITE setRightMargin NOTIFY rightMarginChanged); - Q_PROPERTY(int horizontalCenterOffset READ horizontalCenterOffset WRITE setHorizontalCenterOffset NOTIFY horizontalCenterOffsetChanged()); - Q_PROPERTY(int topMargin READ topMargin WRITE setTopMargin NOTIFY topMarginChanged); - Q_PROPERTY(int bottomMargin READ bottomMargin WRITE setBottomMargin NOTIFY bottomMarginChanged); - Q_PROPERTY(int verticalCenterOffset READ verticalCenterOffset WRITE setVerticalCenterOffset NOTIFY verticalCenterOffsetChanged()); - Q_PROPERTY(QFxItem *fill READ fill WRITE setFill); - Q_PROPERTY(QFxItem *centeredIn READ centeredIn WRITE setCenteredIn); + Q_PROPERTY(QFxAnchorLine left READ left WRITE setLeft RESET resetLeft) + Q_PROPERTY(QFxAnchorLine right READ right WRITE setRight RESET resetRight) + Q_PROPERTY(QFxAnchorLine horizontalCenter READ horizontalCenter WRITE setHorizontalCenter RESET resetHorizontalCenter) + Q_PROPERTY(QFxAnchorLine top READ top WRITE setTop RESET resetTop) + Q_PROPERTY(QFxAnchorLine bottom READ bottom WRITE setBottom RESET resetBottom) + Q_PROPERTY(QFxAnchorLine verticalCenter READ verticalCenter WRITE setVerticalCenter RESET resetVerticalCenter) + Q_PROPERTY(QFxAnchorLine baseline READ baseline WRITE setBaseline RESET resetBaseline) + Q_PROPERTY(int leftMargin READ leftMargin WRITE setLeftMargin NOTIFY leftMarginChanged) + Q_PROPERTY(int rightMargin READ rightMargin WRITE setRightMargin NOTIFY rightMarginChanged) + Q_PROPERTY(int horizontalCenterOffset READ horizontalCenterOffset WRITE setHorizontalCenterOffset NOTIFY horizontalCenterOffsetChanged()) + Q_PROPERTY(int topMargin READ topMargin WRITE setTopMargin NOTIFY topMarginChanged) + Q_PROPERTY(int bottomMargin READ bottomMargin WRITE setBottomMargin NOTIFY bottomMarginChanged) + Q_PROPERTY(int verticalCenterOffset READ verticalCenterOffset WRITE setVerticalCenterOffset NOTIFY verticalCenterOffsetChanged()) + Q_PROPERTY(QFxItem *fill READ fill WRITE setFill) + Q_PROPERTY(QFxItem *centeredIn READ centeredIn WRITE setCenteredIn) public: QFxAnchors(QObject *parent=0); diff --git a/src/declarative/fx/qfxcomponentinstance.h b/src/declarative/fx/qfxcomponentinstance.h index 4b8c142..e749272 100644 --- a/src/declarative/fx/qfxcomponentinstance.h +++ b/src/declarative/fx/qfxcomponentinstance.h @@ -55,7 +55,7 @@ class Q_DECLARATIVE_EXPORT QFxComponentInstance : public QFxItem { Q_OBJECT Q_PROPERTY(QmlComponent *component READ component WRITE setComponent) - Q_PROPERTY(QFxItem *instance READ instance); + Q_PROPERTY(QFxItem *instance READ instance) Q_CLASSINFO("DefaultProperty", "component") public: QFxComponentInstance(QFxItem *parent=0); diff --git a/src/declarative/fx/qfxflickable.h b/src/declarative/fx/qfxflickable.h index dcbc6bb..77aaf50 100644 --- a/src/declarative/fx/qfxflickable.h +++ b/src/declarative/fx/qfxflickable.h @@ -58,8 +58,8 @@ class Q_DECLARATIVE_EXPORT QFxFlickable : public QFxItem Q_PROPERTY(bool overShoot READ overShoot WRITE setOverShoot) Q_PROPERTY(int viewportWidth READ viewportWidth WRITE setViewportWidth NOTIFY viewportWidthChanged) Q_PROPERTY(int viewportHeight READ viewportHeight WRITE setViewportHeight NOTIFY viewportHeightChanged) - Q_PROPERTY(qreal xPosition READ xPosition WRITE setXPosition NOTIFY positionChanged); - Q_PROPERTY(qreal yPosition READ yPosition WRITE setYPosition NOTIFY positionChanged); + Q_PROPERTY(qreal xPosition READ xPosition WRITE setXPosition NOTIFY positionChanged) + Q_PROPERTY(qreal yPosition READ yPosition WRITE setYPosition NOTIFY positionChanged) Q_PROPERTY(bool moving READ isMoving NOTIFY movingChanged) Q_PROPERTY(bool flicking READ isFlicking NOTIFY flickingChanged) Q_PROPERTY(int velocityDecay READ velocityDecay WRITE setVelocityDecay NOTIFY velocityDecayChanged) @@ -68,17 +68,17 @@ class Q_DECLARATIVE_EXPORT QFxFlickable : public QFxItem Q_PROPERTY(DragMode dragMode READ dragMode WRITE setDragMode) Q_PROPERTY(qreal xVelocity READ xVelocity NOTIFY velocityChanged) Q_PROPERTY(qreal yVelocity READ yVelocity NOTIFY velocityChanged) - Q_PROPERTY(bool atXEnd READ isAtXEnd NOTIFY isAtBoundaryChanged); - Q_PROPERTY(bool atYEnd READ isAtYEnd NOTIFY isAtBoundaryChanged); - Q_PROPERTY(bool atXBeginning READ isAtXBeginning NOTIFY isAtBoundaryChanged); - Q_PROPERTY(bool atYBeginning READ isAtYBeginning NOTIFY isAtBoundaryChanged); - Q_PROPERTY(qreal pageXPosition READ pageXPosition NOTIFY pageChanged); - Q_PROPERTY(qreal pageYPosition READ pageYPosition NOTIFY pageChanged); - Q_PROPERTY(qreal pageWidth READ pageWidth NOTIFY pageChanged); - Q_PROPERTY(qreal pageHeight READ pageHeight NOTIFY pageChanged); - - Q_PROPERTY(QmlList* flickableData READ flickableData); - Q_PROPERTY(QmlList* flickableChildren READ flickableChildren); + Q_PROPERTY(bool atXEnd READ isAtXEnd NOTIFY isAtBoundaryChanged) + Q_PROPERTY(bool atYEnd READ isAtYEnd NOTIFY isAtBoundaryChanged) + Q_PROPERTY(bool atXBeginning READ isAtXBeginning NOTIFY isAtBoundaryChanged) + Q_PROPERTY(bool atYBeginning READ isAtYBeginning NOTIFY isAtBoundaryChanged) + Q_PROPERTY(qreal pageXPosition READ pageXPosition NOTIFY pageChanged) + Q_PROPERTY(qreal pageYPosition READ pageYPosition NOTIFY pageChanged) + Q_PROPERTY(qreal pageWidth READ pageWidth NOTIFY pageChanged) + Q_PROPERTY(qreal pageHeight READ pageHeight NOTIFY pageChanged) + + Q_PROPERTY(QmlList* flickableData READ flickableData) + Q_PROPERTY(QmlList* flickableChildren READ flickableChildren) Q_CLASSINFO("DefaultProperty", "flickableData") public: diff --git a/src/declarative/fx/qfxflipable.h b/src/declarative/fx/qfxflipable.h index be9e755..6630633 100644 --- a/src/declarative/fx/qfxflipable.h +++ b/src/declarative/fx/qfxflipable.h @@ -61,7 +61,7 @@ class Q_DECLARATIVE_EXPORT QFxFlipable : public QFxItem { Q_OBJECT - Q_ENUMS(Side); + Q_ENUMS(Side) Q_PROPERTY(QFxItem *front READ front WRITE setFront) Q_PROPERTY(QFxItem *back READ back WRITE setBack) Q_PROPERTY(QFxAxis *axis READ axis WRITE setAxis) diff --git a/src/declarative/fx/qfxgridview.h b/src/declarative/fx/qfxgridview.h index 73f3046..1514451 100644 --- a/src/declarative/fx/qfxgridview.h +++ b/src/declarative/fx/qfxgridview.h @@ -54,21 +54,21 @@ class QFxGridViewPrivate; class Q_DECLARATIVE_EXPORT QFxGridView : public QFxFlickable { Q_OBJECT - Q_DECLARE_PRIVATE(QFxGridView); - - Q_PROPERTY(QVariant model READ model WRITE setModel); - Q_CLASSINFO("DefaultProperty", "delegate"); - Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate); - Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged); - Q_PROPERTY(QFxItem *current READ currentItem NOTIFY currentIndexChanged); - Q_PROPERTY(int count READ count NOTIFY countChanged); - Q_PROPERTY(QmlComponent *highlight READ highlight WRITE setHighlight); - Q_PROPERTY(bool autoHighlight READ autoHighlight WRITE setAutoHighlight); - Q_PROPERTY(Flow flow READ flow WRITE setFlow); - Q_PROPERTY(bool wrap READ isWrapEnabled WRITE setWrapEnabled); - Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer); - Q_PROPERTY(int cellWidth READ cellWidth WRITE setCellWidth NOTIFY cellSizeChanged); - Q_PROPERTY(int cellHeight READ cellHeight WRITE setCellHeight NOTIFY cellSizeChanged); + Q_DECLARE_PRIVATE(QFxGridView) + + Q_PROPERTY(QVariant model READ model WRITE setModel) + Q_CLASSINFO("DefaultProperty", "delegate") + Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate) + Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) + Q_PROPERTY(QFxItem *current READ currentItem NOTIFY currentIndexChanged) + Q_PROPERTY(int count READ count NOTIFY countChanged) + Q_PROPERTY(QmlComponent *highlight READ highlight WRITE setHighlight) + Q_PROPERTY(bool autoHighlight READ autoHighlight WRITE setAutoHighlight) + Q_PROPERTY(Flow flow READ flow WRITE setFlow) + Q_PROPERTY(bool wrap READ isWrapEnabled WRITE setWrapEnabled) + Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer) + Q_PROPERTY(int cellWidth READ cellWidth WRITE setCellWidth NOTIFY cellSizeChanged) + Q_PROPERTY(int cellHeight READ cellHeight WRITE setCellHeight NOTIFY cellSizeChanged) public: QFxGridView(QFxItem *parent=0); diff --git a/src/declarative/fx/qfxitem.h b/src/declarative/fx/qfxitem.h index 778c10f..8ca1f9e 100644 --- a/src/declarative/fx/qfxitem.h +++ b/src/declarative/fx/qfxitem.h @@ -63,8 +63,8 @@ QT_MODULE(Declarative) class Q_DECLARATIVE_EXPORT QFxContents : public QObject { Q_OBJECT - Q_PROPERTY(int height READ height NOTIFY heightChanged); - Q_PROPERTY(int width READ width NOTIFY widthChanged); + Q_PROPERTY(int height READ height NOTIFY heightChanged) + Q_PROPERTY(int width READ width NOTIFY widthChanged) public: QFxContents(); diff --git a/src/declarative/fx/qfxlistview.h b/src/declarative/fx/qfxlistview.h index 4aa9810..5dfb0e4 100644 --- a/src/declarative/fx/qfxlistview.h +++ b/src/declarative/fx/qfxlistview.h @@ -55,24 +55,24 @@ class QFxListViewPrivate; class Q_DECLARATIVE_EXPORT QFxListView : public QFxFlickable { Q_OBJECT - Q_DECLARE_PRIVATE(QFxListView); - - Q_ENUMS(CurrentItemPositioning); - Q_PROPERTY(QVariant model READ model WRITE setModel); - Q_CLASSINFO("DefaultProperty", "delegate"); - Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate); - Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged); - Q_PROPERTY(QFxItem *current READ currentItem NOTIFY currentIndexChanged); - Q_PROPERTY(int count READ count NOTIFY countChanged); - Q_PROPERTY(QmlComponent *highlight READ highlight WRITE setHighlight); - Q_PROPERTY(bool autoHighlight READ autoHighlight WRITE setAutoHighlight); - Q_PROPERTY(CurrentItemPositioning currentItemPositioning READ currentItemPositioning WRITE setCurrentItemPositioning); - Q_PROPERTY(int snapPosition READ snapPosition WRITE setSnapPosition); - Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation); - Q_PROPERTY(bool wrap READ isWrapEnabled WRITE setWrapEnabled); - Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer); - Q_PROPERTY(QString sectionExpression READ sectionExpression WRITE setSectionExpression NOTIFY sectionExpressionChanged); - Q_PROPERTY(QString currentSection READ currentSection NOTIFY currentSectionChanged); + Q_DECLARE_PRIVATE(QFxListView) + + Q_ENUMS(CurrentItemPositioning) + Q_PROPERTY(QVariant model READ model WRITE setModel) + Q_CLASSINFO("DefaultProperty", "delegate") + Q_PROPERTY(QmlComponent *delegate READ delegate WRITE setDelegate) + Q_PROPERTY(int currentIndex READ currentIndex WRITE setCurrentIndex NOTIFY currentIndexChanged) + Q_PROPERTY(QFxItem *current READ currentItem NOTIFY currentIndexChanged) + Q_PROPERTY(int count READ count NOTIFY countChanged) + Q_PROPERTY(QmlComponent *highlight READ highlight WRITE setHighlight) + Q_PROPERTY(bool autoHighlight READ autoHighlight WRITE setAutoHighlight) + Q_PROPERTY(CurrentItemPositioning currentItemPositioning READ currentItemPositioning WRITE setCurrentItemPositioning) + Q_PROPERTY(int snapPosition READ snapPosition WRITE setSnapPosition) + Q_PROPERTY(Qt::Orientation orientation READ orientation WRITE setOrientation) + Q_PROPERTY(bool wrap READ isWrapEnabled WRITE setWrapEnabled) + Q_PROPERTY(int cacheBuffer READ cacheBuffer WRITE setCacheBuffer) + Q_PROPERTY(QString sectionExpression READ sectionExpression WRITE setSectionExpression NOTIFY sectionExpressionChanged) + Q_PROPERTY(QString currentSection READ currentSection NOTIFY currentSectionChanged) public: QFxListView(QFxItem *parent=0); diff --git a/src/declarative/fx/qfxpainteditem.h b/src/declarative/fx/qfxpainteditem.h index 997c324..e086894 100644 --- a/src/declarative/fx/qfxpainteditem.h +++ b/src/declarative/fx/qfxpainteditem.h @@ -60,8 +60,8 @@ public: QFxPaintedItem(QFxItem *parent=0); ~QFxPaintedItem(); - Q_PROPERTY(QSize contentsSize READ contentsSize WRITE setContentsSize); - Q_PROPERTY(bool smooth READ isSmooth WRITE setSmooth); + Q_PROPERTY(QSize contentsSize READ contentsSize WRITE setContentsSize) + Q_PROPERTY(bool smooth READ isSmooth WRITE setSmooth) #if defined(QFX_RENDER_QPAINTER) void paintContents(QPainter &painter); diff --git a/src/declarative/fx/qfxparticles.h b/src/declarative/fx/qfxparticles.h index 9f0d04c..6ef2582 100644 --- a/src/declarative/fx/qfxparticles.h +++ b/src/declarative/fx/qfxparticles.h @@ -128,15 +128,15 @@ public: qreal y_var; }; - Q_PROPERTY(int xvariance READ xVariance WRITE setXVariance); + Q_PROPERTY(int xvariance READ xVariance WRITE setXVariance) int xVariance() const { return int(_xvariance * 1000); } void setXVariance(int var) { _xvariance = var / 1000.0; } - Q_PROPERTY(int yvariance READ yVariance WRITE setYVariance); + Q_PROPERTY(int yvariance READ yVariance WRITE setYVariance) int yVariance() const { return int(_yvariance * 1000); } void setYVariance(int var) { _yvariance = var / 1000.0; } - Q_PROPERTY(int pace READ pace WRITE setPace); + Q_PROPERTY(int pace READ pace WRITE setPace) int pace() const { return int(_pace * 1000); } void setPace(int pace) { _pace = pace / 1000.0; } @@ -153,20 +153,20 @@ class Q_DECLARATIVE_EXPORT QFxParticles : public QFxItem { Q_OBJECT - Q_PROPERTY(QString source READ source WRITE setSource); - Q_PROPERTY(int count READ count WRITE setCount); - Q_PROPERTY(int lifeSpan READ lifeSpan WRITE setLifeSpan); - Q_PROPERTY(int lifeSpanDeviation READ lifeSpanDeviation WRITE setLifeSpanDeviation); - Q_PROPERTY(int fadeInDuration READ fadeInDuration WRITE setFadeInDuration); - Q_PROPERTY(int fadeOutDuration READ fadeOutDuration WRITE setFadeOutDuration); - Q_PROPERTY(qreal angle READ angle WRITE setAngle); - Q_PROPERTY(qreal angleDeviation READ angleDeviation WRITE setAngleDeviation); - Q_PROPERTY(qreal velocity READ velocity WRITE setVelocity); - Q_PROPERTY(qreal velocityDeviation READ velocityDeviation WRITE setVelocityDeviation); - Q_PROPERTY(bool streamIn READ streamIn WRITE setStreamIn); - Q_PROPERTY(bool emitting READ emitting WRITE setEmitting); - Q_PROPERTY(QFxParticleMotion *motion READ motion WRITE setMotion); - Q_CLASSINFO("DefaultProperty", "motion"); + Q_PROPERTY(QString source READ source WRITE setSource) + Q_PROPERTY(int count READ count WRITE setCount) + Q_PROPERTY(int lifeSpan READ lifeSpan WRITE setLifeSpan) + Q_PROPERTY(int lifeSpanDeviation READ lifeSpanDeviation WRITE setLifeSpanDeviation) + Q_PROPERTY(int fadeInDuration READ fadeInDuration WRITE setFadeInDuration) + Q_PROPERTY(int fadeOutDuration READ fadeOutDuration WRITE setFadeOutDuration) + Q_PROPERTY(qreal angle READ angle WRITE setAngle) + Q_PROPERTY(qreal angleDeviation READ angleDeviation WRITE setAngleDeviation) + Q_PROPERTY(qreal velocity READ velocity WRITE setVelocity) + Q_PROPERTY(qreal velocityDeviation READ velocityDeviation WRITE setVelocityDeviation) + Q_PROPERTY(bool streamIn READ streamIn WRITE setStreamIn) + Q_PROPERTY(bool emitting READ emitting WRITE setEmitting) + Q_PROPERTY(QFxParticleMotion *motion READ motion WRITE setMotion) + Q_CLASSINFO("DefaultProperty", "motion") public: QFxParticles(QFxItem *parent=0); diff --git a/src/declarative/fx/qfxtext.h b/src/declarative/fx/qfxtext.h index 158aece..99ab2be 100644 --- a/src/declarative/fx/qfxtext.h +++ b/src/declarative/fx/qfxtext.h @@ -68,7 +68,7 @@ class Q_DECLARATIVE_EXPORT QFxText : public QFxItem Q_PROPERTY(VAlignment vAlign READ vAlign WRITE setVAlign) Q_PROPERTY(bool wrap READ wrap WRITE setWrap) Q_PROPERTY(Qt::TextElideMode elide READ elideMode WRITE setElideMode) - Q_PROPERTY(QString activeLink READ activeLink); + Q_PROPERTY(QString activeLink READ activeLink) Q_CLASSINFO("DefaultProperty", "text") public: diff --git a/src/declarative/qml/qmlbindablevalue.h b/src/declarative/qml/qmlbindablevalue.h index e50c154..c5bb97b 100644 --- a/src/declarative/qml/qmlbindablevalue.h +++ b/src/declarative/qml/qmlbindablevalue.h @@ -70,8 +70,8 @@ public: virtual void setTarget(const QmlMetaProperty &); QmlMetaProperty property() const; - Q_CLASSINFO("DefaultProperty", "expression"); - Q_PROPERTY(QString expression READ expression WRITE setExpression); + Q_CLASSINFO("DefaultProperty", "expression") + Q_PROPERTY(QString expression READ expression WRITE setExpression) virtual void setExpression(const QString &); void init(); diff --git a/src/declarative/util/qmlanimation.h b/src/declarative/util/qmlanimation.h index 74cf1b4..e0ff167 100644 --- a/src/declarative/util/qmlanimation.h +++ b/src/declarative/util/qmlanimation.h @@ -63,13 +63,13 @@ class QmlAbstractAnimation : public QmlPropertyValueSource, public QmlParserStat Q_OBJECT Q_DECLARE_PRIVATE(QmlAbstractAnimation) - Q_INTERFACES(QmlParserStatus); - Q_PROPERTY(bool running READ isRunning WRITE setRunning NOTIFY runningChanged); - Q_PROPERTY(bool finishPlaying READ finishPlaying WRITE setFinishPlaying NOTIFY finishPlayingChanged()); - Q_PROPERTY(bool repeat READ repeat WRITE setRepeat NOTIFY repeatChanged); - Q_PROPERTY(QObject *target READ target WRITE setTarget NOTIFY targetChanged); - Q_PROPERTY(QString property READ property WRITE setProperty NOTIFY targetChanged); - Q_CLASSINFO("DefaultMethod", "start()"); + Q_INTERFACES(QmlParserStatus) + Q_PROPERTY(bool running READ isRunning WRITE setRunning NOTIFY runningChanged) + Q_PROPERTY(bool finishPlaying READ finishPlaying WRITE setFinishPlaying NOTIFY finishPlayingChanged()) + Q_PROPERTY(bool repeat READ repeat WRITE setRepeat NOTIFY repeatChanged) + Q_PROPERTY(QObject *target READ target WRITE setTarget NOTIFY targetChanged) + Q_PROPERTY(QString property READ property WRITE setProperty NOTIFY targetChanged) + Q_CLASSINFO("DefaultMethod", "start()") Q_INTERFACES(QmlParserStatus) public: @@ -130,9 +130,9 @@ class QmlPauseAnimationPrivate; class QmlPauseAnimation : public QmlAbstractAnimation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlPauseAnimation); + Q_DECLARE_PRIVATE(QmlPauseAnimation) - Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged); + Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged) public: QmlPauseAnimation(QObject *parent=0); @@ -154,13 +154,13 @@ class QmlColorAnimationPrivate; class QmlColorAnimation : public QmlAbstractAnimation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlColorAnimation); - Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged); - Q_PROPERTY(QColor from READ from WRITE setFrom NOTIFY fromChanged); - Q_PROPERTY(QColor to READ to WRITE setTo NOTIFY toChanged); - Q_PROPERTY(QString easing READ easing WRITE setEasing NOTIFY easingChanged); - Q_PROPERTY(QList* filter READ filter); - Q_PROPERTY(QList* exclude READ exclude); + Q_DECLARE_PRIVATE(QmlColorAnimation) + Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged) + Q_PROPERTY(QColor from READ from WRITE setFrom NOTIFY fromChanged) + Q_PROPERTY(QColor to READ to WRITE setTo NOTIFY toChanged) + Q_PROPERTY(QString easing READ easing WRITE setEasing NOTIFY easingChanged) + Q_PROPERTY(QList* filter READ filter) + Q_PROPERTY(QList* exclude READ exclude) public: QmlColorAnimation(QObject *parent=0); @@ -201,10 +201,10 @@ class QmlRunScriptActionPrivate; class QmlRunScriptAction : public QmlAbstractAnimation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlRunScriptAction); + Q_DECLARE_PRIVATE(QmlRunScriptAction) - Q_PROPERTY(QString script READ script WRITE setScript NOTIFY scriptChanged); - Q_PROPERTY(QString file READ file WRITE setFile NOTIFY fileChanged); + Q_PROPERTY(QString script READ script WRITE setScript NOTIFY scriptChanged) + Q_PROPERTY(QString file READ file WRITE setFile NOTIFY fileChanged) public: QmlRunScriptAction(QObject *parent=0); @@ -229,12 +229,12 @@ class QmlSetPropertyActionPrivate; class QmlSetPropertyAction : public QmlAbstractAnimation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlSetPropertyAction); + Q_DECLARE_PRIVATE(QmlSetPropertyAction) - Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged); - Q_PROPERTY(QList* filter READ filter); - Q_PROPERTY(QList* exclude READ exclude); - Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged); + Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged) + Q_PROPERTY(QList* filter READ filter) + Q_PROPERTY(QList* exclude READ exclude) + Q_PROPERTY(QVariant value READ value WRITE setValue NOTIFY valueChanged) public: QmlSetPropertyAction(QObject *parent=0); @@ -287,15 +287,15 @@ class QmlNumericAnimationPrivate; class QmlNumericAnimation : public QmlAbstractAnimation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlNumericAnimation); + Q_DECLARE_PRIVATE(QmlNumericAnimation) - Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged); - Q_PROPERTY(qreal from READ from WRITE setFrom NOTIFY fromChanged); - Q_PROPERTY(qreal to READ to WRITE setTo NOTIFY toChanged); - Q_PROPERTY(QString easing READ easing WRITE setEasing NOTIFY easingChanged); - Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged); - Q_PROPERTY(QList* filter READ filter); - Q_PROPERTY(QList* exclude READ exclude); + Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged) + Q_PROPERTY(qreal from READ from WRITE setFrom NOTIFY fromChanged) + Q_PROPERTY(qreal to READ to WRITE setTo NOTIFY toChanged) + Q_PROPERTY(QString easing READ easing WRITE setEasing NOTIFY easingChanged) + Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged) + Q_PROPERTY(QList* filter READ filter) + Q_PROPERTY(QList* exclude READ exclude) public: QmlNumericAnimation(QObject *parent=0); @@ -346,10 +346,10 @@ class QmlAnimationGroupPrivate; class QmlAnimationGroup : public QmlAbstractAnimation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlAnimationGroup); + Q_DECLARE_PRIVATE(QmlAnimationGroup) - Q_CLASSINFO("DefaultProperty", "animations"); - Q_PROPERTY(QmlList *animations READ animations); + Q_CLASSINFO("DefaultProperty", "animations") + Q_PROPERTY(QmlList *animations READ animations) public: QmlAnimationGroup(QObject *parent); @@ -398,15 +398,15 @@ class QmlVariantAnimationPrivate; class QmlVariantAnimation : public QmlAbstractAnimation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlVariantAnimation); - - Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged); - Q_PROPERTY(QVariant from READ from WRITE setFrom NOTIFY fromChanged); - Q_PROPERTY(QVariant to READ to WRITE setTo NOTIFY toChanged); - Q_PROPERTY(QString easing READ easing WRITE setEasing NOTIFY easingChanged); - Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged); - Q_PROPERTY(QList* filter READ filter); - Q_PROPERTY(QList* exclude READ exclude); + Q_DECLARE_PRIVATE(QmlVariantAnimation) + + Q_PROPERTY(int duration READ duration WRITE setDuration NOTIFY durationChanged) + Q_PROPERTY(QVariant from READ from WRITE setFrom NOTIFY fromChanged) + Q_PROPERTY(QVariant to READ to WRITE setTo NOTIFY toChanged) + Q_PROPERTY(QString easing READ easing WRITE setEasing NOTIFY easingChanged) + Q_PROPERTY(QString properties READ properties WRITE setProperties NOTIFY propertiesChanged) + Q_PROPERTY(QList* filter READ filter) + Q_PROPERTY(QList* exclude READ exclude) public: QmlVariantAnimation(QObject *parent=0); diff --git a/src/declarative/util/qmlbehaviour.h b/src/declarative/util/qmlbehaviour.h index 584b96d..aef53a3 100644 --- a/src/declarative/util/qmlbehaviour.h +++ b/src/declarative/util/qmlbehaviour.h @@ -60,10 +60,10 @@ class Q_DECLARATIVE_EXPORT QmlBehaviour : public QmlPropertyValueSource, Q_DECLARE_PRIVATE(QmlBehaviour) Q_INTERFACES(QmlParserStatus) - Q_PROPERTY(QVariant from READ fromValue WRITE setFromValue); - Q_PROPERTY(QVariant to READ toValue WRITE setToValue); - Q_CLASSINFO("DefaultProperty", "operations"); - Q_PROPERTY(QmlList* operations READ operations); + Q_PROPERTY(QVariant from READ fromValue WRITE setFromValue) + Q_PROPERTY(QVariant to READ toValue WRITE setToValue) + Q_CLASSINFO("DefaultProperty", "operations") + Q_PROPERTY(QmlList* operations READ operations) public: QmlBehaviour(QObject *parent=0); diff --git a/src/declarative/util/qmlbind.h b/src/declarative/util/qmlbind.h index 8ff4152..706e202 100644 --- a/src/declarative/util/qmlbind.h +++ b/src/declarative/util/qmlbind.h @@ -60,12 +60,12 @@ class Q_DECLARATIVE_EXPORT QmlBind : public QObject Q_PROPERTY(QObject *target READ object WRITE setObject) Q_PROPERTY(QString property READ property WRITE setProperty) Q_PROPERTY(QVariant value READ value WRITE setValue) + Q_PROPERTY(bool when READ when WRITE setWhen) public: QmlBind(QObject *parent=0); ~QmlBind(); - Q_PROPERTY(bool when READ when WRITE setWhen); bool when() const; void setWhen(bool); diff --git a/src/declarative/util/qmlconnection.h b/src/declarative/util/qmlconnection.h index c776dac..57a406b 100644 --- a/src/declarative/util/qmlconnection.h +++ b/src/declarative/util/qmlconnection.h @@ -59,11 +59,11 @@ class Q_DECLARATIVE_EXPORT QmlConnection : public QObject, public QmlParserStatu Q_OBJECT Q_DECLARE_PRIVATE(QmlConnection) - Q_INTERFACES(QmlParserStatus); - Q_CLASSINFO("DefaultProperty", "script"); - Q_PROPERTY(QObject *sender READ signalSender WRITE setSignalSender); - Q_PROPERTY(QString script READ script WRITE setScript); - Q_PROPERTY(QString signal READ signal WRITE setSignal); + Q_INTERFACES(QmlParserStatus) + Q_CLASSINFO("DefaultProperty", "script") + Q_PROPERTY(QObject *sender READ signalSender WRITE setSignalSender) + Q_PROPERTY(QString script READ script WRITE setScript) + Q_PROPERTY(QString signal READ signal WRITE setSignal) public: QmlConnection(QObject *parent=0); diff --git a/src/declarative/util/qmlfollow.h b/src/declarative/util/qmlfollow.h index 1c7275d..d210592 100644 --- a/src/declarative/util/qmlfollow.h +++ b/src/declarative/util/qmlfollow.h @@ -59,14 +59,14 @@ class Q_DECLARATIVE_EXPORT QmlFollow : public QmlPropertyValueSource, Q_DECLARE_PRIVATE(QmlFollow) Q_INTERFACES(QmlParserStatus) - Q_PROPERTY(qreal source READ sourceValue WRITE setSourceValue); - Q_PROPERTY(qreal velocity READ velocity WRITE setVelocity); - Q_PROPERTY(qreal spring READ spring WRITE setSpring); - Q_PROPERTY(qreal damping READ damping WRITE setDamping); - Q_PROPERTY(qreal epsilon READ epsilon WRITE setEpsilon); - Q_PROPERTY(bool enabled READ enabled WRITE setEnabled); - - Q_PROPERTY(qreal followValue READ value NOTIFY valueChanged); + Q_PROPERTY(qreal source READ sourceValue WRITE setSourceValue) + Q_PROPERTY(qreal velocity READ velocity WRITE setVelocity) + Q_PROPERTY(qreal spring READ spring WRITE setSpring) + Q_PROPERTY(qreal damping READ damping WRITE setDamping) + Q_PROPERTY(qreal epsilon READ epsilon WRITE setEpsilon) + Q_PROPERTY(bool enabled READ enabled WRITE setEnabled) + Q_PROPERTY(qreal followValue READ value NOTIFY valueChanged) + public: QmlFollow(QObject *parent=0); ~QmlFollow(); diff --git a/src/declarative/util/qmlpackage.h b/src/declarative/util/qmlpackage.h index 763ba6a..cc77b6c 100644 --- a/src/declarative/util/qmlpackage.h +++ b/src/declarative/util/qmlpackage.h @@ -63,8 +63,8 @@ class QmlPackage : public QObject Q_OBJECT Q_DECLARE_PRIVATE(QmlPackage) - Q_CLASSINFO("DefaultProperty", "data"); - Q_PROPERTY(QmlList *data READ data SCRIPTABLE false); + Q_CLASSINFO("DefaultProperty", "data") + Q_PROPERTY(QmlList *data READ data SCRIPTABLE false) public: QmlPackage(QObject *parent=0); diff --git a/src/declarative/util/qmlscript.h b/src/declarative/util/qmlscript.h index 35a935b..dc090bc 100644 --- a/src/declarative/util/qmlscript.h +++ b/src/declarative/util/qmlscript.h @@ -55,11 +55,11 @@ class QmlScriptPrivate; class Q_DECLARATIVE_EXPORT QmlScript : public QObject { Q_OBJECT - Q_DECLARE_PRIVATE(QmlScript); + Q_DECLARE_PRIVATE(QmlScript) - Q_PROPERTY(QString script READ script WRITE setScript); - Q_PROPERTY(QString source READ source WRITE setSource); - Q_CLASSINFO("DefaultProperty", "script"); + Q_PROPERTY(QString script READ script WRITE setScript) + Q_PROPERTY(QString source READ source WRITE setSource) + Q_CLASSINFO("DefaultProperty", "script") public: QmlScript(QObject *parent=0); diff --git a/src/declarative/util/qmlsetproperties.h b/src/declarative/util/qmlsetproperties.h index 6dc5993..da5fcf2 100644 --- a/src/declarative/util/qmlsetproperties.h +++ b/src/declarative/util/qmlsetproperties.h @@ -55,10 +55,10 @@ class QmlSetPropertiesPrivate; class Q_DECLARATIVE_EXPORT QmlSetProperties : public QmlStateOperation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlSetProperties); + Q_DECLARE_PRIVATE(QmlSetProperties) - Q_PROPERTY(QObject *target READ object WRITE setObject); - Q_PROPERTY(bool restoreEntryValues READ restoreEntryValues WRITE setRestoreEntryValues); + Q_PROPERTY(QObject *target READ object WRITE setObject) + Q_PROPERTY(bool restoreEntryValues READ restoreEntryValues WRITE setRestoreEntryValues) public: QmlSetProperties(); ~QmlSetProperties(); diff --git a/src/declarative/util/qmlstate.h b/src/declarative/util/qmlstate.h index 39a9f19..0b8d82a 100644 --- a/src/declarative/util/qmlstate.h +++ b/src/declarative/util/qmlstate.h @@ -127,11 +127,11 @@ class Q_DECLARATIVE_EXPORT QmlState : public QObject { Q_OBJECT - Q_PROPERTY(QString name READ name WRITE setName); - Q_PROPERTY(QmlBindableValue *when READ when WRITE setWhen); - Q_PROPERTY(QString extends READ extends WRITE setExtends); - Q_PROPERTY(QmlList* operations READ operations); - Q_CLASSINFO("DefaultProperty", "operations"); + Q_PROPERTY(QString name READ name WRITE setName) + Q_PROPERTY(QmlBindableValue *when READ when WRITE setWhen) + Q_PROPERTY(QString extends READ extends WRITE setExtends) + Q_PROPERTY(QmlList* operations READ operations) + Q_CLASSINFO("DefaultProperty", "operations") public: QmlState(QObject *parent=0); diff --git a/src/declarative/util/qmlstategroup.h b/src/declarative/util/qmlstategroup.h index ac9b8c3..ac1d917 100644 --- a/src/declarative/util/qmlstategroup.h +++ b/src/declarative/util/qmlstategroup.h @@ -55,11 +55,11 @@ class QmlStateGroup : public QObject, public QmlParserStatus { Q_OBJECT Q_INTERFACES(QmlParserStatus) - Q_DECLARE_PRIVATE(QmlStateGroup); + Q_DECLARE_PRIVATE(QmlStateGroup) - Q_PROPERTY(QString state READ state WRITE setState NOTIFY stateChanged); - Q_PROPERTY(QmlList* states READ statesProperty DESIGNABLE false); - Q_PROPERTY(QmlList* transitions READ transitionsProperty DESIGNABLE false); + Q_PROPERTY(QString state READ state WRITE setState NOTIFY stateChanged) + Q_PROPERTY(QmlList* states READ statesProperty DESIGNABLE false) + Q_PROPERTY(QmlList* transitions READ transitionsProperty DESIGNABLE false) public: QmlStateGroup(QObject * = 0); diff --git a/src/declarative/util/qmlstateoperations.h b/src/declarative/util/qmlstateoperations.h index ef36ab2..72296e4 100644 --- a/src/declarative/util/qmlstateoperations.h +++ b/src/declarative/util/qmlstateoperations.h @@ -78,8 +78,8 @@ class Q_DECLARATIVE_EXPORT QmlRunScript : public QmlStateOperation, public Actio Q_OBJECT Q_DECLARE_PRIVATE(QmlRunScript) - Q_PROPERTY(QString script READ script WRITE setScript); - Q_PROPERTY(QString name READ name WRITE setName); + Q_PROPERTY(QString script READ script WRITE setScript) + Q_PROPERTY(QString name READ name WRITE setName) public: QmlRunScript(QObject *parent=0); @@ -101,12 +101,12 @@ class QmlSetPropertyPrivate; class Q_DECLARATIVE_EXPORT QmlSetProperty : public QmlStateOperation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlSetProperty); + Q_DECLARE_PRIVATE(QmlSetProperty) - Q_PROPERTY(QObject *target READ object WRITE setObject); - Q_PROPERTY(QString property READ property WRITE setProperty); - Q_PROPERTY(QVariant value READ value WRITE setValue); - Q_PROPERTY(QString binding READ binding WRITE setBinding); + Q_PROPERTY(QObject *target READ object WRITE setObject) + Q_PROPERTY(QString property READ property WRITE setProperty) + Q_PROPERTY(QVariant value READ value WRITE setValue) + Q_PROPERTY(QString binding READ binding WRITE setBinding) public: QmlSetProperty(QObject *parent=0); -- cgit v0.12 From 861f0fcd140232e8fe94122d640ab69a7c116663 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 27 May 2009 10:30:44 +1000 Subject: Remove more unneeded semicolons. --- src/declarative/canvas/qsimplecanvasitem.h | 4 ++-- src/declarative/canvas/qsimplecanvasitem_p.h | 10 +++++----- src/declarative/debugger/qmldebuggerstatus.h | 2 +- src/declarative/extra/qfxintegermodel.h | 4 ++-- src/declarative/extra/qmlsqlquery.h | 2 +- src/declarative/fx/qfxanchors.h | 2 +- src/declarative/fx/qfxcontentwrapper_p.h | 2 +- src/declarative/fx/qfxpath.h | 2 +- src/declarative/opengl/glsave.h | 4 ++-- src/declarative/opengl/gltexture.h | 2 +- src/declarative/qml/qmlbindablevalue_p.h | 2 +- src/declarative/qml/qmlcomponent.h | 2 +- src/declarative/qml/qmlcustomparser_p.h | 4 ++-- src/declarative/qml/qmlparser_p.h | 2 +- src/declarative/qml/qmlparserstatus.h | 2 +- src/declarative/util/qmlanimation.h | 6 +++--- src/declarative/util/qmlanimation_p.h | 18 +++++++++--------- src/declarative/util/qmllistmodel.cpp | 6 +++--- src/declarative/util/qmlstate_p.h | 2 +- src/declarative/util/qmlstateoperations.h | 2 +- 20 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvasitem.h b/src/declarative/canvas/qsimplecanvasitem.h index e8f1ee8..b928319 100644 --- a/src/declarative/canvas/qsimplecanvasitem.h +++ b/src/declarative/canvas/qsimplecanvasitem.h @@ -91,7 +91,7 @@ public: IsFocusPanel = 0x00000040, IsFocusRealm = 0x00000080, AcceptsInputMethods = 0x00000100}; - Q_DECLARE_FLAGS(Options, Option); + Q_DECLARE_FLAGS(Options, Option) QSimpleCanvasItem(QSimpleCanvasItem *parent=0); virtual ~QSimpleCanvasItem(); @@ -276,7 +276,7 @@ public: QSimpleCanvasItem(QSimpleCanvasItemPrivate &dd, QSimpleCanvasItem *parent); }; -Q_DECLARE_OPERATORS_FOR_FLAGS(QSimpleCanvasItem::Options); +Q_DECLARE_OPERATORS_FOR_FLAGS(QSimpleCanvasItem::Options) class QSimpleCanvasLayer : public QSimpleCanvasItem { diff --git a/src/declarative/canvas/qsimplecanvasitem_p.h b/src/declarative/canvas/qsimplecanvasitem_p.h index f0b44e0..e2deab2 100644 --- a/src/declarative/canvas/qsimplecanvasitem_p.h +++ b/src/declarative/canvas/qsimplecanvasitem_p.h @@ -133,7 +133,7 @@ class QSimpleCanvasFilter; class QGraphicsQSimpleCanvasItem; class QSimpleCanvasItemPrivate : public QObjectPrivate { - Q_DECLARE_PUBLIC(QSimpleCanvasItem); + Q_DECLARE_PUBLIC(QSimpleCanvasItem) public: QSimpleCanvasItemPrivate() : parent(0), canvas(0), debuggerStatus(0), filter(0), @@ -250,16 +250,16 @@ public: InRealm = 0x02, InActiveFocusedRealm = 0x04 }; - Q_DECLARE_FLAGS(FocusStateCheckDatas, FocusStateCheckData); + Q_DECLARE_FLAGS(FocusStateCheckDatas, FocusStateCheckData) enum FocusStateCheckRData { NoCheckRData = 0x00, SeenFocus = 0x01, SeenActiveFocus = 0x02 }; - Q_DECLARE_FLAGS(FocusStateCheckRDatas, FocusStateCheckRData); + Q_DECLARE_FLAGS(FocusStateCheckRDatas, FocusStateCheckRData) bool checkFocusState(FocusStateCheckDatas, FocusStateCheckRDatas *); }; -Q_DECLARE_OPERATORS_FOR_FLAGS(QSimpleCanvasItemPrivate::FocusStateCheckDatas); -Q_DECLARE_OPERATORS_FOR_FLAGS(QSimpleCanvasItemPrivate::FocusStateCheckRDatas); +Q_DECLARE_OPERATORS_FOR_FLAGS(QSimpleCanvasItemPrivate::FocusStateCheckDatas) +Q_DECLARE_OPERATORS_FOR_FLAGS(QSimpleCanvasItemPrivate::FocusStateCheckRDatas) #endif // QSIMPLECANVASITEM_P_H diff --git a/src/declarative/debugger/qmldebuggerstatus.h b/src/declarative/debugger/qmldebuggerstatus.h index 8c6355d..62336de 100644 --- a/src/declarative/debugger/qmldebuggerstatus.h +++ b/src/declarative/debugger/qmldebuggerstatus.h @@ -57,7 +57,7 @@ public: virtual void setSelectedState(bool); }; -Q_DECLARE_INTERFACE(QmlDebuggerStatus, "com.trolltech.qml.QmlDebuggerStatus"); +Q_DECLARE_INTERFACE(QmlDebuggerStatus, "com.trolltech.qml.QmlDebuggerStatus") QT_END_NAMESPACE diff --git a/src/declarative/extra/qfxintegermodel.h b/src/declarative/extra/qfxintegermodel.h index a715949..43504d8 100644 --- a/src/declarative/extra/qfxintegermodel.h +++ b/src/declarative/extra/qfxintegermodel.h @@ -60,11 +60,11 @@ public: QFxIntegerModel(QObject *parent=0); ~QFxIntegerModel(); - Q_PROPERTY(int minimum READ minimum WRITE setMinimum); + Q_PROPERTY(int minimum READ minimum WRITE setMinimum) int minimum() const; void setMinimum(int); - Q_PROPERTY(int maximum READ maximum WRITE setMaximum); + Q_PROPERTY(int maximum READ maximum WRITE setMaximum) int maximum() const; void setMaximum(int); diff --git a/src/declarative/extra/qmlsqlquery.h b/src/declarative/extra/qmlsqlquery.h index 5f750ee..dca3596 100644 --- a/src/declarative/extra/qmlsqlquery.h +++ b/src/declarative/extra/qmlsqlquery.h @@ -60,7 +60,7 @@ class Q_DECLARATIVE_EXPORT QmlSqlBind : public QObject, public QmlParserStatus Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QVariant value READ value WRITE setValue) - Q_CLASSINFO("DefaultValue", "value"); + Q_CLASSINFO("DefaultValue", "value") public: QmlSqlBind(QObject *parent = 0); diff --git a/src/declarative/fx/qfxanchors.h b/src/declarative/fx/qfxanchors.h index b3f2d3f..0e44223 100644 --- a/src/declarative/fx/qfxanchors.h +++ b/src/declarative/fx/qfxanchors.h @@ -116,7 +116,7 @@ public: Horizontal_Mask = HasLeftAnchor | HasRightAnchor | HasHCenterAnchor, Vertical_Mask = HasTopAnchor | HasBottomAnchor | HasVCenterAnchor | HasBaselineAnchor }; - Q_DECLARE_FLAGS(UsedAnchors, UsedAnchor); + Q_DECLARE_FLAGS(UsedAnchors, UsedAnchor) QFxAnchorLine left() const; void setLeft(const QFxAnchorLine &edge); diff --git a/src/declarative/fx/qfxcontentwrapper_p.h b/src/declarative/fx/qfxcontentwrapper_p.h index 4f42e00..a75fa1e 100644 --- a/src/declarative/fx/qfxcontentwrapper_p.h +++ b/src/declarative/fx/qfxcontentwrapper_p.h @@ -60,7 +60,7 @@ QT_BEGIN_NAMESPACE class QFxContentWrapperPrivate : public QFxItemPrivate { - Q_DECLARE_PUBLIC(QFxContentWrapper); + Q_DECLARE_PUBLIC(QFxContentWrapper) public: QFxContentWrapperPrivate() { } diff --git a/src/declarative/fx/qfxpath.h b/src/declarative/fx/qfxpath.h index 5c17fcb..39b9d01 100644 --- a/src/declarative/fx/qfxpath.h +++ b/src/declarative/fx/qfxpath.h @@ -194,7 +194,7 @@ class Q_DECLARATIVE_EXPORT QFxPath : public QObject, public QmlParserStatus { Q_OBJECT - Q_INTERFACES(QmlParserStatus); + Q_INTERFACES(QmlParserStatus) Q_PROPERTY(QList* pathElements READ pathElements) Q_PROPERTY(qreal startX READ startX WRITE setStartX) Q_PROPERTY(qreal startY READ startY WRITE setStartY) diff --git a/src/declarative/opengl/glsave.h b/src/declarative/opengl/glsave.h index 8256162..ad6c0ec 100644 --- a/src/declarative/opengl/glsave.h +++ b/src/declarative/opengl/glsave.h @@ -67,7 +67,7 @@ public: } private: - Q_DISABLE_COPY(GLSaveViewport); + Q_DISABLE_COPY(GLSaveViewport) GLint viewport[4]; }; @@ -100,7 +100,7 @@ public: } private: - Q_DISABLE_COPY(GLSaveScissor); + Q_DISABLE_COPY(GLSaveScissor) GLint box[4]; GLboolean enabled; }; diff --git a/src/declarative/opengl/gltexture.h b/src/declarative/opengl/gltexture.h index 8704498..787c9a5 100644 --- a/src/declarative/opengl/gltexture.h +++ b/src/declarative/opengl/gltexture.h @@ -105,7 +105,7 @@ public: GLuint texture() const; private: - Q_DISABLE_COPY(GLTexture); + Q_DISABLE_COPY(GLTexture) GLTexturePrivate *d; }; diff --git a/src/declarative/qml/qmlbindablevalue_p.h b/src/declarative/qml/qmlbindablevalue_p.h index 9973bdc..9476b80 100644 --- a/src/declarative/qml/qmlbindablevalue_p.h +++ b/src/declarative/qml/qmlbindablevalue_p.h @@ -50,7 +50,7 @@ QT_BEGIN_NAMESPACE class QmlBindableValuePrivate : public QObjectPrivate { - Q_DECLARE_PUBLIC(QmlBindableValue); + Q_DECLARE_PUBLIC(QmlBindableValue) public: QmlBindableValuePrivate(); diff --git a/src/declarative/qml/qmlcomponent.h b/src/declarative/qml/qmlcomponent.h index 3369de3..e7386d9 100644 --- a/src/declarative/qml/qmlcomponent.h +++ b/src/declarative/qml/qmlcomponent.h @@ -60,7 +60,7 @@ class QmlEngine; class Q_DECLARATIVE_EXPORT QmlComponent : public QObject { Q_OBJECT - Q_DECLARE_PRIVATE(QmlComponent); + Q_DECLARE_PRIVATE(QmlComponent) public: QmlComponent(QObject *parent = 0); diff --git a/src/declarative/qml/qmlcustomparser_p.h b/src/declarative/qml/qmlcustomparser_p.h index fd780d6..75da579 100644 --- a/src/declarative/qml/qmlcustomparser_p.h +++ b/src/declarative/qml/qmlcustomparser_p.h @@ -74,7 +74,7 @@ private: friend class QmlCustomParserPropertyPrivate; QmlCustomParserPropertyPrivate *d; }; -Q_DECLARE_METATYPE(QmlCustomParserProperty); +Q_DECLARE_METATYPE(QmlCustomParserProperty) class QmlCustomParserNodePrivate; class Q_DECLARATIVE_EXPORT QmlCustomParserNode @@ -93,7 +93,7 @@ private: friend class QmlCustomParserNodePrivate; QmlCustomParserNodePrivate *d; }; -Q_DECLARE_METATYPE(QmlCustomParserNode); +Q_DECLARE_METATYPE(QmlCustomParserNode) class Q_DECLARATIVE_EXPORT QmlCustomParser { diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h index add5773..721f1a8 100644 --- a/src/declarative/qml/qmlparser_p.h +++ b/src/declarative/qml/qmlparser_p.h @@ -272,7 +272,7 @@ namespace QmlParser void dump(int = 0) const; }; } -Q_DECLARE_METATYPE(QmlParser::Variant); +Q_DECLARE_METATYPE(QmlParser::Variant) QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlparserstatus.h b/src/declarative/qml/qmlparserstatus.h index 0e58229..7c2e141 100644 --- a/src/declarative/qml/qmlparserstatus.h +++ b/src/declarative/qml/qmlparserstatus.h @@ -66,7 +66,7 @@ private: friend class QmlEnginePrivate; QmlParserStatus **d; }; -Q_DECLARE_INTERFACE(QmlParserStatus, "com.trolltech.qml.QmlParserStatus"); +Q_DECLARE_INTERFACE(QmlParserStatus, "com.trolltech.qml.QmlParserStatus") QT_END_NAMESPACE diff --git a/src/declarative/util/qmlanimation.h b/src/declarative/util/qmlanimation.h index e0ff167..8b9ecc2 100644 --- a/src/declarative/util/qmlanimation.h +++ b/src/declarative/util/qmlanimation.h @@ -266,7 +266,7 @@ class QmlParentChangeActionPrivate; class QmlParentChangeAction : public QmlAbstractAnimation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlParentChangeAction); + Q_DECLARE_PRIVATE(QmlParentChangeAction) //XXX should have parent property as well for when it isn't part of a transition @@ -361,7 +361,7 @@ public: class QmlSequentialAnimation : public QmlAnimationGroup { Q_OBJECT - Q_DECLARE_PRIVATE(QmlAnimationGroup); + Q_DECLARE_PRIVATE(QmlAnimationGroup) public: QmlSequentialAnimation(QObject *parent=0); @@ -379,7 +379,7 @@ QML_DECLARE_TYPE(QmlSequentialAnimation) class QmlParallelAnimation : public QmlAnimationGroup { Q_OBJECT - Q_DECLARE_PRIVATE(QmlAnimationGroup); + Q_DECLARE_PRIVATE(QmlAnimationGroup) public: QmlParallelAnimation(QObject *parent=0); diff --git a/src/declarative/util/qmlanimation_p.h b/src/declarative/util/qmlanimation_p.h index 36b826f..e5a7384 100644 --- a/src/declarative/util/qmlanimation_p.h +++ b/src/declarative/util/qmlanimation_p.h @@ -169,7 +169,7 @@ private: class QmlAbstractAnimationPrivate : public QObjectPrivate { - Q_DECLARE_PUBLIC(QmlAbstractAnimation); + Q_DECLARE_PUBLIC(QmlAbstractAnimation) public: QmlAbstractAnimationPrivate() : running(false), finishPlaying(false), repeat(false), @@ -196,7 +196,7 @@ public: class QmlPauseAnimationPrivate : public QmlAbstractAnimationPrivate { - Q_DECLARE_PUBLIC(QmlPauseAnimation); + Q_DECLARE_PUBLIC(QmlPauseAnimation) public: QmlPauseAnimationPrivate() : QmlAbstractAnimationPrivate(), pa(0) {} @@ -208,7 +208,7 @@ public: class QmlColorAnimationPrivate : public QmlAbstractAnimationPrivate { - Q_DECLARE_PUBLIC(QmlColorAnimation); + Q_DECLARE_PUBLIC(QmlColorAnimation) public: QmlColorAnimationPrivate() : QmlAbstractAnimationPrivate(), fromSourced(false), fromIsDefined(false), toIsDefined(false), @@ -242,7 +242,7 @@ public: class QmlRunScriptActionPrivate : public QmlAbstractAnimationPrivate { - Q_DECLARE_PUBLIC(QmlRunScriptAction); + Q_DECLARE_PUBLIC(QmlRunScriptAction) public: QmlRunScriptActionPrivate() : QmlAbstractAnimationPrivate(), proxy(this), rsa(0) {} @@ -261,7 +261,7 @@ public: class QmlSetPropertyActionPrivate : public QmlAbstractAnimationPrivate { - Q_DECLARE_PUBLIC(QmlSetPropertyAction); + Q_DECLARE_PUBLIC(QmlSetPropertyAction) public: QmlSetPropertyActionPrivate() : QmlAbstractAnimationPrivate(), proxy(this), spa(0) {} @@ -283,7 +283,7 @@ public: class QmlParentChangeActionPrivate : public QmlAbstractAnimationPrivate { - Q_DECLARE_PUBLIC(QmlParentChangeAction); + Q_DECLARE_PUBLIC(QmlParentChangeAction) public: QmlParentChangeActionPrivate() : QmlAbstractAnimationPrivate() {} @@ -296,7 +296,7 @@ public: class QmlNumericAnimationPrivate : public QmlAbstractAnimationPrivate { - Q_DECLARE_PUBLIC(QmlNumericAnimation); + Q_DECLARE_PUBLIC(QmlNumericAnimation) public: QmlNumericAnimationPrivate() : QmlAbstractAnimationPrivate(), fromSourced(false), na(0), value(this, &QmlNumericAnimationPrivate::valueChanged) {} @@ -322,7 +322,7 @@ public: class QmlAnimationGroupPrivate : public QmlAbstractAnimationPrivate { - Q_DECLARE_PUBLIC(QmlAnimationGroup); + Q_DECLARE_PUBLIC(QmlAnimationGroup) public: QmlAnimationGroupPrivate() : QmlAbstractAnimationPrivate(), animations(this), ag(0) {} @@ -361,7 +361,7 @@ public: class QmlVariantAnimationPrivate : public QmlAbstractAnimationPrivate { - Q_DECLARE_PUBLIC(QmlVariantAnimation); + Q_DECLARE_PUBLIC(QmlVariantAnimation) public: QmlVariantAnimationPrivate() : QmlAbstractAnimationPrivate(), fromSourced(false), fromIsDefined(false), toIsDefined(false), diff --git a/src/declarative/util/qmllistmodel.cpp b/src/declarative/util/qmllistmodel.cpp index 5dc3fda..cc85661 100644 --- a/src/declarative/util/qmllistmodel.cpp +++ b/src/declarative/util/qmllistmodel.cpp @@ -67,7 +67,7 @@ struct ListModelData ListInstruction *instructions() const { return (ListInstruction *)((char *)this + sizeof(ListModelData)); } }; -Q_DECLARE_METATYPE(QListModelInterface *); +Q_DECLARE_METATYPE(QListModelInterface *) /*! \qmlclass ListModel @@ -178,7 +178,7 @@ public: virtual QList roles() const; virtual QString toString(int role) const; - Q_PROPERTY(int count READ count); + Q_PROPERTY(int count READ count) virtual int count() const; virtual QHash data(int index, const QList &roles = (QList())) const; @@ -243,7 +243,7 @@ struct ModelNode ListModel *modelCache; ModelObject *objectCache; }; -Q_DECLARE_METATYPE(ModelNode *); +Q_DECLARE_METATYPE(ModelNode *) ModelObject::ModelObject(ModelNode *node) : _node(node), _haveProperties(false), _mo(new QmlOpenMetaObject(this)) diff --git a/src/declarative/util/qmlstate_p.h b/src/declarative/util/qmlstate_p.h index a2f18eb..da8fdcd 100644 --- a/src/declarative/util/qmlstate_p.h +++ b/src/declarative/util/qmlstate_p.h @@ -50,7 +50,7 @@ QT_BEGIN_NAMESPACE class QmlStatePrivate : public QObjectPrivate { - Q_DECLARE_PUBLIC(QmlState); + Q_DECLARE_PUBLIC(QmlState) public: QmlStatePrivate() diff --git a/src/declarative/util/qmlstateoperations.h b/src/declarative/util/qmlstateoperations.h index 72296e4..c7a6d42 100644 --- a/src/declarative/util/qmlstateoperations.h +++ b/src/declarative/util/qmlstateoperations.h @@ -54,7 +54,7 @@ class QmlParentChangePrivate; class Q_DECLARATIVE_EXPORT QmlParentChange : public QmlStateOperation { Q_OBJECT - Q_DECLARE_PRIVATE(QmlParentChange); + Q_DECLARE_PRIVATE(QmlParentChange) Q_PROPERTY(QObject *target READ object WRITE setObject) Q_PROPERTY(QObject *parent READ parent WRITE setParent) -- cgit v0.12 From 411678df3e25304b105e5f3afc849b529baa0d6f Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 27 May 2009 10:46:40 +1000 Subject: Don't really need QPainter::save/restore for render hint mods. --- src/declarative/fx/qfximage.cpp | 10 ++++------ src/declarative/fx/qfxrect.cpp | 4 ++-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 6226e45..55aecd7 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -322,10 +322,9 @@ void QFxImage::paintContents(QPainter &p) if (d->_pix.isNull()) return; - if (d->_smooth) { - p.save(); + QPainter::RenderHints oldHints = p.renderHints(); + if (d->_smooth) p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->_smooth); - } QSimpleCanvasConfig::Image pix = d->_pix; @@ -415,9 +414,8 @@ void QFxImage::paintContents(QPainter &p) QRect(pix.width()-sgr, pix.height() - sgb, sgr, sgb)); } - if (d->_smooth) { - p.restore(); - } + if (d->_smooth) + p.setRenderHints(oldHints); } #elif defined(QFX_RENDER_OPENGL) uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index 90170da..cc5afc3 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -505,7 +505,7 @@ void QFxRect::drawRect(QPainter &p) if (d->_gradcolor.isValid() /*|| p.usingQt() */) { // XXX This path is still slower than the image path // Image path won't work for gradients though - p.save(); + QPainter::RenderHints oldHints = p.renderHints(); p.setRenderHint(QPainter::Antialiasing); if (d->_pen && d->_pen->isValid()) { QPen pn(QColor(pen()->color()), pen()->width()); @@ -525,7 +525,7 @@ void QFxRect::drawRect(QPainter &p) p.drawRoundedRect(0, 0, width(), height(), d->_radius, d->_radius); else p.drawRect(0, 0, width(), height()); - p.restore(); + p.setRenderHints(oldHints); } else { int offset = 0; const int pw = d->_pen && d->_pen->isValid() ? (d->_pen->width()+1)/2*2 : 0; -- cgit v0.12 From e4e735ea8c5ae8e65668938d7af2fb11e1cb6c0e Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 27 May 2009 13:41:53 +1000 Subject: Simplify and comment compiler --- src/declarative/qml/qmlcompiler.cpp | 373 +++++++++++++++++++-------------- src/declarative/qml/qmlcompiler_p.h | 11 +- src/declarative/qml/qmlinstruction.cpp | 2 +- src/declarative/qml/qmlinstruction_p.h | 1 - src/declarative/qml/qmlmetatype.cpp | 1 + src/declarative/qml/qmlvme.cpp | 7 +- 6 files changed, 229 insertions(+), 166 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index c5ffeda..cce8109 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -184,16 +184,27 @@ bool QmlCompiler::isValidId(const QString &val) } /*! - Returns true if property name \a name refers to an attached property, false - otherwise. + Returns true if \a name refers to an attached property, false otherwise. Attached property names are those that start with a capital letter. */ -bool QmlCompiler::isAttachedProperty(const QByteArray &name) +bool QmlCompiler::isAttachedPropertyName(const QByteArray &name) { return !name.isEmpty() && name.at(0) >= 'A' && name.at(0) <= 'Z'; } +/*! + Returns true if \a name refers to a signal property, false otherwise. + + Signal property names are those that start with "on", followed by a capital + letter. +*/ +bool QmlCompiler::isSignalPropertyName(const QByteArray &name) +{ + return name.length() >= 3 && name.startsWith("on") && + 'A' <= name.at(2) && 'Z' >= name.at(2); +} + #define COMPILE_EXCEPTION2(token, desc) \ { \ QString exceptionDescription; \ @@ -227,10 +238,10 @@ bool QmlCompiler::isAttachedProperty(const QByteArray &name) if (!a) return false; \ } -bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, - const QMetaProperty &prop, - int coreIdx, - QmlParser::Value *v) +// Compile a simple assignment of v to prop into instr +bool QmlCompiler::compileStoreInstruction(QmlInstruction &instr, + const QMetaProperty &prop, + QmlParser::Value *v) { QString string = v->value.asScript(); @@ -246,7 +257,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, if (value == -1) COMPILE_EXCEPTION2(v, "Cannot assign unknown enumeration to property" << prop.name()); instr.type = QmlInstruction::StoreInteger; - instr.storeInteger.propertyIndex = coreIdx; + instr.storeInteger.propertyIndex = prop.propertyIndex(); instr.storeInteger.value = value; return true; } @@ -255,21 +266,21 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, case -1: { instr.type = QmlInstruction::StoreVariant; - instr.storeString.propertyIndex = coreIdx; + instr.storeString.propertyIndex = prop.propertyIndex(); instr.storeString.value = output->indexForString(string); } break; case QVariant::String: { instr.type = QmlInstruction::StoreString; - instr.storeString.propertyIndex = coreIdx; + instr.storeString.propertyIndex = prop.propertyIndex(); instr.storeString.value = output->indexForString(string); } break; case QVariant::UInt: { instr.type = QmlInstruction::StoreInteger; - instr.storeInteger.propertyIndex = coreIdx; + instr.storeInteger.propertyIndex = prop.propertyIndex(); bool ok; int value = string.toUInt(&ok); if (!ok) @@ -280,7 +291,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, case QVariant::Int: { instr.type = QmlInstruction::StoreInteger; - instr.storeInteger.propertyIndex = coreIdx; + instr.storeInteger.propertyIndex = prop.propertyIndex(); bool ok; int value = string.toInt(&ok); if (!ok) @@ -292,7 +303,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, case QVariant::Double: { instr.type = QmlInstruction::StoreReal; - instr.storeReal.propertyIndex = coreIdx; + instr.storeReal.propertyIndex = prop.propertyIndex(); bool ok; float value = string.toFloat(&ok); if (!ok) @@ -306,7 +317,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, if (!c.isValid()) COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to color"); instr.type = QmlInstruction::StoreColor; - instr.storeColor.propertyIndex = coreIdx; + instr.storeColor.propertyIndex = prop.propertyIndex(); instr.storeColor.value = c.rgba(); } break; @@ -316,7 +327,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, if (!d.isValid()) COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to date"); instr.type = QmlInstruction::StoreDate; - instr.storeDate.propertyIndex = coreIdx; + instr.storeDate.propertyIndex = prop.propertyIndex(); instr.storeDate.value = d.toJulianDay(); } break; @@ -328,7 +339,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, int data[] = { time.hour(), time.minute(), time.second(), time.msec() }; int index = output->indexForInt(data, 4); instr.type = QmlInstruction::StoreTime; - instr.storeTime.propertyIndex = coreIdx; + instr.storeTime.propertyIndex = prop.propertyIndex(); instr.storeTime.valueIndex = index; } break; @@ -344,7 +355,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, dateTime.time().msec() }; int index = output->indexForInt(data, 5); instr.type = QmlInstruction::StoreDateTime; - instr.storeDateTime.propertyIndex = coreIdx; + instr.storeDateTime.propertyIndex = prop.propertyIndex(); instr.storeDateTime.valueIndex = index; } break; @@ -361,7 +372,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, instr.type = QmlInstruction::StorePointF; else instr.type = QmlInstruction::StorePoint; - instr.storeRealPair.propertyIndex = coreIdx; + instr.storeRealPair.propertyIndex = prop.propertyIndex(); instr.storeRealPair.valueIndex = index; } break; @@ -378,7 +389,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, instr.type = QmlInstruction::StoreSizeF; else instr.type = QmlInstruction::StoreSize; - instr.storeRealPair.propertyIndex = coreIdx; + instr.storeRealPair.propertyIndex = prop.propertyIndex(); instr.storeRealPair.valueIndex = index; } break; @@ -396,7 +407,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, instr.type = QmlInstruction::StoreRectF; else instr.type = QmlInstruction::StoreRect; - instr.storeRect.propertyIndex = coreIdx; + instr.storeRect.propertyIndex = prop.propertyIndex(); instr.storeRect.valueIndex = index; } break; @@ -407,7 +418,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, if (!ok) COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to boolean"); instr.type = QmlInstruction::StoreBool; - instr.storeBool.propertyIndex = coreIdx; + instr.storeBool.propertyIndex = prop.propertyIndex(); instr.storeBool.value = b; } break; @@ -421,7 +432,7 @@ bool QmlCompiler::generateStoreInstruction(QmlInstruction &instr, if (converter) { int index = output->customTypeData.count(); instr.type = QmlInstruction::AssignCustomType; - instr.assignCustomType.propertyIndex = coreIdx; + instr.assignCustomType.propertyIndex = prop.propertyIndex(); instr.assignCustomType.valueIndex = index; QmlCompiledData::CustomTypeData data; @@ -536,8 +547,8 @@ void QmlCompiler::compileTree(Object *tree) bool QmlCompiler::compileObject(Object *obj, int ctxt) { - if (obj->type != -1) - obj->metatype = output->types.at(obj->type).metaObject(); + Q_ASSERT (obj->type != -1); + obj->metatype = output->types.at(obj->type).metaObject(); if (output->types.at(obj->type).className == "Component") { COMPILE_CHECK(compileComponent(obj, ctxt)); @@ -555,23 +566,22 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) create.create.type = obj->type; output->bytecode << create; + // Create the synthesized meta object COMPILE_CHECK(compileDynamicMeta(obj)); - int parserStatusCast = -1; - if (obj->type != -1) { - // ### Optimize - const QMetaObject *mo = obj->metatype; - QmlType *type = 0; - while (!type && mo) { - type = QmlMetaType::qmlType(mo); - mo = mo->superClass(); - } - - Q_ASSERT(type); - - parserStatusCast = type->parserStatusCast(); + // Find the native type and check for the QmlParserStatus interface + // ### Optimize + const QMetaObject *mo = obj->metatype; + QmlType *type = 0; + while (!type && mo) { + type = QmlMetaType::qmlType(mo); + mo = mo->superClass(); } + Q_ASSERT(type); + int parserStatusCast = type->parserStatusCast(); + // If the type support the QmlParserStatusInterface we need to invoke + // classBegin() if (parserStatusCast != -1) { QmlInstruction begin; begin.type = QmlInstruction::BeginObject; @@ -580,35 +590,50 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) output->bytecode << begin; } + // Check if this is a custom parser type. Custom parser types allow + // assignments to non-existant properties. These assignments are then + // compiled by the type. bool isCustomParser = output->types.at(obj->type).type && output->types.at(obj->type).type->customParser() != 0; QList customProps; + // Compile all explicit properties specified foreach(Property *prop, obj->properties) { - if (prop->name.length() >= 3 && prop->name.startsWith("on") && - ('A' <= prop->name.at(2) && 'Z' >= prop->name.at(2))) { - if (!isCustomParser) { - COMPILE_CHECK(compileSignal(prop, obj)); + + if (isCustomParser) { + // Custom parser types don't support signal properties + if (testProperty(prop, obj)) { + COMPILE_CHECK(compileProperty(prop, obj, ctxt)); } else { customProps << QmlCustomParserNodePrivate::fromProperty(prop); } } else { - if (!isCustomParser || (isCustomParser && testProperty(prop, obj))) { - COMPILE_CHECK(compileProperty(prop, obj, ctxt)); + if (isSignalPropertyName(prop->name)) { + COMPILE_CHECK(compileSignal(prop,obj)); } else { - customProps << QmlCustomParserNodePrivate::fromProperty(prop); + COMPILE_CHECK(compileProperty(prop, obj, ctxt)); } } + } + // Compile the default property if (obj->defaultProperty) { - if(!isCustomParser || (isCustomParser && testProperty(obj->defaultProperty, obj))) { - COMPILE_CHECK(compileProperty(obj->defaultProperty, obj, ctxt)); + Property *prop = obj->defaultProperty; + + if (isCustomParser) { + if (testProperty(prop, obj)) { + COMPILE_CHECK(compileProperty(prop, obj, ctxt)); + } else { + customProps << QmlCustomParserNodePrivate::fromProperty(prop); + } } else { - customProps << QmlCustomParserNodePrivate::fromProperty(obj->defaultProperty); + COMPILE_CHECK(compileProperty(prop, obj, ctxt)); } + } + // Compile custom parser parts if (isCustomParser && !customProps.isEmpty()) { // ### Check for failure bool ok = false; @@ -621,6 +646,8 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) output->indexForByteArray(customData); } + // If the type support the QmlParserStatusInterface we need to invoke + // classComplete() if (parserStatusCast != -1) { QmlInstruction complete; complete.type = QmlInstruction::CompleteObject; @@ -713,12 +740,13 @@ bool QmlCompiler::compileComponentFromRoot(Object *obj, int ctxt) bool QmlCompiler::compileFetchedObject(Object *obj, int ctxt) { + Q_ASSERT(obj->metatype); + if (obj->defaultProperty) COMPILE_CHECK(compileProperty(obj->defaultProperty, obj, ctxt)); foreach(Property *prop, obj->properties) { - if (prop->name.length() >= 3 && prop->name.startsWith("on") && - ('A' <= prop->name.at(2) && 'Z' >= prop->name.at(2))) { + if (isSignalPropertyName(prop->name)) { COMPILE_CHECK(compileSignal(prop, obj)); } else { COMPILE_CHECK(compileProperty(prop, obj, ctxt)); @@ -811,7 +839,7 @@ bool QmlCompiler::compileSignal(Property *prop, Object *obj) bool QmlCompiler::testProperty(QmlParser::Property *prop, QmlParser::Object *obj) { - if(isAttachedProperty(prop->name) || prop->name == "id") + if(isAttachedPropertyName(prop->name) || prop->name == "id") return true; const QMetaObject *mo = obj->metaObject(); @@ -831,54 +859,71 @@ bool QmlCompiler::testProperty(QmlParser::Property *prop, bool QmlCompiler::compileProperty(Property *prop, Object *obj, int ctxt) { if (prop->values.isEmpty() && !prop->value) - return true; + COMPILE_EXCEPTION2(prop, "Empty property assignment"); - // First we're going to need a reference to this property - const QMetaObject *mo = obj->metaObject(); - if (mo && !isAttachedProperty(prop->name)) { - if (prop->isDefault) { - QMetaProperty p = QmlMetaType::defaultProperty(mo); - // XXX - // Currently we don't handle enums in the static analysis - // so we let them drop through to generateStoreInstruction() - if (p.name() && !p.isEnumType()) { - prop->index = mo->indexOfProperty(p.name()); - prop->name = p.name(); + const QMetaObject *metaObject = obj->metaObject(); + Q_ASSERT(metaObject); - int t = p.type(); - if (t == QVariant::UserType) - t = p.userType(); + if (isAttachedPropertyName(prop->name)) { + // Setup attached property data + QmlType *type = QmlMetaType::qmlType(prop->name); + + if (!type || !type->attachedPropertiesType()) + COMPILE_EXCEPTION2(prop, "Non-existant attached object"); + + if (!prop->value) + COMPILE_EXCEPTION2(prop, "Cannot assign directly to attached object"); + + prop->value->metatype = type->attachedPropertiesType(); + } else { + // Setup regular property data + QMetaProperty p; - prop->type = t; + if (prop->isDefault) { + p = QmlMetaType::defaultProperty(metaObject); + + if (p.name()) { + prop->index = p.propertyIndex(); + prop->name = p.name(); } + } else { - prop->index = mo->indexOfProperty(prop->name.constData()); - QMetaProperty p = mo->property(prop->index); - // XXX - // Currently we don't handle enums in the static analysis - // so we let them drop through to generateStoreInstruction() - if (p.name() && !p.isEnumType()) { - int t = p.type(); - if (t == QVariant::UserType) - t = p.userType(); + prop->index = metaObject->indexOfProperty(prop->name.constData()); - prop->type = t; + if (prop->index != -1) { + p = metaObject->property(prop->index); + Q_ASSERT(p.name()); } } - } else if(isAttachedProperty(prop->name) && prop->value) { - QmlType *type = QmlMetaType::qmlType(prop->name); - if (type && type->attachedPropertiesType()) - prop->value->metatype = type->attachedPropertiesType(); + + // We can't error here as the "id" property does not require a + // successful index resolution + if (p.name()) { + int t = p.type(); + + if (t == QVariant::UserType) + t = p.userType(); + + prop->type = t; + } } - if (prop->name == "id") { + if (!prop->isDefault && prop->name == "id") { COMPILE_CHECK(compileIdProperty(prop, obj)); - } else if (isAttachedProperty(prop->name)) { + } else if (isAttachedPropertyName(prop->name)) { COMPILE_CHECK(compileAttachedProperty(prop, obj, ctxt)); + } else if (prop->index == -1) { + + if (prop->isDefault) { + COMPILE_EXCEPTION2(prop, "Cannot assign to non-existant default property"); + } else { + COMPILE_EXCEPTION2(prop, "Cannot assign to non-existant property" << prop->name); + } + } else if (prop->value) { COMPILE_CHECK(compileNestedProperty(prop, ctxt)); @@ -944,19 +989,22 @@ bool QmlCompiler::compileIdProperty(QmlParser::Property *prop, return true; } +// Compile attached property object. In this example, +// Text { +// GridView.row: 10 +// } +// GridView is an attached property object. bool QmlCompiler::compileAttachedProperty(QmlParser::Property *prop, QmlParser::Object *obj, int ctxt) { - if (!prop->value) - COMPILE_EXCEPTION("Incorrect usage of an attached property"); + Q_ASSERT(prop->value); + int id = QmlMetaType::attachedPropertiesFuncId(prop->name); + Q_ASSERT(id != -1); // This is checked in compileProperty() QmlInstruction fetch; fetch.type = QmlInstruction::FetchAttached; fetch.line = prop->location.start.line; - int id = QmlMetaType::attachedPropertiesFuncId(prop->name); - if (id == -1) - COMPILE_EXCEPTION("Non-existant attached property object" << prop->name); fetch.fetchAttached.id = id; output->bytecode << fetch; @@ -970,16 +1018,20 @@ bool QmlCompiler::compileAttachedProperty(QmlParser::Property *prop, return true; } +// Compile "nested" properties. In this example: +// Text { +// font.size: 12 +// } +// font is a nested property. size is not. bool QmlCompiler::compileNestedProperty(QmlParser::Property *prop, int ctxt) { - if (prop->type != 0) - prop->value->metatype = QmlMetaType::metaObjectForType(prop->type); - - if (prop->index == -1) - COMPILE_EXCEPTION2(prop, "Cannot access non-existant property" << prop->name); + Q_ASSERT(prop->type != 0); + Q_ASSERT(prop->index != -1); - if (!QmlMetaType::isObject(prop->value->metatype)) + // Load the nested property's meta type + prop->value->metatype = QmlMetaType::metaObjectForType(prop->type); + if (!prop->value->metatype) COMPILE_EXCEPTION2(prop, "Cannot nest non-QObject property" << prop->name); QmlInstruction fetch; @@ -999,11 +1051,20 @@ bool QmlCompiler::compileNestedProperty(QmlParser::Property *prop, return true; } +// Compile assignments to QML lists. QML lists are properties of type +// QList * and QmlList *. +// +// QList * types can accept a list of objects, or a single binding +// QmlList * types can accept a list of objects bool QmlCompiler::compileListProperty(QmlParser::Property *prop, QmlParser::Object *obj, int ctxt) { + Q_ASSERT(QmlMetaType::isList(prop->type) || + QmlMetaType::isQmlList(prop->type)); + int t = prop->type; + if (QmlMetaType::isQmlList(t)) { QmlInstruction fetch; fetch.line = prop->location.start.line; @@ -1033,8 +1094,6 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, pop.line = prop->location.start.line; output->bytecode << pop; } else { - Q_ASSERT(QmlMetaType::isList(t)); - QmlInstruction fetch; fetch.type = QmlInstruction::FetchQList; fetch.line = prop->location.start.line; @@ -1072,9 +1131,25 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, pop.type = QmlInstruction::PopQList; output->bytecode << pop; } + return true; } +// Compile regular property assignments of the form property: +// +// ### The following problems exist +// +// There is no distinction between how "lists" of values are specified. This +// Item { +// children: Item {} +// children: Item {} +// } +// is identical to +// Item { +// children: [ Item {}, Item {} ] +// } +// +// We allow assignming multiple values to single value properties bool QmlCompiler::compilePropertyAssignment(QmlParser::Property *prop, QmlParser::Object *obj, int ctxt) @@ -1095,97 +1170,98 @@ bool QmlCompiler::compilePropertyAssignment(QmlParser::Property *prop, return true; } +// Compile assigning a single object instance to a regular property bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, QmlParser::Object *obj, QmlParser::Value *v, int ctxt) { - if (v->object->type != -1) - v->object->metatype = output->types.at(v->object->type).metaObject(); - Q_ASSERT(v->object->metaObject()); - - if (prop->index == -1) - COMPILE_EXCEPTION2(prop, "Cannot assign object to non-existant property" << prop->name); - + Q_ASSERT(prop->index != -1); + Q_ASSERT(v->object->type != -1); if (QmlMetaType::isInterface(prop->type)) { + // Assigning an object to an interface ptr property COMPILE_CHECK(compileObject(v->object, ctxt)); QmlInstruction assign; assign.type = QmlInstruction::StoreInterface; assign.line = v->object->location.start.line; assign.storeObject.propertyIndex = prop->index; - assign.storeObject.cast = 0; output->bytecode << assign; v->type = Value::CreatedObject; } else if (prop->type == -1) { - // Variant - // ### Is it always? + // Assigning an object to a QVariant COMPILE_CHECK(compileObject(v->object, ctxt)); QmlInstruction assign; assign.type = QmlInstruction::StoreVariantObject; assign.line = v->object->location.start.line; assign.storeObject.propertyIndex = prop->index; - assign.storeObject.cast = 0; output->bytecode << assign; v->type = Value::CreatedObject; } else { + // Normally compileObject() will set this up, but we need the static + // meta object earlier to test for assignability. It doesn't matter + // that there may still be outstanding synthesized meta object changes + // on this type, as they are not relevant for assignability testing + v->object->metatype = output->types.at(v->object->type).metaObject(); + Q_ASSERT(v->object->metaObject()); - const QMetaObject *propmo = + // We want to raw metaObject here as the raw metaobject is the + // actual property type before we applied any extensions that might + // effect the properties on the type, but don't effect assignability + const QMetaObject *propertyMetaObject = QmlMetaType::rawMetaObjectForType(prop->type); - bool isPropertyValue = false; + // Will be true if the assigned type inherits QmlPropertyValueSource + bool isPropertyValue = false; + // Will be true if the assgned type inherits propertyMetaObject bool isAssignable = false; - - if (propmo) { - // We want to raw metaObject here as the raw metaobject is the - // actual property type before we applied any extensions + // Determine isPropertyValue and isAssignable values + if (propertyMetaObject) { const QMetaObject *c = v->object->metatype; - while(propmo && c) { - isPropertyValue = isPropertyValue || (c == &QmlPropertyValueSource::staticMetaObject); - isAssignable = isAssignable || (c == propmo); + while(c) { + isPropertyValue |= (c == &QmlPropertyValueSource::staticMetaObject); + isAssignable |= (c == propertyMetaObject); c = c->superClass(); } } else { const QMetaObject *c = v->object->metatype; while(!isPropertyValue && c) { - isPropertyValue = c == &QmlPropertyValueSource::staticMetaObject; + isPropertyValue |= (c == &QmlPropertyValueSource::staticMetaObject); c = c->superClass(); } } if (isAssignable) { + // Simple assignment COMPILE_CHECK(compileObject(v->object, ctxt)); QmlInstruction assign; assign.type = QmlInstruction::StoreObject; assign.line = v->object->location.start.line; assign.storeObject.propertyIndex = prop->index; - // XXX - this cast may not be 0 - assign.storeObject.cast = 0; output->bytecode << assign; v->type = Value::CreatedObject; - } else if (propmo == &QmlComponent::staticMetaObject) { - + } else if (propertyMetaObject == &QmlComponent::staticMetaObject) { + // Automatic "Component" insertion COMPILE_CHECK(compileComponentFromRoot(v->object, ctxt)); QmlInstruction assign; assign.type = QmlInstruction::StoreObject; assign.line = v->object->location.start.line; assign.storeObject.propertyIndex = prop->index; - // XXX - this cast may not be 0 - assign.storeObject.cast = 0; output->bytecode << assign; v->type = Value::Component; } else if (isPropertyValue) { + // Assign as a property value source COMPILE_CHECK(compileObject(v->object, ctxt)); QmlInstruction assign; @@ -1203,11 +1279,14 @@ bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, return true; } +// Compile assigning a literal or binding to a regular property bool QmlCompiler::compilePropertyLiteralAssignment(QmlParser::Property *prop, QmlParser::Object *obj, QmlParser::Value *v, int ctxt) { + Q_ASSERT(prop->index != -1); + if (v->value.isScript()) { COMPILE_CHECK(compileBinding(v->value.asScript(), prop, ctxt, @@ -1220,17 +1299,12 @@ bool QmlCompiler::compilePropertyLiteralAssignment(QmlParser::Property *prop, QmlInstruction assign; assign.line = v->location.start.line; - - if (prop->index != -1) { - COMPILE_CHECK(generateStoreInstruction(assign, obj->metaObject()->property(prop->index), prop->index, v)); - } else { - COMPILE_EXCEPTION2(prop, "Cannot assign value to non-existant property" << prop->name); - } - + COMPILE_CHECK(compileStoreInstruction(assign, obj->metaObject()->property(prop->index), v)); output->bytecode << assign; v->type = Value::Literal; } + return true; } @@ -1325,6 +1399,9 @@ bool QmlCompiler::compileDynamicMeta(QmlParser::Object *obj) bool QmlCompiler::compileBinding(const QString &bind, QmlParser::Property *prop, int ctxt, const QMetaObject *mo, qint64 line) { + Q_ASSERT(mo); + Q_ASSERT(prop->index); + QmlBasicScript bs; bs.compile(bind.toLatin1()); @@ -1335,32 +1412,24 @@ bool QmlCompiler::compileBinding(const QString &bind, QmlParser::Property *prop, bref = output->indexForString(bind); } - if (prop->index != -1) { + QmlInstruction assign; + assign.assignBinding.context = ctxt; + assign.line = line; - QmlInstruction assign; - assign.assignBinding.context = ctxt; - assign.line = line; - - if (bs.isValid()) - assign.type = QmlInstruction::StoreCompiledBinding; - else - assign.type = QmlInstruction::StoreBinding; - - assign.assignBinding.property = prop->index; - assign.assignBinding.value = bref; - assign.assignBinding.category = QmlMetaProperty::Unknown; - if (mo) { - // ### we should generate an exception if the property is read-only - QMetaProperty mp = mo->property(assign.assignBinding.property); - assign.assignBinding.category = QmlMetaProperty::propertyCategory(mp); - } + if (bs.isValid()) + assign.type = QmlInstruction::StoreCompiledBinding; + else + assign.type = QmlInstruction::StoreBinding; - savedTypes.insert(output->bytecode.count(), prop->type); - output->bytecode << assign; + assign.assignBinding.property = prop->index; + assign.assignBinding.value = bref; + QMetaProperty mp = mo->property(assign.assignBinding.property); + if (!mp.isWritable() && !QmlMetaType::isList(prop->type)) + COMPILE_EXCEPTION2(prop, "Cannot assign binding to read-only property"); + assign.assignBinding.category = QmlMetaProperty::propertyCategory(mp); - } else { - COMPILE_EXCEPTION2(prop, "Cannot assign binding to non-existant property" << prop->name); - } + savedTypes.insert(output->bytecode.count(), prop->type); + output->bytecode << assign; return true; } diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index 27c4dd2..bc9e06c 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -119,7 +119,8 @@ public: QList errors() const; static bool isValidId(const QString &); - static bool isAttachedProperty(const QByteArray &); + static bool isAttachedPropertyName(const QByteArray &); + static bool isSignalPropertyName(const QByteArray &); private: void reset(QmlCompiledComponent *, bool); @@ -154,11 +155,9 @@ private: QmlParser::Object *obj, QmlParser::Value *value, int ctxt); - - bool generateStoreInstruction(QmlInstruction &instr, - const QMetaProperty &prop, - int index, - QmlParser::Value *value); + bool compileStoreInstruction(QmlInstruction &instr, + const QMetaProperty &prop, + QmlParser::Value *value); bool compileDynamicMeta(QmlParser::Object *obj); bool compileBinding(const QString &, QmlParser::Property *prop, diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index bb40063..0aa860d 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -116,7 +116,7 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) qWarning() << idx << "\t" << line << "\t" << "STORE_VARIANT\t\t" << instr->storeString.propertyIndex << "\t" << instr->storeString.value << "\t\t" << primitives.at(instr->storeString.value); break; case QmlInstruction::StoreObject: - qWarning() << idx << "\t" << line << "\t" << "STORE_OBJECT\t\t" << instr->storeObject.propertyIndex << "\t" << instr->storeObject.cast; + qWarning() << idx << "\t" << line << "\t" << "STORE_OBJECT\t\t" << instr->storeObject.propertyIndex; break; case QmlInstruction::AssignCustomType: qWarning() << idx << "\t" << line << "\t" << "ASSIGN_CUSTOMTYPE\t\t" << instr->assignCustomType.propertyIndex << "\t" << instr->assignCustomType.valueIndex; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index abefd6c..5c6fa5a 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -235,7 +235,6 @@ public: } storeRect; struct { int propertyIndex; - int cast; } storeObject; struct { int propertyIndex; diff --git a/src/declarative/qml/qmlmetatype.cpp b/src/declarative/qml/qmlmetatype.cpp index 6d44f7a..3e25ae0 100644 --- a/src/declarative/qml/qmlmetatype.cpp +++ b/src/declarative/qml/qmlmetatype.cpp @@ -771,6 +771,7 @@ const char *QmlMetaType::interfaceIId(int userType) bool QmlMetaType::isObject(const QMetaObject *mo) { + // ### Huh? while(mo) { if (mo == &QObject::staticMetaObject) return true; diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 991c7ad..e68afcc 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -546,8 +546,7 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QObject *target = stack.top(); void *a[1]; - void *obj = (void *)(((char *)assignObj) + instr.storeObject.cast); - a[0] = (void *)&obj; + a[0] = (void *)&assignObj; QMetaObject::metacall(target, QMetaObject::WriteProperty, instr.storeObject.propertyIndex, a); @@ -674,8 +673,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QmlMetaProperty mp(target, instr.assignBinding.property, (QmlMetaProperty::PropertyCategory)instr.assignBinding.category); - if (!mp.isWritable()) - VME_EXCEPTION("Cannot assign a binding to read-only property" << mp.name()); QmlBindableValue *bind = new QmlBindableValue((void *)datas.at(instr.assignBinding.value).constData(), comp, context, 0); bindValues.append(bind); @@ -700,8 +697,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QmlMetaProperty mp(target, instr.assignBinding.property, (QmlMetaProperty::PropertyCategory)instr.assignBinding.category); - if (!mp.isWritable()) - VME_EXCEPTION("Cannot assign a binding to read-only property" << mp.name()); QmlBindableValue *bind = new QmlBindableValue(primitives.at(instr.assignBinding.value), context, false); bindValues.append(bind); -- cgit v0.12 From a190b92bb4eb40ecf8c30d6f368c0d15ec317580 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 27 May 2009 15:15:54 +1000 Subject: Small cleanups --- src/declarative/qml/qmlcompiler.cpp | 16 +++++++--------- src/declarative/qml/qmlcompiler_p.h | 4 +--- 2 files changed, 8 insertions(+), 12 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index cce8109..09f4e0b 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -728,12 +728,12 @@ bool QmlCompiler::compileComponentFromRoot(Object *obj, int ctxt) ids.clear(); if (obj) COMPILE_CHECK(compileObject(obj, ctxt)); - ids = oldIds; create.createComponent.count = output->bytecode.count() - count; int inc = optimizeExpressions(count, count - 1 + create.createComponent.count, count); create.createComponent.count += inc; + ids = oldIds; return true; } @@ -914,7 +914,7 @@ bool QmlCompiler::compileProperty(Property *prop, Object *obj, int ctxt) } else if (isAttachedPropertyName(prop->name)) { - COMPILE_CHECK(compileAttachedProperty(prop, obj, ctxt)); + COMPILE_CHECK(compileAttachedProperty(prop, ctxt)); } else if (prop->index == -1) { @@ -995,7 +995,6 @@ bool QmlCompiler::compileIdProperty(QmlParser::Property *prop, // } // GridView is an attached property object. bool QmlCompiler::compileAttachedProperty(QmlParser::Property *prop, - QmlParser::Object *obj, int ctxt) { Q_ASSERT(prop->value); @@ -1158,7 +1157,7 @@ bool QmlCompiler::compilePropertyAssignment(QmlParser::Property *prop, Value *v = prop->values.at(ii); if (v->object) { - COMPILE_CHECK(compilePropertyObjectAssignment(prop, obj, v, ctxt)); + COMPILE_CHECK(compilePropertyObjectAssignment(prop, v, ctxt)); } else { @@ -1172,7 +1171,6 @@ bool QmlCompiler::compilePropertyAssignment(QmlParser::Property *prop, // Compile assigning a single object instance to a regular property bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, - QmlParser::Object *obj, QmlParser::Value *v, int ctxt) { @@ -1402,6 +1400,10 @@ bool QmlCompiler::compileBinding(const QString &bind, QmlParser::Property *prop, Q_ASSERT(mo); Q_ASSERT(prop->index); + QMetaProperty mp = mo->property(prop->index); + if (!mp.isWritable() && !QmlMetaType::isList(prop->type)) + COMPILE_EXCEPTION2(prop, "Cannot assign binding to read-only property"); + QmlBasicScript bs; bs.compile(bind.toLatin1()); @@ -1423,11 +1425,7 @@ bool QmlCompiler::compileBinding(const QString &bind, QmlParser::Property *prop, assign.assignBinding.property = prop->index; assign.assignBinding.value = bref; - QMetaProperty mp = mo->property(assign.assignBinding.property); - if (!mp.isWritable() && !QmlMetaType::isList(prop->type)) - COMPILE_EXCEPTION2(prop, "Cannot assign binding to read-only property"); assign.assignBinding.category = QmlMetaProperty::propertyCategory(mp); - savedTypes.insert(output->bytecode.count(), prop->type); output->bytecode << assign; diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index bc9e06c..6e9bafb 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -137,7 +137,6 @@ private: bool compileIdProperty(QmlParser::Property *prop, QmlParser::Object *obj); bool compileAttachedProperty(QmlParser::Property *prop, - QmlParser::Object *obj, int ctxt); bool compileNestedProperty(QmlParser::Property *prop, int ctxt); @@ -148,7 +147,6 @@ private: QmlParser::Object *obj, int ctxt); bool compilePropertyObjectAssignment(QmlParser::Property *prop, - QmlParser::Object *obj, QmlParser::Value *value, int ctxt); bool compilePropertyLiteralAssignment(QmlParser::Property *prop, @@ -166,11 +164,11 @@ private: int optimizeExpressions(int start, int end, int patch = -1); QSet ids; + QHash savedTypes; QList exceptions; QmlCompiledData *output; - QHash savedTypes; }; QT_END_NAMESPACE -- cgit v0.12 From 0a6df63c7150f0010b08ce2ba08a492cd129a96f Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 27 May 2009 16:03:25 +1000 Subject: Save the JavaScript AST in the QmlParser::Variant for use by others --- src/declarative/qml/qmlparser.cpp | 18 +++++++++++++++--- src/declarative/qml/qmlparser_p.h | 7 ++++++- src/declarative/qml/qmlscriptparser.cpp | 8 ++++---- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/src/declarative/qml/qmlparser.cpp b/src/declarative/qml/qmlparser.cpp index c5d7092..5c2a69f 100644 --- a/src/declarative/qml/qmlparser.cpp +++ b/src/declarative/qml/qmlparser.cpp @@ -281,10 +281,14 @@ QmlParser::Variant::Variant(double v, const QString &asWritten) { } -QmlParser::Variant::Variant(const QString &v, Type type) -: t(type), s(v) +QmlParser::Variant::Variant(const QString &v) +: t(String), s(v) +{ +} + +QmlParser::Variant::Variant(const QString &v, JavaScript::AST::Node *n) +: t(Script), n(n), s(v) { - Q_ASSERT(type == String || type == Script); } QmlParser::Variant &QmlParser::Variant::operator=(const Variant &o) @@ -334,4 +338,12 @@ QString QmlParser::Variant::asScript() const } } +JavaScript::AST::Node *QmlParser::Variant::asAST() const +{ + if (type() == Script) + return n; + else + return 0; +} + QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h index 721f1a8..cb9b540 100644 --- a/src/declarative/qml/qmlparser_p.h +++ b/src/declarative/qml/qmlparser_p.h @@ -55,6 +55,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) +namespace JavaScript { namespace AST { class Node; } } + /* XXX @@ -175,7 +177,8 @@ namespace QmlParser Variant(const Variant &); Variant(bool); Variant(double, const QString &asWritten=QString()); - Variant(const QString &, Type = String); + Variant(const QString &); + Variant(const QString &, JavaScript::AST::Node *); Variant &operator=(const Variant &); Type type() const; @@ -189,12 +192,14 @@ namespace QmlParser QString asString() const; double asNumber() const; QString asScript() const; + JavaScript::AST::Node *asAST() const; private: Type t; union { bool b; double d; + JavaScript::AST::Node *n; }; QString s; }; diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index 5c5b25e..b862953 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -587,7 +587,7 @@ QmlParser::Variant ProcessAST::getVariant(AST::ExpressionNode *expr) if (lit->suffix == AST::NumericLiteral::noSuffix) return QmlParser::Variant(lit->value, asString(expr)); else - return QmlParser::Variant(asString(expr), QmlParser::Variant::Script); + return QmlParser::Variant(asString(expr), expr); } else { @@ -597,7 +597,7 @@ QmlParser::Variant ProcessAST::getVariant(AST::ExpressionNode *expr) } } - return QmlParser::Variant(asString(expr), QmlParser::Variant::Script); + return QmlParser::Variant(asString(expr), expr); } } @@ -620,8 +620,8 @@ bool ProcessAST::visit(AST::UiScriptBinding *node) if (AST::ExpressionStatement *stmt = AST::cast(node->statement)) { primitive = getVariant(stmt->expression); } else { // do binding - primitive = QmlParser::Variant(asString(node->statement), - QmlParser::Variant::Script); + primitive = QmlParser::Variant(asString(node->statement), + node->statement); } Value *v = new Value; -- cgit v0.12 From d53e4499f864719446abdb7fdeff433dbb3f7d98 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Wed, 27 May 2009 16:05:32 +1000 Subject: Remove qmlviewer's sizeHint hack. --- tools/qmlviewer/qmlviewer.cpp | 12 ------------ tools/qmlviewer/qmlviewer.h | 1 - 2 files changed, 13 deletions(-) diff --git a/tools/qmlviewer/qmlviewer.cpp b/tools/qmlviewer/qmlviewer.cpp index 2ef5616..75a8f1c 100644 --- a/tools/qmlviewer/qmlviewer.cpp +++ b/tools/qmlviewer/qmlviewer.cpp @@ -163,18 +163,6 @@ QMenuBar *QmlViewer::menuBar() const return mb; } -QSize QmlViewer::sizeHint() const -{ - if (skin) - return QWidget::sizeHint(); - else { - // Kludge to force QMainWindow to be EXACTLY the right size for the canvas. - QSize sh = canvas->sizeHint(); - sh.setHeight(sh.height()+menuBar()->sizeHint().height()); - return sh; - } -} - void QmlViewer::createMenu(QMenuBar *menu, QMenu *flatmenu) { QObject *parent = flatmenu ? (QObject*)flatmenu : (QObject*)menu; diff --git a/tools/qmlviewer/qmlviewer.h b/tools/qmlviewer/qmlviewer.h index 04d94cc..45ec446 100644 --- a/tools/qmlviewer/qmlviewer.h +++ b/tools/qmlviewer/qmlviewer.h @@ -44,7 +44,6 @@ public: void setCacheEnabled(bool); void addLibraryPath(const QString& lib); - QSize sizeHint() const; QMenuBar *menuBar() const; public slots: -- cgit v0.12 From 634954f1648a1ada74ba03f2eecec71e8bcba898 Mon Sep 17 00:00:00 2001 From: Jason McDonald Date: Wed, 27 May 2009 16:41:53 +1000 Subject: Fix WinCE compile error not fixed by c666b88 You can't implicitly convert QLatin1Char to QString and thus neither to QFileInfo. Instead do the conversion the correct way, as illustrated by the code five lines above the line that broke. Reviewed-by: Lincoln Ramsay Reviewed-by: Andy Shaw --- src/corelib/io/qfsfileengine_win.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp index 82cde8b..0b87e2b 100644 --- a/src/corelib/io/qfsfileengine_win.cpp +++ b/src/corelib/io/qfsfileengine_win.cpp @@ -1298,7 +1298,7 @@ QFileInfoList QFSFileEngine::drives() } return ret; #else - ret.append(QFileInfo(QLatin1Char('/'))); + ret.append(QString::fromLatin1("/")); return ret; #endif } -- cgit v0.12 From ed5d5f6f04cda1f7aa3ea66be5fefc0a85429794 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 27 May 2009 17:00:37 +1000 Subject: Better gradient support for Rect. --- demos/declarative/flickr/content/Progress.qml | 14 ++- demos/declarative/flickr/content/Slider.qml | 15 ++- doc/src/declarative/pics/gradient.png | Bin 0 -> 364 bytes doc/src/snippets/declarative/gradient.qml | 8 ++ examples/declarative/dial/dial.qml | 11 +- examples/declarative/xmldata/yahoonews.qml | 6 +- src/declarative/fx/qfxrect.cpp | 157 +++++++++++++++++--------- src/declarative/fx/qfxrect.h | 51 ++++++++- src/declarative/fx/qfxrect_p.h | 6 +- 9 files changed, 196 insertions(+), 72 deletions(-) create mode 100644 doc/src/declarative/pics/gradient.png create mode 100644 doc/src/snippets/declarative/gradient.qml diff --git a/demos/declarative/flickr/content/Progress.qml b/demos/declarative/flickr/content/Progress.qml index aa2a2e6..743c45e 100644 --- a/demos/declarative/flickr/content/Progress.qml +++ b/demos/declarative/flickr/content/Progress.qml @@ -4,8 +4,12 @@ Item { property var progress: 0 Rect { - id: Container; anchors.fill: parent; gradientColor: "#66000000"; - pen.color: "white"; pen.width: 0; color: "#66343434"; radius: height/2 - 2 + id: Container; anchors.fill: parent + pen.color: "white"; pen.width: 0; radius: height/2 - 2 + gradient: Gradient { + GradientStop { position: 0; color: "#66343434" } + GradientStop { position: 1.0; color: "#66000000" } + } } Rect { @@ -13,7 +17,11 @@ Item { y: 2; height: parent.height-4; x: 2; width: Math.max(parent.width * progress - 4, 0); opacity: width < 1 ? 0 : 1 - color: "lightsteelblue"; gradientColor: "steelblue"; radius: height/2 - 2 + gradient: Gradient { + GradientStop { position: 0; color: "lightsteelblue" } + GradientStop { position: 1.0; color: "steelblue" } + } + radius: height/2 - 2 } Text { diff --git a/demos/declarative/flickr/content/Slider.qml b/demos/declarative/flickr/content/Slider.qml index aae4631..6aff225 100644 --- a/demos/declarative/flickr/content/Slider.qml +++ b/demos/declarative/flickr/content/Slider.qml @@ -9,14 +9,21 @@ Item { property int xMax: Slider.width - Handle.width - 4 Rect { - id: Container; anchors.fill: parent; gradientColor: "#66000000"; - pen.color: "white"; pen.width: 0; color: "#66343434"; radius: 8 + id: Container; anchors.fill: parent + pen.color: "white"; pen.width: 0; radius: 8 + gradient: Gradient { + GradientStop { position: 0.0; color: "#66343434" }, + GradientStop { position: 1.0; color: "#66000000" } + } } Rect { id: Handle - x: Slider.width / 2 - Handle.width / 2; y: 2; width: 30; height: Slider.height-4 - color: "lightgray"; gradientColor: "gray"; radius: 6 + x: Slider.width / 2 - Handle.width / 2; y: 2; width: 30; height: Slider.height-4; radius: 6 + gradient: Gradient { + GradientStop { position: 0.0; color: "lightgray" }, + GradientStop { position: 1.0; color: "gray" } + } MouseRegion { anchors.fill: parent; drag.target: parent diff --git a/doc/src/declarative/pics/gradient.png b/doc/src/declarative/pics/gradient.png new file mode 100644 index 0000000..5eefdd2 Binary files /dev/null and b/doc/src/declarative/pics/gradient.png differ diff --git a/doc/src/snippets/declarative/gradient.qml b/doc/src/snippets/declarative/gradient.qml new file mode 100644 index 0000000..28018b8 --- /dev/null +++ b/doc/src/snippets/declarative/gradient.qml @@ -0,0 +1,8 @@ +Rect { + width: 100; height: 100 + gradient: Gradient { + GradientStop { position: 0.0; color: "red" } + GradientStop { position: 0.33; color: "yellow" } + GradientStop { position: 1.0; color: "green" } + } +} diff --git a/examples/declarative/dial/dial.qml b/examples/declarative/dial/dial.qml index 5e09171..b183798 100644 --- a/examples/declarative/dial/dial.qml +++ b/examples/declarative/dial/dial.qml @@ -9,12 +9,19 @@ Rect { Rect { anchors.top: Dial.bottom x: 20; width: 160; height: 16 - color: "steelblue"; gradientColor: "lightsteelblue" + gradient: Gradient { + GradientStop { position: 0.0; color: "steelblue" } + GradientStop { position: 1.0; color: "lightsteelblue" } + } radius: 8; opacity: 0.7 Rect { id: Slider x: 2; y: 2; width: 30; height: 12 - color: "lightgray"; gradientColor: "gray"; radius: 6 + radius: 6 + gradient: Gradient { + GradientStop { position: 0.0; color: "lightgray" } + GradientStop { position: 1.0; color: "gray" } + } MouseRegion { anchors.fill: parent drag.target: parent; drag.axis: "x"; drag.xmin: 2; drag.xmax: 128 diff --git a/examples/declarative/xmldata/yahoonews.qml b/examples/declarative/xmldata/yahoonews.qml index a465cdd..206c85f 100644 --- a/examples/declarative/xmldata/yahoonews.qml +++ b/examples/declarative/xmldata/yahoonews.qml @@ -1,6 +1,8 @@ Rect { - color: "black" - gradientColor: "#AAAAAA" + gradient: Gradient { + GradientStop { position: 0; color: "black" } + GradientStop { position: 1.0; color: "#AAAAAA" } + } width: 600 height: 600 resources: [ diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index cc5afc3..4271022 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -45,6 +45,8 @@ QT_BEGIN_NAMESPACE QML_DEFINE_TYPE(QFxPen,Pen) +QML_DEFINE_TYPE(QFxGradientStop,GradientStop) +QML_DEFINE_TYPE(QFxGradient,Gradient) /*! \internal @@ -117,6 +119,57 @@ void QFxPen::setWidth(int w) } +/*! + \qmlclass GradientStop QFxGradientStop + \brief The GradientStop item defines the color at a position in a Gradient + + \sa Gradient +*/ + +/*! + \qmlproperty real GradientStop::position + \qmlproperty color GradientStop::color + + Sets a \e color at a \e position in a gradient. +*/ + +/*! + \qmlclass Gradient QFxGradient + \brief The Gradient item defines a gradient fill. + + A gradient is defined by two or more colors, which will be blended seemlessly. The + colors are specified at their position in the range 0.0 - 1.0 via + the GradientStop item. For example, the following code paints a + Rect with a gradient starting with red, blending to yellow at 1/3 of the + size of the Rect, and ending with Green: + + \table + \row + \o \image gradient.png + \o \quotefile doc/src/snippets/declarative/gradient.qml + \endtable + + \sa GradientStop +*/ + +/*! + \qmlproperty list Gradient::stops + This property holds the gradient stops describing the gradient. +*/ + +const QGradient *QFxGradient::gradient() const +{ + if (!m_gradient && !m_stops.isEmpty()) { + m_gradient = new QLinearGradient(0,0,0,1.0); + for (int i = 0; i < m_stops.count(); ++i) { + const QFxGradientStop *stop = m_stops.at(i); + m_gradient->setCoordinateMode(QGradient::ObjectBoundingMode); + m_gradient->setColorAt(stop->position(), stop->color()); + } + } + + return m_gradient; +} QML_DEFINE_TYPE(QFxRect,Rect) @@ -215,6 +268,51 @@ QFxPen *QFxRect::pen() } /*! + \qmlproperty Gradient Rect::gradient + + The gradient to use to fill the rect. + + This property allows for the construction of simple vertical gradients. + Other gradients may by formed by adding rotation to the rect. + + \table + \row + \o \image declarative-rect_gradient.png + \o + \qml + Rect { y: 0; width: 80; height: 80; color: "lightsteelblue" } + Rect { y: 100; width: 80; height: 80 + gradient: Gradient { + GradientStop { position: 0.0; color: "lightsteelblue" } + GradientStop { position: 1.0; color: "blue" } + } + } + Rect { rotation: 90; x: 80; y: 200; width: 80; height: 80 + gradient: Gradient { + GradientStop { position: 0.0; color: "lightsteelblue" } + GradientStop { position: 1.0; color: "blue" } + } + } + // The x offset is needed because the rotation is from the top left corner + \endqml + \endtable + + \sa Gradient, color +*/ +QFxGradient *QFxRect::gradient() const +{ + Q_D(const QFxRect); + return d->gradient; +} + +void QFxRect::setGradient(QFxGradient *gradient) +{ + Q_D(QFxRect); + d->gradient = gradient; +} + + +/*! \qmlproperty real Rect::radius This property holds the corner radius used to draw a rounded rect. @@ -358,42 +456,6 @@ QColor QFxRectPrivate::getColor() } } -/*! - \qmlproperty color Rect::gradientColor - This property holds the color to use at the base of the rectangle and blend upwards. - - This property allows for the easy construction of simple horizontal gradients. Other gradients may by formed by adding rotation to the rect. The gradient will blend linearly from the rect's main color to the color specified for gradient color. - - \qml - Rect { y: 0; width: 80; height: 80; color: "lightsteelblue" } - Rect { y: 100; width: 80; height: 80; color: "lightsteelblue"; gradientColor="blue" } - Rect { rotation: 90; x: 80; y: 200; width: 80; height: 80; color="lightsteelblue" - gradientColor: "blue" } - // The x offset is needed because the rotation is from the top left corner - \endqml - \image declarative-rect_gradient.png -*/ - -/*! - \property QFxRect::gradientColor - \brief The color to use at the base of the rectangle and blend upwards. -*/ - -QColor QFxRect::gradientColor() const -{ - Q_D(const QFxRect); - return d->_gradcolor; -} - -void QFxRect::setGradientColor(const QColor &c) -{ - Q_D(QFxRect); - if (d->_gradcolor == c) - return; - - d->_gradcolor = c; - update(); -} #if defined(QFX_RENDER_QPAINTER) void QFxRect::generateRoundedRect() @@ -485,16 +547,8 @@ void QFxRect::paintContents(QPainter &p) { Q_D(QFxRect); if (d->_radius > 0 || (d->_pen && d->_pen->isValid()) - || d->_gradcolor.isValid()) + || (d->gradient && d->gradient->gradient()) ) drawRect(p); - /* - QLinearGradient grad(0, 0, 0, height()); - grad.setColorAt(0, d->_color); - grad.setColorAt(1, d->_gradcolor); - p.setBrush(grad); - p.drawRect(0, 0, width(), height()); - p.setBrush(QBrush()); - */ else p.fillRect(QRect(0, 0, width(), height()), d->getColor()); } @@ -502,7 +556,7 @@ void QFxRect::paintContents(QPainter &p) void QFxRect::drawRect(QPainter &p) { Q_D(QFxRect); - if (d->_gradcolor.isValid() /*|| p.usingQt() */) { + if (d->gradient && d->gradient->gradient() /*|| p.usingQt() */) { // XXX This path is still slower than the image path // Image path won't work for gradients though QPainter::RenderHints oldHints = p.renderHints(); @@ -513,15 +567,8 @@ void QFxRect::drawRect(QPainter &p) } else { p.setPen(Qt::NoPen); } - if (d->_gradcolor.isValid()){ - QLinearGradient grad(0, 0, 0, height()); - grad.setColorAt(0, d->_color); - grad.setColorAt(1, d->_gradcolor); - p.setBrush(grad); - }else{ - p.setBrush(d->_color); - } - if (d->_radius) + p.setBrush(*d->gradient->gradient()); + if (d->_radius > 0.) p.drawRoundedRect(0, 0, width(), height(), d->_radius, d->_radius); else p.drawRect(0, 0, width(), height()); diff --git a/src/declarative/fx/qfxrect.h b/src/declarative/fx/qfxrect.h index 209a8ef..2c59914 100644 --- a/src/declarative/fx/qfxrect.h +++ b/src/declarative/fx/qfxrect.h @@ -79,6 +79,49 @@ private: }; QML_DECLARE_TYPE(QFxPen) +class Q_DECLARATIVE_EXPORT QFxGradientStop : public QObject +{ + Q_OBJECT + + Q_PROPERTY(qreal position READ position WRITE setPosition) + Q_PROPERTY(QColor color READ color WRITE setColor) + +public: + QFxGradientStop(QObject *parent=0) : QObject(parent) {} + + qreal position() const { return m_position; } + void setPosition(qreal position) { m_position = position; } + + QColor color() const { return m_color; } + void setColor(const QColor &color) { m_color = color; } + +private: + qreal m_position; + QColor m_color; +}; +QML_DECLARE_TYPE(QFxGradientStop) + +class Q_DECLARATIVE_EXPORT QFxGradient : public QObject +{ + Q_OBJECT + + Q_PROPERTY(QList *stops READ stops) + Q_CLASSINFO("DefaultProperty", "stops") + +public: + QFxGradient(QObject *parent=0) : QObject(parent), m_gradient(0), m_created(false) {} + + QList *stops() { return &m_stops; } + + const QGradient *gradient() const; + +private: + QList m_stops; + mutable QGradient *m_gradient; + mutable bool m_created; +}; +QML_DECLARE_TYPE(QFxGradient) + class QFxRectPrivate; class Q_DECLARATIVE_EXPORT QFxRect : public QFxItem { @@ -86,7 +129,7 @@ class Q_DECLARATIVE_EXPORT QFxRect : public QFxItem Q_PROPERTY(QColor color READ color WRITE setColor) Q_PROPERTY(QColor tintColor READ tintColor WRITE setTintColor) - Q_PROPERTY(QColor gradientColor READ gradientColor WRITE setGradientColor) + Q_PROPERTY(QFxGradient *gradient READ gradient WRITE setGradient) Q_PROPERTY(QFxPen * pen READ pen) Q_PROPERTY(qreal radius READ radius WRITE setRadius) public: @@ -98,11 +141,11 @@ public: QColor tintColor() const; void setTintColor(const QColor &); - QColor gradientColor() const; - void setGradientColor(const QColor &); - QFxPen *pen(); + QFxGradient *gradient() const; + void setGradient(QFxGradient *gradient); + qreal radius() const; void setRadius(qreal radius); diff --git a/src/declarative/fx/qfxrect_p.h b/src/declarative/fx/qfxrect_p.h index 2fd555f..8faaa38 100644 --- a/src/declarative/fx/qfxrect_p.h +++ b/src/declarative/fx/qfxrect_p.h @@ -61,13 +61,15 @@ QT_BEGIN_NAMESPACE +class QFxGradient; + class QFxRectPrivate : public QFxItemPrivate { Q_DECLARE_PUBLIC(QFxRect) public: QFxRectPrivate() - : _pen(0), _radius(0) + : gradient(0), _pen(0), _radius(0) { } @@ -85,7 +87,7 @@ public: #endif QColor getColor(); QColor _color; - QColor _gradcolor; + QFxGradient *gradient; QColor _tintColor; QFxPen *pen() { if (!_pen) { -- cgit v0.12 From 68c915846e8820e008d15fb3453aa6f45d5becf4 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 27 May 2009 17:20:56 +1000 Subject: Fix memory leak. --- src/declarative/fx/qfxrect.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/declarative/fx/qfxrect.h b/src/declarative/fx/qfxrect.h index 2c59914..864b1cd 100644 --- a/src/declarative/fx/qfxrect.h +++ b/src/declarative/fx/qfxrect.h @@ -109,7 +109,8 @@ class Q_DECLARATIVE_EXPORT QFxGradient : public QObject Q_CLASSINFO("DefaultProperty", "stops") public: - QFxGradient(QObject *parent=0) : QObject(parent), m_gradient(0), m_created(false) {} + QFxGradient(QObject *parent=0) : QObject(parent), m_gradient(0) {} + ~QFxGradient() { delete m_gradient; } QList *stops() { return &m_stops; } @@ -118,7 +119,6 @@ public: private: QList m_stops; mutable QGradient *m_gradient; - mutable bool m_created; }; QML_DECLARE_TYPE(QFxGradient) -- cgit v0.12 From 5e14efa547ffac5890b008ad23e9ff0bc634a3e1 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Wed, 27 May 2009 09:38:32 +0200 Subject: Use GLInt and not uint because of Apple's old header swap --- src/opengl/qpixmapdata_gl_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/opengl/qpixmapdata_gl_p.h b/src/opengl/qpixmapdata_gl_p.h index 536f33d..7e06db9 100644 --- a/src/opengl/qpixmapdata_gl_p.h +++ b/src/opengl/qpixmapdata_gl_p.h @@ -116,7 +116,7 @@ private: int m_height; mutable QGLFramebufferObject *m_renderFbo; - mutable uint m_textureId; + mutable GLuint m_textureId; mutable QPaintEngine *m_engine; mutable QGLContext *m_ctx; mutable bool m_dirty; -- cgit v0.12 From 0ea19cf01e2381969a8b8ce8cdaffe9ce873d3a9 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Mon, 25 May 2009 22:47:06 +0200 Subject: Add a flag that ensure that a connection is made only one It is often desirable, when doing connection, to ensure that the same connection is only made once. This can be done with the Qt::UniqueConnection 'flag' Also documented the order the slot are called Reviewed-by: Brad --- doc/src/qnamespace.qdoc | 4 ++ doc/src/signalsandslots.qdoc | 14 ++++--- src/corelib/global/qnamespace.h | 3 +- src/corelib/kernel/qobject.cpp | 36 ++++++++++++----- tests/auto/qobject/tst_qobject.cpp | 81 ++++++++++++++++++++++++++++++++++++-- 5 files changed, 119 insertions(+), 19 deletions(-) diff --git a/doc/src/qnamespace.qdoc b/doc/src/qnamespace.qdoc index fc4310b..069541f 100644 --- a/doc/src/qnamespace.qdoc +++ b/doc/src/qnamespace.qdoc @@ -528,6 +528,10 @@ Qt::DirectConnection; otherwise the signal is queued, as with Qt::QueuedConnection. + \value UniqueConnection Same as AutoConnection, but there will be a check that the signal is + not already connected to the same slot before connecting, otherwise, + the connection will fail. + \since 4.6 With queued connections, the parameters must be of types that are known to Qt's meta-object system, because Qt needs to copy the arguments to store them diff --git a/doc/src/signalsandslots.qdoc b/doc/src/signalsandslots.qdoc index 5432bd4..29c8215 100644 --- a/doc/src/signalsandslots.qdoc +++ b/doc/src/signalsandslots.qdoc @@ -178,9 +178,13 @@ looping in the case of cyclic connections (e.g., if \c{b.valueChanged()} were connected to \c{a.setValue()}). - A signal is emitted for every connection you make; if you - duplicate a connection, two signals will be emitted. You can - always break a connection using QObject::disconnect(). + By default, for every connection you make, a signal is emitted; + two signals are emitted for duplicate connections. You can break + all of these connections with a single disconnect() call. + If you pass the Qt::UniqueConnection \a type, the connection will only + be made if it is not a duplicate. If there is already a duplicate + (exact same signal to the exact same slot on the same objects), + the connection will fail and connect will return false This example illustrates that objects can work together without needing to know any information about each other. To enable this, the objects only @@ -218,8 +222,8 @@ will continue immediately, and the slots will be executed later. If several slots are connected to one signal, the slots will be - executed one after the other, in an arbitrary order, when the signal - is emitted. + executed one after the other, in the order they have been connected, + when the signal is emitted. Signals are automatically generated by the \l moc and must not be implemented in the \c .cpp file. They can never have return types diff --git a/src/corelib/global/qnamespace.h b/src/corelib/global/qnamespace.h index 3367581..9e53d89 100644 --- a/src/corelib/global/qnamespace.h +++ b/src/corelib/global/qnamespace.h @@ -1327,7 +1327,8 @@ public: DirectConnection, QueuedConnection, AutoCompatConnection, - BlockingQueuedConnection + BlockingQueuedConnection, + UniqueConnection = 0x80 }; enum ShortcutContext { diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index 65d81f1..be622d9 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -301,7 +301,6 @@ void QObjectPrivate::addConnection(int signal, Connection *c) ConnectionList &connectionList = (*connectionLists)[signal]; connectionList.append(c); - cleanConnectionLists(); } @@ -2377,7 +2376,8 @@ int QObject::receivers(const char *signal) const can be connected to one slot. If a signal is connected to several slots, the slots are activated - in an arbitrary order when the signal is emitted. + in the same order as the order the connection was made, when the + signal is emitted. The function returns true if it successfully connects the signal to the slot. It will return false if it cannot create the @@ -2385,9 +2385,13 @@ int QObject::receivers(const char *signal) const existence of either \a signal or \a method, or if their signatures aren't compatible. - For every connection you make, a signal is emitted; two signals are emitted - for duplicate connections. You can break all of these connections with a - single disconnect() call. + By default, a signal is emitted for every connection you make; + two signals are emitted for duplicate connections. You can break + all of these connections with a single disconnect() call. + If you pass the Qt::UniqueConnection \a type, the connection will only + be made if it is not a duplicate. If there is already a duplicate + (exact same signal to the exact same slot on the same objects), + the connection will fail and connect will return false The optional \a type parameter describes the type of connection to establish. In particular, it determines whether a particular @@ -2520,7 +2524,8 @@ bool QObject::connect(const QObject *sender, const char *signal, } } #endif - QMetaObject::connect(sender, signal_index, receiver, method_index, type, types); + if (!QMetaObject::connect(sender, signal_index, receiver, method_index, type, types)) + return false; const_cast(sender)->connectNotify(signal - 1); return true; } @@ -2771,6 +2776,22 @@ bool QMetaObject::connect(const QObject *sender, int signal_index, QObject *s = const_cast(sender); QObject *r = const_cast(receiver); + QOrderedMutexLocker locker(signalSlotLock(sender), + signalSlotLock(receiver)); + + if (type & Qt::UniqueConnection) { + QObjectConnectionListVector *connectionLists = s->d_func()->connectionLists; + if (connectionLists && connectionLists->count() > signal_index) { + QObjectPrivate::ConnectionList &connectionList = (*connectionLists)[signal_index]; + for (int i = 0; i < connectionList.count(); ++i) { + QObjectPrivate::Connection *c2 = connectionList.at(i); + if (c2->receiver == receiver && c2->method == method_index) + return false; + } + } + type &= Qt::UniqueConnection - 1; + } + QObjectPrivate::Connection *c = new QObjectPrivate::Connection; c->sender = s; c->receiver = r; @@ -2778,9 +2799,6 @@ bool QMetaObject::connect(const QObject *sender, int signal_index, c->connectionType = type; c->argumentTypes = types; - QOrderedMutexLocker locker(signalSlotLock(sender), - signalSlotLock(receiver)); - s->d_func()->addConnection(signal_index, c); r->d_func()->senders.append(c); diff --git a/tests/auto/qobject/tst_qobject.cpp b/tests/auto/qobject/tst_qobject.cpp index fb46073..399d021 100644 --- a/tests/auto/qobject/tst_qobject.cpp +++ b/tests/auto/qobject/tst_qobject.cpp @@ -116,6 +116,7 @@ private slots: void dumpObjectInfo(); void connectToSender(); void qobjectConstCast(); + void uniqConnection(); protected: }; @@ -204,12 +205,20 @@ public: sequence_slot3 = 0; sequence_slot2 = 0; sequence_slot1 = 0; + count_slot1 = 0; + count_slot2 = 0; + count_slot3 = 0; + count_slot4 = 0; } int sequence_slot1; int sequence_slot2; int sequence_slot3; int sequence_slot4; + int count_slot1; + int count_slot2; + int count_slot3; + int count_slot4; bool called(int slot) { switch (slot) { @@ -224,10 +233,10 @@ public: static int sequence; public slots: - void slot1() { sequence_slot1 = ++sequence; } - void slot2() { sequence_slot2 = ++sequence; } - void slot3() { sequence_slot3 = ++sequence; } - void slot4() { sequence_slot4 = ++sequence; } + void slot1() { sequence_slot1 = ++sequence; count_slot1++; } + void slot2() { sequence_slot2 = ++sequence; count_slot2++; } + void slot3() { sequence_slot3 = ++sequence; count_slot3++; } + void slot4() { sequence_slot4 = ++sequence; count_slot4++; } }; @@ -2783,5 +2792,69 @@ void tst_QObject::qobjectConstCast() QVERIFY(qobject_cast(cptr)); } +void tst_QObject::uniqConnection() +{ + SenderObject *s = new SenderObject; + ReceiverObject *r1 = new ReceiverObject; + ReceiverObject *r2 = new ReceiverObject; + r1->reset(); + r2->reset(); + ReceiverObject::sequence = 0; + + QVERIFY( connect( s, SIGNAL( signal1() ), r1, SLOT( slot1() ) , Qt::UniqueConnection) ); + QVERIFY( connect( s, SIGNAL( signal1() ), r2, SLOT( slot1() ) , Qt::UniqueConnection) ); + QVERIFY( connect( s, SIGNAL( signal1() ), r1, SLOT( slot3() ) , Qt::UniqueConnection) ); + QVERIFY( connect( s, SIGNAL( signal3() ), r1, SLOT( slot3() ) , Qt::UniqueConnection) ); + + s->emitSignal1(); + s->emitSignal2(); + s->emitSignal3(); + s->emitSignal4(); + + QCOMPARE( r1->count_slot1, 1 ); + QCOMPARE( r1->count_slot2, 0 ); + QCOMPARE( r1->count_slot3, 2 ); + QCOMPARE( r1->count_slot4, 0 ); + QCOMPARE( r2->count_slot1, 1 ); + QCOMPARE( r2->count_slot2, 0 ); + QCOMPARE( r2->count_slot3, 0 ); + QCOMPARE( r2->count_slot4, 0 ); + QCOMPARE( r1->sequence_slot1, 1 ); + QCOMPARE( r2->sequence_slot1, 2 ); + QCOMPARE( r1->sequence_slot3, 4 ); + + r1->reset(); + r2->reset(); + ReceiverObject::sequence = 0; + + QVERIFY( connect( s, SIGNAL( signal4() ), r1, SLOT( slot4() ) , Qt::UniqueConnection) ); + QVERIFY( connect( s, SIGNAL( signal4() ), r2, SLOT( slot4() ) , Qt::UniqueConnection) ); + QVERIFY(!connect( s, SIGNAL( signal4() ), r2, SLOT( slot4() ) , Qt::UniqueConnection) ); + QVERIFY( connect( s, SIGNAL( signal1() ), r2, SLOT( slot4() ) , Qt::UniqueConnection) ); + QVERIFY(!connect( s, SIGNAL( signal4() ), r1, SLOT( slot4() ) , Qt::UniqueConnection) ); + + s->emitSignal4(); + QCOMPARE( r1->count_slot4, 1 ); + QCOMPARE( r2->count_slot4, 1 ); + QCOMPARE( r1->sequence_slot4, 1 ); + QCOMPARE( r2->sequence_slot4, 2 ); + + r1->reset(); + r2->reset(); + ReceiverObject::sequence = 0; + + connect( s, SIGNAL( signal4() ), r1, SLOT( slot4() ) ); + + s->emitSignal4(); + QCOMPARE( r1->count_slot4, 2 ); + QCOMPARE( r2->count_slot4, 1 ); + QCOMPARE( r1->sequence_slot4, 3 ); + QCOMPARE( r2->sequence_slot4, 2 ); + + delete s; + delete r1; + delete r2; +} + QTEST_MAIN(tst_QObject) #include "tst_qobject.moc" -- cgit v0.12 From 00ffd16d367a19f958149b3b4ec5f5c5e6b71f9b Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 27 May 2009 09:56:16 +0200 Subject: Do not use the locale in QDoubleSpinBoxPrivate::round We had a report from a customer saying this breaks if the decimal separator is the same as the group separator. This is not really something we want to support, but because this fix is easy and cleanup the code I decided to fix it. Reviewed-by: Thierry Task-number: 253962 --- src/gui/widgets/qspinbox.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/gui/widgets/qspinbox.cpp b/src/gui/widgets/qspinbox.cpp index b7426f0..f12946c 100644 --- a/src/gui/widgets/qspinbox.cpp +++ b/src/gui/widgets/qspinbox.cpp @@ -1254,9 +1254,7 @@ QVariant QDoubleSpinBoxPrivate::valueFromText(const QString &f) const double QDoubleSpinBoxPrivate::round(double value) const { - Q_Q(const QDoubleSpinBox); - const QString strDbl = q->locale().toString(value, 'f', decimals); - return q->locale().toDouble(strDbl); + return QString::number(value, 'f', decimals).toDouble(); } -- cgit v0.12 From 0bcfa7aa496d460c72862369662560c49eb55f17 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 27 May 2009 11:48:20 +0200 Subject: small refactor to change the interpolator at the same time as the current interval in the variant animations --- src/corelib/animation/qpropertyanimation.cpp | 11 ++++--- src/corelib/animation/qpropertyanimation_p.h | 2 +- src/corelib/animation/qvariantanimation.cpp | 43 +++++++++++++++++++--------- src/corelib/animation/qvariantanimation_p.h | 18 ++++-------- 4 files changed, 40 insertions(+), 34 deletions(-) diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp index 9a17049..47361a5 100644 --- a/src/corelib/animation/qpropertyanimation.cpp +++ b/src/corelib/animation/qpropertyanimation.cpp @@ -110,17 +110,16 @@ void QPropertyAnimationPrivate::updateMetaProperty() if (!target || propertyName.isEmpty()) return; - if (hasMetaProperty == 0 && !property.isValid()) { + if (!hasMetaProperty && !property.isValid()) { const QMetaObject *mo = target->metaObject(); propertyIndex = mo->indexOfProperty(propertyName); if (propertyIndex != -1) { - hasMetaProperty = 1; + hasMetaProperty = true; property = mo->property(propertyIndex); propertyType = property.userType(); } else { if (!target->dynamicPropertyNames().contains(propertyName)) qWarning("QPropertyAnimation: you're trying to animate a non-existing property %s of your QObject", propertyName.constData()); - hasMetaProperty = 2; } } @@ -133,7 +132,7 @@ void QPropertyAnimationPrivate::updateProperty(const QVariant &newValue) if (!target || state == QAbstractAnimation::Stopped) return; - if (hasMetaProperty == 1) { + if (hasMetaProperty) { if (newValue.userType() == propertyType) { //no conversion is needed, we directly call the QObject::qt_metacall void *data = const_cast(newValue.constData()); @@ -216,7 +215,7 @@ void QPropertyAnimation::setTargetObject(QObject *target) connect(target, SIGNAL(destroyed()), SLOT(_q_targetDestroyed())); d->target = target; - d->hasMetaProperty = 0; + d->hasMetaProperty = false; d->updateMetaProperty(); } @@ -242,7 +241,7 @@ void QPropertyAnimation::setPropertyName(const QByteArray &propertyName) } d->propertyName = propertyName; - d->hasMetaProperty = 0; + d->hasMetaProperty = false; d->updateMetaProperty(); } diff --git a/src/corelib/animation/qpropertyanimation_p.h b/src/corelib/animation/qpropertyanimation_p.h index b51d039..a4387dd 100644 --- a/src/corelib/animation/qpropertyanimation_p.h +++ b/src/corelib/animation/qpropertyanimation_p.h @@ -78,7 +78,7 @@ public: int propertyType; int propertyIndex; - int hasMetaProperty; + bool hasMetaProperty; QByteArray propertyName; void updateProperty(const QVariant &); void updateMetaProperty(); diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp index 239add9..e973ec5 100644 --- a/src/corelib/animation/qvariantanimation.cpp +++ b/src/corelib/animation/qvariantanimation.cpp @@ -144,6 +144,11 @@ static bool animationValueLessThan(const QVariantAnimation::KeyValue &p1, const return p1.first < p2.first; } +static QVariant defaultInterpolator(const void *, const void *, qreal) +{ + return QVariant(); +} + template<> Q_INLINE_TEMPLATE QRect _q_interpolate(const QRect &f, const QRect &t, qreal progress) { QRect ret; @@ -174,6 +179,13 @@ template<> Q_INLINE_TEMPLATE QLineF _q_interpolate(const QLineF &f, const QLineF return QLineF( _q_interpolate(f.p1(), t.p1(), progress), _q_interpolate(f.p2(), t.p2(), progress)); } +QVariantAnimationPrivate::QVariantAnimationPrivate() : duration(250), hasStartValue(false), + interpolator(&defaultInterpolator), + changedSignalMask(1 << QVariantAnimation::staticMetaObject.indexOfSignal("valueChanged(QVariant)")) +{ + //we keep the mask so that we emit valueChanged only when needed (for performance reasons) +} + void QVariantAnimationPrivate::convertValues(int t) { //this ensures that all the keyValues are of type t @@ -186,7 +198,20 @@ void QVariantAnimationPrivate::convertValues(int t) currentInterval.end.second.convert(static_cast(t)); //... and the interpolator - interpolator = 0; + updateInterpolator(); +} + +void QVariantAnimationPrivate::updateInterpolator() +{ + int type = currentInterval.start.second.userType(); + if (type == currentInterval.end.second.userType()) + interpolator = getInterpolator(type); + else + interpolator = 0; + + //we make sure that the interpolator is always set to something + if (!interpolator) + interpolator = &defaultInterpolator; } /*! @@ -224,6 +249,7 @@ void QVariantAnimationPrivate::recalculateCurrentInterval(bool force/*=false*/) // update all the values of the currentInterval currentInterval.start = *itStart; currentInterval.end = *itEnd; + updateInterpolator(); } } setCurrentValueForProgress(progress); @@ -295,7 +321,6 @@ void QVariantAnimationPrivate::setDefaultStartValue(const QVariant &value) */ QVariantAnimation::QVariantAnimation(QObject *parent) : QAbstractAnimation(*new QVariantAnimationPrivate, parent) { - d_func()->init(); } /*! @@ -303,7 +328,6 @@ QVariantAnimation::QVariantAnimation(QObject *parent) : QAbstractAnimation(*new */ QVariantAnimation::QVariantAnimation(QVariantAnimationPrivate &dd, QObject *parent) : QAbstractAnimation(dd, parent) { - d_func()->init(); } /*! @@ -629,15 +653,7 @@ void QVariantAnimation::updateState(QAbstractAnimation::State oldState, */ QVariant QVariantAnimation::interpolated(const QVariant &from, const QVariant &to, qreal progress) const { - Q_D(const QVariantAnimation); - if (d->interpolator == 0) { - if (from.userType() == to.userType()) - d->interpolator = QVariantAnimationPrivate::getInterpolator(from.userType()); - if (d->interpolator == 0) //no interpolator found - return QVariant(); - } - - return d->interpolator(from.constData(), to.constData(), progress); + return d_func()->interpolator(from.constData(), to.constData(), progress); } /*! @@ -645,9 +661,8 @@ QVariant QVariantAnimation::interpolated(const QVariant &from, const QVariant &t */ void QVariantAnimation::updateCurrentTime(int msecs) { - Q_D(QVariantAnimation); Q_UNUSED(msecs); - d->recalculateCurrentInterval(); + d_func()->recalculateCurrentInterval(); } QT_END_NAMESPACE diff --git a/src/corelib/animation/qvariantanimation_p.h b/src/corelib/animation/qvariantanimation_p.h index 0d296db..2c559cf 100644 --- a/src/corelib/animation/qvariantanimation_p.h +++ b/src/corelib/animation/qvariantanimation_p.h @@ -67,17 +67,7 @@ class QVariantAnimationPrivate : public QAbstractAnimationPrivate Q_DECLARE_PUBLIC(QVariantAnimation) public: - QVariantAnimationPrivate() : duration(250), hasStartValue(false) - { - } - - void init() - { - //we keep the mask so that we emit valueChanged only when needed (for performance reasons) - changedSignalMask = (1 << q_func()->metaObject()->indexOfSignal("valueChanged(QVariant)")); - currentInterval.start.first = currentInterval.end.first = 2; //will force the initial refresh - interpolator = 0; - } + QVariantAnimationPrivate(); static QVariantAnimationPrivate *get(QVariantAnimation *q) { @@ -100,9 +90,9 @@ public: QVariantAnimation::KeyValue start, end; } currentInterval; - mutable QVariantAnimation::Interpolator interpolator; + QVariantAnimation::Interpolator interpolator; - quint32 changedSignalMask; + const quint32 changedSignalMask; void setCurrentValueForProgress(const qreal progress); void recalculateCurrentInterval(bool force=false); @@ -110,6 +100,8 @@ public: QVariant valueAt(qreal step) const; void convertValues(int t); + void updateInterpolator(); + static QVariantAnimation::Interpolator getInterpolator(int interpolationType); }; -- cgit v0.12 From 80bc757b56953065fafeffe6c4b8fb6fbca287ac Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Wed, 27 May 2009 10:30:07 +0200 Subject: Avoid deep copies of pixmaps when using cache in QGraphicsView. When we have already a pixmap of an item in the cache, we should remove the entry from the cache otherwise when we will repaint/modify the copy of the pixmap (the copy of the cache) then we will trigger a deep copy ; this is because both entries in the cache and our copy share the same data and if you modify one of them a copy is triggered. I have added a benchmark as well to test that. Reviewed-by:bnilsen Reviewed-by:andreas --- src/gui/graphicsview/qgraphicsscene.cpp | 28 +++--- .../benchmarks/qgraphicsview/images/wine-big.jpeg | Bin 0 -> 12249 bytes tests/benchmarks/qgraphicsview/qgraphicsview.qrc | 1 + .../benchmarks/qgraphicsview/tst_qgraphicsview.cpp | 102 +++++++++++++++++++++ 4 files changed, 118 insertions(+), 13 deletions(-) create mode 100644 tests/benchmarks/qgraphicsview/images/wine-big.jpeg diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 126ea5b..1fc4567 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -4784,6 +4784,12 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte // Redraw any newly exposed areas. if (itemCache->allExposed || !itemCache->exposed.isEmpty()) { + + //We know that we will modify the pixmap, removing it from the cache + //will detach the one we have and avoid a deep copy + if (pixmapFound) + QPixmapCache::remove(pixmapKey); + // Fit the item's bounding rect into the pixmap's coordinates. QTransform itemToPixmap; if (fixedCacheSize) { @@ -4812,12 +4818,8 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(), &cacheOption, painterStateProtection); - if (!pixmapFound) { - // insert this pixmap into the cache. - itemCache->key = QPixmapCache::insert(pix); - } else { - QPixmapCache::replace(pixmapKey, pix); - } + // insert this pixmap into the cache. + itemCache->key = QPixmapCache::insert(pix); // Reset expose data. itemCache->allExposed = false; @@ -4944,6 +4946,11 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte // Check for newly invalidated areas. if (itemCache->allExposed || !itemCache->exposed.isEmpty() || !scrollExposure.isEmpty()) { + //We know that we will modify the pixmap, removing it from the cache + //will detach the one we have and avoid a deep copy + if (pixmapFound) + QPixmapCache::remove(pixmapKey); + // Construct an item-to-pixmap transform. QPointF p = deviceRect.topLeft(); QTransform itemToPixmap = painter->worldTransform(); @@ -4984,13 +4991,8 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } if (pixModified) { - if (!pixmapFound) { - // Insert this pixmap into the cache. - deviceData->key = QPixmapCache::insert(pix); - } else { - //otherwise we replace the pixmap in the cache - QPixmapCache::replace(pixmapKey, pix); - } + // Insert this pixmap into the cache. + deviceData->key = QPixmapCache::insert(pix); } // Redraw the exposed area using an untransformed painter. This diff --git a/tests/benchmarks/qgraphicsview/images/wine-big.jpeg b/tests/benchmarks/qgraphicsview/images/wine-big.jpeg new file mode 100644 index 0000000..9900a50 Binary files /dev/null and b/tests/benchmarks/qgraphicsview/images/wine-big.jpeg differ diff --git a/tests/benchmarks/qgraphicsview/qgraphicsview.qrc b/tests/benchmarks/qgraphicsview/qgraphicsview.qrc index 5e80029..3681648 100644 --- a/tests/benchmarks/qgraphicsview/qgraphicsview.qrc +++ b/tests/benchmarks/qgraphicsview/qgraphicsview.qrc @@ -2,6 +2,7 @@ images/designer.png images/wine.jpeg + images/wine-big.jpeg random.data diff --git a/tests/benchmarks/qgraphicsview/tst_qgraphicsview.cpp b/tests/benchmarks/qgraphicsview/tst_qgraphicsview.cpp index a06e033..570f744 100644 --- a/tests/benchmarks/qgraphicsview/tst_qgraphicsview.cpp +++ b/tests/benchmarks/qgraphicsview/tst_qgraphicsview.cpp @@ -124,6 +124,8 @@ private slots: void textRiver(); void moveItemCache_data(); void moveItemCache(); + void paintItemCache_data(); + void paintItemCache(); }; tst_QGraphicsView::tst_QGraphicsView() @@ -796,5 +798,105 @@ void tst_QGraphicsView::moveItemCache() } } +class UpdatedPixmapCacheItem : public QGraphicsPixmapItem +{ +public: + UpdatedPixmapCacheItem(bool partial, QGraphicsItem *parent = 0) + : QGraphicsPixmapItem(parent), partial(partial) + { + } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) + { + QGraphicsPixmapItem::paint(painter,option,widget); + } +protected: + void advance(int i) + { + if (partial) + update(QRectF(boundingRect().center().x(), boundingRect().center().x(), 30, 30)); + else + update(); + } + +private: + bool partial; +}; + +void tst_QGraphicsView::paintItemCache_data() +{ + QTest::addColumn("updatePartial"); + QTest::addColumn("rotation"); + QTest::addColumn("cacheMode"); + QTest::newRow("Partial Update : ItemCoordinate Cache") << true << false << (int)QGraphicsItem::ItemCoordinateCache; + QTest::newRow("Partial Update : DeviceCoordinate Cache") << true << false << (int)QGraphicsItem::DeviceCoordinateCache; + QTest::newRow("Partial Update : No Cache") << true << false << (int)QGraphicsItem::NoCache; + QTest::newRow("Full Update : ItemCoordinate Cache") << false << false << (int)QGraphicsItem::ItemCoordinateCache; + QTest::newRow("Full Update : DeviceCoordinate Cache") << false << false << (int)QGraphicsItem::DeviceCoordinateCache; + QTest::newRow("Full Update : No Cache") << false << false << (int)QGraphicsItem::NoCache; + QTest::newRow("Partial Update : ItemCoordinate Cache item rotated") << true << true << (int)QGraphicsItem::ItemCoordinateCache; + QTest::newRow("Partial Update : DeviceCoordinate Cache item rotated") << true << true << (int)QGraphicsItem::DeviceCoordinateCache; + QTest::newRow("Partial Update : No Cache item rotated") << true << true << (int)QGraphicsItem::NoCache; + QTest::newRow("Full Update : ItemCoordinate Cache item rotated") << false << true << (int)QGraphicsItem::ItemCoordinateCache; + QTest::newRow("Full Update : DeviceCoordinate Cache item rotated") << false << true << (int)QGraphicsItem::DeviceCoordinateCache; + QTest::newRow("Full Update : No Cache item rotated") << false << true <<(int)QGraphicsItem::NoCache; +} + +void tst_QGraphicsView::paintItemCache() +{ + QFETCH(bool, updatePartial); + QFETCH(bool, rotation); + QFETCH(int, cacheMode); + + QGraphicsScene scene(0, 0, 300, 300); + + CountPaintEventView view(&scene); + view.resize(600, 600); + view.setFrameStyle(0); + view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + view.show(); + + QPixmap pix(":/images/wine.jpeg"); + QVERIFY(!pix.isNull()); + + QList items; + QFile file(":/random.data"); + QVERIFY(file.open(QIODevice::ReadOnly)); + QDataStream str(&file); + UpdatedPixmapCacheItem *item = new UpdatedPixmapCacheItem(updatePartial); + item->setPixmap(pix); + item->setCacheMode((QGraphicsItem::CacheMode)cacheMode); + if (rotation) + item->setTransform(QTransform().rotate(45)); + item->setPos(-100, -100); + scene.addItem(item); + + QPixmap pix2(":/images/wine-big.jpeg"); + item = new UpdatedPixmapCacheItem(updatePartial); + item->setPixmap(pix2); + item->setCacheMode((QGraphicsItem::CacheMode)cacheMode); + if (rotation) + item->setTransform(QTransform().rotate(45)); + item->setPos(0, 0); + scene.addItem(item); + + view.count = 0; + + QBENCHMARK { +#ifdef CALLGRIND_DEBUG + CALLGRIND_START_INSTRUMENTATION +#endif + for (int i = 0; i < 50; ++i) { + scene.advance(); + while (view.count < (i+1)) + qApp->processEvents(); + } +#ifdef CALLGRIND_DEBUG + CALLGRIND_STOP_INSTRUMENTATION +#endif + } +} + QTEST_MAIN(tst_QGraphicsView) #include "tst_qgraphicsview.moc" -- cgit v0.12 From 2c1b11f2192fd48da01a1093a7cb4a848de43c8a Mon Sep 17 00:00:00 2001 From: Trond Kjernaasen Date: Wed, 27 May 2009 11:11:57 +0200 Subject: Fixed aliasing pointer corruption in QDataStream. Use a union instead of an unsafe cast when swapping the bytes in the QDataStream streaming operators. The old seems to cause problems with Link Time Code Generation optimizations with the MSVC compilers. Task-number: 247708 Reviewed-by: Samuel Reviewed-by: Thiago BT: yes --- src/corelib/io/qdatastream.cpp | 92 +++++++++++++++++++++++++++++++++++------- 1 file changed, 77 insertions(+), 15 deletions(-) diff --git a/src/corelib/io/qdatastream.cpp b/src/corelib/io/qdatastream.cpp index b203899..e324ffe 100644 --- a/src/corelib/io/qdatastream.cpp +++ b/src/corelib/io/qdatastream.cpp @@ -622,11 +622,16 @@ QDataStream &QDataStream::operator>>(qint16 &i) setStatus(ReadPastEnd); } } else { - register uchar *p = (uchar *)(&i); + union { + qint16 val1; + char val2[2]; + } x; + char *p = x.val2; char b[2]; if (dev->read(b, 2) == 2) { *p++ = b[1]; *p = b[0]; + i = x.val1; } else { setStatus(ReadPastEnd); } @@ -660,13 +665,18 @@ QDataStream &QDataStream::operator>>(qint32 &i) setStatus(ReadPastEnd); } } else { // swap bytes - uchar *p = (uchar *)(&i); + union { + qint32 val1; + char val2[4]; + } x; + char *p = x.val2; char b[4]; if (dev->read(b, 4) == 4) { *p++ = b[3]; *p++ = b[2]; *p++ = b[1]; *p = b[0]; + i = x.val1; } else { setStatus(ReadPastEnd); } @@ -703,7 +713,12 @@ QDataStream &QDataStream::operator>>(qint64 &i) setStatus(ReadPastEnd); } } else { // swap bytes - uchar *p = (uchar *)(&i); + union { + qint64 val1; + char val2[8]; + } x; + + char *p = x.val2; char b[8]; if (dev->read(b, 8) == 8) { *p++ = b[7]; @@ -714,6 +729,7 @@ QDataStream &QDataStream::operator>>(qint64 &i) *p++ = b[2]; *p++ = b[1]; *p = b[0]; + i = x.val1; } else { setStatus(ReadPastEnd); } @@ -751,13 +767,19 @@ QDataStream &QDataStream::operator>>(float &f) setStatus(ReadPastEnd); } } else { // swap bytes - uchar *p = (uchar *)(&f); + union { + float val1; + char val2[4]; + } x; + + char *p = x.val2; char b[4]; if (dev->read(b, 4) == 4) { *p++ = b[3]; *p++ = b[2]; *p++ = b[1]; *p = b[0]; + f = x.val1; } else { setStatus(ReadPastEnd); } @@ -788,7 +810,11 @@ QDataStream &QDataStream::operator>>(double &f) setStatus(ReadPastEnd); } } else { // swap bytes - register uchar *p = (uchar *)(&f); + union { + double val1; + char val2[8]; + } x; + char *p = x.val2; char b[8]; if (dev->read(b, 8) == 8) { *p++ = b[7]; @@ -799,13 +825,18 @@ QDataStream &QDataStream::operator>>(double &f) *p++ = b[2]; *p++ = b[1]; *p = b[0]; + f = x.val1; } else { setStatus(ReadPastEnd); } } #else //non-standard floating point format - register uchar *p = (uchar *)(&f); + union { + double val1; + char val2[8]; + } x; + char *p = x.val2; char b[8]; if (dev->read(b, 8) == 8) { if (noswap) { @@ -827,6 +858,7 @@ QDataStream &QDataStream::operator>>(double &f) *p++ = b[Q_DF(1)]; *p = b[Q_DF(0)]; } + f = x.val1; } else { setStatus(ReadPastEnd); } @@ -970,7 +1002,12 @@ QDataStream &QDataStream::operator<<(qint16 i) if (noswap) { dev->write((char *)&i, sizeof(qint16)); } else { // swap bytes - register uchar *p = (uchar *)(&i); + union { + qint16 val1; + char val2[2]; + } x; + x.val1 = i; + char *p = x.val2; char b[2]; b[1] = *p++; b[0] = *p; @@ -992,7 +1029,12 @@ QDataStream &QDataStream::operator<<(qint32 i) if (noswap) { dev->write((char *)&i, sizeof(qint32)); } else { // swap bytes - register uchar *p = (uchar *)(&i); + union { + qint32 val1; + char val2[4]; + } x; + x.val1 = i; + char *p = x.val2; char b[4]; b[3] = *p++; b[2] = *p++; @@ -1022,13 +1064,18 @@ QDataStream &QDataStream::operator<<(qint64 i) { CHECK_STREAM_PRECOND(*this) if (version() < 6) { - quint32 i1 = i & 0xffffffff; - quint32 i2 = i >> 32; - *this << i2 << i1; + quint32 i1 = i & 0xffffffff; + quint32 i2 = i >> 32; + *this << i2 << i1; } else if (noswap) { // no conversion needed dev->write((char *)&i, sizeof(qint64)); } else { // swap bytes - register uchar *p = (uchar *)(&i); + union { + qint64 val1; + char val2[8]; + } x; + x.val1 = i; + char *p = x.val2; char b[8]; b[7] = *p++; b[6] = *p++; @@ -1077,7 +1124,12 @@ QDataStream &QDataStream::operator<<(float f) if (noswap) { // no conversion needed dev->write((char *)&g, sizeof(float)); } else { // swap bytes - register uchar *p = (uchar *)(&g); + union { + float val1; + char val2[4]; + } x; + x.val1 = f; + char *p = x.val2; char b[4]; b[3] = *p++; b[2] = *p++; @@ -1103,7 +1155,12 @@ QDataStream &QDataStream::operator<<(double f) if (noswap) { dev->write((char *)&f, sizeof(double)); } else { - register uchar *p = (uchar *)(&f); + union { + double val1; + char val2[8]; + } x; + x.val1 = f; + char *p = x.val2; char b[8]; b[7] = *p++; b[6] = *p++; @@ -1116,7 +1173,12 @@ QDataStream &QDataStream::operator<<(double f) dev->write(b, 8); } #else - register uchar *p = (uchar *)(&f); + union { + double val1; + char val2[8]; + } x; + x.val1 = f; + char *p = x.val2; char b[8]; if (noswap) { b[Q_DF(0)] = *p++; -- cgit v0.12 From 76cea46fdbd8145a484bd4bde7c2e6edd55cf2ac Mon Sep 17 00:00:00 2001 From: Erik Verbruggen Date: Wed, 27 May 2009 11:30:56 +0200 Subject: Fixed a bug where the DOM reported the value of an ID to be Invalid. --- src/declarative/qml/qmldom.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/qml/qmldom.cpp b/src/declarative/qml/qmldom.cpp index b689ec5..38436b4 100644 --- a/src/declarative/qml/qmldom.cpp +++ b/src/declarative/qml/qmldom.cpp @@ -1170,7 +1170,7 @@ QmlDomValue::Type QmlDomValue::type() const case QmlParser::Value::SignalExpression: return Literal; case QmlParser::Value::Id: - return Invalid; + return Literal; } return Invalid; } -- cgit v0.12 From cfdfdf079c4a2095c588dd8af8403c74d2cfa37a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 27 May 2009 09:44:14 +0200 Subject: Optimized QRasterPixmapData::metric. Avoid needless DPI calculations when not needed, and simplify the DPI calculations to the point where most of the operations disappear. Also avoid calling QImage::metric() so that we don't need to go through two switch statements and an extra function call just to get the width of a pixmap. Reviewed-by: Trond --- src/gui/image/qpixmap_raster.cpp | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/src/gui/image/qpixmap_raster.cpp b/src/gui/image/qpixmap_raster.cpp index b5556cd..29e4f3f 100644 --- a/src/gui/image/qpixmap_raster.cpp +++ b/src/gui/image/qpixmap_raster.cpp @@ -322,25 +322,36 @@ extern int qt_defaultDpiY(); int QRasterPixmapData::metric(QPaintDevice::PaintDeviceMetric metric) const { + QImageData *d = image.d; + if (!d) + return 0; + // override the image dpi with the screen dpi when rendering to a pixmap - const int dpmX = qRound(qt_defaultDpiX() * 100 / qreal(2.54)); - const int dpmY = qRound(qt_defaultDpiY() * 100 / qreal(2.54)); switch (metric) { + case QPaintDevice::PdmWidth: + return d->width; + case QPaintDevice::PdmHeight: + return d->height; case QPaintDevice::PdmWidthMM: - return qRound(image.width() * 1000 / dpmX); + return qRound(d->width * 25.4 / qt_defaultDpiX()); case QPaintDevice::PdmHeightMM: - return qRound(image.height() * 1000 / dpmY); - case QPaintDevice::PdmDpiX: - return qRound(dpmX * qreal(0.0254)); - case QPaintDevice::PdmDpiY: - return qRound(dpmY * qreal(0.0254)); + return qRound(d->width * 25.4 / qt_defaultDpiY()); + case QPaintDevice::PdmNumColors: + return d->colortable.size(); + case QPaintDevice::PdmDepth: + return d->depth; + case QPaintDevice::PdmDpiX: // fall-through case QPaintDevice::PdmPhysicalDpiX: - return qRound(dpmX * qreal(0.0254)); + return qt_defaultDpiX(); + case QPaintDevice::PdmDpiY: // fall-through case QPaintDevice::PdmPhysicalDpiY: - return qRound(dpmY * qreal(0.0254)); + return qt_defaultDpiY(); default: - return image.metric(metric); + qWarning("QRasterPixmapData::metric(): Unhandled metric type %d", metric); + break; } + + return 0; } QImage* QRasterPixmapData::buffer() -- cgit v0.12 From c8f180e7023308b8a051b53943b9a088a7f0c427 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 27 May 2009 20:40:28 +1000 Subject: Small cleanups --- src/declarative/qml/qmlcompiler.cpp | 175 +++++++++++++++----------------- src/declarative/qml/qmlcompiler_p.h | 26 ++++- src/declarative/qml/qmlscriptparser.cpp | 34 +++++-- src/declarative/qml/qmlscriptparser_p.h | 2 + 4 files changed, 132 insertions(+), 105 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 09f4e0b..b9a848a 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -62,6 +62,7 @@ #include "private/qmlcustomparser_p_p.h" #include #include +#include "parser/javascriptast_p.h" #include "qmlscriptparser_p.h" @@ -516,6 +517,7 @@ bool QmlCompiler::compile(QmlEngine *engine, } output = 0; + return !isError(); } @@ -542,7 +544,7 @@ void QmlCompiler::compileTree(Object *tree) def.type = QmlInstruction::SetDefault; output->bytecode << def; - optimizeExpressions(0, output->bytecode.count() - 1, 0); + finalizeComponent(0); } bool QmlCompiler::compileObject(Object *obj, int ctxt) @@ -588,6 +590,8 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) begin.begin.castValue = parserStatusCast; begin.line = obj->location.start.line; output->bytecode << begin; + + compileState.parserStatusCount++; } // Check if this is a custom parser type. Custom parser types allow @@ -688,9 +692,14 @@ bool QmlCompiler::compileComponent(Object *obj, int ctxt) if (!isValidId(val)) COMPILE_EXCEPTION("Invalid id property value"); - if (ids.contains(val)) + if (compileState.ids.contains(val)) COMPILE_EXCEPTION("id is not unique"); - ids.insert(val); + + IdReference reference; + reference.id = val; + reference.object = obj; + reference.instructionIdx = output->bytecode.count(); + compileState.ids.insert(val, reference); int pref = output->indexForString(val); QmlInstruction id; @@ -699,8 +708,6 @@ bool QmlCompiler::compileComponent(Object *obj, int ctxt) id.setId.value = pref; id.setId.save = -1; - savedTypes.insert(output->bytecode.count(), -1); - output->bytecode << id; } @@ -724,16 +731,16 @@ bool QmlCompiler::compileComponentFromRoot(Object *obj, int ctxt) init.line = obj->location.start.line; output->bytecode << init; - QSet oldIds = ids; - ids.clear(); + ComponentCompileState oldComponentCompileState = compileState; + compileState = ComponentCompileState(); if (obj) COMPILE_CHECK(compileObject(obj, ctxt)); create.createComponent.count = output->bytecode.count() - count; - int inc = optimizeExpressions(count, count - 1 + create.createComponent.count, count); + int inc = finalizeComponent(count); create.createComponent.count += inc; - ids = oldIds; + compileState = oldComponentCompileState; return true; } @@ -950,41 +957,43 @@ bool QmlCompiler::compileIdProperty(QmlParser::Property *prop, if (prop->values.count() > 1) COMPILE_EXCEPTION2(prop, "The object id may only be set once"); - if (prop->values.count() == 1) { - if (prop->values.at(0)->object) - COMPILE_EXCEPTION("Cannot assign an object as an id"); - QString val = prop->values.at(0)->primitive(); - if (!isValidId(val)) - COMPILE_EXCEPTION(val << "is not a valid id"); - if (ids.contains(val)) - COMPILE_EXCEPTION("id is not unique"); - ids.insert(val); + if (prop->values.at(0)->object) + COMPILE_EXCEPTION("Cannot assign an object as an id"); + QString val = prop->values.at(0)->primitive(); + if (!isValidId(val)) + COMPILE_EXCEPTION(val << "is not a valid id"); + if (compileState.ids.contains(val)) + COMPILE_EXCEPTION("id is not unique"); - int pref = output->indexForString(val); + int pref = output->indexForString(val); - if (prop->type == QVariant::String) { - QmlInstruction assign; - assign.type = QmlInstruction::StoreString; - assign.storeString.propertyIndex = prop->index; - assign.storeString.value = pref; - assign.line = prop->values.at(0)->location.start.line; - output->bytecode << assign; + if (prop->type == QVariant::String) { + QmlInstruction assign; + assign.type = QmlInstruction::StoreString; + assign.storeString.propertyIndex = prop->index; + assign.storeString.value = pref; + assign.line = prop->values.at(0)->location.start.line; + output->bytecode << assign; - prop->values.at(0)->type = Value::Id; - } else { - prop->values.at(0)->type = Value::Literal; - } + prop->values.at(0)->type = Value::Id; + } else { + prop->values.at(0)->type = Value::Literal; + } - QmlInstruction id; - id.type = QmlInstruction::SetId; - id.line = prop->values.at(0)->location.start.line; - id.setId.value = pref; - id.setId.save = -1; - savedTypes.insert(output->bytecode.count(), obj->type); - output->bytecode << id; + IdReference reference; + reference.id = val; + reference.object = obj; + reference.instructionIdx = output->bytecode.count(); + compileState.ids.insert(val, reference); - obj->id = val.toLatin1(); - } + QmlInstruction id; + id.type = QmlInstruction::SetId; + id.line = prop->values.at(0)->location.start.line; + id.setId.value = pref; + id.setId.save = -1; + output->bytecode << id; + + obj->id = val.toLatin1(); return true; } @@ -1116,7 +1125,7 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, COMPILE_EXCEPTION("Can only assign one binding to lists"); assignedBinding = true; - COMPILE_CHECK(compileBinding(v->value.asScript(), prop, ctxt, + COMPILE_CHECK(compileBinding(v->value, prop, ctxt, obj->metaObject(), v->location.start.line)); v->type = Value::PropertyBinding; @@ -1287,7 +1296,7 @@ bool QmlCompiler::compilePropertyLiteralAssignment(QmlParser::Property *prop, if (v->value.isScript()) { - COMPILE_CHECK(compileBinding(v->value.asScript(), prop, ctxt, + COMPILE_CHECK(compileBinding(v->value, prop, ctxt, obj->metaObject(), v->location.start.line)); @@ -1394,7 +1403,8 @@ bool QmlCompiler::compileDynamicMeta(QmlParser::Object *obj) return true; } -bool QmlCompiler::compileBinding(const QString &bind, QmlParser::Property *prop, +bool QmlCompiler::compileBinding(const QmlParser::Variant &bind, + QmlParser::Property *prop, int ctxt, const QMetaObject *mo, qint64 line) { Q_ASSERT(mo); @@ -1405,13 +1415,13 @@ bool QmlCompiler::compileBinding(const QString &bind, QmlParser::Property *prop, COMPILE_EXCEPTION2(prop, "Cannot assign binding to read-only property"); QmlBasicScript bs; - bs.compile(bind.toLatin1()); + bs.compile(bind.asScript().toLatin1()); int bref; if (bs.isValid()) { bref = output->indexForByteArray(QByteArray(bs.compileData(), bs.compileDataSize())); } else { - bref = output->indexForString(bind); + bref = output->indexForString(bind.asScript()); } QmlInstruction assign; @@ -1426,49 +1436,28 @@ bool QmlCompiler::compileBinding(const QString &bind, QmlParser::Property *prop, assign.assignBinding.property = prop->index; assign.assignBinding.value = bref; assign.assignBinding.category = QmlMetaProperty::propertyCategory(mp); - savedTypes.insert(output->bytecode.count(), prop->type); + BindingReference reference; + reference.expression = bind; + reference.property = prop; + reference.instructionIdx = output->bytecode.count(); + compileState.bindings << reference; + output->bytecode << assign; return true; } -int QmlCompiler::optimizeExpressions(int start, int end, int patch) +// Update the init instruction with final data, and optimize some simple +// bindings +int QmlCompiler::finalizeComponent(int patch) { - QHash ids; int saveCount = 0; int newInstrs = 0; - int bindingsCount = 0; - int parserStatusCount = 0; - for (int ii = start; ii <= end; ++ii) { - const QmlInstruction &instr = output->bytecode.at(ii); - - if (instr.type == QmlInstruction::CreateComponent) { - ii += instr.createComponent.count - 1; - continue; - } - - if (instr.type == QmlInstruction::SetId) { - QString id = output->primitives.at(instr.setId.value); - ids.insert(id, ii); - } - } - - for (int ii = start; ii <= end; ++ii) { - const QmlInstruction &instr = output->bytecode.at(ii); - - if (instr.type == QmlInstruction::CreateComponent) { - ii += instr.createComponent.count - 1; - continue; - } - - if (instr.type == QmlInstruction::StoreBinding || - instr.type == QmlInstruction::StoreCompiledBinding) { - ++bindingsCount; - } else if (instr.type == QmlInstruction::BeginObject) { - ++parserStatusCount; - } + for (int ii = 0; ii < compileState.bindings.count(); ++ii) { + const BindingReference &binding = compileState.bindings.at(ii); + QmlInstruction &instr = output->bytecode[binding.instructionIdx]; if (instr.type == QmlInstruction::StoreCompiledBinding) { QmlBasicScript s(output->datas.at(instr.assignBinding.value).constData()); @@ -1478,16 +1467,17 @@ int QmlCompiler::optimizeExpressions(int start, int end, int patch) if (!slt.at(0).isUpper()) continue; - if (ids.contains(slt) && + if (compileState.ids.contains(slt) && instr.assignBinding.category == QmlMetaProperty::Object) { - int id = ids[slt]; - int idType = savedTypes.value(id); - int storeType = savedTypes.value(ii); + IdReference reference = + compileState.ids[slt]; + + const QMetaObject *idMo = reference.object->metaObject(); + const QMetaObject *storeMo = QmlMetaType::rawMetaObjectForType(binding.property->type); - const QMetaObject *idMo = (idType == -1)?&QmlComponent::staticMetaObject:output->types.at(idType).metaObject(); - const QMetaObject *storeMo = - QmlMetaType::rawMetaObjectForType(storeType); + Q_ASSERT(idMo); + Q_ASSERT(storeMo); bool canAssign = false; while (!canAssign && idMo) { @@ -1502,19 +1492,19 @@ int QmlCompiler::optimizeExpressions(int start, int end, int patch) int saveId = -1; - if (output->bytecode.at(id).setId.save != -1) { - saveId = output->bytecode.at(id).setId.save; + int instructionIdx = reference.instructionIdx; + if (output->bytecode.at(instructionIdx).setId.save != -1) { + saveId = output->bytecode.at(instructionIdx).setId.save; } else { - output->bytecode[id].setId.save = saveCount; + output->bytecode[instructionIdx].setId.save = saveCount; saveId = saveCount; ++saveCount; } int prop = instr.assignBinding.property; - QmlInstruction &rwinstr = output->bytecode[ii]; - rwinstr.type = QmlInstruction::PushProperty; - rwinstr.pushProperty.property = prop; + instr.type = QmlInstruction::PushProperty; + instr.pushProperty.property = prop; QmlInstruction instr; instr.type = QmlInstruction::StoreStackObject; @@ -1529,8 +1519,9 @@ int QmlCompiler::optimizeExpressions(int start, int end, int patch) } output->bytecode[patch].init.dataSize = saveCount; - output->bytecode[patch].init.bindingsSize = bindingsCount; - output->bytecode[patch].init.parserStatusSize = parserStatusCount;; + output->bytecode[patch].init.bindingsSize = compileState.bindings.count(); + output->bytecode[patch].init.parserStatusSize = + compileState.parserStatusCount; return newInstrs; } diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index 6e9bafb..b1963da 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -158,13 +158,31 @@ private: QmlParser::Value *value); bool compileDynamicMeta(QmlParser::Object *obj); - bool compileBinding(const QString &, QmlParser::Property *prop, + bool compileBinding(const QmlParser::Variant &, QmlParser::Property *prop, int ctxt, const QMetaObject *, qint64); - int optimizeExpressions(int start, int end, int patch = -1); + int finalizeComponent(int patch); - QSet ids; - QHash savedTypes; + struct IdReference { + QString id; + QmlParser::Object *object; + int instructionIdx; + }; + + struct BindingReference { + QmlParser::Variant expression; + QmlParser::Property *property; + int instructionIdx; + }; + + struct ComponentCompileState + { + ComponentCompileState() : parserStatusCount(0) {} + QHash ids; + int parserStatusCount; + QList bindings; + }; + ComponentCompileState compileState; QList exceptions; QmlCompiledData *output; diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index b862953..b1ffc98 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -597,7 +597,7 @@ QmlParser::Variant ProcessAST::getVariant(AST::ExpressionNode *expr) } } - return QmlParser::Variant(asString(expr), expr); + return QmlParser::Variant(asString(expr), expr); } } @@ -716,33 +716,44 @@ bool ProcessAST::visit(AST::UiSourceElement *node) QmlScriptParser::QmlScriptParser() -: root(0) +: root(0), data(0) { } QmlScriptParser::~QmlScriptParser() { + clear(); } -bool QmlScriptParser::parse(const QByteArray &data, const QUrl &url) +class QmlScriptParserJsASTData +{ +public: + QmlScriptParserJsASTData(const QString &filename) + : nodePool(filename, &engine) {} + + Engine engine; + NodePool nodePool; +}; + +bool QmlScriptParser::parse(const QByteArray &qmldata, const QUrl &url) { #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer pt; #endif + clear(); + const QString fileName = url.toString(); - QTextStream stream(data, QIODevice::ReadOnly); + QTextStream stream(qmldata, QIODevice::ReadOnly); const QString code = stream.readAll(); - Engine engine; - - NodePool nodePool(fileName, &engine); + data = new QmlScriptParserJsASTData(fileName); - Lexer lexer(&engine); + Lexer lexer(&data->engine); lexer.setCode(code, /*line = */ 1); - Parser parser(&engine); + Parser parser(&data->engine); if (! parser.parse() || !_errors.isEmpty()) { @@ -808,6 +819,11 @@ void QmlScriptParser::clear() _nameSpacePaths.clear(); _typeNames.clear(); _errors.clear(); + + if (data) { + delete data; + data = 0; + } } int QmlScriptParser::findOrCreateTypeId(const QString &name) diff --git a/src/declarative/qml/qmlscriptparser_p.h b/src/declarative/qml/qmlscriptparser_p.h index a9ffa47..3993194 100644 --- a/src/declarative/qml/qmlscriptparser_p.h +++ b/src/declarative/qml/qmlscriptparser_p.h @@ -54,6 +54,7 @@ QT_MODULE(Declarative) class QByteArray; +class QmlScriptParserJsASTData; class QmlScriptParser { public: @@ -98,6 +99,7 @@ public: QList _imports; QStringList _typeNames; QString _scriptFile; + QmlScriptParserJsASTData *data; }; QT_END_NAMESPACE -- cgit v0.12 From 15c8f565973592c9929cdd6fc83d61641aa63afa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Mon, 25 May 2009 14:56:27 +0200 Subject: Fixed bugs in GL2 paint engine when several engines are active. Make sure makeCurrent() on a window surface unbinds any active FBO, and simplify ensureActive() code in GL2 paint engine a bit. We don't need the last_engine pointer as ensureActive() will take care of ensuring the correct engine is active anway. --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 46 ++++++++-------------- src/opengl/qgl.cpp | 15 +++++++ src/opengl/qgl_p.h | 1 + src/opengl/qglframebufferobject.cpp | 12 ++++-- 4 files changed, 41 insertions(+), 33 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index f174306..a7c7426 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -175,8 +175,6 @@ public: void updateDepthClip(); void systemStateChanged(); uint use_system_clip : 1; - - QPaintEngine *last_engine; }; @@ -830,10 +828,11 @@ void QGL2PaintEngineEx::stroke(const QVectorPath &path, const QPen &pen) { Q_D(QGL2PaintEngineEx); - ensureActive(); if (pen.style() == Qt::NoPen) return; + ensureActive(); + if ( (pen.isCosmetic() && (pen.style() == Qt::SolidLine)) && (pen.widthF() < 2.5f) ) { // We only handle solid, cosmetic pens with a width of 1 pixel @@ -1051,10 +1050,19 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) Q_D(QGL2PaintEngineEx); // qDebug("QGL2PaintEngineEx::begin()"); - d->drawable.setDevice(pdev); - d->drawable.makeCurrent(); d->ctx = d->drawable.context(); + + if (d->ctx->d_ptr->active_engine) { + QGL2PaintEngineEx *engine = static_cast(d->ctx->d_ptr->active_engine); + QGL2PaintEngineExPrivate *p = static_cast(engine->d_ptr); + p->transferMode(BrushDrawingMode); + p->drawable.doneCurrent(); + } + + d->ctx->d_ptr->active_engine = this; + + d->drawable.makeCurrent(); QSize sz = d->drawable.size(); d->width = sz.width(); d->height = sz.height(); @@ -1064,14 +1072,6 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) qt_resolve_version_2_0_functions(d->ctx); #endif - d->last_engine = d->ctx->d_ptr->active_engine; - d->ctx->d_ptr->active_engine = this; - - if (d->last_engine) { - QGL2PaintEngineEx *engine = static_cast(d->last_engine); - static_cast(engine->d_ptr)->transferMode(BrushDrawingMode); - } - if (!d->shaderManager) d->shaderManager = new QGLEngineShaderManager(d->ctx); @@ -1115,8 +1115,8 @@ bool QGL2PaintEngineEx::end() Q_D(QGL2PaintEngineEx); QGLContext *ctx = d->ctx; if (ctx->d_ptr->active_engine != this) { - QGL2PaintEngineEx *engine = static_cast(d->last_engine); - if (engine) { + QGL2PaintEngineEx *engine = static_cast(ctx->d_ptr->active_engine); + if (engine && engine->isActive()) { QGL2PaintEngineExPrivate *p = static_cast(engine->d_ptr); p->transferMode(BrushDrawingMode); p->drawable.doneCurrent(); @@ -1128,19 +1128,7 @@ bool QGL2PaintEngineEx::end() d->transferMode(BrushDrawingMode); d->drawable.swapBuffers(); d->drawable.doneCurrent(); - d->ctx->d_ptr->active_engine = d->last_engine; - - if (d->last_engine) { - QGL2PaintEngineEx *engine = static_cast(d->last_engine); - QGL2PaintEngineExPrivate *p = static_cast(engine->d_ptr); - - glDisable(GL_DEPTH_TEST); - glDisable(GL_SCISSOR_TEST); - - glViewport(0, 0, p->width, p->height); - engine->setState(engine->state()); - p->updateDepthClip(); - } + d->ctx->d_ptr->active_engine = 0; return false; } @@ -1152,7 +1140,7 @@ void QGL2PaintEngineEx::ensureActive() if (isActive() && ctx->d_ptr->active_engine != this) { QGL2PaintEngineEx *engine = static_cast(ctx->d_ptr->active_engine); - if (engine) { + if (engine && engine->isActive()) { QGL2PaintEngineExPrivate *p = static_cast(engine->d_ptr); p->transferMode(BrushDrawingMode); p->drawable.doneCurrent(); diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 0a2a196..62a592a 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -4391,6 +4391,15 @@ void QGLDrawable::swapBuffers() void QGLDrawable::makeCurrent() { + previous_fbo = 0; + if (!pixmapData && !fbo) { + QGLContext *ctx = context(); + previous_fbo = ctx->d_ptr->current_fbo; + ctx->d_ptr->current_fbo = 0; + if (previous_fbo) + glBindFramebuffer(GL_FRAMEBUFFER_EXT, 0); + } + if (widget) widget->makeCurrent(); #if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) @@ -4428,6 +4437,12 @@ void QGLDrawable::doneCurrent() } #endif + if (previous_fbo) { + QGLContext *ctx = context(); + ctx->d_ptr->current_fbo = previous_fbo; + glBindFramebuffer(GL_FRAMEBUFFER_EXT, previous_fbo); + } + if (fbo && !wasBound) fbo->release(); } diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index b421eee..9657416 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -333,6 +333,7 @@ private: #if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) QGLPixmapData *pixmapData; #endif + int previous_fbo; }; // GL extension definitions diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 338ce1f..3e7ca0a 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -804,8 +804,10 @@ bool QGLFramebufferObject::bind() const QGLContext *context = QGLContext::currentContext(); if (d->valid && context) { // Save the previous setting to automatically restore in release(). - d->previous_fbo = context->d_ptr->current_fbo; - context->d_ptr->current_fbo = d->fbo; + if (context->d_ptr->current_fbo != d->fbo) { + d->previous_fbo = context->d_ptr->current_fbo; + context->d_ptr->current_fbo = d->fbo; + } } return d->valid; } @@ -834,8 +836,10 @@ bool QGLFramebufferObject::release() const QGLContext *context = QGLContext::currentContext(); if (context) { // Restore the previous setting for stacked framebuffer objects. - context->d_ptr->current_fbo = d->previous_fbo; - glBindFramebuffer(GL_FRAMEBUFFER_EXT, d->previous_fbo); + if (d->previous_fbo != context->d_ptr->current_fbo) { + context->d_ptr->current_fbo = d->previous_fbo; + glBindFramebuffer(GL_FRAMEBUFFER_EXT, d->previous_fbo); + } d->previous_fbo = 0; } -- cgit v0.12 From 855022d6108f6b3c90832e742217c50550af717d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 26 May 2009 10:58:30 +0200 Subject: Avoided expensive image upload for GL pixmap backend for QPixmap::fill. In the fill case we can simply set a flag saying the pixmap needs to be filled, and then when painting on the pixmap we start by filling the background using glClear via the existing QGLDrawable::autoFillBackground interface. --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 8 +++- src/opengl/qgl.cpp | 4 ++ src/opengl/qpixmapdata_gl.cpp | 46 +++++++++++++++++----- src/opengl/qpixmapdata_gl_p.h | 12 +++++- 4 files changed, 59 insertions(+), 11 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index a7c7426..aafa6de 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1095,7 +1095,13 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) glDisable(GL_SCISSOR_TEST); QGLPixmapData *source = d->drawable.copyOnBegin(); - if (source) { + if (d->drawable.autoFillBackground()) { + QColor color = d->drawable.backgroundColor(); + + float alpha = color.alphaF(); + glClearColor(color.redF() * alpha, color.greenF() * alpha, color.blueF() * alpha, alpha); + glClear(GL_COLOR_BUFFER_BIT); + } else if (source) { d->transferMode(ImageDrawingMode); source->bind(false); diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 62a592a..0be70d7 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -4525,6 +4525,8 @@ QColor QGLDrawable::backgroundColor() const { if (widget) return widget->palette().brush(widget->backgroundRole()).color(); + else if (pixmapData) + return pixmapData->fillColor(); return QApplication::palette().brush(QPalette::Background).color(); } @@ -4547,6 +4549,8 @@ bool QGLDrawable::autoFillBackground() const { if (widget) return widget->autoFillBackground(); + else if (pixmapData) + return pixmapData->needsFill(); else return false; } diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index c89b99b..85bcda5 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -103,6 +103,7 @@ QGLPixmapData::QGLPixmapData(PixelType type) , m_engine(0) , m_ctx(0) , m_dirty(false) + , m_hasFillColor(false) { setSerialNumber(++qt_gl_pixmap_serial); } @@ -196,6 +197,13 @@ void QGLPixmapData::fromImage(const QImage &image, resize(image.width(), image.height()); m_source = image; m_dirty = true; + m_hasFillColor = false; + + if (m_textureId) { + QGLShareContextScope ctx(qt_gl_share_widget()->context()); + glDeleteTextures(1, &m_textureId); + m_textureId = 0; + } } bool QGLPixmapData::scroll(int dx, int dy, const QRect &rect) @@ -222,7 +230,11 @@ void QGLPixmapData::fill(const QColor &color) if (!isValid()) return; - if (!m_source.isNull()) { + if (useFramebufferObjects()) { + m_source = QImage(); + m_hasFillColor = true; + m_fillColor = color; + } else if (!m_source.isNull()) { m_source.fill(PREMUL(color.rgba())); } else { // ## TODO: improve performance here @@ -243,14 +255,18 @@ QImage QGLPixmapData::toImage() const if (!isValid()) return QImage(); - if (m_renderFbo) + if (m_renderFbo) { copyBackFromRenderFbo(true); - else if (!m_source.isNull()) + } else if (!m_source.isNull()) { return m_source; - else if (m_dirty) - return QImage(m_width, m_height, QImage::Format_ARGB32_Premultiplied); - else + } else if (m_dirty || m_hasFillColor) { + QImage img(m_width, m_height, QImage::Format_ARGB32_Premultiplied); + if (m_hasFillColor) + img.fill(PREMUL(m_fillColor.rgba())); + return img; + } else { ensureCreated(); + } QGLShareContextScope ctx(qt_gl_share_widget()->context()); extern QImage qt_gl_read_texture(const QSize &size, bool alpha_format, bool include_alpha); @@ -272,6 +288,8 @@ void QGLPixmapData::copyBackFromRenderFbo(bool keepCurrentFboBound) const if (!isValid()) return; + m_hasFillColor = false; + const QGLContext *share_ctx = qt_gl_share_widget()->context(); QGLShareContextScope ctx(share_ctx); @@ -356,9 +374,12 @@ QPaintEngine* QGLPixmapData::paintEngine() const return m_engine; else if (!useFramebufferObjects()) { m_dirty = true; - if (m_source.size() != size()) m_source = QImage(size(), QImage::Format_ARGB32_Premultiplied); + if (m_hasFillColor) { + m_source.fill(PREMUL(m_fillColor.rgba())); + m_hasFillColor = false; + } return m_source.paintEngine(); } @@ -394,10 +415,17 @@ QPaintEngine* QGLPixmapData::paintEngine() const GLuint QGLPixmapData::bind(bool copyBack) const { - if (m_renderFbo && copyBack) + if (m_renderFbo && copyBack) { copyBackFromRenderFbo(true); - else + } else { + if (m_hasFillColor) { + m_dirty = true; + m_source = QImage(m_width, m_height, QImage::Format_ARGB32_Premultiplied); + m_source.fill(PREMUL(m_fillColor.rgba())); + m_hasFillColor = false; + } ensureCreated(); + } GLuint id = m_textureId; glBindTexture(GL_TEXTURE_2D, id); diff --git a/src/opengl/qpixmapdata_gl_p.h b/src/opengl/qpixmapdata_gl_p.h index 7e06db9..1b6b7ae 100644 --- a/src/opengl/qpixmapdata_gl_p.h +++ b/src/opengl/qpixmapdata_gl_p.h @@ -91,6 +91,9 @@ public: bool isUninitialized() const { return m_dirty && m_source.isNull(); } + bool needsFill() const { return m_hasFillColor; } + QColor fillColor() const { return m_fillColor; } + QSize size() const { return QSize(m_width, m_height); } int width() const { return m_width; } int height() const { return m_height; } @@ -119,8 +122,15 @@ private: mutable GLuint m_textureId; mutable QPaintEngine *m_engine; mutable QGLContext *m_ctx; - mutable bool m_dirty; mutable QImage m_source; + + // the texture is not in sync with the source image + mutable bool m_dirty; + + // fill has been called and no painting has been done, so the pixmap is + // represented by a single fill color + mutable QColor m_fillColor; + mutable bool m_hasFillColor; }; QT_END_NAMESPACE -- cgit v0.12 From 73e7d0cbed0261715f534d95f81055bf97ce4314 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 27 May 2009 11:45:52 +0200 Subject: Make WA_TranslucentBackground work on QGLWidget for X11 This patch enables QGLWidget's to have an ARGB visual on X11, alowing GL rendering on semi-transparent windows. Reviewed-By: Trond --- src/gui/kernel/qwidget_x11.cpp | 31 ++++-- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 10 ++ src/opengl/qgl.cpp | 2 +- src/opengl/qgl_x11.cpp | 116 ++++++++++++++++++++- src/opengl/qpaintengine_opengl.cpp | 2 +- 5 files changed, 146 insertions(+), 15 deletions(-) diff --git a/src/gui/kernel/qwidget_x11.cpp b/src/gui/kernel/qwidget_x11.cpp index b35740a..7e41ea1 100644 --- a/src/gui/kernel/qwidget_x11.cpp +++ b/src/gui/kernel/qwidget_x11.cpp @@ -893,15 +893,28 @@ void QWidgetPrivate::x11UpdateIsOpaque() int screen = xinfo.screen(); if (topLevel && X11->use_xrender && X11->argbVisuals[screen] && xinfo.depth() != 32) { - // recreate widget - QPoint pos = q->pos(); - bool visible = q->isVisible(); - if (visible) - q->hide(); - q->setParent(q->parentWidget(), q->windowFlags()); - q->move(pos); - if (visible) - q->show(); + + if (q->inherits("QGLWidget")) { + // We send QGLWidgets a ParentChange event which causes them to + // recreate their GL context, which in turn causes them to choose + // their visual again. Now that WA_TranslucentBackground is set, + // QGLContext::chooseVisual will select an ARGB visual. + QEvent e(QEvent::ParentChange); + QApplication::sendEvent(q, &e); + } + else { + // For regular widgets, reparent them with their parent which + // also triggers a recreation of the native window + QPoint pos = q->pos(); + bool visible = q->isVisible(); + if (visible) + q->hide(); + + q->setParent(q->parentWidget(), q->windowFlags()); + q->move(pos); + if (visible) + q->show(); + } } #endif } diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index aafa6de..5c8b364 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1083,6 +1083,16 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) // qDebug("You should see green now"); // sleep(5); + const QColor &c = d->drawable.backgroundColor(); + glClearColor(c.redF(), c.greenF(), c.blueF(), d->drawable.format().alpha() ? c.alphaF() : 1.0); + if (d->drawable.context()->d_func()->clear_on_painter_begin && d->drawable.autoFillBackground()) { + GLbitfield clearBits = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT; +#ifndef QT_OPENGL_ES + clearBits |= GL_ACCUM_BUFFER_BIT; +#endif + glClear(clearBits); + } + d->brushTextureDirty = true; d->brushUniformsDirty = true; d->matrixDirty = true; diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 0be70d7..9626a3d 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -3306,7 +3306,7 @@ bool QGLWidget::event(QEvent *e) glFinish(); doneCurrent(); } else if (e->type() == QEvent::ParentChange) { - if (d->glcx->d_func()->screen != d->xinfo.screen()) { + if (d->glcx->d_func()->screen != d->xinfo.screen() || testAttribute(Qt::WA_TranslucentBackground)) { setContext(new QGLContext(d->glcx->requestedFormat(), this)); // ### recreating the overlay isn't supported atm } diff --git a/src/opengl/qgl_x11.cpp b/src/opengl/qgl_x11.cpp index 28c34de..aba1e5c 100644 --- a/src/opengl/qgl_x11.cpp +++ b/src/opengl/qgl_x11.cpp @@ -533,11 +533,22 @@ void *QGLContext::chooseVisual() void *QGLContext::tryVisual(const QGLFormat& f, int bufDepth) { Q_D(QGLContext); - int spec[40]; + int spec[45]; int i = 0; spec[i++] = GLX_LEVEL; spec[i++] = f.plane(); const QX11Info *xinfo = qt_x11Info(d->paintDevice); + bool useFBConfig = false; + +#if defined(GLX_VERSION_1_3) && !defined(QT_NO_XRENDER) + QWidget* widget = 0; + if (d->paintDevice->devType() == QInternal::Widget) + widget = static_cast(d->paintDevice); + + // Only use glXChooseFBConfig for widgets if we're trying to get an ARGB visual + if (widget && widget->testAttribute(Qt::WA_TranslucentBackground) && X11->use_xrender) + useFBConfig = true; +#endif #if defined(GLX_VERSION_1_1) && defined(GLX_EXT_visual_info) static bool useTranspExt = false; @@ -565,28 +576,41 @@ void *QGLContext::tryVisual(const QGLFormat& f, int bufDepth) useTranspExtChecked = true; } - if (f.plane() && useTranspExt) { + if (f.plane() && useTranspExt && !useFBConfig) { // Required to avoid non-transparent overlay visual(!) on some systems spec[i++] = GLX_TRANSPARENT_TYPE_EXT; spec[i++] = f.rgba() ? GLX_TRANSPARENT_RGB_EXT : GLX_TRANSPARENT_INDEX_EXT; } #endif +#if defined(GLX_VERSION_1_3) + // GLX_RENDER_TYPE is only in glx >=1.3 + if (useFBConfig) { + spec[i++] = GLX_RENDER_TYPE; + spec[i++] = f.rgba() ? GLX_RGBA_BIT : GLX_COLOR_INDEX_BIT; + } +#endif + if (f.doubleBuffer()) spec[i++] = GLX_DOUBLEBUFFER; + if (useFBConfig) + spec[i++] = True; if (f.depth()) { spec[i++] = GLX_DEPTH_SIZE; spec[i++] = f.depthBufferSize() == -1 ? 1 : f.depthBufferSize(); } if (f.stereo()) { spec[i++] = GLX_STEREO; + if (useFBConfig) + spec[i++] = True; } if (f.stencil()) { spec[i++] = GLX_STENCIL_SIZE; spec[i++] = f.stencilBufferSize() == -1 ? 1 : f.stencilBufferSize(); } if (f.rgba()) { - spec[i++] = GLX_RGBA; + if (!useFBConfig) + spec[i++] = GLX_RGBA; spec[i++] = GLX_RED_SIZE; spec[i++] = f.redBufferSize() == -1 ? 1 : f.redBufferSize(); spec[i++] = GLX_GREEN_SIZE; @@ -621,8 +645,86 @@ void *QGLContext::tryVisual(const QGLFormat& f, int bufDepth) spec[i++] = f.samples() == -1 ? 4 : f.samples(); } +#if defined(GLX_VERSION_1_3) + if (useFBConfig) { + spec[i++] = GLX_DRAWABLE_TYPE; + switch(d->paintDevice->devType()) { + case QInternal::Pixmap: + spec[i++] = GLX_PIXMAP_BIT; + break; + case QInternal::Pbuffer: + spec[i++] = GLX_PBUFFER_BIT; + break; + default: + qWarning("QGLContext: Unknown paint device type %d", d->paintDevice->devType()); + // Fall-through & assume it's a window + case QInternal::Widget: + spec[i++] = GLX_WINDOW_BIT; + break; + }; + } +#endif + spec[i] = XNone; - return glXChooseVisual(xinfo->display(), xinfo->screen(), spec); + + + XVisualInfo* chosenVisualInfo = 0; + +#if defined(GLX_VERSION_1_3) + while (useFBConfig) { + GLXFBConfig *configs; + int configCount = 0; + configs = glXChooseFBConfig(xinfo->display(), xinfo->screen(), spec, &configCount); + + if (!configs) + break; // fallback to trying glXChooseVisual + + for (i = 0; i < configCount; ++i) { + XVisualInfo* vi; + vi = glXGetVisualFromFBConfig(xinfo->display(), configs[i]); + if (!vi) + continue; + +#if !defined(QT_NO_XRENDER) + QWidget* w = 0; + if (d->paintDevice->devType() == QInternal::Widget) + w = static_cast(d->paintDevice); + + if (w && w->testAttribute(Qt::WA_TranslucentBackground) && f.alpha()) { + // Attempt to find a config who's visual has a proper alpha channel + XRenderPictFormat *pictFormat; + pictFormat = XRenderFindVisualFormat(xinfo->display(), vi->visual); + + if (pictFormat && (pictFormat->type == PictTypeDirect) && pictFormat->direct.alphaMask) { + // The pict format for the visual matching the FBConfig indicates ARGB + if (chosenVisualInfo) + XFree(chosenVisualInfo); + chosenVisualInfo = vi; + break; + } + } else +#endif //QT_NO_XRENDER + if (chosenVisualInfo) { + // If we've got a visual we can use and we're not trying to find one with a + // real alpha channel, we might as well just use the one we've got + break; + } + + if (!chosenVisualInfo) + chosenVisualInfo = vi; // Have something to fall back to + else + XFree(vi); + } + + XFree(configs); + break; + } +#endif // defined(GLX_VERSION_1_3) + + if (!chosenVisualInfo) + chosenVisualInfo = glXChooseVisual(xinfo->display(), xinfo->screen(), spec); + + return chosenVisualInfo; } @@ -1191,6 +1293,12 @@ void QGLWidget::setContext(QGLContext *context, d_func()->xinfo = parentWidget()->d_func()->xinfo; } + // If the application has set WA_TranslucentBackground and not explicitly set + // the alpha buffer size to zero, modify the format so it have an alpha channel + QGLFormat& fmt = d->glcx->d_func()->glFormat; + if (testAttribute(Qt::WA_TranslucentBackground) && fmt.alphaBufferSize() == -1) + fmt.setAlphaBufferSize(1); + bool createFailed = false; if (!d->glcx->isValid()) { if (!d->glcx->create(shareContext ? shareContext : oldcx)) diff --git a/src/opengl/qpaintengine_opengl.cpp b/src/opengl/qpaintengine_opengl.cpp index d98cd7c..d5bf1dc 100644 --- a/src/opengl/qpaintengine_opengl.cpp +++ b/src/opengl/qpaintengine_opengl.cpp @@ -1331,7 +1331,7 @@ bool QOpenGLPaintEngine::begin(QPaintDevice *pdev) d->offscreen.begin(); const QColor &c = d->drawable.backgroundColor(); - glClearColor(c.redF(), c.greenF(), c.blueF(), 1.0); + glClearColor(c.redF(), c.greenF(), c.blueF(), d->drawable.format().alpha() ? c.alphaF() : 1.0); if (d->drawable.context()->d_func()->clear_on_painter_begin && d->drawable.autoFillBackground()) { GLbitfield clearBits = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT; #ifndef QT_OPENGL_ES -- cgit v0.12 From 71cb35e942b94e4dba2055acdebbf90c352da762 Mon Sep 17 00:00:00 2001 From: Benjamin Poulain Date: Wed, 27 May 2009 13:23:53 +0200 Subject: Add comparation of images with indexed color Previously, two images with indexed colors were not equal if their color tables were not the same. The image are not compared by the value of the pixels Reviewed-by: Samuel --- src/gui/image/qimage.cpp | 10 +++++----- tests/auto/qimage/tst_qimage.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp index 25c68bc..c1c5631 100644 --- a/src/gui/image/qimage.cpp +++ b/src/gui/image/qimage.cpp @@ -4853,8 +4853,6 @@ bool QImage::operator==(const QImage & i) const return false; if (d->format != Format_RGB32) { - if (d->colortable != i.d->colortable) - return false; if (d->format >= Format_ARGB32) { // all bits defined const int n = d->width * d->depth / 8; if (n == d->bytes_per_line && n == i.d->bytes_per_line) { @@ -4867,11 +4865,13 @@ bool QImage::operator==(const QImage & i) const } } } else { - int w = width(); - int h = height(); + const int w = width(); + const int h = height(); + const QVector &colortable = d->colortable; + const QVector &icolortable = i.d->colortable; for (int y=0; y colorTable(256); + for (int i = 0; i < 256; ++i) + colorTable[i] = qRgb(i, i, i); + img.setColorTable(colorTable); + + for (int i = 0; i < 256; ++i) { + img.setPixel(i, 0, i); + } + + QImage imgInverted(256, 1, QImage::Format_Indexed8); + QVector invertedColorTable(256); + for (int i = 0; i < 256; ++i) + invertedColorTable[255-i] = qRgb(i, i, i); + imgInverted.setColorTable(invertedColorTable); + + for (int i = 0; i < 256; ++i) { + imgInverted.setPixel(i, 0, (255-i)); + } + + QCOMPARE(img, imgInverted); +} + QTEST_MAIN(tst_QImage) #include "tst_qimage.moc" -- cgit v0.12 From 962d216ce9f9f1e6bd73fe43e3d2a7c86f64b75f Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Wed, 27 May 2009 14:02:14 +0200 Subject: Make QGLWidgets have the same background colour as QWidgets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QWidgets are filled with Qt::transparent when WA_TranslucentBackground is set, reguardless of what their background colour has been set to. This patch makes QGLWidgets behave the same way. Reviewed-By: Samuel Rødal --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 23 ++++++++-------------- src/opengl/qgl.cpp | 5 +++++ src/opengl/qgl_p.h | 1 + src/opengl/qpaintengine_opengl.cpp | 10 ++++++++-- 4 files changed, 22 insertions(+), 17 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 5c8b364..f7dbed3 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1083,16 +1083,6 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) // qDebug("You should see green now"); // sleep(5); - const QColor &c = d->drawable.backgroundColor(); - glClearColor(c.redF(), c.greenF(), c.blueF(), d->drawable.format().alpha() ? c.alphaF() : 1.0); - if (d->drawable.context()->d_func()->clear_on_painter_begin && d->drawable.autoFillBackground()) { - GLbitfield clearBits = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT; -#ifndef QT_OPENGL_ES - clearBits |= GL_ACCUM_BUFFER_BIT; -#endif - glClear(clearBits); - } - d->brushTextureDirty = true; d->brushUniformsDirty = true; d->matrixDirty = true; @@ -1105,11 +1095,14 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) glDisable(GL_SCISSOR_TEST); QGLPixmapData *source = d->drawable.copyOnBegin(); - if (d->drawable.autoFillBackground()) { - QColor color = d->drawable.backgroundColor(); - - float alpha = color.alphaF(); - glClearColor(color.redF() * alpha, color.greenF() * alpha, color.blueF() * alpha, alpha); + if (d->drawable.context()->d_func()->clear_on_painter_begin && d->drawable.autoFillBackground()) { + if (d->drawable.hasTransparentBackground()) + glClearColor(0.0, 0.0, 0.0, 0.0); + else { + const QColor &c = d->drawable.backgroundColor(); + float alpha = c.alphaF(); + glClearColor(c.redF() * alpha, c.greenF() * alpha, c.blueF() * alpha, alpha); + } glClear(GL_COLOR_BUFFER_BIT); } else if (source) { d->transferMode(ImageDrawingMode); diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 9626a3d..ced3452 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -4530,6 +4530,11 @@ QColor QGLDrawable::backgroundColor() const return QApplication::palette().brush(QPalette::Background).color(); } +bool QGLDrawable::hasTransparentBackground() const +{ + return widget && widget->testAttribute(Qt::WA_TranslucentBackground); +} + QGLContext *QGLDrawable::context() const { if (widget) diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index 9657416..b1a63b5 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -314,6 +314,7 @@ public: QColor backgroundColor() const; QGLContext *context() const; bool autoFillBackground() const; + bool hasTransparentBackground() const; #if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) QGLPixmapData *copyOnBegin() const; diff --git a/src/opengl/qpaintengine_opengl.cpp b/src/opengl/qpaintengine_opengl.cpp index d5bf1dc..e3d8a1d 100644 --- a/src/opengl/qpaintengine_opengl.cpp +++ b/src/opengl/qpaintengine_opengl.cpp @@ -1330,9 +1330,15 @@ bool QOpenGLPaintEngine::begin(QPaintDevice *pdev) d->offscreen.begin(); - const QColor &c = d->drawable.backgroundColor(); - glClearColor(c.redF(), c.greenF(), c.blueF(), d->drawable.format().alpha() ? c.alphaF() : 1.0); if (d->drawable.context()->d_func()->clear_on_painter_begin && d->drawable.autoFillBackground()) { + + if (d->drawable.hasTransparentBackground()) + glClearColor(0.0, 0.0, 0.0, 0.0); + else { + const QColor &c = d->drawable.backgroundColor(); + glClearColor(c.redF(), c.greenF(), c.blueF(), 1.0); + } + GLbitfield clearBits = GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT; #ifndef QT_OPENGL_ES clearBits |= GL_ACCUM_BUFFER_BIT; -- cgit v0.12 From 16275ff6b9abc085a498428170047f2bee9ee30b Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Wed, 27 May 2009 14:28:06 +0200 Subject: A few html code generator fixes. There was an empty
    element with a name that came after it. I moved the name inside the
    element. And there were some elements that began inside one element and ended inside the next element. I just removed them, because they didn't really add anything. And I made the "Access functions:" bold. --- tools/qdoc3/htmlgenerator.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index 798cbb5..e2e6950 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -2207,18 +2207,14 @@ void HtmlGenerator::generateSectionList(const Section& section, else { if (twoColumn && i == (int) (section.members.count() + 1) / 2) out() << "
      \n"; - out() << "
    • "; + out() << "
    • "; } - if (style == CodeMarker::Accessors) - out() << ""; generateSynopsis(*m, relative, marker, style, name_alignment); - if (style == CodeMarker::Accessors) - out() << ""; if (name_alignment) out() << "\n"; else - out() << "
    • \n"; + out() << "
    \n"; i++; ++m; } @@ -2283,8 +2279,10 @@ void HtmlGenerator::generateSynopsis(const Node *node, marked.replace("<@param>", ""); marked.replace("", ""); - if (style == CodeMarker::Summary) - marked.replace("@name>", "b>"); + if (style == CodeMarker::Summary) { + marked.replace("<@name>", ""); // was "" + marked.replace("", ""); // was "" + } if (style == CodeMarker::SeparateList) { QRegExp extraRegExp("<@extra>.*"); @@ -3090,7 +3088,7 @@ void HtmlGenerator::generateDetailedMember(const Node *node, section.members += property->resetters(); if (!section.members.isEmpty()) { - out() << "

    Access functions:

    \n"; + out() << "

    Access functions:

    \n"; generateSectionList(section, node, marker, CodeMarker::Accessors); } } -- cgit v0.12 From 3a61a448b92b4f7c7ee02196340d3bcb75d067fb Mon Sep 17 00:00:00 2001 From: diaulas Date: Tue, 12 May 2009 14:15:34 +0200 Subject: Dont show children when parent is not visible in QGraphicsItem When setVisible() is called on a QGraphicsItem, if the parent of that item was hidden, the child shouldn't be actually shown. Task-number: 197802 Reviewed-by: leo Reviewed-by: alexis --- src/gui/graphicsview/qgraphicsitem.cpp | 5 ++++ tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 32 ++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 4908296..b6a7386 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1522,6 +1522,11 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo if (visible == quint32(newVisible)) return; + QGraphicsItem *parent(q_ptr->parentItem()); + if (parent && newVisible && !parent->d_ptr->visible) { + return; + } + // Modify the property. const QVariant newVisibleVariant(q_ptr->itemChange(QGraphicsItem::ItemVisibleChange, quint32(newVisible))); diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 58a17ea..d477135 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -123,6 +123,7 @@ private slots: void destruction(); void scene(); void parentItem(); + void childrenVisibility(); void setParentItem(); void children(); void flags(); @@ -549,6 +550,37 @@ void tst_QGraphicsItem::parentItem() delete item2; } +void tst_QGraphicsItem::childrenVisibility() +{ + QGraphicsScene scene; + QGraphicsRectItem item(QRectF(0,0,20,20)); + + QGraphicsRectItem *item2 = new QGraphicsRectItem(QRectF(0,0,10,10), &item); + scene.addItem(&item); + + //freshly created: both visible + QVERIFY(item.isVisible()); + QVERIFY(item2->isVisible()); + //hide child: parent visible, child not + item2->hide(); + QVERIFY(item.isVisible()); + QVERIFY(!item2->isVisible()); + //hide parent: parent and child invisible + item.hide(); + QVERIFY(!item.isVisible()); + QVERIFY(!item2->isVisible()); + //ask to show the child: parent and child invisible anyways + item2->show(); + QVERIFY(!item.isVisible()); + QVERIFY(!item2->isVisible()); + //show the parent: both parent and child visible + item.show(); + QVERIFY(item.isVisible()); + QVERIFY(item2->isVisible()); + + delete item2; +} + void tst_QGraphicsItem::setParentItem() { QGraphicsScene scene; -- cgit v0.12 From 5675d15eebd76fde43bc9305347c3b7833a7d893 Mon Sep 17 00:00:00 2001 From: Leonardo Sobral Cunha Date: Wed, 27 May 2009 15:03:00 +0200 Subject: Fixes for merge-request #407 Removed unused line and added task number to autotest. --- src/gui/graphicsview/qgraphicsitem.cpp | 5 +- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 70 ++++++++++++++------------ 2 files changed, 39 insertions(+), 36 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index b6a7386..e8ace65 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1522,10 +1522,9 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo if (visible == quint32(newVisible)) return; - QGraphicsItem *parent(q_ptr->parentItem()); - if (parent && newVisible && !parent->d_ptr->visible) { + // Don't show child if parent is not visible + if (parent && newVisible && !parent->d_ptr->visible) return; - } // Modify the property. const QVariant newVisibleVariant(q_ptr->itemChange(QGraphicsItem::ItemVisibleChange, diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index d477135..34a6ab1 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -123,7 +123,6 @@ private slots: void destruction(); void scene(); void parentItem(); - void childrenVisibility(); void setParentItem(); void children(); void flags(); @@ -227,6 +226,7 @@ private slots: void task240400_clickOnTextItem_data(); void task240400_clickOnTextItem(); void task243707_addChildBeforeParent(); + void task197802_childrenVisibility(); }; void tst_QGraphicsItem::init() @@ -550,37 +550,6 @@ void tst_QGraphicsItem::parentItem() delete item2; } -void tst_QGraphicsItem::childrenVisibility() -{ - QGraphicsScene scene; - QGraphicsRectItem item(QRectF(0,0,20,20)); - - QGraphicsRectItem *item2 = new QGraphicsRectItem(QRectF(0,0,10,10), &item); - scene.addItem(&item); - - //freshly created: both visible - QVERIFY(item.isVisible()); - QVERIFY(item2->isVisible()); - //hide child: parent visible, child not - item2->hide(); - QVERIFY(item.isVisible()); - QVERIFY(!item2->isVisible()); - //hide parent: parent and child invisible - item.hide(); - QVERIFY(!item.isVisible()); - QVERIFY(!item2->isVisible()); - //ask to show the child: parent and child invisible anyways - item2->show(); - QVERIFY(!item.isVisible()); - QVERIFY(!item2->isVisible()); - //show the parent: both parent and child visible - item.show(); - QVERIFY(item.isVisible()); - QVERIFY(item2->isVisible()); - - delete item2; -} - void tst_QGraphicsItem::setParentItem() { QGraphicsScene scene; @@ -5378,7 +5347,7 @@ void tst_QGraphicsItem::task243707_addChildBeforeParent() // inconsistent internal state that can cause a crash. This test shows // one such crash. QGraphicsScene scene; - QGraphicsWidget *widget = new QGraphicsWidget; + QGraphicsWidget *widget = new QGraphicsWidget; QGraphicsWidget *widget2 = new QGraphicsWidget(widget); scene.addItem(widget2); QVERIFY(!widget2->parentItem()); @@ -5387,6 +5356,41 @@ void tst_QGraphicsItem::task243707_addChildBeforeParent() QVERIFY(!widget2->commonAncestorItem(widget)); } +void tst_QGraphicsItem::task197802_childrenVisibility() +{ + QGraphicsScene scene; + QGraphicsRectItem item(QRectF(0,0,20,20)); + + QGraphicsRectItem *item2 = new QGraphicsRectItem(QRectF(0,0,10,10), &item); + scene.addItem(&item); + + //freshly created: both visible + QVERIFY(item.isVisible()); + QVERIFY(item2->isVisible()); + + //hide child: parent visible, child not + item2->hide(); + QVERIFY(item.isVisible()); + QVERIFY(!item2->isVisible()); + + //hide parent: parent and child invisible + item.hide(); + QVERIFY(!item.isVisible()); + QVERIFY(!item2->isVisible()); + + //ask to show the child: parent and child invisible anyways + item2->show(); + QVERIFY(!item.isVisible()); + QVERIFY(!item2->isVisible()); + + //show the parent: both parent and child visible + item.show(); + QVERIFY(item.isVisible()); + QVERIFY(item2->isVisible()); + + delete item2; +} + void tst_QGraphicsItem::boundingRegion_data() { QTest::addColumn("line"); -- cgit v0.12 From 0a13be045b7e7fdf2b4d1a44b7aba72711375787 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Wed, 27 May 2009 15:41:12 +0200 Subject: fix flickr demo after recent changes to gradients. --- demos/declarative/flickr/content/Slider.qml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/demos/declarative/flickr/content/Slider.qml b/demos/declarative/flickr/content/Slider.qml index 6aff225..931dfe3 100644 --- a/demos/declarative/flickr/content/Slider.qml +++ b/demos/declarative/flickr/content/Slider.qml @@ -12,7 +12,7 @@ Item { id: Container; anchors.fill: parent pen.color: "white"; pen.width: 0; radius: 8 gradient: Gradient { - GradientStop { position: 0.0; color: "#66343434" }, + GradientStop { position: 0.0; color: "#66343434" } GradientStop { position: 1.0; color: "#66000000" } } } @@ -21,7 +21,7 @@ Item { id: Handle x: Slider.width / 2 - Handle.width / 2; y: 2; width: 30; height: Slider.height-4; radius: 6 gradient: Gradient { - GradientStop { position: 0.0; color: "lightgray" }, + GradientStop { position: 0.0; color: "lightgray" } GradientStop { position: 1.0; color: "gray" } } -- cgit v0.12 From d8a2e52e4db873a2cfd39630df47b61bec502fd1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dani=C3=ABl?= Date: Fri, 15 May 2009 05:29:29 +0000 Subject: Memory of fixedKernel is never returned, found by cppcheck. --- src/gui/image/qpixmapfilter.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gui/image/qpixmapfilter.cpp b/src/gui/image/qpixmapfilter.cpp index 8631c8c..4e6adc0 100644 --- a/src/gui/image/qpixmapfilter.cpp +++ b/src/gui/image/qpixmapfilter.cpp @@ -401,6 +401,7 @@ static void convolute( } yk++; } + delete[] fixedKernel; } /*! -- cgit v0.12 From b66f7a2e95c32c64701a992f28d99e32f48e2db1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 27 May 2009 16:25:25 +0200 Subject: Optimized fast scaling of ARGB8565 images onto RGB16 images. There was an optimized blend function for this case but not an optimized scale function. Performance increase seems to be in the order of 5x. Reviewed-by: Trond --- src/gui/painting/qblendfunctions.cpp | 59 +++++++++++++++++++++++++++++++++++- 1 file changed, 58 insertions(+), 1 deletion(-) diff --git a/src/gui/painting/qblendfunctions.cpp b/src/gui/painting/qblendfunctions.cpp index 8f4a2bf..f83ff7b 100644 --- a/src/gui/painting/qblendfunctions.cpp +++ b/src/gui/painting/qblendfunctions.cpp @@ -104,6 +104,37 @@ struct Blend_RGB16_on_RGB16_ConstAlpha { quint32 m_ialpha; }; +struct Blend_ARGB24_on_RGB16_SourceAlpha { + inline void write(quint16 *dst, qargb8565 src) { + const uint alpha = src.alpha(); + if (alpha) { + quint16 s = qrgb565(src).rawValue(); + if (alpha < 255) + s += BYTE_MUL_RGB16(*dst, 255 - alpha); + *dst = s; + } + } +}; + +struct Blend_ARGB24_on_RGB16_SourceAndConstAlpha { + inline Blend_ARGB24_on_RGB16_SourceAndConstAlpha(quint32 alpha) { + m_alpha = (alpha * 255) >> 8; + } + + inline void write(quint16 *dst, qargb8565 src) { + src = src.byte_mul(src.alpha(m_alpha)); + const uint alpha = src.alpha(); + if (alpha) { + quint16 s = qrgb565(src).rawValue(); + if (alpha < 255) + s += BYTE_MUL_RGB16(*dst, 255 - alpha); + *dst = s; + } + } + + quint32 m_alpha; +}; + struct Blend_ARGB32_on_RGB16_SourceAlpha { inline void write(quint16 *dst, quint32 src) { const quint8 alpha = qAlpha(src); @@ -237,6 +268,32 @@ void qt_scale_image_rgb16_on_rgb16(uchar *destPixels, int dbpl, } } +void qt_scale_image_argb24_on_rgb16(uchar *destPixels, int dbpl, + const uchar *srcPixels, int sbpl, + const QRectF &targetRect, + const QRectF &sourceRect, + const QRect &clip, + int const_alpha) +{ +#ifdef QT_DEBUG_DRAW + printf("qt_scale_argb24_on_rgb16: dst=(%p, %d), src=(%p, %d), target=(%d, %d), [%d x %d], src=(%d, %d) [%d x %d] alpha=%d\n", + destPixels, dbpl, srcPixels, sbpl, + targetRect.x(), targetRect.y(), targetRect.width(), targetRect.height(), + sourceRect.x(), sourceRect.y(), sourceRect.width(), sourceRect.height(), + const_alpha); +#endif + if (const_alpha == 256) { + Blend_ARGB24_on_RGB16_SourceAlpha noAlpha; + qt_scale_image_16bit(destPixels, dbpl, srcPixels, sbpl, + targetRect, sourceRect, clip, noAlpha); + } else { + Blend_ARGB24_on_RGB16_SourceAndConstAlpha constAlpha(const_alpha); + qt_scale_image_16bit(destPixels, dbpl, srcPixels, sbpl, + targetRect, sourceRect, clip, constAlpha); + } +} + + void qt_scale_image_argb32_on_rgb16(uchar *destPixels, int dbpl, const uchar *srcPixels, int sbpl, const QRectF &targetRect, @@ -874,7 +931,7 @@ SrcOverScaleFunc qScaleFunctions[QImage::NImageFormats][QImage::NImageFormats] = 0, // Format_ARGB32, qt_scale_image_argb32_on_rgb16, // Format_ARGB32_Premultiplied, qt_scale_image_rgb16_on_rgb16, // Format_RGB16, - 0, // Format_ARGB8565_Premultiplied, + qt_scale_image_argb24_on_rgb16, // Format_ARGB8565_Premultiplied, 0, // Format_RGB666, 0, // Format_ARGB6666_Premultiplied, 0, // Format_RGB555, -- cgit v0.12 From e24868e99ef0ffd8e5690761a798d731c4b71b26 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Wed, 27 May 2009 16:30:47 +0200 Subject: Fixed a possible assert in QGtkStyle We now set and unset the GTK_HAS_FOCUS flag on the same painting call only if focus is set instead of resetting it on each painting call. This is a tiny optimization but also kills a possible assert on certain versions of Gtk+ (as reported with Red Hat Enterprise Linux 5). Task-number: 254614 Reviewed-by: denis --- src/gui/styles/qgtkstyle.cpp | 63 ++++++++++++++++++++++---------------------- 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index 14be518..0e54af8 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -940,10 +940,6 @@ void QGtkStyle::drawPrimitive(PrimitiveElement element, case PE_FrameLineEdit: { GtkWidget *gtkEntry = QGtk::gtkWidget(QLS("GtkEntry")); - if (option->state & State_HasFocus) - GTK_WIDGET_SET_FLAGS(gtkEntry, GTK_HAS_FOCUS); - else - GTK_WIDGET_UNSET_FLAGS(gtkEntry, GTK_HAS_FOCUS); gboolean interior_focus; gint focus_line_width; @@ -957,6 +953,9 @@ void QGtkStyle::drawPrimitive(PrimitiveElement element, if (!interior_focus && option->state & State_HasFocus) rect.adjust(focus_line_width, focus_line_width, -focus_line_width, -focus_line_width); + + if (option->state & State_HasFocus) + GTK_WIDGET_SET_FLAGS(gtkEntry, GTK_HAS_FOCUS); gtkPainter.paintShadow(gtkEntry, "entry", rect, option->state & State_Enabled ? GTK_STATE_NORMAL : GTK_STATE_INSENSITIVE, GTK_SHADOW_IN, gtkEntry->style, @@ -965,6 +964,9 @@ void QGtkStyle::drawPrimitive(PrimitiveElement element, gtkPainter.paintShadow(gtkEntry, "entry", option->rect, option->state & State_Enabled ? GTK_STATE_ACTIVE : GTK_STATE_INSENSITIVE, GTK_SHADOW_IN, gtkEntry->style, QLS("GtkEntryShadowIn")); + + if (option->state & State_HasFocus) + GTK_WIDGET_UNSET_FLAGS(gtkEntry, GTK_HAS_FOCUS); } break; @@ -1050,17 +1052,13 @@ void QGtkStyle::drawPrimitive(PrimitiveElement element, GTK_WIDGET_SET_FLAGS(gtkButton, GTK_HAS_DEFAULT); gtkPainter.paintBox(gtkButton, "buttondefault", buttonRect, state, GTK_SHADOW_IN, style, isDefault ? QLS("d") : QString()); - } else - GTK_WIDGET_UNSET_FLAGS(gtkButton, GTK_HAS_DEFAULT); + } bool hasFocus = option->state & State_HasFocus; if (hasFocus) { key += QLS("def"); GTK_WIDGET_SET_FLAGS(gtkButton, GTK_HAS_FOCUS); - - } else { - GTK_WIDGET_UNSET_FLAGS(gtkButton, GTK_HAS_FOCUS); } if (!interiorFocus) @@ -1071,6 +1069,10 @@ void QGtkStyle::drawPrimitive(PrimitiveElement element, gtkPainter.paintBox(gtkButton, "button", buttonRect, state, shadow, style, key); + if (isDefault) + GTK_WIDGET_UNSET_FLAGS(gtkButton, GTK_HAS_DEFAULT); + if (hasFocus) + GTK_WIDGET_UNSET_FLAGS(gtkButton, GTK_HAS_FOCUS); } break; @@ -1334,6 +1336,8 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom GtkWidget *gtkToggleButton = QGtk::gtkWidget(buttonPath); QGtk::gtk_widget_set_direction(gtkToggleButton, reverse ? GTK_TEXT_DIR_RTL : GTK_TEXT_DIR_LTR); if (gtkToggleButton && (appears_as_list || comboBox->editable)) { + if (focus) + GTK_WIDGET_SET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS); // Draw the combo box as a line edit with a button next to it if (comboBox->editable || appears_as_list) { GtkStateType frameState = (state == GTK_STATE_PRELIGHT) ? GTK_STATE_NORMAL : state; @@ -1347,22 +1351,16 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom else frameRect.setRight(arrowButtonRect.left()); - // Required for inner blue highlight with clearlooks - if (focus) { - GTK_WIDGET_SET_FLAGS(gtkEntry, GTK_HAS_FOCUS); - GTK_WIDGET_SET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS); - - } else { - GTK_WIDGET_UNSET_FLAGS(gtkEntry, GTK_HAS_FOCUS); - GTK_WIDGET_UNSET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS); - } - // Fill the line edit background // We could have used flat_box with "entry_bg" but that is probably not worth the overhead uint resolve_mask = option->palette.resolve(); int xt = gtkEntry->style->xthickness; int yt = gtkEntry->style->ythickness; QRect contentRect = frameRect.adjusted(xt, yt, -xt, -yt); + // Required for inner blue highlight with clearlooks + if (focus) + GTK_WIDGET_SET_FLAGS(gtkEntry, GTK_HAS_FOCUS); + if (widget && widget->testAttribute(Qt::WA_SetPalette) && resolve_mask & (1 << QPalette::Base)) // Palette overridden by user p->fillRect(contentRect, option->palette.base().color()); @@ -1376,6 +1374,8 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom GTK_SHADOW_IN, gtkEntry->style, entryPath + QString::number(focus) + QString::number(comboBox->editable) + QString::number(option->direction)); + if (focus) + GTK_WIDGET_UNSET_FLAGS(gtkEntry, GTK_HAS_FOCUS); } GtkStateType buttonState = GTK_STATE_NORMAL; @@ -1394,22 +1394,21 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom gtkCachedPainter.paintBox( gtkToggleButton, "button", arrowButtonRect, buttonState, shadow, gtkToggleButton->style, buttonPath + QString::number(focus) + QString::number(option->direction)); - + if (focus) + GTK_WIDGET_UNSET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS); } else { // Draw combo box as a button QRect buttonRect = option->rect; - if (focus) { // Clearlooks actually check the widget for the default state + if (focus) // Clearlooks actually check the widget for the default state GTK_WIDGET_SET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS); - - } else { - GTK_WIDGET_UNSET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS); - } - gtkCachedPainter.paintBox(gtkToggleButton, "button", buttonRect, state, shadow, gtkToggleButton->style, buttonPath + QString::number(focus)); + if (focus) + GTK_WIDGET_UNSET_FLAGS(gtkToggleButton, GTK_HAS_FOCUS); + // Draw the separator between label and arrows QString vSeparatorPath = buttonPath + QLS(".GtkHBox.GtkVSeparator"); @@ -1775,15 +1774,12 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom shadow = GTK_SHADOW_IN; style = gtkPainter.getStyle(gtkSpinButton); - if (option->state & State_HasFocus) - GTK_WIDGET_SET_FLAGS(gtkSpinButton, GTK_HAS_FOCUS); - else - GTK_WIDGET_UNSET_FLAGS(gtkSpinButton, GTK_HAS_FOCUS); QString key; - - if (option->state & State_HasFocus) + if (option->state & State_HasFocus) { key = QLS("f"); + GTK_WIDGET_SET_FLAGS(gtkSpinButton, GTK_HAS_FOCUS); + } uint resolve_mask = option->palette.resolve(); @@ -1816,6 +1812,9 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom gtkPainter.paintBox( gtkSpinButton, "spinbutton_down", downRect, GTK_STATE_PRELIGHT, GTK_SHADOW_OUT, style, key); else gtkPainter.paintBox( gtkSpinButton, "spinbutton_down", downRect, GTK_STATE_NORMAL, GTK_SHADOW_OUT, style, key); + + if (option->state & State_HasFocus) + GTK_WIDGET_UNSET_FLAGS(gtkSpinButton, GTK_HAS_FOCUS); } if (spinBox->buttonSymbols == QAbstractSpinBox::PlusMinus) { -- cgit v0.12 From 884eb97fe9eab4ee84dd8aafb026fd918906cf9a Mon Sep 17 00:00:00 2001 From: Matteo Bertozzi Date: Sun, 17 May 2009 15:19:31 +0200 Subject: Speed up util/normalize dir iteration Use QDirIterator to speed up iterating over directories in normalize util. Reviewed-by: Eskil --- util/normalize/main.cpp | 22 +++++++++------------- 1 file changed, 9 insertions(+), 13 deletions(-) diff --git a/util/normalize/main.cpp b/util/normalize/main.cpp index 905c1ec..b16335e 100644 --- a/util/normalize/main.cpp +++ b/util/normalize/main.cpp @@ -39,7 +39,7 @@ ** ****************************************************************************/ #include -#include +#include #include #include #include @@ -140,18 +140,14 @@ void check(const QString &fileName) void traverse(const QString &path) { - QDir dir(path); - dir.setFilter(QDir::Dirs | QDir::Files | QDir::NoSymLinks); - - const QFileInfoList list = dir.entryInfoList(); - for (int i = 0; i < list.count(); ++i) { - const QFileInfo fi = list.at(i); - if (fi.fileName() == QLatin1String(".") || fi.fileName() == QLatin1String("..")) - continue; - if (fi.fileName().endsWith(".cpp")) - check(path + fi.fileName()); - if (fi.isDir()) - traverse(path + fi.fileName() + "/"); // recurse + QDirIterator dirIterator(path, QDir::NoDotAndDotDot | QDir::Dirs | QDir::Files | QDir::NoSymLinks); + + while (dirIterator.hasNext()) { + QString filePath = dirIterator.next(); + if (filePath.endsWith(".cpp")) + check(filePath); + else if (QFileInfo(filePath).isDir()) + traverse(filePath); // recurse } } -- cgit v0.12 From 2be3c937fdca26287f74dd58cc217cb51924cf8a Mon Sep 17 00:00:00 2001 From: Peter Hartmann Date: Wed, 27 May 2009 17:21:53 +0200 Subject: QNetworkReply internals: do not assert when aborted and reading data ...but just silently return. This is ok because at another location in QNetworkReplyImplPrivate we do the same. Reviewed-by: Thiago Task-number: 254638 --- src/network/access/qnetworkreplyimpl.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/network/access/qnetworkreplyimpl.cpp b/src/network/access/qnetworkreplyimpl.cpp index 79c3d1a..6f715e5 100644 --- a/src/network/access/qnetworkreplyimpl.cpp +++ b/src/network/access/qnetworkreplyimpl.cpp @@ -382,7 +382,8 @@ void QNetworkReplyImplPrivate::feed(const QByteArray &data) void QNetworkReplyImplPrivate::feed(QIODevice *data) { Q_Q(QNetworkReplyImpl); - Q_ASSERT(q->isOpen()); + if (!q->isOpen()) + return; // read until EOF from data if (copyDevice) { -- cgit v0.12 From d0bc0a26f8ac4c2f02819c262b8aa7c3dd1cad3b Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 27 May 2009 17:25:01 +0200 Subject: Fixed: Setting a border using stylesheet for QComboBox adds an unwated frame. This was already fix. But there was still a frame if there was a stylesheet on the applicaiton. The reason is that the frame's constructor call the style for some hints. And later the combobox will query the style again for the frame hint, before the view get polished. The problem is that the StyleSheetStyle will fill the css cache with wrong information on the first call. This is not visible if there is no stylesheet as in the constructor, the widget style is still the default application stylesheet if there is no global applicaiton stylesheet. Task-number: 254589 Reviewed-by: jbache BT: --- src/gui/styles/qstylesheetstyle.cpp | 9 ++++++--- tests/auto/qcombobox/tst_qcombobox.cpp | 8 +++++--- 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/src/gui/styles/qstylesheetstyle.cpp b/src/gui/styles/qstylesheetstyle.cpp index 714b8c5..bd80bb6 100644 --- a/src/gui/styles/qstylesheetstyle.cpp +++ b/src/gui/styles/qstylesheetstyle.cpp @@ -5252,9 +5252,12 @@ int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWi #ifndef QT_NO_COMBOBOX if (qobject_cast(w)) { QAbstractItemView *view = qFindChild(w); - QRenderRule subRule = renderRule(view, PseudoElement_None); - if (subRule.hasBox() || !subRule.hasNativeBorder()) - return QFrame::NoFrame; + if (view) { + view->ensurePolished(); + QRenderRule subRule = renderRule(view, PseudoElement_None); + if (subRule.hasBox() || !subRule.hasNativeBorder()) + return QFrame::NoFrame; + } } #endif // QT_NO_COMBOBOX break; diff --git a/tests/auto/qcombobox/tst_qcombobox.cpp b/tests/auto/qcombobox/tst_qcombobox.cpp index 2fff6d0..816b2e8 100644 --- a/tests/auto/qcombobox/tst_qcombobox.cpp +++ b/tests/auto/qcombobox/tst_qcombobox.cpp @@ -2171,7 +2171,7 @@ void tst_QComboBox::noScrollbar_data() QTest::newRow("everything and more") << QString::fromLatin1("QAbstractItemView { border: 1px 3px 5px 1px solid blue; " " padding: 2px 5px 3px 1px; margin: 2px 5px 3px 1px; } " " QAbstractItemView::item { border: 2px solid green; " - " padding: 1px 1px 2px 2px margin: 1px; } " ); + " padding: 1px 1px 2px 2px; margin: 1px; } " ); } void tst_QComboBox::noScrollbar() @@ -2179,10 +2179,11 @@ void tst_QComboBox::noScrollbar() QStringList initialContent; initialContent << "foo" << "bar" << "foobar" << "moo"; QFETCH(QString, stylesheet); + QString oldCss = qApp->styleSheet(); + qApp->setStyleSheet(stylesheet); { QComboBox comboBox; - comboBox.setStyleSheet(stylesheet); comboBox.addItems(initialContent); comboBox.show(); comboBox.resize(200, comboBox.height()); @@ -2196,7 +2197,6 @@ void tst_QComboBox::noScrollbar() { QTableWidget *table = new QTableWidget(2,2); QComboBox comboBox; - comboBox.setStyleSheet(stylesheet); comboBox.setView(table); comboBox.setModel(table->model()); comboBox.show(); @@ -2207,6 +2207,8 @@ void tst_QComboBox::noScrollbar() QVERIFY(!comboBox.view()->horizontalScrollBar()->isVisible()); QVERIFY(!comboBox.view()->verticalScrollBar()->isVisible()); } + + qApp->setStyleSheet(oldCss); } void tst_QComboBox::setItemDelegate() -- cgit v0.12 From 665614ede1de33d5ccfacb81c1463896a99ffd86 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 27 May 2009 18:21:30 +0200 Subject: Remove used variable olsFrameStyle was old. Reviewed-by: jbache --- src/gui/widgets/qframe.cpp | 4 +--- src/gui/widgets/qframe_p.h | 1 - 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/src/gui/widgets/qframe.cpp b/src/gui/widgets/qframe.cpp index 6f81331..22a990b 100644 --- a/src/gui/widgets/qframe.cpp +++ b/src/gui/widgets/qframe.cpp @@ -59,8 +59,7 @@ QFramePrivate::QFramePrivate() midLineWidth(0), frameWidth(0), leftFrameWidth(0), rightFrameWidth(0), - topFrameWidth(0), bottomFrameWidth(0), - oldFrameStyle(QFrame::NoFrame | QFrame::Plain) + topFrameWidth(0), bottomFrameWidth(0) { } @@ -333,7 +332,6 @@ void QFrame::setFrameStyle(int style) d->frameStyle = (short)style; update(); d->updateFrameWidth(); - d->oldFrameStyle = (short)style; } /*! diff --git a/src/gui/widgets/qframe_p.h b/src/gui/widgets/qframe_p.h index 3ea0c8b..537f5bf 100644 --- a/src/gui/widgets/qframe_p.h +++ b/src/gui/widgets/qframe_p.h @@ -74,7 +74,6 @@ public: short frameWidth; short leftFrameWidth, rightFrameWidth; short topFrameWidth, bottomFrameWidth; - short oldFrameStyle; inline void init(); -- cgit v0.12 From a9308e78e9b8aea110316c18489dd222936e13e4 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 27 May 2009 18:50:20 +0200 Subject: Compile without OpenGL Reviewed-by: Alexis --- examples/animation/sub-attaq/mainwindow.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/examples/animation/sub-attaq/mainwindow.cpp b/examples/animation/sub-attaq/mainwindow.cpp index a166241..9cf9eb5 100644 --- a/examples/animation/sub-attaq/mainwindow.cpp +++ b/examples/animation/sub-attaq/mainwindow.cpp @@ -43,11 +43,11 @@ #include "mainwindow.h" #include "graphicsscene.h" +//Qt +#include #ifndef QT_NO_OPENGL - #include +#include #endif -//Qt -#include MainWindow::MainWindow() : QMainWindow(0) { -- cgit v0.12 From 8facefaef36ae313661bbdbcf317c374e35754cb Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 27 May 2009 19:04:55 +0200 Subject: Fixes sub-attaq in shadow build. Reviewed-by: Alexis --- examples/animation/sub-attaq/graphicsscene.cpp | 2 +- examples/animation/sub-attaq/subattaq.qrc | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/animation/sub-attaq/graphicsscene.cpp b/examples/animation/sub-attaq/graphicsscene.cpp index f2d41bc..e773dae 100644 --- a/examples/animation/sub-attaq/graphicsscene.cpp +++ b/examples/animation/sub-attaq/graphicsscene.cpp @@ -120,7 +120,7 @@ GraphicsScene::GraphicsScene(int x, int y, int width, int height, Mode mode) //parse the xml that contain all data of the game QXmlStreamReader reader; - QFile file(QDir::currentPath() + "/data.xml"); + QFile file(":data.xml"); file.open(QIODevice::ReadOnly); reader.setDevice(&file); LevelDescription currentLevel; diff --git a/examples/animation/sub-attaq/subattaq.qrc b/examples/animation/sub-attaq/subattaq.qrc index c76f8ef..80a3af1 100644 --- a/examples/animation/sub-attaq/subattaq.qrc +++ b/examples/animation/sub-attaq/subattaq.qrc @@ -34,5 +34,6 @@ pics/big/explosion/submarine/step2.png pics/big/explosion/submarine/step3.png pics/big/explosion/submarine/step4.png + data.xml -- cgit v0.12 From e4cd7640d98f229e777f0699d7b738a8b539c269 Mon Sep 17 00:00:00 2001 From: mae Date: Wed, 27 May 2009 20:18:01 +0200 Subject: Restore undo compression for cut/del of selections This is a small fix to 4af30f47c37fd0e6826aca2984dd0f567dc7e465 --- src/gui/text/qtextcursor.cpp | 57 +++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 25 deletions(-) diff --git a/src/gui/text/qtextcursor.cpp b/src/gui/text/qtextcursor.cpp index d12e3fe..b9e1c89 100644 --- a/src/gui/text/qtextcursor.cpp +++ b/src/gui/text/qtextcursor.cpp @@ -1361,12 +1361,15 @@ void QTextCursor::deleteChar() if (!d || !d->priv) return; - if (d->position == d->anchor) { - if (!d->canDelete(d->position)) - return; - d->adjusted_anchor = d->anchor = - d->priv->nextCursorPosition(d->anchor, QTextLayout::SkipCharacters); + if (d->position != d->anchor) { + removeSelectedText(); + return; } + + if (!d->canDelete(d->position)) + return; + d->adjusted_anchor = d->anchor = + d->priv->nextCursorPosition(d->anchor, QTextLayout::SkipCharacters); d->remove(); d->setX(); } @@ -1381,27 +1384,29 @@ void QTextCursor::deletePreviousChar() { if (!d || !d->priv) return; - - if (d->position == d->anchor) { - if (d->anchor < 1 || !d->canDelete(d->anchor-1)) - return; - d->anchor--; - - QTextDocumentPrivate::FragmentIterator fragIt = d->priv->find(d->anchor); - const QTextFragmentData * const frag = fragIt.value(); - int fpos = fragIt.position(); - QChar uc = d->priv->buffer().at(d->anchor - fpos + frag->stringPosition); - if (d->anchor > fpos && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) { - // second half of a surrogate, check if we have the first half as well, - // if yes delete both at once - uc = d->priv->buffer().at(d->anchor - 1 - fpos + frag->stringPosition); - if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) - --d->anchor; - } - - d->adjusted_anchor = d->anchor; + + if (d->position != d->anchor) { + removeSelectedText(); + return; } - + + if (d->anchor < 1 || !d->canDelete(d->anchor-1)) + return; + d->anchor--; + + QTextDocumentPrivate::FragmentIterator fragIt = d->priv->find(d->anchor); + const QTextFragmentData * const frag = fragIt.value(); + int fpos = fragIt.position(); + QChar uc = d->priv->buffer().at(d->anchor - fpos + frag->stringPosition); + if (d->anchor > fpos && uc.unicode() >= 0xdc00 && uc.unicode() < 0xe000) { + // second half of a surrogate, check if we have the first half as well, + // if yes delete both at once + uc = d->priv->buffer().at(d->anchor - 1 - fpos + frag->stringPosition); + if (uc.unicode() >= 0xd800 && uc.unicode() < 0xdc00) + --d->anchor; + } + + d->adjusted_anchor = d->anchor; d->remove(); d->setX(); } @@ -1517,7 +1522,9 @@ void QTextCursor::removeSelectedText() if (!d || !d->priv || d->position == d->anchor) return; + d->priv->beginEditBlock(); d->remove(); + d->priv->endEditBlock(); d->setX(); } -- cgit v0.12 From b865ab6508963cbad0a12319b40db17f9925bbde Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Thu, 28 May 2009 10:48:50 +1000 Subject: QmlBasicScript should work on the actual JS AST tree --- src/declarative/fx/qfxkeyactions.cpp | 2 +- src/declarative/qml/parser/javascriptast_p.h | 6 +- src/declarative/qml/qml.pri | 6 +- src/declarative/qml/qmlbasicscript.cpp | 853 +++++++++++++++++++ src/declarative/qml/qmlbasicscript_p.h | 104 +++ src/declarative/qml/qmlbindablevalue.cpp | 4 +- src/declarative/qml/qmlbindablevalue.h | 2 +- src/declarative/qml/qmlcompiler.cpp | 45 +- src/declarative/qml/qmlengine.cpp | 36 +- src/declarative/qml/qmlengine_p.h | 4 +- src/declarative/qml/qmlexpression.h | 2 - src/declarative/qml/qmlparser.cpp | 1 - src/declarative/qml/script/generator/generator.pro | 11 - src/declarative/qml/script/generator/main.cpp | 135 --- src/declarative/qml/script/instructions.h | 32 - src/declarative/qml/script/keywords.cpp | 89 -- src/declarative/qml/script/lexer.cpp | 139 ---- src/declarative/qml/script/lexer.h | 54 -- src/declarative/qml/script/qmlbasicscript.cpp | 921 --------------------- src/declarative/qml/script/qmlbasicscript.h | 76 -- src/declarative/qml/script/qmlbasicscript_p.h | 53 -- src/declarative/qml/script/script.pri | 11 - src/declarative/qml/script/tokens.cpp | 43 - src/declarative/qml/script/tokens.h | 36 - 24 files changed, 1017 insertions(+), 1648 deletions(-) create mode 100644 src/declarative/qml/qmlbasicscript.cpp create mode 100644 src/declarative/qml/qmlbasicscript_p.h delete mode 100644 src/declarative/qml/script/generator/generator.pro delete mode 100644 src/declarative/qml/script/generator/main.cpp delete mode 100644 src/declarative/qml/script/instructions.h delete mode 100644 src/declarative/qml/script/keywords.cpp delete mode 100644 src/declarative/qml/script/lexer.cpp delete mode 100644 src/declarative/qml/script/lexer.h delete mode 100644 src/declarative/qml/script/qmlbasicscript.cpp delete mode 100644 src/declarative/qml/script/qmlbasicscript.h delete mode 100644 src/declarative/qml/script/qmlbasicscript_p.h delete mode 100644 src/declarative/qml/script/script.pri delete mode 100644 src/declarative/qml/script/tokens.cpp delete mode 100644 src/declarative/qml/script/tokens.h diff --git a/src/declarative/fx/qfxkeyactions.cpp b/src/declarative/fx/qfxkeyactions.cpp index 5a1fd7d..4aae74f 100644 --- a/src/declarative/fx/qfxkeyactions.cpp +++ b/src/declarative/fx/qfxkeyactions.cpp @@ -899,7 +899,7 @@ void QFxKeyActions::keyPressEvent(QKeyEvent *event) { Qt::Key key = (Qt::Key)event->key(); if (d->enabled && d->key(key)) { - QmlExpression b(qmlContext(this), d->action(key), this, false); + QmlExpression b(qmlContext(this), d->action(key), this); b.value(); event->accept(); } else { diff --git a/src/declarative/qml/parser/javascriptast_p.h b/src/declarative/qml/parser/javascriptast_p.h index b5fd922..23d59e5 100644 --- a/src/declarative/qml/parser/javascriptast_p.h +++ b/src/declarative/qml/parser/javascriptast_p.h @@ -61,8 +61,6 @@ QT_BEGIN_NAMESPACE #define JAVASCRIPT_DECLARE_AST_NODE(name) \ enum { K = Kind_##name }; -class NameId; - namespace QSOperator // ### rename { @@ -106,7 +104,9 @@ enum Op { } // namespace QSOperator -namespace JavaScript { namespace AST { +namespace JavaScript { +class NameId; +namespace AST { template _T1 cast(_T2 *ast) diff --git a/src/declarative/qml/qml.pri b/src/declarative/qml/qml.pri index b6ac30e..c61200e 100644 --- a/src/declarative/qml/qml.pri +++ b/src/declarative/qml/qml.pri @@ -23,7 +23,8 @@ SOURCES += qml/qmlparser.cpp \ qml/qmlcompositetypemanager.cpp \ qml/qmlinfo.cpp \ qml/qmlerror.cpp \ - qml/qmlscriptparser.cpp + qml/qmlscriptparser.cpp \ + qml/qmlbasicscript.cpp HEADERS += qml/qmlparser_p.h \ qml/qmlinstruction_p.h \ @@ -61,7 +62,8 @@ HEADERS += qml/qmlparser_p.h \ qml/qmllist.h \ qml/qmldeclarativedata_p.h \ qml/qmlerror.h \ - qml/qmlscriptparser_p.h + qml/qmlscriptparser_p.h \ + qml/qmlbasicscript_p.h # for qtscript debugger QT += scripttools diff --git a/src/declarative/qml/qmlbasicscript.cpp b/src/declarative/qml/qmlbasicscript.cpp new file mode 100644 index 0000000..3d74b37 --- /dev/null +++ b/src/declarative/qml/qmlbasicscript.cpp @@ -0,0 +1,853 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the $MODULE$ of the Qt Toolkit. +** +** $TROLLTECH_DUAL_LICENSE$ +** +****************************************************************************/ + +#include "qmlbasicscript_p.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +struct ScriptInstruction { + enum { + Load, // fetch + Fetch, // fetch + + Add, // NA + Subtract, // NA + Multiply, // NA + Equals, // NA + And, // NA + + Int, // integer + Bool, // boolean + } type; + + union { + struct { + int idx; + } fetch; + struct { + int value; + } integer; + struct { + bool value; + } boolean; + }; +}; + +DEFINE_BOOL_CONFIG_OPTION(scriptWarnings, QML_SCRIPT_WARNINGS); + +class QmlBasicScriptPrivate +{ +public: + enum Flags { OwnData = 0x00000001 }; + + int size; + int stateSize; + int instructionCount; + int exprLen; + + ScriptInstruction *instructions() const { return (ScriptInstruction *)((char *)this + sizeof(QmlBasicScriptPrivate)); } + + const char *expr() const + { + return (const char *)(instructions() + instructionCount); + } + + const char *data() const + { + return (const char *)(instructions() + instructionCount) + exprLen + 1; + } + + static unsigned int alignRound(int s) + { + if (s % 4) + s += 4 - (s % 4); + return s; + } +}; + +QDebug operator<<(QDebug lhs, const QmlBasicScriptNodeCache &rhs) +{ + switch(rhs.type) { + case QmlBasicScriptNodeCache::Invalid: + lhs << "Invalid"; + break; + case QmlBasicScriptNodeCache::Core: + lhs << "Core" << rhs.object << rhs.core; + break; + case QmlBasicScriptNodeCache::Attached: + lhs << "Attached" << rhs.object << rhs.attached; + break; + case QmlBasicScriptNodeCache::Signal: + lhs << "Signal" << rhs.object << rhs.core; + break; + case QmlBasicScriptNodeCache::SignalProperty: + lhs << "SignalProperty" << rhs.object << rhs.core; + break; + case QmlBasicScriptNodeCache::Variant: + lhs << "Variant" << rhs.context; + break; + } + + return lhs; +} + +void QmlBasicScriptNodeCache::clear() +{ + object = 0; + metaObject = 0; + type = Invalid; +} + +static QVariant toObjectOrVariant(const QVariant &v) +{ + switch(v.type()) { + case QVariant::String: + case QVariant::UInt: + case QVariant::Int: + case 135: + case QVariant::Double: + case QVariant::Color: + case QVariant::Bool: + default: + return v; + case QVariant::UserType: + { + QObject *o = QmlMetaType::toQObject(v); + if (o) + return qVariantFromValue(o); + else + return v; + } + break; + } +} + +static QVariant fetch_value(QObject *o, int idx, int type) +{ + switch(type) { + case QVariant::String: + { + QString val; + void *args[] = { &val, 0 }; + QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); + return QVariant(val); + } + break; + case QVariant::UInt: + { + uint val; + void *args[] = { &val, 0 }; + QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); + return QVariant(val); + } + break; + case QVariant::Int: + { + int val; + void *args[] = { &val, 0 }; + QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); + return QVariant(val); + } + break; + case 135: + { + float val; + void *args[] = { &val, 0 }; + QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); + return QVariant(val); + } + break; + case QVariant::Double: + { + double val; + void *args[] = { &val, 0 }; + QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); + return QVariant(val); + } + break; + case QVariant::Color: + { + QColor val; + void *args[] = { &val, 0 }; + QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); + return QVariant(val); + } + break; + case QVariant::Bool: + { + bool val; + void *args[] = { &val, 0 }; + QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); + return QVariant(val); + } + break; + default: + { + if (QmlMetaType::isObject(type)) { + // NOTE: This assumes a cast to QObject does not alter the + // object pointer + QObject *val = 0; + void *args[] = { &val, 0 }; + QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); + return QVariant::fromValue(val); + } else { + QVariant var = o->metaObject()->property(idx).read(o); + if (QmlMetaType::isObject(var.userType())) { + QObject *obj = 0; + obj = *(QObject **)var.data(); + var = QVariant::fromValue(obj); + } + return var; + } + } + break; + }; +} + +QVariant QmlBasicScriptNodeCache::value(const char *) const +{ + //QFxPerfTimer pt; + switch(type) { + case Invalid: + break; + case Core: + return fetch_value(object, core, coreType); + break; + case Attached: + return qVariantFromValue(static_cast(attached)); + break; + case Signal: + // XXX + Q_ASSERT(!"Not implemented"); + break; + case SignalProperty: + break; + case Variant: + return context->propertyValues[contextIndex]; + }; + return QVariant(); +} + +struct QmlBasicScriptCompiler +{ + QmlBasicScriptCompiler() + : script(0), stateSize(0) {} + QmlBasicScript *script; + int stateSize; + + bool compile(JavaScript::AST::Node *); + + bool compileExpression(JavaScript::AST::Node *); + + bool tryConstant(JavaScript::AST::Node *); + bool parseConstant(JavaScript::AST::Node *); + bool tryName(JavaScript::AST::Node *); + bool parseName(JavaScript::AST::Node *); + bool tryBinaryExpression(JavaScript::AST::Node *); + bool compileBinaryExpression(JavaScript::AST::Node *); + + QByteArray data; + QList bytecode; +}; + +/*! + \internal + \class QmlBasicScript + \brief The QmlBasicScript class provides a fast implementation of a limited subset of JavaScript bindings. + + QmlBasicScript instances are used to accelerate binding. Instead of using + the slower, fully fledged JavaScript engine, many simple bindings can be + evaluated using the QmlBasicScript engine. + + To see if the QmlBasicScript engine can handle a binding, call compile() + and check the return value, or isValid() afterwards. + + To evaluate the binding, the QmlBasicScript instance needs some memory in + which to cache state. This may be allocated by calling newScriptState() + and destroyed by calling deleteScriptState(). The state data is then passed + to the run() method when evaluating the binding. + + To further accelerate binding, QmlBasicScript can return a precompiled + version of itself that can be saved for future use. Call compileData() to + get an opaque pointer to the compiled state, and compileDataSize() for the + size of this data in bytes. This data can be saved and passed to future + instances of the QmlBasicScript constructor. The initial copy of compile + data is owned by the QmlBindScript instance on which compile() was called. +*/ + +/*! + Create a new QmlBasicScript instance. +*/ +QmlBasicScript::QmlBasicScript() +: flags(0), d(0), rc(0) +{ +} + +/*! + Create a new QmlBasicScript instance from saved \a data. + + \a data \b must be data previously acquired from calling compileData() on a + previously created QmlBasicScript instance. Any other data will almost + certainly cause the QmlBasicScript engine to crash. + + \a data must continue to be valid throughout the QmlBasicScript instance + life. It does not assume ownership of the memory. + + If \a owner is set, it is referenced on creation and dereferenced on + destruction of this instance. +*/ +QmlBasicScript::QmlBasicScript(const char *data, QmlRefCount *owner) +: flags(0), d((QmlBasicScriptPrivate *)data), rc(owner) +{ + if (rc) rc->addref(); +} + +/*! + Return the text of the script expression. + */ +QByteArray QmlBasicScript::expression() const +{ + if (!d) + return QByteArray(); + else + return QByteArray(d->expr()); +} + +/*! + Destroy the script instance. +*/ +QmlBasicScript::~QmlBasicScript() +{ + if (flags & QmlBasicScriptPrivate::OwnData) + free(d); + if (rc) rc->release(); + d = 0; + rc = 0; +} + +/*! + Clear this script. The object will then be in its initial state, as though + it were freshly constructed with default constructor. +*/ +void QmlBasicScript::clear() +{ + if (flags & QmlBasicScriptPrivate::OwnData) + free(d); + if (rc) rc->release(); + d = 0; + rc = 0; + flags = 0; +} + +/*! + Return the script state memory for this script instance. This memory should + only be destroyed by calling deleteScriptState(). + */ +void *QmlBasicScript::newScriptState() +{ + if (!d) { + return 0; + } else { + void *rv = ::malloc(d->stateSize * sizeof(QmlBasicScriptNodeCache)); + ::memset(rv, 0, d->stateSize * sizeof(QmlBasicScriptNodeCache)); + return rv; + } +} + +/*! + Delete the \a data previously allocated by newScriptState(). + */ +void QmlBasicScript::deleteScriptState(void *data) +{ + if (!data) return; + Q_ASSERT(d); + clearCache(data); + free(data); +} + +/*! + Dump the script instructions to stderr for debugging. + */ +void QmlBasicScript::dump() +{ + if (!d) + return; + + qWarning() << d->instructionCount << "instructions:"; + const char *data = d->data(); + for (int ii = 0; ii < d->instructionCount; ++ii) { + const ScriptInstruction &instr = d->instructions()[ii]; + + switch(instr.type) { + case ScriptInstruction::Load: + qWarning().nospace() << "LOAD\t\t" << instr.fetch.idx << "\t\t" + << QByteArray(data + instr.fetch.idx); + break; + case ScriptInstruction::Fetch: + qWarning().nospace() << "FETCH\t\t" << instr.fetch.idx << "\t\t" + << QByteArray(data + instr.fetch.idx); + break; + case ScriptInstruction::Add: + qWarning().nospace() << "ADD"; + break; + case ScriptInstruction::Subtract: + qWarning().nospace() << "SUBTRACT"; + break; + case ScriptInstruction::Multiply: + qWarning().nospace() << "MULTIPLY"; + break; + case ScriptInstruction::Equals: + qWarning().nospace() << "EQUALS"; + break; + case ScriptInstruction::Int: + qWarning().nospace() << "INT\t\t" << instr.integer.value; + break; + case ScriptInstruction::Bool: + qWarning().nospace() << "BOOL\t\t" << instr.boolean.value; + break; + default: + qWarning().nospace() << "UNKNOWN"; + break; + } + } +} + +/*! + Return true if this is a valid script binding, otherwise returns false. + */ +bool QmlBasicScript::isValid() const +{ + return d != 0; +} + +/*! + Compile \a v and return true if the compilation is successful, otherwise + returns false. + */ +bool QmlBasicScript::compile(const QmlParser::Variant &v) +{ + if (!v.asAST()) return false; + + QByteArray expr = v.asScript().toLatin1(); + const char *src = expr.constData(); + + QmlBasicScriptCompiler bsc; + bsc.script = this; + + if (d) { + if (flags & QmlBasicScriptPrivate::OwnData) + free(d); + d = 0; + flags = 0; + } + + if (bsc.compile(v.asAST())) { + int len = ::strlen(src); + flags = QmlBasicScriptPrivate::OwnData; + int size = sizeof(QmlBasicScriptPrivate) + + bsc.bytecode.count() * sizeof(ScriptInstruction) + + QmlBasicScriptPrivate::alignRound(bsc.data.count() + len + 1); + d = (QmlBasicScriptPrivate *) malloc(size); + d->size = size; + d->stateSize = bsc.stateSize; + d->instructionCount = bsc.bytecode.count(); + d->exprLen = len; + ::memcpy((char *)d->expr(), src, len + 1); + for (int ii = 0; ii < d->instructionCount; ++ii) + d->instructions()[ii] = bsc.bytecode.at(ii); + ::memcpy((char *)d->data(), bsc.data.constData(), bsc.data.count()); + } + + return d != 0; +} + +bool QmlBasicScriptCompiler::compile(JavaScript::AST::Node *node) +{ + return compileExpression(node); +} + +using namespace JavaScript; +bool QmlBasicScriptCompiler::tryConstant(JavaScript::AST::Node *node) +{ + if (node->kind == AST::Node::Kind_TrueLiteral || + node->kind == AST::Node::Kind_FalseLiteral) + return true; + + if (node->kind == AST::Node::Kind_NumericLiteral) { + AST::NumericLiteral *lit = static_cast(node); + + return lit->suffix == AST::NumericLiteral::noSuffix && + double(int(lit->value)) == lit->value; + } + + return false; +} + +bool QmlBasicScriptCompiler::parseConstant(JavaScript::AST::Node *node) +{ + ScriptInstruction instr; + + if (node->kind == AST::Node::Kind_NumericLiteral) { + AST::NumericLiteral *lit = static_cast(node); + instr.type = ScriptInstruction::Int; + instr.integer.value = int(lit->value); + } else { + instr.type = ScriptInstruction::Bool; + instr.boolean.value = node->kind == AST::Node::Kind_TrueLiteral; + } + + bytecode.append(instr); + + return true; +} + +bool QmlBasicScriptCompiler::tryName(JavaScript::AST::Node *node) +{ + return node->kind == AST::Node::Kind_IdentifierExpression || + node->kind == AST::Node::Kind_FieldMemberExpression; +} + +bool QmlBasicScriptCompiler::parseName(AST::Node *node) +{ + bool load = false; + + QString name; + if (node->kind == AST::Node::Kind_IdentifierExpression) { + name = static_cast(node)->name->asString(); + load = true; + } else if (node->kind == AST::Node::Kind_FieldMemberExpression) { + AST::FieldMemberExpression *expr = static_cast(node); + + if (!parseName(expr->base)) + return false; + + name = expr->name->asString(); + } else { + return false; + } + + int nref = data.count(); + data.append(name.toUtf8()); + data.append('\0'); + ScriptInstruction instr; + if (load) + instr.type = ScriptInstruction::Load; + else + instr.type = ScriptInstruction::Fetch; + instr.fetch.idx = nref; + bytecode.append(instr); + ++stateSize; + + return true; +} + +bool QmlBasicScriptCompiler::compileExpression(JavaScript::AST::Node *node) +{ + if (tryBinaryExpression(node)) + return compileBinaryExpression(node); + else if (tryConstant(node)) + return parseConstant(node); + else if (tryName(node)) + return parseName(node); + else + return false; +} + +bool QmlBasicScriptCompiler::tryBinaryExpression(AST::Node *node) +{ + if (node->kind == AST::Node::Kind_BinaryExpression) { + AST::BinaryExpression *expr = + static_cast(node); + + if (expr->op == QSOperator::Add || + expr->op == QSOperator::Sub || + expr->op == QSOperator::Equal || + expr->op == QSOperator::And || + expr->op == QSOperator::Mul) + return true; + } + return false; +} + +bool QmlBasicScriptCompiler::compileBinaryExpression(AST::Node *node) +{ + if (node->kind == AST::Node::Kind_BinaryExpression) { + AST::BinaryExpression *expr = + static_cast(node); + + if (!compileExpression(expr->left)) return false; + if (!compileExpression(expr->right)) return false; + + ScriptInstruction instr; + switch (expr->op) { + case QSOperator::Add: + instr.type = ScriptInstruction::Add; + break; + case QSOperator::Sub: + instr.type = ScriptInstruction::Subtract; + break; + case QSOperator::Equal: + instr.type = ScriptInstruction::Equals; + break; + case QSOperator::And: + instr.type = ScriptInstruction::And; + break; + case QSOperator::Mul: + instr.type = ScriptInstruction::Multiply; + break; + default: + return false; + } + + bytecode.append(instr); + return true; + } + return false; +} + +/*! + \internal +*/ +void QmlBasicScript::clearCache(void *voidCache) +{ + QmlBasicScriptNodeCache *dataCache = + reinterpret_cast(voidCache); + + for (int ii = 0; ii < d->stateSize; ++ii) { + if (!dataCache[ii].isCore() && !dataCache[ii].isVariant() && + dataCache[ii].object) { + QMetaObject::removeGuard(&dataCache[ii].object); + dataCache[ii].object = 0; + } + dataCache[ii].clear(); + } +} + +void QmlBasicScript::guard(QmlBasicScriptNodeCache &n) +{ + if (n.object) { + if (n.isVariant()) { + } else if (n.isCore()) { + n.metaObject = + n.object->metaObject(); + } else { + QMetaObject::addGuard(&n.object); + } + } +} + +bool QmlBasicScript::valid(QmlBasicScriptNodeCache &n, QObject *obj) +{ + return n.object == obj && + (!n.isCore() || obj->metaObject() == n.metaObject); +} + + +/*! + \enum QmlBasicScript::CacheState + \value NoChange The query has not change. Any previous monitoring is still + valid. + \value Incremental The query has been incrementally changed. Any previous + monitoring is still valid, but needs to have the fresh properties added to + it. + \value Reset The entire query has been reset from the beginning. Any previous + monitoring is now invalid. +*/ + +/*! + Run the script in \a context and return the result. \a voidCache should + contain state memory previously acquired from newScript. + */ +QVariant QmlBasicScript::run(QmlContext *context, void *voidCache, CacheState *cached) +{ + if (!isValid()) + return QVariant(); + + QmlBasicScriptNodeCache *dataCache = + reinterpret_cast(voidCache); + int dataCacheItem; + QStack stack; + + bool resetting = false; + bool hasReset = false; + + const char *data = d->data(); + + if (dataCache[0].type == QmlBasicScriptNodeCache::Invalid) { + resetting = true; + hasReset = true; + } + + CacheState state = NoChange; + + dataCacheItem = 0; + for (int idx = 0; idx < d->instructionCount; ++idx) { + const ScriptInstruction &instr = d->instructions()[idx]; + + switch(instr.type) { + case ScriptInstruction::Load: // either an object or a property + case ScriptInstruction::Fetch: // can only be a property + { + const char *id = data + instr.fetch.idx; + QmlBasicScriptNodeCache &n = dataCache[dataCacheItem]; + + if (instr.type == ScriptInstruction::Load) { + + if (n.type == QmlBasicScriptNodeCache::Invalid) { + context->engine()->d_func()->loadCache(n, QLatin1String(id), static_cast(context->d_ptr)); + state = Incremental; + } + + if(!n.isValid()) + qWarning("ReferenceError: %s is not defined", id); + + } else { // instr.type == ScriptInstruction::Fetch + + QVariant o = stack.pop(); + QObject *obj = qvariant_cast(o); + if (!obj) { + if (n.type == QmlBasicScriptNodeCache::Invalid) { + if (scriptWarnings()) + qWarning() << "QmlBasicScript: Unable to convert" << o; + *cached = state; + return QVariant(); + } else { + clearCache(dataCache); + *cached = Reset; + CacheState dummy; + return run(context, voidCache, &dummy); + } + } else if (n.type == QmlBasicScriptNodeCache::Invalid) { + context->engine()->d_func()->fetchCache(n, QLatin1String(id), obj); + guard(n); + state = Incremental; + } else if (!valid(n, obj)) { + clearCache(dataCache); + *cached = Reset; + CacheState dummy; + return run(context, voidCache, &dummy); + } + + } + + QVariant var = n.value(id); + stack.push(var); + ++dataCacheItem; + } + break; + case ScriptInstruction::Int: + stack.push(QVariant(instr.integer.value)); + break; + case ScriptInstruction::Bool: + stack.push(QVariant(instr.boolean.value)); + break; + case ScriptInstruction::Add: + { + QVariant rhs = stack.pop(); + QVariant lhs = stack.pop(); + + stack.push(rhs.toDouble() + lhs.toDouble()); + } + break; + case ScriptInstruction::Subtract: + { + QVariant rhs = stack.pop(); + QVariant lhs = stack.pop(); + + stack.push(lhs.toDouble() - rhs.toDouble()); + } + break; + case ScriptInstruction::Multiply: + { + QVariant rhs = stack.pop(); + QVariant lhs = stack.pop(); + + stack.push(rhs.toDouble() * lhs.toDouble()); + } + break; + case ScriptInstruction::Equals: + { + QVariant rhs = stack.pop(); + QVariant lhs = stack.pop(); + + stack.push(rhs == lhs); + } + break; + case ScriptInstruction::And: + { + QVariant rhs = stack.pop(); + QVariant lhs = stack.pop(); + + stack.push(rhs.toBool() && lhs.toBool()); + } + break; + default: + break; + } + } + + *cached = state; + + if (stack.isEmpty()) + return QVariant(); + else + return stack.top(); +} + +/*! + Return a pointer to the script's compile data, or null if there is no data. + */ +const char *QmlBasicScript::compileData() const +{ + return (const char *)d; +} + +/*! + Return the size of the script's compile data, or zero if there is no data. + The size will always be a multiple of 4. + */ +unsigned int QmlBasicScript::compileDataSize() const +{ + if (d) + return d->size; + else + return 0; +} + +bool QmlBasicScript::isSingleLoad() const +{ + if (!d) + return false; + + return d->instructionCount == 1 && + d->instructions()[0].type == ScriptInstruction::Load; +} + +QByteArray QmlBasicScript::singleLoadTarget() const +{ + if (!isSingleLoad()) + return QByteArray(); + + // We know there is one instruction and it is a load + return QByteArray(d->data() + d->instructions()[0].fetch.idx); +} + + +QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlbasicscript_p.h b/src/declarative/qml/qmlbasicscript_p.h new file mode 100644 index 0000000..1117e11 --- /dev/null +++ b/src/declarative/qml/qmlbasicscript_p.h @@ -0,0 +1,104 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the $MODULE$ of the Qt Toolkit. +** +** $TROLLTECH_DUAL_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLBASICSCRIPT_P_H +#define QMLBASICSCRIPT_P_H + +#include +#include +#include +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +class QmlRefCount; +class QmlContext; +class QmlBasicScriptPrivate; +class QmlBasicScriptNodeCache; +class QmlBasicScript +{ +public: + QmlBasicScript(); + QmlBasicScript(const char *, QmlRefCount * = 0); + ~QmlBasicScript(); + + // Always 4-byte aligned + const char *compileData() const; + unsigned int compileDataSize() const; + + QByteArray expression() const; + + bool compile(const QmlParser::Variant &); + bool isValid() const; + + void clear(); + + void dump(); + void *newScriptState(); + void deleteScriptState(void *); + + enum CacheState { NoChange, Incremental, Reset }; + QVariant run(QmlContext *, void *, CacheState *); + + // Optimization opportunities + bool isSingleLoad() const; + QByteArray singleLoadTarget() const; + +private: + int flags; + QmlBasicScriptPrivate *d; + QmlRefCount *rc; + + void clearCache(void *); + void guard(QmlBasicScriptNodeCache &); + bool valid(QmlBasicScriptNodeCache &, QObject *); +}; + +class QmlContextPrivate; +class QDebug; +class QmlBasicScriptNodeCache +{ +public: + QObject *object; + const QMetaObject *metaObject; + enum { Invalid, + Core, + Attached, + Signal, + SignalProperty, + Variant + } type; + union { + int core; + QObject *attached; + QmlContextPrivate *context; + }; + int coreType; + int contextIndex; + + bool isValid() const { return type != Invalid; } + bool isCore() const { return type == Core; } + bool isVariant() const { return type == Variant; } + void clear(); + QVariant value(const char *) const; +}; + +QDebug operator<<(QDebug, const QmlBasicScriptNodeCache &); + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QMLBASICSCRIPT_P_H + + diff --git a/src/declarative/qml/qmlbindablevalue.cpp b/src/declarative/qml/qmlbindablevalue.cpp index d5157b6..351e0bd 100644 --- a/src/declarative/qml/qmlbindablevalue.cpp +++ b/src/declarative/qml/qmlbindablevalue.cpp @@ -69,8 +69,8 @@ QmlBindableValue::QmlBindableValue(void *data, QmlRefCount *rc, QObject *obj, QO { } -QmlBindableValue::QmlBindableValue(const QString &str, QObject *obj, bool sse, QObject *parent) -: QmlPropertyValueSource(*new QmlBindableValuePrivate, parent), QmlExpression(QmlContext::activeContext(), str, obj, sse) +QmlBindableValue::QmlBindableValue(const QString &str, QObject *obj, QObject *parent) +: QmlPropertyValueSource(*new QmlBindableValuePrivate, parent), QmlExpression(QmlContext::activeContext(), str, obj) { } diff --git a/src/declarative/qml/qmlbindablevalue.h b/src/declarative/qml/qmlbindablevalue.h index c5bb97b..71a7051 100644 --- a/src/declarative/qml/qmlbindablevalue.h +++ b/src/declarative/qml/qmlbindablevalue.h @@ -63,7 +63,7 @@ class Q_DECLARATIVE_EXPORT QmlBindableValue : public QmlPropertyValueSource, Q_OBJECT public: QmlBindableValue(QObject *parent); - QmlBindableValue(const QString &, QObject *, bool = true, QObject *parent=0); + QmlBindableValue(const QString &, QObject *, QObject *parent=0); QmlBindableValue(void *, QmlRefCount *, QObject *, QObject *parent); ~QmlBindableValue(); diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index b9a848a..75d01c2 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -46,7 +46,7 @@ #include #include #include "private/qmetaobjectbuilder_p.h" -#include +#include "qmlbasicscript_p.h" #include #include #include @@ -1415,7 +1415,7 @@ bool QmlCompiler::compileBinding(const QmlParser::Variant &bind, COMPILE_EXCEPTION2(prop, "Cannot assign binding to read-only property"); QmlBasicScript bs; - bs.compile(bind.asScript().toLatin1()); + bs.compile(bind); int bref; if (bs.isValid()) { @@ -1447,6 +1447,47 @@ bool QmlCompiler::compileBinding(const QmlParser::Variant &bind, return true; } +#if 0 + +#include +#ifdef Q_CC_GNU +#include +#endif + +//////////////////////////////////////////////////////////////////////////////// +// AST Dump +//////////////////////////////////////////////////////////////////////////////// +class Dump: protected JavaScript::AST::Visitor +{ + std::ostream &out; + int depth; + +public: + Dump(std::ostream &out) + : out(out), depth(-1) + { } + + void operator()(JavaScript::AST::Node *node) + { JavaScript::AST::Node::acceptChild(node, this); } + +protected: + virtual bool preVisit(JavaScript::AST::Node *node) + { + const char *name = typeid(*node).name(); +#ifdef Q_CC_GNU + name = abi::__cxa_demangle(name, 0, 0, 0) + 17; +#endif + std::cout << std::string(++depth, ' ') << name << std::endl; + return true; + } + + virtual void postVisit(JavaScript::AST::Node *) + { + --depth; + } +}; +#endif + // Update the init instruction with final data, and optimize some simple // bindings int QmlCompiler::finalizeComponent(int patch) diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index 3db8d92..c67c220 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -820,15 +820,9 @@ QmlExpressionPrivate::QmlExpressionPrivate(QmlExpression *b, void *expr, QmlRefC { } -QmlExpressionPrivate::QmlExpressionPrivate(QmlExpression *b, const QString &expr, bool ssecompile) +QmlExpressionPrivate::QmlExpressionPrivate(QmlExpression *b, const QString &expr) : q(b), ctxt(0), expression(expr), sseData(0), proxy(0), me(0), trackChange(true), line(-1), id(0), log(0) { - if (ssecompile) { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer pt; -#endif - sse.compile(expr.toLatin1()); - } } QmlExpressionPrivate::~QmlExpressionPrivate() @@ -863,19 +857,6 @@ QmlExpression::QmlExpression(QmlContext *ctxt, void *expr, d->me = me; } -/*! \internal */ -QmlExpression::QmlExpression(QmlContext *ctxt, const QString &expr, - QObject *me, bool ssecompile) -: d(new QmlExpressionPrivate(this, expr, ssecompile)) -{ - d->ctxt = ctxt; - if(ctxt && ctxt->engine()) - d->id = ctxt->engine()->d_func()->getUniqueId(); - if(ctxt) - ctxt->d_func()->childExpressions.insert(this); - d->me = me; -} - /*! Create a QmlExpression object. @@ -885,7 +866,7 @@ QmlExpression::QmlExpression(QmlContext *ctxt, const QString &expr, */ QmlExpression::QmlExpression(QmlContext *ctxt, const QString &expression, QObject *scope) -: d(new QmlExpressionPrivate(this, expression, true)) +: d(new QmlExpressionPrivate(this, expression)) { d->ctxt = ctxt; if(ctxt && ctxt->engine()) @@ -956,10 +937,7 @@ void QmlExpression::setExpression(const QString &expression) d->expression = expression; - if (d->expression.isEmpty()) - d->sse.clear(); - else - d->sse.compile(expression.toLatin1()); + d->sse.clear(); } /*! @@ -1245,13 +1223,7 @@ QmlExpressionObject::QmlExpressionObject(QObject *parent) the expression's execution. */ QmlExpressionObject::QmlExpressionObject(QmlContext *ctxt, const QString &expression, QObject *scope, QObject *parent) -: QObject(parent), QmlExpression(ctxt, expression, scope, true) -{ -} - -/*! \internal */ -QmlExpressionObject::QmlExpressionObject(QmlContext *ctxt, const QString &expr, QObject *scope, bool sse) -: QmlExpression(ctxt, expr, scope, sse) +: QObject(parent), QmlExpression(ctxt, expression, scope) { } diff --git a/src/declarative/qml/qmlengine_p.h b/src/declarative/qml/qmlengine_p.h index 0dc4736..89b0a4a 100644 --- a/src/declarative/qml/qmlengine_p.h +++ b/src/declarative/qml/qmlengine_p.h @@ -53,7 +53,7 @@ #include #include #include -#include +#include #include #include #include @@ -265,7 +265,7 @@ class QmlExpressionPrivate { public: QmlExpressionPrivate(QmlExpression *); - QmlExpressionPrivate(QmlExpression *, const QString &expr, bool); + QmlExpressionPrivate(QmlExpression *, const QString &expr); QmlExpressionPrivate(QmlExpression *, void *expr, QmlRefCount *rc); ~QmlExpressionPrivate(); diff --git a/src/declarative/qml/qmlexpression.h b/src/declarative/qml/qmlexpression.h index ea3b093..651fd9c 100644 --- a/src/declarative/qml/qmlexpression.h +++ b/src/declarative/qml/qmlexpression.h @@ -62,7 +62,6 @@ class Q_DECLARATIVE_EXPORT QmlExpression public: QmlExpression(); QmlExpression(QmlContext *, const QString &, QObject *); - QmlExpression(QmlContext *, const QString &, QObject *, bool); QmlExpression(QmlContext *, void *, QmlRefCount *rc, QObject *me); virtual ~QmlExpression(); @@ -101,7 +100,6 @@ class Q_DECLARATIVE_EXPORT QmlExpressionObject : public QObject, public: QmlExpressionObject(QObject *parent = 0); QmlExpressionObject(QmlContext *, const QString &, QObject *scope, QObject *parent = 0); - QmlExpressionObject(QmlContext *, const QString &, QObject *scope, bool); QmlExpressionObject(QmlContext *, void *, QmlRefCount *, QObject *); public Q_SLOTS: diff --git a/src/declarative/qml/qmlparser.cpp b/src/declarative/qml/qmlparser.cpp index 5c2a69f..f262b5d 100644 --- a/src/declarative/qml/qmlparser.cpp +++ b/src/declarative/qml/qmlparser.cpp @@ -52,7 +52,6 @@ #include #include "private/qmlcomponent_p.h" #include -#include #include "private/qmetaobjectbuilder_p.h" #include #include diff --git a/src/declarative/qml/script/generator/generator.pro b/src/declarative/qml/script/generator/generator.pro deleted file mode 100644 index 1b2a4c7..0000000 --- a/src/declarative/qml/script/generator/generator.pro +++ /dev/null @@ -1,11 +0,0 @@ -###################################################################### -# Automatically generated by qmake (2.01a) Mon Apr 2 20:15:52 2007 -###################################################################### - -TEMPLATE = app -TARGET = -DEPENDPATH += . -INCLUDEPATH += . - -# Input -SOURCES += main.cpp diff --git a/src/declarative/qml/script/generator/main.cpp b/src/declarative/qml/script/generator/main.cpp deleted file mode 100644 index a841cbc..0000000 --- a/src/declarative/qml/script/generator/main.cpp +++ /dev/null @@ -1,135 +0,0 @@ -/**************************************************************************** -** -** This file is part of the $PACKAGE_NAME$. -** -** Copyright (C) $THISYEAR$ $COMPANY_NAME$. -** -** $QT_EXTENDED_DUAL_LICENSE$ -** -****************************************************************************/ - -#include -#include - - -QT_BEGIN_NAMESPACE -struct Keyword { - const char *lexem; - const char *token; -}; - -struct State -{ - State(const char* token) : token(token) - { - ::memset(next, 0, sizeof(next)); - } - State(const State &other) : token(other.token) - { - ::memcpy(next, other.next, sizeof(next)); - } - State &operator=(const State &other) - { - token = other.token; - ::memcpy(next, other.next, sizeof(next)); - return *this; - } - - QByteArray token; - int next[128]; -}; - -Keyword keywords[] = -{ - {"<", "LANGLE" }, - {">", "RANGLE" }, - {"+", "PLUS" }, - {"-", "MINUS" }, - {"*", "STAR" }, - {"==", "EQUALS" }, - {"&&", "AND" }, - {".", "DOT"}, - {"true", "TOKEN_TRUE"}, - {"false", "TOKEN_FALSE"}, - {" ", "WHITESPACE"}, - {"\t", "WHITESPACE"}, - {0, 0} -}; - -bool is_character(char s) -{ - return (s >= 'a' && s <= 'z') || - (s >= 'A' && s <= 'Z') || - (s >= '0' && s <= '9') || - s == '_'; -} - -void newState(QList &states, const char *token, const char *lexem) -{ - int state = 0; - bool character = is_character(*lexem); - - while(*lexem) { - int next = states[state].next[(int)*lexem]; - - if (!next) { - next = states.size(); - states += State(character?"CHARACTER":"INCOMPLETE"); - states[state].next[(int)*lexem] = next; - } - - state = next; - ++lexem; - character = character && is_character(*lexem); - } - - states[state].token = token; -} - -void newState(QList &states, const char *token, char lexem) -{ - int next = states[0].next[(int)lexem]; - if (!next) { - next = states.size(); - states += State(token); - states[0].next[(int)lexem] = next; - } else { - states[next].token = token; - } -} - -int main() -{ - QList states; - states += State("NOTOKEN"); - - // identifiers - for (int cc = 'a'; cc <= 'z'; ++cc) - newState(states, "CHARACTER", cc); - for (int cc = 'A'; cc <= 'Z'; ++cc) - newState(states, "CHARACTER", cc); - newState(states, "CHARACTER", '_'); - - // add digits - for (int cc = '0'; cc <= '9'; ++cc) - newState(states, "DIGIT", cc); - - // keywords - for (int ii = 0; keywords[ii].lexem; ++ii) - newState(states, keywords[ii].token, keywords[ii].lexem); - - ::printf("static const struct\n{\n" - " Token token;\n" - " char next[128];\n" - "} keywords[] = {\n"); - - for (int ii = 0; ii < states.size(); ++ii) { - printf("%s { %s, { ", ii?",\n":"", states[ii].token.data()); - for (int jj = 0; jj < 128; jj++) - printf("%s%d", jj?",":"", states[ii].next[jj]); - printf(" } }"); - } - - printf("\n};\n"); -} -QT_END_NAMESPACE diff --git a/src/declarative/qml/script/instructions.h b/src/declarative/qml/script/instructions.h deleted file mode 100644 index a21cbce..0000000 --- a/src/declarative/qml/script/instructions.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef _INSTRUCTIONS_H_ -#define _INSTRUCTIONS_H_ - -struct ScriptInstruction { - enum { - Load, // fetch - Fetch, // fetch - - Add, // NA - Subtract, // NA - Multiply, // NA - Equals, // NA - And, // NA - - Int, // integer - Bool, // boolean - } type; - - union { - struct { - int idx; - } fetch; - struct { - int value; - } integer; - struct { - bool value; - } boolean; - }; -}; - -#endif // _INSTRUCTIONS_H_ diff --git a/src/declarative/qml/script/keywords.cpp b/src/declarative/qml/script/keywords.cpp deleted file mode 100644 index 4cde65b..0000000 --- a/src/declarative/qml/script/keywords.cpp +++ /dev/null @@ -1,89 +0,0 @@ -static const struct -{ - Token token; - char next[128]; -} keywords[] = { - { NOTOKEN, { 0,0,0,0,0,0,0,0,0,82,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,81,0,0,0,0,0,71,0,0,0,68,66,0,67,73,0,54,55,56,57,58,59,60,61,62,63,0,0,64,69,65,0,0,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,0,0,0,0,53,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,77,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,74,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DIGIT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { LANGLE, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { RANGLE, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { PLUS, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { MINUS, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { STAR, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { INCOMPLETE, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,70,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { EQUALS, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { INCOMPLETE, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,72,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { AND, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { DOT, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,75,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,76,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { TOKEN_TRUE, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,78,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,79,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { CHARACTER, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,80,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { TOKEN_FALSE, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { WHITESPACE, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } }, - { WHITESPACE, { 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 } } -}; diff --git a/src/declarative/qml/script/lexer.cpp b/src/declarative/qml/script/lexer.cpp deleted file mode 100644 index d3ef935..0000000 --- a/src/declarative/qml/script/lexer.cpp +++ /dev/null @@ -1,139 +0,0 @@ -/**************************************************************************** -** -** This file is part of the $PACKAGE_NAME$. -** -** Copyright (C) $THISYEAR$ $COMPANY_NAME$. -** -** $QT_EXTENDED_DUAL_LICENSE$ -** -****************************************************************************/ - -#include -#include "lexer.h" -#include "keywords.cpp" -#include - - -QT_BEGIN_NAMESPACE -QList tokenize(const char *text) -{ - QList rv; - - int lineNo = 0; - int charNo = 0; - int state = 0; - int tokenStart = 0; - bool other = false; - - const char *textprog = text; - - bool done = false; - while (!done) { - char textchar = *textprog; - done = !textchar; - - if (other) { - if (keywords[state].next[(int)textchar]) { - - // Do other token - LexerToken token; - token.token = OTHER; - token.start = tokenStart; - token.end = textprog - text - 1; - token.line = lineNo + 1; - token.offset = charNo - (token.end - token.start); - tokenStart = token.end + 1; - rv.append(token); - other = false; - - } else { - goto continue_loop; - } - } - - if (keywords[state].next[(int)textchar]) { - - state = keywords[state].next[(int)textchar]; - - } else if (0 == state || - keywords[state].token == INCOMPLETE) { - - other = true; - if (keywords[state].token == INCOMPLETE) { - state = 0; - continue; - } - - } else { - - // Token completed - Token tokenType = keywords[state].token; - bool tokenCollapsed = false; - if (tokenType == CHARACTER || - tokenType == DIGIT || - tokenType == WHITESPACE) { - - Token lastTokenType = - rv.isEmpty()?NOTOKEN:rv.last().token; - if (tokenType == lastTokenType) { - - rv.last().end = textprog - text - 1; - tokenStart = rv.last().end + 1; - - tokenCollapsed = true; - } - } - - if (!tokenCollapsed) { - LexerToken token; - token.token = keywords[state].token; - token.start = tokenStart; - token.end = textprog - text - 1; - token.line = lineNo + 1; - token.offset = charNo - (token.end - token.start); - tokenStart = token.end + 1; - rv.append(token); - } - - state = keywords[0].next[(int)textchar]; - if (0 == state) - other = true; - } - -continue_loop: - // Reset error reporting variables - if (textchar == '\n') { - ++lineNo; - charNo = 0; - } else { - charNo++; - } - - // Increment ptrs - ++textprog; - } - - if (other && ((textprog - text - 1) != tokenStart)) { - // Do other token - LexerToken token; - token.token = OTHER; - token.start = tokenStart; - token.end = textprog - text - 1; - token.line = lineNo + 1; - token.offset = charNo - (token.end - token.start); - tokenStart = token.end + 1; - rv.append(token); - other = false; - } - return rv; -} - -void dumpTokens(const char *text, const QList &tokens) -{ - for (int ii = 0; ii < tokens.count(); ++ii) { - QByteArray ba(text + tokens.at(ii).start, tokens.at(ii).end - tokens.at(ii).start + 1); - qWarning() << tokens.at(ii).line << ":" << tokens.at(ii).offset << tokenToString(tokens.at(ii).token) << "(" << tokens.at(ii).start << "-" << tokens.at(ii).end << ")" << ba; - } -} - -QT_END_NAMESPACE diff --git a/src/declarative/qml/script/lexer.h b/src/declarative/qml/script/lexer.h deleted file mode 100644 index 9de4afd..0000000 --- a/src/declarative/qml/script/lexer.h +++ /dev/null @@ -1,54 +0,0 @@ -/**************************************************************************** -** -** This file is part of the $PACKAGE_NAME$. -** -** Copyright (C) $THISYEAR$ $COMPANY_NAME$. -** -** $QT_EXTENDED_DUAL_LICENSE$ -** -****************************************************************************/ - -#ifndef LEXER_H -#define LEXER_H - -#include -#include "tokens.h" - - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) -struct LexerToken -{ - LexerToken() : token(NOTOKEN), start(-1), end(-1), line(-1), offset(-1) {} - LexerToken(const LexerToken &other) : token(other.token), - start(other.start), - end(other.end), - line(other.line), - offset(other.offset) {} - LexerToken &operator=(const LexerToken &other) { - token = other.token; - start = other.start; - end = other.end; - line = other.line; - offset = other.offset; - return *this; - } - - Token token; - int start; - int end; - int line; - int offset; -}; - -QList tokenize(const char *text); -void dumpTokens(const char *text, const QList &tokens); - - -QT_END_NAMESPACE - -QT_END_HEADER -#endif diff --git a/src/declarative/qml/script/qmlbasicscript.cpp b/src/declarative/qml/script/qmlbasicscript.cpp deleted file mode 100644 index 37a6678..0000000 --- a/src/declarative/qml/script/qmlbasicscript.cpp +++ /dev/null @@ -1,921 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the $MODULE$ of the Qt Toolkit. -** -** $TROLLTECH_DUAL_LICENSE$ -** -****************************************************************************/ - -#include "qmlbasicscript.h" -#include "qmlbasicscript_p.h" -#include "lexer.h" -#include -#include -#include -#include -#include -#include -#include - - -QT_BEGIN_NAMESPACE -DEFINE_BOOL_CONFIG_OPTION(scriptWarnings, QML_SCRIPT_WARNINGS); - -class QmlBasicScriptPrivate -{ -public: - enum Flags { OwnData = 0x00000001 }; - - int size; - int stateSize; - int instructionCount; - int exprLen; - - ScriptInstruction *instructions() const { return (ScriptInstruction *)((char *)this + sizeof(QmlBasicScriptPrivate)); } - - const char *expr() const - { - return (const char *)(instructions() + instructionCount); - } - - const char *data() const - { - return (const char *)(instructions() + instructionCount) + exprLen + 1; - } - - static unsigned int alignRound(int s) - { - if (s % 4) - s += 4 - (s % 4); - return s; - } -}; - -QDebug operator<<(QDebug lhs, const QmlBasicScriptNodeCache &rhs) -{ - switch(rhs.type) { - case QmlBasicScriptNodeCache::Invalid: - lhs << "Invalid"; - break; - case QmlBasicScriptNodeCache::Core: - lhs << "Core" << rhs.object << rhs.core; - break; - case QmlBasicScriptNodeCache::Attached: - lhs << "Attached" << rhs.object << rhs.attached; - break; - case QmlBasicScriptNodeCache::Signal: - lhs << "Signal" << rhs.object << rhs.core; - break; - case QmlBasicScriptNodeCache::SignalProperty: - lhs << "SignalProperty" << rhs.object << rhs.core; - break; - case QmlBasicScriptNodeCache::Variant: - lhs << "Variant" << rhs.context; - break; - } - - return lhs; -} - -void QmlBasicScriptNodeCache::clear() -{ - object = 0; - metaObject = 0; - type = Invalid; -} - -static QVariant toObjectOrVariant(const QVariant &v) -{ - switch(v.type()) { - case QVariant::String: - case QVariant::UInt: - case QVariant::Int: - case 135: - case QVariant::Double: - case QVariant::Color: - case QVariant::Bool: - default: - return v; - case QVariant::UserType: - { - QObject *o = QmlMetaType::toQObject(v); - if (o) - return qVariantFromValue(o); - else - return v; - } - break; - } -} - -static QVariant fetch_value(QObject *o, int idx, int type) -{ - switch(type) { - case QVariant::String: - { - QString val; - void *args[] = { &val, 0 }; - QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); - return QVariant(val); - } - break; - case QVariant::UInt: - { - uint val; - void *args[] = { &val, 0 }; - QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); - return QVariant(val); - } - break; - case QVariant::Int: - { - int val; - void *args[] = { &val, 0 }; - QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); - return QVariant(val); - } - break; - case 135: - { - float val; - void *args[] = { &val, 0 }; - QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); - return QVariant(val); - } - break; - case QVariant::Double: - { - double val; - void *args[] = { &val, 0 }; - QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); - return QVariant(val); - } - break; - case QVariant::Color: - { - QColor val; - void *args[] = { &val, 0 }; - QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); - return QVariant(val); - } - break; - case QVariant::Bool: - { - bool val; - void *args[] = { &val, 0 }; - QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); - return QVariant(val); - } - break; - default: - { - if (QmlMetaType::isObject(type)) { - // NOTE: This assumes a cast to QObject does not alter the - // object pointer - QObject *val = 0; - void *args[] = { &val, 0 }; - QMetaObject::metacall(o, QMetaObject::ReadProperty, idx, args); - return QVariant::fromValue(val); - } else { - QVariant var = o->metaObject()->property(idx).read(o); - if (QmlMetaType::isObject(var.userType())) { - QObject *obj = 0; - obj = *(QObject **)var.data(); - var = QVariant::fromValue(obj); - } - return var; - } - } - break; - }; -} - -QVariant QmlBasicScriptNodeCache::value(const char *name) const -{ - //QFxPerfTimer pt; - switch(type) { - case Invalid: - break; - case Core: - return fetch_value(object, core, coreType); - break; - case Attached: - return qVariantFromValue(static_cast(attached)); - break; - case Signal: - // XXX - Q_ASSERT(!"Not implemented"); - break; - case SignalProperty: - break; - case Variant: - return context->propertyValues[contextIndex]; - }; - return QVariant(); -} - -struct QmlBasicScriptCompiler -{ - QmlBasicScriptCompiler() - : script(0), stateSize(0), src(0), idx(0) {} - QmlBasicScript *script; - QList tokens; - int stateSize; - const char *src; - int idx; - - bool compile(); - bool compileExpr(); - - bool parseFetch(); - bool parseName(); - bool parseConstant(); - void skipWhitespace(); - - QByteArray data; - QList bytecode; - - QByteArray string(int, int); - Token token() const; - bool atEnd() const; - void adv(); - int index() const; -}; - -/*! - \internal - \class QmlBasicScript - \brief The QmlBasicScript class provides a fast implementation of a limited subset of JavaScript bindings. - - QmlBasicScript instances are used to accelerate binding. Instead of using - the slower, fully fledged JavaScript engine, many simple bindings can be - evaluated using the QmlBasicScript engine. - - To see if the QmlBasicScript engine can handle a binding, call compile() - and check the return value, or isValid() afterwards. - - To evaluate the binding, the QmlBasicScript instance needs some memory in - which to cache state. This may be allocated by calling newScriptState() - and destroyed by calling deleteScriptState(). The state data is then passed - to the run() method when evaluating the binding. - - To further accelerate binding, QmlBasicScript can return a precompiled - version of itself that can be saved for future use. Call compileData() to - get an opaque pointer to the compiled state, and compileDataSize() for the - size of this data in bytes. This data can be saved and passed to future - instances of the QmlBasicScript constructor. The initial copy of compile - data is owned by the QmlBindScript instance on which compile() was called. -*/ - -/*! - Create a new QmlBasicScript instance. -*/ -QmlBasicScript::QmlBasicScript() -: flags(0), d(0), rc(0) -{ -} - -/*! - Create a new QmlBasicScript instance from saved \a data. - - \a data \b must be data previously acquired from calling compileData() on a - previously created QmlBasicScript instance. Any other data will almost - certainly cause the QmlBasicScript engine to crash. - - \a data must continue to be valid throughout the QmlBasicScript instance - life. It does not assume ownership of the memory. - - If \a owner is set, it is referenced on creation and dereferenced on - destruction of this instance. -*/ -QmlBasicScript::QmlBasicScript(const char *data, QmlRefCount *owner) -: flags(0), d((QmlBasicScriptPrivate *)data), rc(owner) -{ - if (rc) rc->addref(); -} - -/*! - Return the text of the script expression. - */ -QByteArray QmlBasicScript::expression() const -{ - if (!d) - return QByteArray(); - else - return QByteArray(d->expr()); -} - -/*! - Destroy the script instance. -*/ -QmlBasicScript::~QmlBasicScript() -{ - if (flags & QmlBasicScriptPrivate::OwnData) - free(d); - if (rc) rc->release(); - d = 0; - rc = 0; -} - -/*! - Clear this script. The object will then be in its initial state, as though - it were freshly constructed with default constructor. -*/ -void QmlBasicScript::clear() -{ - if (flags & QmlBasicScriptPrivate::OwnData) - free(d); - if (rc) rc->release(); - d = 0; - rc = 0; - flags = 0; -} - -/*! - Return the script state memory for this script instance. This memory should - only be destroyed by calling deleteScriptState(). - */ -void *QmlBasicScript::newScriptState() -{ - if (!d) { - return 0; - } else { - void *rv = ::malloc(d->stateSize * sizeof(QmlBasicScriptNodeCache)); - ::memset(rv, 0, d->stateSize * sizeof(QmlBasicScriptNodeCache)); - return rv; - } -} - -/*! - Delete the \a data previously allocated by newScriptState(). - */ -void QmlBasicScript::deleteScriptState(void *data) -{ - if (!data) return; - Q_ASSERT(d); - clearCache(data); - free(data); -} - -/*! - Dump the script instructions to stderr for debugging. - */ -void QmlBasicScript::dump() -{ - if (!d) - return; - - qWarning() << d->instructionCount << "instructions:"; - const char *data = d->data(); - for (int ii = 0; ii < d->instructionCount; ++ii) { - const ScriptInstruction &instr = d->instructions()[ii]; - - switch(instr.type) { - case ScriptInstruction::Load: - qWarning().nospace() << "LOAD\t\t" << instr.fetch.idx << "\t\t" - << QByteArray(data + instr.fetch.idx); - break; - case ScriptInstruction::Fetch: - qWarning().nospace() << "FETCH\t\t" << instr.fetch.idx << "\t\t" - << QByteArray(data + instr.fetch.idx); - break; - case ScriptInstruction::Add: - qWarning().nospace() << "ADD"; - break; - case ScriptInstruction::Subtract: - qWarning().nospace() << "SUBTRACT"; - break; - case ScriptInstruction::Multiply: - qWarning().nospace() << "MULTIPLY"; - break; - case ScriptInstruction::Equals: - qWarning().nospace() << "EQUALS"; - break; - case ScriptInstruction::Int: - qWarning().nospace() << "INT\t\t" << instr.integer.value; - break; - case ScriptInstruction::Bool: - qWarning().nospace() << "BOOL\t\t" << instr.boolean.value; - break; - default: - qWarning().nospace() << "UNKNOWN"; - break; - } - } -} - -/*! - Return true if this is a valid script binding, otherwise returns false. - */ -bool QmlBasicScript::isValid() const -{ - return d != 0; -} - -/*! - Compile \a src and return true if the compilation is successful, otherwise - returns false. - */ -bool QmlBasicScript::compile(const QByteArray &src) -{ - bool rv = compile(src.constData()); - return rv; -} - -/*! - \overload - - Compile \a src and return true if the compilation is successful, otherwise - returns false. - */ -bool QmlBasicScript::compile(const char *src) -{ - if (!src) return false; - - QmlBasicScriptCompiler bsc; - bsc.script = this; - bsc.tokens = tokenize(src); - bsc.src = src; - // dumpTokens(src, bsc.tokens); - - if (d) { - if (flags & QmlBasicScriptPrivate::OwnData) - free(d); - d = 0; - flags = 0; - } - - if (bsc.compile()) { - int len = ::strlen(src); - flags = QmlBasicScriptPrivate::OwnData; - int size = sizeof(QmlBasicScriptPrivate) + - bsc.bytecode.count() * sizeof(ScriptInstruction) + - QmlBasicScriptPrivate::alignRound(bsc.data.count() + len + 1); - d = (QmlBasicScriptPrivate *) malloc(size); - d->size = size; - d->stateSize = bsc.stateSize; - d->instructionCount = bsc.bytecode.count(); - d->exprLen = len; - ::memcpy((char *)d->expr(), src, len + 1); - for (int ii = 0; ii < d->instructionCount; ++ii) - d->instructions()[ii] = bsc.bytecode.at(ii); - ::memcpy((char *)d->data(), bsc.data.constData(), bsc.data.count()); - } - - return d != 0; -} - -void QmlBasicScriptCompiler::skipWhitespace() -{ - while(idx < tokens.count() && tokens.at(idx).token == WHITESPACE) - ++idx; -} - -bool QmlBasicScriptCompiler::compile() -{ - if (!compileExpr()) - return false; - - skipWhitespace(); - - if (atEnd()) - return true; - - int t = token(); - if (t != AND) - return false; - - adv(); - skipWhitespace(); - if (!compileExpr()) - return false; - - ScriptInstruction instr; - instr.type = ScriptInstruction::And; - bytecode.append(instr); - - skipWhitespace(); - - return atEnd(); -} - -bool QmlBasicScriptCompiler::compileExpr() -{ - /* - EXPRESSION := [|] - */ - - if (!parseName()) - return false; - - skipWhitespace(); - - if (atEnd()) - return true; - - int t = token(); - switch(t) { - case PLUS: - case MINUS: - /* - case LANGLE: - case RANGLE: - */ - case STAR: - case EQUALS: - break; - default: - return true; - } - adv(); - - skipWhitespace(); - - if (!parseConstant() && - !parseName()) - return false; - - ScriptInstruction instr; - switch(t) { - case PLUS: - instr.type = ScriptInstruction::Add; - break; - case MINUS: - instr.type = ScriptInstruction::Subtract; - break; - case STAR: - instr.type = ScriptInstruction::Multiply; - break; - case EQUALS: - instr.type = ScriptInstruction::Equals; - break; - default: - break; - } - bytecode.append(instr); - - skipWhitespace(); - - return true; -} - -bool QmlBasicScriptCompiler::parseName() -{ - skipWhitespace(); - - bool named = false; - bool seenchar = false; - bool seendot = false; - int namestart = -1; - bool pushed = false; - while(!atEnd()) { - int t = token(); - if (t == CHARACTER) { - named = true; - seendot = false; - seenchar = true; - namestart = index(); - adv(); - } else if (t == DIGIT) { - if (!seenchar) break; - adv(); - } else if (t == DOT) { - seendot = true; - if (namestart == -1) - break; - - seenchar = false; - QByteArray name = string(namestart, index() - 1); - int nref = data.count(); - data.append(name); - data.append('\0'); - ScriptInstruction instr; - if (pushed) - instr.type = ScriptInstruction::Fetch; - else - instr.type = ScriptInstruction::Load; - pushed = true; - instr.fetch.idx = nref; - bytecode.append(instr); - ++stateSize; - namestart = -1; - adv(); - } else { - break; - } - } - - if (namestart != -1) { - QByteArray name = string(namestart, index() - 1); - int nref = data.count(); - data.append(name); - data.append('\0'); - ScriptInstruction instr; - if (pushed) - instr.type = ScriptInstruction::Fetch; - else - instr.type = ScriptInstruction::Load; - pushed = true; - instr.fetch.idx = nref; - bytecode.append(instr); - ++stateSize; - } - - if (seendot) - return false; - else - return named; -} - -bool QmlBasicScriptCompiler::parseConstant() -{ - switch(token()) { - case DIGIT: - { - ScriptInstruction instr; - instr.type = ScriptInstruction::Int; - instr.integer.value = string(index(), index()).toUInt(); - bytecode.append(instr); - adv(); - } - break; - case TOKEN_TRUE: - case TOKEN_FALSE: - { - ScriptInstruction instr; - instr.type = ScriptInstruction::Bool; - instr.boolean.value = (token() == TOKEN_TRUE); - bytecode.append(instr); - adv(); - } - break; - - default: - return false; - } - - return true; -} - -bool QmlBasicScriptCompiler::atEnd() const -{ - return idx >= tokens.count(); -} - -Token QmlBasicScriptCompiler::token() const -{ - return tokens.at(idx).token; -} - -void QmlBasicScriptCompiler::adv() -{ - ++idx; -} - -int QmlBasicScriptCompiler::index() const -{ - return idx; -} - -QByteArray QmlBasicScriptCompiler::string(int from, int to) -{ - QByteArray rv; - for (int ii = from; ii <= to; ++ii) { - const LexerToken &token = tokens.at(ii); - rv.append(QByteArray(src + token.start, token.end - token.start + 1)); - } - return rv; -} - -/*! - \internal -*/ -void QmlBasicScript::clearCache(void *voidCache) -{ - QmlBasicScriptNodeCache *dataCache = - reinterpret_cast(voidCache); - - for (int ii = 0; ii < d->stateSize; ++ii) { - if (!dataCache[ii].isCore() && !dataCache[ii].isVariant() && - dataCache[ii].object) { - QMetaObject::removeGuard(&dataCache[ii].object); - dataCache[ii].object = 0; - } - dataCache[ii].clear(); - } -} - -void QmlBasicScript::guard(QmlBasicScriptNodeCache &n) -{ - if (n.object) { - if (n.isVariant()) { - } else if (n.isCore()) { - n.metaObject = - n.object->metaObject(); - } else { - QMetaObject::addGuard(&n.object); - } - } -} - -bool QmlBasicScript::valid(QmlBasicScriptNodeCache &n, QObject *obj) -{ - return n.object == obj && - (!n.isCore() || obj->metaObject() == n.metaObject); -} - - -/*! - \enum QmlBasicScript::CacheState - \value NoChange The query has not change. Any previous monitoring is still - valid. - \value Incremental The query has been incrementally changed. Any previous - monitoring is still valid, but needs to have the fresh properties added to - it. - \value Reset The entire query has been reset from the beginning. Any previous - monitoring is now invalid. -*/ - -/*! - Run the script in \a context and return the result. \a voidCache should - contain state memory previously acquired from newScript. - */ -QVariant QmlBasicScript::run(QmlContext *context, void *voidCache, CacheState *cached) -{ - if (!isValid()) - return QVariant(); - - QmlBasicScriptNodeCache *dataCache = - reinterpret_cast(voidCache); - int dataCacheItem; - QStack stack; - - bool resetting = false; - bool hasReset = false; - - const char *data = d->data(); - - if (dataCache[0].type == QmlBasicScriptNodeCache::Invalid) { - resetting = true; - hasReset = true; - } - - CacheState state = NoChange; - - dataCacheItem = 0; - for (int idx = 0; idx < d->instructionCount; ++idx) { - const ScriptInstruction &instr = d->instructions()[idx]; - - switch(instr.type) { - case ScriptInstruction::Load: // either an object or a property - case ScriptInstruction::Fetch: // can only be a property - { - const char *id = data + instr.fetch.idx; - QmlBasicScriptNodeCache &n = dataCache[dataCacheItem]; - - if (instr.type == ScriptInstruction::Load) { - - if (n.type == QmlBasicScriptNodeCache::Invalid) { - context->engine()->d_func()->loadCache(n, QLatin1String(id), static_cast(context->d_ptr)); - state = Incremental; - } - - if(!n.isValid()) - qWarning("ReferenceError: %s is not defined", id); - - } else { // instr.type == ScriptInstruction::Fetch - - QVariant o = stack.pop(); - QObject *obj = qvariant_cast(o); - if (!obj) { - if (n.type == QmlBasicScriptNodeCache::Invalid) { - if (scriptWarnings()) - qWarning() << "QmlBasicScript: Unable to convert" << o; - *cached = state; - return QVariant(); - } else { - clearCache(dataCache); - *cached = Reset; - CacheState dummy; - return run(context, voidCache, &dummy); - } - } else if (n.type == QmlBasicScriptNodeCache::Invalid) { - context->engine()->d_func()->fetchCache(n, QLatin1String(id), obj); - guard(n); - state = Incremental; - } else if (!valid(n, obj)) { - clearCache(dataCache); - *cached = Reset; - CacheState dummy; - return run(context, voidCache, &dummy); - } - - } - - QVariant var = n.value(id); - stack.push(var); - ++dataCacheItem; - } - break; - case ScriptInstruction::Int: - stack.push(QVariant(instr.integer.value)); - break; - case ScriptInstruction::Bool: - stack.push(QVariant(instr.boolean.value)); - break; - case ScriptInstruction::Add: - { - QVariant rhs = stack.pop(); - QVariant lhs = stack.pop(); - - stack.push(rhs.toDouble() + lhs.toDouble()); - } - break; - case ScriptInstruction::Subtract: - { - QVariant rhs = stack.pop(); - QVariant lhs = stack.pop(); - - stack.push(lhs.toDouble() - rhs.toDouble()); - } - break; - case ScriptInstruction::Multiply: - { - QVariant rhs = stack.pop(); - QVariant lhs = stack.pop(); - - stack.push(rhs.toDouble() * lhs.toDouble()); - } - break; - case ScriptInstruction::Equals: - { - QVariant rhs = stack.pop(); - QVariant lhs = stack.pop(); - - stack.push(rhs == lhs); - } - break; - case ScriptInstruction::And: - { - QVariant rhs = stack.pop(); - QVariant lhs = stack.pop(); - - stack.push(rhs.toBool() && lhs.toBool()); - } - break; - default: - break; - } - } - - *cached = state; - - if (stack.isEmpty()) - return QVariant(); - else - return stack.top(); -} - -/*! - Return a pointer to the script's compile data, or null if there is no data. - */ -const char *QmlBasicScript::compileData() const -{ - return (const char *)d; -} - -/*! - Return the size of the script's compile data, or zero if there is no data. - The size will always be a multiple of 4. - */ -unsigned int QmlBasicScript::compileDataSize() const -{ - if (d) - return d->size; - else - return 0; -} - -bool QmlBasicScript::isSingleLoad() const -{ - if (!d) - return false; - - return d->instructionCount == 1 && - d->instructions()[0].type == ScriptInstruction::Load; -} - -QByteArray QmlBasicScript::singleLoadTarget() const -{ - if (!isSingleLoad()) - return QByteArray(); - - // We know there is one instruction and it is a load - return QByteArray(d->data() + d->instructions()[0].fetch.idx); -} - - -QT_END_NAMESPACE diff --git a/src/declarative/qml/script/qmlbasicscript.h b/src/declarative/qml/script/qmlbasicscript.h deleted file mode 100644 index 5ef2148..0000000 --- a/src/declarative/qml/script/qmlbasicscript.h +++ /dev/null @@ -1,76 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the $MODULE$ of the Qt Toolkit. -** -** $TROLLTECH_DUAL_LICENSE$ -** -****************************************************************************/ - -#ifndef QMLBASICSCRIPT_H -#define QMLBASICSCRIPT_H - -#include "instructions.h" -#include -#include -#include "lexer.h" -#include - - -QT_BEGIN_HEADER - -QT_BEGIN_NAMESPACE - -QT_MODULE(Declarative) -class QmlRefCount; -class QmlContext; -class QmlBasicScriptPrivate; -class QmlBasicScriptNodeCache; -class QmlBasicScript -{ -public: - QmlBasicScript(); - QmlBasicScript(const char *, QmlRefCount * = 0); - ~QmlBasicScript(); - - // Always 4-byte aligned - const char *compileData() const; - unsigned int compileDataSize() const; - - QByteArray expression() const; - - bool compile(const QByteArray &); - bool compile(const char *); - bool isValid() const; - - void clear(); - - void dump(); - void *newScriptState(); - void deleteScriptState(void *); - - enum CacheState { NoChange, Incremental, Reset }; - QVariant run(QmlContext *, void *, CacheState *); - - // Optimization opportunities - bool isSingleLoad() const; - QByteArray singleLoadTarget() const; - -private: - int flags; - QmlBasicScriptPrivate *d; - QmlRefCount *rc; - - void clearCache(void *); - void guard(QmlBasicScriptNodeCache &); - bool valid(QmlBasicScriptNodeCache &, QObject *); -}; - -#endif // QMLBASICSCRIPT_H - - -QT_END_NAMESPACE - -QT_END_HEADER diff --git a/src/declarative/qml/script/qmlbasicscript_p.h b/src/declarative/qml/script/qmlbasicscript_p.h deleted file mode 100644 index 3b7e966..0000000 --- a/src/declarative/qml/script/qmlbasicscript_p.h +++ /dev/null @@ -1,53 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the $MODULE$ of the Qt Toolkit. -** -** $TROLLTECH_DUAL_LICENSE$ -** -****************************************************************************/ - -#ifndef QMLBASICSCRIPT_P_H -#define QMLBASICSCRIPT_P_H - -QT_BEGIN_NAMESPACE - -class QObject; -class QmlContextPrivate; -class QDebug; -class QByteArray; - -class QmlBasicScriptNodeCache -{ -public: - QObject *object; - const QMetaObject *metaObject; - enum { Invalid, - Core, - Attached, - Signal, - SignalProperty, - Variant - } type; - union { - int core; - QObject *attached; - QmlContextPrivate *context; - }; - int coreType; - int contextIndex; - - bool isValid() const { return type != Invalid; } - bool isCore() const { return type == Core; } - bool isVariant() const { return type == Variant; } - void clear(); - QVariant value(const char *) const; -}; - -QDebug operator<<(QDebug, const QmlBasicScriptNodeCache &); - -#endif // QMLBASICSCRIPT_P_H - -QT_END_NAMESPACE diff --git a/src/declarative/qml/script/script.pri b/src/declarative/qml/script/script.pri deleted file mode 100644 index 6c43efe..0000000 --- a/src/declarative/qml/script/script.pri +++ /dev/null @@ -1,11 +0,0 @@ -SOURCES += \ - qml/script/tokens.cpp \ - qml/script/lexer.cpp \ - qml/script/qmlbasicscript.cpp - -HEADERS += \ - qml/script/tokens.h \ - qml/script/lexer.h \ - qml/script/instructions.h \ - qml/script/qmlbasicscript.h \ - qml/script/qmlbasicscript_p.h diff --git a/src/declarative/qml/script/tokens.cpp b/src/declarative/qml/script/tokens.cpp deleted file mode 100644 index a2fb100..0000000 --- a/src/declarative/qml/script/tokens.cpp +++ /dev/null @@ -1,43 +0,0 @@ -/**************************************************************************** -** -** This file is part of the $PACKAGE_NAME$. -** -** Copyright (C) $THISYEAR$ $COMPANY_NAME$. -** -** $QT_EXTENDED_DUAL_LICENSE$ -** -****************************************************************************/ - -#include "tokens.h" - - -/*! - Returns a string representation of token \a tok. -*/ -const char *tokenToString(Token tok) -{ - switch(tok) { -#define CASE(X) case X: return #X; - CASE(NOTOKEN) - CASE(INCOMPLETE) - CASE(WHITESPACE) - CASE(LANGLE) - CASE(RANGLE) - CASE(PLUS) - CASE(MINUS) - CASE(STAR) - CASE(EQUALS) - CASE(DOT) - CASE(CHARACTER) - CASE(DIGIT) - CASE(OTHER) - CASE(AND) - case TOKEN_TRUE: - return "TRUE"; - case TOKEN_FALSE: - return "FALSE"; -#undef CASE - } - return 0; -} - diff --git a/src/declarative/qml/script/tokens.h b/src/declarative/qml/script/tokens.h deleted file mode 100644 index 753e40c..0000000 --- a/src/declarative/qml/script/tokens.h +++ /dev/null @@ -1,36 +0,0 @@ -/**************************************************************************** -** -** This file is part of the $PACKAGE_NAME$. -** -** Copyright (C) $THISYEAR$ $COMPANY_NAME$. -** -** $QT_EXTENDED_DUAL_LICENSE$ -** -****************************************************************************/ - -#ifndef TOKENS_H -#define TOKENS_H - -enum Token { - // Lexer tokens - NOTOKEN, - INCOMPLETE, - WHITESPACE, - LANGLE, - RANGLE, - PLUS, - MINUS, - STAR, - EQUALS, - AND, - DOT, - CHARACTER, - DIGIT, - TOKEN_TRUE, - TOKEN_FALSE, - OTHER -}; - -const char *tokenToString(Token); - -#endif -- cgit v0.12 From 8aef511877d460e4d7e75c978142f1ca3bd50451 Mon Sep 17 00:00:00 2001 From: Bill King Date: Thu, 28 May 2009 11:12:26 +1000 Subject: Adds support for linking against iodbc on linux. If unixodbc detection fails, try and link/detect iodbc libraries and link against them. Reviewed-by: Lincoln Ramsay --- config.tests/unix/iodbc/iodbc.cpp | 7 +++++++ config.tests/unix/iodbc/iodbc.pro | 4 ++++ configure | 25 ++++++++++++++++++------- projects.pro | 1 + src/plugins/sqldrivers/odbc/odbc.pro | 8 +------- 5 files changed, 31 insertions(+), 14 deletions(-) create mode 100644 config.tests/unix/iodbc/iodbc.cpp create mode 100644 config.tests/unix/iodbc/iodbc.pro diff --git a/config.tests/unix/iodbc/iodbc.cpp b/config.tests/unix/iodbc/iodbc.cpp new file mode 100644 index 0000000..6b64e12 --- /dev/null +++ b/config.tests/unix/iodbc/iodbc.cpp @@ -0,0 +1,7 @@ +#include +#include + +int main(int, char **) +{ + return 0; +} diff --git a/config.tests/unix/iodbc/iodbc.pro b/config.tests/unix/iodbc/iodbc.pro new file mode 100644 index 0000000..465a9a7 --- /dev/null +++ b/config.tests/unix/iodbc/iodbc.pro @@ -0,0 +1,4 @@ +SOURCES = iodbc.cpp +CONFIG -= qt dylib +mac:CONFIG -= app_bundle +LIBS += -liodbc diff --git a/configure b/configure index 85ce3da..764840e 100755 --- a/configure +++ b/configure @@ -716,6 +716,7 @@ QT_LFLAGS_MYSQL= QT_LFLAGS_MYSQL_R= QT_CFLAGS_SQLITE= QT_LFLAGS_SQLITE= +QT_LFLAGS_ODBC="-lodbc" # flags for libdbus-1 QT_CFLAGS_DBUS= @@ -4431,14 +4432,21 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do CFG_SQL_odbc=plugin fi else - if [ "$CFG_SQL_odbc" != "auto" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then - echo "ODBC support cannot be enabled due to functionality tests!" - echo " Turn on verbose messaging (-v) to $0 to see the final report." - echo " If you believe this message is in error you may use the continue" - echo " switch (-continue) to $0 to continue." - exit 101 + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/iodbc "iODBC" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + QT_LFLAGS_ODBC="-liodbc" + if [ "$CFG_SQL_odbc" = "auto" ]; then + CFG_SQL_odbc=plugin + fi else - CFG_SQL_odbc=no + if [ "$CFG_SQL_odbc" != "auto" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then + echo "ODBC support cannot be enabled due to functionality tests!" + echo " Turn on verbose messaging (-v) to $0 to see the final report." + echo " If you believe this message is in error you may use the continue" + echo " switch (-continue) to $0 to continue." + exit 101 + else + CFG_SQL_odbc=no + fi fi fi fi @@ -6684,6 +6692,9 @@ fi if [ -n "$QT_LFLAGS_SQLITE" ]; then echo "QT_LFLAGS_SQLITE = $QT_LFLAGS_SQLITE" >> "$CACHEFILE.tmp" fi +if [ -n "$QT_LFLAGS_ODBC" ]; then + echo "QT_LFLAGS_ODBC = $QT_LFLAGS_ODBC" >> "$CACHEFILE.tmp" +fi if [ "$QT_EDITION" != "QT_EDITION_OPENSOURCE" ]; then echo "DEFINES *= QT_EDITION=QT_EDITION_DESKTOP" >> "$CACHEFILE.tmp" diff --git a/projects.pro b/projects.pro index 2596c0a..3817792 100644 --- a/projects.pro +++ b/projects.pro @@ -61,6 +61,7 @@ unix { (cd config.tests/unix/mysql_r && $(MAKE) distclean); \ (cd config.tests/unix/nis && $(MAKE) distclean); \ (cd config.tests/unix/nix && $(MAKE) distclean); \ + (cd config.tests/unix/iodbc && $(MAKE) distclean); \ (cd config.tests/unix/odbc && $(MAKE) distclean); \ (cd config.tests/unix/oci && $(MAKE) distclean); \ (cd config.tests/unix/tds && $(MAKE) distclean); \ diff --git a/src/plugins/sqldrivers/odbc/odbc.pro b/src/plugins/sqldrivers/odbc/odbc.pro index 0835ce1..3de8ab2 100644 --- a/src/plugins/sqldrivers/odbc/odbc.pro +++ b/src/plugins/sqldrivers/odbc/odbc.pro @@ -4,15 +4,9 @@ HEADERS = ../../../sql/drivers/odbc/qsql_odbc.h SOURCES = main.cpp \ ../../../sql/drivers/odbc/qsql_odbc.cpp -mac { - !contains( LIBS, .*odbc.* ) { - LIBS *= -liodbc - } -} - unix { !contains( LIBS, .*odbc.* ) { - LIBS *= -lodbc + LIBS *= $$QT_LFLAGS_ODBC } } -- cgit v0.12 From d9e51611a2be361cb75b682c5552846b64e32df3 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Thu, 28 May 2009 13:24:18 +1000 Subject: Remove extra semicolons. --- src/declarative/debugger/qmldebugclient.cpp | 2 +- src/declarative/test/qfxtestobjects.cpp | 24 ++++++++++++------------ src/declarative/test/qfxtestobjects.h | 28 ++++++++++++++-------------- src/declarative/util/qperformancelog.h | 2 +- 4 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/declarative/debugger/qmldebugclient.cpp b/src/declarative/debugger/qmldebugclient.cpp index 85ccf0b..3dacf01 100644 --- a/src/declarative/debugger/qmldebugclient.cpp +++ b/src/declarative/debugger/qmldebugclient.cpp @@ -40,7 +40,7 @@ ****************************************************************************/ #include "qmldebugclient.h" -#include +#include #include #include #include diff --git a/src/declarative/test/qfxtestobjects.cpp b/src/declarative/test/qfxtestobjects.cpp index 5beefd9..12fc7fb 100644 --- a/src/declarative/test/qfxtestobjects.cpp +++ b/src/declarative/test/qfxtestobjects.cpp @@ -47,18 +47,18 @@ QT_BEGIN_NAMESPACE -QML_DECLARE_TYPE(TestObject); -QML_DEFINE_TYPE(TestObject,TestObject); -QML_DECLARE_TYPE(TestFrame); -QML_DEFINE_TYPE(TestFrame,TestFrame); -QML_DECLARE_TYPE(TestFullFrame); -QML_DEFINE_TYPE(TestFullFrame,TestFullFrame); -QML_DECLARE_TYPE(TestMouse); -QML_DEFINE_TYPE(TestMouse,TestMouse); -QML_DECLARE_TYPE(TestKey); -QML_DEFINE_TYPE(TestKey,TestKey); -QML_DECLARE_TYPE(TestLog); -QML_DEFINE_TYPE(TestLog,TestLog); +QML_DECLARE_TYPE(TestObject) +QML_DEFINE_TYPE(TestObject,TestObject) +QML_DECLARE_TYPE(TestFrame) +QML_DEFINE_TYPE(TestFrame,TestFrame) +QML_DECLARE_TYPE(TestFullFrame) +QML_DEFINE_TYPE(TestFullFrame,TestFullFrame) +QML_DECLARE_TYPE(TestMouse) +QML_DEFINE_TYPE(TestMouse,TestMouse) +QML_DECLARE_TYPE(TestKey) +QML_DEFINE_TYPE(TestKey,TestKey) +QML_DECLARE_TYPE(TestLog) +QML_DEFINE_TYPE(TestLog,TestLog) static QString padding(int pad) { diff --git a/src/declarative/test/qfxtestobjects.h b/src/declarative/test/qfxtestobjects.h index de4d94b..80fcfe7 100644 --- a/src/declarative/test/qfxtestobjects.h +++ b/src/declarative/test/qfxtestobjects.h @@ -60,7 +60,7 @@ Q_OBJECT public: TestObject(QObject * = 0); - Q_PROPERTY(int time READ time WRITE setTime NOTIFY dataChanged); + Q_PROPERTY(int time READ time WRITE setTime NOTIFY dataChanged) int time() const; void setTime(int); @@ -78,7 +78,7 @@ Q_OBJECT public: TestFrame(QObject * = 0); - Q_PROPERTY(QString hash READ hash WRITE setHash NOTIFY frameChanged); + Q_PROPERTY(QString hash READ hash WRITE setHash NOTIFY frameChanged) QString hash() const; void setHash(const QString &); @@ -96,7 +96,7 @@ Q_OBJECT public: TestFullFrame(QObject * = 0); - Q_PROPERTY(int frameId READ frameId WRITE setFrameId NOTIFY frameChanged); + Q_PROPERTY(int frameId READ frameId WRITE setFrameId NOTIFY frameChanged) int frameId() const; void setFrameId(int); @@ -114,23 +114,23 @@ Q_OBJECT public: TestMouse(QObject * = 0); - Q_PROPERTY(int type READ type WRITE setType NOTIFY mouseChanged); + Q_PROPERTY(int type READ type WRITE setType NOTIFY mouseChanged) int type() const; void setType(int); - Q_PROPERTY(int button READ button WRITE setButton NOTIFY mouseChanged); + Q_PROPERTY(int button READ button WRITE setButton NOTIFY mouseChanged) int button() const; void setButton(int); - Q_PROPERTY(int buttons READ buttons WRITE setButtons NOTIFY mouseChanged); + Q_PROPERTY(int buttons READ buttons WRITE setButtons NOTIFY mouseChanged) int buttons() const; void setButtons(int); - Q_PROPERTY(QPoint globalPos READ globalPos WRITE setGlobalPos NOTIFY mouseChanged); + Q_PROPERTY(QPoint globalPos READ globalPos WRITE setGlobalPos NOTIFY mouseChanged) QPoint globalPos() const; void setGlobalPos(const QPoint &); - Q_PROPERTY(QPoint pos READ pos WRITE setPos NOTIFY mouseChanged); + Q_PROPERTY(QPoint pos READ pos WRITE setPos NOTIFY mouseChanged) QPoint pos() const; void setPos(const QPoint &); @@ -153,19 +153,19 @@ Q_OBJECT public: TestKey(QObject * = 0); - Q_PROPERTY(int type READ type WRITE setType NOTIFY keyChanged); + Q_PROPERTY(int type READ type WRITE setType NOTIFY keyChanged) int type() const; void setType(int); - Q_PROPERTY(int modifiers READ modifiers WRITE setModifiers NOTIFY keyChanged); + Q_PROPERTY(int modifiers READ modifiers WRITE setModifiers NOTIFY keyChanged) int modifiers() const; void setModifiers(int); - Q_PROPERTY(QString text READ text WRITE setText NOTIFY keyChanged); + Q_PROPERTY(QString text READ text WRITE setText NOTIFY keyChanged) QString text() const; void setText(const QString &); - Q_PROPERTY(int key READ key WRITE setKey NOTIFY keyChanged); + Q_PROPERTY(int key READ key WRITE setKey NOTIFY keyChanged) int key() const; void setKey(int); @@ -187,8 +187,8 @@ Q_OBJECT public: TestLog(QObject * = 0); - Q_CLASSINFO("DefaultProperty", "actions"); - Q_PROPERTY(QList *actions READ qmlActions); + Q_CLASSINFO("DefaultProperty", "actions") + Q_PROPERTY(QList *actions READ qmlActions) QList *qmlActions(); QList &actions(); diff --git a/src/declarative/util/qperformancelog.h b/src/declarative/util/qperformancelog.h index 9d19bbd..6bb9037 100644 --- a/src/declarative/util/qperformancelog.h +++ b/src/declarative/util/qperformancelog.h @@ -64,7 +64,7 @@ namespace QPerformanceLog void displayData(LogData *); void clear(LogData *); #endif -}; +} #ifdef Q_ENABLE_PERFORMANCE_LOG -- cgit v0.12 From 1090d5d1fad890d9f43e87e19277e1f624921d6d Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Thu, 28 May 2009 13:25:31 +1000 Subject: Delay the compilation of bindings until the end This way we have a better understanding of the complete context in which the binding will be executed. --- src/declarative/qml/qmlcompiler.cpp | 175 +++++++++++++++----------------- src/declarative/qml/qmlcompiler_p.h | 14 ++- src/declarative/qml/qmlparser.cpp | 17 ++-- src/declarative/qml/qmlparser_p.h | 3 + src/declarative/qml/qmlscriptparser.cpp | 1 + 5 files changed, 107 insertions(+), 103 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 75d01c2..3029934 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -736,10 +736,8 @@ bool QmlCompiler::compileComponentFromRoot(Object *obj, int ctxt) if (obj) COMPILE_CHECK(compileObject(obj, ctxt)); + finalizeComponent(count); create.createComponent.count = output->bytecode.count() - count; - - int inc = finalizeComponent(count); - create.createComponent.count += inc; compileState = oldComponentCompileState; return true; } @@ -1125,9 +1123,7 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, COMPILE_EXCEPTION("Can only assign one binding to lists"); assignedBinding = true; - COMPILE_CHECK(compileBinding(v->value, prop, ctxt, - obj->metaObject(), - v->location.start.line)); + COMPILE_CHECK(compileBinding(v, prop, ctxt)); v->type = Value::PropertyBinding; } else { COMPILE_EXCEPTION("Cannot assign primitives to lists"); @@ -1296,9 +1292,7 @@ bool QmlCompiler::compilePropertyLiteralAssignment(QmlParser::Property *prop, if (v->value.isScript()) { - COMPILE_CHECK(compileBinding(v->value, prop, ctxt, - obj->metaObject(), - v->location.start.line)); + COMPILE_CHECK(compileBinding(v, prop, ctxt)); v->type = Value::PropertyBinding; @@ -1403,46 +1397,27 @@ bool QmlCompiler::compileDynamicMeta(QmlParser::Object *obj) return true; } -bool QmlCompiler::compileBinding(const QmlParser::Variant &bind, +bool QmlCompiler::compileBinding(QmlParser::Value *value, QmlParser::Property *prop, - int ctxt, const QMetaObject *mo, qint64 line) + int ctxt) { - Q_ASSERT(mo); Q_ASSERT(prop->index); + Q_ASSERT(prop->parent); + Q_ASSERT(prop->parent->metaObject()); - QMetaProperty mp = mo->property(prop->index); + QMetaProperty mp = prop->parent->metaObject()->property(prop->index); if (!mp.isWritable() && !QmlMetaType::isList(prop->type)) COMPILE_EXCEPTION2(prop, "Cannot assign binding to read-only property"); - QmlBasicScript bs; - bs.compile(bind); - - int bref; - if (bs.isValid()) { - bref = output->indexForByteArray(QByteArray(bs.compileData(), bs.compileDataSize())); - } else { - bref = output->indexForString(bind.asScript()); - } - - QmlInstruction assign; - assign.assignBinding.context = ctxt; - assign.line = line; - - if (bs.isValid()) - assign.type = QmlInstruction::StoreCompiledBinding; - else - assign.type = QmlInstruction::StoreBinding; - - assign.assignBinding.property = prop->index; - assign.assignBinding.value = bref; - assign.assignBinding.category = QmlMetaProperty::propertyCategory(mp); BindingReference reference; - reference.expression = bind; + reference.expression = value->value; reference.property = prop; + reference.value = value; reference.instructionIdx = output->bytecode.count(); + reference.bindingContext = ctxt; compileState.bindings << reference; - output->bytecode << assign; + output->bytecode << QmlInstruction();; return true; } @@ -1490,81 +1465,95 @@ protected: // Update the init instruction with final data, and optimize some simple // bindings -int QmlCompiler::finalizeComponent(int patch) +void QmlCompiler::finalizeComponent(int patch) { - int saveCount = 0; - int newInstrs = 0; - for (int ii = 0; ii < compileState.bindings.count(); ++ii) { const BindingReference &binding = compileState.bindings.at(ii); + finalizeBinding(binding); + } - QmlInstruction &instr = output->bytecode[binding.instructionIdx]; - - if (instr.type == QmlInstruction::StoreCompiledBinding) { - QmlBasicScript s(output->datas.at(instr.assignBinding.value).constData()); - - if (s.isSingleLoad()) { - QString slt = QLatin1String(s.singleLoadTarget()); - if (!slt.at(0).isUpper()) - continue; - - if (compileState.ids.contains(slt) && - instr.assignBinding.category == QmlMetaProperty::Object) { + output->bytecode[patch].init.dataSize = compileState.savedObjects;; + output->bytecode[patch].init.bindingsSize = compileState.bindings.count(); + output->bytecode[patch].init.parserStatusSize = + compileState.parserStatusCount; +} - IdReference reference = - compileState.ids[slt]; +void QmlCompiler::finalizeBinding(const BindingReference &binding) +{ + QmlBasicScript bs; + bs.compile(binding.expression); - const QMetaObject *idMo = reference.object->metaObject(); - const QMetaObject *storeMo = QmlMetaType::rawMetaObjectForType(binding.property->type); + QmlInstruction &instr = output->bytecode[binding.instructionIdx]; + instr.line = binding.value->location.start.line; - Q_ASSERT(idMo); - Q_ASSERT(storeMo); + // Single load optimization + if (bs.isValid() && bs.isSingleLoad()) { - bool canAssign = false; - while (!canAssign && idMo) { - if (idMo == storeMo) - canAssign = true; - else - idMo = idMo->superClass(); - } + QString singleLoadTarget = QLatin1String(bs.singleLoadTarget()); - if (!canAssign) - continue; + if (singleLoadTarget.at(0).isUpper() && + compileState.ids.contains(singleLoadTarget) && + QmlMetaType::isObject(binding.property->type)) { - int saveId = -1; + IdReference reference = compileState.ids[singleLoadTarget]; - int instructionIdx = reference.instructionIdx; - if (output->bytecode.at(instructionIdx).setId.save != -1) { - saveId = output->bytecode.at(instructionIdx).setId.save; - } else { - output->bytecode[instructionIdx].setId.save = saveCount; - saveId = saveCount; - ++saveCount; - } + const QMetaObject *idMo = reference.object->metaObject(); + const QMetaObject *storeMo = + QmlMetaType::rawMetaObjectForType(binding.property->type); - int prop = instr.assignBinding.property; + Q_ASSERT(idMo); + Q_ASSERT(storeMo); - instr.type = QmlInstruction::PushProperty; - instr.pushProperty.property = prop; + bool canAssign = false; + while (!canAssign && idMo) { + if (idMo == storeMo) + canAssign = true; + else + idMo = idMo->superClass(); + } - QmlInstruction instr; - instr.type = QmlInstruction::StoreStackObject; - instr.line = 0; - instr.assignStackObject.property = newInstrs; - instr.assignStackObject.object = saveId; - output->bytecode << instr; - ++newInstrs; + if (canAssign) { + int instructionIdx = reference.instructionIdx; + if (output->bytecode.at(instructionIdx).setId.save == -1) { + output->bytecode[instructionIdx].setId.save = + compileState.savedObjects++; } + int saveId = output->bytecode.at(instructionIdx).setId.save; + + instr.type = QmlInstruction::PushProperty; + instr.pushProperty.property = binding.property->index; + + QmlInstruction store; + store.type = QmlInstruction::StoreStackObject; + store.line = 0; + store.assignStackObject.property = + compileState.pushedProperties++; + store.assignStackObject.object = saveId; + output->bytecode << store; + return; } - } + } } - output->bytecode[patch].init.dataSize = saveCount; - output->bytecode[patch].init.bindingsSize = compileState.bindings.count(); - output->bytecode[patch].init.parserStatusSize = - compileState.parserStatusCount; + // General binding fallback + int bref; + if (bs.isValid()) { + bref = output->indexForByteArray(QByteArray(bs.compileData(), bs.compileDataSize())); + } else { + bref = output->indexForString(binding.expression.asScript()); + } + + instr.assignBinding.context = binding.bindingContext; + + if (bs.isValid()) + instr.type = QmlInstruction::StoreCompiledBinding; + else + instr.type = QmlInstruction::StoreBinding; - return newInstrs; + instr.assignBinding.property = binding.property->index; + instr.assignBinding.value = bref; + QMetaProperty mp = binding.property->parent->metaObject()->property(binding.property->index); + instr.assignBinding.category = QmlMetaProperty::propertyCategory(mp); } QmlCompiledData::QmlCompiledData() diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index b1963da..eb24b91 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -158,10 +158,12 @@ private: QmlParser::Value *value); bool compileDynamicMeta(QmlParser::Object *obj); - bool compileBinding(const QmlParser::Variant &, QmlParser::Property *prop, - int ctxt, const QMetaObject *, qint64); + bool compileBinding(QmlParser::Value *, QmlParser::Property *prop, + int ctxt); - int finalizeComponent(int patch); + void finalizeComponent(int patch); + class BindingReference; + void finalizeBinding(const BindingReference &); struct IdReference { QString id; @@ -172,14 +174,18 @@ private: struct BindingReference { QmlParser::Variant expression; QmlParser::Property *property; + QmlParser::Value *value; int instructionIdx; + int bindingContext; }; struct ComponentCompileState { - ComponentCompileState() : parserStatusCount(0) {} + ComponentCompileState() : parserStatusCount(0), savedObjects(0), pushedProperties(0) {} QHash ids; int parserStatusCount; + int savedObjects; + int pushedProperties; QList bindings; }; ComponentCompileState compileState; diff --git a/src/declarative/qml/qmlparser.cpp b/src/declarative/qml/qmlparser.cpp index f262b5d..fadfbb1 100644 --- a/src/declarative/qml/qmlparser.cpp +++ b/src/declarative/qml/qmlparser.cpp @@ -83,18 +83,23 @@ const QMetaObject *Object::metaObject() const QmlParser::Property *Object::getDefaultProperty() { - if (!defaultProperty) + if (!defaultProperty) { defaultProperty = new Property; + defaultProperty->parent = this; + } return defaultProperty; } Property *QmlParser::Object::getProperty(const QByteArray &name, bool create) { if (!properties.contains(name)) { - if (create) - properties.insert(name, new Property(name)); - else + if (create) { + Property *property = new Property(name); + property->parent = this; + properties.insert(name, property); + } else { return 0; + } } return properties[name]; } @@ -153,12 +158,12 @@ void QmlParser::Object::dump(int indent) const } QmlParser::Property::Property() -: type(0), index(-1), value(0), isDefault(true) +: parent(0), type(0), index(-1), value(0), isDefault(true) { } QmlParser::Property::Property(const QByteArray &n) -: type(0), index(-1), value(0), name(n), isDefault(false) +: parent(0), type(0), index(-1), value(0), name(n), isDefault(false) { } diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h index cb9b540..020cae5 100644 --- a/src/declarative/qml/qmlparser_p.h +++ b/src/declarative/qml/qmlparser_p.h @@ -252,6 +252,9 @@ namespace QmlParser Property(const QByteArray &n); virtual ~Property(); + // The Object to which this property is attached + Object *parent; + Object *getValue(); void addValue(Value *v); diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index b1ffc98..75c81a7 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -532,6 +532,7 @@ bool ProcessAST::visit(AST::UiPublicMember *node) if (node->expression) { // default value property.defaultValue = new Property; + property.defaultValue->parent = _stateStack.top().object; Value *value = new Value; value->location = location(node->expression->firstSourceLocation(), node->expression->lastSourceLocation()); -- cgit v0.12 From 5d7a0073ac8e9ad241812ae8b5dc138961bd612f Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 28 May 2009 09:35:39 +0200 Subject: Doc change; QGraphicsView::DontClipPainter is obsolete since Qt 4.5. Reviewed-by: Lars --- src/gui/graphicsview/qgraphicsview.cpp | 11 +---------- src/gui/graphicsview/qgraphicsview.h | 2 +- 2 files changed, 2 insertions(+), 11 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 501aef1..10b837a 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -200,16 +200,7 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < Note that setting a flag usually imposes a side effect, and this effect can vary between paint devices and platforms. - \value DontClipPainter QGraphicsView sometimes clips the painter when - rendering the scene contents. This can generally improve performance - (e.g., rendering only small parts of a large pixmap), and protects against - rendering mistakes (e.g., drawing outside bounding rectangles, or outside - the exposed area). In some situations, however, the painter clip can slow - down rendering; especially when all painting is restricted to inside - exposed areas. By enabling this flag, QGraphicsView will completely - disable its implicit clipping. Note that rendering artifacts from using a - semi-transparent foreground or background brush can occur if clipping is - disabled. + \value DontClipPainter This value is obsolete and has no effect. \value DontSavePainterState When rendering, QGraphicsView protects the painter state (see QPainter::save()) when rendering the background or diff --git a/src/gui/graphicsview/qgraphicsview.h b/src/gui/graphicsview/qgraphicsview.h index e77e45c..c3ea6e5 100644 --- a/src/gui/graphicsview/qgraphicsview.h +++ b/src/gui/graphicsview/qgraphicsview.h @@ -110,7 +110,7 @@ public: }; enum OptimizationFlag { - DontClipPainter = 0x1, + DontClipPainter = 0x1, // obsolete DontSavePainterState = 0x2, DontAdjustForAntialiasing = 0x4 }; -- cgit v0.12 From b3be28bf199521546bc7890c66f8454f5d310083 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 28 May 2009 09:51:06 +0200 Subject: Compile qstatemachine autotest --- src/corelib/statemachine/qstate_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/statemachine/qstate_p.h b/src/corelib/statemachine/qstate_p.h index 491cb87..93744b9 100644 --- a/src/corelib/statemachine/qstate_p.h +++ b/src/corelib/statemachine/qstate_p.h @@ -79,7 +79,7 @@ class QAbstractTransition; class QHistoryState; class QState; -class QStatePrivate : public QAbstractStatePrivate +class Q_AUTOTEST_EXPORT QStatePrivate : public QAbstractStatePrivate { Q_DECLARE_PUBLIC(QState) public: -- cgit v0.12 From 695e49acfb34ffb5b61fddbd6afff9f1281e8299 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Thu, 28 May 2009 10:00:22 +0200 Subject: Doc - final screenshot and changes --- doc/src/designer-manual.qdoc | 19 ++++++++----------- .../images/rgbController-configure-connection1.png | Bin 29210 -> 23241 bytes 2 files changed, 8 insertions(+), 11 deletions(-) diff --git a/doc/src/designer-manual.qdoc b/doc/src/designer-manual.qdoc index 58d0f71..4b8de32 100644 --- a/doc/src/designer-manual.qdoc +++ b/doc/src/designer-manual.qdoc @@ -58,7 +58,8 @@ and custom plugins allow you to use your own components with \QD. If you are new to \QD, you can take a look at the - \l{Getting To Know Qt Designer} document. + \l{Getting To Know Qt Designer} document. For a quick tutorial on how to + use \QD, refer to \l{A Quick Start to Qt Designer}. Qt Designer 4.5 boasts a long list of improvements. For a detailed list of what is new, refer \l{What's New in Qt Designer 4.5}. @@ -499,7 +500,7 @@ correct signal and slot and click \gui OK. \endtable - \image rgbController-configureConnection1.png + \image rgbController-configure-connection1.png Repeat the step (in reverse order), clicking on the spin box and dragging the cursor towards the slider, to connect the spin box's @@ -531,15 +532,11 @@ process for the remaining spin boxes and sliders. \endtable - Now, we preview your form to see how it would look in your application. To - preview your form, press \key{Ctrl + R} or select \gui Preview from the - \gui Form menu. - - \image rgbController-preview.png - - Try dragging the slider - the spin box will mirror its value too (and vice - versa). Also, you can resize it to see how the layouts used to manage the - child widgets respond to different window sizes. + Now, we preview your form to see how it would look in your application - + press \key{Ctrl + R} or select \gui Preview from the \gui Form menu. Try + dragging the slider - the spin box will mirror its value too (and vice + versa). Also, you can resize it to see how the layouts that are used to + manage the child widgets, respond to different window sizes. */ diff --git a/doc/src/images/rgbController-configure-connection1.png b/doc/src/images/rgbController-configure-connection1.png index 0798184..4e5dcf2 100644 Binary files a/doc/src/images/rgbController-configure-connection1.png and b/doc/src/images/rgbController-configure-connection1.png differ -- cgit v0.12 From 0bb0699d403b7541472a72a4057ecf0ca366a7cd Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 28 May 2009 09:51:43 +0200 Subject: Use Qt::UniqueConnection instead of disconnect/connect Also fix an issue in QTreeView where a signal could be connected several times Reviewed-by: Thierry --- src/corelib/statemachine/qstatemachine.cpp | 3 +-- src/gui/dialogs/qinputdialog.cpp | 3 +-- src/gui/itemviews/qtreeview.cpp | 2 +- src/gui/styles/qstylesheetstyle.cpp | 8 ++------ src/gui/widgets/qpushbutton.cpp | 3 +-- 5 files changed, 6 insertions(+), 13 deletions(-) diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp index 757584a..185fb7d 100644 --- a/src/corelib/statemachine/qstatemachine.cpp +++ b/src/corelib/statemachine/qstatemachine.cpp @@ -803,8 +803,7 @@ void QStateMachinePrivate::applyProperties(const QList &tr stateForAnimation.insert(a, s); animationsForState[s].append(a); // ### connect to just the top-level animation? - QObject::disconnect(a, SIGNAL(finished()), q, SLOT(_q_animationFinished())); - QObject::connect(a, SIGNAL(finished()), q, SLOT(_q_animationFinished())); + QObject::connect(a, SIGNAL(finished()), q, SLOT(_q_animationFinished()), Qt::UniqueConnection); } it2 = assignments.erase(it2); } else { diff --git a/src/gui/dialogs/qinputdialog.cpp b/src/gui/dialogs/qinputdialog.cpp index 78d99e3..8608334 100644 --- a/src/gui/dialogs/qinputdialog.cpp +++ b/src/gui/dialogs/qinputdialog.cpp @@ -307,8 +307,7 @@ void QInputDialogPrivate::ensureEnabledConnection(QAbstractSpinBox *spinBox) { if (spinBox) { QAbstractButton *okButton = buttonBox->button(QDialogButtonBox::Ok); - QObject::disconnect(spinBox, SIGNAL(textChanged(bool)), okButton, SLOT(setEnabled(bool))); - QObject::connect(spinBox, SIGNAL(textChanged(bool)), okButton, SLOT(setEnabled(bool))); + QObject::connect(spinBox, SIGNAL(textChanged(bool)), okButton, SLOT(setEnabled(bool)), Qt::UniqueConnection); } } diff --git a/src/gui/itemviews/qtreeview.cpp b/src/gui/itemviews/qtreeview.cpp index c3fca8e..7837700 100644 --- a/src/gui/itemviews/qtreeview.cpp +++ b/src/gui/itemviews/qtreeview.cpp @@ -851,7 +851,7 @@ void QTreeView::setSortingEnabled(bool enable) // because otherwise it will not call sort on the model. sortByColumn(header()->sortIndicatorSection(), header()->sortIndicatorOrder()); connect(header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), - this, SLOT(_q_sortIndicatorChanged(int, Qt::SortOrder))); + this, SLOT(_q_sortIndicatorChanged(int, Qt::SortOrder)), Qt::UniqueConnection); } else { disconnect(header(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(_q_sortIndicatorChanged(int, Qt::SortOrder))); diff --git a/src/gui/styles/qstylesheetstyle.cpp b/src/gui/styles/qstylesheetstyle.cpp index 1d6dc8a..9a8f97e 100644 --- a/src/gui/styles/qstylesheetstyle.cpp +++ b/src/gui/styles/qstylesheetstyle.cpp @@ -2702,14 +2702,10 @@ void QStyleSheetStyle::polish(QWidget *w) QRenderRule rule = renderRule(sa, PseudoElement_None, PseudoClass_Enabled); if ((rule.hasBorder() && rule.border()->hasBorderImage()) || (rule.hasBackground() && !rule.background()->pixmap.isNull())) { - QObject::disconnect(sa->horizontalScrollBar(), SIGNAL(valueChanged(int)), - sa, SLOT(update())); - QObject::disconnect(sa->verticalScrollBar(), SIGNAL(valueChanged(int)), - sa, SLOT(update())); QObject::connect(sa->horizontalScrollBar(), SIGNAL(valueChanged(int)), - sa, SLOT(update())); + sa, SLOT(update()), Qt::UniqueConnection); QObject::connect(sa->verticalScrollBar(), SIGNAL(valueChanged(int)), - sa, SLOT(update())); + sa, SLOT(update()), Qt::UniqueConnection); } } #endif diff --git a/src/gui/widgets/qpushbutton.cpp b/src/gui/widgets/qpushbutton.cpp index 03ca751..ca58f87 100644 --- a/src/gui/widgets/qpushbutton.cpp +++ b/src/gui/widgets/qpushbutton.cpp @@ -527,8 +527,7 @@ void QPushButton::setMenu(QMenu* menu) return; if (menu && !d->menu) { - disconnect(this, SIGNAL(pressed()), this, SLOT(_q_popupPressed())); - connect(this, SIGNAL(pressed()), this, SLOT(_q_popupPressed())); + connect(this, SIGNAL(pressed()), this, SLOT(_q_popupPressed()), Qt::UniqueConnection); } if (d->menu) removeAction(d->menu->menuAction()); -- cgit v0.12 From f390f9b51cf8686e9ed44f13a33c7349b9e96a09 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 28 May 2009 10:27:50 +0200 Subject: improved string operations all over the place used character operations whenever possible better usage of QLatin1String --- .../clucene/src/CLucene/store/FSDirectory.cpp | 2 +- src/3rdparty/clucene/src/CLucene/util/Misc.cpp | 9 +- .../webkit/WebCore/bridge/qt/qt_instance.cpp | 4 +- .../webkit/WebCore/bridge/qt/qt_runtime.cpp | 6 +- src/3rdparty/webkit/WebCore/dom/XMLTokenizerQt.cpp | 2 +- .../webkit/WebCore/platform/graphics/qt/PathQt.cpp | 6 +- src/activeqt/container/qaxbase.cpp | 76 ++++----- src/activeqt/container/qaxdump.cpp | 38 ++--- src/activeqt/container/qaxscript.cpp | 4 +- src/activeqt/control/qaxserver.cpp | 183 +++++++++++---------- src/activeqt/control/qaxserverbase.cpp | 10 +- src/activeqt/control/qaxservermain.cpp | 2 +- src/activeqt/shared/qaxtypes.cpp | 2 +- src/corelib/io/qfsfileengine_unix.cpp | 6 +- src/corelib/io/qfsfileengine_win.cpp | 8 +- src/corelib/io/qurl.cpp | 2 +- src/corelib/kernel/qcoreapplication.cpp | 2 +- src/corelib/kernel/qcoreapplication_win.cpp | 2 +- src/corelib/plugin/qlibrary_unix.cpp | 2 +- src/corelib/tools/qdatetime.cpp | 2 +- src/corelib/tools/qlocale.cpp | 4 +- src/corelib/xml/qxmlstream.cpp | 2 +- src/dbus/qdbuserror.cpp | 2 +- src/dbus/qdbusintegrator.cpp | 6 +- src/dbus/qdbusmetaobject.cpp | 2 +- src/dbus/qdbusutil.cpp | 16 +- src/gui/dialogs/qprintdialog_unix.cpp | 8 +- src/gui/dialogs/qprintpreviewdialog.cpp | 4 +- src/gui/embedded/qmouse_qws.cpp | 4 +- src/gui/embedded/qscreenmulti_qws.cpp | 4 +- src/gui/embedded/qscreentransformed_qws.cpp | 6 +- src/gui/embedded/qscreenvfb_qws.cpp | 4 +- src/gui/embedded/qtransportauth_qws.cpp | 4 +- src/gui/embedded/qunixsocket.cpp | 32 ++-- src/gui/embedded/qunixsocketserver.cpp | 8 +- src/gui/embedded/qwindowsystem_qws.cpp | 4 +- src/gui/embedded/qwscommand_qws.cpp | 8 +- src/gui/kernel/qapplication_qws.cpp | 6 +- src/gui/kernel/qapplication_win.cpp | 4 +- src/gui/kernel/qmime_mac.cpp | 4 +- src/gui/kernel/qmime_win.cpp | 8 +- src/gui/kernel/qsound_qws.cpp | 2 +- src/gui/painting/qbezier.cpp | 8 +- src/gui/painting/qpaintengine_raster.cpp | 2 +- src/gui/painting/qprinterinfo_unix.cpp | 4 +- src/gui/painting/qtessellator.cpp | 2 +- src/gui/painting/qwindowsurface_x11.cpp | 2 +- src/gui/styles/gtksymbols.cpp | 6 +- src/gui/styles/qgtkstyle.cpp | 3 +- src/gui/text/qfontdatabase_qws.cpp | 4 +- src/gui/text/qfontdatabase_x11.cpp | 28 ++-- src/gui/text/qfontengine_qpf.cpp | 10 +- src/gui/text/qfontengine_x11.cpp | 5 +- src/gui/text/qtextdocumentlayout.cpp | 2 +- src/gui/text/qtexthtmlparser.cpp | 2 +- src/gui/util/qdesktopservices_mac.cpp | 2 +- src/gui/util/qdesktopservices_x11.cpp | 4 +- src/gui/widgets/qcombobox_p.h | 2 +- src/gui/widgets/qprogressbar.cpp | 8 +- src/network/access/qhttpnetworkrequest.cpp | 4 +- src/network/access/qnetworkaccessfilebackend.cpp | 2 +- src/network/access/qnetworkcookie.cpp | 2 +- src/network/kernel/qauthenticator.cpp | 4 +- src/network/kernel/qhostaddress.cpp | 2 +- src/network/kernel/qnetworkinterface.cpp | 2 +- src/network/socket/qabstractsocket.cpp | 6 +- src/network/socket/qlocalsocket.cpp | 4 +- src/network/socket/qsocks5socketengine.cpp | 14 +- src/network/ssl/qsslcertificate.cpp | 16 +- src/network/ssl/qsslcipher.cpp | 2 +- src/network/ssl/qsslkey.cpp | 2 +- src/network/ssl/qsslsocket.cpp | 16 +- src/network/ssl/qsslsocket_openssl.cpp | 2 +- src/opengl/qegl.cpp | 14 +- src/opengl/qgl.cpp | 2 +- src/opengl/qgl_x11.cpp | 6 +- src/opengl/qglpixmapfilter.cpp | 37 ++--- src/opengl/util/generator.cpp | 2 +- src/plugins/accessible/widgets/rangecontrols.cpp | 2 +- src/plugins/gfxdrivers/hybrid/hybridscreen.cpp | 4 +- src/plugins/gfxdrivers/vnc/qscreenvnc_qws.cpp | 4 +- src/qt3support/dialogs/q3filedialog.cpp | 8 +- src/qt3support/dialogs/q3filedialog_mac.cpp | 2 +- src/qt3support/dialogs/q3filedialog_win.cpp | 2 +- src/qt3support/itemviews/q3iconview.cpp | 6 +- src/qt3support/network/q3dns.cpp | 16 +- src/qt3support/network/q3ftp.cpp | 22 +-- src/qt3support/network/q3http.cpp | 8 +- src/qt3support/network/q3url.cpp | 61 ++++--- src/qt3support/network/q3urloperator.cpp | 2 +- src/qt3support/other/q3dragobject.cpp | 6 +- src/qt3support/other/q3process.cpp | 2 +- src/qt3support/other/q3process_unix.cpp | 2 +- src/qt3support/other/q3process_win.cpp | 10 +- src/qt3support/painting/q3paintengine_svg.cpp | 48 +++--- src/qt3support/text/q3richtext.cpp | 28 ++-- src/qt3support/text/q3textedit.cpp | 4 +- src/qt3support/widgets/q3mainwindow.cpp | 18 +- src/script/qscriptcontext.cpp | 2 +- src/script/qscriptcontext_p.cpp | 6 +- src/script/qscriptecmaerror.cpp | 6 +- src/script/qscriptecmafunction.cpp | 2 +- src/script/qscriptecmaglobal.cpp | 2 +- src/script/qscriptecmaobject.cpp | 2 +- src/script/qscriptparser.cpp | 4 +- src/script/qscriptprettypretty.cpp | 108 ++++++------ src/script/qscriptsyntaxchecker.cpp | 4 +- src/script/qscriptvalueimpl.cpp | 10 +- src/script/qscriptxmlgenerator.cpp | 10 +- .../debugging/qscriptcompletiontask.cpp | 10 +- .../debugging/qscriptdebuggerbackend.cpp | 2 +- .../debugging/qscriptdebuggerconsole.cpp | 4 +- .../debugging/qscriptdebuggerlocalsmodel.cpp | 2 +- src/sql/drivers/db2/qsql_db2.cpp | 2 +- src/sql/drivers/ibase/qsql_ibase.cpp | 6 +- src/sql/drivers/mysql/qsql_mysql.cpp | 11 +- src/sql/drivers/oci/qsql_oci.cpp | 16 +- src/sql/drivers/odbc/qsql_odbc.cpp | 21 +-- src/sql/drivers/psql/qsql_psql.cpp | 22 +-- src/sql/drivers/sqlite/qsql_sqlite.cpp | 4 +- src/sql/drivers/sqlite2/qsql_sqlite2.cpp | 6 +- src/sql/drivers/tds/qsql_tds.cpp | 6 +- src/sql/kernel/qsqldriver.cpp | 18 +- src/sql/kernel/qsqlerror.cpp | 2 +- src/sql/kernel/qsqlfield.cpp | 4 +- src/sql/kernel/qsqlrecord.cpp | 2 +- src/sql/models/qsqlrelationaltablemodel.cpp | 2 +- src/svg/qsvggenerator.cpp | 77 +++++---- src/testlib/qbenchmark_p.h | 2 +- src/testlib/qbenchmarkvalgrind.cpp | 10 +- src/testlib/qplaintestlogger.cpp | 4 +- src/testlib/qsignaldumper.cpp | 10 +- src/tools/idc/main.cpp | 6 +- src/tools/moc/generator.cpp | 4 +- src/tools/moc/moc.cpp | 6 +- src/tools/moc/preprocessor.cpp | 2 +- src/tools/uic/cpp/cppwriteicondata.cpp | 4 +- src/tools/uic/cpp/cppwriteinitialization.cpp | 6 +- src/tools/uic3/embed.cpp | 2 +- src/tools/uic3/form.cpp | 84 +++++----- src/tools/uic3/main.cpp | 2 +- src/tools/uic3/parser.cpp | 12 +- src/tools/uic3/qt3to4.cpp | 2 +- src/tools/uic3/subclassing.cpp | 36 ++-- src/tools/uic3/ui3reader.cpp | 24 +-- src/winmain/qtmain_win.cpp | 4 +- src/xml/dom/qdom.cpp | 2 +- src/xml/sax/qxml.cpp | 12 +- src/xmlpatterns/acceltree/qacceltree.cpp | 14 +- src/xmlpatterns/api/qsourcelocation.cpp | 2 +- src/xmlpatterns/data/qabstractfloat.cpp | 2 +- src/xmlpatterns/data/qcommonvalues.cpp | 2 +- src/xmlpatterns/expr/qexpression_p.h | 2 +- tools/assistant/tools/assistant/main.cpp | 2 +- tools/linguist/linguist/mainwindow.cpp | 2 +- tools/linguist/linguist/phrase.cpp | 12 +- tools/linguist/lupdate/merge.cpp | 6 +- tools/linguist/shared/profileevaluator.cpp | 4 +- tools/linguist/shared/proparserutils.h | 2 +- tools/pixeltool/qpixeltool.cpp | 4 +- tools/porting/src/logger.cpp | 6 +- tools/qdoc3/config.cpp | 2 +- tools/shared/qttoolbardialog/qttoolbardialog.cpp | 6 +- 163 files changed, 827 insertions(+), 846 deletions(-) diff --git a/src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp b/src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp index 36c170a..e9659cf 100644 --- a/src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp +++ b/src/3rdparty/clucene/src/CLucene/store/FSDirectory.cpp @@ -624,7 +624,7 @@ LuceneLock* FSDirectory::makeLock(const QString& name) QString lockFile(getLockPrefix()); - lockFile.append(QLatin1String("-")).append(name); + lockFile.append(QLatin1Char('-')).append(name); return _CLNEW FSLock(lockDir, lockFile); } diff --git a/src/3rdparty/clucene/src/CLucene/util/Misc.cpp b/src/3rdparty/clucene/src/CLucene/util/Misc.cpp index 069b487..cb2efe2 100644 --- a/src/3rdparty/clucene/src/CLucene/util/Misc.cpp +++ b/src/3rdparty/clucene/src/CLucene/util/Misc.cpp @@ -181,12 +181,9 @@ void Misc::segmentname(QString& buffer, int32_t bufferLen, CND_PRECONDITION(!segment.isEmpty(), "segment is NULL"); CND_PRECONDITION(!ext.isEmpty(), "extention is NULL"); - buffer.clear(); - if (x == -1) { - buffer = QString(segment + ext); - } else { - buffer = QString(QLatin1String("%1%2%3")).arg(segment).arg(ext).arg(x); - } + buffer = segment + ext; + if (x != -1) + buffer += QString::number(x); } // #pragma mark -- TCHAR related utils diff --git a/src/3rdparty/webkit/WebCore/bridge/qt/qt_instance.cpp b/src/3rdparty/webkit/WebCore/bridge/qt/qt_instance.cpp index 4b94a94..26323e8 100644 --- a/src/3rdparty/webkit/WebCore/bridge/qt/qt_instance.cpp +++ b/src/3rdparty/webkit/WebCore/bridge/qt/qt_instance.cpp @@ -337,7 +337,7 @@ JSValuePtr QtField::valueFromInstance(ExecState* exec, const Instance* inst) con return ret; } else { - QString msg = QString(QLatin1String("cannot access member `%1' of deleted QObject")).arg(QLatin1String(name())); + QString msg = QString::fromLatin1("cannot access member `%1' of deleted QObject").arg(QLatin1String(name())); return throwError(exec, GeneralError, msg.toLatin1().constData()); } } @@ -362,7 +362,7 @@ void QtField::setValueToInstance(ExecState* exec, const Instance* inst, JSValueP } else if (m_type == DynamicProperty) obj->setProperty(m_dynamicProperty.constData(), val); } else { - QString msg = QString(QLatin1String("cannot access member `%1' of deleted QObject")).arg(QLatin1String(name())); + QString msg = QString::fromLatin1("cannot access member `%1' of deleted QObject").arg(QLatin1String(name())); throwError(exec, GeneralError, msg.toLatin1().constData()); } } diff --git a/src/3rdparty/webkit/WebCore/bridge/qt/qt_runtime.cpp b/src/3rdparty/webkit/WebCore/bridge/qt/qt_runtime.cpp index c7ba6c2..5a73dc7 100644 --- a/src/3rdparty/webkit/WebCore/bridge/qt/qt_runtime.cpp +++ b/src/3rdparty/webkit/WebCore/bridge/qt/qt_runtime.cpp @@ -1515,7 +1515,7 @@ JSValuePtr QtRuntimeConnectionMethod::call(ExecState* exec, JSObject* functionOb bool ok = QMetaObject::connect(sender, signalIndex, conn, conn->metaObject()->methodOffset()); if (!ok) { delete conn; - QString msg = QString(QLatin1String("QtMetaMethod.connect: failed to connect to %1::%2()")) + QString msg = QString::fromLatin1("QtMetaMethod.connect: failed to connect to %1::%2()") .arg(QLatin1String(sender->metaObject()->className())) .arg(QLatin1String(d->m_signature)); return throwError(exec, GeneralError, msg.toLatin1().constData()); @@ -1541,14 +1541,14 @@ JSValuePtr QtRuntimeConnectionMethod::call(ExecState* exec, JSObject* functionOb } if (!ret) { - QString msg = QString(QLatin1String("QtMetaMethod.disconnect: failed to disconnect from %1::%2()")) + QString msg = QString::fromLatin1("QtMetaMethod.disconnect: failed to disconnect from %1::%2()") .arg(QLatin1String(sender->metaObject()->className())) .arg(QLatin1String(d->m_signature)); return throwError(exec, GeneralError, msg.toLatin1().constData()); } } } else { - QString msg = QString(QLatin1String("QtMetaMethod.%1: %2::%3() is not a signal")) + QString msg = QString::fromLatin1("QtMetaMethod.%1: %2::%3() is not a signal") .arg(QLatin1String(d->m_isConnect ? "connect": "disconnect")) .arg(QLatin1String(sender->metaObject()->className())) .arg(QLatin1String(d->m_signature)); diff --git a/src/3rdparty/webkit/WebCore/dom/XMLTokenizerQt.cpp b/src/3rdparty/webkit/WebCore/dom/XMLTokenizerQt.cpp index 2050a70..39ccefe 100644 --- a/src/3rdparty/webkit/WebCore/dom/XMLTokenizerQt.cpp +++ b/src/3rdparty/webkit/WebCore/dom/XMLTokenizerQt.cpp @@ -357,7 +357,7 @@ HashMap parseAttributes(const String& string, bool& attrsOK) state.gotAttributes = false; QXmlStreamReader stream; - QString dummy = QString(QLatin1String("")).arg(string); + QString dummy = QString::fromLatin1("").arg(string); stream.addData(dummy); while (!stream.atEnd()) { stream.readNext(); diff --git a/src/3rdparty/webkit/WebCore/platform/graphics/qt/PathQt.cpp b/src/3rdparty/webkit/WebCore/platform/graphics/qt/PathQt.cpp index e68be2b..bff9edb 100644 --- a/src/3rdparty/webkit/WebCore/platform/graphics/qt/PathQt.cpp +++ b/src/3rdparty/webkit/WebCore/platform/graphics/qt/PathQt.cpp @@ -286,10 +286,10 @@ String Path::debugString() const switch (cur.type) { case QPainterPath::MoveToElement: - ret += QString(QLatin1String("M %1 %2")).arg(cur.x).arg(cur.y); + ret += QString::fromLatin1("M %1 %2").arg(cur.x).arg(cur.y); break; case QPainterPath::LineToElement: - ret += QString(QLatin1String("L %1 %2")).arg(cur.x).arg(cur.y); + ret += QString::fromLatin1("L %1 %2").arg(cur.x).arg(cur.y); break; case QPainterPath::CurveToElement: { @@ -299,7 +299,7 @@ String Path::debugString() const Q_ASSERT(c1.type == QPainterPath::CurveToDataElement); Q_ASSERT(c2.type == QPainterPath::CurveToDataElement); - ret += QString(QLatin1String("C %1 %2 %3 %4 %5 %6")).arg(cur.x).arg(cur.y).arg(c1.x).arg(c1.y).arg(c2.x).arg(c2.y); + ret += QString::fromLatin1("C %1 %2 %3 %4 %5 %6").arg(cur.x).arg(cur.y).arg(c1.x).arg(c1.y).arg(c2.x).arg(c2.y); i += 2; break; diff --git a/src/activeqt/container/qaxbase.cpp b/src/activeqt/container/qaxbase.cpp index 44c3e9e..e1ffb81 100644 --- a/src/activeqt/container/qaxbase.cpp +++ b/src/activeqt/container/qaxbase.cpp @@ -421,7 +421,7 @@ public: argv[p + 1] = varp + p + 1; } else { argv[p + 1] = const_cast(varp[p + 1].constData()); - if (ptype.endsWith("*")) { + if (ptype.endsWith('*')) { argv_pointer[p + 1] = argv[p + 1]; argv[p + 1] = argv_pointer + p + 1; } @@ -648,7 +648,7 @@ QByteArray QAxEventSink::findProperty(DISPID dispID) int index = mo->indexOfProperty(propname); const QMetaProperty prop = mo->property(index); propsignal += prop.typeName(); - propsignal += ")"; + propsignal += ')'; addProperty(dispID, propname, propsignal); return propname; @@ -1661,7 +1661,7 @@ private: void addProperty(const QByteArray &type, const QByteArray &name, uint flags) { QByteArray propertyType(type); - if (propertyType.endsWith("&")) + if (propertyType.endsWith('&')) propertyType.chop(1); Property &prop = property_list[name]; @@ -2046,11 +2046,11 @@ QByteArray MetaObjectGenerator::guessTypes(const TYPEDESC &tdesc, ITypeInfo *inf case VT_INT: case VT_UINT: case VT_CY: - str += "&"; + str += '&'; break; case VT_PTR: if (str == "QFont" || str == "QPixmap") { - str += "&"; + str += '&'; break; } else if (str == "void*") { str = "void **"; @@ -2059,19 +2059,19 @@ QByteArray MetaObjectGenerator::guessTypes(const TYPEDESC &tdesc, ITypeInfo *inf // FALLTHROUGH default: if (str == "QColor") - str += "&"; + str += '&'; else if (str == "QDateTime") - str += "&"; + str += '&'; else if (str == "QVariantList") - str += "&"; + str += '&'; else if (str == "QByteArray") - str += "&"; + str += '&'; else if (str == "QStringList") - str += "&"; + str += '&'; else if (!str.isEmpty() && hasEnum(str)) - str += "&"; + str += '&'; else if (!str.isEmpty() && str != "QFont" && str != "QPixmap" && str != "QVariant") - str += "*"; + str += '*'; } break; case VT_SAFEARRAY: @@ -2089,7 +2089,7 @@ QByteArray MetaObjectGenerator::guessTypes(const TYPEDESC &tdesc, ITypeInfo *inf default: str = guessTypes(tdesc.lpadesc->tdescElem, info, function); if (!str.isEmpty()) - str = "QList<" + str + ">"; + str = "QList<" + str + '>'; break; } break; @@ -2097,7 +2097,7 @@ QByteArray MetaObjectGenerator::guessTypes(const TYPEDESC &tdesc, ITypeInfo *inf str = guessTypes(tdesc.lpadesc->tdescElem, info, function); if (!str.isEmpty()) { for (int index = 0; index < tdesc.lpadesc->cDims; ++index) - str += "[" + QByteArray::number((int)tdesc.lpadesc->rgbounds[index].cElements) + "]"; + str += '[' + QByteArray::number((int)tdesc.lpadesc->rgbounds[index].cElements) + ']'; } break; case VT_USERDEFINED: @@ -2114,7 +2114,7 @@ QByteArray MetaObjectGenerator::guessTypes(const TYPEDESC &tdesc, ITypeInfo *inf } if (tdesc.vt & VT_BYREF) - str += "&"; + str += '&'; str.replace("&*", "**"); return str; @@ -2141,7 +2141,7 @@ void MetaObjectGenerator::readClassInfo() if (d->useClassInfo && !hasClassInfo("CoClass")) { QString coClassIDstr = iidnames.value(QLatin1String("/CLSID/") + coClassID + QLatin1String("/Default"), coClassID).toString(); addClassInfo("CoClass", coClassIDstr.isEmpty() ? coClassID.toLatin1() : coClassIDstr.toLatin1()); - QByteArray version = QByteArray::number(typeattr->wMajorVerNum) + "." + QByteArray::number(typeattr->wMinorVerNum); + QByteArray version = QByteArray::number(typeattr->wMajorVerNum) + '.' + QByteArray::number(typeattr->wMinorVerNum); if (version != "0.0") addClassInfo("Version", version); } @@ -2174,7 +2174,7 @@ void MetaObjectGenerator::readClassInfo() while (tlfile.isEmpty() && vit != versions.end()) { QString version = *vit; ++vit; - tlfile = controls.value(QLatin1String("/") + version + QLatin1String("/0/win32/.")).toString(); + tlfile = controls.value(QLatin1Char('/') + version + QLatin1String("/0/win32/.")).toString(); } controls.endGroup(); } else { @@ -2347,7 +2347,7 @@ void MetaObjectGenerator::addChangedSignal(const QByteArray &function, const QBy // generate changed signal QByteArray signalName(function); signalName += "Changed"; - QByteArray signalProto = signalName + "(" + replaceType(type) + ")"; + QByteArray signalProto = signalName + '(' + replaceType(type) + ')'; if (!hasSignal(signalProto)) addSignal(signalProto, function); if (eventSink) @@ -2364,7 +2364,7 @@ void MetaObjectGenerator::addSetterSlot(const QByteArray &property) set = "set"; prototype[0] = toupper(prototype[0]); } - prototype = set + prototype + "(" + propertyType(property) + ")"; + prototype = set + prototype + '(' + propertyType(property) + ')'; if (!hasSlot(prototype)) addSlot(0, prototype, property); } @@ -2381,7 +2381,7 @@ QByteArray MetaObjectGenerator::createPrototype(FUNCDESC *funcdesc, ITypeInfo *t type = guessTypes(funcdesc->lprgelemdescParam->tdesc, typeinfo, function); } - prototype = function + "("; + prototype = function + '('; if (funcdesc->invkind == INVOKE_FUNC && type == hresult) type = 0; @@ -2395,7 +2395,7 @@ QByteArray MetaObjectGenerator::createPrototype(FUNCDESC *funcdesc, ITypeInfo *t QByteArray ptype = guessTypes(tdesc, typeinfo, function); if (pdesc.wParamFlags & PARAMFLAG_FRETVAL) { - if (ptype.endsWith("&")) { + if (ptype.endsWith('&')) { ptype.truncate(ptype.length() - 1); } else if (ptype.endsWith("**")) { ptype.truncate(ptype.length() - 1); @@ -2403,8 +2403,8 @@ QByteArray MetaObjectGenerator::createPrototype(FUNCDESC *funcdesc, ITypeInfo *t type = ptype; } else { prototype += ptype; - if (pdesc.wParamFlags & PARAMFLAG_FOUT && !ptype.endsWith("&") && !ptype.endsWith("**")) - prototype += "&"; + if (pdesc.wParamFlags & PARAMFLAG_FOUT && !ptype.endsWith('&') && !ptype.endsWith("**")) + prototype += '&'; if (optional || pdesc.wParamFlags & PARAMFLAG_FOPT) paramName += "=0"; else if (pdesc.wParamFlags & PARAMFLAG_FHASDEFAULT) { @@ -2414,22 +2414,22 @@ QByteArray MetaObjectGenerator::createPrototype(FUNCDESC *funcdesc, ITypeInfo *t parameters << paramName; } if (p < funcdesc->cParams && !(pdesc.wParamFlags & PARAMFLAG_FRETVAL)) - prototype += ","; + prototype += ','; } if (!prototype.isEmpty()) { - if (prototype.right(1) == ",") { + if (prototype.endsWith(',')) { if (funcdesc->invkind == INVOKE_PROPERTYPUT && p == funcdesc->cParams) { TYPEDESC tdesc = funcdesc->lprgelemdescParam[p-1].tdesc; QByteArray ptype = guessTypes(tdesc, typeinfo, function); prototype += ptype; - prototype += ")"; + prototype += ')'; parameters << "rhs"; } else { prototype[prototype.length()-1] = ')'; } } else { - prototype += ")"; + prototype += ')'; } } @@ -2577,11 +2577,11 @@ void MetaObjectGenerator::readFuncsInfo(ITypeInfo *typeinfo, ushort nFuncs) if (defargs) { parameters.takeLast(); - int lastParam = prototype.lastIndexOf(","); + int lastParam = prototype.lastIndexOf(','); if (lastParam == -1) - lastParam = prototype.indexOf("(") + 1; + lastParam = prototype.indexOf('(') + 1; prototype.truncate(lastParam); - prototype += ")"; + prototype += ')'; } } while (defargs); } @@ -2597,8 +2597,8 @@ void MetaObjectGenerator::readFuncsInfo(ITypeInfo *typeinfo, ushort nFuncs) QString strDocu = QString::fromUtf16((const ushort*)bstrDocu); SysFreeString(bstrDocu); if (!!strDocu) - desc += "[" + strDocu + "]"; - desc += "\n"; + desc += '[' + strDocu + ']'; + desc += '\n'; #endif typeinfo->ReleaseFuncDesc(funcdesc); } @@ -2680,8 +2680,8 @@ void MetaObjectGenerator::readVarsInfo(ITypeInfo *typeinfo, ushort nVars) QString strDocu = QString::fromUtf16((const ushort*)bstrDocu); SysFreeString(bstrDocu); if (!!strDocu) - desc += "[" + strDocu + "]"; - desc += "\n"; + desc += '[' + strDocu + ']'; + desc += '\n'; #endif typeinfo->ReleaseVarDesc(vardesc); } @@ -2827,8 +2827,8 @@ void MetaObjectGenerator::readEventInterface(ITypeInfo *eventinfo, IConnectionPo QString strDocu = QString::fromUtf16((const ushort*)bstrDocu); SysFreeString(bstrDocu); if (!!strDocu) - desc += "[" + strDocu + "]"; - desc += "\n"; + desc += '[' + strDocu + ']'; + desc += '\n'; #endif eventinfo->ReleaseFuncDesc(funcdesc); } @@ -4398,8 +4398,8 @@ QVariant QAxBase::asVariant() const cn = cn.mid(cn.lastIndexOf(':') + 1); QObject *object = qObject(); if (QMetaType::type(cn)) - qvar = QVariant(qRegisterMetaType(cn + "*"), &object); -// qVariantSetValue(qvar, qObject(), cn + "*"); + qvar = QVariant(qRegisterMetaType(cn + '*'), &object); +// qVariantSetValue(qvar, qObject(), cn + '*'); } return qvar; diff --git a/src/activeqt/container/qaxdump.cpp b/src/activeqt/container/qaxdump.cpp index 62ef0a4..c3218a9 100644 --- a/src/activeqt/container/qaxdump.cpp +++ b/src/activeqt/container/qaxdump.cpp @@ -94,14 +94,14 @@ static QByteArray namedPrototype(const QList ¶meterTypes, const prototype += type; if (p < parameterNames.count()) - prototype += " " + parameterNames.at(p); + prototype += ' ' + parameterNames.at(p); if (numDefArgs >= parameterTypes.count() - p) prototype += " = 0"; if (p < parameterTypes.count() - 1) prototype += ", "; } - prototype += ")"; + prototype += ')'; return prototype; } @@ -196,8 +196,8 @@ QString qax_generateDocumentation(QAxBase *that) prototype = namedPrototype(slot.parameterTypes(), slot.parameterNames()); QString detail = QString::fromLatin1("

    ") + - QString::fromLatin1(returntype.constData()) + QLatin1String(" ") + - QString::fromLatin1(name.constData()) + QLatin1String(" ") + + QLatin1String(returntype.constData()) + QLatin1Char(' ') + + QLatin1String(name.constData()) + QLatin1Char(' ') + QString::fromLatin1(prototype.constData()) + QLatin1String(" [slot]

    \n"); prototype = namedPrototype(slot.parameterTypes(), QList()); detail += docuFromName(typeInfo, QString::fromLatin1(name.constData())); @@ -220,14 +220,14 @@ QString qax_generateDocumentation(QAxBase *that) returntype = "QAxObject *"; } if (returntype != "void") - detail += QString::fromLatin1(returntype.constData()) + QLatin1String(" result = "); - detail += QLatin1String("object->") + QString::fromLatin1(functionToCall.constData()) + - QLatin1String("(\"" + name + prototype + "\""); + detail += QLatin1String(returntype.constData()) + QLatin1String(" result = "); + detail += QLatin1String("object->") + QLatin1String(functionToCall.constData()) + + QLatin1String("(\"" + name + prototype + '\"'); if (hasParams) detail += QLatin1String(", params"); - detail += QLatin1String(")"); + detail += QLatin1Char(')'); if (returntype != "void" && returntype != "QAxObject *" && returntype != "QVariant") - detail += QLatin1String(".") + QString::fromLatin1(toType(returntype)); + detail += QLatin1Char('.') + QLatin1String(toType(returntype)); detail += QLatin1String(";\n"); } else { detail += QLatin1String("

    This function has parameters of unsupported types and cannot be called directly."); @@ -262,9 +262,9 @@ QString qax_generateDocumentation(QAxBase *that) QByteArray name = signature.left(signature.indexOf('(')); stream << "

  • void " << name << "" << prototype << ";
  • " << endl; - QString detail = QLatin1String("

    void ") + - QString::fromLatin1(name.constData()) + QLatin1String(" ") + - QString::fromLatin1(prototype.constData()) + QLatin1String(" [signal]

    \n"); + QString detail = QLatin1String("

    void ") + + QLatin1String(name.constData()) + QLatin1Char(' ') + + QLatin1String(prototype.constData()) + QLatin1String(" [signal]

    \n"); if (typeLib) { interCount = 0; do { @@ -311,8 +311,8 @@ QString qax_generateDocumentation(QAxBase *that) stream << "
  • " << type << " " << name << ";
  • " << endl; QString detail = QLatin1String("

    ") + - QString::fromLatin1(type.constData()) + - QLatin1String(" ") + QString::fromLatin1(name.constData()) + QLatin1String("

    \n"); + QLatin1String(type.constData()) + + QLatin1Char(' ') + QLatin1String(name.constData()) + QLatin1String("\n"); detail += docuFromName(typeInfo, QString::fromLatin1(name)); QVariant::Type vartype = QVariant::nameToType(type); if (!prop.isReadable()) @@ -326,14 +326,14 @@ QString qax_generateDocumentation(QAxBase *that) if (prop.isEnumType()) detail += QLatin1String("\tint val = "); else - detail += QLatin1String("\t") + QString::fromLatin1(type.constData()) + QLatin1String(" val = "); - detail += QLatin1String("object->property(\"") + QString::fromLatin1(name.constData()) + - QLatin1String("\").") + QString::fromLatin1(toType(type).constData()) + QLatin1String(";\n"); + detail += QLatin1Char('\t') + QLatin1String(type.constData()) + QLatin1String(" val = "); + detail += QLatin1String("object->property(\"") + QLatin1String(name.constData()) + + QLatin1String("\").") + QLatin1String(toType(type).constData()) + QLatin1String(";\n"); detail += QLatin1String("\n"); } else if (type == "IDispatch*" || type == "IUnknown*") { detail += QLatin1String("

    Get the subobject using querySubObject:

    \n");
    -		detail += QLatin1String("\tQAxObject *") + QString::fromLatin1(name.constData()) +
    -                          QLatin1String(" = object->querySubObject(\"") + QString::fromLatin1(name.constData()) + QLatin1String("\");\n");
    +		detail += QLatin1String("\tQAxObject *") + QLatin1String(name.constData()) +
    +                          QLatin1String(" = object->querySubObject(\"") + QLatin1String(name.constData()) + QLatin1String("\");\n");
     		detail += QLatin1String("
    \n"); } else { detail += QLatin1String("

    This property is of an unsupported type.\n"); diff --git a/src/activeqt/container/qaxscript.cpp b/src/activeqt/container/qaxscript.cpp index c69fea0..8f8186a 100644 --- a/src/activeqt/container/qaxscript.cpp +++ b/src/activeqt/container/qaxscript.cpp @@ -1203,9 +1203,9 @@ QString QAxScriptManager::scriptFileFilter() continue; allFiles += QLatin1String(" *") + engine.extension; - specialFiles += QLatin1String(";;") + engine.name + QLatin1String(" Files (*") + engine.extension + QLatin1String(")"); + specialFiles += QLatin1String(";;") + engine.name + QLatin1String(" Files (*") + engine.extension + QLatin1Char(')'); } - allFiles += QLatin1String(")"); + allFiles += QLatin1Char(')'); return allFiles + specialFiles + QLatin1String(";;All Files (*.*)"); } diff --git a/src/activeqt/control/qaxserver.cpp b/src/activeqt/control/qaxserver.cpp index d919382..1771293 100644 --- a/src/activeqt/control/qaxserver.cpp +++ b/src/activeqt/control/qaxserver.cpp @@ -90,7 +90,7 @@ QAxFactory *qAxFactory() QStringList keys(qax_factory->featureList()); for (int i = 0; i < keys.count(); ++i) { QString key(keys.at(i)); - qRegisterMetaType((key + QLatin1String("*")).toLatin1(), (void**)0); + qRegisterMetaType((key + QLatin1Char('*')).toLatin1(), (void**)0); } } return qax_factory; @@ -208,9 +208,9 @@ HRESULT UpdateRegistry(BOOL bRegister) { qAxIsServer = false; QString file = QString::fromLocal8Bit(qAxModuleFilename); - QString path = file.left(file.lastIndexOf(QLatin1String("\\"))+1); + QString path = file.left(file.lastIndexOf(QLatin1Char('\\'))+1); QString module = file.right(file.length() - path.length()); - module = module.left(module.lastIndexOf(QLatin1String("."))); + module = module.left(module.lastIndexOf(QLatin1Char('.'))); const QString appId = qAxFactory()->appID().toString().toUpper(); const QString libId = qAxFactory()->typeLibID().toString().toUpper(); @@ -226,7 +226,7 @@ HRESULT UpdateRegistry(BOOL bRegister) DWORD major = libAttr->wMajorVerNum; DWORD minor = libAttr->wMinorVerNum; - typeLibVersion = QString::number((uint)major) + QLatin1String(".") + QString::number((uint)minor); + typeLibVersion = QString::number((uint)major) + QLatin1Char('.') + QString::number((uint)minor); if (bRegister) RegisterTypeLib(qAxTypeLibrary, (TCHAR*)libFile.utf16(), 0); @@ -271,12 +271,12 @@ HRESULT UpdateRegistry(BOOL bRegister) className = qax_clean_type(className, mo); if (object) { // don't register subobject classes - QString classVersion = mo ? QString(QLatin1String(mo->classInfo(mo->indexOfClassInfo("Version")).value())) : QString(); + QString classVersion = mo ? QString::fromLatin1(mo->classInfo(mo->indexOfClassInfo("Version")).value()) : QString(); if (classVersion.isNull()) classVersion = QLatin1String("1.0"); bool insertable = mo && !qstricmp(mo->classInfo(mo->indexOfClassInfo("Insertable")).value(), "yes"); bool control = object->isWidgetType(); - const QString classMajorVersion = classVersion.left(classVersion.indexOf(QLatin1String("."))); + const QString classMajorVersion = classVersion.left(classVersion.indexOf(QLatin1Char('.'))); uint olemisc = OLEMISC_SETCLIENTSITEFIRST |OLEMISC_ACTIVATEWHENVISIBLE |OLEMISC_INSIDEOUT @@ -287,17 +287,17 @@ HRESULT UpdateRegistry(BOOL bRegister) else if (qFindChild(object) && !qax_disable_inplaceframe) olemisc |= OLEMISC_WANTSTOMENUMERGE; - settings.setValue(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String(".") + classMajorVersion + QLatin1String("/."), className + QLatin1String(" Class")); - settings.setValue(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String(".") + classMajorVersion + QLatin1String("/CLSID/."), classId); + settings.setValue(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1Char('.') + classMajorVersion + QLatin1String("/."), className + QLatin1String(" Class")); + settings.setValue(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1Char('.') + classMajorVersion + QLatin1String("/CLSID/."), classId); if (insertable) - settings.setValue(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String(".") + classMajorVersion + QLatin1String("/Insertable/."), QVariant(QLatin1String(""))); + settings.setValue(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1Char('.') + classMajorVersion + QLatin1String("/Insertable/."), QVariant(QLatin1String(""))); - settings.setValue(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String("/."), className + QLatin1String(" Class")); - settings.setValue(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String("/CLSID/."), classId); - settings.setValue(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String("/CurVer/."), module + QLatin1String(".") + className + QLatin1String(".") + classMajorVersion); + settings.setValue(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1String("/."), className + QLatin1String(" Class")); + settings.setValue(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1String("/CLSID/."), classId); + settings.setValue(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1String("/CurVer/."), module + QLatin1Char('.') + className + QLatin1Char('.') + classMajorVersion); settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/."), className + QLatin1String(" Class")); - if (file.right(3).toLower() == QLatin1String("exe")) + if (file.endsWith(QLatin1String("exe"), Qt::CaseInsensitive)) settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/AppID"), appId); if (control) settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/Control/."), QVariant(QLatin1String(""))); @@ -307,15 +307,15 @@ HRESULT UpdateRegistry(BOOL bRegister) settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/InProcServer32/."), file); else settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/LocalServer32/."), - QLatin1String("\"") + file + QLatin1String("\" -activex")); + QLatin1Char('\"') + file + QLatin1String("\" -activex")); settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/MiscStatus/."), control ? QLatin1String("1") : QLatin1String("0")); settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/MiscStatus/1/."), QString::number(olemisc)); settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/Programmable/."), QVariant(QLatin1String(""))); - settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/ToolboxBitmap32/."), QLatin1String("\"") + + settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/ToolboxBitmap32/."), QLatin1Char('\"') + file + QLatin1String("\", 101")); settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/TypeLib/."), libId); settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/Version/."), classVersion); - settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/VersionIndependentProgID/."), module + QLatin1String(".") + className); - settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/ProgID/."), module + QLatin1String(".") + className + QLatin1String(".") + classVersion.left(classVersion.indexOf(QLatin1Char('.')))); + settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/VersionIndependentProgID/."), module + QLatin1Char('.') + className); + settings.setValue(QLatin1String("/CLSID/") + classId + QLatin1String("/ProgID/."), module + QLatin1Char('.') + className + QLatin1Char('.') + classVersion.left(classVersion.indexOf(QLatin1Char('.')))); QString mime = QLatin1String(mo->classInfo(mo->indexOfClassInfo("MIME")).value()); if (!mime.isEmpty()) { @@ -330,15 +330,15 @@ HRESULT UpdateRegistry(BOOL bRegister) mime = mime.left(mime.length() - extension.length() - 1); // Prepend '.' before extension, if required. extension = extension.trimmed(); - if (extension[0] != QChar(QLatin1Char('.'))) - extension = QLatin1String(".") + extension; + if (extension[0] != QLatin1Char('.')) + extension = QLatin1Char('.') + extension; } if (!extension.isEmpty()) { - settings.setValue(QLatin1String("/") + extension + QLatin1String("/."), module + QLatin1String(".") + className); - settings.setValue(QLatin1String("/") + extension + QLatin1String("/Content Type"), mime); + settings.setValue(QLatin1Char('/') + extension + QLatin1String("/."), module + QLatin1Char('.') + className); + settings.setValue(QLatin1Char('/') + extension + QLatin1String("/Content Type"), mime); - mime = mime.replace(QLatin1String("/"), QLatin1String("\\")); + mime = mime.replace(QLatin1Char('/'), QLatin1Char('\\')); settings.setValue(QLatin1String("/MIME/Database/Content Type/") + mime + QLatin1String("/CLSID"), classId); settings.setValue(QLatin1String("/MIME/Database/Content Type/") + mime + QLatin1String("/Extension"), extension); } @@ -358,22 +358,22 @@ HRESULT UpdateRegistry(BOOL bRegister) const QString classId = qAxFactory()->classID(className).toString().toUpper(); className = qax_clean_type(className, mo); - QString classVersion = mo ? QString(QLatin1String(mo->classInfo(mo->indexOfClassInfo("Version")).value())) : QString(); + QString classVersion = mo ? QString::fromLatin1(mo->classInfo(mo->indexOfClassInfo("Version")).value()) : QString(); if (classVersion.isNull()) classVersion = QLatin1String("1.0"); - const QString classMajorVersion = classVersion.left(classVersion.indexOf(QLatin1String("."))); + const QString classMajorVersion = classVersion.left(classVersion.indexOf(QLatin1Char('.'))); qAxFactory()->unregisterClass(*key, &settings); - settings.remove(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String(".") + classMajorVersion + QLatin1String("/CLSID/.")); - settings.remove(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String(".") + classMajorVersion + QLatin1String("/Insertable/.")); - settings.remove(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String(".") + classMajorVersion + QLatin1String("/.")); - settings.remove(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String(".") + classMajorVersion); + settings.remove(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1Char('.') + classMajorVersion + QLatin1String("/CLSID/.")); + settings.remove(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1Char('.') + classMajorVersion + QLatin1String("/Insertable/.")); + settings.remove(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1Char('.') + classMajorVersion + QLatin1String("/.")); + settings.remove(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1Char('.') + classMajorVersion); - settings.remove(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String("/CLSID/.")); - settings.remove(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String("/CurVer/.")); - settings.remove(QLatin1String("/") + module + QLatin1String(".") + className + QLatin1String("/.")); - settings.remove(QLatin1String("/") + module + QLatin1String(".") + className); + settings.remove(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1String("/CLSID/.")); + settings.remove(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1String("/CurVer/.")); + settings.remove(QLatin1Char('/') + module + QLatin1Char('.') + className + QLatin1String("/.")); + settings.remove(QLatin1Char('/') + module + QLatin1Char('.') + className); settings.remove(QLatin1String("/CLSID/") + classId + QLatin1String("/AppID")); settings.remove(QLatin1String("/CLSID/") + classId + QLatin1String("/Control/.")); @@ -404,14 +404,14 @@ HRESULT UpdateRegistry(BOOL bRegister) mime = mime.left(mime.length() - extension.length() - 1); // Prepend '.' before extension, if required. extension = extension.trimmed(); - if (extension[0] != QChar(QLatin1Char('.'))) - extension = QLatin1String(".") + extension; + if (extension[0] != QLatin1Char('.')) + extension.prepend(QLatin1Char('.')); } if (!extension.isEmpty()) { - settings.remove(QLatin1String("/") + extension + QLatin1String("/Content Type")); - settings.remove(QLatin1String("/") + extension + QLatin1String("/.")); - settings.remove(QLatin1String("/") + extension); - mime = mime.replace(QLatin1String("/"), QLatin1String("\\")); + settings.remove(QLatin1Char('/') + extension + QLatin1String("/Content Type")); + settings.remove(QLatin1Char('/') + extension + QLatin1String("/.")); + settings.remove(QLatin1Char('/') + extension); + mime.replace(QLatin1Char('/'), QLatin1Char('\\')); settings.remove(QLatin1String("/MIME/Database/Content Type/") + mime + QLatin1String("/Extension")); settings.remove(QLatin1String("/MIME/Database/Content Type/") + mime + QLatin1String("/CLSID")); settings.remove(QLatin1String("/MIME/Database/Content Type/") + mime + QLatin1String("/.")); @@ -455,8 +455,8 @@ static const char* const type_map[][2] = { "QFont", "IFontDisp*" }, { "QPixmap", "IPictureDisp*" }, { "QVariant", "VARIANT" }, - { "QVariantList", "SAFEARRAY(VARIANT)" }, - { "QList","SAFEARRAY(VARIANT)" }, + { "QVariantList", "SAFEARRAY(VARIANT)" }, + { "QList", "SAFEARRAY(VARIANT)" }, { "quint64", "CY" }, { "qint64", "CY" }, { "qulonglong", "CY" }, @@ -464,8 +464,8 @@ static const char* const type_map[][2] = { "QByteArray", "SAFEARRAY(BYTE)" }, { "QStringList", "SAFEARRAY(BSTR)" }, // Userdefined Qt datatypes - some not on Borland though - { "QCursor", "enum MousePointer" }, - { "Qt::FocusPolicy","enum FocusPolicy" }, + { "QCursor", "enum MousePointer" }, + { "Qt::FocusPolicy", "enum FocusPolicy" }, #ifndef Q_CC_BOR # if __REQUIRED_RPCNDR_H_VERSION__ >= Q_REQUIRED_RPCNDR_H_VERSION { "QRect", "struct QRect" }, @@ -578,7 +578,7 @@ static QByteArray renameOverloads(const QByteArray &name) int n = mapping.value(name); if (mapping.contains(name)) { int n = mapping.value(name); - newName = name + "_" + QByteArray::number(n); + newName = name + '_' + QByteArray::number(n); mapping.insert(name, n+1); } else { mapping.insert(name, 1); @@ -686,13 +686,13 @@ static QByteArray prototype(const QList ¶meterTypes, const QList QByteArray type(parameterTypes.at(p)); QByteArray name(parameterNames.at(p)); - if (type.endsWith("&")) { + if (type.endsWith('&')) { out = true; type.truncate(type.length() - 1); } else if (type.endsWith("**")) { out = true; type.truncate(type.length() - 1); - } else if (type.endsWith("*") && !subtypes.contains(type)) { + } else if (type.endsWith('*') && !subtypes.contains(type)) { type.truncate(type.length() - 1); } if (type.isEmpty()) { @@ -701,14 +701,14 @@ static QByteArray prototype(const QList ¶meterTypes, const QList } type = convertTypes(type, ok); if (!out) - prototype += "[in] " + type + " "; + prototype += "[in] " + type + ' '; else - prototype += "[in,out] " + type + " "; + prototype += "[in,out] " + type + ' '; if (out) - prototype += "*"; + prototype += '*'; if (name.isEmpty()) - prototype += "p" + QByteArray::number(p); + prototype += 'p' + QByteArray::number(p); else prototype += "p_" + replaceKeyword(name); @@ -728,12 +728,12 @@ static QByteArray addDefaultArguments(const QByteArray &prototype, int numDefArg QByteArray ptype(prototype); int in = -1; while (numDefArgs) { - in = ptype.lastIndexOf("]", in); + in = ptype.lastIndexOf(']', in); ptype.replace(in, 1, ",optional]"); in = ptype.indexOf(' ', in) + 1; QByteArray type = ptype.mid(in, ptype.indexOf(' ', in) - in); if (type == "enum") - type += " " + ptype.mid(in + 5, ptype.indexOf(' ', in + 5) - in - 5); + type += ' ' + ptype.mid(in + 5, ptype.indexOf(' ', in + 5) - in - 5); ptype.replace(in, type.length(), QByteArray("VARIANT /*was: ") + type + "*/"); --numDefArgs; } @@ -801,7 +801,7 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN for (int j = 0; j < enumerator.keyCount(); ++j) { QByteArray key(enumerator.key(j)); while (enumValues.contains(key)) { - key += "_"; + key += '_'; } enumValues.append(key); uint value = (uint)enumerator.value(j); @@ -822,32 +822,32 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN if (!enums.contains("MousePointer")) { enums.append("MousePointer"); out << "\tenum MousePointer {" << endl; - out << "\t\tArrowCursor = " << Qt::ArrowCursor << "," << endl; - out << "\t\tUpArrowCursor = " << Qt::UpArrowCursor << "," << endl; - out << "\t\tCrossCursor = " << Qt::CrossCursor << "," << endl; - out << "\t\tWaitCursor = " << Qt::WaitCursor << "," << endl; - out << "\t\tIBeamCursor = " << Qt::IBeamCursor << "," << endl; - out << "\t\tSizeVerCursor = " << Qt::SizeVerCursor << "," << endl; - out << "\t\tSizeHorCursor = " << Qt::SizeHorCursor << "," << endl; - out << "\t\tSizeBDiagCursor = " << Qt::SizeBDiagCursor << "," << endl; - out << "\t\tSizeFDiagCursor = " << Qt::SizeFDiagCursor << "," << endl; - out << "\t\tSizeAllCursor = " << Qt::SizeAllCursor << "," << endl; - out << "\t\tBlankCursor = " << Qt::BlankCursor << "," << endl; - out << "\t\tSplitVCursor = " << Qt::SplitVCursor << "," << endl; - out << "\t\tSplitHCursor = " << Qt::SplitHCursor << "," << endl; - out << "\t\tPointingHandCursor = " << Qt::PointingHandCursor << "," << endl; - out << "\t\tForbiddenCursor = " << Qt::ForbiddenCursor << "," << endl; - out << "\t\tWhatsThisCursor = " << Qt::WhatsThisCursor << "," << endl; + out << "\t\tArrowCursor = " << Qt::ArrowCursor << ',' << endl; + out << "\t\tUpArrowCursor = " << Qt::UpArrowCursor << ',' << endl; + out << "\t\tCrossCursor = " << Qt::CrossCursor << ',' << endl; + out << "\t\tWaitCursor = " << Qt::WaitCursor << ',' << endl; + out << "\t\tIBeamCursor = " << Qt::IBeamCursor << ',' << endl; + out << "\t\tSizeVerCursor = " << Qt::SizeVerCursor << ',' << endl; + out << "\t\tSizeHorCursor = " << Qt::SizeHorCursor << ',' << endl; + out << "\t\tSizeBDiagCursor = " << Qt::SizeBDiagCursor << ',' << endl; + out << "\t\tSizeFDiagCursor = " << Qt::SizeFDiagCursor << ',' << endl; + out << "\t\tSizeAllCursor = " << Qt::SizeAllCursor << ',' << endl; + out << "\t\tBlankCursor = " << Qt::BlankCursor << ',' << endl; + out << "\t\tSplitVCursor = " << Qt::SplitVCursor << ',' << endl; + out << "\t\tSplitHCursor = " << Qt::SplitHCursor << ',' << endl; + out << "\t\tPointingHandCursor = " << Qt::PointingHandCursor << ',' << endl; + out << "\t\tForbiddenCursor = " << Qt::ForbiddenCursor << ',' << endl; + out << "\t\tWhatsThisCursor = " << Qt::WhatsThisCursor << ',' << endl; out << "\t\tBusyCursor\t= " << Qt::BusyCursor << endl; out << "\t};" << endl << endl; } if (!enums.contains("FocusPolicy")) { enums.append("FocusPolicy"); out << "\tenum FocusPolicy {" << endl; - out << "\t\tNoFocus = " << Qt::NoFocus << "," << endl; - out << "\t\tTabFocus = " << Qt::TabFocus << "," << endl; - out << "\t\tClickFocus = " << Qt::ClickFocus << "," << endl; - out << "\t\tStrongFocus = " << Qt::StrongFocus << "," << endl; + out << "\t\tNoFocus = " << Qt::NoFocus << ',' << endl; + out << "\t\tTabFocus = " << Qt::TabFocus << ',' << endl; + out << "\t\tClickFocus = " << Qt::ClickFocus << ',' << endl; + out << "\t\tStrongFocus = " << Qt::StrongFocus << ',' << endl; out << "\t\tWheelFocus = " << Qt::WheelFocus << endl; out << "\t};" << endl << endl; } @@ -877,7 +877,7 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN if (!ok) out << "\t/****** Property is of unsupported datatype" << endl; - out << "\t\t[id(" << id << ")"; + out << "\t\t[id(" << id << ')'; if (!property.isWritable()) out << ", readonly"; if (isBindable && property.isScriptable(o)) @@ -886,9 +886,9 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN out << ", nonbrowsable"; if (isBindable) out << ", requestedit"; - if (defProp == QString::fromLatin1(name.constData())) + if (defProp == QLatin1String(name)) out << ", uidefault"; - out << "] " << type << " " << name << ";" << endl; + out << "] " << type << ' ' << name << ';' << endl; if (!ok) out << "\t******/" << endl; @@ -939,7 +939,7 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN if (!ok) outBuffer += "\t/****** Slot parameter uses unsupported datatype\n"; - outBuffer += "\t\t[id(" + QString::number(id).toLatin1() + ")] " + type + " " + name + "(" + ptype + ");\n"; + outBuffer += "\t\t[id(" + QString::number(id).toLatin1() + ")] " + type + ' ' + name + '(' + ptype + ");\n"; if (!ok) outBuffer += "\t******/\n"; @@ -991,7 +991,7 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN QList parameterTypes(signal.parameterTypes()); QList parameterNames(signal.parameterNames()); - bool isDefault = defSignal == QString::fromLatin1(name.constData()); + bool isDefault = defSignal == QLatin1String(name); name = renameOverloads(replaceKeyword(name)); bool ok = true; @@ -1003,10 +1003,10 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN if (!ok) out << "\t/****** Signal parameter uses unsupported datatype" << endl; - out << "\t\t[id(" << id << ")"; + out << "\t\t[id(" << id << ')'; if (isDefault) out << ", uidefault"; - out << "] void " << name << "(" << ptype << ");" << endl; + out << "] void " << name << '(' << ptype << ");" << endl; if (!ok) out << "\t******/" << endl; @@ -1031,7 +1031,7 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN const char *classVersion = mo->classInfo(mo->indexOfClassInfo("Version")).value(); if (classVersion) out << "\t\tversion(" << classVersion << ")," << endl; - out << "\t\tuuid(" << classID << ")"; + out << "\t\tuuid(" << classID << ')'; if (control) { out << ", " << endl; out << "\t\tcontrol"; @@ -1043,7 +1043,7 @@ static HRESULT classIDL(QObject *o, const QMetaObject *mo, const QString &classN out << "\t]" << endl; out << "\tcoclass " << cleanClassName << endl; out << "\t{" << endl; - out << "\t\t[default] dispinterface I" << cleanClassName << ";" << endl; + out << "\t\t[default] dispinterface I" << cleanClassName << ';' << endl; if (hasEvents) out << "\t\t[default, source] dispinterface I" << cleanClassName << "Events;" << endl; out << "\t};" << endl; @@ -1068,7 +1068,7 @@ extern "C" HRESULT __stdcall DumpIDL(const QString &outfile, const QString &ver) file.remove(); QString filebase = QString::fromLocal8Bit(qAxModuleFilename); - filebase = filebase.left(filebase.lastIndexOf(QLatin1String("."))); + filebase = filebase.left(filebase.lastIndexOf(QLatin1Char('.'))); QString appID = qAxFactory()->appID().toString().toUpper(); if (QUuid(appID).isNull()) @@ -1103,7 +1103,7 @@ extern "C" HRESULT __stdcall DumpIDL(const QString &outfile, const QString &ver) out << "/****************************************************************************" << endl; out << "** Interface definition generated for ActiveQt project" << endl; out << "**" << endl; - out << "** '" << qAxModuleFilename << "'" << endl; + out << "** '" << qAxModuleFilename << '\'' << endl; out << "**" << endl; out << "** Created: " << QDateTime::currentDateTime().toString() << endl; out << "**" << endl; @@ -1121,13 +1121,13 @@ extern "C" HRESULT __stdcall DumpIDL(const QString &outfile, const QString &ver) delete_qApp = true; } - out << "[" << endl; + out << '[' << endl; out << "\tuuid(" << typeLibID << ")," << endl; out << "\tversion(" << version << ")," << endl; - out << "\thelpstring(\"" << typelib << " " << version << " Type Library\")" << endl; - out << "]" << endl; + out << "\thelpstring(\"" << typelib << ' ' << version << " Type Library\")" << endl; + out << ']' << endl; out << "library " << typelib << "Lib" << endl; - out << "{" << endl; + out << '{' << endl; out << "\timportlib(\"stdole32.tlb\");" << endl; out << "\timportlib(\"stdole2.tlb\");" << endl << endl; @@ -1188,11 +1188,12 @@ extern "C" HRESULT __stdcall DumpIDL(const QString &outfile, const QString &ver) // We have meta object information for this type. Forward declare it. if (mo) { QByteArray cleanType = qax_clean_type(*key, mo).toLatin1(); - out << "\tcoclass " << cleanType << ";" << endl; + out << "\tcoclass " << cleanType << ';' << endl; + subtypes.append(cleanType); + qRegisterMetaType(cleanType, (void**)0); + cleanType += '*'; subtypes.append(cleanType); - subtypes.append(cleanType + "*"); qRegisterMetaType(cleanType, (void**)0); - qRegisterMetaType(cleanType + "*", (void**)0); } } out << endl; @@ -1225,7 +1226,7 @@ extern "C" HRESULT __stdcall DumpIDL(const QString &outfile, const QString &ver) QByteArray cleanType = qax_clean_type(*key, mo).toLatin1(); subtypes.append(cleanType); - subtypes.append(cleanType + "*"); + subtypes.append(cleanType + '*'); res = classIDL(o, mo, QString::fromLatin1(className.constData()), isBindable, out); delete o; if (res != S_OK) diff --git a/src/activeqt/control/qaxserverbase.cpp b/src/activeqt/control/qaxserverbase.cpp index f3e1dff..19c2404 100644 --- a/src/activeqt/control/qaxserverbase.cpp +++ b/src/activeqt/control/qaxserverbase.cpp @@ -2446,10 +2446,10 @@ HRESULT WINAPI QAxServerBase::Invoke(DISPID dispidMember, REFIID riid, int nameLength = 0; if (index == -1) { nameLength = name.length(); - name += "("; + name += '('; // no parameter - shortcut if (!pDispParams->cArgs) - index = mo->indexOfSlot((name + ")")); + index = mo->indexOfSlot((name + ')')); // search if (index == -1) { for (int i = 0; i < mo->methodCount(); ++i) { @@ -2463,7 +2463,7 @@ HRESULT WINAPI QAxServerBase::Invoke(DISPID dispidMember, REFIID riid, if (index == -1) { QRegExp regexp(QLatin1String("_([0-9])\\(")); if (regexp.lastIndexIn(QString::fromLatin1(name.constData())) != -1) { - name = name.left(name.length() - regexp.cap(0).length()) + "("; + name = name.left(name.length() - regexp.cap(0).length()) + '('; int overload = regexp.cap(1).toInt() + 1; for (int s = 0; s < qt.object->metaObject()->methodCount(); ++s) { @@ -2559,7 +2559,7 @@ HRESULT WINAPI QAxServerBase::Invoke(DISPID dispidMember, REFIID riid, argv[p + 1] = varp + p + 1; } else { argv[p + 1] = const_cast(varp[p + 1].constData()); - if (ptype.endsWith("*")) { + if (ptype.endsWith('*')) { argv_pointer[p + 1] = argv[p + 1]; argv[p + 1] = argv_pointer + p + 1; } @@ -2590,7 +2590,7 @@ HRESULT WINAPI QAxServerBase::Invoke(DISPID dispidMember, REFIID riid, } else { argv[0] = const_cast(varp[0].constData()); } - if (type.endsWith("*")) { + if (type.endsWith('*')) { argv_pointer[0] = argv[0]; argv[0] = argv_pointer; } diff --git a/src/activeqt/control/qaxservermain.cpp b/src/activeqt/control/qaxservermain.cpp index a50fef0..e3e1e5d 100644 --- a/src/activeqt/control/qaxservermain.cpp +++ b/src/activeqt/control/qaxservermain.cpp @@ -253,7 +253,7 @@ EXTERN_C int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR, run = false; break; } else { - unprocessed += cmds.at(i) + " "; + unprocessed += cmds.at(i) + ' '; } } diff --git a/src/activeqt/shared/qaxtypes.cpp b/src/activeqt/shared/qaxtypes.cpp index ace81e7..12307f3 100644 --- a/src/activeqt/shared/qaxtypes.cpp +++ b/src/activeqt/shared/qaxtypes.cpp @@ -1111,7 +1111,7 @@ QVariant VARIANTToQVariant(const VARIANT &arg, const QByteArray &typeName, uint if (iface) { QObject *qObj = iface->qObject(); iface->Release(); - var = QVariant(qRegisterMetaType(qObj ? QByteArray(qObj->metaObject()->className()) + "*" : typeName), &qObj); + var = QVariant(qRegisterMetaType(qObj ? QByteArray(qObj->metaObject()->className()) + '*' : typeName), &qObj); } else #endif { diff --git a/src/corelib/io/qfsfileengine_unix.cpp b/src/corelib/io/qfsfileengine_unix.cpp index 8ea48d1..3c443ff 100644 --- a/src/corelib/io/qfsfileengine_unix.cpp +++ b/src/corelib/io/qfsfileengine_unix.cpp @@ -83,12 +83,12 @@ static QByteArray openModeToFopenMode(QIODevice::OpenMode flags, const QString & } else if (flags & QIODevice::WriteOnly) { mode = "wb"; if (flags & QIODevice::ReadOnly) - mode += "+"; + mode += '+'; } if (flags & QIODevice::Append) { mode = "ab"; if (flags & QIODevice::ReadOnly) - mode += "+"; + mode += '+'; } return mode; } @@ -723,7 +723,7 @@ QString QFSFileEngine::fileName(FileName file) const bool isDir = ret.endsWith(QLatin1Char('/')); ret = QDir::cleanPath(ret); if (isDir) - ret += QLatin1String("/"); + ret += QLatin1Char('/'); if (file == AbsolutePathName) { int slash = ret.lastIndexOf(QLatin1Char('/')); if (slash == -1) diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp index 0b87e2b..790f1eb 100644 --- a/src/corelib/io/qfsfileengine_win.cpp +++ b/src/corelib/io/qfsfileengine_win.cpp @@ -1770,10 +1770,10 @@ QString QFSFileEngine::fileName(FileName file) const if(slash == -1) { if(d->filePath.length() >= 2 && d->filePath.at(1) == QLatin1Char(':')) return d->filePath.left(2); - return QString::fromLatin1("."); + return QLatin1Char('.'); } else { if(!slash) - return QString::fromLatin1("/"); + return QLatin1Char('/'); if(slash == 2 && d->filePath.length() >= 2 && d->filePath.at(1) == QLatin1Char(':')) slash++; return d->filePath.left(slash); @@ -1831,7 +1831,7 @@ QString QFSFileEngine::fileName(FileName file) const if (slash == -1) ret = QDir::currentPath(); else if (slash == 0) - ret = QLatin1String("/"); + ret = QLatin1Char('/'); ret = ret.left(slash); } return ret; @@ -1893,7 +1893,7 @@ QString QFSFileEngine::owner(FileOwner own) const #else Q_UNUSED(own); #endif - return QString(QLatin1String("")); + return QString(); } bool QFSFileEngine::setPermissions(uint perms) diff --git a/src/corelib/io/qurl.cpp b/src/corelib/io/qurl.cpp index 94a53f1..5846e23 100644 --- a/src/corelib/io/qurl.cpp +++ b/src/corelib/io/qurl.cpp @@ -5330,7 +5330,7 @@ QString QUrl::toString(FormattingOptions options) const url += QLatin1Char('/'); url += ourPath; // check if we need to remove trailing slashes - while ((options & StripTrailingSlash) && url.right(1) == QLatin1String("/")) + while ((options & StripTrailingSlash) && url.endsWith(QLatin1Char('/'))) url.chop(1); } diff --git a/src/corelib/kernel/qcoreapplication.cpp b/src/corelib/kernel/qcoreapplication.cpp index 6847173..cb40f19 100644 --- a/src/corelib/kernel/qcoreapplication.cpp +++ b/src/corelib/kernel/qcoreapplication.cpp @@ -1908,7 +1908,7 @@ QStringList QCoreApplication::arguments() wchar_t tempFilename[MAX_PATH+1]; if (GetModuleFileNameW(0, tempFilename, MAX_PATH)) { tempFilename[MAX_PATH] = 0; - cmdline.prepend(QLatin1Char('\"') + QString::fromUtf16((unsigned short *)tempFilename) + QString(QLatin1String("\" "))); + cmdline.prepend(QLatin1Char('\"') + QString::fromUtf16((unsigned short *)tempFilename) + QLatin1String("\" ")); } #endif // Q_OS_WINCE diff --git a/src/corelib/kernel/qcoreapplication_win.cpp b/src/corelib/kernel/qcoreapplication_win.cpp index 9868c23..815a558 100644 --- a/src/corelib/kernel/qcoreapplication_win.cpp +++ b/src/corelib/kernel/qcoreapplication_win.cpp @@ -840,7 +840,7 @@ QString decodeMSG(const MSG& msg) FLGSTR(ISC_SHOWUICANDIDATEWINDOW << 2), FLGSTR(ISC_SHOWUICANDIDATEWINDOW << 3), FLAG_STRING()); - parameters.sprintf("Input context(%s) Show flags(%s)", (fSet?"Active":"Inactive"), showFlgs.toLatin1().data()); + parameters.sprintf("Input context(%s) Show flags(%s)", (fSet? "Active" : "Inactive"), showFlgs.toLatin1().data()); } break; #endif diff --git a/src/corelib/plugin/qlibrary_unix.cpp b/src/corelib/plugin/qlibrary_unix.cpp index 08bd2d0..de1baac 100644 --- a/src/corelib/plugin/qlibrary_unix.cpp +++ b/src/corelib/plugin/qlibrary_unix.cpp @@ -71,7 +71,7 @@ static QString qdlerror() #else const char *err = strerror(errno); #endif - return err ? QLatin1String("(")+QString::fromLocal8Bit(err) + QLatin1String(")"): QString(); + return err ? QLatin1Char('(') + QString::fromLocal8Bit(err) + QLatin1Char(')'): QString(); } bool QLibraryPrivate::load_sys() diff --git a/src/corelib/tools/qdatetime.cpp b/src/corelib/tools/qdatetime.cpp index 090ca61..de41360 100644 --- a/src/corelib/tools/qdatetime.cpp +++ b/src/corelib/tools/qdatetime.cpp @@ -4688,7 +4688,7 @@ QDateTimeParser::StateNode QDateTimeParser::parse(QString &input, int &cursorPos if (fixup && tmpstate == Intermediate && used < sn.count) { const FieldInfo fi = fieldInfo(index); if ((fi & (Numeric|FixedWidth)) == (Numeric|FixedWidth)) { - const QString newText = QString(QLatin1String("%1")).arg(num, sn.count, 10, QLatin1Char('0')); + const QString newText = QString::fromLatin1("%1").arg(num, sn.count, 10, QLatin1Char('0')); input.replace(pos, used, newText); used = sn.count; } diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp index 248137a..9953155 100644 --- a/src/corelib/tools/qlocale.cpp +++ b/src/corelib/tools/qlocale.cpp @@ -321,7 +321,7 @@ static QString readEscapedFormatString(const QString &format, int *idx) { int &i = *idx; - Q_ASSERT(format.at(i).unicode() == '\''); + Q_ASSERT(format.at(i) == QLatin1Char('\'')); ++i; if (i == format.size()) return QString(); @@ -635,7 +635,7 @@ static QLocale::MeasurementSystem winSystemMeasurementSystem() QString iMeasure = QT_WA_INLINE( QString::fromUtf16(reinterpret_cast(output)), QString::fromLocal8Bit(reinterpret_cast(output))); - if (iMeasure == QString::fromLatin1("1")) { + if (iMeasure == QLatin1String("1")) { return QLocale::ImperialSystem; } } diff --git a/src/corelib/xml/qxmlstream.cpp b/src/corelib/xml/qxmlstream.cpp index ff1a01f..5e1fec3 100644 --- a/src/corelib/xml/qxmlstream.cpp +++ b/src/corelib/xml/qxmlstream.cpp @@ -3058,7 +3058,7 @@ QXmlStreamPrivateTagStack::NamespaceDeclaration &QXmlStreamWriterPrivate::findNa QString s; int n = ++namespacePrefixCount; forever { - s = QLatin1String("n") + QString::number(n++); + s = QLatin1Char('n') + QString::number(n++); int j = namespaceDeclarations.size() - 2; while (j >= 0 && namespaceDeclarations.at(j).prefix != s) --j; diff --git a/src/dbus/qdbuserror.cpp b/src/dbus/qdbuserror.cpp index 955a31c..2347a54 100644 --- a/src/dbus/qdbuserror.cpp +++ b/src/dbus/qdbuserror.cpp @@ -339,7 +339,7 @@ QString QDBusError::errorString(ErrorType error) #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QDBusError &msg) { - dbg.nospace() << "QDBusError(" << msg.name() << ", " << msg.message() << ")"; + dbg.nospace() << "QDBusError(" << msg.name() << ", " << msg.message() << ')'; return dbg.space(); } #endif diff --git a/src/dbus/qdbusintegrator.cpp b/src/dbus/qdbusintegrator.cpp index f40a45f..33f44ab 100644 --- a/src/dbus/qdbusintegrator.cpp +++ b/src/dbus/qdbusintegrator.cpp @@ -74,7 +74,7 @@ static inline QDebug operator<<(QDebug dbg, const QThread *th) dbg.nospace() << "QThread(ptr=" << (void*)th; if (th && !th->objectName().isEmpty()) dbg.nospace() << ", name=" << th->objectName(); - dbg.nospace() << ")"; + dbg.nospace() << ')'; return dbg.space(); } @@ -90,7 +90,7 @@ static inline QDebug operator<<(QDebug dbg, const QDBusConnectionPrivate *conn) dbg.nospace() << "same thread"; else dbg.nospace() << conn->thread(); - dbg.nospace() << ")"; + dbg.nospace() << ')'; return dbg.space(); } @@ -565,7 +565,7 @@ static void huntAndEmit(DBusConnection *connection, DBusMessage *msg, QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator it = haystack.children.constBegin(); QDBusConnectionPrivate::ObjectTreeNode::DataList::ConstIterator end = haystack.children.constEnd(); for ( ; it != end; ++it) - huntAndEmit(connection, msg, needle, *it, isScriptable, isAdaptor, path + QLatin1String("/") + it->name); + huntAndEmit(connection, msg, needle, *it, isScriptable, isAdaptor, path + QLatin1Char('/') + it->name); if (needle == haystack.obj) { // is this a signal we should relay? diff --git a/src/dbus/qdbusmetaobject.cpp b/src/dbus/qdbusmetaobject.cpp index 8eb8b1a..ce76ecc 100644 --- a/src/dbus/qdbusmetaobject.cpp +++ b/src/dbus/qdbusmetaobject.cpp @@ -601,7 +601,7 @@ QDBusMetaObject *QDBusMetaObject::createMetaObject(const QString &interface, con // mark as an error error = QDBusError(QDBusError::UnknownInterface, - QString( QLatin1String("Interface '%1' was not found") ) + QString::fromLatin1("Interface '%1' was not found") .arg(interface)); return 0; } diff --git a/src/dbus/qdbusutil.cpp b/src/dbus/qdbusutil.cpp index 471b899..dd983a0 100644 --- a/src/dbus/qdbusutil.cpp +++ b/src/dbus/qdbusutil.cpp @@ -80,15 +80,15 @@ static bool variantToString(const QVariant &arg, QString &out) int argType = arg.userType(); if (argType == QVariant::StringList) { - out += QLatin1String("{"); + out += QLatin1Char('{'); QStringList list = arg.toStringList(); foreach (QString item, list) out += QLatin1Char('\"') + item + QLatin1String("\", "); if (!list.isEmpty()) out.chop(2); - out += QLatin1String("}"); + out += QLatin1Char('}'); } else if (argType == QVariant::ByteArray) { - out += QLatin1String("{"); + out += QLatin1Char('{'); QByteArray list = arg.toByteArray(); for (int i = 0; i < list.count(); ++i) { out += QString::number(list.at(i)); @@ -96,9 +96,9 @@ static bool variantToString(const QVariant &arg, QString &out) } if (!list.isEmpty()) out.chop(2); - out += QLatin1String("}"); + out += QLatin1Char('}'); } else if (argType == QVariant::List) { - out += QLatin1String("{"); + out += QLatin1Char('{'); QList list = arg.toList(); foreach (QVariant item, list) { if (!variantToString(item, out)) @@ -107,7 +107,7 @@ static bool variantToString(const QVariant &arg, QString &out) } if (!list.isEmpty()) out.chop(2); - out += QLatin1String("}"); + out += QLatin1Char('}'); } else if (argType == QMetaType::Char || argType == QMetaType::Short || argType == QMetaType::Int || argType == QMetaType::Long || argType == QMetaType::LongLong) { out += QString::number(arg.toLongLong()); @@ -142,7 +142,7 @@ static bool variantToString(const QVariant &arg, QString &out) return false; out += QLatin1Char(']'); } else if (arg.canConvert(QVariant::String)) { - out += QLatin1String("\"") + arg.toString() + QLatin1String("\""); + out += QLatin1Char('\"') + arg.toString() + QLatin1Char('\"'); } else { out += QLatin1Char('['); out += QLatin1String(arg.typeName()); @@ -226,7 +226,7 @@ bool argToString(const QDBusArgument &busArg, QString &out) if (elementType != QDBusArgument::BasicType && elementType != QDBusArgument::VariantType && elementType != QDBusArgument::MapEntryType) - out += QLatin1String("]"); + out += QLatin1Char(']'); return true; } diff --git a/src/gui/dialogs/qprintdialog_unix.cpp b/src/gui/dialogs/qprintdialog_unix.cpp index 87a4e65..8456d13 100644 --- a/src/gui/dialogs/qprintdialog_unix.cpp +++ b/src/gui/dialogs/qprintdialog_unix.cpp @@ -669,7 +669,7 @@ QUnixPrintWidgetPrivate::QUnixPrintWidgetPrivate(QUnixPrintWidget *p) for (int i = 0; i < cupsPrinterCount; ++i) { QString printerName(QString::fromLocal8Bit(cupsPrinters[i].name)); if (cupsPrinters[i].instance) - printerName += QLatin1String("/") + QString::fromLocal8Bit(cupsPrinters[i].instance); + printerName += QLatin1Char('/') + QString::fromLocal8Bit(cupsPrinters[i].instance); widget.printers->addItem(printerName); if (cupsPrinters[i].is_default) @@ -813,7 +813,7 @@ void QUnixPrintWidgetPrivate::_q_printerChanged(int index) optionsPane->selectPrinter(0); #endif if (lprPrinters.count() > 0) { - QString type = lprPrinters.at(index).name + QLatin1String("@") + lprPrinters.at(index).host; + QString type = lprPrinters.at(index).name + QLatin1Char('@') + lprPrinters.at(index).host; if (!lprPrinters.at(index).comment.isEmpty()) type += QLatin1String(", ") + lprPrinters.at(index).comment; widget.type->setText(type); @@ -1194,9 +1194,9 @@ QVariant QPPDOptionsModel::headerData(int section, Qt::Orientation, int role) co switch(section){ case 0: - return QVariant(QApplication::translate("QPPDOptionsModel","Name")); + return QVariant(QApplication::translate("QPPDOptionsModel", "Name")); case 1: - return QVariant(QApplication::translate("QPPDOptionsModel","Value")); + return QVariant(QApplication::translate("QPPDOptionsModel", "Value")); default: return QVariant(); } diff --git a/src/gui/dialogs/qprintpreviewdialog.cpp b/src/gui/dialogs/qprintpreviewdialog.cpp index 29a2738..a696160 100644 --- a/src/gui/dialogs/qprintpreviewdialog.cpp +++ b/src/gui/dialogs/qprintpreviewdialog.cpp @@ -460,7 +460,7 @@ void QPrintPreviewDialogPrivate::updatePageNumLabel() int numPages = preview->numPages(); int maxChars = QString::number(numPages).length(); - pageNumLabel->setText(QString(QLatin1String("/ %1")).arg(numPages)); + pageNumLabel->setText(QString::fromLatin1("/ %1").arg(numPages)); int cyphersWidth = q->fontMetrics().width(QString().fill(QLatin1Char('8'), maxChars)); int maxWidth = pageNumEdit->minimumSizeHint().width() + cyphersWidth; pageNumEdit->setMinimumWidth(maxWidth); @@ -611,7 +611,7 @@ void QPrintPreviewDialogPrivate::_q_zoomFactorChanged() factor = qMax(qreal(1.0), qMin(qreal(1000.0), factor)); if (ok) { preview->setZoomFactor(factor/100.0); - zoomFactor->setEditText(QString(QLatin1String("%1%")).arg(factor)); + zoomFactor->setEditText(QString::fromLatin1("%1%").arg(factor)); setFitting(false); } } diff --git a/src/gui/embedded/qmouse_qws.cpp b/src/gui/embedded/qmouse_qws.cpp index 044a574..b5eda0c 100644 --- a/src/gui/embedded/qmouse_qws.cpp +++ b/src/gui/embedded/qmouse_qws.cpp @@ -413,8 +413,8 @@ void QWSCalibratedMouseHandler::writeCalibration() QFile file(calFile); if (file.open(QIODevice::WriteOnly)) { QTextStream t(&file); - t << a << " " << b << " " << c << " "; - t << d << " " << e << " " << f << " " << s << endl; + t << a << ' ' << b << ' ' << c << ' '; + t << d << ' ' << e << ' ' << f << ' ' << s << endl; } else #endif { diff --git a/src/gui/embedded/qscreenmulti_qws.cpp b/src/gui/embedded/qscreenmulti_qws.cpp index 1914b44..a639e01 100644 --- a/src/gui/embedded/qscreenmulti_qws.cpp +++ b/src/gui/embedded/qscreenmulti_qws.cpp @@ -221,9 +221,9 @@ bool QMultiScreen::connect(const QString &displaySpec) { QString dSpec = displaySpec; if (dSpec.startsWith(QLatin1String("Multi:"), Qt::CaseInsensitive)) - dSpec = dSpec.mid(QString(QLatin1String("Multi:")).size()); + dSpec = dSpec.mid(QString::fromLatin1("Multi:").size()); - const QString displayIdSpec = QString(QLatin1String(" :%1")).arg(displayId); + const QString displayIdSpec = QString::fromLatin1(" :%1").arg(displayId); if (dSpec.endsWith(displayIdSpec)) dSpec = dSpec.left(dSpec.size() - displayIdSpec.size()); diff --git a/src/gui/embedded/qscreentransformed_qws.cpp b/src/gui/embedded/qscreentransformed_qws.cpp index e22ea1f..01a18b3 100644 --- a/src/gui/embedded/qscreentransformed_qws.cpp +++ b/src/gui/embedded/qscreentransformed_qws.cpp @@ -206,11 +206,11 @@ bool QTransformedScreen::connect(const QString &displaySpec) { QString dspec = displaySpec.trimmed(); if (dspec.startsWith(QLatin1String("Transformed:"), Qt::CaseInsensitive)) - dspec = dspec.mid(QString(QLatin1String("Transformed:")).size()); + dspec = dspec.mid(QString::fromLatin1("Transformed:").size()); else if (!dspec.compare(QLatin1String("Transformed"), Qt::CaseInsensitive)) dspec = QString(); - const QString displayIdSpec = QString(QLatin1String(" :%1")).arg(displayId); + const QString displayIdSpec = QString::fromLatin1(" :%1").arg(displayId); if (dspec.endsWith(displayIdSpec)) dspec = dspec.left(dspec.size() - displayIdSpec.size()); @@ -223,7 +223,7 @@ bool QTransformedScreen::connect(const QString &displaySpec) if (!QScreenDriverFactory::keys().contains(driver, Qt::CaseInsensitive)) if (!dspec.isEmpty()) - dspec.prepend(QLatin1String(":")); + dspec.prepend(QLatin1Char(':')); const int id = getDisplayId(dspec); QScreen *s = qt_get_screen(id, dspec.toLatin1().constData()); diff --git a/src/gui/embedded/qscreenvfb_qws.cpp b/src/gui/embedded/qscreenvfb_qws.cpp index accfe1f..ec393e3 100644 --- a/src/gui/embedded/qscreenvfb_qws.cpp +++ b/src/gui/embedded/qscreenvfb_qws.cpp @@ -330,7 +330,7 @@ void QVFbScreen::disconnect() bool QVFbScreen::initDevice() { #ifndef QT_NO_QWS_MOUSE_QVFB - const QString mouseDev = QString(QLatin1String(QT_VFB_MOUSE_PIPE)) + const QString mouseDev = QString::fromLatin1(QT_VFB_MOUSE_PIPE) .arg(displayId); d_ptr->mouse = new QVFbMouseHandler(QLatin1String("QVFbMouse"), mouseDev); qwsServer->setDefaultMouse("None"); @@ -339,7 +339,7 @@ bool QVFbScreen::initDevice() #endif #if !defined(QT_NO_QWS_KBD_QVFB) && !defined(QT_NO_QWS_KEYBOARD) - const QString keyboardDev = QString(QLatin1String(QT_VFB_KEYBOARD_PIPE)) + const QString keyboardDev = QString::fromLatin1(QT_VFB_KEYBOARD_PIPE) .arg(displayId); d_ptr->keyboard = new QVFbKeyboardHandler(keyboardDev); qwsServer->setDefaultKeyboard("None"); diff --git a/src/gui/embedded/qtransportauth_qws.cpp b/src/gui/embedded/qtransportauth_qws.cpp index 97ba5b8..6677482 100644 --- a/src/gui/embedded/qtransportauth_qws.cpp +++ b/src/gui/embedded/qtransportauth_qws.cpp @@ -834,12 +834,12 @@ QString RequestAnalyzer::analyze( QByteArray *msgQueue ) if ( command_type == QWSCommand::QCopSend ) { QWSQCopSendCommand *sendCommand = static_cast(command); - request += QString( QLatin1String("/QCop/%1/%2") ).arg( sendCommand->channel ).arg( sendCommand->message ); + request += QString::fromLatin1("/QCop/%1/%2").arg( sendCommand->channel ).arg( sendCommand->message ); } if ( command_type == QWSCommand::QCopRegisterChannel ) { QWSQCopRegisterChannelCommand *registerCommand = static_cast(command); - request += QString( QLatin1String("/QCop/RegisterChannel/%1") ).arg( registerCommand->channel ); + request += QString::fromLatin1("/QCop/RegisterChannel/%1").arg( registerCommand->channel ); } #endif dataSize = QWS_PROTOCOL_ITEM_SIZE( *command ); diff --git a/src/gui/embedded/qunixsocket.cpp b/src/gui/embedded/qunixsocket.cpp index 16f2cae..1600505 100644 --- a/src/gui/embedded/qunixsocket.cpp +++ b/src/gui/embedded/qunixsocket.cpp @@ -135,7 +135,7 @@ struct QUnixSocketRightsPrivate : public QSharedData #ifdef QUNIXSOCKET_DEBUG if(0 != closerv) { qDebug() << "QUnixSocketRightsPrivate: Unable to close managed" - " file descriptor (" << ::strerror(errno) << ")"; + " file descriptor (" << ::strerror(errno) << ')'; } #endif } @@ -166,7 +166,7 @@ QUnixSocketRights::QUnixSocketRights(int fd) #ifdef QUNIXSOCKET_DEBUG if(-1 == d->fd) { qDebug() << "QUnixSocketRights: Unable to duplicate fd " - << fd << " (" << ::strerror(errno) << ")"; + << fd << " (" << ::strerror(errno) << ')'; } #endif } @@ -237,7 +237,7 @@ int QUnixSocketRights::dupFd() const #ifdef QUNIXSOCKET_DEBUG if(-1 == rv) qDebug() << "QUnixSocketRights: Unable to duplicate managed file " - "descriptor (" << ::strerror(errno) << ")"; + "descriptor (" << ::strerror(errno) << ')'; #endif return rv; @@ -927,7 +927,7 @@ bool QUnixSocket::connect(const QByteArray & path) int crv; #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Connect requested to '" - << path << "'"; + << path << '\''; #endif abort(); // Reset any existing connection @@ -949,7 +949,7 @@ bool QUnixSocket::connect(const QByteArray & path) if(-1 == d->fd) { #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Unable to create socket (" - << strerror(errno) << ")"; + << strerror(errno) << ')'; #endif d->error = ResourceError; goto connect_error; @@ -962,7 +962,7 @@ bool QUnixSocket::connect(const QByteArray & path) if(-1 == crv) { #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Unable to configure socket (" - << ::strerror(errno) << ")"; + << ::strerror(errno) << ')'; #endif d->error = ResourceError; @@ -981,7 +981,7 @@ bool QUnixSocket::connect(const QByteArray & path) if(-1 == crv) { #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Unable to connect (" - << ::strerror(errno) << ")"; + << ::strerror(errno) << ')'; #endif if(ECONNREFUSED == errno) d->error = ConnectionRefused; @@ -1021,7 +1021,7 @@ connect_error: // Cleanup failed connection #ifdef QUNIXSOCKET_DEBUG if(0 != closerv) { qDebug() << "QUnixSocket: Unable to close file descriptor after " - "failed connect (" << ::strerror(errno) << ")"; + "failed connect (" << ::strerror(errno) << ')'; } #endif } @@ -1065,7 +1065,7 @@ bool QUnixSocket::setSocketDescriptor(int socketDescriptor) if(-1 == crv) { #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Unable to configure client provided socket (" - << ::strerror(errno) << ")"; + << ::strerror(errno) << ')'; #endif d->error = ResourceError; @@ -1136,7 +1136,7 @@ void QUnixSocket::abort() #ifdef QUNIXSOCKET_DEBUG if(0 != closerv) { qDebug() << "QUnixSocket: Unable to close socket during abort (" - << strerror(errno) << ")"; + << strerror(errno) << ')'; } #endif @@ -1686,11 +1686,11 @@ qint64 QUnixSocketPrivate::writeActivated() } #ifdef QUNIXSOCKET_DEBUG - qDebug() << "QUnixSocket: Transmitting message (length" << m.d->size() << ")"; + qDebug() << "QUnixSocket: Transmitting message (length" << m.d->size() << ')'; #endif ::ssize_t s = ::sendmsg(fd, &sendmessage, MSG_DONTWAIT | MSG_NOSIGNAL); #ifdef QUNIXSOCKET_DEBUG - qDebug() << "QUnixSocket: Transmitted message (" << s << ")"; + qDebug() << "QUnixSocket: Transmitted message (" << s << ')'; #endif if(-1 == s) { @@ -1699,13 +1699,13 @@ qint64 QUnixSocketPrivate::writeActivated() } else if(EPIPE == errno) { #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Remote side disconnected during transmit " - "(" << ::strerror(errno) << ")"; + "(" << ::strerror(errno) << ')'; #endif me->abort(); } else { #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Unable to transmit data (" - << ::strerror(errno) << ")"; + << ::strerror(errno) << ')'; #endif error = (QUnixSocket::SocketError)(QUnixSocket::WriteFailure | CausedAbort); @@ -1764,12 +1764,12 @@ void QUnixSocketPrivate::readActivated() int recvrv = ::recvmsg(fd, &message, 0); #ifdef QUNIXSOCKET_DEBUG - qDebug() << "QUnixSocket: Received message (" << recvrv << ")"; + qDebug() << "QUnixSocket: Received message (" << recvrv << ')'; #endif if(-1 == recvrv) { #ifdef QUNIXSOCKET_DEBUG qDebug() << "QUnixSocket: Unable to receive data (" - << ::strerror(errno) << ")"; + << ::strerror(errno) << ')'; #endif error = (QUnixSocket::SocketError)(QUnixSocket::ReadFailure | CausedAbort); diff --git a/src/gui/embedded/qunixsocketserver.cpp b/src/gui/embedded/qunixsocketserver.cpp index 6e9347b..489c40a 100644 --- a/src/gui/embedded/qunixsocketserver.cpp +++ b/src/gui/embedded/qunixsocketserver.cpp @@ -172,7 +172,7 @@ void QUnixSocketServer::close() #ifdef QUNIXSOCKET_DEBUG if(0 != closerv) { qDebug() << "QUnixSocketServer: Unable to close socket (" - << strerror(errno) << ")"; + << strerror(errno) << ')'; } #endif } @@ -245,7 +245,7 @@ bool QUnixSocketServer::listen(const QByteArray & path) if(-1 == d->fd) { #ifdef QUNIXSOCKETSERVER_DEBUG qDebug() << "QUnixSocketServer: Unable to create socket (" - << strerror(errno) << ")"; + << strerror(errno) << ')'; #endif close(); d->error = ResourceError; @@ -263,7 +263,7 @@ bool QUnixSocketServer::listen(const QByteArray & path) if(-1 == ::bind(d->fd, (sockaddr *)&addr, sizeof(sockaddr_un))) { #ifdef QUNIXSOCKETSERVER_DEBUG qDebug() << "QUnixSocketServer: Unable to bind socket (" - << strerror(errno) << ")"; + << strerror(errno) << ')'; #endif close(); d->error = BindError; @@ -274,7 +274,7 @@ bool QUnixSocketServer::listen(const QByteArray & path) if(-1 == ::listen(d->fd, d->maxConns)) { #ifdef QUNIXSOCKETSERVER_DEBUG qDebug() << "QUnixSocketServer: Unable to listen socket (" - << strerror(errno) << ")"; + << strerror(errno) << ')'; #endif close(); d->error = ListenError; diff --git a/src/gui/embedded/qwindowsystem_qws.cpp b/src/gui/embedded/qwindowsystem_qws.cpp index fdcd193..a15decd 100644 --- a/src/gui/embedded/qwindowsystem_qws.cpp +++ b/src/gui/embedded/qwindowsystem_qws.cpp @@ -2210,7 +2210,7 @@ void QWSServer::sendMouseEvent(const QPoint& pos, int state, int wheel) { bool block = qwsServerPrivate->screensaverblockevent(MOUSE, qwsServerPrivate->screensaverinterval, state); #ifdef EVENT_BLOCK_DEBUG - qDebug() << "sendMouseEvent" << pos.x() << pos.y() << state << (block?"block":"pass"); + qDebug() << "sendMouseEvent" << pos.x() << pos.y() << state << (block ? "block" : "pass"); #endif if (state || wheel) @@ -4110,7 +4110,7 @@ void QWSServer::processKeyEvent(int unicode, int keycode, Qt::KeyboardModifiers block = qwsServerPrivate->screensaverblockevent(KEY, qwsServerPrivate->screensaverinterval, isPress); #ifdef EVENT_BLOCK_DEBUG - qDebug() << "processKeyEvent" << unicode << keycode << modifiers << isPress << autoRepeat << (block?"block":"pass"); + qDebug() << "processKeyEvent" << unicode << keycode << modifiers << isPress << autoRepeat << (block ? "block" : "pass"); #endif // If we press a key and it's going to be blocked, wake up the screen diff --git a/src/gui/embedded/qwscommand_qws.cpp b/src/gui/embedded/qwscommand_qws.cpp index b0fd78b..26d3435 100644 --- a/src/gui/embedded/qwscommand_qws.cpp +++ b/src/gui/embedded/qwscommand_qws.cpp @@ -133,7 +133,7 @@ void QWSHexDump::init() void QWSHexDump::hexDump() { - *outstrm << "(" << dataSize << " bytes):\n" << prefix; + *outstrm << '(' << dataSize << " bytes):\n" << prefix; sprintf(sideviewLayout, " [%%-%us]", wrap); dataWidth = (2 * wrap) + (wrap / clustering); @@ -144,7 +144,7 @@ void QWSHexDump::hexDump() sideview[wrapIndex = i%wrap] = isprint(c) ? c : '.'; if (wrapIndex && (wrapIndex % clustering == 0)) - *outstrm << " "; + *outstrm << ' '; outstrm->setFieldWidth(2); outstrm->setPadChar('0'); @@ -172,14 +172,14 @@ void QWSHexDump::sideviewDump(int at) int currentWidth = (2 * at) + (at / clustering) - (at%clustering?0:1); int missing = qMax(dataWidth - currentWidth, 0); while (missing--) - *outstrm << " "; + *outstrm << ' '; *outstrm << " ["; outstrm->setPadChar(' '); outstrm->setFieldWidth(wrap); outstrm->setFieldAlignment( QTextStream::AlignLeft ); *outstrm << sideview; - *outstrm << "]"; + *outstrm << ']'; } } diff --git a/src/gui/kernel/qapplication_qws.cpp b/src/gui/kernel/qapplication_qws.cpp index 1125610..ea52e11 100644 --- a/src/gui/kernel/qapplication_qws.cpp +++ b/src/gui/kernel/qapplication_qws.cpp @@ -194,7 +194,7 @@ QString qws_dataDir() static QString result; if (!result.isEmpty()) return result; - QByteArray dataDir = QString(QLatin1String("/tmp/qtembedded-%1")).arg(qws_display_id).toLocal8Bit(); + QByteArray dataDir = QString::fromLatin1("/tmp/qtembedded-%1").arg(qws_display_id).toLocal8Bit(); if (QT_MKDIR(dataDir, 0700)) { if (errno != EEXIST) { qFatal("Cannot create Qt for Embedded Linux data directory: %s", dataDir.constData()); @@ -215,7 +215,7 @@ QString qws_dataDir() if ((buf.st_mode & 0677) != 0600) qFatal("Qt for Embedded Linux data directory has incorrect permissions: %s", dataDir.constData()); #endif - dataDir += "/"; + dataDir += '/'; result = QString::fromLocal8Bit(dataDir); return result; @@ -224,7 +224,7 @@ QString qws_dataDir() // Get the filename of the pipe Qt for Embedded Linux uses for server/client comms Q_GUI_EXPORT QString qws_qtePipeFilename() { - return (qws_dataDir() + QString(QLatin1String(QTE_PIPE)).arg(qws_display_id)); + return (qws_dataDir() + QString::fromLatin1(QTE_PIPE).arg(qws_display_id)); } static void setMaxWindowRect(const QRect &rect) diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 39f7335..670058b 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -955,8 +955,8 @@ const QString qt_reg_winclass(QWidget *w) // register window class wchar_t uniqueAppID[256]; GetModuleFileNameW(0, uniqueAppID, 255); cname = QString::number(RegisterWindowMessageW( - (const wchar_t *) QString::fromUtf16((const ushort *)uniqueAppID).toLower().replace(QString(QString::fromLatin1("\\")), - QString(QString::fromLatin1("_"))).utf16())); + (const wchar_t *) QString::fromUtf16((const ushort *)uniqueAppID).toLower().replace(QLatin1Char('\\'), + QLatin1Char('_')).utf16())); #endif // since multiple Qt versions can be used in one process diff --git a/src/gui/kernel/qmime_mac.cpp b/src/gui/kernel/qmime_mac.cpp index b2eeb5c..9cb8b61 100644 --- a/src/gui/kernel/qmime_mac.cpp +++ b/src/gui/kernel/qmime_mac.cpp @@ -218,7 +218,7 @@ QString QMacPasteboardMimeAny::flavorFor(const QString &mime) if(mime == QLatin1String("application/x-qt-mime-type-name")) return QString(); QString ret = QLatin1String("com.trolltech.anymime.") + mime; - return ret.replace(QLatin1String("/"), QLatin1String("--")); + return ret.replace(QLatin1Char('/'), QLatin1String("--")); } QString QMacPasteboardMimeAny::mimeFor(QString flav) @@ -394,7 +394,7 @@ QString QMacPasteboardMimeUnicodeText::flavorFor(const QString &mime) int i = mime.indexOf(QLatin1String("charset=")); if (i >= 0) { QString cs(mime.mid(i+8).toLower()); - i = cs.indexOf(QLatin1String(";")); + i = cs.indexOf(QLatin1Char(';')); if (i>=0) cs = cs.left(i); if (cs == QLatin1String("system")) diff --git a/src/gui/kernel/qmime_win.cpp b/src/gui/kernel/qmime_win.cpp index 109ce20..ad2dec1 100644 --- a/src/gui/kernel/qmime_win.cpp +++ b/src/gui/kernel/qmime_win.cpp @@ -1262,16 +1262,16 @@ QVector QLastResortMimes::formatsForMime(const QString &mimeType, con } return formatetcs; } -static const char *x_qt_windows_mime = "application/x-qt-windows-mime;value=\""; +static const char x_qt_windows_mime[] = "application/x-qt-windows-mime;value=\""; -bool isCustomMimeType(const QString &mimeType) +static bool isCustomMimeType(const QString &mimeType) { return mimeType.startsWith(QLatin1String(x_qt_windows_mime), Qt::CaseInsensitive); } -QString customMimeType(const QString &mimeType) +static QString customMimeType(const QString &mimeType) { - int len = QString(QLatin1String(x_qt_windows_mime)).length(); + int len = sizeof(x_qt_windows_mime) - 1; int n = mimeType.lastIndexOf(QLatin1Char('\"'))-len; return mimeType.mid(len, n); } diff --git a/src/gui/kernel/qsound_qws.cpp b/src/gui/kernel/qsound_qws.cpp index e83935f..661544f 100644 --- a/src/gui/kernel/qsound_qws.cpp +++ b/src/gui/kernel/qsound_qws.cpp @@ -279,7 +279,7 @@ QAuBucketQWS::QAuBucketQWS( QAuServerQWS *server, QSound *sound, QObject* parent sound->setObjectName( m_id.toString() ); - m_channel = new QCopChannel(QString( QLatin1String("QPE/QSound/") ).append( m_id ), this ); + m_channel = new QCopChannel(QLatin1String("QPE/QSound/") + m_id ), this ); connect( m_channel, SIGNAL(received(QString,QByteArray)), this, SLOT(processMessage(QString,QByteArray)) ); diff --git a/src/gui/painting/qbezier.cpp b/src/gui/painting/qbezier.cpp index 7ed521e..6a206ee 100644 --- a/src/gui/painting/qbezier.cpp +++ b/src/gui/painting/qbezier.cpp @@ -673,10 +673,10 @@ static int IntersectBB(const QBezier &a, const QBezier &b) #ifdef QDEBUG_BEZIER static QDebug operator<<(QDebug dbg, const QBezier &bz) { - dbg <<"["<= 0); fprintf(stderr,"clip %d: %d %d - %d %d\n", counter, x0, y0, x1, y1); - clipImg.save(QString(QLatin1String("clip-%0.png")).arg(counter++)); + clipImg.save(QString::fromLatin1("clip-%0.png").arg(counter++)); } #endif diff --git a/src/gui/painting/qprinterinfo_unix.cpp b/src/gui/painting/qprinterinfo_unix.cpp index 0f33ea7..5724173 100644 --- a/src/gui/painting/qprinterinfo_unix.cpp +++ b/src/gui/painting/qprinterinfo_unix.cpp @@ -822,7 +822,7 @@ QList QPrinterInfo::availablePrinters() for (int i = 0; i < cupsPrinterCount; ++i) { QString printerName(QString::fromLocal8Bit(cupsPrinters[i].name)); if (cupsPrinters[i].instance) - printerName += QLatin1String("/") + QString::fromLocal8Bit(cupsPrinters[i].instance); + printerName += QLatin1Char('/') + QString::fromLocal8Bit(cupsPrinters[i].instance); list.append(QPrinterInfo(printerName)); if (cupsPrinters[i].is_default) list[i].d_ptr->m_default = true; @@ -893,7 +893,7 @@ QPrinterInfo::QPrinterInfo(const QPrinter& printer) for (int i = 0; i < cupsPrinterCount; ++i) { QString printerName(QString::fromLocal8Bit(cupsPrinters[i].name)); if (cupsPrinters[i].instance) - printerName += QLatin1String("/") + QString::fromLocal8Bit(cupsPrinters[i].instance); + printerName += QLatin1Char('/') + QString::fromLocal8Bit(cupsPrinters[i].instance); if (printerName == printer.printerName()) { if (cupsPrinters[i].is_default) d->m_default = true; diff --git a/src/gui/painting/qtessellator.cpp b/src/gui/painting/qtessellator.cpp index b743940..9b5efee 100644 --- a/src/gui/painting/qtessellator.cpp +++ b/src/gui/painting/qtessellator.cpp @@ -1273,7 +1273,7 @@ QRectF QTessellator::tessellate(const QPointF *points, int nPoints) << "p0= (" << Q27Dot5ToDouble(d->scanline.edges[i]->v0->x) << '/' << Q27Dot5ToDouble(d->scanline.edges[i]->v0->y) << ") p1= (" << Q27Dot5ToDouble(d->scanline.edges[i]->v1->x) - << '/' << Q27Dot5ToDouble(d->scanline.edges[i]->v1->y) << ")" + << '/' << Q27Dot5ToDouble(d->scanline.edges[i]->v1->y) << ')' << "x=" << Q27Dot5ToDouble(d->scanline.edges[i]->positionAt(d->y)) << "isLeftOfNext=" << ((i < d->scanline.size - 1) diff --git a/src/gui/painting/qwindowsurface_x11.cpp b/src/gui/painting/qwindowsurface_x11.cpp index 9e8b498..f29d627 100644 --- a/src/gui/painting/qwindowsurface_x11.cpp +++ b/src/gui/painting/qwindowsurface_x11.cpp @@ -128,7 +128,7 @@ void QX11WindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint return; // qDebug() << "XSetClipRectangles"; // for (int i = 0; i < num; ++i) -// qDebug() << " " << i << rects[i].x << rects[i].x << rects[i].y << rects[i].width << rects[i].height; +// qDebug() << ' ' << i << rects[i].x << rects[i].x << rects[i].y << rects[i].width << rects[i].height; XSetClipRectangles(X11->display, gc, 0, 0, rects, num, YXBanded); XCopyArea(X11->display, d_ptr->device.handle(), widget->handle(), gc, br.x() + offset.x(), br.y() + offset.y(), br.width(), br.height(), wbr.x(), wbr.y()); diff --git a/src/gui/styles/gtksymbols.cpp b/src/gui/styles/gtksymbols.cpp index 07cec93..f92fd0e 100644 --- a/src/gui/styles/gtksymbols.cpp +++ b/src/gui/styles/gtksymbols.cpp @@ -374,8 +374,8 @@ static QString getThemeName() while(!in.atEnd()) { QString line = in.readLine(); if (line.contains(QLS("gtk-theme-name"))) { - line = line.right(line.length() - line.indexOf(QLS("=")) - 1); - line.remove(QLS("\"")); + line = line.right(line.length() - line.indexOf(QLatin1Char('=')) - 1); + line.remove(QLatin1Char('\"')); line = line.trimmed(); themeName = line; break; @@ -695,7 +695,7 @@ void QGtk::initGtkWidgets() QHashIterator it(oldMap); while (it.hasNext()) { it.next(); - if (!it.key().contains(QLS("."))) { + if (!it.key().contains(QLatin1Char('.'))) { add_all_sub_widgets(it.value()); } } diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index 0e54af8..151dab0 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -1776,8 +1776,9 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom QString key; + if (option->state & State_HasFocus) { - key = QLS("f"); + key += QLatin1Char('f'); GTK_WIDGET_SET_FLAGS(gtkSpinButton, GTK_HAS_FOCUS); } diff --git a/src/gui/text/qfontdatabase_qws.cpp b/src/gui/text/qfontdatabase_qws.cpp index f62a6d1..9a29de2 100644 --- a/src/gui/text/qfontdatabase_qws.cpp +++ b/src/gui/text/qfontdatabase_qws.cpp @@ -767,8 +767,8 @@ QFontEngine *loadSingleEngine(int script, const QFontPrivate *fp, QString fn = qwsFontPath(); fn += QLatin1Char('/'); fn += family->name.toLower() - + QLatin1String("_") + QString::number(pixelSize*10) - + QLatin1String("_") + QString::number(style->key.weight) + + QLatin1Char('_') + QString::number(pixelSize*10) + + QLatin1Char('_') + QString::number(style->key.weight) + (style->key.style == QFont::StyleItalic ? QLatin1String("i.qpf") : QLatin1String(".qpf")); //###rotation ### diff --git a/src/gui/text/qfontdatabase_x11.cpp b/src/gui/text/qfontdatabase_x11.cpp index 70e1599..605a7dd 100644 --- a/src/gui/text/qfontdatabase_x11.cpp +++ b/src/gui/text/qfontdatabase_x11.cpp @@ -509,9 +509,9 @@ bool qt_fillFontDef(const QByteArray &xlfd, QFontDef *fd, int dpi, QtFontDesc *d fd->styleStrategy |= QFont::NoAntialias; fd->family = QString::fromLatin1(tokens[Family]); QString foundry = QString::fromLatin1(tokens[Foundry]); - if (! foundry.isEmpty() && foundry != QString::fromLatin1("*") && (!desc || desc->family->count > 1)) + if (! foundry.isEmpty() && foundry != QLatin1String("*") && (!desc || desc->family->count > 1)) fd->family += - QString::fromLatin1(" [") + foundry + QString::fromLatin1("]"); + QLatin1String(" [") + foundry + QLatin1Char(']'); if (qstrlen(tokens[AddStyle]) > 0) fd->addStyle = QString::fromLatin1(tokens[AddStyle]); @@ -1802,30 +1802,30 @@ QFontEngine *QFontDatabase::loadXlfd(int screen, int script, const QFontDef &req QByteArray xlfd("-"); xlfd += desc.foundry->name.isEmpty() ? QByteArray("*") : desc.foundry->name.toLatin1(); - xlfd += "-"; + xlfd += '-'; xlfd += desc.family->name.isEmpty() ? QByteArray("*") : desc.family->name.toLatin1(); - xlfd += "-"; + xlfd += '-'; xlfd += desc.style->weightName ? desc.style->weightName : "*"; - xlfd += "-"; + xlfd += '-'; xlfd += (desc.style->key.style == QFont::StyleItalic - ? "i" - : (desc.style->key.style == QFont::StyleOblique ? "o" : "r")); - xlfd += "-"; + ? 'i' + : (desc.style->key.style == QFont::StyleOblique ? 'o' : 'r')); + xlfd += '-'; xlfd += desc.style->setwidthName ? desc.style->setwidthName : "*"; // ### handle add-style xlfd += "-*-"; xlfd += QByteArray::number(px); - xlfd += "-"; + xlfd += '-'; xlfd += QByteArray::number(desc.encoding->xpoint); - xlfd += "-"; + xlfd += '-'; xlfd += QByteArray::number(desc.encoding->xres); - xlfd += "-"; + xlfd += '-'; xlfd += QByteArray::number(desc.encoding->yres); - xlfd += "-"; + xlfd += '-'; xlfd += desc.encoding->pitch; - xlfd += "-"; + xlfd += '-'; xlfd += QByteArray::number(desc.encoding->avgwidth); - xlfd += "-"; + xlfd += '-'; xlfd += xlfd_for_id(desc.encoding->encoding); FM_DEBUG(" using XLFD: %s\n", xlfd.data()); diff --git a/src/gui/text/qfontengine_qpf.cpp b/src/gui/text/qfontengine_qpf.cpp index b7d1c59..28eb362 100644 --- a/src/gui/text/qfontengine_qpf.cpp +++ b/src/gui/text/qfontengine_qpf.cpp @@ -308,7 +308,7 @@ QFontEngineQPF::QFontEngineQPF(const QFontDef &def, int fileDescriptor, QFontEng readOnly = true; #if defined(DEBUG_FONTENGINE) - qDebug() << "QFontEngineQPF::QFontEngineQPF( fd =" << fd << ", renderingFontEngine =" << renderingFontEngine << ")"; + qDebug() << "QFontEngineQPF::QFontEngineQPF( fd =" << fd << ", renderingFontEngine =" << renderingFontEngine << ')'; #endif #ifndef QT_FONTS_ARE_RESOURCES @@ -316,11 +316,11 @@ QFontEngineQPF::QFontEngineQPF(const QFontDef &def, int fileDescriptor, QFontEng if (!renderingFontEngine) return; - fileName = fontDef.family.toLower() + QLatin1String("_") + fileName = fontDef.family.toLower() + QLatin1Char('_') + QString::number(fontDef.pixelSize) - + QLatin1String("_") + QString::number(fontDef.weight) + + QLatin1Char('_') + QString::number(fontDef.weight) + (fontDef.style != QFont::StyleNormal ? - QLatin1String("_italic") : QLatin1String("")) + QLatin1String("_italic") : QLatin1String()) + QLatin1String(".qsf"); fileName.replace(QLatin1Char(' '), QLatin1Char('_')); fileName.prepend(qws_fontCacheDir()); @@ -550,7 +550,7 @@ bool QFontEngineQPF::stringToCMap(const QChar *str, int len, QGlyphLayout *glyph #if 0 && defined(DEBUG_FONTENGINE) QChar c(uc); if (!findGlyph(glyphs[glyph_pos].glyph) && !seenGlyphs.contains(c)) - qDebug() << "glyph for character" << c << "/" << hex << uc << "is" << dec << glyphs[glyph_pos].glyph; + qDebug() << "glyph for character" << c << '/' << hex << uc << "is" << dec << glyphs[glyph_pos].glyph; seenGlyphs.insert(c); #endif diff --git a/src/gui/text/qfontengine_x11.cpp b/src/gui/text/qfontengine_x11.cpp index 0972b2b..bafc99d 100644 --- a/src/gui/text/qfontengine_x11.cpp +++ b/src/gui/text/qfontengine_x11.cpp @@ -227,7 +227,7 @@ static QFontEngine::FaceId fontFile(const QByteArray &_xname, QFreetypeFace **fr QByteArray best_mapping; for (QStringList::ConstIterator it = fontpath.constBegin(); it != fontpath.constEnd(); ++it) { - if ((*it).left(1) != QLatin1String("/")) + if (!(*it).startsWith(QLatin1Char('/'))) continue; // not a path name, a font server QString fontmapname; int num = 0; @@ -693,9 +693,8 @@ QFontEngine::FaceId QFontEngineXLFD::faceId() const if (freetype) { const_cast(this)->fsType = freetype->fsType(); } else { - QFontEngine::Properties properties = QFontEngine::properties(); face_id.index = 0; - face_id.filename = "-" + properties.postscriptName; + face_id.filename = '-' + QFontEngine::properties().postscriptName; } } #endif diff --git a/src/gui/text/qtextdocumentlayout.cpp b/src/gui/text/qtextdocumentlayout.cpp index c66d0c1..fa032e6 100644 --- a/src/gui/text/qtextdocumentlayout.cpp +++ b/src/gui/text/qtextdocumentlayout.cpp @@ -2500,7 +2500,7 @@ void QTextDocumentLayoutPrivate::layoutBlock(const QTextBlock &bl, int blockPosi LDEBUG << "layoutBlock from=" << layoutFrom << "to=" << layoutTo; -// qDebug() << "layoutBlock; width" << layoutStruct->x_right - layoutStruct->x_left << "(maxWidth is btw" << tl->maximumWidth() << ")"; +// qDebug() << "layoutBlock; width" << layoutStruct->x_right - layoutStruct->x_left << "(maxWidth is btw" << tl->maximumWidth() << ')'; if (previousBlockFormat) { qreal margin = qMax(blockFormat.topMargin(), previousBlockFormat->bottomMargin()); diff --git a/src/gui/text/qtexthtmlparser.cpp b/src/gui/text/qtexthtmlparser.cpp index b1f1b75..ee743dc 100644 --- a/src/gui/text/qtexthtmlparser.cpp +++ b/src/gui/text/qtexthtmlparser.cpp @@ -499,7 +499,7 @@ void QTextHtmlParser::dumpHtml() { for (int i = 0; i < count(); ++i) { qDebug().nospace() << qPrintable(QString(depth(i)*4, QLatin1Char(' '))) - << qPrintable(at(i).tag) << ":" + << qPrintable(at(i).tag) << ':' << quoteNewline(at(i).text); ; } diff --git a/src/gui/util/qdesktopservices_mac.cpp b/src/gui/util/qdesktopservices_mac.cpp index fdafa1e..fb1e193 100644 --- a/src/gui/util/qdesktopservices_mac.cpp +++ b/src/gui/util/qdesktopservices_mac.cpp @@ -154,7 +154,7 @@ QString QDesktopServices::storageLocation(StandardLocation type) QString appName = QCoreApplication::applicationName(); if (!appName.isEmpty() && (QDesktopServices::DataLocation == type || QDesktopServices::CacheLocation == type)) - path += QLatin1String("/") + appName; + path += QLatin1Char('/') + appName; return path; } diff --git a/src/gui/util/qdesktopservices_x11.cpp b/src/gui/util/qdesktopservices_x11.cpp index b3486e8..8c4a597 100644 --- a/src/gui/util/qdesktopservices_x11.cpp +++ b/src/gui/util/qdesktopservices_x11.cpp @@ -164,8 +164,8 @@ QString QDesktopServices::storageLocation(StandardLocation type) QString key = lst.at(1); QString value = lst.at(2); if (value.length() > 2 - && value.startsWith(QLatin1String("\"")) - && value.endsWith(QLatin1String("\""))) + && value.startsWith(QLatin1Char('\"')) + && value.endsWith(QLatin1Char('\"'))) value = value.mid(1, value.length() - 2); // Store the key and value: "DESKTOP", "$HOME/Desktop" lines[key] = value; diff --git a/src/gui/widgets/qcombobox_p.h b/src/gui/widgets/qcombobox_p.h index ee0da62..0998e52 100644 --- a/src/gui/widgets/qcombobox_p.h +++ b/src/gui/widgets/qcombobox_p.h @@ -290,7 +290,7 @@ public: QComboBoxDelegate(QObject *parent, QComboBox *cmb) : QItemDelegate(parent), mCombo(cmb) {} static bool isSeparator(const QModelIndex &index) { - return index.data(Qt::AccessibleDescriptionRole).toString() == QString::fromLatin1("separator"); + return index.data(Qt::AccessibleDescriptionRole).toString() == QLatin1String("separator"); } static void setSeparator(QAbstractItemModel *model, const QModelIndex &index) { model->setData(index, QString::fromLatin1("separator"), Qt::AccessibleDescriptionRole); diff --git a/src/gui/widgets/qprogressbar.cpp b/src/gui/widgets/qprogressbar.cpp index cdb3836..804220d 100644 --- a/src/gui/widgets/qprogressbar.cpp +++ b/src/gui/widgets/qprogressbar.cpp @@ -448,19 +448,19 @@ QString QProgressBar::text() const qint64 totalSteps = qint64(d->maximum) - qint64(d->minimum); QString result = d->format; - result.replace(QLatin1String("%m"), QString::fromLatin1("%1").arg(totalSteps)); - result.replace(QLatin1String("%v"), QString::fromLatin1("%1").arg(d->value)); + result.replace(QLatin1String("%m"), QString::number(totalSteps)); + result.replace(QLatin1String("%v"), QString::number(d->value)); // If max and min are equal and we get this far, it means that the // progress bar has one step and that we are on that step. Return // 100% here in order to avoid division by zero further down. if (totalSteps == 0) { - result.replace(QLatin1String("%p"), QString::fromLatin1("%1").arg(100)); + result.replace(QLatin1String("%p"), QString::number(100)); return result; } int progress = int(((qreal(d->value) - qreal(d->minimum)) * 100.0) / totalSteps); - result.replace(QLatin1String("%p"), QString::fromLatin1("%1").arg(progress)); + result.replace(QLatin1String("%p"), QString::number(progress)); return result; } diff --git a/src/network/access/qhttpnetworkrequest.cpp b/src/network/access/qhttpnetworkrequest.cpp index 7df68fc..b9b9d84 100644 --- a/src/network/access/qhttpnetworkrequest.cpp +++ b/src/network/access/qhttpnetworkrequest.cpp @@ -127,11 +127,11 @@ QByteArray QHttpNetworkRequestPrivate::header(const QHttpNetworkRequest &request { QByteArray ba = request.d->methodName(); QByteArray uri = request.d->uri(throughProxy); - ba += " " + uri; + ba += ' ' + uri; QString majorVersion = QString::number(request.majorVersion()); QString minorVersion = QString::number(request.minorVersion()); - ba += " HTTP/" + majorVersion.toLatin1() + "." + minorVersion.toLatin1() + "\r\n"; + ba += " HTTP/" + majorVersion.toLatin1() + '.' + minorVersion.toLatin1() + "\r\n"; QList > fields = request.header(); QList >::const_iterator it = fields.constBegin(); diff --git a/src/network/access/qnetworkaccessfilebackend.cpp b/src/network/access/qnetworkaccessfilebackend.cpp index 6374fde..d905b70 100644 --- a/src/network/access/qnetworkaccessfilebackend.cpp +++ b/src/network/access/qnetworkaccessfilebackend.cpp @@ -109,7 +109,7 @@ void QNetworkAccessFileBackend::open() QString fileName = url.toLocalFile(); if (fileName.isEmpty()) { if (url.scheme() == QLatin1String("qrc")) - fileName = QLatin1String(":") + url.path(); + fileName = QLatin1Char(':') + url.path(); else fileName = url.toString(QUrl::RemoveAuthority | QUrl::RemoveFragment | QUrl::RemoveQuery); } diff --git a/src/network/access/qnetworkcookie.cpp b/src/network/access/qnetworkcookie.cpp index 67df526..29bf042 100644 --- a/src/network/access/qnetworkcookie.cpp +++ b/src/network/access/qnetworkcookie.cpp @@ -1026,7 +1026,7 @@ QList QNetworkCookiePrivate::parseSetCookieHeaderLine(const QByt #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug s, const QNetworkCookie &cookie) { - s.nospace() << "QNetworkCookie(" << cookie.toRawForm(QNetworkCookie::Full) << ")"; + s.nospace() << "QNetworkCookie(" << cookie.toRawForm(QNetworkCookie::Full) << ')'; return s.space(); } #endif diff --git a/src/network/kernel/qauthenticator.cpp b/src/network/kernel/qauthenticator.cpp index 33795aa..b672765 100644 --- a/src/network/kernel/qauthenticator.cpp +++ b/src/network/kernel/qauthenticator.cpp @@ -511,13 +511,13 @@ QByteArray QAuthenticatorPrivate::digestMd5Response(const QByteArray &challenge, credentials += "uri=\"" + path + "\", "; if (!opaque.isEmpty()) credentials += "opaque=\"" + opaque + "\", "; - credentials += "response=\"" + response + "\""; + credentials += "response=\"" + response + '\"'; if (!options.value("algorithm").isEmpty()) credentials += ", algorithm=" + options.value("algorithm"); if (!options.value("qop").isEmpty()) { credentials += ", qop=" + qop + ", "; credentials += "nc=" + nonceCountString + ", "; - credentials += "cnonce=\"" + cnonce + "\""; + credentials += "cnonce=\"" + cnonce + '\"'; } return credentials; diff --git a/src/network/kernel/qhostaddress.cpp b/src/network/kernel/qhostaddress.cpp index b225c17..c2fb690 100644 --- a/src/network/kernel/qhostaddress.cpp +++ b/src/network/kernel/qhostaddress.cpp @@ -1078,7 +1078,7 @@ QPair QHostAddress::parseSubnet(const QString &subnet) #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug d, const QHostAddress &address) { - d.maybeSpace() << "QHostAddress(" << address.toString() << ")"; + d.maybeSpace() << "QHostAddress(" << address.toString() << ')'; return d.space(); } #endif diff --git a/src/network/kernel/qnetworkinterface.cpp b/src/network/kernel/qnetworkinterface.cpp index 960999e..f12b0c0 100644 --- a/src/network/kernel/qnetworkinterface.cpp +++ b/src/network/kernel/qnetworkinterface.cpp @@ -594,7 +594,7 @@ static inline QDebug operator<<(QDebug debug, const QNetworkAddressEntry &entry) debug.nospace() << ", netmask = " << entry.netmask(); if (!entry.broadcast().isNull()) debug.nospace() << ", broadcast = " << entry.broadcast(); - debug.nospace() << ")"; + debug.nospace() << ')'; return debug.space(); } diff --git a/src/network/socket/qabstractsocket.cpp b/src/network/socket/qabstractsocket.cpp index 4bb12e6..2d37e2e 100644 --- a/src/network/socket/qabstractsocket.cpp +++ b/src/network/socket/qabstractsocket.cpp @@ -852,7 +852,7 @@ void QAbstractSocketPrivate::_q_startConnecting(const QHostInfo &hostInfo) if (i != 0) s += ", "; s += addresses.at(i).toString(); } - s += "}"; + s += '}'; qDebug("QAbstractSocketPrivate::_q_startConnecting(hostInfo == %s)", s.toLatin1().constData()); #endif @@ -2596,7 +2596,7 @@ Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketError er debug << "QAbstractSocket::ProxyProtocolError"; break; default: - debug << "QAbstractSocket::SocketError(" << int(error) << ")"; + debug << "QAbstractSocket::SocketError(" << int(error) << ')'; break; } return debug; @@ -2627,7 +2627,7 @@ Q_NETWORK_EXPORT QDebug operator<<(QDebug debug, QAbstractSocket::SocketState st debug << "QAbstractSocket::ClosingState"; break; default: - debug << "QAbstractSocket::SocketState(" << int(state) << ")"; + debug << "QAbstractSocket::SocketState(" << int(state) << ')'; break; } return debug; diff --git a/src/network/socket/qlocalsocket.cpp b/src/network/socket/qlocalsocket.cpp index 327bfc6..9411130 100644 --- a/src/network/socket/qlocalsocket.cpp +++ b/src/network/socket/qlocalsocket.cpp @@ -468,7 +468,7 @@ QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketError error) debug << "QLocalSocket::UnknownSocketError"; break; default: - debug << "QLocalSocket::SocketError(" << int(error) << ")"; + debug << "QLocalSocket::SocketError(" << int(error) << ')'; break; } return debug; @@ -490,7 +490,7 @@ QDebug operator<<(QDebug debug, QLocalSocket::LocalSocketState state) debug << "QLocalSocket::ClosingState"; break; default: - debug << "QLocalSocket::SocketState(" << int(state) << ")"; + debug << "QLocalSocket::SocketState(" << int(state) << ')'; break; } return debug; diff --git a/src/network/socket/qsocks5socketengine.cpp b/src/network/socket/qsocks5socketengine.cpp index c41e32d..40d86ac 100644 --- a/src/network/socket/qsocks5socketengine.cpp +++ b/src/network/socket/qsocks5socketengine.cpp @@ -153,7 +153,7 @@ static inline QString dump(const QByteArray &) { return QString(); } */ static bool qt_socks5_set_host_address_and_port(const QHostAddress &address, quint16 port, QByteArray *pBuf) { - QSOCKS5_DEBUG << "setting [" << address << ":" << port << "]"; + QSOCKS5_DEBUG << "setting [" << address << ':' << port << ']'; union { quint16 port; @@ -186,7 +186,7 @@ static bool qt_socks5_set_host_address_and_port(const QHostAddress &address, qui */ static bool qt_socks5_set_host_name_and_port(const QString &hostname, quint16 port, QByteArray *pBuf) { - QSOCKS5_DEBUG << "setting [" << hostname << ":" << port << "]"; + QSOCKS5_DEBUG << "setting [" << hostname << ':' << port << ']'; QByteArray encodedHostName = QUrl::toAce(hostname); QByteArray &buf = *pBuf; @@ -265,7 +265,7 @@ static bool qt_socks5_get_host_address_and_port(const QByteArray &buf, QHostAddr } if (ret) { - QSOCKS5_DEBUG << "got [" << address << ":" << port << "]"; + QSOCKS5_DEBUG << "got [" << address << ':' << port << ']'; *pAddress = address; *pPort = port; *pPos = pos; @@ -1124,7 +1124,7 @@ bool QSocks5SocketEngine::connectInternal() bool QSocks5SocketEngine::connectToHost(const QHostAddress &address, quint16 port) { Q_D(QSocks5SocketEngine); - QSOCKS5_DEBUG << "connectToHost" << address << ":" << port; + QSOCKS5_DEBUG << "connectToHost" << address << ':' << port; setPeerAddress(address); setPeerPort(port); @@ -1379,7 +1379,7 @@ bool QSocks5SocketEngine::bind(const QHostAddress &address, quint16 port) //### reset and error return false; } - QSOCKS5_DEBUG << "udp actual address and port" << d->localAddress << ":" << d->localPort; + QSOCKS5_DEBUG << "udp actual address and port" << d->localAddress << ':' << d->localPort; return true; #endif // QT_NO_UDPSOCKET } @@ -1478,7 +1478,7 @@ qint64 QSocks5SocketEngine::bytesAvailable() const qint64 QSocks5SocketEngine::read(char *data, qint64 maxlen) { Q_D(QSocks5SocketEngine); - QSOCKS5_Q_DEBUG << "read( , maxlen = " << maxlen << ")"; + QSOCKS5_Q_DEBUG << "read( , maxlen = " << maxlen << ')'; if (d->mode == QSocks5SocketEnginePrivate::ConnectMode) { if (d->connectData->readBuffer.size() == 0) { if (d->data->controlSocket->state() == QAbstractSocket::UnconnectedState) { @@ -1766,7 +1766,7 @@ void QSocks5SocketEngine::setReadNotificationEnabled(bool enable) { Q_D(QSocks5SocketEngine); - QSOCKS5_Q_DEBUG << "setReadNotificationEnabled(" << enable << ")"; + QSOCKS5_Q_DEBUG << "setReadNotificationEnabled(" << enable << ')'; bool emitSignal = false; if (!d->readNotificationEnabled diff --git a/src/network/ssl/qsslcertificate.cpp b/src/network/ssl/qsslcertificate.cpp index 7b554dc..7ee0f07 100644 --- a/src/network/ssl/qsslcertificate.cpp +++ b/src/network/ssl/qsslcertificate.cpp @@ -766,16 +766,16 @@ QDebug operator<<(QDebug debug, const QSslCertificate &certificate) { debug << "QSslCertificate(" << certificate.version() - << "," << certificate.serialNumber() - << "," << certificate.digest().toBase64() - << "," << certificate.issuerInfo(QSslCertificate::Organization) - << "," << certificate.subjectInfo(QSslCertificate::Organization) - << "," << certificate.alternateSubjectNames() + << ',' << certificate.serialNumber() + << ',' << certificate.digest().toBase64() + << ',' << certificate.issuerInfo(QSslCertificate::Organization) + << ',' << certificate.subjectInfo(QSslCertificate::Organization) + << ',' << certificate.alternateSubjectNames() #ifndef QT_NO_TEXTSTREAM - << "," << certificate.effectiveDate() - << "," << certificate.expiryDate() + << ',' << certificate.effectiveDate() + << ',' << certificate.expiryDate() #endif - << ")"; + << ')'; return debug; } QDebug operator<<(QDebug debug, QSslCertificate::SubjectInfo info) diff --git a/src/network/ssl/qsslcipher.cpp b/src/network/ssl/qsslcipher.cpp index 7fec2df..696db1e 100644 --- a/src/network/ssl/qsslcipher.cpp +++ b/src/network/ssl/qsslcipher.cpp @@ -231,7 +231,7 @@ QDebug operator<<(QDebug debug, const QSslCipher &cipher) debug << "QSslCipher(name=" << qPrintable(cipher.name()) << ", bits=" << cipher.usedBits() << ", proto=" << qPrintable(cipher.protocolString()) - << ")"; + << ')'; return debug; } #endif diff --git a/src/network/ssl/qsslkey.cpp b/src/network/ssl/qsslkey.cpp index 8d550c0..6dbdc29 100644 --- a/src/network/ssl/qsslkey.cpp +++ b/src/network/ssl/qsslkey.cpp @@ -460,7 +460,7 @@ QDebug operator<<(QDebug debug, const QSslKey &key) << (key.type() == QSsl::PublicKey ? "PublicKey" : "PrivateKey") << ", " << (key.algorithm() == QSsl::Rsa ? "RSA" : "DSA") << ", " << key.length() - << ")"; + << ')'; return debug; } #endif diff --git a/src/network/ssl/qsslsocket.cpp b/src/network/ssl/qsslsocket.cpp index 92054a4..16033b6 100644 --- a/src/network/ssl/qsslsocket.cpp +++ b/src/network/ssl/qsslsocket.cpp @@ -442,8 +442,8 @@ bool QSslSocket::setSocketDescriptor(int socketDescriptor, SocketState state, Op { Q_D(QSslSocket); #ifdef QSSLSOCKET_DEBUG - qDebug() << "QSslSocket::setSocketDescriptor(" << socketDescriptor << "," - << state << "," << openMode << ")"; + qDebug() << "QSslSocket::setSocketDescriptor(" << socketDescriptor << ',' + << state << ',' << openMode << ')'; #endif if (!d->plainSocket) d->createPlainSocket(openMode); @@ -1608,7 +1608,7 @@ void QSslSocket::connectToHostImplementation(const QString &hostName, quint16 po #ifdef QSSLSOCKET_DEBUG qDebug() << "QSslSocket::connectToHostImplementation(" - << hostName << "," << port << "," << openMode << ")"; + << hostName << ',' << port << ',' << openMode << ')'; #endif if (!d->plainSocket) { #ifdef QSSLSOCKET_DEBUG @@ -1682,7 +1682,7 @@ qint64 QSslSocket::readData(char *data, qint64 maxlen) } while (!d->readBuffer.isEmpty() && readBytes < maxlen); } #ifdef QSSLSOCKET_DEBUG - qDebug() << "QSslSocket::readData(" << (void *)data << "," << maxlen << ") ==" << readBytes; + qDebug() << "QSslSocket::readData(" << (void *)data << ',' << maxlen << ") ==" << readBytes; #endif return readBytes; } @@ -1694,7 +1694,7 @@ qint64 QSslSocket::writeData(const char *data, qint64 len) { Q_D(QSslSocket); #ifdef QSSLSOCKET_DEBUG - qDebug() << "QSslSocket::writeData(" << (void *)data << "," << len << ")"; + qDebug() << "QSslSocket::writeData(" << (void *)data << ',' << len << ')'; #endif if (d->mode == UnencryptedMode && !d->autoStartHandshake) return d->plainSocket->write(data, len); @@ -1999,7 +1999,7 @@ void QSslSocketPrivate::_q_stateChangedSlot(QAbstractSocket::SocketState state) { Q_Q(QSslSocket); #ifdef QSSLSOCKET_DEBUG - qDebug() << "QSslSocket::_q_stateChangedSlot(" << state << ")"; + qDebug() << "QSslSocket::_q_stateChangedSlot(" << state << ')'; #endif q->setSocketState(state); emit q->stateChanged(state); @@ -2012,7 +2012,7 @@ void QSslSocketPrivate::_q_errorSlot(QAbstractSocket::SocketError error) { Q_Q(QSslSocket); #ifdef QSSLSOCKET_DEBUG - qDebug() << "QSslSocket::_q_errorSlot(" << error << ")"; + qDebug() << "QSslSocket::_q_errorSlot(" << error << ')'; qDebug() << "\tstate =" << q->state(); qDebug() << "\terrorString =" << q->errorString(); #endif @@ -2047,7 +2047,7 @@ void QSslSocketPrivate::_q_bytesWrittenSlot(qint64 written) { Q_Q(QSslSocket); #ifdef QSSLSOCKET_DEBUG - qDebug() << "QSslSocket::_q_bytesWrittenSlot(" << written << ")"; + qDebug() << "QSslSocket::_q_bytesWrittenSlot(" << written << ')'; #endif if (mode == QSslSocket::UnencryptedMode) diff --git a/src/network/ssl/qsslsocket_openssl.cpp b/src/network/ssl/qsslsocket_openssl.cpp index 32b02c5..4017c4d 100644 --- a/src/network/ssl/qsslsocket_openssl.cpp +++ b/src/network/ssl/qsslsocket_openssl.cpp @@ -276,7 +276,7 @@ init_context: if (first) first = false; else - cipherString.append(":"); + cipherString.append(':'); cipherString.append(cipher.name().toLatin1()); } diff --git a/src/opengl/qegl.cpp b/src/opengl/qegl.cpp index c6c258b..f1ae4ed 100644 --- a/src/opengl/qegl.cpp +++ b/src/opengl/qegl.cpp @@ -582,7 +582,7 @@ QString QEglProperties::toString() const if (val != EGL_DONT_CARE) { str += QLatin1String("id="); str += QString::number(val); - str += QLatin1String(" "); + str += QLatin1Char(' '); } #ifdef EGL_RENDERABLE_TYPE @@ -617,11 +617,11 @@ QString QEglProperties::toString() const bufferSize = EGL_DONT_CARE; str += QLatin1String(" rgba="); str += QString::number(red); - str += QLatin1String(","); + str += QLatin1Char(','); str += QString::number(green); - str += QLatin1String(","); + str += QLatin1Char(','); str += QString::number(blue); - str += QLatin1String(","); + str += QLatin1Char(','); str += QString::number(alpha); if (bufferSize != EGL_DONT_CARE) { // Only report buffer size if different than r+g+b+a. @@ -708,7 +708,7 @@ QString QEglProperties::toString() const if (height != EGL_DONT_CARE || width != EGL_DONT_CARE) { addTag(str, QLatin1String(" max-pbuffer-size=")); str += QString::number(width); - str += QLatin1String("x"); + str += QLatin1Char('x'); str += QString::number(height); if (pixels != (width * height)) { addTag(str, QLatin1String(" max-pbuffer-pixels=")); @@ -762,9 +762,9 @@ QString QEglProperties::toString() const if (val == EGL_TRANSPARENT_RGB) { addTag(str, QLatin1String(" transparent-rgb=")); str += QString::number(value(EGL_TRANSPARENT_RED_VALUE)); - str += QLatin1String(","); + str += QLatin1Char(','); str += QString::number(value(EGL_TRANSPARENT_GREEN_VALUE)); - str += QLatin1String(","); + str += QLatin1Char(','); str += QString::number(value(EGL_TRANSPARENT_BLUE_VALUE)); } diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 431b488..60039eb 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -4365,7 +4365,7 @@ Q_OPENGL_EXPORT const QString qt_gl_library_name() { if (qt_gl_lib_name()->isNull()) { #if defined(Q_WS_X11) || defined(Q_WS_QWS) - return QString(QLatin1String("GL")); + return QLatin1String("GL"); #else // Q_WS_MAC return QLatin1String("/System/Library/Frameworks/OpenGL.framework/Versions/A/Libraries/libGL.dylib"); #endif diff --git a/src/opengl/qgl_x11.cpp b/src/opengl/qgl_x11.cpp index 528cc3b..28a50bd 100644 --- a/src/opengl/qgl_x11.cpp +++ b/src/opengl/qgl_x11.cpp @@ -433,7 +433,7 @@ bool QGLContext::chooseContext(const QGLContext* shareContext) if (!d->gpm) return false; } - QString glxExt = QString(QLatin1String(glXGetClientString(QX11Info::display(), GLX_EXTENSIONS))); + QString glxExt = QLatin1String(glXGetClientString(QX11Info::display(), GLX_EXTENSIONS)); if (glxExt.contains(QLatin1String("GLX_SGI_video_sync"))) { if (d->glFormat.swapInterval() == -1) d->glFormat.setSwapInterval(0); @@ -787,7 +787,7 @@ void QGLContext::swapBuffers() const static qt_glXWaitVideoSyncSGI glXWaitVideoSyncSGI = 0; static bool resolved = false; if (!resolved) { - QString glxExt = QString(QLatin1String(glXGetClientString(QX11Info::display(), GLX_EXTENSIONS))); + QString glxExt = QLatin1String(glXGetClientString(QX11Info::display(), GLX_EXTENSIONS)); if (glxExt.contains(QLatin1String("GLX_SGI_video_sync"))) { #if defined(Q_OS_LINUX) || defined(Q_OS_BSD4) void *handle = dlopen(NULL, RTLD_LAZY); @@ -1032,7 +1032,7 @@ void *QGLContext::getProcAddress(const QString &proc) const if (resolved && !glXGetProcAddressARB) return 0; if (!glXGetProcAddressARB) { - QString glxExt = QString(QLatin1String(glXGetClientString(QX11Info::display(), GLX_EXTENSIONS))); + QString glxExt = QLatin1String(glXGetClientString(QX11Info::display(), GLX_EXTENSIONS)); if (glxExt.contains(QLatin1String("GLX_ARB_get_proc_address"))) { #if defined(Q_OS_LINUX) || defined(Q_OS_BSD4) void *handle = dlopen(NULL, RTLD_LAZY); diff --git a/src/opengl/qglpixmapfilter.cpp b/src/opengl/qglpixmapfilter.cpp index eb3298b..275bbed 100644 --- a/src/opengl/qglpixmapfilter.cpp +++ b/src/opengl/qglpixmapfilter.cpp @@ -192,15 +192,15 @@ bool QGLPixmapColorizeFilter::processGL(QPainter *, const QPointF &pos, const QP // generates convolution filter code for arbitrary sized kernel QByteArray QGLPixmapConvolutionFilter::generateConvolutionShader() const { QByteArray code; - code.append("uniform sampler2D texture;\n"); - code.append("uniform vec2 inv_texture_size;\n"); - code.append("uniform float matrix["); + code.append("uniform sampler2D texture;\n" + "uniform vec2 inv_texture_size;\n" + "uniform float matrix["); code.append(QByteArray::number(m_kernelWidth * m_kernelHeight)); - code.append("];\n"); - code.append("vec2 offset["); + code.append("];\n" + "vec2 offset["); code.append(QByteArray::number(m_kernelWidth*m_kernelHeight)); - code.append("];\n"); - code.append("void main(void) {\n"); + code.append("];\n" + "void main(void) {\n"); for(int y = 0; y < m_kernelHeight; y++) { for(int x = 0; x < m_kernelWidth; x++) { @@ -210,22 +210,21 @@ QByteArray QGLPixmapConvolutionFilter::generateConvolutionShader() const { code.append(QByteArray::number(x-(int)(m_kernelWidth/2))); code.append(".0, inv_texture_size.y * "); code.append(QByteArray::number((int)(m_kernelHeight/2)-y)); - code.append(".0)"); - code.append(";\n"); + code.append(".0);\n"); } } - code.append(" int i = 0;\n"); - code.append(" vec2 coords = gl_TexCoord[0].st;\n"); - code.append(" vec4 sum = vec4(0.0);\n"); - code.append(" for (i = 0; i < "); + code.append(" int i = 0;\n" + " vec2 coords = gl_TexCoord[0].st;\n" + " vec4 sum = vec4(0.0);\n" + " for (i = 0; i < "); code.append(QByteArray::number(m_kernelWidth * m_kernelHeight)); - code.append("; i++) {\n"); - code.append(" vec4 tmp = texture2D(texture,coords+offset[i]);\n"); - code.append(" sum += matrix[i] * tmp;\n"); - code.append(" }\n"); - code.append(" gl_FragColor = sum;\n"); - code.append("}"); + code.append("; i++) {\n" + " vec4 tmp = texture2D(texture,coords+offset[i]);\n" + " sum += matrix[i] * tmp;\n" + " }\n" + " gl_FragColor = sum;\n" + "}"); return code; } diff --git a/src/opengl/util/generator.cpp b/src/opengl/util/generator.cpp index de2450d..dac5a2d 100644 --- a/src/opengl/util/generator.cpp +++ b/src/opengl/util/generator.cpp @@ -116,7 +116,7 @@ QList readConf(const QString &confFile) lineStream >> enumerator; if (lineStream.atEnd()) { - qDebug() << "Error in file" << confFile << "(" << enumerator << ")"; + qDebug() << "Error in file" << confFile << '(' << enumerator << ')'; exit(0); } diff --git a/src/plugins/accessible/widgets/rangecontrols.cpp b/src/plugins/accessible/widgets/rangecontrols.cpp index 9297d6e..6d8c184 100644 --- a/src/plugins/accessible/widgets/rangecontrols.cpp +++ b/src/plugins/accessible/widgets/rangecontrols.cpp @@ -799,7 +799,7 @@ int QAccessibleSlider::defaultAction(int /*child*/) const /*! \internal */ QString QAccessibleSlider::actionText(int /*action*/, Text /*t*/, int /*child*/) const { - return QString(QLatin1String("")); + return QLatin1String(""); } QAccessibleAbstractSlider::QAccessibleAbstractSlider(QWidget *w, Role r) diff --git a/src/plugins/gfxdrivers/hybrid/hybridscreen.cpp b/src/plugins/gfxdrivers/hybrid/hybridscreen.cpp index 3a40b4c..da61a22 100644 --- a/src/plugins/gfxdrivers/hybrid/hybridscreen.cpp +++ b/src/plugins/gfxdrivers/hybrid/hybridscreen.cpp @@ -103,11 +103,11 @@ bool HybridScreen::connect(const QString &displaySpec) { QString dspec = displaySpec; if (dspec.startsWith(QLatin1String("hybrid:"), Qt::CaseInsensitive)) - dspec = dspec.mid(QString(QLatin1String("hybrid:")).size()); + dspec = dspec.mid(QString::fromLatin1("hybrid:").size()); else if (dspec.compare(QLatin1String("hybrid"), Qt::CaseInsensitive) == 0) dspec = QString(); - const QString displayIdSpec = QString(QLatin1String(" :%1")).arg(displayId); + const QString displayIdSpec = QString::fromLatin1(" :%1").arg(displayId); if (dspec.endsWith(displayIdSpec)) dspec = dspec.left(dspec.size() - displayIdSpec.size()); diff --git a/src/plugins/gfxdrivers/vnc/qscreenvnc_qws.cpp b/src/plugins/gfxdrivers/vnc/qscreenvnc_qws.cpp index b7f03ba..8be3672 100644 --- a/src/plugins/gfxdrivers/vnc/qscreenvnc_qws.cpp +++ b/src/plugins/gfxdrivers/vnc/qscreenvnc_qws.cpp @@ -2100,11 +2100,11 @@ bool QVNCScreen::connect(const QString &displaySpec) { QString dspec = displaySpec; if (dspec.startsWith(QLatin1String("vnc:"), Qt::CaseInsensitive)) - dspec = dspec.mid(QString(QLatin1String("vnc:")).size()); + dspec = dspec.mid(QString::fromLatin1("vnc:").size()); else if (dspec.compare(QLatin1String("vnc"), Qt::CaseInsensitive) == 0) dspec = QString(); - const QString displayIdSpec = QString(QLatin1String(" :%1")).arg(displayId); + const QString displayIdSpec = QString::fromLatin1(" :%1").arg(displayId); if (dspec.endsWith(displayIdSpec)) dspec = dspec.left(dspec.size() - displayIdSpec.size()); diff --git a/src/qt3support/dialogs/q3filedialog.cpp b/src/qt3support/dialogs/q3filedialog.cpp index b9f8196..e41941b 100644 --- a/src/qt3support/dialogs/q3filedialog.cpp +++ b/src/qt3support/dialogs/q3filedialog.cpp @@ -3879,7 +3879,7 @@ void Q3FileDialog::detailViewSelectionChanged() d->moreFiles->setSelected(f->i, i->isSelected()); } if (i->isSelected() && !((Q3FileDialogPrivate::File *)i)->info.isDir()) - str += QString(QLatin1String("\"%1\" ")).arg(i->text(0)); + str += QString::fromLatin1("\"%1\" ").arg(i->text(0)); i = i->nextSibling(); } d->moreFiles->blockSignals(false); @@ -3931,7 +3931,7 @@ void Q3FileDialog::listBoxSelectionChanged() } if (d->moreFiles->isSelected(i) && !((Q3FileDialogPrivate::File*)(mcitem)->i)->info.isDir()) { - str += QString(QLatin1String("\"%1\" ")).arg(i->text()); + str += QString::fromLatin1("\"%1\" ").arg(i->text()); if (j == 0) j = i; } @@ -5757,8 +5757,8 @@ void Q3FileDialog::insertEntry(const Q3ValueList &lst, Q3NetworkOperat if (!bShowHiddenFiles && inf.name() != QLatin1String("..")) { if (d->url.isLocalFile()) { QString file = d->url.path(); - if (!file.endsWith(QLatin1String("/"))) - file.append(QLatin1String("/")); + if (!file.endsWith(QLatin1Char('/'))) + file.append(QLatin1Char('/')); file += inf.name(); QT_WA({ if (GetFileAttributesW((TCHAR*)file.ucs2()) & FILE_ATTRIBUTE_HIDDEN) diff --git a/src/qt3support/dialogs/q3filedialog_mac.cpp b/src/qt3support/dialogs/q3filedialog_mac.cpp index f1c749ec..18bebf1 100644 --- a/src/qt3support/dialogs/q3filedialog_mac.cpp +++ b/src/qt3support/dialogs/q3filedialog_mac.cpp @@ -554,7 +554,7 @@ QString Q3FileDialog::macGetSaveFileName(const QString &start, const QString &fi retstr = QString::fromUtf8((const char *)str_buffer); //now filename CFStringGetCString(ret.saveFileName, (char *)str_buffer, 1024, kCFStringEncodingUTF8); - retstr += QLatin1String("/") + QString::fromUtf8((const char *)str_buffer); + retstr += QLatin1Char('/') + QString::fromUtf8((const char *)str_buffer); } NavDisposeReply(&ret); if(selectedFilter) diff --git a/src/qt3support/dialogs/q3filedialog_win.cpp b/src/qt3support/dialogs/q3filedialog_win.cpp index 1be797a..a1c98f3 100644 --- a/src/qt3support/dialogs/q3filedialog_win.cpp +++ b/src/qt3support/dialogs/q3filedialog_win.cpp @@ -737,7 +737,7 @@ QString Q3FileDialog::winGetExistingDirectory(const QString& initialDirectory, QDir::setCurrent(currentDir); if (!result.isEmpty()) - result.replace(QLatin1String("\\"), QLatin1String("/")); + result.replace(QLatin1Char('\\'), QLatin1Char('/')); return result; #else return QString(); diff --git a/src/qt3support/itemviews/q3iconview.cpp b/src/qt3support/itemviews/q3iconview.cpp index d1a9c1e..a5664de 100644 --- a/src/qt3support/itemviews/q3iconview.cpp +++ b/src/qt3support/itemviews/q3iconview.cpp @@ -614,7 +614,7 @@ QByteArray Q3IconDrag::encodedData(const char* mime) const (*it).item.textRect().x()).arg((*it).item.textRect().y()). arg((*it).item.textRect().width()).arg( (*it).item.textRect().height()); - k += QString(QLatin1String((*it).data.data())) + QLatin1String("$@@$"); + k += QString::fromLatin1((*it).data.data()) + QLatin1String("$@@$"); s += k; } @@ -1820,8 +1820,8 @@ void Q3IconViewItem::calcRect(const QString &text_) tw = r.width(); th = r.height(); - if (tw < view->d->fm->width(QLatin1String("X"))) - tw = view->d->fm->width(QLatin1String("X")); + if (tw < view->d->fm->width(QLatin1Char('X'))) + tw = view->d->fm->width(QLatin1Char('X')); itemTextRect.setWidth(tw); itemTextRect.setHeight(th); diff --git a/src/qt3support/network/q3dns.cpp b/src/qt3support/network/q3dns.cpp index c53f2ff..3ca3977 100644 --- a/src/qt3support/network/q3dns.cpp +++ b/src/qt3support/network/q3dns.cpp @@ -1738,7 +1738,7 @@ void Q3Dns::setLabel( const QString & label ) const char * dom; while( (dom=it.current()) != 0 ) { ++it; - n.append( l.lower() + QLatin1String(".") + QLatin1String(dom) ); + n.append( l.lower() + QLatin1Char('.') + QLatin1String(dom) ); } } n.append( l.lower() ); @@ -1902,8 +1902,8 @@ QString Q3Dns::toInAddrArpaDomain( const QHostAddress &address ) s = QLatin1String("ip6.arpa"); uint b = 0; while( b < 16 ) { - s = QString::number( i.c[b]%16, 16 ) + QLatin1String(".") + - QString::number( i.c[b]/16, 16 ) + QLatin1String(".") + s; + s = QString::number( i.c[b]%16, 16 ) + QLatin1Char('.') + + QString::number( i.c[b]/16, 16 ) + QLatin1Char('.') + s; b++; } } @@ -2347,7 +2347,7 @@ void Q3Dns::doResInit() nameServer += QLatin1String(dnsServer->IpAddress.String); dnsServer = dnsServer->Next; if ( dnsServer != 0 ) - nameServer += QLatin1String(" "); + nameServer += QLatin1Char(' '); } searchList = QLatin1String(""); separator = ' '; @@ -2360,12 +2360,12 @@ void Q3Dns::doResInit() } if ( !gotNetworkParams ) { if ( getDnsParamsFromRegistry( - QString( QLatin1String("System\\CurrentControlSet\\Services\\Tcpip\\Parameters") ), + QLatin1String("System\\CurrentControlSet\\Services\\Tcpip\\Parameters"), &domainName, &nameServer, &searchList )) { // for NT separator = ' '; } else if ( getDnsParamsFromRegistry( - QString( QLatin1String("System\\CurrentControlSet\\Services\\VxD\\MSTCP") ), + QLatin1String("System\\CurrentControlSet\\Services\\VxD\\MSTCP"), &domainName, &nameServer, &searchList )) { // for Windows 98 separator = ','; @@ -2395,7 +2395,7 @@ void Q3Dns::doResInit() } while( first < (int)nameServer.length() ); } - searchList = searchList + QLatin1String(" ") + domainName; + searchList += QLatin1Char(' ') + domainName; searchList = searchList.simplifyWhiteSpace().lower(); first = 0; do { @@ -2488,7 +2488,7 @@ void Q3Dns::doResInit() while ( !stream.atEnd() ) { line = stream.readLine(); QStringList list = QStringList::split( QLatin1String(" "), line ); - if( line.startsWith( QLatin1String("#") ) || list.size() < 2 ) + if( line.startsWith( QLatin1Char('#') ) || list.size() < 2 ) continue; const QString type = list[0].lower(); diff --git a/src/qt3support/network/q3ftp.cpp b/src/qt3support/network/q3ftp.cpp index 5ab84cc..44c1f5c 100644 --- a/src/qt3support/network/q3ftp.cpp +++ b/src/qt3support/network/q3ftp.cpp @@ -485,7 +485,7 @@ bool Q3FtpDTP::parseDir( const QString &buffer, const QString &userName, QUrlInf dateStr += lst[ 6 ]; dateStr += QLatin1Char(' '); - if ( lst[ 7 ].contains( QLatin1String(":") ) ) { + if ( lst[ 7 ].contains( QLatin1Char(':') ) ) { time = QTime( lst[ 7 ].left( 2 ).toInt(), lst[ 7 ].right( 2 ).toInt() ); dateStr += QString::number( QDate::currentDate().year() ); } else { @@ -495,7 +495,7 @@ bool Q3FtpDTP::parseDir( const QString &buffer, const QString &userName, QUrlInf QDate date = QDate::fromString( dateStr ); info->setLastModified( QDateTime( date, time ) ); - if ( lst[ 7 ].contains( QLatin1String(":") ) ) { + if ( lst[ 7 ].contains( QLatin1Char(':') ) ) { const int futureTolerance = 600; if( info->lastModified().secsTo( QDateTime::currentDateTime() ) < -futureTolerance ) { QDateTime dt = info->lastModified(); @@ -512,7 +512,7 @@ bool Q3FtpDTP::parseDir( const QString &buffer, const QString &userName, QUrlInf else { QString n; for ( uint i = 8; i < (uint) lst.count(); ++i ) - n += lst[ i ] + QLatin1String(" "); + n += lst[ i ] + QLatin1Char(' '); n = n.stripWhiteSpace(); info->setName( n ); } @@ -897,7 +897,7 @@ bool Q3FtpPI::processReply() // ### error handling } else { QStringList lst = addrPortPattern.capturedTexts(); - QString host = lst[1] + QLatin1String(".") + lst[2] + QLatin1String(".") + lst[3] + QLatin1String(".") + lst[4]; + QString host = lst[1] + QLatin1Char('.') + lst[2] + QLatin1Char('.') + lst[3] + QLatin1Char('.') + lst[4]; Q_UINT16 port = ( lst[5].toUInt() << 8 ) + lst[6].toUInt(); waitForDtpToConnect = true; dtp.connectToHost( host, port ); @@ -1435,8 +1435,8 @@ int Q3Ftp::connectToHost( const QString &host, Q_UINT16 port ) int Q3Ftp::login( const QString &user, const QString &password ) { QStringList cmds; - cmds << ( QString(QLatin1String("USER ")) + ( user.isNull() ? QString(QLatin1String("anonymous")) : user ) + QLatin1String("\r\n") ); - cmds << ( QString(QLatin1String("PASS ")) + ( password.isNull() ? QString(QLatin1String("anonymous@")) : password ) + QLatin1String("\r\n") ); + cmds << ( QString::fromLatin1("USER ") + ( user.isNull() ? QString::fromLatin1("anonymous") : user ) + QLatin1String("\r\n") ); + cmds << ( QString::fromLatin1("PASS ") + ( password.isNull() ? QString::fromLatin1("anonymous@") : password ) + QLatin1String("\r\n") ); return addCommand( new Q3FtpCommand( Login, cmds ) ); } @@ -2095,7 +2095,7 @@ void Q3Ftp::operationListChildren( Q3NetworkOperation *op ) { op->setState( StInProgress ); - cd( ( url()->path().isEmpty() ? QString( QLatin1String("/") ) : url()->path() ) ); + cd( ( url()->path().isEmpty() ? QString::fromLatin1("/") : url()->path() ) ); list(); emit start( op ); } @@ -2115,7 +2115,7 @@ void Q3Ftp::operationRemove( Q3NetworkOperation *op ) { op->setState( StInProgress ); - cd( ( url()->path().isEmpty() ? QString( QLatin1String("/") ) : url()->path() ) ); + cd( ( url()->path().isEmpty() ? QString::fromLatin1("/") : url()->path() ) ); remove( Q3Url( op->arg( 0 ) ).path() ); } @@ -2125,7 +2125,7 @@ void Q3Ftp::operationRename( Q3NetworkOperation *op ) { op->setState( StInProgress ); - cd( ( url()->path().isEmpty() ? QString( QLatin1String("/") ) : url()->path() ) ); + cd( ( url()->path().isEmpty() ? QString::fromLatin1("/") : url()->path() ) ); rename( op->arg( 0 ), op->arg( 1 )); } @@ -2179,8 +2179,8 @@ bool Q3Ftp::checkConnection( Q3NetworkOperation *op ) connectToHost( url()->host(), url()->port() != -1 ? url()->port() : 21 ); break; } - QString user = url()->user().isEmpty() ? QString( QLatin1String("anonymous") ) : url()->user(); - QString pass = url()->password().isEmpty() ? QString( QLatin1String("anonymous@") ) : url()->password(); + QString user = url()->user().isEmpty() ? QString::fromLatin1("anonymous") : url()->user(); + QString pass = url()->password().isEmpty() ? QString::fromLatin1("anonymous@") : url()->password(); login( user, pass ); } diff --git a/src/qt3support/network/q3http.cpp b/src/qt3support/network/q3http.cpp index 591b381..aabf4a3 100644 --- a/src/qt3support/network/q3http.cpp +++ b/src/qt3support/network/q3http.cpp @@ -468,7 +468,7 @@ bool Q3HttpHeader::parse( const QString& str ) if ( !(*it).isEmpty() ) { if ( (*it)[0].isSpace() ) { if ( !lines.isEmpty() ) { - lines.last() += QLatin1String(" "); + lines.last() += QLatin1Char(' '); lines.last() += (*it).stripWhiteSpace(); } } else { @@ -562,7 +562,7 @@ void Q3HttpHeader::removeValue( const QString& key ) */ bool Q3HttpHeader::parseLine( const QString& line, int ) { - int i = line.find( QLatin1String(":") ); + int i = line.find( QLatin1Char(':') ); if ( i == -1 ) return false; @@ -647,7 +647,7 @@ QString Q3HttpHeader::contentType() const if ( type.isEmpty() ) return QString(); - int pos = type.find( QLatin1String(";") ); + int pos = type.find( QLatin1Char(';') ); if ( pos == -1 ) return type; @@ -2210,7 +2210,7 @@ void Q3Http::clientReply( const Q3HttpResponseHeader &rep ) if ( rep.statusCode() >= 400 && rep.statusCode() < 600 ) { op->setState( StFailed ); op->setProtocolDetail( - QString(QLatin1String("%1 %2")).arg(rep.statusCode()).arg(rep.reasonPhrase()) + QString::fromLatin1("%1 %2").arg(rep.statusCode()).arg(rep.reasonPhrase()) ); switch ( rep.statusCode() ) { case 401: diff --git a/src/qt3support/network/q3url.cpp b/src/qt3support/network/q3url.cpp index fc2fdb2..68753b6 100644 --- a/src/qt3support/network/q3url.cpp +++ b/src/qt3support/network/q3url.cpp @@ -211,8 +211,8 @@ Q3Url::Q3Url( const Q3Url& url ) bool Q3Url::isRelativeUrl( const QString &url ) { - int colon = url.find( QLatin1String(":") ); - int slash = url.find( QLatin1String("/") ); + int colon = url.find( QLatin1Char(':') ); + int slash = url.find( QLatin1Char('/') ); return ( slash != 0 && ( colon == -1 || ( slash != -1 && colon > slash ) ) ); } @@ -280,8 +280,8 @@ Q3Url::Q3Url( const Q3Url& url, const QString& relUrl, bool checkSlash ) if ( !d->host.isEmpty() && !d->user.isEmpty() && !d->pass.isEmpty() ) p = QLatin1String("/"); } - if ( !p.isEmpty() && p.right(1)!=QLatin1String("/") ) - p += QLatin1String("/"); + if ( !p.isEmpty() && !p.endsWith(QLatin1Char('/')) ) + p += QLatin1Char('/'); p += rel; d->path = p; d->cleanPathDirty = true; @@ -678,7 +678,7 @@ bool Q3Url::parse( const QString& url ) ++cs; while ( url_[ cs ] == QLatin1Char('/') ) ++cs; - int slash = url_.find( QLatin1String("/"), cs ); + int slash = url_.find( QLatin1Char('/'), cs ); if ( slash == -1 ) slash = url_.length() - 1; QString tmp = url_.mid( cs, slash - cs + 1 ); @@ -686,7 +686,7 @@ bool Q3Url::parse( const QString& url ) if ( !tmp.isEmpty() ) { // if this part exists // look for the @ in this part - int at = tmp.find( QLatin1String("@") ); + int at = tmp.find( QLatin1Char('@') ); if ( at != -1 ) at += cs; // we have no @, which means host[:port], so directly @@ -793,7 +793,7 @@ bool Q3Url::parse( const QString& url ) // hack for windows if ( d->path.length() == 2 && d->path[ 1 ] == QLatin1Char(':') ) - d->path += QLatin1String("/"); + d->path += QLatin1Char('/'); // #### do some corrections, should be done nicer too if ( !d->pass.isEmpty() ) { @@ -808,7 +808,7 @@ bool Q3Url::parse( const QString& url ) if ( d->path[ 0 ] == QLatin1Char('@') || d->path[ 0 ] == QLatin1Char(':') ) d->path.remove( (uint)0, 1 ); if ( d->path[ 0 ] != QLatin1Char('/') && !relPath && d->path[ 1 ] != QLatin1Char(':') ) - d->path.prepend( QLatin1String("/") ); + d->path.prepend( QLatin1Char('/') ); } if ( !d->refEncoded.isEmpty() && d->refEncoded[ 0 ] == QLatin1Char('#') ) d->refEncoded.remove( (uint)0, 1 ); @@ -820,9 +820,9 @@ bool Q3Url::parse( const QString& url ) #if defined(Q_OS_WIN32) // hack for windows file://machine/path syntax if ( d->protocol == QLatin1String("file") ) { - if ( url.left( 7 ) == QLatin1String("file://") && + if ( url.startsWith(QLatin1String("file://")) && d->path.length() > 1 && d->path[ 1 ] != QLatin1Char(':') ) - d->path.prepend( QLatin1String("/") ); + d->path.prepend( QLatin1Char('/') ); } #endif @@ -942,7 +942,7 @@ void Q3Url::setFileName( const QString& name ) p += fn; if ( !d->queryEncoded.isEmpty() ) - p += QLatin1String("?") + d->queryEncoded; + p += QLatin1Char('?') + d->queryEncoded; setEncodedPathAndQuery( p ); } @@ -961,7 +961,7 @@ QString Q3Url::encodedPathAndQuery() encode( p ); if ( !d->queryEncoded.isEmpty() ) { - p += QLatin1String("?"); + p += QLatin1Char('?'); p += d->queryEncoded; } @@ -1011,7 +1011,7 @@ QString Q3Url::path( bool correct ) const } else if ( isLocalFile() ) { #if defined(Q_OS_WIN32) // hack for stuff like \\machine\path and //machine/path on windows - if ( ( d->path.left( 1 ) == QLatin1String("/") || d->path.left( 1 ) == QLatin1String("\\") ) && + if ( ( d->path.startsWith(QLatin1Char('/')) || d->path.startsWith(QLatin1Char('\\')) ) && d->path.length() > 1 ) { d->cleanPath = d->path; bool share = (d->cleanPath[0] == QLatin1Char('\\') && d->cleanPath[1] == QLatin1Char('\\')) || @@ -1021,7 +1021,7 @@ QString Q3Url::path( bool correct ) const if ( share ) { check = false; while (d->cleanPath.at(0) != QLatin1Char('/') || d->cleanPath.at(1) != QLatin1Char('/')) - d->cleanPath.prepend(QLatin1String("/")); + d->cleanPath.prepend(QLatin1Char('/')); } } #endif @@ -1036,7 +1036,7 @@ QString Q3Url::path( bool correct ) const dir = QDir::cleanDirPath( canPath ); else dir = QDir::cleanDirPath( QDir( d->path ).absPath() ); - dir += QLatin1String("/"); + dir += QLatin1Char('/'); if ( dir == QLatin1String("//") ) d->cleanPath = QLatin1String("/"); else @@ -1046,14 +1046,13 @@ QString Q3Url::path( bool correct ) const QDir::cleanDirPath( (qt_resolve_symlinks ? fi.dir().canonicalPath() : fi.dir().absPath()) ); - d->cleanPath = p + QLatin1String("/") + fi.fileName(); + d->cleanPath = p + QLatin1Char('/') + fi.fileName(); } } } else { - if ( d->path != QLatin1String("/") && d->path[ (int)d->path.length() - 1 ] == QLatin1Char('/') ) - d->cleanPath = QDir::cleanDirPath( d->path ) + QLatin1String("/"); - else d->cleanPath = QDir::cleanDirPath( d->path ); + if ( d->path.length() > 1 && d->path.endsWith(QLatin1Char('/')) ) + d->cleanPath += QLatin1Char('/'); } if ( check ) @@ -1084,9 +1083,9 @@ bool Q3Url::isLocalFile() const QString Q3Url::fileName() const { - if ( d->path.isEmpty() || d->path.endsWith( QLatin1String("/") ) + if ( d->path.isEmpty() || d->path.endsWith( QLatin1Char('/') ) #ifdef Q_WS_WIN - || d->path.endsWith( QLatin1String("\\") ) + || d->path.endsWith( QLatin1Char('\\') ) #endif ) return QString(); @@ -1110,12 +1109,12 @@ void Q3Url::addPath( const QString& pa ) if ( path().isEmpty() ) { if ( p[ 0 ] != QLatin1Char( '/' ) ) - d->path = QLatin1String("/") + p; + d->path = QLatin1Char('/') + p; else d->path = p; } else { if ( p[ 0 ] != QLatin1Char( '/' ) && d->path[ (int)d->path.length() - 1 ] != QLatin1Char('/') ) - d->path += QLatin1String("/") + p; + d->path += QLatin1Char('/') + p; else d->path += p; } @@ -1250,11 +1249,11 @@ QString Q3Url::toString( bool encodedPath, bool forcePrependProtocol ) const if ( isLocalFile() ) { if ( forcePrependProtocol ) - res = d->protocol + QLatin1String(":") + p; + res = d->protocol + QLatin1Char(':') + p; else res = p; } else if ( d->protocol == QLatin1String("mailto") ) { - res = d->protocol + QLatin1String(":") + p; + res = d->protocol + QLatin1Char(':') + p; } else { res = d->protocol + QLatin1String("://"); if ( !d->user.isEmpty() || !d->pass.isEmpty() ) { @@ -1267,24 +1266,24 @@ QString Q3Url::toString( bool encodedPath, bool forcePrependProtocol ) const if ( !d->pass.isEmpty() ) { tmp = d->pass; encode( tmp ); - res += QLatin1String(":") + tmp; + res += QLatin1Char(':') + tmp; } - res += QLatin1String("@"); + res += QLatin1Char('@'); } res += d->host; if ( d->port != -1 ) - res += QLatin1String(":") + QString( QLatin1String("%1") ).arg( d->port ); + res += QLatin1Char(':') + QString::number( d->port ); if ( !p.isEmpty() ) { if ( !d->host.isEmpty() && p[0]!= QLatin1Char( '/' ) ) - res += QLatin1String("/"); + res += QLatin1Char('/'); res += p; } } if ( !d->refEncoded.isEmpty() ) - res += QLatin1String("#") + d->refEncoded; + res += QLatin1Char('#') + d->refEncoded; if ( !d->queryEncoded.isEmpty() ) - res += QLatin1String("?") + d->queryEncoded; + res += QLatin1Char('?') + d->queryEncoded; return res; } diff --git a/src/qt3support/network/q3urloperator.cpp b/src/qt3support/network/q3urloperator.cpp index b415e12..6afd8ab 100644 --- a/src/qt3support/network/q3urloperator.cpp +++ b/src/qt3support/network/q3urloperator.cpp @@ -579,7 +579,7 @@ Q3PtrList Q3UrlOperator::copy( const QString &from, const QS if (frm == to + file) return ops; - file.prepend( QLatin1String("/") ); + file.prepend( QLatin1Char('/') ); // uFrom and uTo are deleted when the Q3NetworkProtocol deletes itself via // autodelete diff --git a/src/qt3support/other/q3dragobject.cpp b/src/qt3support/other/q3dragobject.cpp index 50b75a4..89ffe24 100644 --- a/src/qt3support/other/q3dragobject.cpp +++ b/src/qt3support/other/q3dragobject.cpp @@ -93,7 +93,7 @@ public: Q3TextDragPrivate() { setSubType(QLatin1String("plain")); } void setSubType(const QString & st) { subtype = st; - fmt = QString(QLatin1String("text/")).toLatin1() + subtype.toLatin1(); + fmt = "text/" + subtype.toLatin1(); } QString txt; @@ -1297,7 +1297,7 @@ QByteArray Q3UriDrag::localFileToUri(const QString& filename) r.prepend(QString::fromLatin1(hostname)); } #endif - return unicodeUriToUri(QString(QLatin1String("file://") + r)); + return unicodeUriToUri(QLatin1String("file://") + r); } /*! @@ -1352,7 +1352,7 @@ QString Q3UriDrag::uriToLocalFile(const char* uri) return file; if (0==qstrnicmp(uri,"file:/",6)) // It is a local file uri uri += 6; - else if (QString(QLatin1String(uri)).indexOf(QLatin1String(":/")) != -1) // It is a different scheme uri + else if (QString::fromLatin1(uri).indexOf(QLatin1String(":/")) != -1) // It is a different scheme uri return file; bool local = uri[0] != '/' || (uri[0] != '\0' && uri[1] == '/'); diff --git a/src/qt3support/other/q3process.cpp b/src/qt3support/other/q3process.cpp index 6eac812..9689de9 100644 --- a/src/qt3support/other/q3process.cpp +++ b/src/qt3support/other/q3process.cpp @@ -483,7 +483,7 @@ QString Q3Process::readLineStdout() return QString(); if ( !buf->scanNewline( &a ) ) - return QString( QLatin1String(buf->readAll()) ); + return QLatin1String(buf->readAll()); } uint size = a.size(); diff --git a/src/qt3support/other/q3process_unix.cpp b/src/qt3support/other/q3process_unix.cpp index 098c581..2492bf2 100644 --- a/src/qt3support/other/q3process_unix.cpp +++ b/src/qt3support/other/q3process_unix.cpp @@ -828,7 +828,7 @@ bool Q3Process::start( QStringList *env ) #ifndef QT_NO_DIR QFileInfo fileInfo( dir, command ); #else - QFileInfo fileInfo( dir + "/" + command ); + QFileInfo fileInfo( dir + QLatin1Char('/') + command ); #endif if ( fileInfo.isExecutable() ) { #if defined(Q_OS_MACX) diff --git a/src/qt3support/other/q3process_win.cpp b/src/qt3support/other/q3process_win.cpp index 3c862ee..7dc28cb 100644 --- a/src/qt3support/other/q3process_win.cpp +++ b/src/qt3support/other/q3process_win.cpp @@ -285,7 +285,7 @@ bool Q3Process::start( QStringList *env ) for ( ; it != _arguments.end(); ++it ) { QString tmp = *it; // escape a single " because the arguments will be parsed - tmp.replace( QLatin1String("\""), QLatin1String("\\\"") ); + tmp.replace( QLatin1Char('\"'), QLatin1String("\\\"") ); if ( tmp.isEmpty() || tmp.contains( QLatin1Char(' ') ) || tmp.contains( QLatin1Char('\t') ) ) { // The argument must not end with a \ since this would be interpreted // as escaping the quote -- rather put the \ behind the quote: e.g. @@ -294,9 +294,9 @@ bool Q3Process::start( QStringList *env ) int i = tmp.length(); while ( i>0 && tmp.at( i-1 ) == QLatin1Char('\\') ) { --i; - endQuote += QLatin1String("\\"); + endQuote += QLatin1Char('\\'); } - args += QString( QLatin1String(" \"") ) + tmp.left( i ) + endQuote; + args += QLatin1String(" \"") + tmp.left( i ) + endQuote; } else { args += QLatin1Char(' ') + tmp; } @@ -330,7 +330,7 @@ bool Q3Process::start( QStringList *env ) // add PATH if necessary (for DLL loading) QByteArray path = qgetenv( "PATH" ); if ( env->grep( QRegExp(QLatin1String("^PATH="),FALSE) ).empty() && !path.isNull() ) { - QString tmp = QString( QLatin1String("PATH=%1") ).arg(QString::fromLatin1(path.constData())); + QString tmp = QString::fromLatin1("PATH=%1").arg(QLatin1String(path.constData())); uint tmpSize = sizeof(TCHAR) * (tmp.length()+1); envlist.resize( envlist.size() + tmpSize ); memcpy( envlist.data()+pos, tmp.ucs2(), tmpSize ); @@ -378,7 +378,7 @@ bool Q3Process::start( QStringList *env ) // add PATH if necessary (for DLL loading) QByteArray path = qgetenv( "PATH" ); if ( env->grep( QRegExp(QLatin1String("^PATH="),FALSE) ).empty() && !path.isNull() ) { - Q3CString tmp = QString( QLatin1String("PATH=%1") ).arg(QString::fromLatin1(path.constData())).local8Bit(); + Q3CString tmp = QString::fromLatin1("PATH=%1").arg(QString::fromLatin1(path.constData())).local8Bit(); uint tmpSize = tmp.length() + 1; envlist.resize( envlist.size() + tmpSize ); memcpy( envlist.data()+pos, tmp.data(), tmpSize ); diff --git a/src/qt3support/painting/q3paintengine_svg.cpp b/src/qt3support/painting/q3paintengine_svg.cpp index 95528e8..22e0d49 100644 --- a/src/qt3support/painting/q3paintengine_svg.cpp +++ b/src/qt3support/painting/q3paintengine_svg.cpp @@ -263,7 +263,7 @@ void Q3SVGPaintEngine::updateClipPath(const QPainterPath &path, Qt::ClipOperatio QDomElement e; d->currentClip++; e = d->doc.createElement(QLatin1String("clipPath")); - e.setAttribute(QLatin1String("id"), QString(QLatin1String("clip%1")).arg(d->currentClip)); + e.setAttribute(QLatin1String("id"), QString::fromLatin1("clip%1").arg(d->currentClip)); QDomElement path_element = d->doc.createElement(QLatin1String("path")); path_element.setAttribute(QLatin1String("d"), qt_svg_compose_path(path)); @@ -509,14 +509,14 @@ bool Q3SVGPaintEngine::save(const QString &fileName) int icount = 0; ImageList::Iterator iit = d->images.begin(); for (; iit != d->images.end(); ++iit) { - QString href = QString(QLatin1String("%1_%2.png")).arg(svgName).arg(icount); + QString href = QString::fromLatin1("%1_%2.png").arg(svgName).arg(icount); (*iit).image.save(href, "PNG"); (*iit).element.setAttribute(QLatin1String("xlink:href"), href); icount++; } PixmapList::Iterator pit = d->pixmaps.begin(); for (; pit != d->pixmaps.end(); ++pit) { - QString href = QString(QLatin1String("%1_%2.png")).arg(svgName).arg(icount); + QString href = QString::fromLatin1("%1_%2.png").arg(svgName).arg(icount); (*pit).pixmap.save(href, "PNG"); (*pit).element.setAttribute(QLatin1String("xlink:href"), href); icount++; @@ -592,7 +592,7 @@ void Q3SVGPaintEnginePrivate::appendChild(QDomElement &e, QPicturePrivate::Paint if (c == QPicturePrivate::PdcSetClipRegion || c == QPicturePrivate::PdcSetClipPath) { QDomElement ne; ne = doc.createElement(QLatin1String("g")); - ne.setAttribute(QLatin1String("style"), QString(QLatin1String("clip-path:url(#clip%1)")).arg(currentClip)); + ne.setAttribute(QLatin1String("style"), QString::fromLatin1("clip-path:url(#clip%1)").arg(currentClip)); if (dirtyTransform) { applyTransform(&ne); dirtyTransform = false; @@ -621,12 +621,12 @@ void Q3SVGPaintEnginePrivate::applyStyle(QDomElement *e, QPicturePrivate::PaintC if (c == QPicturePrivate::PdcDrawText2 || c == QPicturePrivate::PdcDrawText2Formatted) { // QPainter has a reversed understanding of pen/stroke vs. // brush/fill for text - s += QString(QLatin1String("fill:rgb(%1,%2,%3);")).arg(pcol.red()).arg(pcol.green()).arg(pcol.blue()); - s += QString(QLatin1String("stroke-width:0;")); + s += QString::fromLatin1("fill:rgb(%1,%2,%3);").arg(pcol.red()).arg(pcol.green()).arg(pcol.blue()); + s += QLatin1String("stroke-width:0;"); QFont f = cfont; QFontInfo fi(f); - s += QString(QLatin1String("font-size:%1;")).arg(fi.pointSize()); - s += QString(QLatin1String("font-style:%1;")).arg(f.italic() ? QLatin1String("italic") : QLatin1String("normal")); + s += QString::fromLatin1("font-size:%1;").arg(fi.pointSize()); + s += QString::fromLatin1("font-style:%1;").arg(f.italic() ? QLatin1String("italic") : QLatin1String("normal")); // not a very scientific distribution QString fw; if (f.weight() <= QFont::Light) @@ -641,32 +641,32 @@ void Q3SVGPaintEnginePrivate::applyStyle(QDomElement *e, QPicturePrivate::PaintC fw = QLatin1String("800"); else fw = QLatin1String("900"); - s += QString(QLatin1String("font-weight:%1;")).arg(fw); - s += QString(QLatin1String("font-family:%1;")).arg(f.family()); + s += QString::fromLatin1("font-weight:%1;").arg(fw); + s += QString::fromLatin1("font-family:%1;").arg(f.family()); } else { - s += QString(QLatin1String("stroke:rgb(%1,%2,%3);")).arg(pcol.red()).arg(pcol.green()).arg(pcol.blue()); + s += QString::fromLatin1("stroke:rgb(%1,%2,%3);").arg(pcol.red()).arg(pcol.green()).arg(pcol.blue()); if (pcol.alpha() != 255) - s += QString(QLatin1String("stroke-opacity:%1;")).arg(pcol.alpha()/255.0); + s += QString::fromLatin1("stroke-opacity:%1;").arg(pcol.alpha()/255.0); if (bcol.alpha() != 255) - s += QString(QLatin1String("fill-opacity:%1;")).arg(bcol.alpha()/255.0); + s += QString::fromLatin1("fill-opacity:%1;").arg(bcol.alpha()/255.0); double pw = cpen.width(); if (pw == 0 && cpen.style() != Qt::NoPen) pw = 0.9; if (c == QPicturePrivate::PdcDrawLine) pw /= (qAbs(worldMatrix.m11()) + qAbs(worldMatrix.m22())) / 2.0; - s += QString(QLatin1String("stroke-width:%1;")).arg(pw); + s += QString::fromLatin1("stroke-width:%1;").arg(pw); if (cpen.style() == Qt::DashLine) - s+= QString(QLatin1String("stroke-dasharray:18,6;")); + s+= QLatin1String("stroke-dasharray:18,6;"); else if (cpen.style() == Qt::DotLine) - s+= QString(QLatin1String("stroke-dasharray:3;")); + s+= QLatin1String("stroke-dasharray:3;"); else if (cpen.style() == Qt::DashDotLine) - s+= QString(QLatin1String("stroke-dasharray:9,6,3,6;")); + s+= QLatin1String("stroke-dasharray:9,6,3,6;"); else if (cpen.style() == Qt::DashDotDotLine) - s+= QString(QLatin1String("stroke-dasharray:9,3,3;")); + s+= QLatin1String("stroke-dasharray:9,3,3;"); if (cbrush.style() == Qt::NoBrush || c == QPicturePrivate::PdcDrawPolyline || c == QPicturePrivate::PdcDrawCubicBezier) s += QLatin1String("fill:none;"); // Qt polylines use no brush, neither do Beziers else - s += QString(QLatin1String("fill:rgb(%1,%2,%3);")).arg(bcol.red()).arg(bcol.green()).arg(bcol.blue()); + s += QString::fromLatin1("fill:rgb(%1,%2,%3);").arg(bcol.red()).arg(bcol.green()).arg(bcol.blue()); } e->setAttribute(QLatin1String("style"), s); } @@ -679,13 +679,13 @@ void Q3SVGPaintEnginePrivate::applyTransform(QDomElement *e) const bool rot = (m.m11() != 1.0 || m.m12() != 0.0 || m.m21() != 0.0 || m.m22() != 1.0); if (!rot && (m.dx() != 0.0 || m.dy() != 0.0)) { - s = QString(QLatin1String("translate(%1,%2)")).arg(m.dx()).arg(m.dy()); + s = QString::fromLatin1("translate(%1,%2)").arg(m.dx()).arg(m.dy()); } else if (rot) { if (m.m12() == 0.0 && m.m21() == 0.0 && m.dx() == 0.0 && m.dy() == 0.0) - s = QString(QLatin1String("scale(%1,%2)")).arg(m.m11()).arg(m.m22()); + s = QString::fromLatin1("scale(%1,%2)").arg(m.m11()).arg(m.m22()); else - s = QString(QLatin1String("matrix(%1,%2,%3,%4,%5,%6)")) + s = QString::fromLatin1("matrix(%1,%2,%3,%4,%5,%6)") .arg(m.m11()).arg(m.m12()) .arg(m.m21()).arg(m.m22()) .arg(m.dx()).arg(m.dy()); @@ -730,9 +730,9 @@ bool Q3SVGPaintEngine::play(QPainter *pt) d->brect.setX(x); d->brect.setY(y); QString wstr = attr.contains(QLatin1String("width")) - ? attr.namedItem(QLatin1String("width")).nodeValue() : QString(QLatin1String("100%")); + ? attr.namedItem(QLatin1String("width")).nodeValue() : QString::fromLatin1("100%"); QString hstr = attr.contains(QLatin1String("height")) - ? attr.namedItem(QLatin1String("height")).nodeValue() : QString(QLatin1String("100%")); + ? attr.namedItem(QLatin1String("height")).nodeValue() : QString::fromLatin1("100%"); double width = d->parseLen(wstr, 0, true); double height = d->parseLen(hstr, 0, false); // SVG doesn't respect x and y. But we want a proper bounding rect. diff --git a/src/qt3support/text/q3richtext.cpp b/src/qt3support/text/q3richtext.cpp index e508001..d02f961 100644 --- a/src/qt3support/text/q3richtext.cpp +++ b/src/qt3support/text/q3richtext.cpp @@ -1678,7 +1678,7 @@ void Q3TextDocument::setRichTextInternal(const QString &text, Q3TextCursor* curs if (curtag.style->displayMode() == Q3StyleSheetItem::DisplayListItem) { // we are in a li and a new block comes along - if (nstyle->name() == QString(QLatin1String("ul")) || nstyle->name() == QLatin1String("ol")) + if (nstyle->name() == QLatin1String("ul") || nstyle->name() == QLatin1String("ol")) hasNewPar = false; // we want an empty li (like most browsers) if (!hasNewPar) { /* do not add new blocks inside @@ -1857,7 +1857,7 @@ void Q3TextDocument::setRichTextInternal(const QString &text, Q3TextCursor* curs curtag.format = curtag.format.makeTextFormat(nstyle, attr, scaleFontsFactor); if (nstyle->isAnchor()) { if (!anchorName.isEmpty()) - anchorName += QLatin1String("#") + attr[QLatin1String("name")]; + anchorName += QLatin1Char('#') + attr[QLatin1String("name")]; else anchorName = attr[QLatin1String("name")]; curtag.anchorHref = attr[QLatin1String("href")]; @@ -2436,7 +2436,7 @@ QString Q3TextDocument::richText() const list_type = QLatin1String(" type=") + list_style_to_string(p->listStyle()); for (int i = pastListDepth; i < listDepth; i++) { s += list_is_ordered(p->listStyle()) ? QLatin1String(""); + s += list_type + QLatin1Char('>'); } } else { s += QLatin1Char('\n'); @@ -2463,7 +2463,7 @@ QString Q3TextDocument::richText() const s += margin_to_string(item_li, p->utm, p->ubm, p->ulm, p->urm, p->uflm); s += list_value_to_string(p->listValue()); s += direction_to_string(p->direction()); - s += QLatin1String(">"); + s += QLatin1Char('>'); s += ps; s += QLatin1String(""); } else if (p->listDepth()) { @@ -2471,7 +2471,7 @@ QString Q3TextDocument::richText() const s += align_to_string(p->alignment()); s += margin_to_string(item_div, p->utm, p->ubm, p->ulm, p->urm, p->uflm); s += direction_to_string(p->direction()); - s += QLatin1String(">"); + s += QLatin1Char('>'); s += ps; s += QLatin1String("

    "); } else { @@ -2480,7 +2480,7 @@ QString Q3TextDocument::richText() const s += align_to_string(p->alignment()); s += margin_to_string(item_p, p->utm, p->ubm, p->ulm, p->urm, p->uflm); s += direction_to_string(p->direction()); - s += QLatin1String(">"); + s += QLatin1Char('>'); s += ps; s += QLatin1String("

    "); } @@ -6667,7 +6667,7 @@ Q3TextImage::Q3TextImage(Q3TextDocument *p, const QMap &attr, imageName = attr[QLatin1String("source")]; if (!imageName.isEmpty()) { - imgId = QString(QLatin1String("%1,%2,%3,%4")).arg(imageName).arg(width).arg(height).arg((ulong)&factory); + imgId = QString::fromLatin1("%1,%2,%3,%4").arg(imageName).arg(width).arg(height).arg((ulong)&factory); if (!pixmap_map) pixmap_map = new QMap; if (pixmap_map->contains(imgId)) { @@ -6761,13 +6761,13 @@ QString Q3TextImage::richText() const s += QLatin1String("::ConstIterator it = attributes.begin(); for (; it != attributes.end(); ++it) { - s += it.key() + QLatin1String("="); + s += it.key() + QLatin1Char('='); if ((*it).contains(QLatin1Char(' '))) - s += QLatin1String("\"") + *it + QLatin1String("\" "); + s += QLatin1Char('\"') + *it + QLatin1String("\" "); else - s += *it + QLatin1String(" "); + s += *it + QLatin1Char(' '); } - s += QLatin1String(">"); + s += QLatin1Char('>'); return s; } @@ -7722,7 +7722,7 @@ QString Q3TextTable::richText() const s = QLatin1String("::ConstIterator it = attributes.begin(); for (; it != attributes.end(); ++it) - s += it.key() + QLatin1String("=") + *it + QLatin1String(" "); + s += it.key() + QLatin1Char('=') + *it + QLatin1Char(' '); s += QLatin1String(">\n"); int lastRow = -1; @@ -7739,8 +7739,8 @@ QString Q3TextTable::richText() const s += QLatin1String("attributes.constBegin(); for (; it != cell->attributes.constEnd(); ++it) - s += QLatin1String(" ") + it.key() + QLatin1String("=") + *it; - s += QLatin1String(">"); + s += QLatin1Char(' ') + it.key() + QLatin1Char('=') + *it; + s += QLatin1Char('>'); s += cell->richText()->richText(); s += QLatin1String(""); } diff --git a/src/qt3support/text/q3textedit.cpp b/src/qt3support/text/q3textedit.cpp index 7577dce..d1db1e4 100644 --- a/src/qt3support/text/q3textedit.cpp +++ b/src/qt3support/text/q3textedit.cpp @@ -77,7 +77,7 @@ #include #define ACCEL_KEY(k) QLatin1Char('\t') + QString(QKeySequence(Qt::CTRL | Qt::Key_ ## k)) #else -#define ACCEL_KEY(k) QLatin1Char('\t' )+ QString(QLatin1String("Ctrl+" #k)) +#define ACCEL_KEY(k) QLatin1Char('\t' )+ QString::fromLatin1("Ctrl+" #k) #endif #ifdef QT_TEXTEDIT_OPTIMIZATION @@ -6625,7 +6625,7 @@ void Q3TextEdit::optimSetTextFormat(Q3TextDocument * td, Q3TextCursor * cur, } if (tag) { QString col = tag->tag.simplified(); - if (col.left(10) == QLatin1String("font color")) { + if (col.startsWith(QLatin1String("font color"))) { int i = col.indexOf(QLatin1Char('='), 10); col = col.mid(i + 1).simplified(); if (col[0] == QLatin1Char('\"')) diff --git a/src/qt3support/widgets/q3mainwindow.cpp b/src/qt3support/widgets/q3mainwindow.cpp index 2ee3bdc..ae80321 100644 --- a/src/qt3support/widgets/q3mainwindow.cpp +++ b/src/qt3support/widgets/q3mainwindow.cpp @@ -2261,7 +2261,7 @@ static void saveDockArea(QTextStream &ts, Q3DockArea *a) for (int i = 0; i < l.size(); ++i) { Q3DockWindow *dw = l.at(i); ts << QString(dw->windowTitle()); - ts << ","; + ts << ','; } ts << endl; ts << *a; @@ -2287,7 +2287,7 @@ QTextStream &operator<<(QTextStream &ts, const Q3MainWindow &mainWindow) for (int i = 0; i < l.size(); ++i) { Q3DockWindow *dw = l.at(i); ts << dw->windowTitle(); - ts << ","; + ts << ','; } ts << endl; @@ -2295,17 +2295,17 @@ QTextStream &operator<<(QTextStream &ts, const Q3MainWindow &mainWindow) for (int i = 0; i < l.size(); ++i) { Q3DockWindow *dw = l.at(i); ts << dw->windowTitle(); - ts << ","; + ts << ','; } ts << endl; for (int i = 0; i < l.size(); ++i) { Q3DockWindow *dw = l.at(i); - ts << "[" << dw->windowTitle() << "," - << (int)dw->geometry().x() << "," - << (int)dw->geometry().y() << "," - << (int)dw->geometry().width() << "," - << (int)dw->geometry().height() << "," - << (int)dw->isVisible() << "]"; + ts << '[' << dw->windowTitle() << ',' + << (int)dw->geometry().x() << ',' + << (int)dw->geometry().y() << ',' + << (int)dw->geometry().width() << ',' + << (int)dw->geometry().height() << ',' + << (int)dw->isVisible() << ']'; } ts << endl; diff --git a/src/script/qscriptcontext.cpp b/src/script/qscriptcontext.cpp index 020601b..ff519c7 100644 --- a/src/script/qscriptcontext.cpp +++ b/src/script/qscriptcontext.cpp @@ -469,7 +469,7 @@ QString QScriptContext::toString() const QScriptValue arg = argument(i); result.append(safeValueToString(arg)); } - result.append(QLatin1String(")")); + result.append(QLatin1Char(')')); QString fileName = info.fileName(); int lineNumber = info.lineNumber(); diff --git a/src/script/qscriptcontext_p.cpp b/src/script/qscriptcontext_p.cpp index 199c9d4..f19ba9c 100644 --- a/src/script/qscriptcontext_p.cpp +++ b/src/script/qscriptcontext_p.cpp @@ -841,7 +841,7 @@ Ltop: flags = iPtr->operand[1].m_int_value; #ifndef QT_NO_REGEXP if (flags != 0) { - literal += QLatin1String("/"); + literal += QLatin1Char('/'); literal += QString::number(flags); } #endif @@ -2396,10 +2396,10 @@ QStringList QScriptContextPrivate::backtrace() const s += QLatin1String(""); } } - s += QLatin1String("("); + s += QLatin1Char('('); for (int i = 0; i < ctx->argc; ++i) { if (i > 0) - s += QLatin1String(","); + s += QLatin1Char(','); QScriptValueImpl arg = ctx->args[i]; if (arg.isObject()) s += QLatin1String("[object Object]"); // don't do a function call diff --git a/src/script/qscriptecmaerror.cpp b/src/script/qscriptecmaerror.cpp index fc39bf9..0dde68c 100644 --- a/src/script/qscriptecmaerror.cpp +++ b/src/script/qscriptecmaerror.cpp @@ -318,18 +318,18 @@ QStringList Error::backtrace(const QScriptValueImpl &error) } else { s += functionName; } - s += QLatin1String("("); + s += QLatin1Char('('); QScriptValueImpl arguments = frame.property(QLatin1String("arguments")); if (arguments.isObject()) { int argCount = arguments.property(QLatin1String("length")).toInt32(); for (int j = 0; j < argCount; ++j) { if (j > 0) - s += QLatin1String(","); + s += QLatin1Char(','); s += arguments.property(j).toString(); } } s += QLatin1String(")@") + o.property(QLatin1String("fileName")).toString() - + QLatin1String(":") + o.property(QLatin1String("lineNumber")).toString(); + + QLatin1Char(':') + o.property(QLatin1String("lineNumber")).toString(); result.append(s); } return result; diff --git a/src/script/qscriptecmafunction.cpp b/src/script/qscriptecmafunction.cpp index ec45ae4..a1e5b58 100644 --- a/src/script/qscriptecmafunction.cpp +++ b/src/script/qscriptecmafunction.cpp @@ -197,7 +197,7 @@ QString Function::buildFunction(QScriptContextPrivate *context) // the formals for (int i = 0; i < argc - 1; ++i) { if (i != 0) - code += QLatin1String(","); + code += QLatin1Char(','); code += context->argument(i).toString(); } diff --git a/src/script/qscriptecmaglobal.cpp b/src/script/qscriptecmaglobal.cpp index da7ab9e..b5cf675 100644 --- a/src/script/qscriptecmaglobal.cpp +++ b/src/script/qscriptecmaglobal.cpp @@ -296,7 +296,7 @@ public: QString result; for (int i = 0; i < context->argumentCount(); ++i) { if (i != 0) - result.append(QLatin1String(" ")); + result.append(QLatin1Char(' ')); QString s = context->argument(i).toString(); if (context->state() == QScriptContext::ExceptionState) diff --git a/src/script/qscriptecmaobject.cpp b/src/script/qscriptecmaobject.cpp index 694f479..c4a1b08 100644 --- a/src/script/qscriptecmaobject.cpp +++ b/src/script/qscriptecmaobject.cpp @@ -113,7 +113,7 @@ QScriptValueImpl Object::method_toString(QScriptContextPrivate *context, QScript QString s = QLatin1String("[object "); QScriptValueImpl self = context->thisObject(); s += self.classInfo()->name(); - s += QLatin1String("]"); + s += QLatin1Char(']'); return (QScriptValueImpl(eng, s)); } diff --git a/src/script/qscriptparser.cpp b/src/script/qscriptparser.cpp index 0b04df1..7408ec5 100644 --- a/src/script/qscriptparser.cpp +++ b/src/script/qscriptparser.cpp @@ -1148,9 +1148,9 @@ case 266: { error_message += QLatin1String (", "); first = false; - error_message += QLatin1String("`"); + error_message += QLatin1Char('`'); error_message += QLatin1String (spell [expected_tokens [s]]); - error_message += QLatin1String("'"); + error_message += QLatin1Char('\''); } } diff --git a/src/script/qscriptprettypretty.cpp b/src/script/qscriptprettypretty.cpp index 6ee1e55..b221b0a 100644 --- a/src/script/qscriptprettypretty.cpp +++ b/src/script/qscriptprettypretty.cpp @@ -73,13 +73,13 @@ PrettyPretty::~PrettyPretty() void PrettyPretty::acceptAsBlock(AST::Node *node) { - out << "{"; + out << '{'; pushIndentLevel(); newlineAndIndent(); accept(node); popIndentLevel(); newlineAndIndent(); - out << "}"; + out << '}'; } int PrettyPretty::operatorPrecedenceLevel(int op) @@ -230,8 +230,8 @@ void PrettyPretty::endVisit(AST::FalseLiteral *node) bool PrettyPretty::visit(AST::StringLiteral *node) { QString lit = QScriptEnginePrivate::toString(node->value); - lit.replace(QLatin1String("\\"), QLatin1String("\\\\")); - out << "\"" << lit << "\""; + lit.replace(QLatin1Char('\\'), QLatin1String("\\\\")); + out << '\"' << lit << '\"'; return false; } @@ -253,7 +253,7 @@ void PrettyPretty::endVisit(AST::NumericLiteral *node) bool PrettyPretty::visit(AST::RegExpLiteral *node) { - out << "/" << QScriptEnginePrivate::toString(node->pattern) << "/"; + out << '/' << QScriptEnginePrivate::toString(node->pattern) << '/'; if (node->flags) out << QScript::Ecma::RegExp::flagsToString(node->flags); @@ -267,10 +267,10 @@ void PrettyPretty::endVisit(AST::RegExpLiteral *node) bool PrettyPretty::visit(AST::ArrayLiteral *node) { - out << "["; + out << '['; accept(node->elements); accept(node->elision); - out << "]"; + out << ']'; return false; } @@ -281,7 +281,7 @@ void PrettyPretty::endVisit(AST::ArrayLiteral *node) bool PrettyPretty::visit(AST::ObjectLiteral *node) { - out << "{"; + out << '{'; if (node->properties) { pushIndentLevel(); AST::PropertyNameAndValueList *prop; @@ -289,12 +289,12 @@ bool PrettyPretty::visit(AST::ObjectLiteral *node) newlineAndIndent(); accept(prop); if (prop->next) - out << ","; + out << ','; } popIndentLevel(); newlineAndIndent(); } - out << "}"; + out << '}'; return false; } @@ -384,9 +384,9 @@ void PrettyPretty::endVisit(AST::NumericLiteralPropertyName *node) bool PrettyPretty::visit(AST::ArrayMemberExpression *node) { accept(node->base); - out << "["; + out << '['; accept(node->expression); - out << "]"; + out << ']'; return false; } @@ -398,7 +398,7 @@ void PrettyPretty::endVisit(AST::ArrayMemberExpression *node) bool PrettyPretty::visit(AST::FieldMemberExpression *node) { accept(node->base); - out << "." << QScriptEnginePrivate::toString(node->name); + out << '.' << QScriptEnginePrivate::toString(node->name); return false; } @@ -411,9 +411,9 @@ bool PrettyPretty::visit(AST::NewMemberExpression *node) { out << "new "; accept(node->base); - out << "("; + out << '('; accept(node->arguments); - out << ")"; + out << ')'; return false; } @@ -437,9 +437,9 @@ void PrettyPretty::endVisit(AST::NewExpression *node) bool PrettyPretty::visit(AST::CallExpression *node) { accept(node->base); - out << "("; + out << '('; accept(node->arguments); - out << ")"; + out << ')'; return false; } @@ -549,13 +549,13 @@ void PrettyPretty::endVisit(AST::PreDecrementExpression *node) bool PrettyPretty::visit(AST::UnaryPlusExpression *node) { - out << "+"; + out << '+'; bool needParens = (node->expression->binaryExpressionCast() != 0); if (needParens) - out << "("; + out << '('; accept(node->expression); if (needParens) - out << ")"; + out << ')'; return false; } @@ -566,13 +566,13 @@ void PrettyPretty::endVisit(AST::UnaryPlusExpression *node) bool PrettyPretty::visit(AST::UnaryMinusExpression *node) { - out << "-"; + out << '-'; bool needParens = (node->expression->binaryExpressionCast() != 0); if (needParens) - out << "("; + out << '('; accept(node->expression); if (needParens) - out << ")"; + out << ')'; return false; } @@ -583,13 +583,13 @@ void PrettyPretty::endVisit(AST::UnaryMinusExpression *node) bool PrettyPretty::visit(AST::TildeExpression *node) { - out << "~"; + out << '~'; bool needParens = (node->expression->binaryExpressionCast() != 0); if (needParens) - out << "("; + out << '('; accept(node->expression); if (needParens) - out << ")"; + out << ')'; return false; } @@ -600,13 +600,13 @@ void PrettyPretty::endVisit(AST::TildeExpression *node) bool PrettyPretty::visit(AST::NotExpression *node) { - out << "!"; + out << '!'; bool needParens = (node->expression->binaryExpressionCast() != 0); if (needParens) - out << "("; + out << '('; accept(node->expression); if (needParens) - out << ")"; + out << ')'; return false; } @@ -620,10 +620,10 @@ bool PrettyPretty::visit(AST::BinaryExpression *node) bool needParens = node->left->binaryExpressionCast() && (compareOperatorPrecedence(node->left->binaryExpressionCast()->op, node->op) < 0); if (needParens) - out << "("; + out << '('; accept(node->left); if (needParens) - out << ")"; + out << ')'; QString s; switch (node->op) { case QSOperator::Add: @@ -699,14 +699,14 @@ bool PrettyPretty::visit(AST::BinaryExpression *node) default: Q_ASSERT (0); } - out << " " << s << " "; + out << ' ' << s << ' '; needParens = node->right->binaryExpressionCast() && (compareOperatorPrecedence(node->right->binaryExpressionCast()->op, node->op) <= 0); if (needParens) - out << "("; + out << '('; accept(node->right); if (needParens) - out << ")"; + out << ')'; return false; } @@ -798,7 +798,7 @@ bool PrettyPretty::visit(AST::VariableStatement *node) void PrettyPretty::endVisit(AST::VariableStatement *node) { Q_UNUSED(node); - out << ";"; + out << ';'; } bool PrettyPretty::visit(AST::VariableDeclaration *node) @@ -819,7 +819,7 @@ void PrettyPretty::endVisit(AST::VariableDeclaration *node) bool PrettyPretty::visit(AST::EmptyStatement *node) { Q_UNUSED(node); - out << ";"; + out << ';'; return true; } @@ -831,7 +831,7 @@ void PrettyPretty::endVisit(AST::EmptyStatement *node) bool PrettyPretty::visit(AST::ExpressionStatement *node) { accept(node->expression); - out << ";"; + out << ';'; return false; } @@ -959,9 +959,9 @@ bool PrettyPretty::visit(AST::ContinueStatement *node) { out << "continue"; if (node->label) { - out << " " << QScriptEnginePrivate::toString(node->label); + out << ' ' << QScriptEnginePrivate::toString(node->label); } - out << ";"; + out << ';'; return false; } @@ -974,9 +974,9 @@ bool PrettyPretty::visit(AST::BreakStatement *node) { out << "break"; if (node->label) { - out << " " << QScriptEnginePrivate::toString(node->label); + out << ' ' << QScriptEnginePrivate::toString(node->label); } - out << ";"; + out << ';'; return false; } @@ -989,10 +989,10 @@ bool PrettyPretty::visit(AST::ReturnStatement *node) { out << "return"; if (node->expression) { - out << " "; + out << ' '; accept(node->expression); } - out << ";"; + out << ';'; return false; } @@ -1067,7 +1067,7 @@ bool PrettyPretty::visit(AST::CaseClause *node) { out << "case "; accept(node->expression); - out << ":"; + out << ':'; if (node->statements) { newlineAndIndent(); accept(node->statements); @@ -1109,7 +1109,7 @@ bool PrettyPretty::visit(AST::ThrowStatement *node) Q_UNUSED(node); out << "throw "; accept(node->expression); - out << ";"; + out << ';'; return false; } @@ -1166,10 +1166,10 @@ bool PrettyPretty::visit(AST::FunctionDeclaration *node) out << "function"; if (node->name) - out << " " << QScriptEnginePrivate::toString(node->name); + out << ' ' << QScriptEnginePrivate::toString(node->name); // the arguments - out << "("; + out << '('; for (AST::FormalParameterList *it = node->formals; it; it = it->next) { if (it->name) out << QScriptEnginePrivate::toString(it->name); @@ -1177,7 +1177,7 @@ bool PrettyPretty::visit(AST::FunctionDeclaration *node) if (it->next) out << ", "; } - out << ")"; + out << ')'; // the function body out << " {"; @@ -1190,7 +1190,7 @@ bool PrettyPretty::visit(AST::FunctionDeclaration *node) newlineAndIndent(); } - out << "}"; + out << '}'; return false; } @@ -1205,10 +1205,10 @@ bool PrettyPretty::visit(AST::FunctionExpression *node) out << "function"; if (node->name) - out << " " << QScriptEnginePrivate::toString(node->name); + out << ' ' << QScriptEnginePrivate::toString(node->name); // the arguments - out << "("; + out << '('; for (AST::FormalParameterList *it = node->formals; it; it = it->next) { if (it->name) out << QScriptEnginePrivate::toString(it->name); @@ -1216,7 +1216,7 @@ bool PrettyPretty::visit(AST::FunctionExpression *node) if (it->next) out << ", "; } - out << ")"; + out << ')'; // the function body out << " {"; @@ -1229,7 +1229,7 @@ bool PrettyPretty::visit(AST::FunctionExpression *node) newlineAndIndent(); } - out << "}"; + out << '}'; return false; } @@ -1320,7 +1320,7 @@ bool PrettyPretty::visit(AST::DebuggerStatement *node) void PrettyPretty::endVisit(AST::DebuggerStatement *node) { Q_UNUSED(node); - out << ";"; + out << ';'; } bool PrettyPretty::preVisit(AST::Node *node) diff --git a/src/script/qscriptsyntaxchecker.cpp b/src/script/qscriptsyntaxchecker.cpp index 9653bc1..74ca00f 100644 --- a/src/script/qscriptsyntaxchecker.cpp +++ b/src/script/qscriptsyntaxchecker.cpp @@ -186,9 +186,9 @@ SyntaxChecker::Result SyntaxChecker::checkSyntax(const QString &code) error_message += QLatin1String (", "); first = false; - error_message += QLatin1String("`"); + error_message += QLatin1Char('`'); error_message += QLatin1String (spell [expected_tokens [s]]); - error_message += QLatin1String("'"); + error_message += QLatin1Char('\''); } } diff --git a/src/script/qscriptvalueimpl.cpp b/src/script/qscriptvalueimpl.cpp index 15d1b8a..a890839 100644 --- a/src/script/qscriptvalueimpl.cpp +++ b/src/script/qscriptvalueimpl.cpp @@ -395,7 +395,7 @@ QDebug &operator<<(QDebug &d, const QScriptValueImpl &object) QScriptObject *od = object.objectValue(); for (int i=0; imemberCount(); ++i) { if (i != 0) - d << ","; + d << ','; QScript::Member m; od->member(i, &m); @@ -404,7 +404,7 @@ QDebug &operator<<(QDebug &d, const QScriptValueImpl &object) d << object.engine()->toString(m.nameId()); QScriptValueImpl o; od->get(m, &o); - d.nospace() << QLatin1String(":") + d.nospace() << QLatin1Char(':') << (o.classInfo() ? o.classInfo()->name() : QLatin1String("?")); @@ -415,14 +415,14 @@ QDebug &operator<<(QDebug &d, const QScriptValueImpl &object) QScriptValueImpl scope = object.scope(); while (scope.isValid()) { Q_ASSERT(scope.isObject()); - d.nospace() << " " << scope.objectValue(); + d.nospace() << ' ' << scope.objectValue(); scope = scope.scope(); } - d.nospace() << "}"; + d.nospace() << '}'; break; } - d << ")"; + d << ')'; return d; } diff --git a/src/script/qscriptxmlgenerator.cpp b/src/script/qscriptxmlgenerator.cpp index 131882b..163b60c 100644 --- a/src/script/qscriptxmlgenerator.cpp +++ b/src/script/qscriptxmlgenerator.cpp @@ -121,10 +121,10 @@ QTextStream &XmlGenerator::startTag(const QString &name, AST::Node *locationNode { pushIndentLevel(); newlineAndIndent(); - out << QLatin1String("<") << name; + out << QLatin1Char('<') << name; if (locationNode) - out << QLatin1String(" line=\"") << locationNode->startLine << QLatin1String("\""); - out << QLatin1String(">"); + out << QLatin1String(" line=\"") << locationNode->startLine << QLatin1Char('\"'); + out << QLatin1Char('>'); return out; } @@ -132,7 +132,7 @@ QTextStream &XmlGenerator::endTag(const QString &name) { newlineAndIndent(); popIndentLevel(); - out << QLatin1String(""); + out << QLatin1String("'); return out; } @@ -233,7 +233,7 @@ void XmlGenerator::endVisit(AST::NumericLiteral *) bool XmlGenerator::visit(AST::RegExpLiteral *node) { startTag(QLatin1String("regexp")); - out << QLatin1String("/") << escape(QScriptEnginePrivate::toString(node->pattern)) << QLatin1String("/"); + out << QLatin1Char('/') << escape(QScriptEnginePrivate::toString(node->pattern)) << QLatin1Char('/'); if (node->flags) out << QScript::Ecma::RegExp::flagsToString(node->flags); out << QLatin1String(""); diff --git a/src/scripttools/debugging/qscriptcompletiontask.cpp b/src/scripttools/debugging/qscriptcompletiontask.cpp index 119b96a..2f3c2cf 100644 --- a/src/scripttools/debugging/qscriptcompletiontask.cpp +++ b/src/scripttools/debugging/qscriptcompletiontask.cpp @@ -158,7 +158,7 @@ void QScriptCompletionTaskPrivate::completeScriptExpression() if (path.size() > 1) { const QString &topLevelIdent = path.at(0); QScriptValue obj; - if (topLevelIdent == QString::fromLatin1("this")) { + if (topLevelIdent == QLatin1String("this")) { obj = ctx->thisObject(); } else { QScriptValueList scopeChain; @@ -256,9 +256,9 @@ void QScriptCompletionTask::start() } QString argType = cmd->argumentTypes().value(argNum); if (!argType.isEmpty()) { - if (argType == QString::fromLatin1("command-or-group-name")) { + if (argType == QLatin1String("command-or-group-name")) { d->results = d->console->commandManager()->completions(arg); - } else if (argType == QString::fromLatin1("script-filename")) { + } else if (argType == QLatin1String("script-filename")) { // ### super-cheating for now; have to use the async API QScriptEngineDebuggerFrontend *edf = static_cast(d->frontend); QScriptDebuggerBackend *backend = edf->backend(); @@ -269,13 +269,13 @@ void QScriptCompletionTask::start() if (isPrefixOf(arg, fileName)) d->results.append(fileName); } - } else if (argType == QString::fromLatin1("subcommand-name")) { + } else if (argType == QLatin1String("subcommand-name")) { for (int i = 0; i < cmd->subCommands().size(); ++i) { QString name = cmd->subCommands().at(i); if (isPrefixOf(arg, name)) d->results.append(name); } - } else if (argType == QString::fromLatin1("script")) { + } else if (argType == QLatin1String("script")) { d->completeScriptExpression(); } if ((d->type == NoCompletion) && !d->results.isEmpty()) { diff --git a/src/scripttools/debugging/qscriptdebuggerbackend.cpp b/src/scripttools/debugging/qscriptdebuggerbackend.cpp index 3c29130..0771d0b 100644 --- a/src/scripttools/debugging/qscriptdebuggerbackend.cpp +++ b/src/scripttools/debugging/qscriptdebuggerbackend.cpp @@ -292,7 +292,7 @@ QScriptValue QScriptDebuggerBackendPrivate::trace(QScriptContext *context, QString str; for (int i = 0; i < context->argumentCount(); ++i) { if (i > 0) - str.append(QLatin1String(" ")); + str.append(QLatin1Char(' ')); str.append(context->argument(i).toString()); } QScriptDebuggerEvent e(QScriptDebuggerEvent::Trace); diff --git a/src/scripttools/debugging/qscriptdebuggerconsole.cpp b/src/scripttools/debugging/qscriptdebuggerconsole.cpp index 70bb8b1..546ec63 100644 --- a/src/scripttools/debugging/qscriptdebuggerconsole.cpp +++ b/src/scripttools/debugging/qscriptdebuggerconsole.cpp @@ -163,10 +163,10 @@ QScriptDebuggerConsoleCommandJob *QScriptDebuggerConsolePrivate::createJob( .arg(name)); for (int j = 0; j < completions.size(); ++j) { if (j > 0) - msg.append(QString::fromLatin1(", ")); + msg.append(QLatin1String(", ")); msg.append(completions.at(j)); } - msg.append(QString::fromLatin1(".")); + msg.append(QLatin1Char('.')); messageHandler->message(QtWarningMsg, msg); return 0; } diff --git a/src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp b/src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp index caeb971..e096ba8 100644 --- a/src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp +++ b/src/scripttools/debugging/qscriptdebuggerlocalsmodel.cpp @@ -807,7 +807,7 @@ QVariant QScriptDebuggerLocalsModel::data(const QModelIndex &index, int role) co QString str = node->property.valueAsString(); if (node->property.value().type() == QScriptDebuggerValue::StringValue) { // escape - str.replace(QLatin1String("\""), QLatin1String("\\\"")); + str.replace(QLatin1Char('\"'), QLatin1String("\\\"")); str.prepend(QLatin1Char('\"')); str.append(QLatin1Char('\"')); } diff --git a/src/sql/drivers/db2/qsql_db2.cpp b/src/sql/drivers/db2/qsql_db2.cpp index 11d0041..c7cbc9b 100644 --- a/src/sql/drivers/db2/qsql_db2.cpp +++ b/src/sql/drivers/db2/qsql_db2.cpp @@ -1666,7 +1666,7 @@ QVariant QDB2Driver::handle() const QString QDB2Driver::escapeIdentifier(const QString &identifier, IdentifierType) const { QString res = identifier; - if(!identifier.isEmpty() && identifier.left(1) != QString(QLatin1Char('"')) && identifier.right(1) != QString(QLatin1Char('"')) ) { + if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) { res.replace(QLatin1Char('"'), QLatin1String("\"\"")); res.prepend(QLatin1Char('"')).append(QLatin1Char('"')); res.replace(QLatin1Char('.'), QLatin1String("\".\"")); diff --git a/src/sql/drivers/ibase/qsql_ibase.cpp b/src/sql/drivers/ibase/qsql_ibase.cpp index 1645555..199ad8e 100644 --- a/src/sql/drivers/ibase/qsql_ibase.cpp +++ b/src/sql/drivers/ibase/qsql_ibase.cpp @@ -1732,7 +1732,7 @@ bool QIBaseDriver::subscribeToNotificationImplementation(const QString &name) eBuffer->resultBuffer); if (status[0] == 1 && status[1]) { - setLastError(QSqlError(QString(QLatin1String("Could not subscribe to event notifications for %1.")).arg(name))); + setLastError(QSqlError(QString::fromLatin1("Could not subscribe to event notifications for %1.").arg(name))); d->eventBuffers.remove(name); qFreeEventBuffer(eBuffer); return false; @@ -1760,7 +1760,7 @@ bool QIBaseDriver::unsubscribeFromNotificationImplementation(const QString &name isc_cancel_events(status, &d->ibase, &eBuffer->eventId); if (status[0] == 1 && status[1]) { - setLastError(QSqlError(QString(QLatin1String("Could not unsubscribe from event notifications for %1.")).arg(name))); + setLastError(QSqlError(QString::fromLatin1("Could not unsubscribe from event notifications for %1.").arg(name))); return false; } @@ -1818,7 +1818,7 @@ void QIBaseDriver::qHandleEventNotification(void *updatedResultBuffer) QString QIBaseDriver::escapeIdentifier(const QString &identifier, IdentifierType) const { QString res = identifier; - if(!identifier.isEmpty() && identifier.left(1) != QString(QLatin1Char('"')) && identifier.right(1) != QString(QLatin1Char('"')) ) { + if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) { res.replace(QLatin1Char('"'), QLatin1String("\"\"")); res.prepend(QLatin1Char('"')).append(QLatin1Char('"')); res.replace(QLatin1Char('.'), QLatin1String("\".\"")); diff --git a/src/sql/drivers/mysql/qsql_mysql.cpp b/src/sql/drivers/mysql/qsql_mysql.cpp index 53645c9..82ed124 100644 --- a/src/sql/drivers/mysql/qsql_mysql.cpp +++ b/src/sql/drivers/mysql/qsql_mysql.cpp @@ -1468,7 +1468,7 @@ QString QMYSQLDriver::formatValue(const QSqlField &field, bool trimStrings) cons QString QMYSQLDriver::escapeIdentifier(const QString &identifier, IdentifierType) const { QString res = identifier; - if(!identifier.isEmpty() && identifier.left(1) != QString(QLatin1Char('`')) && identifier.right(1) != QString(QLatin1Char('`')) ) { + if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('`')) && !identifier.endsWith(QLatin1Char('`')) ) { res.prepend(QLatin1Char('`')).append(QLatin1Char('`')); res.replace(QLatin1Char('.'), QLatin1String("`.`")); } @@ -1478,12 +1478,9 @@ QString QMYSQLDriver::escapeIdentifier(const QString &identifier, IdentifierType bool QMYSQLDriver::isIdentifierEscapedImplementation(const QString &identifier, IdentifierType type) const { Q_UNUSED(type); - bool isLeftDelimited = (identifier.left(1) == QString(QLatin1Char('`'))); - bool isRightDelimited = (identifier.right(1) == QString(QLatin1Char('`'))); - if( identifier.size() > 2 && isLeftDelimited && isRightDelimited ) - return true; - else - return false; + return identifier.size() > 2 + && identifier.startsWith(QLatin1Char('`')) //left delimited + && identifier.endsWith(QLatin1Char('`')); //right delimited } QT_END_NAMESPACE diff --git a/src/sql/drivers/oci/qsql_oci.cpp b/src/sql/drivers/oci/qsql_oci.cpp index a7031b1..e6ee63d 100644 --- a/src/sql/drivers/oci/qsql_oci.cpp +++ b/src/sql/drivers/oci/qsql_oci.cpp @@ -2040,8 +2040,8 @@ bool QOCIDriver::open(const QString & db, QString connectionString = db; if (!hostname.isEmpty()) connectionString = - QString(QLatin1String("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=%1)(Port=%2))" - "(CONNECT_DATA=(SID=%3)))")).arg(hostname).arg((port > -1 ? port : 1521)).arg(db); + QString::fromLatin1("(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(Host=%1)(Port=%2))" + "(CONNECT_DATA=(SID=%3)))").arg(hostname).arg((port > -1 ? port : 1521)).arg(db); r = OCIHandleAlloc(d->env, reinterpret_cast(&d->srvhp), OCI_HTYPE_SERVER, 0, 0); if (r == OCI_SUCCESS) @@ -2219,7 +2219,7 @@ QStringList QOCIDriver::tables(QSql::TableType type) const while (t.next()) { if (t.value(0).toString().toUpper() != user.toUpper()) - tl.append(t.value(0).toString() + QLatin1String(".") + t.value(1).toString()); + tl.append(t.value(0).toString() + QLatin1Char('.') + t.value(1).toString()); else tl.append(t.value(1).toString()); } @@ -2235,7 +2235,7 @@ QStringList QOCIDriver::tables(QSql::TableType type) const "and owner != 'WMSYS'")); while (t.next()) { if (t.value(0).toString().toUpper() != d->user.toUpper()) - tl.append(t.value(0).toString() + QLatin1String(".") + t.value(1).toString()); + tl.append(t.value(0).toString() + QLatin1Char('.') + t.value(1).toString()); else tl.append(t.value(1).toString()); } @@ -2297,7 +2297,7 @@ QSqlRecord QOCIDriver::record(const QString& tablename) const else owner = owner.toUpper(); - tmpStmt += QLatin1String(" and owner='") + owner + QLatin1String("'"); + tmpStmt += QLatin1String(" and owner='") + owner + QLatin1Char('\''); t.setForwardOnly(true); t.exec(tmpStmt); if (!t.next()) { // try and see if the tablename is a synonym @@ -2352,7 +2352,7 @@ QSqlIndex QOCIDriver::primaryIndex(const QString& tablename) const else table = table.toUpper(); - tmpStmt = stmt + QLatin1String(" and a.table_name='") + table + QLatin1String("'"); + tmpStmt = stmt + QLatin1String(" and a.table_name='") + table + QLatin1Char('\''); if (owner.isEmpty()) { owner = d->user; } @@ -2362,7 +2362,7 @@ QSqlIndex QOCIDriver::primaryIndex(const QString& tablename) const else owner = owner.toUpper(); - tmpStmt += QLatin1String(" and a.owner='") + owner + QLatin1String("'"); + tmpStmt += QLatin1String(" and a.owner='") + owner + QLatin1Char('\''); t.setForwardOnly(true); t.exec(tmpStmt); @@ -2386,7 +2386,7 @@ QSqlIndex QOCIDriver::primaryIndex(const QString& tablename) const tt.exec(QLatin1String("select data_type from all_tab_columns where table_name='") + t.value(2).toString() + QLatin1String("' and column_name='") + t.value(0).toString() + QLatin1String("' and owner='") + - owner +QLatin1String("'")); + owner + QLatin1Char('\'')); if (!tt.next()) { return QSqlIndex(); } diff --git a/src/sql/drivers/odbc/qsql_odbc.cpp b/src/sql/drivers/odbc/qsql_odbc.cpp index ee500a0..8eaa8bf 100644 --- a/src/sql/drivers/odbc/qsql_odbc.cpp +++ b/src/sql/drivers/odbc/qsql_odbc.cpp @@ -213,14 +213,14 @@ static QString qWarnODBCHandle(int handleType, SQLHANDLE handle, int *nativeCode static QString qODBCWarn(const QODBCPrivate* odbc, int *nativeCode = 0) { - return (qWarnODBCHandle(SQL_HANDLE_ENV, odbc->hEnv) + QLatin1String(" ") - + qWarnODBCHandle(SQL_HANDLE_DBC, odbc->hDbc) + QLatin1String(" ") + return (qWarnODBCHandle(SQL_HANDLE_ENV, odbc->hEnv) + QLatin1Char(' ') + + qWarnODBCHandle(SQL_HANDLE_DBC, odbc->hDbc) + QLatin1Char(' ') + qWarnODBCHandle(SQL_HANDLE_STMT, odbc->hStmt, nativeCode)); } static QString qODBCWarn(const QODBCDriverPrivate* odbc, int *nativeCode = 0) { - return (qWarnODBCHandle(SQL_HANDLE_ENV, odbc->hEnv) + QLatin1String(" ") + return (qWarnODBCHandle(SQL_HANDLE_ENV, odbc->hEnv) + QLatin1Char(' ') + qWarnODBCHandle(SQL_HANDLE_DBC, odbc->hDbc, nativeCode)); } @@ -2414,12 +2414,12 @@ QString QODBCDriver::escapeIdentifier(const QString &identifier, IdentifierType) { QString res = identifier; if (d->isMySqlServer) { - if(!identifier.isEmpty() && identifier.left(1) != QString(QLatin1Char('`')) && identifier.right(1) != QString(QLatin1Char('`')) ) { + if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('`')) && !identifier.endsWith(QLatin1Char('`')) ) { res.prepend(QLatin1Char('`')).append(QLatin1Char('`')); res.replace(QLatin1Char('.'), QLatin1String("`.`")); } } else { - if(!identifier.isEmpty() && identifier.left(1) != QString(QLatin1Char('"')) && identifier.right(1) != QString(QLatin1Char('"')) ) { + if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) { res.replace(QLatin1Char('"'), QLatin1String("\"\"")); res.prepend(QLatin1Char('"')).append(QLatin1Char('"')); res.replace(QLatin1Char('.'), QLatin1String("\".\"")); @@ -2430,13 +2430,10 @@ QString QODBCDriver::escapeIdentifier(const QString &identifier, IdentifierType) bool QODBCDriver::isIdentifierEscapedImplementation(const QString &identifier, IdentifierType) const { - QString quote = d->quoteChar(); - bool isLeftDelimited = identifier.left(1) == quote; - bool isRightDelimited = identifier.right(1) == quote; - if( identifier.size() > 2 && isLeftDelimited && isRightDelimited ) - return true; - else - return false; + QChar quote = d->quoteChar(); + return identifier.size() > 2 + && identifier.startsWith(quote) //left delimited + && identifier.endsWith(quote); //right delimited } QT_END_NAMESPACE diff --git a/src/sql/drivers/psql/qsql_psql.cpp b/src/sql/drivers/psql/qsql_psql.cpp index 16d19f1..ce0b8c5 100644 --- a/src/sql/drivers/psql/qsql_psql.cpp +++ b/src/sql/drivers/psql/qsql_psql.cpp @@ -541,7 +541,7 @@ bool QPSQLResult::prepare(const QString &query) qDeallocatePreparedStmt(d); const QString stmtId = qMakePreparedStmtId(); - const QString stmt = QString(QLatin1String("PREPARE %1 AS ")).arg(stmtId).append(qReplacePlaceholderMarkers(query)); + const QString stmt = QString::fromLatin1("PREPARE %1 AS ").arg(stmtId).append(qReplacePlaceholderMarkers(query)); PGresult *result = PQexec(d->driver->connection, d->driver->isUtf8 ? stmt.toUtf8().constData() @@ -570,9 +570,9 @@ bool QPSQLResult::exec() QString stmt; const QString params = qCreateParamString(boundValues(), d->q->driver()); if (params.isEmpty()) - stmt = QString(QLatin1String("EXECUTE %1")).arg(d->preparedStmtId); + stmt = QString::fromLatin1("EXECUTE %1").arg(d->preparedStmtId); else - stmt = QString(QLatin1String("EXECUTE %1 (%2)")).arg(d->preparedStmtId).arg(params); + stmt = QString::fromLatin1("EXECUTE %1 (%2)").arg(d->preparedStmtId).arg(params); d->result = PQexec(d->driver->connection, d->driver->isUtf8 ? stmt.toUtf8().constData() @@ -1102,12 +1102,12 @@ QString QPSQLDriver::formatValue(const QSqlField &field, bool trimStrings) const QTime tm = field.value().toDateTime().time(); // msecs need to be right aligned otherwise psql // interpretes them wrong - r = QLatin1String("'") + QString::number(dt.year()) + QLatin1String("-") - + QString::number(dt.month()) + QLatin1String("-") - + QString::number(dt.day()) + QLatin1String(" ") - + tm.toString() + QLatin1String(".") + r = QLatin1Char('\'') + QString::number(dt.year()) + QLatin1Char('-') + + QString::number(dt.month()) + QLatin1Char('-') + + QString::number(dt.day()) + QLatin1Char(' ') + + tm.toString() + QLatin1Char('.') + QString::number(tm.msec()).rightJustified(3, QLatin1Char('0')) - + QLatin1String("'"); + + QLatin1Char('\''); } else { r = QLatin1String("NULL"); } @@ -1162,7 +1162,7 @@ QString QPSQLDriver::formatValue(const QSqlField &field, bool trimStrings) const QString QPSQLDriver::escapeIdentifier(const QString &identifier, IdentifierType) const { QString res = identifier; - if(!identifier.isEmpty() && identifier.left(1) != QString(QLatin1Char('"')) && identifier.right(1) != QString(QLatin1Char('"')) ) { + if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) { res.replace(QLatin1Char('"'), QLatin1String("\"\"")); res.prepend(QLatin1Char('"')).append(QLatin1Char('"')); res.replace(QLatin1Char('.'), QLatin1String("\".\"")); @@ -1195,7 +1195,7 @@ bool QPSQLDriver::subscribeToNotificationImplementation(const QString &name) int socket = PQsocket(d->connection); if (socket) { - QString query = QString(QLatin1String("LISTEN %1")).arg(escapeIdentifier(name, QSqlDriver::TableName)); + QString query = QLatin1String("LISTEN ") + escapeIdentifier(name, QSqlDriver::TableName); if (PQresultStatus(PQexec(d->connection, d->isUtf8 ? query.toUtf8().constData() : query.toLocal8Bit().constData()) @@ -1227,7 +1227,7 @@ bool QPSQLDriver::unsubscribeFromNotificationImplementation(const QString &name) return false; } - QString query = QString(QLatin1String("UNLISTEN %1")).arg(escapeIdentifier(name, QSqlDriver::TableName)); + QString query = QLatin1String("UNLISTEN ") + escapeIdentifier(name, QSqlDriver::TableName); if (PQresultStatus(PQexec(d->connection, d->isUtf8 ? query.toUtf8().constData() : query.toLocal8Bit().constData()) diff --git a/src/sql/drivers/sqlite/qsql_sqlite.cpp b/src/sql/drivers/sqlite/qsql_sqlite.cpp index f732077..05d63ca 100644 --- a/src/sql/drivers/sqlite/qsql_sqlite.cpp +++ b/src/sql/drivers/sqlite/qsql_sqlite.cpp @@ -631,9 +631,9 @@ static QSqlIndex qGetTableInfo(QSqlQuery &q, const QString &tableName, bool only { QString schema; QString table(tableName); - int indexOfSeparator = tableName.indexOf(QLatin1String(".")); + int indexOfSeparator = tableName.indexOf(QLatin1Char('.')); if (indexOfSeparator > -1) { - schema = tableName.left(indexOfSeparator).append(QLatin1String(".")); + schema = tableName.left(indexOfSeparator).append(QLatin1Char('.')); table = tableName.mid(indexOfSeparator + 1); } q.exec(QLatin1String("PRAGMA ") + schema + QLatin1String("table_info ('") + table + QLatin1String("')")); diff --git a/src/sql/drivers/sqlite2/qsql_sqlite2.cpp b/src/sql/drivers/sqlite2/qsql_sqlite2.cpp index d0c6e18..cb72ff0 100644 --- a/src/sql/drivers/sqlite2/qsql_sqlite2.cpp +++ b/src/sql/drivers/sqlite2/qsql_sqlite2.cpp @@ -170,8 +170,8 @@ void QSQLite2ResultPrivate::init(const char **cnames, int numCols) //remove quotations around the field name if any QString fieldStr = QString::fromAscii(fieldName); - QString quote = QString::fromLatin1("\""); - if ( fieldStr.length() > 2 && fieldStr.left(1) == quote && fieldStr.right(1) == quote) { + QLatin1Char quote('\"'); + if ( fieldStr.length() > 2 && fieldStr.startsWith(quote) && fieldStr.endsWith(quote)) { fieldStr = fieldStr.mid(1); fieldStr.chop(1); } @@ -561,7 +561,7 @@ QVariant QSQLite2Driver::handle() const QString QSQLite2Driver::escapeIdentifier(const QString &identifier, IdentifierType /*type*/) const { QString res = identifier; - if(!identifier.isEmpty() && identifier.left(1) != QString(QLatin1Char('"')) && identifier.right(1) != QString(QLatin1Char('"')) ) { + if(!identifier.isEmpty() && !identifier.startsWith(QLatin1Char('"')) && !identifier.endsWith(QLatin1Char('"')) ) { res.replace(QLatin1Char('"'), QLatin1String("\"\"")); res.prepend(QLatin1Char('"')).append(QLatin1Char('"')); res.replace(QLatin1Char('.'), QLatin1String("\".\"")); diff --git a/src/sql/drivers/tds/qsql_tds.cpp b/src/sql/drivers/tds/qsql_tds.cpp index 515f0de..298b008 100644 --- a/src/sql/drivers/tds/qsql_tds.cpp +++ b/src/sql/drivers/tds/qsql_tds.cpp @@ -181,7 +181,7 @@ static int CS_PUBLIC qTdsMsgHandler (DBPROCESS* dbproc, } if (severity > 0) { - QString errMsg = QString(QLatin1String("%1 (%2)")).arg(QString::fromAscii(msgtext)).arg( + QString errMsg = QString::fromLatin1("%1 (%2)").arg(QString::fromAscii(msgtext)).arg( msgstate); p->addErrorMsg(errMsg); } @@ -211,8 +211,8 @@ static int CS_PUBLIC qTdsErrHandler(DBPROCESS* dbproc, } - QString errMsg = QString(QLatin1String("%1 %2\n")).arg(QString::fromAscii(dberrstr)).arg( - QString::fromAscii(oserrstr)); + QString errMsg = QString::fromLatin1("%1 %2\n").arg(QLatin1String(dberrstr)).arg( + QLatin1String(oserrstr)); errMsg += p->getErrorMsgs(); p->lastError = qMakeError(errMsg, QSqlError::UnknownError, dberr); p->clearErrorMsgs(); diff --git a/src/sql/kernel/qsqldriver.cpp b/src/sql/kernel/qsqldriver.cpp index 40bc0df..477d531 100644 --- a/src/sql/kernel/qsqldriver.cpp +++ b/src/sql/kernel/qsqldriver.cpp @@ -520,7 +520,7 @@ QString QSqlDriver::sqlStatement(StatementType type, const QString &tableName, continue; s.append(prepareIdentifier(rec.fieldName(i), QSqlDriver::FieldName, this)).append(QLatin1String(", ")); if (preparedStatement) - vals.append(QLatin1String("?")); + vals.append(QLatin1Char('?')); else vals.append(formatValue(rec.field(i))); vals.append(QLatin1String(", ")); @@ -530,7 +530,7 @@ QString QSqlDriver::sqlStatement(StatementType type, const QString &tableName, } else { vals.chop(2); // remove trailing comma s[s.length() - 2] = QLatin1Char(')'); - s.append(QLatin1String("VALUES (")).append(vals).append(QLatin1String(")")); + s.append(QLatin1String("VALUES (")).append(vals).append(QLatin1Char(')')); } break; } } @@ -625,10 +625,7 @@ QString QSqlDriver::formatValue(const QSqlField &field, bool trimStrings) const break; } case QVariant::Bool: - if (field.value().toBool()) - r = QLatin1String("1"); - else - r = QLatin1String("0"); + r = QString::number(field.value().toBool()); break; case QVariant::ByteArray : { if (hasFeature(BLOB)) { @@ -884,12 +881,9 @@ QStringList QSqlDriver::subscribedToNotificationsImplementation() const bool QSqlDriver::isIdentifierEscapedImplementation(const QString &identifier, IdentifierType type) const { Q_UNUSED(type); - bool isLeftDelimited = identifier.left(1) == QString(QLatin1Char('"')); - bool isRightDelimited = identifier.right(1) == QString(QLatin1Char('"')); - if( identifier.size() > 2 && isLeftDelimited && isRightDelimited ) - return true; - else - return false; + return identifier.size() > 2 + && identifier.startsWith(QLatin1Char('"')) //left delimited + && identifier.endsWith(QLatin1Char('"')); //right delimited } /*! diff --git a/src/sql/kernel/qsqlerror.cpp b/src/sql/kernel/qsqlerror.cpp index 14fc050..b1fa6e2 100644 --- a/src/sql/kernel/qsqlerror.cpp +++ b/src/sql/kernel/qsqlerror.cpp @@ -48,7 +48,7 @@ QT_BEGIN_NAMESPACE QDebug operator<<(QDebug dbg, const QSqlError &s) { dbg.nospace() << "QSqlError(" << s.number() << ", " << s.driverText() << - ", " << s.databaseText() << ")"; + ", " << s.databaseText() << ')'; return dbg.space(); } #endif diff --git a/src/sql/kernel/qsqlfield.cpp b/src/sql/kernel/qsqlfield.cpp index 8a808b6..46a5135 100644 --- a/src/sql/kernel/qsqlfield.cpp +++ b/src/sql/kernel/qsqlfield.cpp @@ -514,8 +514,8 @@ QDebug operator<<(QDebug dbg, const QSqlField &f) if (f.typeID() >= 0) dbg.nospace() << ", typeID: " << f.typeID(); if (!f.defaultValue().isNull()) - dbg.nospace() << ", auto-value: \"" << f.defaultValue() << "\""; - dbg.nospace() << ")"; + dbg.nospace() << ", auto-value: \"" << f.defaultValue() << '\"'; + dbg.nospace() << ')'; return dbg.space(); #else qWarning("This compiler doesn't support streaming QSqlField to QDebug"); diff --git a/src/sql/kernel/qsqlrecord.cpp b/src/sql/kernel/qsqlrecord.cpp index 0162664..95f6020 100644 --- a/src/sql/kernel/qsqlrecord.cpp +++ b/src/sql/kernel/qsqlrecord.cpp @@ -589,7 +589,7 @@ void QSqlRecord::detach() #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QSqlRecord &r) { - dbg << "QSqlRecord(" << r.count() << ")"; + dbg << "QSqlRecord(" << r.count() << ')'; for (int i = 0; i < r.count(); ++i) dbg << '\n' << QString::fromLatin1("%1:").arg(i, 2) << r.field(i) << r.value(i).toString(); return dbg; diff --git a/src/sql/models/qsqlrelationaltablemodel.cpp b/src/sql/models/qsqlrelationaltablemodel.cpp index 12eae84..1b8fb4c 100644 --- a/src/sql/models/qsqlrelationaltablemodel.cpp +++ b/src/sql/models/qsqlrelationaltablemodel.cpp @@ -573,7 +573,7 @@ QString QSqlRelationalTableModel::selectStatement() const } // this needs fixing!! the below if is borken. - tables.append(relation.tableName().append(QLatin1String(" ")).append(relTableAlias)); + tables.append(relation.tableName().append(QLatin1Char(' ')).append(relTableAlias)); if(!where.isEmpty()) where.append(QLatin1String(" AND ")); where.append(d->relationField(tableName(), d->db.driver()->escapeIdentifier(rec.fieldName(i), QSqlDriver::FieldName))); diff --git a/src/svg/qsvggenerator.cpp b/src/svg/qsvggenerator.cpp index 2d351ff..d51636f 100644 --- a/src/svg/qsvggenerator.cpp +++ b/src/svg/qsvggenerator.cpp @@ -362,7 +362,7 @@ public: translate_dashPattern(spen.dashPattern(), penWidth, &dashPattern); // SVG uses absolute offset - dashOffset = QString::fromLatin1("%1").arg(spen.dashOffset() * penWidth); + dashOffset = QString::number(spen.dashOffset() * penWidth); d_func()->attributes.stroke = color; d_func()->attributes.strokeOpacity = colorOpacity; @@ -403,8 +403,8 @@ public: } switch (spen.joinStyle()) { case Qt::MiterJoin: - stream() << "stroke-linejoin=\"miter\" "; - stream() << "stroke-miterlimit=\""<attributes.fill = color; d_func()->attributes.fillOpacity = colorOpacity; @@ -493,9 +493,9 @@ public: d->attributes.font_style = d->font.italic() ? QLatin1String("italic") : QLatin1String("normal"); *d->stream << "font-family=\"" << d->attributes.font_family << "\" " - << "font-size=\"" << d->attributes.font_size << "\" " - << "font-weight=\"" << d->attributes.font_weight << "\" " - << "font-style=\"" << d->attributes.font_style << "\" " + "font-size=\"" << d->attributes.font_size << "\" " + "font-weight=\"" << d->attributes.font_weight << "\" " + "font-style=\"" << d->attributes.font_style << "\" " << endl; } }; @@ -849,13 +849,13 @@ bool QSvgPaintEngine::begin(QPaintDevice *) } if (d->viewBox.isValid()) { - *d->stream << " viewBox=\"" << d->viewBox.left() << " " << d->viewBox.top(); - *d->stream << " " << d->viewBox.width() << " " << d->viewBox.height() << "\"" << endl; + *d->stream << " viewBox=\"" << d->viewBox.left() << ' ' << d->viewBox.top(); + *d->stream << ' ' << d->viewBox.width() << ' ' << d->viewBox.height() << '\"' << endl; } *d->stream << " xmlns=\"http://www.w3.org/2000/svg\"" - << " xmlns:xlink=\"http://www.w3.org/1999/xlink\" " - << " version=\"1.2\" baseProfile=\"tiny\">" << endl; + " xmlns:xlink=\"http://www.w3.org/1999/xlink\" " + " version=\"1.2\" baseProfile=\"tiny\">" << endl; if (!d->attributes.document_title.isEmpty()) { *d->stream << "" << d->attributes.document_title << "" << endl; @@ -918,10 +918,10 @@ void QSvgPaintEngine::drawImage(const QRectF &r, const QImage &image, Q_UNUSED(sr); Q_UNUSED(flags); stream() << "\n"; + <<"\" />\n"; } void QSvgPaintEngine::updateState(const QPaintEngineState &state) @@ -958,10 +957,10 @@ void QSvgPaintEngine::updateState(const QPaintEngineState &state) if (flags & QPaintEngine::DirtyTransform) { d->matrix = state.matrix(); - *d->stream << "transform=\"matrix(" << d->matrix.m11() << "," - << d->matrix.m12() << "," - << d->matrix.m21() << "," << d->matrix.m22() << "," - << d->matrix.dx() << "," << d->matrix.dy() + *d->stream << "transform=\"matrix(" << d->matrix.m11() << ',' + << d->matrix.m12() << ',' + << d->matrix.m21() << ',' << d->matrix.m22() << ',' + << d->matrix.dx() << ',' << d->matrix.dy() << ")\"" << endl; } @@ -975,7 +974,7 @@ void QSvgPaintEngine::updateState(const QPaintEngineState &state) stream() << "opacity=\""<stream << ">" << endl; + *d->stream << '>' << endl; d->afterFirstUpdate = true; } @@ -984,10 +983,8 @@ void QSvgPaintEngine::drawPath(const QPainterPath &p) { Q_D(QSvgPaintEngine); - *d->stream << "stream << "fill-rule="; + *d->stream << "stream << "M" << e.x << "," << e.y; + *d->stream << 'M' << e.x << ',' << e.y; break; case QPainterPath::LineToElement: - *d->stream << "L" << e.x << "," << e.y; + *d->stream << 'L' << e.x << ',' << e.y; break; case QPainterPath::CurveToElement: - *d->stream << "C" << e.x << "," << e.y; + *d->stream << 'C' << e.x << ',' << e.y; ++i; while (i < p.elementCount()) { const QPainterPath::Element &e = p.elementAt(i); @@ -1013,8 +1010,8 @@ void QSvgPaintEngine::drawPath(const QPainterPath &p) --i; break; } else - *d->stream << " "; - *d->stream << e.x << "," << e.y; + *d->stream << ' '; + *d->stream << e.x << ',' << e.y; ++i; } break; @@ -1022,7 +1019,7 @@ void QSvgPaintEngine::drawPath(const QPainterPath &p) break; } if (i != p.elementCount() - 1) { - *d->stream << " "; + *d->stream << ' '; } } @@ -1044,7 +1041,7 @@ void QSvgPaintEngine::drawPolygon(const QPointF *points, int pointCount, stream() << "" <stream << "attributes.stroke << "\" " - << "fill-opacity=\"" << d->attributes.strokeOpacity << "\" " - << "stroke=\"none\" " - << "x=\"" << pt.x() << "\" y=\"" << pt.y() << "\" "; + "fill=\"" << d->attributes.stroke << "\" " + "fill-opacity=\"" << d->attributes.strokeOpacity << "\" " + "stroke=\"none\" " + "x=\"" << pt.x() << "\" y=\"" << pt.y() << "\" "; qfontToSvg(textItem.font()); *d->stream << " >" << Qt::escape(s) diff --git a/src/testlib/qbenchmark_p.h b/src/testlib/qbenchmark_p.h index 8bb6e84..b6340f8 100644 --- a/src/testlib/qbenchmark_p.h +++ b/src/testlib/qbenchmark_p.h @@ -81,7 +81,7 @@ struct QBenchmarkContext QString toString() const { - QString s = QString(QLatin1String("%1,%2,%3")).arg(slotName).arg(tag).arg(checkpointIndex); + QString s = QString::fromLatin1("%1,%2,%3").arg(slotName).arg(tag).arg(checkpointIndex); return s; } diff --git a/src/testlib/qbenchmarkvalgrind.cpp b/src/testlib/qbenchmarkvalgrind.cpp index bcce147..c61460d 100644 --- a/src/testlib/qbenchmarkvalgrind.cpp +++ b/src/testlib/qbenchmarkvalgrind.cpp @@ -133,12 +133,12 @@ QString QBenchmarkValgrindUtils::getNewestFileName() QString base = QBenchmarkGlobalData::current->callgrindOutFileBase; Q_ASSERT(!base.isEmpty()); - nameFilters << QString(QLatin1String("%1.*")).arg(base); + nameFilters << QString::fromLatin1("%1.*").arg(base); QFileInfoList fiList = QDir().entryInfoList(nameFilters, QDir::Files | QDir::Readable); Q_ASSERT(!fiList.empty()); int hiSuffix = -1; QFileInfo lastFileInfo; - const QString pattern = QString(QLatin1String("%1.(\\d+)")).arg(base); + const QString pattern = QString::fromLatin1("%1.(\\d+)").arg(base); const QRegExp rx(pattern); foreach (QFileInfo fileInfo, fiList) { const int index = rx.indexIn(fileInfo.fileName()); @@ -168,8 +168,8 @@ void QBenchmarkValgrindUtils::cleanup() QString base = QBenchmarkGlobalData::current->callgrindOutFileBase; Q_ASSERT(!base.isEmpty()); nameFilters - << QString(QLatin1String("%1")).arg(base) // overall summary - << QString(QLatin1String("%1.*")).arg(base); // individual dumps + << base // overall summary + << QString::fromLatin1("%1.*").arg(base); // individual dumps QFileInfoList fiList = QDir().entryInfoList(nameFilters, QDir::Files | QDir::Readable); foreach (QFileInfo fileInfo, fiList) { const bool removeOk = QFile::remove(fileInfo.fileName()); @@ -180,7 +180,7 @@ void QBenchmarkValgrindUtils::cleanup() QString QBenchmarkValgrindUtils::outFileBase(qint64 pid) { - return QString(QLatin1String("callgrind.out.%1")).arg( + return QString::fromLatin1("callgrind.out.%1").arg( pid != -1 ? pid : QCoreApplication::applicationPid()); } diff --git a/src/testlib/qplaintestlogger.cpp b/src/testlib/qplaintestlogger.cpp index 6f10d72..8ffdca2 100644 --- a/src/testlib/qplaintestlogger.cpp +++ b/src/testlib/qplaintestlogger.cpp @@ -216,9 +216,9 @@ namespace QTest { template QString formatResult(T number, int significantDigits) { if (number < T(0)) - return QString(QLatin1String("NAN")); + return QLatin1String("NAN"); if (number == T(0)) - return QString(QLatin1String("0")); + return QLatin1String("0"); QString beforeDecimalPoint = QString::number(qint64(number), 'f', 0); QString afterDecimalPoint = QString::number(number, 'f', 20); diff --git a/src/testlib/qsignaldumper.cpp b/src/testlib/qsignaldumper.cpp index 0a32a6d..3a9d75e 100644 --- a/src/testlib/qsignaldumper.cpp +++ b/src/testlib/qsignaldumper.cpp @@ -87,7 +87,7 @@ static void qSignalDumperCallback(QObject *caller, int method_index, void **argv str.fill(' ', QTest::iLevel++ * QTest::IndentSpacesCount); str += "Signal: "; str += mo->className(); - str += "("; + str += '('; QString objname = caller->objectName(); str += objname.toLocal8Bit(); @@ -114,15 +114,15 @@ static void qSignalDumperCallback(QObject *caller, int method_index, void **argv str.append(QByteArray::number(addr, 16)); } else if (typeId != QMetaType::Void) { str.append(arg) - .append("(") + .append('(') .append(QVariant(typeId, argv[i + 1]).toString().toLocal8Bit()) - .append(")"); + .append(')'); } str.append(", "); } if (str.endsWith(", ")) str.chop(2); - str.append(")"); + str.append(')'); qPrintMessage(str); } @@ -143,7 +143,7 @@ static void qSignalDumperCallbackSlot(QObject *caller, int method_index, void ** str.fill(' ', QTest::iLevel * QTest::IndentSpacesCount); str += "Slot: "; str += mo->className(); - str += "("; + str += '('; QString objname = caller->objectName(); str += objname.toLocal8Bit(); diff --git a/src/tools/idc/main.cpp b/src/tools/idc/main.cpp index eb04114..8d2f0cc 100644 --- a/src/tools/idc/main.cpp +++ b/src/tools/idc/main.cpp @@ -50,8 +50,8 @@ QT_BEGIN_NAMESPACE static QString quotePath(const QString &s) { - if (!s.startsWith(QLatin1String("\"")) && s.contains(QLatin1Char(' '))) - return QLatin1String("\"") + s + QLatin1String("\""); + if (!s.startsWith(QLatin1Char('\"')) && s.contains(QLatin1Char(' '))) + return QLatin1Char('\"') + s + QLatin1Char('\"'); return s; } @@ -282,7 +282,7 @@ int runIdc(int argc, char **argv) fprintf(stderr, "Server unregistered successfully!\n"); return 0; } else if (p[0] == QLatin1Char('/') || p[0] == QLatin1Char('-')) { - error = QLatin1String("Unknown option \"") + p + QLatin1String("\""); + error = QLatin1String("Unknown option \"") + p + QLatin1Char('\"'); break; } else { input = QLatin1String(argv[i]); diff --git a/src/tools/moc/generator.cpp b/src/tools/moc/generator.cpp index ae8a76e..e94bb77 100644 --- a/src/tools/moc/generator.cpp +++ b/src/tools/moc/generator.cpp @@ -1161,8 +1161,8 @@ void Generator::_generateFunctions(QList &list, int type) for (int j = 0; j < f.arguments.count(); ++j) { const ArgumentDef &a = f.arguments.at(j); if (j) { - sig += ","; - arguments += ","; + sig += ','; + arguments += ','; } sig += a.normalizedType; arguments += a.name; diff --git a/src/tools/moc/moc.cpp b/src/tools/moc/moc.cpp index a6a0ba1..8ca2823 100644 --- a/src/tools/moc/moc.cpp +++ b/src/tools/moc/moc.cpp @@ -752,14 +752,14 @@ void Moc::generate(FILE *out) if (!noInclude) { - if (includePath.size() && includePath.right(1) != "/") - includePath += "/"; + if (includePath.size() && !includePath.endsWith('/')) + includePath += '/'; for (int i = 0; i < includeFiles.size(); ++i) { QByteArray inc = includeFiles.at(i); if (inc[0] != '<' && inc[0] != '"') { if (includePath.size() && includePath != "./") inc.prepend(includePath); - inc = "\"" + inc + "\""; + inc = '\"' + inc + '\"'; } fprintf(out, "#include %s\n", inc.constData()); } diff --git a/src/tools/moc/preprocessor.cpp b/src/tools/moc/preprocessor.cpp index 45cbbfd..3260ca2 100644 --- a/src/tools/moc/preprocessor.cpp +++ b/src/tools/moc/preprocessor.cpp @@ -807,7 +807,7 @@ void Preprocessor::preprocess(const QByteArray &filename, Symbols &preprocessed) continue; QByteArray frameworkCandidate = include.left(slashPos); frameworkCandidate.append(".framework/Headers/"); - fi.setFile(QString::fromLocal8Bit(p.path + "/" + frameworkCandidate), QString::fromLocal8Bit(include.mid(slashPos + 1))); + fi.setFile(QString::fromLocal8Bit(p.path + '/' + frameworkCandidate), QString::fromLocal8Bit(include.mid(slashPos + 1))); } else { fi.setFile(QString::fromLocal8Bit(p.path), QString::fromLocal8Bit(include)); } diff --git a/src/tools/uic/cpp/cppwriteicondata.cpp b/src/tools/uic/cpp/cppwriteicondata.cpp index 53b108f..08d552d 100644 --- a/src/tools/uic/cpp/cppwriteicondata.cpp +++ b/src/tools/uic/cpp/cppwriteicondata.cpp @@ -161,9 +161,9 @@ void WriteIconData::writeImage(QTextStream &output, const QString &indent, DomIm for (a = 0; a < (int) (data.length()/2)-1; a++) { output << "0x" << QString(data[2*a]) << QString(data[2*a+1]) << ','; if (a % 12 == 11) - output << "\n" << indent; + output << '\n' << indent; else - output << " "; + output << ' '; } output << "0x" << QString(data[2*a]) << QString(data[2*a+1]) << '\n'; output << "};\n\n"; diff --git a/src/tools/uic/cpp/cppwriteinitialization.cpp b/src/tools/uic/cpp/cppwriteinitialization.cpp index 47566ad..5a2f487 100644 --- a/src/tools/uic/cpp/cppwriteinitialization.cpp +++ b/src/tools/uic/cpp/cppwriteinitialization.cpp @@ -2813,7 +2813,7 @@ QString WriteInitialization::Item::writeSetupUi(const QString &parent, Item::Emp bool generateMultiDirective = false; if (emptyItemPolicy == Item::ConstructItemOnly && m_children.size() == 0) { if (m_setupUiData.policy == ItemData::DontGenerate) { - m_setupUiStream << m_indent << "new " << m_itemClassName << "(" << parent << ");\n"; + m_setupUiStream << m_indent << "new " << m_itemClassName << '(' << parent << ");\n"; return QString(); } else if (m_setupUiData.policy == ItemData::GenerateWithMultiDirective) { generateMultiDirective = true; @@ -2824,11 +2824,11 @@ QString WriteInitialization::Item::writeSetupUi(const QString &parent, Item::Emp generateMultiDirectiveBegin(m_setupUiStream, m_setupUiData.directives); const QString uniqueName = m_driver->unique(QLatin1String("__") + m_itemClassName.toLower()); - m_setupUiStream << m_indent << m_itemClassName << " *" << uniqueName << " = new " << m_itemClassName << "(" << parent << ");\n"; + m_setupUiStream << m_indent << m_itemClassName << " *" << uniqueName << " = new " << m_itemClassName << '(' << parent << ");\n"; if (generateMultiDirective) { m_setupUiStream << "#else\n"; - m_setupUiStream << m_indent << "new " << m_itemClassName << "(" << parent << ");\n"; + m_setupUiStream << m_indent << "new " << m_itemClassName << '(' << parent << ");\n"; generateMultiDirectiveEnd(m_setupUiStream, m_setupUiData.directives); } diff --git a/src/tools/uic3/embed.cpp b/src/tools/uic3/embed.cpp index 882328a..b406c1f 100644 --- a/src/tools/uic3/embed.cpp +++ b/src/tools/uic3/embed.cpp @@ -238,7 +238,7 @@ void Ui3Reader::embed(const char *project, const QStringList &images) out << "true, "; else out << "false, "; - out << "\"" << e->name << "\" },\n"; + out << '\"' << e->name << "\" },\n"; delete e; } #ifndef QT_NO_IMAGE_COLLECTION_COMPRESSION diff --git a/src/tools/uic3/form.cpp b/src/tools/uic3/form.cpp index d9e968b..b484210 100644 --- a/src/tools/uic3/form.cpp +++ b/src/tools/uic3/form.cpp @@ -185,14 +185,14 @@ void Ui3Reader::createFormDecl(const QDomElement &e, bool implicitIncludes) for (it = globalIncludes.constBegin(); it != globalIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); - out << "#include <" << header << ">" << endl; + out << "#include <" << header << '>' << endl; } } localIncludes = unique(localIncludes); for (it = localIncludes.constBegin(); it != localIncludes.constEnd(); ++it) { if (!(*it).isEmpty()) { QString header = fixHeaderName(*it); - out << "#include \"" << header << "\"" << endl; + out << "#include \"" << header << '\"' << endl; } } out << endl; @@ -216,7 +216,7 @@ void Ui3Reader::createFormDecl(const QDomElement &e, bool implicitIncludes) typeDefs = unique(typeDefs); for (it = typeDefs.constBegin(); it != typeDefs.constEnd(); ++it) { if (!(*it).isEmpty()) - out << "typedef " << *it << ";" << endl; + out << "typedef " << *it << ';' << endl; } nl = e.parentNode().toElement().elementsByTagName(QLatin1String("forward")); @@ -236,17 +236,17 @@ void Ui3Reader::createFormDecl(const QDomElement &e, bool implicitIncludes) out << "namespace " << *ns << " {" << endl; ++ns; } - out << "class " << forwardName << ";" << endl; + out << "class " << forwardName << ';' << endl; for (int i = 0; i < (int) forwardNamespaces.count(); i++) - out << "}" << endl; + out << '}' << endl; } } for (it = forwardDecl2.constBegin(); it != forwardDecl2.constEnd(); ++it) { QString fd = *it; fd = fd.trimmed(); - if (!fd.endsWith(QLatin1String(";"))) - fd += QLatin1String(";"); + if (!fd.endsWith(QLatin1Char(';'))) + fd += QLatin1Char(';'); out << fd << endl; } @@ -279,7 +279,7 @@ void Ui3Reader::createWrapperDecl(const QDomElement &e, const QString &converted out << "#ifndef " << protector << endl; out << "#define " << protector << endl; out << endl; - out << "#include \"" << convertedUiFile << "\"" << endl; + out << "#include \"" << convertedUiFile << '\"' << endl; createWrapperDeclContents(e); out << endl; @@ -309,8 +309,8 @@ void Ui3Reader::createWrapperDeclContents(const QDomElement &e) out << "class "; if (!exportMacro.isEmpty()) - out << exportMacro << " "; - out << bareNameOfClass << " : public " << objClass << ", public Ui::" << bareNameOfClass << endl << "{" << endl; + out << exportMacro << ' '; + out << bareNameOfClass << " : public " << objClass << ", public Ui::" << bareNameOfClass << endl << '{' << endl; /* qmake ignore Q_OBJECT */ out << " Q_OBJECT" << endl; @@ -362,8 +362,8 @@ void Ui3Reader::createWrapperDeclContents(const QDomElement &e) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); - if (functionName.endsWith(QLatin1String(";"))) - functionName = functionName.left(functionName.length() - 1); + if (functionName.endsWith(QLatin1Char(';'))) + functionName.chop(1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if (access == QLatin1String(QLatin1String("protected"))) { @@ -394,8 +394,8 @@ void Ui3Reader::createWrapperDeclContents(const QDomElement &e) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); - if (functionName.endsWith(QLatin1String(";"))) - functionName = functionName.left(functionName.length() - 1); + if (functionName.endsWith(QLatin1Char(';'))) + functionName.chop(1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if (access == QLatin1String("protected")) { @@ -423,8 +423,8 @@ void Ui3Reader::createWrapperDeclContents(const QDomElement &e) // continue; QString access = n.attribute(QLatin1String("access"), QLatin1String("protected")); QString var = fixDeclaration(n.firstChild().toText().data().trimmed()); - if (!var.endsWith(QLatin1String(";"))) - var += QLatin1String(";"); + if (!var.endsWith(QLatin1Char(';'))) + var += QLatin1Char(';'); if (access == QLatin1String("public")) publicVars += var; else if (access == QLatin1String("private")) @@ -458,7 +458,7 @@ void Ui3Reader::createWrapperDeclContents(const QDomElement &e) if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString sigName = n.firstChild().toText().data().trimmed(); - if (sigName.endsWith(QLatin1String(";"))) + if (sigName.endsWith(QLatin1Char(';'))) sigName = sigName.left(sigName.length() - 1); extraSignals += fixDeclaration(sigName); } @@ -467,7 +467,7 @@ void Ui3Reader::createWrapperDeclContents(const QDomElement &e) if (!extraSignals.isEmpty()) { out << "signals:" << endl; for (it = extraSignals.constBegin(); it != extraSignals.constEnd(); ++it) - out << " void " << (*it) << ";" << endl; + out << " void " << (*it) << ';' << endl; out << endl; } @@ -513,7 +513,7 @@ void Ui3Reader::createWrapperDeclContents(const QDomElement &e) out << "};" << endl; for (i = 0; i < (int) namespaces.count(); i++) - out << "}" << endl; + out << '}' << endl; out << endl; } @@ -543,7 +543,7 @@ void Ui3Reader::writeFunctionsDecl(const QStringList &fuLst, const QStringList & signature = fixDeclaration(signature); type = fixType(type); - out << " " << specifier << type << " " << signature << pure << ";" << endl; + out << " " << specifier << type << ' ' << signature << pure << ';' << endl; } out << endl; } @@ -583,8 +583,8 @@ void Ui3Reader::createFormImpl(const QDomElement &e) if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString functionName = n.firstChild().toText().data().trimmed(); - if (functionName.endsWith(QLatin1String(";"))) - functionName = functionName.left(functionName.length() - 1); + if (functionName.endsWith(QLatin1Char(';'))) + functionName.chop(1); extraFuncts += functionName; extraFunctTyp += n.attribute(QLatin1String("returnType"), QLatin1String("void")); extraFunctSpecifier += n.attribute(QLatin1String("specifier"), QLatin1String("virtual")); @@ -598,8 +598,8 @@ void Ui3Reader::createFormImpl(const QDomElement &e) if (n.attribute(QLatin1String("language"), QLatin1String("C++")) != QLatin1String("C++")) continue; QString functionName = n.firstChild().toText().data().trimmed(); - if (functionName.endsWith(QLatin1String(";"))) - functionName = functionName.left(functionName.length() - 1); + if (functionName.endsWith(QLatin1Char(';'))) + functionName.chop(1); extraFuncts += functionName; extraFunctTyp += n.attribute(QLatin1String("returnType"), QLatin1String("void")); extraFunctSpecifier += n.attribute(QLatin1String("specifier"), QLatin1String("virtual")); @@ -663,7 +663,7 @@ void Ui3Reader::createFormImpl(const QDomElement &e) globalIncludes = unique(globalIncludes); for (it = globalIncludes.begin(); it != globalIncludes.end(); ++it) { if (!(*it).isEmpty()) - out << "#include <" << fixHeaderName(*it) << ">" << endl; + out << "#include <" << fixHeaderName(*it) << '>' << endl; } if (externPixmaps) { @@ -677,14 +677,14 @@ void Ui3Reader::createFormImpl(const QDomElement &e) localIncludes = unique(localIncludes); for (it = localIncludes.begin(); it != localIncludes.end(); ++it) { if (!(*it).isEmpty() && *it != QFileInfo(fileName + QLatin1String(".h")).fileName()) - out << "#include \"" << fixHeaderName(*it) << "\"" << endl; + out << "#include \"" << fixHeaderName(*it) << '\"' << endl; } QString uiDotH = fileName + QLatin1String(".h"); if (QFile::exists(uiDotH)) { if (!outputFileName.isEmpty()) uiDotH = QString::fromUtf8(combinePath(uiDotH.ascii(), outputFileName.ascii())); - out << "#include \"" << uiDotH << "\"" << endl; + out << "#include \"" << uiDotH << '\"' << endl; writeFunctImpl = false; } @@ -702,7 +702,7 @@ void Ui3Reader::createFormImpl(const QDomElement &e) out << " * name 'name' and widget flags set to 'f'." << endl; out << " *" << endl; out << " * The " << objClass.mid(1).toLower() << " will by default be modeless, unless you set 'modal' to" << endl; - out << " * true to construct a modal " << objClass.mid(1).toLower() << "." << endl; + out << " * true to construct a modal " << objClass.mid(1).toLower() << '.' << endl; out << " */" << endl; out << nameOfClass << "::" << bareNameOfClass << "(QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl)" << endl; out << " : " << objClass << "(parent, name, modal, fl)"; @@ -733,7 +733,7 @@ void Ui3Reader::createFormImpl(const QDomElement &e) out << endl; - out << "{" << endl; + out << '{' << endl; // // setup the gui @@ -775,7 +775,7 @@ void Ui3Reader::createFormImpl(const QDomElement &e) out << indent << "init();" << endl; // end of constructor - out << "}" << endl; + out << '}' << endl; out << endl; // destructor @@ -783,11 +783,11 @@ void Ui3Reader::createFormImpl(const QDomElement &e) out << " * Destroys the object and frees any allocated resources" << endl; out << " */" << endl; out << nameOfClass << "::~" << bareNameOfClass << "()" << endl; - out << "{" << endl; + out << '{' << endl; if (extraFuncts.contains(QLatin1String("destroy()"))) out << indent << "destroy();" << endl; out << indent << "// no need to delete child widgets, Qt does it all for us" << endl; - out << "}" << endl; + out << '}' << endl; out << endl; // handle application events if required @@ -816,9 +816,9 @@ void Ui3Reader::createFormImpl(const QDomElement &e) out << " * language." << endl; out << " */" << endl; out << "void " << nameOfClass << "::languageChange()" << endl; - out << "{" << endl; + out << '{' << endl; out << " retranslateUi(this);" << endl; - out << "}" << endl; + out << '}' << endl; out << endl; // create stubs for additional slots if necessary @@ -833,8 +833,8 @@ void Ui3Reader::createFormImpl(const QDomElement &e) type = type.simplified(); QString fname = fixDeclaration(Parser::cleanArgs(*it)); if (!(*it3).startsWith(QLatin1String("pure"))) { // "pure virtual" or "pureVirtual" - out << type << " " << nameOfClass << "::" << fname << endl; - out << "{" << endl; + out << type << ' ' << nameOfClass << "::" << fname << endl; + out << '{' << endl; if (*it != QLatin1String("init()") && *it != QLatin1String("destroy()")) { QRegExp numeric(QLatin1String("^(?:signed|unsigned|u?char|u?short|u?int" "|u?long|Q_U?INT(?:8|16|32)|Q_U?LONG|float" @@ -868,14 +868,14 @@ void Ui3Reader::createFormImpl(const QDomElement &e) if (type == QLatin1String("bool")) { retVal = QLatin1String("false"); - } else if (isBasicNumericType || type.endsWith(QLatin1String("*"))) { + } else if (isBasicNumericType || type.endsWith(QLatin1Char('*'))) { retVal = QLatin1String("0"); - } else if (type.endsWith(QLatin1String("&"))) { + } else if (type.endsWith(QLatin1Char('&'))) { do { type.chop(1); - } while (type.endsWith(QLatin1String(" "))); + } while (type.endsWith(QLatin1Char(' '))); retVal = QLatin1String("uic_temp_var"); - out << indent << "static " << type << " " << retVal << ";" << endl; + out << indent << "static " << type << ' ' << retVal << ';' << endl; } else { retVal = type + QLatin1String("()"); } @@ -883,9 +883,9 @@ void Ui3Reader::createFormImpl(const QDomElement &e) out << indent << "qWarning(\"" << nameOfClass << "::" << fname << ": Not implemented yet\");" << endl; if (!retVal.isEmpty()) - out << indent << "return " << retVal << ";" << endl; + out << indent << "return " << retVal << ';' << endl; } - out << "}" << endl; + out << '}' << endl; out << endl; } ++it; diff --git a/src/tools/uic3/main.cpp b/src/tools/uic3/main.cpp index d581016..9535b91 100644 --- a/src/tools/uic3/main.cpp +++ b/src/tools/uic3/main.cpp @@ -367,7 +367,7 @@ int runUic3(int argc, char * argv[]) } if (headerFile) { - out << "#include \"" << headerFile << "\"" << endl << endl; + out << "#include \"" << headerFile << '\"' << endl << endl; } QString convertedUi; diff --git a/src/tools/uic3/parser.cpp b/src/tools/uic3/parser.cpp index 744dd30..395cc4d 100644 --- a/src/tools/uic3/parser.cpp +++ b/src/tools/uic3/parser.cpp @@ -48,14 +48,14 @@ QT_BEGIN_NAMESPACE QString Parser::cleanArgs(const QString &func) { QString slot(func); - int begin = slot.indexOf(QLatin1String("(")) + 1; + int begin = slot.indexOf(QLatin1Char('(')) + 1; QString args = slot.mid(begin); - args = args.left(args.indexOf(QLatin1String(")"))); + args = args.left(args.indexOf(QLatin1Char(')'))); QStringList lst = args.split(QLatin1Char(',')); QString res = slot.left(begin); for (QStringList::Iterator it = lst.begin(); it != lst.end(); ++it) { if (it != lst.begin()) - res += QLatin1String(","); + res += QLatin1Char(','); QString arg = *it; int pos = 0; if ((pos = arg.indexOf(QLatin1Char('&'))) != -1) { @@ -65,7 +65,7 @@ QString Parser::cleanArgs(const QString &func) } else { arg = arg.simplified(); if ((pos = arg.indexOf(QLatin1Char(':'))) != -1) - arg = arg.left(pos).simplified() + QLatin1String(":") + arg.mid(pos + 1).simplified(); + arg = arg.left(pos).simplified() + QLatin1Char(':') + arg.mid(pos + 1).simplified(); QStringList l = arg.split(QLatin1Char(' ')); if (l.count() == 2) { if (l[0] != QLatin1String("const") @@ -73,12 +73,12 @@ QString Parser::cleanArgs(const QString &func) && l[0] != QLatin1String("var")) arg = l[0]; } else if (l.count() == 3) { - arg = l[0] + QLatin1String(" ") + l[1]; + arg = l[0] + QLatin1Char(' ') + l[1]; } } res += arg; } - res += QLatin1String(")"); + res += QLatin1Char(')'); return res; } diff --git a/src/tools/uic3/qt3to4.cpp b/src/tools/uic3/qt3to4.cpp index 9e5b64b..2862727 100644 --- a/src/tools/uic3/qt3to4.cpp +++ b/src/tools/uic3/qt3to4.cpp @@ -149,7 +149,7 @@ void Porting::readXML(RuleList *renamedHeaders, RuleList *renamedClasses, RuleLi QString fileName = QLatin1String("q3porting.xml"); QString filePath; //check QLibraryInfo::DataPath/filename - filePath = QDir::cleanPath(QLibraryInfo::location(QLibraryInfo::DataPath) + QLatin1String("/") + fileName) ; + filePath = QDir::cleanPath(QLibraryInfo::location(QLibraryInfo::DataPath) + QLatin1Char('/') + fileName) ; //check QLibraryInfo::PrefixPath/tools/porting/src/filename if (!QFile::exists(filePath)) diff --git a/src/tools/uic3/subclassing.cpp b/src/tools/uic3/subclassing.cpp index e590ab7..85c2218 100644 --- a/src/tools/uic3/subclassing.cpp +++ b/src/tools/uic3/subclassing.cpp @@ -69,7 +69,7 @@ void Ui3Reader::createSubDecl( const QDomElement &e, const QString& subClass ) return; out << "class " << subClass << " : public " << nameOfClass << endl; - out << "{" << endl; + out << '{' << endl; /* tmake ignore Q_OBJECT */ out << " Q_OBJECT" << endl; @@ -105,8 +105,8 @@ void Ui3Reader::createSubDecl( const QDomElement &e, const QString& subClass ) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); - if ( functionName.endsWith(QLatin1String(";"))) - functionName = functionName.left( functionName.length() - 1 ); + if ( functionName.endsWith(QLatin1Char(';'))) + functionName.chop(1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if ( access == QLatin1String("protected") ) { @@ -133,8 +133,8 @@ void Ui3Reader::createSubDecl( const QDomElement &e, const QString& subClass ) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); - if ( functionName.endsWith(QLatin1String(";")) ) - functionName = functionName.left( functionName.length() - 1 ); + if ( functionName.endsWith(QLatin1Char(';')) ) + functionName.chop(1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if ( access == QLatin1String("protected") ) { @@ -195,7 +195,7 @@ void Ui3Reader::writeFunctionsSubDecl( const QStringList &fuLst, const QStringLi type = QLatin1String("void"); if ( *it3 == QLatin1String("non virtual") ) continue; - out << " " << type << " " << fixDeclaration(*it) << ";" << endl; + out << " " << type << ' ' << fixDeclaration(*it) << ';' << endl; } out << endl; } @@ -223,7 +223,7 @@ void Ui3Reader::createSubImpl( const QDomElement &e, const QString& subClass ) out << " * name 'name' and widget flags set to 'f' " << endl; out << " *" << endl; out << " * The " << objClass.mid(1).toLower() << " will by default be modeless, unless you set 'modal' to" << endl; - out << " * true to construct a modal " << objClass.mid(1).toLower() << "." << endl; + out << " * true to construct a modal " << objClass.mid(1).toLower() << '.' << endl; out << " */" << endl; out << subClass << "::" << subClass << "( QWidget* parent, const char* name, bool modal, Qt::WindowFlags fl )" << endl; out << " : " << nameOfClass << "( parent, name, modal, fl )" << endl; @@ -235,8 +235,8 @@ void Ui3Reader::createSubImpl( const QDomElement &e, const QString& subClass ) out << subClass << "::" << subClass << "( QWidget* parent, const char* name, Qt::WindowFlags fl )" << endl; out << " : " << nameOfClass << "( parent, name, fl )" << endl; } - out << "{" << endl; - out << "}" << endl; + out << '{' << endl; + out << '}' << endl; out << endl; // destructor @@ -244,9 +244,9 @@ void Ui3Reader::createSubImpl( const QDomElement &e, const QString& subClass ) out << " * Destroys the object and frees any allocated resources" << endl; out << " */" << endl; out << subClass << "::~" << subClass << "()" << endl; - out << "{" << endl; + out << '{' << endl; out << " // no need to delete child widgets, Qt does it all for us" << endl; - out << "}" << endl; + out << '}' << endl; out << endl; @@ -268,8 +268,8 @@ void Ui3Reader::createSubImpl( const QDomElement &e, const QString& subClass ) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); - if ( functionName.endsWith(QLatin1String(";")) ) - functionName = functionName.left( functionName.length() - 1 ); + if ( functionName.endsWith(QLatin1Char(';')) ) + functionName.chop(1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if ( access == QLatin1String("protected") ) { @@ -296,8 +296,8 @@ void Ui3Reader::createSubImpl( const QDomElement &e, const QString& subClass ) continue; QString returnType = n.attribute(QLatin1String("returnType"), QLatin1String("void")); QString functionName = n.firstChild().toText().data().trimmed(); - if ( functionName.endsWith(QLatin1String(";")) ) - functionName = functionName.left( functionName.length() - 1 ); + if ( functionName.endsWith(QLatin1Char(';')) ) + functionName.chop(1); QString specifier = n.attribute(QLatin1String("specifier")); QString access = n.attribute(QLatin1String("access")); if ( access == QLatin1String("protected") ) { @@ -351,10 +351,10 @@ void Ui3Reader::writeFunctionsSubImpl( const QStringList &fuLst, const QStringLi out << "/*" << endl; out << " * " << descr << endl; out << " */" << endl; - out << type << " " << subClass << "::" << fixDeclaration(*it) << endl; - out << "{" << endl; + out << type << ' ' << subClass << "::" << fixDeclaration(*it) << endl; + out << '{' << endl; out << " qWarning( \"" << subClass << "::" << fixDeclaration(*it) << " not yet implemented!\" );" << endl; - out << "}" << endl << endl; + out << '}' << endl << endl; } out << endl; } diff --git a/src/tools/uic3/ui3reader.cpp b/src/tools/uic3/ui3reader.cpp index 1ba4b2f..539565c 100644 --- a/src/tools/uic3/ui3reader.cpp +++ b/src/tools/uic3/ui3reader.cpp @@ -125,10 +125,10 @@ QString Ui3Reader::fixString(const QString &str, bool encode) QString s; if (!encode) { s = str; - s.replace(QLatin1String("\\"), QLatin1String("\\\\")); - s.replace(QLatin1String("\""), QLatin1String("\\\"")); - s.replace(QLatin1String("\r"), QLatin1String("")); - s.replace(QLatin1String("\n"), QLatin1String("\\n\"\n\"")); + s.replace(QLatin1Char('\\'), QLatin1String("\\\\")); + s.replace(QLatin1Char('\"'), QLatin1String("\\\"")); + s.remove(QLatin1Char('\r')); + s.replace(QLatin1Char('\n'), QLatin1String("\\n\"\n\"")); } else { QByteArray utf8 = str.utf8(); const int l = utf8.length(); @@ -136,7 +136,7 @@ QString Ui3Reader::fixString(const QString &str, bool encode) s += QLatin1String("\\x") + QString::number((uchar)utf8[i], 16); } - return QLatin1String("\"") + s + QLatin1String("\""); + return QLatin1Char('\"') + s + QLatin1Char('\"'); } QString Ui3Reader::trcall(const QString& sourceText, const QString& comment) @@ -158,12 +158,12 @@ QString Ui3Reader::trcall(const QString& sourceText, const QString& comment) } if (comment.isEmpty()) { - return t + QLatin1String("(") + fixString(sourceText, encode) + QLatin1String(")"); + return t + QLatin1Char('(') + fixString(sourceText, encode) + QLatin1Char(')'); } else { - return t + QLatin1String("(") + return t + QLatin1Char('(') + fixString(sourceText, encode) + QLatin1String(", ") - + fixString(comment, encode) + QLatin1String(")"); + + fixString(comment, encode) + QLatin1Char(')'); } } @@ -480,10 +480,10 @@ void Ui3Reader::createColorGroupImpl(const QString& name, const QDomElement& e) QString pixmap = n.firstChild().toText().data(); if (!pixmapLoaderFunction.isEmpty()) { pixmap.prepend(pixmapLoaderFunction - + QLatin1String("(") + + QLatin1Char('(') + QLatin1String(externPixmaps ? "\"" : "")); - pixmap.append(QLatin1String(externPixmaps ? "\"" : "") + QLatin1String(")")); + pixmap.append(QLatin1String(externPixmaps ? "\"" : "") + QLatin1Char(')')); } out << indent << name << ".setBrush(QColorGroup::" << ColorRole[r] << ", QBrush(" << color << ", " << pixmap << "));" << endl; @@ -578,9 +578,9 @@ QString Ui3Reader::registerObject(const QString& name) if (objectNames.contains(result)) { int i = 2; - while (objectNames.contains(result + QLatin1String("_") + QString::number(i))) + while (objectNames.contains(result + QLatin1Char('_') + QString::number(i))) i++; - result += QLatin1String("_"); + result += QLatin1Char('_'); result += QString::number(i); } objectNames += result; diff --git a/src/winmain/qtmain_win.cpp b/src/winmain/qtmain_win.cpp index a3bc0e0..b83b324 100644 --- a/src/winmain/qtmain_win.cpp +++ b/src/winmain/qtmain_win.cpp @@ -100,7 +100,7 @@ int APIENTRY WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR /*cmdPara #if defined(Q_OS_WINCE) TCHAR appName[256]; GetModuleFileName(0, appName, 255); - cmdParam = QString(QLatin1String("\"%1\" ")).arg(QString::fromUtf16((const unsigned short *)appName)).toLocal8Bit() + cmdParam; + cmdParam.prepend(QString::fromLatin1("\"%1\" ").arg(QString::fromUtf16((const unsigned short *)appName)).toLocal8Bit()); #endif int argc = 0; @@ -110,7 +110,7 @@ int APIENTRY WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR /*cmdPara #if defined(Q_OS_WINCE) TCHAR uniqueAppID[256]; GetModuleFileName(0, uniqueAppID, 255); - QString uid = QString::fromUtf16((const unsigned short *)uniqueAppID).toLower().replace(QString(QLatin1String("\\")), QString(QLatin1String("_"))); + QString uid = QString::frosmUtf16((const unsigned short *)uniqueAppID).toLower().replace(QLatin1Char('\\'), QLatin1Char('_')); // If there exists an other instance of this application // it will be the owner of a mutex with the unique ID. diff --git a/src/xml/dom/qdom.cpp b/src/xml/dom/qdom.cpp index dc6ff92..da0e31b 100644 --- a/src/xml/dom/qdom.cpp +++ b/src/xml/dom/qdom.cpp @@ -4589,7 +4589,7 @@ void QDomElementPrivate::save(QTextStream& s, int depth, int indent) const qName = prefix + QLatin1Char(':') + name; nsDecl = QLatin1String(" xmlns:") + prefix; } - nsDecl += QLatin1String("=\"") + encodeText(namespaceURI, s) + QLatin1String("\""); + nsDecl += QLatin1String("=\"") + encodeText(namespaceURI, s) + QLatin1Char('\"'); } s << '<' << qName << nsDecl; diff --git a/src/xml/sax/qxml.cpp b/src/xml/sax/qxml.cpp index ade0339..db50f01 100644 --- a/src/xml/sax/qxml.cpp +++ b/src/xml/sax/qxml.cpp @@ -5464,7 +5464,7 @@ bool QXmlSimpleReaderPrivate::parsePEReference() if (skipIt) { if (contentHnd) { - if (!contentHnd->skippedEntity(QString::fromLatin1("%") + ref())) { + if (!contentHnd->skippedEntity(QLatin1Char('%') + ref())) { reportParseError(contentHnd->errorString()); return false; } @@ -5476,7 +5476,7 @@ bool QXmlSimpleReaderPrivate::parsePEReference() return false; } else if (parsePEReference_context == InDTD) { // Included as PE - if (!insertXmlRef(QString::fromLatin1(" ")+xmlRefString+QString::fromLatin1(" "), ref(), false)) + if (!insertXmlRef(QLatin1Char(' ') + xmlRefString + QLatin1Char(' '), ref(), false)) return false; } } @@ -6728,7 +6728,7 @@ bool QXmlSimpleReaderPrivate::parseEntityDecl() if ( !entityExist(name())) { parameterEntities.insert(name(), string()); if (declHnd) { - if (!declHnd->internalEntityDecl(QString::fromLatin1("%")+name(), string())) { + if (!declHnd->internalEntityDecl(QLatin1Char('%') + name(), string())) { reportParseError(declHnd->errorString()); return false; } @@ -6740,7 +6740,7 @@ bool QXmlSimpleReaderPrivate::parseEntityDecl() if ( !entityExist(name())) { externParameterEntities.insert(name(), QXmlSimpleReaderPrivate::ExternParameterEntity(publicId, systemId)); if (declHnd) { - if (!declHnd->externalEntityDecl(QString::fromLatin1("%")+name(), publicId, systemId)) { + if (!declHnd->externalEntityDecl(QLatin1Char('%') + name(), publicId, systemId)) { reportParseError(declHnd->errorString()); return false; } @@ -7864,8 +7864,8 @@ bool QXmlSimpleReaderPrivate::insertXmlRef(const QString &data, const QString &n { if (inLiteral) { QString tmp = data; - xmlRefStack.push(XmlRef(name, tmp.replace(QLatin1String("\""), - QLatin1String(""")).replace(QLatin1String("'"), QLatin1String("'")))); + xmlRefStack.push(XmlRef(name, tmp.replace(QLatin1Char('\"'), + QLatin1String(""")).replace(QLatin1Char('\''), QLatin1String("'")))); } else { xmlRefStack.push(XmlRef(name, data)); } diff --git a/src/xmlpatterns/acceltree/qacceltree.cpp b/src/xmlpatterns/acceltree/qacceltree.cpp index 60e6e27..6bc1794 100644 --- a/src/xmlpatterns/acceltree/qacceltree.cpp +++ b/src/xmlpatterns/acceltree/qacceltree.cpp @@ -71,7 +71,7 @@ void AccelTree::printStats(const NamePool::Ptr &np) const for(int i = 0; i < len; ++i) { const BasicNodeData &v = basicData.at(i); - pDebug() << "|" << i + pDebug() << '|' << i << "\t\t|" << v.depth() << "\t|" << v.size() << "\t|" << postNumber(i) @@ -81,12 +81,12 @@ void AccelTree::printStats(const NamePool::Ptr &np) const : data.value(i)) << "\t|"; /* - pDebug() << "|" << QString().arg(i, 14) - << "|" << QString().arg(v.depth(), 6) - << "|" << QString().arg(v.size(), 6) - << "|" << QString().arg(postNumber(i), 14) - << "|" << QString().arg(v.kind(), 6) - << "|"; + pDebug() << '|' << QString().arg(i, 14) + << '|' << QString().arg(v.depth(), 6) + << '|' << QString().arg(v.size(), 6) + << '|' << QString().arg(postNumber(i), 14) + << '|' << QString().arg(v.kind(), 6) + << '|'; */ } pDebug() << "+---------------+-------+-------+---------------+-------+--------------+"; diff --git a/src/xmlpatterns/api/qsourcelocation.cpp b/src/xmlpatterns/api/qsourcelocation.cpp index 4eee39c..1dd8ffd 100644 --- a/src/xmlpatterns/api/qsourcelocation.cpp +++ b/src/xmlpatterns/api/qsourcelocation.cpp @@ -206,7 +206,7 @@ QDebug operator<<(QDebug debug, const QSourceLocation &sourceLocation) << sourceLocation.line() << ", column:" << sourceLocation.column() - << ")"; + << ')'; return debug; } #endif diff --git a/src/xmlpatterns/data/qabstractfloat.cpp b/src/xmlpatterns/data/qabstractfloat.cpp index b6226b5..a45b0fd 100644 --- a/src/xmlpatterns/data/qabstractfloat.cpp +++ b/src/xmlpatterns/data/qabstractfloat.cpp @@ -186,7 +186,7 @@ QString AbstractFloat::stringValue() const if(sign) valueAsString += QLatin1Char('-'); - valueAsString += qret.left(1); + valueAsString += qret.at(0); valueAsString += QLatin1Char('.'); if(1 == qret.size()) diff --git a/src/xmlpatterns/data/qcommonvalues.cpp b/src/xmlpatterns/data/qcommonvalues.cpp index 07a273d..99a8086 100644 --- a/src/xmlpatterns/data/qcommonvalues.cpp +++ b/src/xmlpatterns/data/qcommonvalues.cpp @@ -57,7 +57,7 @@ using namespace QPatternist; // STATIC DATA const AtomicString::Ptr CommonValues::EmptyString - (new AtomicString(QString(QLatin1String("")))); + (new AtomicString(QLatin1String(""))); const AtomicString::Ptr CommonValues::TrueString (new AtomicString(QLatin1String("true"))); const AtomicString::Ptr CommonValues::FalseString diff --git a/src/xmlpatterns/expr/qexpression_p.h b/src/xmlpatterns/expr/qexpression_p.h index 5eb63de..65918e6 100644 --- a/src/xmlpatterns/expr/qexpression_p.h +++ b/src/xmlpatterns/expr/qexpression_p.h @@ -884,7 +884,7 @@ namespace QPatternist { pDebug() << "AST REWRITE:" << old.data() << "to" << New.data() << '(' << old->actualReflection() << "to" << New->actualReflection() << ", " - << old->description() << "to" << New->description() << ")"; + << old->description() << "to" << New->description() << ')'; /* The order of these two lines is significant.. */ context->addLocation(New.data(), context->locationFor(old->actualReflection())); diff --git a/tools/assistant/tools/assistant/main.cpp b/tools/assistant/tools/assistant/main.cpp index 75955ec..f63cc65 100644 --- a/tools/assistant/tools/assistant/main.cpp +++ b/tools/assistant/tools/assistant/main.cpp @@ -230,7 +230,7 @@ int main(int argc, char *argv[]) if (file.isEmpty()) file = MainWindow::defaultHelpCollectionFileName(); QString path = QFileInfo(file).path(); - path += QLatin1String("/") + indexFilesFolder(file); + path += QLatin1Char('/') + indexFilesFolder(file); QLocalSocket localSocket; localSocket.connectToServer(QString(QLatin1String("QtAssistant%1")) diff --git a/tools/linguist/linguist/mainwindow.cpp b/tools/linguist/linguist/mainwindow.cpp index 921b8b6..f91175d 100644 --- a/tools/linguist/linguist/mainwindow.cpp +++ b/tools/linguist/linguist/mainwindow.cpp @@ -127,7 +127,7 @@ static Ending ending(QString str, QLocale::Language lang) switch (ch) { case 0x002e: // full stop - if (str.endsWith(QString(QLatin1String("...")))) + if (str.endsWith(QLatin1String("..."))) return End_Ellipsis; else return End_FullStop; diff --git a/tools/linguist/linguist/phrase.cpp b/tools/linguist/linguist/phrase.cpp index 300f6e8..b1f9818 100644 --- a/tools/linguist/linguist/phrase.cpp +++ b/tools/linguist/linguist/phrase.cpp @@ -152,10 +152,10 @@ bool QphHandler::startElement(const QString & /* namespaceURI */, const QString &qName, const QXmlAttributes &atts) { - if (qName == QString(QLatin1String("QPH"))) { + if (qName == QLatin1String("QPH")) { m_language = atts.value(QLatin1String("language")); m_sourceLanguage = atts.value(QLatin1String("sourcelanguage")); - } else if (qName == QString(QLatin1String("phrase"))) { + } else if (qName == QLatin1String("phrase")) { source.truncate(0); target.truncate(0); definition.truncate(0); @@ -168,13 +168,13 @@ bool QphHandler::endElement(const QString & /* namespaceURI */, const QString & /* localName */, const QString &qName) { - if (qName == QString(QLatin1String("source"))) + if (qName == QLatin1String("source")) source = accum; - else if (qName == QString(QLatin1String("target"))) + else if (qName == QLatin1String("target")) target = accum; - else if (qName == QString(QLatin1String("definition"))) + else if (qName == QLatin1String("definition")) definition = accum; - else if (qName == QString(QLatin1String("phrase"))) + else if (qName == QLatin1String("phrase")) pb->m_phrases.append(new Phrase(source, target, definition, pb)); return true; } diff --git a/tools/linguist/lupdate/merge.cpp b/tools/linguist/lupdate/merge.cpp index c4f4448..4849d6e 100644 --- a/tools/linguist/lupdate/merge.cpp +++ b/tools/linguist/lupdate/merge.cpp @@ -193,7 +193,7 @@ static QString translationAttempt(const QString &oldTranslation, */ for (k = 0; k < p; k++) { if (!met[k]) - attempt += QString(QLatin1String(" {")) + newNumbers[k] + QString(QLatin1String("?}")); + attempt += QLatin1String(" {") + newNumbers[k] + QLatin1String("?}"); } /* @@ -205,8 +205,8 @@ static QString translationAttempt(const QString &oldTranslation, for (ell = 0; ell < p; ell++) { if (k != ell && oldNumbers[k] == oldNumbers[ell] && newNumbers[k] < newNumbers[ell]) - attempt += QString(QLatin1String(" {")) + newNumbers[k] + QString(QLatin1String(" or ")) + - newNumbers[ell] + QString(QLatin1String("?}")); + attempt += QLatin1String(" {") + newNumbers[k] + QLatin1String(" or ") + + newNumbers[ell] + QLatin1String("?}"); } } return attempt; diff --git a/tools/linguist/shared/profileevaluator.cpp b/tools/linguist/shared/profileevaluator.cpp index 0be6bec..ae46ad8 100644 --- a/tools/linguist/shared/profileevaluator.cpp +++ b/tools/linguist/shared/profileevaluator.cpp @@ -894,7 +894,7 @@ QStringList ProFileEvaluator::Private::qmakeFeaturePaths() { QStringList concat; { - const QString base_concat = QDir::separator() + QString(QLatin1String("features")); + const QString base_concat = QDir::separator() + QLatin1String("features"); concat << base_concat + QDir::separator() + QLatin1String("mac"); concat << base_concat + QDir::separator() + QLatin1String("macx"); concat << base_concat + QDir::separator() + QLatin1String("unix"); @@ -903,7 +903,7 @@ QStringList ProFileEvaluator::Private::qmakeFeaturePaths() concat << base_concat + QDir::separator() + QLatin1String("qnx6"); concat << base_concat; } - const QString mkspecs_concat = QDir::separator() + QString(QLatin1String("mkspecs")); + const QString mkspecs_concat = QDir::separator() + QLatin1String("mkspecs"); QStringList feature_roots; QByteArray mkspec_path = qgetenv("QMAKEFEATURES"); if (!mkspec_path.isNull()) diff --git a/tools/linguist/shared/proparserutils.h b/tools/linguist/shared/proparserutils.h index c27c3c0..3eab43f 100644 --- a/tools/linguist/shared/proparserutils.h +++ b/tools/linguist/shared/proparserutils.h @@ -282,7 +282,7 @@ static QStringList split_value_list(const QString &vals, bool do_semicolon=false static QStringList qmake_mkspec_paths() { QStringList ret; - const QString concat = QDir::separator() + QString(QLatin1String("mkspecs")); + const QString concat = QDir::separator() + QLatin1String("mkspecs"); QByteArray qmakepath = qgetenv("QMAKEPATH"); if (!qmakepath.isEmpty()) { const QStringList lst = splitPathList(QString::fromLocal8Bit(qmakepath)); diff --git a/tools/pixeltool/qpixeltool.cpp b/tools/pixeltool/qpixeltool.cpp index 6de7741..c55cbd1 100644 --- a/tools/pixeltool/qpixeltool.cpp +++ b/tools/pixeltool/qpixeltool.cpp @@ -179,13 +179,13 @@ void QPixelTool::paintEvent(QPaintEvent *) if (m_displayZoom) { render_string(&p, w, h, - QString(QLatin1String("Zoom: x%1")).arg(m_zoom), + QString::fromLatin1("Zoom: x%1").arg(m_zoom), Qt::AlignTop | Qt::AlignRight); } if (m_displayGridSize) { render_string(&p, w, h, - QString(QLatin1String("Grid size: %1")).arg(m_gridSize), + QString::fromLatin1("Grid size: %1").arg(m_gridSize), Qt::AlignBottom | Qt::AlignLeft); } diff --git a/tools/porting/src/logger.cpp b/tools/porting/src/logger.cpp index fb44de7..bbeac9c 100644 --- a/tools/porting/src/logger.cpp +++ b/tools/porting/src/logger.cpp @@ -60,8 +60,8 @@ SourcePointLogEntry::SourcePointLogEntry(QString type, QString location, QString QString SourcePointLogEntry::description() const { return QLatin1String("In file ") + file + - QLatin1String(" at line ") + QString(QLatin1String("%1")).arg(line + 1) + //line count is zero based, adjust here. - QLatin1String(" column ") + QString(QLatin1String("%1")).arg(column) + + QLatin1String(" at line ") + QString::number(line + 1) + //line count is zero based, adjust here. + QLatin1String(" column ") + QString::number(column) + QLatin1String(": ") + text ; } @@ -127,7 +127,7 @@ QStringList Logger::fullReport() commitSection(); QStringList report; report << QLatin1String("Log for qt3to4 on ") + QDateTime::currentDateTime().toString() + - QLatin1String(". Number of log entries: ") + QString(QLatin1String("%1")).arg(logEntries.size()); + QLatin1String(". Number of log entries: ") + QString::number(logEntries.size()); foreach(LogEntry *logEntry, logEntries) { report << logEntry->description(); } diff --git a/tools/qdoc3/config.cpp b/tools/qdoc3/config.cpp index c8488f3..aa6b454 100644 --- a/tools/qdoc3/config.cpp +++ b/tools/qdoc3/config.cpp @@ -751,7 +751,7 @@ void Config::load(Location location, const QString& fileName) word += QChar(c.digitValue()); SKIP_CHAR(); } - else if ((metaCharPos = QString(QLatin1String("abfnrtv")).indexOf(c)) != -1) { + else if ((metaCharPos = QString::fromLatin1("abfnrtv").indexOf(c)) != -1) { word += "\a\b\f\n\r\t\v"[metaCharPos]; SKIP_CHAR(); } diff --git a/tools/shared/qttoolbardialog/qttoolbardialog.cpp b/tools/shared/qttoolbardialog/qttoolbardialog.cpp index f15c4bc..9c54e75 100644 --- a/tools/shared/qttoolbardialog/qttoolbardialog.cpp +++ b/tools/shared/qttoolbardialog/qttoolbardialog.cpp @@ -637,10 +637,10 @@ QToolBar *QtFullToolBarManager::createToolBar(const QString &toolBarName) return 0; QToolBar *toolBar = new QToolBar(toolBarName, mainWindow()); int i = 1; - const QString prefix = QLatin1String("_Custom_Toolbar_"); - QString name = QString(QLatin1String("%1%2")).arg(prefix).arg(i); + const QString prefix = QLatin1String("_Custom_Toolbar_%1"); + QString name = prefix.arg(i); while (d_ptr->toolBarByName(name)) - name = QString(QLatin1String("%1%2")).arg(prefix).arg(++i); + name = prefix.arg(++i); toolBar->setObjectName(name); mainWindow()->addToolBar(toolBar); d_ptr->customToolBars.append(toolBar); -- cgit v0.12 From cd6fa8abed473936af55055a3ebe209bb7241a85 Mon Sep 17 00:00:00 2001 From: Christoph Feck Date: Mon, 11 May 2009 21:58:22 +0200 Subject: Respect PM_ScrollView_ScrollBarSpacing in QAbstractScrollArea::minimumSizeHint() Reviewed-by: Olivier Goffart Request-url: http://qt.gitorious.org/qt/qt/merge_requests/382 --- src/gui/widgets/qabstractscrollarea.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/gui/widgets/qabstractscrollarea.cpp b/src/gui/widgets/qabstractscrollarea.cpp index 0d8b4de..5eed745 100644 --- a/src/gui/widgets/qabstractscrollarea.cpp +++ b/src/gui/widgets/qabstractscrollarea.cpp @@ -1265,6 +1265,12 @@ QSize QAbstractScrollArea::minimumSizeHint() const int hsbExt = d->hbar->sizeHint().height(); int vsbExt = d->vbar->sizeHint().width(); int extra = 2 * d->frameWidth; + QStyleOption opt; + opt.initFrom(this); + if ((d->frameStyle != QFrame::NoFrame) + && style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, &opt, this)) { + extra += style()->pixelMetric(QStyle::PM_ScrollView_ScrollBarSpacing, &opt, this); + } return QSize(d->scrollBarContainers[Qt::Horizontal]->sizeHint().width() + vsbExt + extra, d->scrollBarContainers[Qt::Vertical]->sizeHint().height() + hsbExt + extra); } -- cgit v0.12 From abed949f0de16c94a146a965a13b38493cde6671 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Thu, 28 May 2009 11:29:34 +0200 Subject: BT: aboutQt dialog is too big. Make use of setInformativeText in qmessagebox for aboutQt dialog for now. Proper fix might be to add scrollable widget to the dialog, or split the about info into several pieces, though it cannot be done in a patch release. Task-number: 254464 Reviewed-by: Trenton Schulz --- src/gui/dialogs/qmessagebox.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/dialogs/qmessagebox.cpp b/src/gui/dialogs/qmessagebox.cpp index fb3bcb8..b121a8f 100644 --- a/src/gui/dialogs/qmessagebox.cpp +++ b/src/gui/dialogs/qmessagebox.cpp @@ -1723,7 +1723,7 @@ void QMessageBox::aboutQt(QWidget *parent, const QString &title) QMessageBox *msgBox = new QMessageBox(parent); msgBox->setAttribute(Qt::WA_DeleteOnClose); msgBox->setWindowTitle(title.isEmpty() ? tr("About Qt") : title); - msgBox->setText(translatedTextAboutQt); + msgBox->setInformativeText(translatedTextAboutQt); QPixmap pm(QLatin1String(":/trolltech/qmessagebox/images/qtlogo-64.png")); if (!pm.isNull()) -- cgit v0.12 From b2a1e5938e1abf45d70cbfa7ec1ab0c21c01911d Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Wed, 27 May 2009 10:19:44 +0200 Subject: support for -ltcg configure switch for Windows CE builds Additionally we turn -ltcg on by default on Windows CE. See commit 56191830 for details. Reviewed-by: mauricek BT: yes --- mkspecs/common/wince.conf | 7 +++++-- tools/configure/configureapp.cpp | 1 + 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/mkspecs/common/wince.conf b/mkspecs/common/wince.conf index d017cae..d6e4ba7 100644 --- a/mkspecs/common/wince.conf +++ b/mkspecs/common/wince.conf @@ -19,7 +19,8 @@ QMAKE_YACCFLAGS = -d QMAKE_CFLAGS = -nologo -Zm200 -Zc:wchar_t- QMAKE_CFLAGS_WARN_ON = -W3 QMAKE_CFLAGS_WARN_OFF = -W0 -QMAKE_CFLAGS_RELEASE = -O2 -GL -MD +QMAKE_CFLAGS_RELEASE = -O2 -MD +QMAKE_CFLAGS_LTCG = -GL QMAKE_CFLAGS_DEBUG = -DDEBUG -D_DEBUG -Zi -MDd QMAKE_CFLAGS_YACC = @@ -34,6 +35,7 @@ QMAKE_CXXFLAGS_WARN_ON = $$QMAKE_CFLAGS_WARN_ON -w34100 -w34189 QMAKE_CXXFLAGS_WARN_OFF = $$QMAKE_CFLAGS_WARN_OFF QMAKE_CXXFLAGS_RELEASE = $$QMAKE_CFLAGS_RELEASE QMAKE_CXXFLAGS_DEBUG = $$QMAKE_CFLAGS_DEBUG +QMAKE_CXXFLAGS_LTCG = $$QMAKE_CFLAGS_LTCG QMAKE_CXXFLAGS_YACC = $$QMAKE_CFLAGS_YACC QMAKE_CXXFLAGS_STL_ON = -EHsc QMAKE_CXXFLAGS_STL_OFF = @@ -55,8 +57,9 @@ QMAKE_RUN_CXX_IMP_BATCH = $(CXX) -c $(CXXFLAGS) $(INCPATH) -Fo$@ @<< QMAKE_LINK = link QMAKE_LFLAGS = /NOLOGO /NODEFAULTLIB:OLDNAMES.LIB -QMAKE_LFLAGS_RELEASE = /LTCG /INCREMENTAL:NO +QMAKE_LFLAGS_RELEASE = /INCREMENTAL:NO QMAKE_LFLAGS_DEBUG = /DEBUG +QMAKE_LFLAGS_LTCG = /LTCG QMAKE_LIBS_NETWORK = ws2.lib QMAKE_LIBS_OPENGL = QMAKE_LIBS_COMPAT = diff --git a/tools/configure/configureapp.cpp b/tools/configure/configureapp.cpp index 91344c8..a6b06a6 100644 --- a/tools/configure/configureapp.cpp +++ b/tools/configure/configureapp.cpp @@ -1326,6 +1326,7 @@ void Configure::applySpecSpecifics() dictionary[ "WEBKIT" ] = "no"; dictionary[ "PHONON" ] = "yes"; dictionary[ "DIRECTSHOW" ] = "no"; + dictionary[ "LTCG" ] = "yes"; // We only apply MMX/IWMMXT for mkspecs we know they work if (dictionary[ "XQMAKESPEC" ].startsWith("wincewm")) { dictionary[ "MMX" ] = "yes"; -- cgit v0.12 From 4b45c38a19145f5235d93fa9d1577615cdfc162e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 28 May 2009 10:58:58 +0200 Subject: Moved QGL2PaintEngineExPrivate into GL2 paint engine header file. Reviewed-by: Tom --- src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h | 5 ++ .../gl2paintengineex/qpaintengineex_opengl2.cpp | 91 ---------------------- .../gl2paintengineex/qpaintengineex_opengl2_p.h | 90 +++++++++++++++++++++ src/opengl/qglpixelbuffer.cpp | 3 +- 4 files changed, 96 insertions(+), 93 deletions(-) diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h index a83f13e..35566ca 100644 --- a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h +++ b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h @@ -50,6 +50,9 @@ // We mean it. // +#ifndef QGL2PEXVERTEXARRAY_P_H +#define QGL2PEXVERTEXARRAY_P_H + #include #include @@ -120,3 +123,5 @@ private: inline void curveToArray(const QGLPoint &cp1, const QGLPoint &cp2, const QGLPoint &ep, GLfloat inverseScale); }; + +#endif diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index f7dbed3..5b33421 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -62,7 +62,6 @@ and use the correct program when we really need it. */ - #include "qpaintengineex_opengl2_p.h" #include //for memcpy @@ -83,101 +82,11 @@ extern QImage qt_imageForBrush(int brushStyle, bool invert); //in qbrush.cpp - -#include - -enum EngineMode { - ImageDrawingMode, - TextDrawingMode, - BrushDrawingMode -}; - static const GLuint QT_BRUSH_TEXTURE_UNIT = 0; static const GLuint QT_IMAGE_TEXTURE_UNIT = 0; //Can be the same as brush texture unit static const GLuint QT_MASK_TEXTURE_UNIT = 1; static const GLuint QT_BACKGROUND_TEXTURE_UNIT = 2; -class QGL2PaintEngineExPrivate : public QPaintEngineExPrivate -{ - Q_DECLARE_PUBLIC(QGL2PaintEngineEx) -public: - QGL2PaintEngineExPrivate(QGL2PaintEngineEx *q_ptr) : - q(q_ptr), - width(0), height(0), - ctx(0), - currentBrush( &(q->state()->brush) ), - inverseScale(1), - shaderManager(0) - { } - - ~QGL2PaintEngineExPrivate(); - - void updateBrushTexture(); - void updateBrushUniforms(); - void updateMatrix(); - void updateCompositionMode(); - void updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform); - - void setBrush(const QBrush* brush); - - void transferMode(EngineMode newMode); - - // fill, drawOutline, drawTexture & drawCachedGlyphs are the rendering entry points: - void fill(const QVectorPath &path); - void drawOutline(const QVectorPath& path); - void drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize); - void drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti); - - void drawVertexArrays(QGL2PEXVertexArray& vertexArray, GLenum primitive); - // ^ draws whatever is in the vertex array - void composite(const QGLRect& boundingRect); - // ^ Composites the bounding rect onto dest buffer - void fillStencilWithVertexArray(QGL2PEXVertexArray& vertexArray, bool useWindingFill); - // ^ Calls drawVertexArrays to render into stencil buffer - void cleanStencilBuffer(const QGLRect& area); - - void prepareForDraw(bool srcPixelsAreOpaque); - - inline void useSimpleShader(); - inline QColor premultiplyColor(QColor c, GLfloat opacity); - - QGL2PaintEngineEx* q; - QGLDrawable drawable; - int width, height; - QGLContext *ctx; - - EngineMode mode; - - // Dirty flags - bool matrixDirty; // Implies matrix uniforms are also dirty - bool compositionModeDirty; - bool brushTextureDirty; - bool brushUniformsDirty; - bool simpleShaderMatrixUniformDirty; - bool shaderMatrixUniformDirty; - bool stencilBuferDirty; - - const QBrush* currentBrush; // May not be the state's brush! - - GLfloat inverseScale; - - QGL2PEXVertexArray vertexCoordinateArray; - QGL2PEXVertexArray textureCoordinateArray; - - GLfloat staticVertexCoordinateArray[8]; - GLfloat staticTextureCoordinateArray[8]; - - GLfloat pmvMatrix[4][4]; - - QGLEngineShaderManager* shaderManager; - - // Clipping & state stuff stolen from QOpenGLPaintEngine: - void updateDepthClip(); - void systemStateChanged(); - uint use_system_clip : 1; -}; - - ////////////////////////////////// Private Methods ////////////////////////////////////////// QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate() diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index ccf89f0..34ab6b3 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -53,7 +53,17 @@ // We mean it. // +#include + #include +#include +#include + +enum EngineMode { + ImageDrawingMode, + TextDrawingMode, + BrushDrawingMode +}; class QGL2PaintEngineExPrivate; @@ -119,4 +129,84 @@ private: Q_DISABLE_COPY(QGL2PaintEngineEx) }; +class QGL2PaintEngineExPrivate : public QPaintEngineExPrivate +{ + Q_DECLARE_PUBLIC(QGL2PaintEngineEx) +public: + QGL2PaintEngineExPrivate(QGL2PaintEngineEx *q_ptr) : + q(q_ptr), + width(0), height(0), + ctx(0), + currentBrush( &(q->state()->brush) ), + inverseScale(1), + shaderManager(0) + { } + + ~QGL2PaintEngineExPrivate(); + + void updateBrushTexture(); + void updateBrushUniforms(); + void updateMatrix(); + void updateCompositionMode(); + void updateTextureFilter(GLenum target, GLenum wrapMode, bool smoothPixmapTransform); + + void setBrush(const QBrush* brush); + + void transferMode(EngineMode newMode); + + // fill, drawOutline, drawTexture & drawCachedGlyphs are the rendering entry points: + void fill(const QVectorPath &path); + void drawOutline(const QVectorPath& path); + void drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize); + void drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti); + + void drawVertexArrays(QGL2PEXVertexArray& vertexArray, GLenum primitive); + // ^ draws whatever is in the vertex array + void composite(const QGLRect& boundingRect); + // ^ Composites the bounding rect onto dest buffer + void fillStencilWithVertexArray(QGL2PEXVertexArray& vertexArray, bool useWindingFill); + // ^ Calls drawVertexArrays to render into stencil buffer + void cleanStencilBuffer(const QGLRect& area); + + void prepareForDraw(bool srcPixelsAreOpaque); + + inline void useSimpleShader(); + inline QColor premultiplyColor(QColor c, GLfloat opacity); + + QGL2PaintEngineEx* q; + QGLDrawable drawable; + int width, height; + QGLContext *ctx; + + EngineMode mode; + + // Dirty flags + bool matrixDirty; // Implies matrix uniforms are also dirty + bool compositionModeDirty; + bool brushTextureDirty; + bool brushUniformsDirty; + bool simpleShaderMatrixUniformDirty; + bool shaderMatrixUniformDirty; + bool stencilBuferDirty; + + const QBrush* currentBrush; // May not be the state's brush! + + GLfloat inverseScale; + + QGL2PEXVertexArray vertexCoordinateArray; + QGL2PEXVertexArray textureCoordinateArray; + + GLfloat staticVertexCoordinateArray[8]; + GLfloat staticTextureCoordinateArray[8]; + + GLfloat pmvMatrix[4][4]; + + QGLEngineShaderManager* shaderManager; + + // Clipping & state stuff stolen from QOpenGLPaintEngine: + void updateDepthClip(); + void systemStateChanged(); + uint use_system_clip : 1; +}; + #endif diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp index efc58f2..483856a 100644 --- a/src/opengl/qglpixelbuffer.cpp +++ b/src/opengl/qglpixelbuffer.cpp @@ -76,13 +76,12 @@ \sa {opengl/pbuffers}{Pbuffers Example} */ +#include #include #include #include -#include - #ifndef QT_OPENGL_ES_2 #include #endif -- cgit v0.12 From 218c9883f5b1f7e7eb9e6272460223088bfaf305 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 28 May 2009 11:53:15 +0200 Subject: QStateMachine: better way to get the sender signalIndex The QObject internals have changed, and the mutex that need to be locked to access the senders list is not the same anymore, and not accessible form qstatemachine.cpp But we do not need to loop over the senders list anyway because this is done in sender() We also do not need to lock in order to access the currentSender Reviewed-by: Eskil --- src/corelib/statemachine/qstatemachine.cpp | 25 +++++++------------------ 1 file changed, 7 insertions(+), 18 deletions(-) diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp index 185fb7d..84619d7 100644 --- a/src/corelib/statemachine/qstatemachine.cpp +++ b/src/corelib/statemachine/qstatemachine.cpp @@ -1301,22 +1301,6 @@ void QStateMachinePrivate::unregisterTransition(QAbstractTransition *transition) #endif } -static int senderSignalIndex(const QObject *sender) -{ - QObjectPrivate *d = QObjectPrivate::get(const_cast(sender)); - QMutexLocker(&d->threadData->mutex); - if (!d->currentSender) - return -1; - - // Return -1 if d->currentSender isn't in d->senders - bool found = false; - for (int i = 0; !found && i < d->senders.count(); ++i) - found = (d->senders.at(i)->sender == d->currentSender->sender); - if (!found) - return -1; - return d->currentSender->signal; -} - void QStateMachinePrivate::registerSignalTransition(QSignalTransition *transition) { Q_Q(QStateMachine); @@ -2087,10 +2071,15 @@ int QSignalEventGenerator::qt_metacall(QMetaObject::Call _c, int _id, void **_a) switch (_id) { case 0: { // ### in Qt 4.6 we can use QObject::senderSignalIndex() - int signalIndex = senderSignalIndex(this); + QObjectPrivate *d = static_cast(d_ptr); + int signalIndex = -1; + QObject *sender = this->sender(); + if (sender && d->currentSender) + signalIndex = d->currentSender->signal; + Q_ASSERT(signalIndex != -1); QStateMachine *machine = qobject_cast(parent()); - QStateMachinePrivate::get(machine)->handleTransitionSignal(sender(), signalIndex, _a); + QStateMachinePrivate::get(machine)->handleTransitionSignal(sender, signalIndex, _a); break; } default: ; -- cgit v0.12 From d2377967485a9c0ba397bbbab250689b61e529f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20G=C3=A2teau?= Date: Sun, 17 May 2009 14:34:35 +0200 Subject: Do not deduce scrollbar extent twice if scrollbar policy is Qt::ScrollBarAlwaysOn Request-url: http://qt.gitorious.org/qt/qt/merge_requests/432 Reviewed-by: Olivier Goffart Reviewed-by: Thierry --- src/gui/itemviews/qlistview.cpp | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/src/gui/itemviews/qlistview.cpp b/src/gui/itemviews/qlistview.cpp index 1071c1d..8b50d0e 100644 --- a/src/gui/itemviews/qlistview.cpp +++ b/src/gui/itemviews/qlistview.cpp @@ -1973,10 +1973,16 @@ void QListViewPrivate::prepareItemsLayout() int frameAroundContents = 0; if (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents)) frameAroundContents = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth) * 2; - int verticalMargin = vbarpolicy==Qt::ScrollBarAlwaysOff ? 0 : - q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, q->verticalScrollBar()) + frameAroundContents; - int horizontalMargin = hbarpolicy==Qt::ScrollBarAlwaysOff ? 0 : - q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, q->horizontalScrollBar()) + frameAroundContents; + + // maximumViewportSize() already takes scrollbar into account if policy is + // Qt::ScrollBarAlwaysOn but scrollbar extent must be deduced if policy + // is Qt::ScrollBarAsNeeded + int verticalMargin = vbarpolicy==Qt::ScrollBarAsNeeded + ? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, q->verticalScrollBar()) + frameAroundContents + : 0; + int horizontalMargin = hbarpolicy==Qt::ScrollBarAsNeeded + ? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, q->horizontalScrollBar()) + frameAroundContents + : 0; layoutBounds.adjust(0, 0, -verticalMargin, -horizontalMargin); -- cgit v0.12 From 4db48cbc4860010813b988b77d34a2606a444a3c Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 28 May 2009 10:20:34 +0200 Subject: Fix build on X11/OpenGL ES 2.0 Reviewed-By: TrustMe --- src/opengl/qwindowsurface_gl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/opengl/qwindowsurface_gl.cpp b/src/opengl/qwindowsurface_gl.cpp index a3422b5..965c7a5 100644 --- a/src/opengl/qwindowsurface_gl.cpp +++ b/src/opengl/qwindowsurface_gl.cpp @@ -405,8 +405,8 @@ void QGLWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoint & drawTexture(rect, d_ptr->tex_id, window()->size(), rect); } } -#endif } +#endif d_ptr->paintedRegion = QRegion(); context()->swapBuffers(); -- cgit v0.12 From ce5f9bc2a6b1945abdbdc4106be048eb9cbb7102 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 28 May 2009 10:21:48 +0200 Subject: Print the error string when surface creation fails Reviewed-By: TrustMe --- src/opengl/qegl_x11egl.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/opengl/qegl_x11egl.cpp b/src/opengl/qegl_x11egl.cpp index 8efe7e7..c703900 100644 --- a/src/opengl/qegl_x11egl.cpp +++ b/src/opengl/qegl_x11egl.cpp @@ -42,6 +42,7 @@ #include #include #include +#include #include "qegl_p.h" #if defined(QT_OPENGL_ES) || defined(QT_OPENVG) @@ -80,8 +81,10 @@ bool QEglContext::createSurface(QPaintDevice *device) surf = eglCreateWindowSurface(dpy, cfg, windowDrawable, 0); else surf = eglCreatePixmapSurface(dpy, cfg, pixmapDrawable, 0); + if (surf == EGL_NO_SURFACE) { - qWarning("QEglContext::createSurface(): Unable to create EGL surface, error = 0x%x", eglGetError()); + qWarning() << "QEglContext::createSurface(): Unable to create EGL surface:" + << errorString(eglGetError()); return false; } return true; -- cgit v0.12 From 7ff70350f485f815bbcb2412631b636485ebe37d Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 28 May 2009 10:35:43 +0200 Subject: Send ParentChanged event to QGLWidgets when the wId changes on EGL EGL has window surfaces which are bound to a particular window ID. When that window ID changes, the EGL surface must be re-created. This is achieved by sending the QGLWidget a ParentChanged event. Reviewed-By: Trond --- src/gui/kernel/qwidget.cpp | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index d6e5cce..5538c11 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -9203,11 +9203,12 @@ void QWidget::setParent(QWidget *parent, Qt::WindowFlags f) d->resolveLayoutDirection(); d->resolveLocale(); - // Note: GL widgets under Windows will always need a ParentChange - // event to handle recreation/rebinding of the GL context, hence - // the (f & Qt::MSWindowsOwnDC) clause + // Note: GL widgets under WGL or EGL will always need a ParentChange + // event to handle recreation/rebinding of the GL context, hence the + // (f & Qt::MSWindowsOwnDC) clause (which is set on QGLWidgets on all + // platforms). if (newParent -#ifdef Q_WS_WIN +#if defined(Q_WS_WIN) || defined(QT_OPENGL_ES) || (f & Qt::MSWindowsOwnDC) #endif ) { -- cgit v0.12 From 54aaf1f72e11ba4d7e38bbde127a4630aa27df23 Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 28 May 2009 10:42:20 +0200 Subject: Make WA_TranslucentBackground work for QGLWidgets on X11/EGL Reviewed-By: TrustMe --- src/opengl/qgl_x11egl.cpp | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/opengl/qgl_x11egl.cpp b/src/opengl/qgl_x11egl.cpp index 514e763..3c745b8 100644 --- a/src/opengl/qgl_x11egl.cpp +++ b/src/opengl/qgl_x11egl.cpp @@ -243,13 +243,24 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, return; } - - // Create the EGL Context (which will also choose the config for us) if (d->glcx) d->glcx->doneCurrent(); QGLContext* oldcx = d->glcx; d->glcx = context; + if (parentWidget()) { + // force creation of delay-created widgets + parentWidget()->winId(); + if (parentWidget()->x11Info().screen() != x11Info().screen()) + d_func()->xinfo = parentWidget()->d_func()->xinfo; + } + + // If the application has set WA_TranslucentBackground and not explicitly set + // the alpha buffer size to zero, modify the format so it have an alpha channel + QGLFormat& fmt = d->glcx->d_func()->glFormat; + if (testAttribute(Qt::WA_TranslucentBackground) && fmt.alphaBufferSize() == -1) + fmt.setAlphaBufferSize(1); + bool createFailed = false; if (!d->glcx->isValid()) { if (!d->glcx->create(shareContext ? shareContext : oldcx)) @@ -267,15 +278,6 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, return; } - - - // Make sure native winIds are avaliable - if (parentWidget()) { - parentWidget()->winId(); - if (parentWidget()->x11Info().screen() != x11Info().screen()) - d_func()->xinfo = parentWidget()->d_func()->xinfo; - } - bool visible = isVisible(); if (visible) hide(); @@ -384,6 +386,7 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, a.colormap = XCreateColormap(x11Info().display(), p, vi.visual, AllocNone); valueMask |= CWColormap; } + Window w = XCreateWindow(x11Info().display(), p, x(), y(), width(), height(), 0, vi.depth, InputOutput, vi.visual, valueMask, &a); @@ -406,6 +409,7 @@ void QGLWidget::setContext(QGLContext *context, const QGLContext* shareContext, if (visible) show(); + XFlush(X11->display); d->glcx->setWindowCreated(true); } -- cgit v0.12 From 389ca4b5931efbf2bcac050ec80ec7971b61c857 Mon Sep 17 00:00:00 2001 From: hjk Date: Thu, 28 May 2009 13:17:27 +0200 Subject: Compile fix with namespaces. --- examples/webkit/fancybrowser/mainwindow.h | 2 +- src/corelib/kernel/qsharedmemory_unix.cpp | 2 -- src/gui/graphicsview/qgraphicsitem_p.h | 4 ++-- src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp | 4 ++++ src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h | 4 ++++ src/opengl/gl2paintengineex/qglengineshadermanager.cpp | 4 +++- src/opengl/gl2paintengineex/qglgradientcache.cpp | 4 ++++ src/opengl/gl2paintengineex/qglgradientcache_p.h | 4 +++- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 7 ++++++- src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h | 4 ++++ 10 files changed, 31 insertions(+), 8 deletions(-) diff --git a/examples/webkit/fancybrowser/mainwindow.h b/examples/webkit/fancybrowser/mainwindow.h index 2e1068c..ba0bede 100644 --- a/examples/webkit/fancybrowser/mainwindow.h +++ b/examples/webkit/fancybrowser/mainwindow.h @@ -41,8 +41,8 @@ #include -QT_BEGIN_NAMESPACE class QWebView; +QT_BEGIN_NAMESPACE class QLineEdit; QT_END_NAMESPACE diff --git a/src/corelib/kernel/qsharedmemory_unix.cpp b/src/corelib/kernel/qsharedmemory_unix.cpp index 12f21b7..9187ad3 100644 --- a/src/corelib/kernel/qsharedmemory_unix.cpp +++ b/src/corelib/kernel/qsharedmemory_unix.cpp @@ -51,8 +51,6 @@ #ifndef QT_NO_SHAREDMEMORY -QT_BEGIN_NAMESPACE - #include #include #include diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 62e0411..bd81fe5 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -423,10 +423,10 @@ public: QGraphicsItem *q_ptr; }; -Q_DECLARE_METATYPE(QGraphicsItemPrivate::DecomposedTransform *) - QT_END_NAMESPACE +Q_DECLARE_METATYPE(QGraphicsItemPrivate::DecomposedTransform *) + #endif // QT_NO_GRAPHICSVIEW #endif diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp b/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp index f237847..560ad3a 100644 --- a/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp +++ b/src/opengl/gl2paintengineex/qgl2pexvertexarray.cpp @@ -43,6 +43,8 @@ #include +QT_BEGIN_NAMESPACE + void QGL2PEXVertexArray::clear() { vertexArray.reset(); @@ -160,3 +162,5 @@ void QGL2PEXVertexArray::curveToArray(const QGLPoint &cp1, const QGLPoint &cp2, } } } + +QT_END_NAMESPACE diff --git a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h index 35566ca..d7a9f73 100644 --- a/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h +++ b/src/opengl/gl2paintengineex/qgl2pexvertexarray_p.h @@ -59,6 +59,8 @@ #include #include +QT_BEGIN_NAMESPACE + class QGLPoint { public: @@ -124,4 +126,6 @@ private: inline void curveToArray(const QGLPoint &cp1, const QGLPoint &cp2, const QGLPoint &ep, GLfloat inverseScale); }; +QT_END_NAMESPACE + #endif diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index 514aac0..f64af85 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -47,6 +47,8 @@ #endif +QT_BEGIN_NAMESPACE + const char* QGLEngineShaderManager::qglEngineShaderSourceCode[] = { 0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0, @@ -462,4 +464,4 @@ void QGLEngineShaderManager::compileNamedShader(QGLEngineShaderManager::ShaderNa compiledShaders[name] = newShader; } - +QT_END_NAMESPACE diff --git a/src/opengl/gl2paintengineex/qglgradientcache.cpp b/src/opengl/gl2paintengineex/qglgradientcache.cpp index 2239c2f..f1a8850 100644 --- a/src/opengl/gl2paintengineex/qglgradientcache.cpp +++ b/src/opengl/gl2paintengineex/qglgradientcache.cpp @@ -44,6 +44,8 @@ #include "qglgradientcache_p.h" +QT_BEGIN_NAMESPACE + void QGL2GradientCache::cleanCache() { QGLGradientColorTableHash::const_iterator it = cache.constBegin(); for (; it != cache.constEnd(); ++it) { @@ -180,3 +182,5 @@ void QGL2GradientCache::generateGradientColorTable(const QGradient& gradient, ui // Make sure the last color stop is represented at the end of the table colorTable[size-1] = last_color; } + +QT_END_NAMESPACE diff --git a/src/opengl/gl2paintengineex/qglgradientcache_p.h b/src/opengl/gl2paintengineex/qglgradientcache_p.h index 6acaa00..9bf58c7 100644 --- a/src/opengl/gl2paintengineex/qglgradientcache_p.h +++ b/src/opengl/gl2paintengineex/qglgradientcache_p.h @@ -54,6 +54,8 @@ #include #include +QT_BEGIN_NAMESPACE + class QGL2GradientCache : public QObject { Q_OBJECT @@ -104,5 +106,5 @@ public slots: } }; - +QT_END_NAMESPACE diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 5b33421..338919e 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -80,7 +80,11 @@ #include "qgl2pexvertexarray_p.h" -extern QImage qt_imageForBrush(int brushStyle, bool invert); //in qbrush.cpp +#include + +QT_BEGIN_NAMESPACE + +extern QImage qt_imageForBrush(int brushStyle, bool invert); static const GLuint QT_BRUSH_TEXTURE_UNIT = 0; static const GLuint QT_IMAGE_TEXTURE_UNIT = 0; //Can be the same as brush texture unit @@ -1328,3 +1332,4 @@ QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState() { } +QT_END_NAMESPACE diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index 34ab6b3..ef62390 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -65,6 +65,8 @@ enum EngineMode { BrushDrawingMode }; +QT_BEGIN_NAMESPACE + class QGL2PaintEngineExPrivate; @@ -209,4 +211,6 @@ public: uint use_system_clip : 1; }; +QT_END_NAMESPACE + #endif -- cgit v0.12 From 3331605529d2d81145259fd56d03bb59c480cac5 Mon Sep 17 00:00:00 2001 From: hjk Date: Thu, 28 May 2009 13:18:00 +0200 Subject: Introduce a new class QStringBuilder to speed up the creation of QString objects from smaller chunks. The QStringBuilder class: QStringBuilder uses expression templates (using the '%' operator) to postpone any actual concatenation until it is assigned to an actual QString. At that time it knows the exact sizes of all chunks, can compute the required space, allocates once a QString of appriopriate size and then copies over the chunk data one-by-one. In addition, QLatin1Literal is a drop-in replacement for QLatin1String (which we can't change for compatibility reasons) that knows its size, therefore saving a few cycles when computing the size of the resulting string. Some further saved cycles stem from inlining and reduced reference counting logic (the QString created from a QStringBuilder has typically ref count equal to 1, while QString::append() needs an extra test) Minor changes to the existing QString class: - Introduce QString constructor to create an uninitialized QString of a given size. This particular constructor is used by QStringBuilder class. - Introduce a QT_USE_FAST_CONCATENATION macro to disable the existing overloads of operator+() and helps finding the places where they are used in code. - Introduce QT_USE_FAST_OPERATOR_PLUS. This also disables the existing overloads of operator+() and creates a new templated operator+() with identical implementation of operator%(). This allows code that is compilable QT_CAST_{TO,FROM}_ASCII to use QStringBuilder almost transparently. The only case that is not covered is creating objects like QUrl that are implicitly constructible from a QString from a QStringBuilder result. This needs to be converted explicitly to a QString first, e.g. by using QUrl url(QString(QLatin1String("http://") + hostName)); Reviewed-by: MariusSO --- src/corelib/tools/qstring.cpp | 17 ++ src/corelib/tools/qstring.h | 15 +- src/corelib/tools/qstringbuilder.cpp | 135 +++++++++ src/corelib/tools/qstringbuilder.h | 207 ++++++++++++++ src/corelib/tools/tools.pri | 2 + tests/benchmarks/qstringbuilder/main.cpp | 304 +++++++++++++++++++++ tests/benchmarks/qstringbuilder/qstringbuilder.pro | 12 + 7 files changed, 689 insertions(+), 3 deletions(-) create mode 100644 src/corelib/tools/qstringbuilder.cpp create mode 100644 src/corelib/tools/qstringbuilder.h create mode 100644 tests/benchmarks/qstringbuilder/main.cpp create mode 100644 tests/benchmarks/qstringbuilder/qstringbuilder.pro diff --git a/src/corelib/tools/qstring.cpp b/src/corelib/tools/qstring.cpp index 29509c5..c64e1d6 100644 --- a/src/corelib/tools/qstring.cpp +++ b/src/corelib/tools/qstring.cpp @@ -944,6 +944,23 @@ QString::QString(int size, QChar ch) } } +/*! + Constructs a string of the given \a size without initializing the + characters. This is only used in \c QStringBuilder::toString(). + + \internal +*/ + +QString::QString(int size, Uninitialized) +{ + d = (Data*) qMalloc(sizeof(Data)+size*sizeof(QChar)); + d->ref = 1; + d->alloc = d->size = size; + d->clean = d->asciiCache = d->simpletext = d->righttoleft = d->capacity = 0; + d->data = d->array; + d->array[size] = '\0'; +} + /*! \fn QString::QString(const QLatin1String &str) Constructs a copy of the Latin-1 string \a str. diff --git a/src/corelib/tools/qstring.h b/src/corelib/tools/qstring.h index 69c4f2f..7c0d6a3 100644 --- a/src/corelib/tools/qstring.h +++ b/src/corelib/tools/qstring.h @@ -579,6 +579,9 @@ public: bool isSimpleText() const { if (!d->clean) updateProperties(); return d->simpletext; } bool isRightToLeft() const { if (!d->clean) updateProperties(); return d->righttoleft; } + struct Uninitialized {}; + QString(int size, Uninitialized); + private: #if defined(QT_NO_CAST_FROM_ASCII) && !defined(Q_NO_DECLARED_NOT_DEFINED) QString &operator+=(const char *s); @@ -1001,13 +1004,15 @@ inline int QByteArray::findRev(const QString &s, int from) const # endif // QT3_SUPPORT #endif // QT_NO_CAST_TO_ASCII +#ifndef QT_USE_FAST_OPERATOR_PLUS +# ifndef QT_USE_FAST_CONCATENATION inline const QString operator+(const QString &s1, const QString &s2) { QString t(s1); t += s2; return t; } inline const QString operator+(const QString &s1, QChar s2) { QString t(s1); t += s2; return t; } inline const QString operator+(QChar s1, const QString &s2) { QString t(s1); t += s2; return t; } -#ifndef QT_NO_CAST_FROM_ASCII +# ifndef QT_NO_CAST_FROM_ASCII inline QT_ASCII_CAST_WARN const QString operator+(const QString &s1, const char *s2) { QString t(s1); t += QString::fromAscii(s2); return t; } inline QT_ASCII_CAST_WARN const QString operator+(const char *s1, const QString &s2) @@ -1020,7 +1025,9 @@ inline QT_ASCII_CAST_WARN const QString operator+(const QByteArray &ba, const QS { QString t = QString::fromAscii(ba.constData(), qstrnlen(ba.constData(), ba.size())); t += s; return t; } inline QT_ASCII_CAST_WARN const QString operator+(const QString &s, const QByteArray &ba) { QString t(s); t += QString::fromAscii(ba.constData(), qstrnlen(ba.constData(), ba.size())); return t; } -#endif +# endif // QT_NO_CAST_FROM_ASCII +# endif // QT_USE_FAST_CONCATENATION +#endif // QT_USE_FAST_OPERATOR_PLUS #ifndef QT_NO_STL inline std::string QString::toStdString() const @@ -1229,6 +1236,8 @@ inline int QStringRef::localeAwareCompare(const QStringRef &s1, const QStringRef QT_END_NAMESPACE -QT_END_HEADER +#ifdef QT_USE_FAST_CONCATENATION +#include +#endif #endif // QSTRING_H diff --git a/src/corelib/tools/qstringbuilder.cpp b/src/corelib/tools/qstringbuilder.cpp new file mode 100644 index 0000000..b807a89 --- /dev/null +++ b/src/corelib/tools/qstringbuilder.cpp @@ -0,0 +1,135 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the $MODULE$ of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qstringbuilder.h" + +/*! + \class QLatin1Literal + \reentrant + \since 4.6 + + \brief The QLatin1Literal class provides a thin wrapper around string + literals used in source code. + + \ingroup tools + \ingroup shared + \ingroup text + \mainclass + + Unlike \c QLatin1String, a \c QLatin1Literal can retrieve its size + without iterating over the literal. + + The main use of \c QLatin1Literal is in conjunction with \c QStringBuilder + to reduce the number of reallocations needed to build up a string from + smaller chunks. + + \sa QStringBuilder, QLatin1String, QString, QStringRef +*/ + +/*! \fn QLatin1Literal::QLatin1Literal(const char(&string)[]) + + Constructs a new literal from the given \a string. +*/ + +/*! \fn int QLatin1Literal::size() const + + Returns the number of characters in the literal \i{excluding} the trailing + NUL char. +*/ + +/*! \fn char *QLatin1Literal::data() const + + Returns a pointer to the first character of the string literal. + The string literal is terminated by a NUL character. +*/ + +/*! \fn QLatin1Literal::operator QString() const + + Converts the \c QLatin1Literal into a \c QString object. +*/ + + + +/*! + \class QStringBuilder + \reentrant + \since 4.6 + + \brief QStringBuilder is a template class that provides a facility to build + up QStrings from smaller chunks. + + \ingroup tools + \ingroup shared + \ingroup text + \mainclass + + When creating strings from smaller chunks, typically \c QString::operator+() + is used, resulting in \i{n - 1} reallocations when operating on \i{n} chunks. + + QStringBuilder uses expression templates to collect the individual parts, + compute the total size, allocate memory for the resulting QString object, + and copy the contents of the chunks into the result. + + The QStringBuilder class is not to be used explicitly in user code. + Instances of the class are created as return values of the operator%() + function, acting on objects of type \c QString, \c QLatin1String, + \c QLatin1Literal, \c \QStringRef, \c QChar, + \c QLatin1Char, and \c char. + + Concatenating strings with operator%() generally yields better + performance then using \c QString::operator+() on the same chunks + if there are three or more of them, and performs equally well in other + cases. + + \sa QLatin1Literal, QString +*/ + +/* !fn template QStringBuilder operator%(const A &a, const B &b) + + Returns a \c QStringBuilder object that is converted to a QString object + when assigned to a variable of QString type or passed to a function that + takes a QString parameter. + + This function is usable with arguments of type \c QString, + \c QLatin1String, \c QLatin1Literal, \c QStringRef, + \c QChar, \c QLatin1Char, and \c char. +*/ + diff --git a/src/corelib/tools/qstringbuilder.h b/src/corelib/tools/qstringbuilder.h new file mode 100644 index 0000000..1e67b7d --- /dev/null +++ b/src/corelib/tools/qstringbuilder.h @@ -0,0 +1,207 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the $MODULE$ of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** Commercial Usage +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QSTRINGBUILDER_H +#define QSTRINGBUILDER_H + +#include + +#include + +QT_BEGIN_HEADER + +QT_BEGIN_NAMESPACE + +QT_MODULE(Core) + +// ### Qt 5: merge with QLatin1String +class QLatin1Literal +{ +public: + template + QLatin1Literal(const char (&str)[N]) : m_size(N - 1), m_data(str) {} + + inline int size() const { return m_size; } + inline const char *data() const { return m_data; } + +private: + const int m_size; + const char *m_data; +}; + + +template class QConcatenable {}; + +template +class QStringBuilder +{ +public: + QStringBuilder(const A &a_, const B &b_) : a(a_), b(b_) {} + + operator QString() const + { + QString s(QConcatenable< QStringBuilder >::size(*this), + QString::Uninitialized()); + + QChar *d = s.data(); + QConcatenable< QStringBuilder >::appendTo(*this, d); + return s; + } + QByteArray toLatin1() const { return QString(*this).toLatin1(); } + + const A &a; + const B &b; +}; + + +template <> struct QConcatenable +{ + typedef char type; + static int size(const char) { return 1; } + static inline void appendTo(const char c, QChar *&out) + { + *out++ = QLatin1Char(c); + } +}; + +template <> struct QConcatenable +{ + typedef QLatin1Char type; + static int size(const QLatin1Char) { return 1; } + static inline void appendTo(const QLatin1Char c, QChar *&out) + { + *out++ = c; + } +}; + +template <> struct QConcatenable +{ + typedef QChar type; + static int size(const QChar) { return 1; } + static inline void appendTo(const QChar c, QChar *&out) + { + *out++ = c; + } +}; + +template <> struct QConcatenable +{ + typedef QLatin1String type; + static int size(const QLatin1String &a) { return qstrlen(a.latin1()); } + static inline void appendTo(const QLatin1String &a, QChar *&out) + { + for (const char *s = a.latin1(); *s; ) + *out++ = QLatin1Char(*s++); + } + +}; + +template <> struct QConcatenable +{ + typedef QLatin1Literal type; + static int size(const QLatin1Literal &a) { return a.size(); } + static inline void appendTo(const QLatin1Literal &a, QChar *&out) + { + for (const char *s = a.data(); *s; ) + *out++ = QLatin1Char(*s++); + } +}; + +template <> struct QConcatenable +{ + typedef QString type; + static int size(const QString &a) { return a.size(); } + static inline void appendTo(const QString &a, QChar *&out) + { + const int n = a.size(); + memcpy(out, (char*)a.constData(), sizeof(QChar) * n); + out += n; + } +}; + +template <> struct QConcatenable +{ + typedef QStringRef type; + static int size(const QStringRef &a) { return a.size(); } + static inline void appendTo(QStringRef a, QChar *&out) + { + const int n = a.size(); + memcpy(out, (char*)a.constData(), sizeof(QChar) * n); + out += n; + } +}; + +template +struct QConcatenable< QStringBuilder > +{ + typedef QStringBuilder type; + static int size(const type &p) + { + return QConcatenable::size(p.a) + QConcatenable::size(p.b); + } + static inline void appendTo(const QStringBuilder &p, QChar *&out) + { + QConcatenable::appendTo(p.a, out); + QConcatenable::appendTo(p.b, out); + } +}; + +template +QStringBuilder::type, typename QConcatenable::type> +operator%(const A &a, const B &b) +{ + return QStringBuilder(a, b); +} + +#ifdef QT_USE_FAST_OPERATOR_PLUS +template +QStringBuilder::type, typename QConcatenable::type> +operator+(const A &a, const B &b) +{ + return QStringBuilder(a, b); +} +#endif + +QT_END_NAMESPACE + +QT_END_HEADER + +#endif // QSTRINGBUILDER_H diff --git a/src/corelib/tools/tools.pri b/src/corelib/tools/tools.pri index 90287cb..aea0c6c 100644 --- a/src/corelib/tools/tools.pri +++ b/src/corelib/tools/tools.pri @@ -32,6 +32,7 @@ HEADERS += \ tools/qsize.h \ tools/qstack.h \ tools/qstring.h \ + tools/qstringbuilder.h \ tools/qstringlist.h \ tools/qstringmatcher.h \ tools/qtextboundaryfinder.h \ @@ -62,6 +63,7 @@ SOURCES += \ tools/qsharedpointer.cpp \ tools/qsize.cpp \ tools/qstring.cpp \ + tools/qstringbuilder.cpp \ tools/qstringlist.cpp \ tools/qtextboundaryfinder.cpp \ tools/qtimeline.cpp \ diff --git a/tests/benchmarks/qstringbuilder/main.cpp b/tests/benchmarks/qstringbuilder/main.cpp new file mode 100644 index 0000000..cb76925 --- /dev/null +++ b/tests/benchmarks/qstringbuilder/main.cpp @@ -0,0 +1,304 @@ + +#include "qstringbuilder.h" + +#include +#include + +#include + + +#define COMPARE(a, b) QCOMPARE(a, b) +//#define COMPARE(a, b) + +#define SEP(s) qDebug() << "\n\n-------- " s " ---------"; +#define L(s) QLatin1String(s) + +class tst_qstringbuilder : public QObject +{ + Q_OBJECT + +public: + tst_qstringbuilder() + : l1literal("some string literal"), + l1string("some string literal"), + ba("some string literal"), + string(l1string), + stringref(&string, 2, 10), + achar('c') + {} + + +public: + enum { N = 10000 }; + + int run_traditional() + { + int s = 0; + for (int i = 0; i < N; ++i) { +#if 0 + s += QString(l1string + l1string).size(); + s += QString(l1string + l1string + l1string).size(); + s += QString(l1string + l1string + l1string + l1string).size(); + s += QString(l1string + l1string + l1string + l1string + l1string).size(); +#endif + s += QString(achar + l1string + achar).size(); + } + return s; + } + + int run_builder() + { + int s = 0; + for (int i = 0; i < N; ++i) { +#if 0 + s += QString(l1literal % l1literal).size(); + s += QString(l1literal % l1literal % l1literal).size(); + s += QString(l1literal % l1literal % l1literal % l1literal).size(); + s += QString(l1literal % l1literal % l1literal % l1literal % l1literal).size(); +#endif + s += QString(achar % l1literal % achar).size(); + } + return s; + } + +private slots: + + void separator_0() { + qDebug() << "\nIn each block the QStringBuilder based result appear first, " + "QStringBased second.\n"; + } + + void separator_1() { SEP("literal + literal (builder first)"); } + + void b_2_l1literal() { + QBENCHMARK { r = l1literal % l1literal; } + COMPARE(r, l1string + l1string); + } + void s_2_l1string() { + QBENCHMARK { r = l1string + l1string; } + COMPARE(r, QString(l1literal % l1literal)); + } + + + void separator_2() { SEP("2 strings"); } + + void b_2_string() { + QBENCHMARK { r = string % string; } + COMPARE(r, string + string); + } + void s_2_string() { + QBENCHMARK { r = string + string; } + COMPARE(r, QString(string % string)); + } + + + void separator_2c() { SEP("2 string refs"); } + + void b_2_stringref() { + QBENCHMARK { r = stringref % stringref; } + COMPARE(r, stringref.toString() + stringref.toString()); + } + void s_2_stringref() { + QBENCHMARK { r = stringref.toString() + stringref.toString(); } + COMPARE(r, QString(stringref % stringref)); + } + + + void separator_2b() { SEP("3 strings"); } + + void b_3_string() { + QBENCHMARK { r = string % string % string; } + COMPARE(r, string + string + string); + } + void s_3_string() { + QBENCHMARK { r = string + string + string; } + COMPARE(r, QString(string % string % string)); + } + + + void separator_2a() { SEP("string + literal (builder first)"); } + + void b_string_l1literal() { + QBENCHMARK { r = string % l1literal; } + COMPARE(r, string + l1string); + } + void b_string_l1string() { + QBENCHMARK { r = string % l1string; } + COMPARE(r, string + l1string); + } + void s_string_l1literal() { + QBENCHMARK { r = string + l1string; } + COMPARE(r, QString(string % l1literal)); + } + void s_string_l1string() { + QBENCHMARK { r = string + l1string; } + COMPARE(r, QString(string % l1literal)); + } + + + void separator_3() { SEP("3 literals"); } + + void b_3_l1literal() { + QBENCHMARK { r = l1literal % l1literal % l1literal; } + COMPARE(r, l1string + l1string + l1string); + } + void s_3_l1string() { + QBENCHMARK { r = l1string + l1string + l1string; } + COMPARE(r, QString(l1literal % l1literal % l1literal)); + } + + + void separator_4() { SEP("4 literals"); } + + void b_4_l1literal() { + QBENCHMARK { r = l1literal % l1literal % l1literal % l1literal; } + COMPARE(r, l1string + l1string + l1string + l1string); + } + void s_4_l1string() { + QBENCHMARK { r = l1string + l1string + l1string + l1string; } + COMPARE(r, QString(l1literal % l1literal % l1literal % l1literal)); + } + + + void separator_5() { SEP("5 literals"); } + + void b_5_l1literal() { + QBENCHMARK { r = l1literal % l1literal % l1literal % l1literal %l1literal; } + COMPARE(r, l1string + l1string + l1string + l1string + l1string); + } + + void s_5_l1string() { + QBENCHMARK { r = l1string + l1string + l1string + l1string + l1string; } + COMPARE(r, QString(l1literal % l1literal % l1literal % l1literal % l1literal)); + } + + + void separator_6() { SEP("4 chars"); } + + void b_string_4_char() { + QBENCHMARK { r = string + achar + achar + achar + achar; } + COMPARE(r, QString(string % achar % achar % achar % achar)); + } + + void s_string_4_char() { + QBENCHMARK { r = string + achar + achar + achar + achar; } + COMPARE(r, QString(string % achar % achar % achar % achar)); + } + + + void separator_7() { SEP("char + string + char"); } + + void b_char_string_char() { + QBENCHMARK { r = achar + string + achar; } + COMPARE(r, QString(achar % string % achar)); + } + + void s_char_string_char() { + QBENCHMARK { r = achar + string + achar; } + COMPARE(r, QString(achar % string % achar)); + } + + void separator_8() { SEP("string.arg"); } + + void b_string_arg() { + const QString pattern = l1string + "%1" + l1string; + QBENCHMARK { r = l1literal % string % l1literal; } + COMPARE(r, l1string + string + l1string); + } + + void s_string_arg() { + const QString pattern = l1string + "%1" + l1string; + QBENCHMARK { r = pattern.arg(string); } + COMPARE(r, l1string + string + l1string); + } + + void s_bytearray_arg() { + QByteArray result; + QBENCHMARK { result = ba + ba + ba; } + } + + + void separator_9() { SEP("QString::reserve()"); } + + void b_reserve() { + QBENCHMARK { + r.clear(); + r = string % string % string % string; + } + COMPARE(r, string + string + string + string); + } + void b_reserve_lit() { + QBENCHMARK { + r.clear(); + r = string % l1literal % string % string; + } + COMPARE(r, string + string + string + string); + } + void s_reserve() { + QBENCHMARK { + r.clear(); + r.reserve(string.size() + string.size() + string.size() + string.size()); + r += string; + r += string; + r += string; + r += string; + } + COMPARE(r, string + string + string + string); + } + void s_reserve_lit() { + QBENCHMARK { + r.clear(); + //r.reserve(string.size() + qstrlen(l1string.latin1()) + // + string.size() + string.size()); + r.reserve(1024); + r += string; + r += l1string; + r += string; + r += string; + } + COMPARE(r, string + string + string + string); + } + +private: + const QLatin1Literal l1literal; + const QLatin1String l1string; + const QByteArray ba; + const QString string; + const QStringRef stringref; + const QLatin1Char achar; + + QString r; +}; + + +//void operator%(QString, int) {} + +int main(int argc, char *argv[]) +{ + //qDebug() << (QString("xx") * QLatin1String("y")).toString(); + //42 % 3; // Sanity test, should always work. + //QString("x") % 2; // Sanity test, should only compile when the + // operator%(QString, int) is visible. + + if (argc == 2 && (argv[1] == L("--run-builder") || argv[1] == L("-b"))) { + tst_qstringbuilder test; + return test.run_builder(); + } + + if (argc == 2 && (argv[1] == L("--run-traditional") || argv[1] == L("-t"))) { + tst_qstringbuilder test; + return test.run_traditional(); + } + + if (argc == 1) { + QCoreApplication app(argc, argv); + QStringList args = app.arguments(); + tst_qstringbuilder test; + return QTest::qExec(&test, argc, argv); + } + + qDebug() << "Usage: " << argv[0] << " [--run-builder|-r|--run-traditional|-t]"; +} + + +#include "main.moc" diff --git a/tests/benchmarks/qstringbuilder/qstringbuilder.pro b/tests/benchmarks/qstringbuilder/qstringbuilder.pro new file mode 100644 index 0000000..79171b4 --- /dev/null +++ b/tests/benchmarks/qstringbuilder/qstringbuilder.pro @@ -0,0 +1,12 @@ +load(qttest_p4) +TEMPLATE = app +TARGET = tst_qstringbuilder + +QMAKE_CXXFLAGS += -g +QMAKE_CFLAGS += -g + +QT -= gui + +CONFIG += release + +SOURCES += main.cpp -- cgit v0.12 From 8ed5931925b4e8ed8f098b5c36e1378f95d7d25a Mon Sep 17 00:00:00 2001 From: Eskil Abrahamsen Blomfeldt Date: Thu, 28 May 2009 13:40:59 +0200 Subject: BT: Support saving forms with resources more than once in Qt Jambi When a form is loaded, Designer will set the path to the resource as an absolute path rather than the path actually stored in the file. There is code to work around this to make file paths relative when saving the file later on, but no work around for Qt Jambi. So when saving Qt Jambi forms, you would get an absolute path to the resource which contains the location of the resource file (.jar or on disk) This of course breaks the concept of resources, as the .jui file was no longer portable. The fix is to special case Qt Jambi resources and set the relative path when loading them. The patch has no effect on regular Designer. Task-number: 254621 Reviewed-by: Kai Koehne --- .../components/formeditor/qdesigner_resource.cpp | 34 ++++++++++++++-------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/tools/designer/src/components/formeditor/qdesigner_resource.cpp b/tools/designer/src/components/formeditor/qdesigner_resource.cpp index 75a53b7..064da9b 100644 --- a/tools/designer/src/components/formeditor/qdesigner_resource.cpp +++ b/tools/designer/src/components/formeditor/qdesigner_resource.cpp @@ -159,6 +159,7 @@ private: QDesignerFormEditorInterface *m_core; DesignerPixmapCache *m_pixmapCache; DesignerIconCache *m_iconCache; + const QDesignerLanguageExtension *m_lang; bool m_saveRelative; mutable QMap m_usedQrcFiles; mutable QMap m_loadedQrcFiles; @@ -168,13 +169,18 @@ QDesignerResourceBuilder::QDesignerResourceBuilder(QDesignerFormEditorInterface m_core(core), m_pixmapCache(pixmapCache), m_iconCache(iconCache), + m_lang(qt_extension(core->extensionManager(), core)), m_saveRelative(true) { } -static inline void setIconPixmap(QIcon::Mode m, QIcon::State s, const QDir &workingDirectory, const QString &v, PropertySheetIconValue &icon) +static inline void setIconPixmap(QIcon::Mode m, QIcon::State s, const QDir &workingDirectory, + QString path, PropertySheetIconValue &icon, + const QDesignerLanguageExtension *lang = 0) { - icon.setPixmap(m, s, PropertySheetPixmapValue(QFileInfo(workingDirectory, v).absoluteFilePath())); + if (lang == 0 || !lang->isLanguageResource(path)) + path = QFileInfo(workingDirectory, path).absoluteFilePath(); + icon.setPixmap(m, s, PropertySheetPixmapValue(path)); } QVariant QDesignerResourceBuilder::loadResource(const QDir &workingDirectory, const DomProperty *property) const @@ -184,7 +190,11 @@ QVariant QDesignerResourceBuilder::loadResource(const QDir &workingDirectory, co PropertySheetPixmapValue pixmap; DomResourcePixmap *dp = property->elementPixmap(); if (!dp->text().isEmpty()) { - pixmap.setPath(QFileInfo(workingDirectory, dp->text()).absoluteFilePath()); + if (m_lang != 0 && m_lang->isLanguageResource(dp->text())) { + pixmap.setPath(dp->text()); + } else { + pixmap.setPath(QFileInfo(workingDirectory, dp->text()).absoluteFilePath()); + } #ifdef OLD_RESOURCE_FORMAT if (dp->hasAttributeResource()) m_loadedQrcFiles.insert(QFileInfo(workingDirectory, dp->attributeResource()).absoluteFilePath(), false); @@ -198,24 +208,24 @@ QVariant QDesignerResourceBuilder::loadResource(const QDir &workingDirectory, co DomResourceIcon *di = property->elementIconSet(); if (const int flags = iconStateFlags(di)) { // new, post 4.4 format if (flags & NormalOff) - setIconPixmap(QIcon::Normal, QIcon::Off, workingDirectory, di->elementNormalOff()->text(), icon); + setIconPixmap(QIcon::Normal, QIcon::Off, workingDirectory, di->elementNormalOff()->text(), icon, m_lang); if (flags & NormalOn) - setIconPixmap(QIcon::Normal, QIcon::On, workingDirectory, di->elementNormalOn()->text(), icon); + setIconPixmap(QIcon::Normal, QIcon::On, workingDirectory, di->elementNormalOn()->text(), icon, m_lang); if (flags & DisabledOff) - setIconPixmap(QIcon::Disabled, QIcon::Off, workingDirectory, di->elementDisabledOff()->text(), icon); + setIconPixmap(QIcon::Disabled, QIcon::Off, workingDirectory, di->elementDisabledOff()->text(), icon, m_lang); if (flags & DisabledOn) - setIconPixmap(QIcon::Disabled, QIcon::On, workingDirectory, di->elementDisabledOn()->text(), icon); + setIconPixmap(QIcon::Disabled, QIcon::On, workingDirectory, di->elementDisabledOn()->text(), icon, m_lang); if (flags & ActiveOff) - setIconPixmap(QIcon::Active, QIcon::Off, workingDirectory, di->elementActiveOff()->text(), icon); + setIconPixmap(QIcon::Active, QIcon::Off, workingDirectory, di->elementActiveOff()->text(), icon, m_lang); if (flags & ActiveOn) - setIconPixmap(QIcon::Active, QIcon::On, workingDirectory, di->elementActiveOn()->text(), icon); + setIconPixmap(QIcon::Active, QIcon::On, workingDirectory, di->elementActiveOn()->text(), icon, m_lang); if (flags & SelectedOff) - setIconPixmap(QIcon::Selected, QIcon::Off, workingDirectory, di->elementSelectedOff()->text(), icon); + setIconPixmap(QIcon::Selected, QIcon::Off, workingDirectory, di->elementSelectedOff()->text(), icon, m_lang); if (flags & SelectedOn) - setIconPixmap(QIcon::Selected, QIcon::On, workingDirectory, di->elementSelectedOn()->text(), icon); + setIconPixmap(QIcon::Selected, QIcon::On, workingDirectory, di->elementSelectedOn()->text(), icon, m_lang); } else { #ifdef OLD_RESOURCE_FORMAT - setIconPixmap(QIcon::Normal, QIcon::Off, workingDirectory, di->text(), icon); + setIconPixmap(QIcon::Normal, QIcon::Off, workingDirectory, di->text(), icon, m_lang); if (di->hasAttributeResource()) m_loadedQrcFiles.insert(QFileInfo(workingDirectory, di->attributeResource()).absoluteFilePath(), false); #endif -- cgit v0.12 From 6b75c19e42cd7ffd6d8c0716aa9b1251be28b3e7 Mon Sep 17 00:00:00 2001 From: Robert Griebl Date: Thu, 28 May 2009 13:59:36 +0200 Subject: Forgot to close the TTY handle. Reviewed-by: TrustMe --- src/gui/embedded/qkbdtty_qws.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gui/embedded/qkbdtty_qws.cpp b/src/gui/embedded/qkbdtty_qws.cpp index 5c0dec8..31489cf 100644 --- a/src/gui/embedded/qkbdtty_qws.cpp +++ b/src/gui/embedded/qkbdtty_qws.cpp @@ -209,6 +209,7 @@ QWSTtyKbPrivate::~QWSTtyKbPrivate() ::ioctl(m_tty_fd, KDSKBMODE, K_XLATE); #endif tcsetattr(m_tty_fd, TCSANOW, &m_tty_attr); + QT_CLOSE(m_tty_fd); } } -- cgit v0.12 From 27d979b0ea39922e6e2ae3a3cc6a4d45c9c8f0e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 28 May 2009 13:45:42 +0200 Subject: Fixed incorrect handling of composition modes in GL2 paint engine. Even if the source pixels are opaque we have to enable blending for the non-trivial composition modes. Some of the composition modes are independent of source alpha and depend on destination alpha for example. Reviewed-by: Tom --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 31 +++++++--------------- .../gl2paintengineex/qpaintengineex_opengl2_p.h | 2 +- 2 files changed, 11 insertions(+), 22 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 338919e..75422a2 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -425,7 +425,7 @@ static inline void setCoords(GLfloat *coords, const QGLRect &rect) coords[7] = rect.bottom; } -void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize) +void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque) { transferMode(ImageDrawingMode); @@ -434,7 +434,7 @@ void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& s // Setup for texture drawing shaderManager->setSrcPixelType(QGLEngineShaderManager::ImageSrc); shaderManager->setTextureCoordsEnabled(true); - prepareForDraw(false); // ### + prepareForDraw(opaque); shaderManager->currentProgram()->setUniformValue("imageTexture", QT_IMAGE_TEXTURE_UNIT); @@ -634,11 +634,12 @@ void QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque) updateMatrix(); const bool stateHasOpacity = q->state()->opacity < 0.99f; - if ( (!srcPixelsAreOpaque || stateHasOpacity) && - q->state()->compositionMode() != QPainter::CompositionMode_Source) - glEnable(GL_BLEND); - else + if (q->state()->compositionMode() == QPainter::CompositionMode_Source + || (q->state()->compositionMode() == QPainter::CompositionMode_SourceOver + && srcPixelsAreOpaque && !stateHasOpacity)) glDisable(GL_BLEND); + else + glEnable(GL_BLEND); bool useGlobalOpacityUniform = stateHasOpacity; if (stateHasOpacity && (mode != ImageDrawingMode)) { @@ -822,12 +823,7 @@ void QGL2PaintEngineEx::drawPixmap(const QRectF& dest, const QPixmap & pixmap, c ctx->d_func()->bindTexture(pixmap, GL_TEXTURE_2D, GL_RGBA, true); //FIXME: we should use hasAlpha() instead, but that's SLOW at the moment - if ((state()->opacity < 0.99f) || pixmap.hasAlphaChannel()) - glEnable(GL_BLEND); - else - glDisable(GL_BLEND); - - d->drawTexture(dest, src, pixmap.size()); + d->drawTexture(dest, src, pixmap.size(), !pixmap.hasAlphaChannel()); } void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const QRectF& src, @@ -841,12 +837,7 @@ void QGL2PaintEngineEx::drawImage(const QRectF& dest, const QImage& image, const glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT); ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); - if ((state()->opacity < 0.99f) || image.hasAlphaChannel()) - glEnable(GL_BLEND); - else - glDisable(GL_BLEND); - - d->drawTexture(dest, src, image.size()); + d->drawTexture(dest, src, image.size(), !image.hasAlphaChannel()); } void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem) @@ -1022,10 +1013,8 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) source->bind(false); - glDisable(GL_BLEND); - QRect rect(0, 0, source->width(), source->height()); - d->drawTexture(QRectF(rect), QRectF(rect), rect.size()); + d->drawTexture(QRectF(rect), QRectF(rect), rect.size(), true); } updateClipRegion(QRegion(), Qt::NoClip); diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index ef62390..dececa3 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -159,7 +159,7 @@ public: // fill, drawOutline, drawTexture & drawCachedGlyphs are the rendering entry points: void fill(const QVectorPath &path); void drawOutline(const QVectorPath& path); - void drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize); + void drawTexture(const QGLRect& dest, const QGLRect& src, const QSize &textureSize, bool opaque); void drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti); void drawVertexArrays(QGL2PEXVertexArray& vertexArray, GLenum primitive); -- cgit v0.12 From 353afc392b843519023f27753b45b2e6fd9467ff Mon Sep 17 00:00:00 2001 From: Tom Cooksey Date: Thu, 28 May 2009 13:11:29 +0200 Subject: Don't assume the tty was in K_XLATE when application started Instead, query the mode at startup, store it and restore it on exit. Reviewed-By: TrustMe Task-number: 254194 --- src/gui/embedded/qkbdtty_qws.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gui/embedded/qkbdtty_qws.cpp b/src/gui/embedded/qkbdtty_qws.cpp index b588e55..7c162bc 100644 --- a/src/gui/embedded/qkbdtty_qws.cpp +++ b/src/gui/embedded/qkbdtty_qws.cpp @@ -97,6 +97,7 @@ private slots: private: QWSPC101KeyboardHandler *handler; struct termios origTermData; + int originalKbdMode; }; QWSTtyKeyboardHandler::QWSTtyKeyboardHandler(const QString &device) @@ -156,6 +157,7 @@ QWSTtyKbPrivate::QWSTtyKbPrivate(QWSPC101KeyboardHandler *h, const QString &devi tcgetattr(kbdFD, &termdata); #if defined(Q_OS_LINUX) + ioctl(kbdFD, KDGKBMODE, &originalKbdMode); # ifdef QT_QWS_USE_KEYCODES ioctl(kbdFD, KDSKBMODE, K_MEDIUMRAW); # else @@ -202,7 +204,7 @@ QWSTtyKbPrivate::~QWSTtyKbPrivate() { if (kbdFD >= 0) { #if defined(Q_OS_LINUX) - ioctl(kbdFD, KDSKBMODE, K_XLATE); + ioctl(kbdFD, KDSKBMODE, originalKbdMode); #endif tcsetattr(kbdFD, TCSANOW, &origTermData); ::close(kbdFD); -- cgit v0.12 From eb54435ac5717c854d6c737bca19ae23c00da045 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Thu, 28 May 2009 14:33:52 +0200 Subject: Removed dead code ifdefed with QDOC2DOX These changes were added to qdoc in the days when we thought we might switch to doxygen. Now we have taken the approach of making qdoc output be more doxygen-like, so this ifdefed code is now dead. --- tools/qdoc3/codeparser.cpp | 13 - tools/qdoc3/cppcodeparser.cpp | 22 - tools/qdoc3/doc.cpp | 1980 +---------------------------------------- tools/qdoc3/doc.h | 177 ---- tools/qdoc3/main.cpp | 50 -- 5 files changed, 2 insertions(+), 2240 deletions(-) diff --git a/tools/qdoc3/codeparser.cpp b/tools/qdoc3/codeparser.cpp index 9a58bc6..f0ff27e 100644 --- a/tools/qdoc3/codeparser.cpp +++ b/tools/qdoc3/codeparser.cpp @@ -241,19 +241,6 @@ void CodeParser::processCommonMetaCommand(const Location &location, if (node->type() == Node::Fake) { FakeNode *fake = static_cast(node); fake->setTitle(arg); -#ifdef QDOC2DOX - /* qdoc -> doxygen. - I think this must be done here, because there can be multiple - "\externalpage" and "\title" metacommands in a single qdoc - comment, which means, among other things, that the "\title" - commands are not inserted into the metacommand map used by - the Doc class. I'm sure there4 is a better way to do this in - the DoxWriter class using the information in the FakeNode, - but I don't have time to figure it out right now. - */ - if (DoxWriter::isDoxPass(1)) - DoxWriter::insertTitle(fake,arg); -#endif } else location.warning(tr("Ignored '\\%1'").arg(COMMAND_TITLE)); diff --git a/tools/qdoc3/cppcodeparser.cpp b/tools/qdoc3/cppcodeparser.cpp index 1ad5843..8baef0c 100644 --- a/tools/qdoc3/cppcodeparser.cpp +++ b/tools/qdoc3/cppcodeparser.cpp @@ -589,22 +589,6 @@ Node *CppCodeParser::processTopicCommand(const Doc& doc, // ### split(" ") hack is there to support header file syntax QStringList paths = arg.split(" "); QStringList path = paths[0].split("::"); - -#if QDOC2DOX - // qdoc -> doxygen. - if (Doc::isDoxPass(1)) { - if (command == COMMAND_PROPERTY) { - Doc::insertProperty(path); - } - else if (command == COMMAND_VARIABLE) { - Doc::insertVariable(path); - } - else if (command == COMMAND_ENUM) { - // zzz - } - } -#endif - Node *node = 0; if (!usedNamespaces.isEmpty()) { foreach (const QString &usedNamespace, usedNamespaces) { @@ -1753,12 +1737,6 @@ bool CppCodeParser::matchDocsAndStuff() readToken(); Doc::trimCStyleComment(start_loc,comment); - /* - qdoc --> doxygen - We must also remember the location of the end - of the comment, so we can construct a diff for - it. - */ Location end_loc(location()); /* diff --git a/tools/qdoc3/doc.cpp b/tools/qdoc3/doc.cpp index 397fbfa..f0a4c12 100644 --- a/tools/qdoc3/doc.cpp +++ b/tools/qdoc3/doc.cpp @@ -515,14 +515,7 @@ void DocParser::parse(const QString& source, break; case CMD_BADCODE: leavePara(); -#ifdef QDOC2DOX - if (DoxWriter::isDoxPass()) - append(Atom::CodeBad,getUnmarkedCode(CMD_BADCODE)); - else - append(Atom::CodeBad,getCode(CMD_BADCODE, marker)); -#else append(Atom::CodeBad,getCode(CMD_BADCODE, marker)); -#endif break; case CMD_BASENAME: leavePara(); @@ -538,17 +531,8 @@ void DocParser::parse(const QString& source, case CMD_C: enterPara(); x = untabifyEtc(getArgument(true)); -#ifdef QDOC2DOX - if (DoxWriter::isDoxPass()) - append(Atom::C, x); - else { - marker = CodeMarker::markerForCode(x); - append(Atom::C, marker->markedUpCode(x, 0, "")); - } -#else marker = CodeMarker::markerForCode(x); append(Atom::C, marker->markedUpCode(x, 0, "")); -#endif break; case CMD_CAPTION: leavePara(); @@ -559,14 +543,7 @@ void DocParser::parse(const QString& source, break; case CMD_CODE: leavePara(); -#ifdef QDOC2DOX - if (DoxWriter::isDoxPass()) - append(Atom::Code, getUnmarkedCode(CMD_CODE)); - else - append(Atom::Code, getCode(CMD_CODE, marker)); -#else append(Atom::Code, getCode(CMD_CODE, marker)); -#endif break; #ifdef QDOC_QML case CMD_QML: @@ -579,17 +556,6 @@ void DocParser::parse(const QString& source, #endif case CMD_CODELINE: { -#ifdef QDOC2DOX - if (!quoting && !DoxWriter::isDoxPass()) { - if (priv->text.lastAtom()->type() == Atom::Code - && priv->text.lastAtom()->string().endsWith("\n\n")) - priv->text.lastAtom()->chopString(); - appendToCode("\n"); - } lse { - append(Atom::CodeQuoteCommand, cmdStr); - append(Atom::CodeQuoteArgument, " "); - } -#else if (!quoting) { if (priv->text.lastAtom()->type() == Atom::Code && priv->text.lastAtom()->string().endsWith("\n\n")) @@ -600,37 +566,10 @@ void DocParser::parse(const QString& source, append(Atom::CodeQuoteCommand, cmdStr); append(Atom::CodeQuoteArgument, " "); } -#endif } break; case CMD_DOTS: { -#ifdef QDOC2DOX - if (DoxWriter::isDoxPass()) { - append(Atom::CodeQuoteCommand, cmdStr); - append(Atom::CodeQuoteArgument, " ..."); - } - else if (!quoting) { - if (priv->text.lastAtom()->type() == Atom::Code - && priv->text.lastAtom()->string().endsWith("\n\n")) - priv->text.lastAtom()->chopString(); - - QString arg = getOptionalArgument(); - int indent = 4; - if (!arg.isEmpty()) - indent = arg.toInt(); - for (int i = 0; i < indent; ++i) - appendToCode(" "); - appendToCode("...\n"); - } - else { - append(Atom::CodeQuoteCommand, cmdStr); - QString arg = getOptionalArgument(); - if (arg.isEmpty()) - arg = "4"; - append(Atom::CodeQuoteArgument, arg); - } -#else if (!quoting) { if (priv->text.lastAtom()->type() == Atom::Code && priv->text.lastAtom()->string().endsWith("\n\n")) @@ -651,7 +590,6 @@ void DocParser::parse(const QString& source, arg = "4"; append(Atom::CodeQuoteArgument, arg); } -#endif } break; case CMD_ELSE: @@ -953,19 +891,8 @@ void DocParser::parse(const QString& source, break; case CMD_OLDCODE: leavePara(); -#ifdef QDOC2DOX - if (DoxWriter::isDoxPass()) { - append(Atom::CodeOld, getUnmarkedCode(CMD_OLDCODE)); - append(Atom::CodeNew, getUnmarkedCode(CMD_NEWCODE)); - } - else { - append(Atom::CodeOld, getCode(CMD_OLDCODE, marker)); - append(Atom::CodeNew, getCode(CMD_NEWCODE, marker)); - } -#else append(Atom::CodeOld, getCode(CMD_OLDCODE, marker)); append(Atom::CodeNew, getCode(CMD_NEWCODE, marker)); -#endif break; case CMD_OMIT: getUntilEnd(cmd); @@ -1147,18 +1074,6 @@ void DocParser::parse(const QString& source, { QString snippet = getArgument(); QString identifier = getRestOfLine(); -#ifdef QDOC2DOX - if (quoting || DoxWriter::isDoxPass()) { - append(Atom::SnippetCommand, cmdStr); - append(Atom::SnippetLocation, snippet); - append(Atom::SnippetIdentifier, identifier); - } - else { - Doc::quoteFromFile(location(),quoter,snippet); - appendToCode(quoter.quoteSnippet(location(), - identifier)); - } -#else if (quoting) { append(Atom::SnippetCommand, cmdStr); append(Atom::SnippetLocation, snippet); @@ -1169,7 +1084,6 @@ void DocParser::parse(const QString& source, appendToCode(quoter.quoteSnippet(location(), identifier)); } -#endif } break; case CMD_SUB: @@ -1251,7 +1165,7 @@ void DocParser::parse(const QString& source, append(Atom::FormattingRight, ATOM_FORMATTING_BOLD); append(Atom::String, " "); break; - case CMD_OVERLOAD: // qdoc --> doxygen + case CMD_OVERLOAD: priv->metacommandsUsed.insert(cmdStr); x.clear(); if (!isBlankLine()) @@ -2343,7 +2257,7 @@ QString DocParser::getCode(int cmd, CodeMarker *marker) } /*! - Used only for generating doxygen output. + Was used only for generating doxygen output. */ QString DocParser::getUnmarkedCode(int cmd) { @@ -2579,36 +2493,6 @@ QString DocParser::slashed(const QString& str) #define COMMAND_QMLBRIEF Doc::alias("qmlbrief") #endif -#ifdef QDOC2DOX -#define DOXYGEN_INDENT 2 -#define DOXYGEN_TAB_SIZE 4 -#define DOXYGEN_INDENT_STRING " " -#define DOXYGEN_TAB_STRING " " - -static QRegExp ws_rx("\\s"); -static QRegExp not_ws_rx("\\S"); - -int DoxWriter::doxPass = 0; -QString DoxWriter::currentClass; -QSet DoxWriter::anchors; -QStringMap DoxWriter::exampleTitles; -QStringMap DoxWriter::headerFileTitles; -QStringMap DoxWriter::fileTitles; -QStringMap DoxWriter::groupTitles; -QStringMap DoxWriter::moduleTitles; -QStringMap DoxWriter::pageTitles; -QStringMap DoxWriter::externalPageTitles; -QStringMap DoxWriter::exampleTitlesInverse; -QStringMap DoxWriter::headerFileTitlesInverse; -QStringMap DoxWriter::fileTitlesInverse; -QStringMap DoxWriter::groupTitlesInverse; -QStringMap DoxWriter::moduleTitlesInverse; -QStringMap DoxWriter::pageTitlesInverse; -QStringMap DoxWriter::externalPageTitlesInverse; -QStringMultiMap DoxWriter::variables; -QStringMultiMap DoxWriter::properties; -QStringMultiMap DoxWriter::enums; -#endif Doc::Doc(const Location& start_loc, const Location& end_loc, @@ -2618,15 +2502,6 @@ Doc::Doc(const Location& start_loc, priv = new DocPrivate(start_loc,end_loc,source); DocParser parser; parser.parse(source,priv,metaCommandSet); -#ifdef QDOC2DOX - if (DoxWriter::isDoxPass()) { - DoxWriter doxWriter(source,priv); - if (DoxWriter::isDoxPass(1)) - doxWriter.pass1(); - else - doxWriter.pass2(); - } -#endif } Doc::Doc(const Doc& doc) @@ -3180,1855 +3055,4 @@ void Doc::detach() priv = newPriv; } -#ifdef QDOC2DOX -/*! - Sets the doxygen writer pass to \a pass. You can use - isDoxPass(), with or without a parameter, to test if - you are in a doxygen writer run or in a specific pass - of a doxygen writer run. - - This function is only called from main() if either the - \e doxygen1 or \e doxygen2 flag is passed to qdoc3 on - the command line. - */ -void DoxWriter::setDoxPass(int pass) -{ - qDebug() << "SETTING doxygen pass to " << pass - << " in DoxWriter::setDoxPass()"; - doxPass = pass; -} - -/*! - Returns true if the doxygen pass is set to \a pass, - which means we are in the specified \a pass of a doxygen - writer run of qdoc3. - */ -bool DoxWriter::isDoxPass(int pass) { return (doxPass == pass); } - -/*! - Returns true if the doxygen pass is 1 or 2, which - means this is a doxygen writer run to transform qdoc - comments into doxygen comments. - */ -bool DoxWriter::isDoxPass() { return (doxPass > 0); } - -bool DoxWriter::conversionRequired() const -{ - /* - Loop through all the topic commands searching for - one that must be transformed to doxygen format. If - one is found, return true. - */ - QCommandMap::const_iterator i; - i = priv->metaCommandMap.constBegin(); - while (i != priv->metaCommandMap.constEnd()) { - QString s = i.key(); - if (s == "enum") - return true; - else if (s == "example") - return true; - else if (s == "externalpage") - return true; - else if (s == "group") - return true; - else if (s == "headerfile") - return true; - else if (s == "module") - return true; - else if (s == "page") - return true; - else if (s == "property") - return true; - else if (s == "typedef") - return true; - else if (s == "variable") - return true; - else if (s == "overload") - return true; - else if (s == "reimp") - return true; - else if (s == "relates") - return true; - else if (s == "macro") - return true; - else { -#if 0 - if (s == "class") - else if (s == "namespace") - else if (s == "service") - else if (s == "inheaderfile") - else if (s == "file") - else if (s == "fn") - else if (s == "contentspage") - else if (s == "nextpage") - else if (s == "previous") - else if (s == "indexpage") - else if (s == "startpage") -#endif - } - ++i; - } - - /* - Loop through all the qdoc atoms searching for one - that must be transformed to doxygen format. If one - is found, return true. - */ - const Atom* next = priv->text.firstAtom(); - while (next != 0) { - Atom::Type atomType = next->type(); - switch (atomType) { - case Atom::C: - case Atom::CaptionLeft: - case Atom::Code: - case Atom::CodeBad: - case Atom::CodeNew: - case Atom::CodeOld: - case Atom::CodeQuoteArgument: - case Atom::CodeQuoteCommand: - case Atom::FootnoteLeft: - case Atom::FormatElse: - case Atom::FormatEndif: - case Atom::FormatIf: - case Atom::GeneratedList: - case Atom::Image: - case Atom::ImageText: - case Atom::InlineImage: - case Atom::LegaleseLeft: - case Atom::LineBreak: - case Atom::Link: - case Atom::LinkNode: - case Atom::ListLeft: - case Atom::ListItemNumber: - case Atom::ListTagLeft: - case Atom::ListItemLeft: - case Atom::QuotationLeft: - case Atom::RawString: - case Atom::SectionLeft: - case Atom::SectionHeadingLeft: - case Atom::SidebarLeft: - case Atom::SnippetCommand: - case Atom::SnippetIdentifier: - case Atom::SnippetLocation: - case Atom::TableLeft: - case Atom::TableHeaderLeft: - case Atom::TableRowLeft: - case Atom::TableItemLeft: - case Atom::TableOfContents: - case Atom::Target: - return true; - case Atom::AbstractLeft: - case Atom::AbstractRight: - case Atom::AutoLink: - case Atom::BaseName: - case Atom::BriefLeft: - case Atom::BriefRight: - case Atom::CaptionRight: - case Atom::FormattingLeft: - case Atom::FormattingRight: - case Atom::Nop: - case Atom::ParaLeft: - case Atom::ParaRight: - case Atom::FootnoteRight: - case Atom::LegaleseRight: - case Atom::ListTagRight: - case Atom::ListItemRight: - case Atom::ListRight: - case Atom::QuotationRight: - case Atom::SectionRight: - case Atom::SectionHeadingRight: - case Atom::SidebarRight: - case Atom::String: - case Atom::TableRight: - case Atom::TableHeaderRight: - case Atom::TableRowRight: - case Atom::TableItemRight: - default: - break; - } - next = next->next(); - } - return false; -} - -/*! - A convenience function to write a qdoc metacommand as a - doxygen command, without conversion. i.e., some of the - qdoc metacommands don't require conversion for doxygen. - */ -void DoxWriter::writeCommand(QCommandMap::const_iterator cmd) -{ - concatenate("\\" + cmd.key() + " " + cmd.value()[0]); - newLine(); -} - -/*! - Convert the qdoc commands in the metacommand map to - doxygen format. This function is called only in pass2(). - The metacommand map contains all the metacommands that - were found in the qdoc comment that is being converted. - The metacommands are the ones that begin with the '\'. - These are not considered part of the text of the comment. - The text is converted by convertText(). - */ -void DoxWriter::convertMetaCommands() -{ - QCommandMap& metaCmdMap = priv->metaCommandMap; - QCommandMap::iterator cmd; - int c; - - currentPage.clear(); - currentFn.clear(); - currentTitle.clear(); - currentEnum.clear(); - currentProperty.clear(); - currentVariable.clear(); - currentClass.clear(); - currentExample.clear(); - currentGroup.clear(); - currentModule.clear(); - currentMacro.clear(); - currentService.clear(); - currentTypedef.clear(); - currentHeaderFile.clear(); - commentType = OtherComment; - - if ((cmd = metaCmdMap.find("class")) != metaCmdMap.end()) { - currentClass = cmd.value()[0]; - if ((c = currentClass.indexOf(' ')) > 0) - currentClass = currentClass.left(c); - writeCommand(cmd); - metaCmdMap.erase(cmd); - commentType = ClassComment; - } - else if ((cmd = metaCmdMap.find("fn")) != metaCmdMap.end()) { - currentFn = cmd.value()[0]; - writeCommand(cmd); - metaCmdMap.erase(cmd); - commentType = FnComment; - } - else if ((cmd = metaCmdMap.find("enum")) != metaCmdMap.end()) { - currentEnum = cmd.value()[0]; - if ((c = currentEnum.lastIndexOf("::")) > 0) { - currentClass = currentEnum.left(c); - currentEnum = currentEnum.right(currentEnum.size()-c-2); - qDebug() << "currentEnum =" << currentEnum; - qDebug() << "currentClass =" << currentClass; - } - writeCommand(cmd); - metaCmdMap.erase(cmd); - commentType = EnumComment; - } - else if ((cmd = metaCmdMap.find("property")) != metaCmdMap.end()) { - currentClass = cmd.value()[0]; - if ((c = currentClass.lastIndexOf("::")) > 0) { - currentProperty = currentClass.right(currentClass.size()-c-2); - currentClass = currentClass.left(c); - qDebug() << "currentProperty =" << currentProperty; - qDebug() << "currentClass =" << currentClass; - } - writeCommand(cmd); - metaCmdMap.erase(cmd); - commentType = PropertyComment; - } - else if ((cmd = metaCmdMap.find("variable")) != metaCmdMap.end()) { - currentClass = cmd.value()[0]; - if ((c = currentClass.lastIndexOf("::")) > 0) { - currentVariable = currentClass.right(currentClass.size()-c-2); - currentClass = currentClass.left(c); - qDebug() << "currentVariable =" << currentVariable; - qDebug() << "currentClass =" << currentClass; - } - concatenate("\\var " + cmd.value()[0]); - newLine(); - metaCmdMap.erase(cmd); - commentType = VariableComment; - } - - if ((cmd = metaCmdMap.find("page")) != metaCmdMap.end()) { - currentPage = cmd.value()[0]; - QString htmlFile = currentPage; - const QString* title = getPageTitle(htmlFile); - QStringList parts = htmlFile.split('.'); - metaCmdMap.erase(cmd); - if (title) { - concatenate("\\page " + parts[0] + " " + *title); - newLine(); - } - commentType = PageComment; - qDebug() << "currentPage =" << currentPage; - } - - if ((cmd = metaCmdMap.find("example")) != metaCmdMap.end()) { - currentExample = cmd.value()[0]; - metaCmdMap.erase(cmd); - commentType = ExampleComment; - qDebug() << "currentExample =" << currentExample; - } - - if ((cmd = metaCmdMap.find("macro")) != metaCmdMap.end()) { - currentMacro = cmd.value()[0]; - metaCmdMap.erase(cmd); - commentType = MacroComment; - qDebug() << "currentMacro =" << currentMacro; - } - - if ((cmd = metaCmdMap.find("group")) != metaCmdMap.end()) { - currentGroup = cmd.value()[0]; - metaCmdMap.erase(cmd); - commentType = GroupComment; - qDebug() << "currentGroup =" << currentGroup; - } - - if ((cmd = metaCmdMap.find("module")) != metaCmdMap.end()) { - currentModule = cmd.value()[0]; - metaCmdMap.erase(cmd); - commentType = ModuleComment; - qDebug() << "currentModule =" << currentModule; - } - - if ((cmd = metaCmdMap.find("headerfile")) != metaCmdMap.end()) { - currentHeaderFile = cmd.value()[0]; - metaCmdMap.erase(cmd); - commentType = HeaderFileComment; - qDebug() << "currentHeaderFile =" << currentHeaderFile; - } - - if ((cmd = metaCmdMap.find("typedef")) != metaCmdMap.end()) { - currentClass = cmd.value()[0]; - if ((c = currentClass.lastIndexOf("::")) > 0) { - currentTypedef = currentClass.right(currentClass.size()-c-2); - currentClass = currentClass.left(c); - } - metaCmdMap.erase(cmd); - commentType = TypedefComment; - qDebug() << "currentTypedef =" << currentTypedef; - qDebug() << "currentClass =" << currentClass; - } - - cmd = priv->metaCommandMap.begin(); - while (cmd != priv->metaCommandMap.end()) { - for (int i=0; itext.firstAtom(); - while (next != 0) { - next->dump(); - Atom::Type atomType = next->type(); - switch (atomType) { - case Atom::AbstractLeft: - break; - case Atom::AbstractRight: - break; - case Atom::AutoLink: - concatenate(next->string()); - break; - case Atom::BaseName: - break; - case Atom::BriefLeft: - concatenate("\\brief "); - break; - case Atom::BriefRight: - newLine(); - break; - case Atom::C: - tt(next); - break; - case Atom::CaptionLeft: - unhandled(next); - break; - case Atom::CaptionRight: - unhandled(next); - break; - case Atom::Code: - code(next); - break; - case Atom::CodeBad: - code(next); - break; - case Atom::CodeNew: - newLine(); - concatenate("you can rewrite it as"); - code(next); - break; - case Atom::CodeOld: - newLine(); - concatenate("For example, if you have code like"); - code(next); - break; - case Atom::CodeQuoteArgument: - unhandled(next); - break; - case Atom::CodeQuoteCommand: - next = codeQuoteCommand(next); - break; - case Atom::FootnoteLeft: - break; - case Atom::FootnoteRight: - break; - case Atom::FormatElse: - formatElse(); - break; - case Atom::FormatEndif: - formatEndif(); - break; - case Atom::FormatIf: - formatIf(next); - break; - case Atom::FormattingLeft: - formattingLeft(next,next->next()); - break; - case Atom::FormattingRight: - formattingRight(next,prev); - break; - case Atom::GeneratedList: - break; - case Atom::Image: - break; - case Atom::ImageText: - break; - case Atom::InlineImage: - break; - case Atom::LegaleseLeft: - break; - case Atom::LegaleseRight: - break; - case Atom::LineBreak: - break; - case Atom::Link: - next = link(next); - break; - case Atom::LinkNode: - break; - case Atom::ListLeft: - { - bool nested = false; - if (structs.isEmpty()) { - const Atom* i = next->next(); - while (i->type() != Atom::ListRight) { - if ((i->type() == Atom::ListLeft) || - (i->type() == Atom::TableLeft)) { - nested = true; - break; - } - i = i->next(); - } - } - else - nested = true; - StructDesc d(BulletList,nested); - if (next->string() == "numeric") - d.structType = NumericList; - else if (next->string() == "value") { - d.structType = ValueList; - } - else if (next->string() != "bullet") - qDebug() << "UNKNOWN LIST TYPE" << next->string(); - structs.push(d); - if (nested || (d.structType != BulletList)) { - if (d.structType == BulletList) - concatenate("
      "); - else if (d.structType == NumericList) - concatenate("
        "); - else if (d.structType == ValueList) - concatenate("
        "); - newLine(); - } - } - break; - case Atom::ListItemNumber: - structs.top().count = next->string().toInt(); - break; - case Atom::ListTagLeft: - { - structs.top().count++; - concatenate("
        "); - const Atom* n = next->next(); - if (n->type() == Atom::String) { - qDebug() << "ENUM VALUE" << n->string(); - } - else - qDebug() << "NOT EN ENUM"; - } - break; - case Atom::ListTagRight: - concatenate("
        "); - break; - case Atom::ListItemLeft: - { - newLine(); - const StructDesc& d = structs.top(); - if (d.structType == BulletList) { - if (!d.nested) - concatenate("\\arg "); - else - concatenate("
      1. "); - } - else if (d.structType == NumericList) - concatenate("
      2. "); - else if (d.structType == ValueList) - concatenate("
        "); - } - break; - case Atom::ListItemRight: - { - const StructDesc& d = structs.top(); - if (d.structType == BulletList) { - if (d.nested) { - concatenate("
      3. "); - newLine(); - } - } - else if (d.structType == NumericList) { - concatenate(""); - newLine(); - } - else if (d.structType == ValueList) { - concatenate(""); - newLine(); - } - } - break; - case Atom::ListRight: - { - if (!structs.isEmpty()) { - const StructDesc& d = structs.top(); - if (d.nested || (d.structType != BulletList)) { - if (d.structType == BulletList) - concatenate("
    "); - else if (d.structType == NumericList) - concatenate(""); - else if (d.structType == ValueList) - concatenate(""); - newLine(); - } - structs.pop(); - } - } - break; - case Atom::Nop: - // nothing. - break; - case Atom::ParaLeft: - if (structs.isEmpty()) - newLine(); - break; - case Atom::ParaRight: - { - if (structs.isEmpty()) - newLine(); - else { - const StructDesc& d = structs.top(); - if (d.nested || (d.structType != BulletList)) { - Atom::Type t = next->next()->type(); - if ((t != Atom::ListItemRight) && - (t != Atom::TableItemRight)) - newLine(); - } - else - newLine(); - } - } - break; - case Atom::QuotationLeft: - break; - case Atom::QuotationRight: - break; - case Atom::RawString: - concatenate(next->string()); - break; - case Atom::SectionLeft: - // nothing. - break; - case Atom::SectionRight: - // nothing. - break; - case Atom::SectionHeadingLeft: - next = sectionHeading(next); - break; - case Atom::SectionHeadingRight: - newLine(); - break; - case Atom::SidebarLeft: - break; - case Atom::SidebarRight: - break; - case Atom::SnippetCommand: - newLine(); - concatenate("\\snippet "); - break; - case Atom::SnippetIdentifier: - newText += next->string(); - lineLength += next->string().size(); - newLine(); - break; - case Atom::SnippetLocation: - newText += next->string() + " "; - lineLength += next->string().size() + 1; - break; - case Atom::String: - wrap(next->string()); - break; - case Atom::TableLeft: - { - bool nested = false; - if (structs.isEmpty()) { - const Atom* i = next->next(); - while (i->type() != Atom::TableRight) { - if ((i->type() == Atom::ListLeft) || - (i->type() == Atom::TableLeft)) { - nested = true; - break; - } - i = i->next(); - } - } - else - nested = true; - StructDesc d(Table,nested); - structs.push(d); - if (next->string().isEmpty()) - concatenate("
    "); - else { - QString attrs = "width=\"" + next->string() + "\""; - attrs += " align=\"center\""; - concatenate("
    "); - } - newLine(); - } - break; - case Atom::TableRight: - concatenate("
    "); - if (!structs.isEmpty()) - structs.pop(); - newLine(); - break; - case Atom::TableHeaderLeft: - concatenate(""); - if (!structs.isEmpty()) - structs.top().inTableHeader = true; - newLine(); - break; - case Atom::TableHeaderRight: - concatenate(""); - if (!structs.isEmpty()) - structs.top().inTableHeader = false; - newLine(); - break; - case Atom::TableRowLeft: - if (!structs.isEmpty()) { - structs.top().inTableRow = true; - concatenate(""); - else - concatenate("even\">"); - structs.top().odd = !structs.top().odd; - } - newLine(); - break; - case Atom::TableRowRight: - concatenate(""); - if (!structs.isEmpty()) - structs.top().inTableRow = false; - newLine(); - break; - case Atom::TableItemLeft: - if (!structs.isEmpty()) { - structs.top().inTableItem = true; - concatenate(""); - if (structs.top().inTableHeader) - concatenate(" "); - } - break; - case Atom::TableItemRight: - if (!structs.isEmpty()) { - structs.top().inTableItem = false; - if (structs.top().inTableHeader) - concatenate(" "); - concatenate(""); - } - newLine(); - break; - case Atom::TableOfContents: - break; - case Atom::Target: - { - QString text = next->string(); - text.remove(ws_rx); - newLine(); - concatenate("\\anchor "); - newText += text; - lineLength += text.size(); - newLine(); - } - break; - case Atom::UnhandledFormat: - unhandled(next); - break; - case Atom::UnknownCommand: - unhandled(next); - break; - default: - //next->dump(); - break; - } - prev = next; - next = next->next(); - } -} - -/*! - - Pass one looks for topic commands and target and section - commands, and maybe other stuff. These are serialized to - text files, which are read back in by pass2(). - */ -void DoxWriter::pass1() -{ - QCommandMap& metaCmdMap = priv->metaCommandMap; - if (!metaCmdMap.isEmpty()) { - int c; - QCommandMap::iterator cmd; - if ((cmd = metaCmdMap.find("enum")) != metaCmdMap.end()) { - commentType = EnumComment; - currentEnum = cmd.value()[0]; - if ((c = currentEnum.lastIndexOf("::")) > 0) { - currentClass = currentEnum.left(c); - currentEnum = currentEnum.right(currentEnum.size()-c-2); - qDebug() << "currentEnum =" << currentEnum; - qDebug() << "currentClass =" << currentClass; - if (enums.contains(currentEnum,currentClass)) { - qWarning() << "DoxWriter::pass1():" - << "Duplicate enum:" - << currentClass << currentEnum; - } - else - enums.insert(currentEnum,currentClass); - } - } - else if ((cmd = metaCmdMap.find("property")) != metaCmdMap.end()) { - commentType = PropertyComment; - currentClass = cmd.value()[0]; - if ((c = currentClass.lastIndexOf("::")) > 0) { - currentProperty = currentClass.right(currentClass.size()-c-2); - currentClass = currentClass.left(c); - qDebug() << "currentProperty =" << currentProperty; - qDebug() << "currentClass =" << currentClass; - if (properties.contains(currentProperty,currentClass)) { - qWarning() << "DoxWriter::pass1():" - << "Duplicate property:" - << currentClass << currentProperty; - } - else - properties.insert(currentProperty,currentClass); - } - } - else if ((cmd = metaCmdMap.find("variable")) != metaCmdMap.end()) { - commentType = VariableComment; - currentClass = cmd.value()[0]; - if ((c = currentClass.lastIndexOf("::")) > 0) { - currentVariable = currentClass.right(currentClass.size()-c-2); - currentClass = currentClass.left(c); - qDebug() << "currentVariable =" << currentVariable; - qDebug() << "currentClass =" << currentClass; - if (variables.contains(currentVariable,currentClass)) { - qWarning() << "DoxWriter::pass1():" - << "Duplicate variable:" - << currentClass << currentVariable; - } - else - variables.insert(currentVariable,currentClass); - } - } - } - - /* - */ - const Atom* next = priv->text.firstAtom(); - while (next != 0) { - switch (next->type()) { - case Atom::SectionHeadingLeft: - { - QString text; - next = next->next(); - while (next) { - if (next->type() == Atom::SectionHeadingRight) - break; - else - text += next->string(); - next = next->next(); - } - //text.remove(ws_rx); - insertAnchor(text); - } - break; - case Atom::Target: - { - QString text = next->string(); - //text.remove(ws_rx); - insertAnchor(text); - } - default: - break; - } - next = next->next(); - } -} - -/*! - Output a parsed, tokenized qdoc comment as a doxygen - comment in diff format for input to the patch command. - */ -void DoxWriter::pass2() -{ - if (!conversionRequired()) { - qDebug() << "NO CONVERSION - FILE:" << priv->start_loc.fileName() - << "START:" << priv->start_loc.lineNo() - << "END:" << priv->end_loc.lineNo() - 1; - return; - } - - /* - Transformation to doxygen required... - */ - newText = "\n/*! \n"; - convertMetaCommands(); - convertText(); - if (newText[newText.size()-1] == ' ') - newText.remove(newText.size()-1,1); - newText += " */\n"; - qDebug() << "CONVERTED COMMENT - FILE:" << priv->start_loc.fileName() - << "START:" << priv->start_loc.lineNo() - << "END:" << priv->end_loc.lineNo() - 1; - qDebug() << newText; -} - -/*! - Unparse the second parameter of a "\l" command. - */ -const Atom* DoxWriter::link(const Atom* atom) -{ - QString first_text = atom->string(); - QString second_text; - const QString* value = 0; - - const Atom* next = atom->next(Atom::FormattingLeft,Atom::LINK_); - if (next) { - next->dump(); - while (1) { - next = next->next(); - next->dump(); - if (next->type() == Atom::FormattingRight) { - if (next->string() == Atom::LINK_) - break; - else { - // ignore it. - } - } - else - second_text += next->string(); - } - int i = first_text.indexOf('#'); - if (i >= 0) - first_text = first_text.right(first_text.size() - i - 1); - //newLine(); - if ((value = getExternalPage(first_text))) { - //qDebug() << "USED AN EXTERNAL PAGE TITLE" << first_text; - QString href = ""+first_text+""; - concatenate(href); - } - else if (first_text.startsWith("http:",Qt::CaseInsensitive)) { - if (first_text == second_text) { - concatenate(first_text); - } - else { - QString href = ""+second_text+""; - concatenate(href); - } - } - else if ((value = getPageFile(first_text))) { - //qDebug() << "USED A PAGE TITLE" << first_text; - QStringList parts = (*value).split('.'); - QString ref = "\\ref " + parts[0] + " \"" + second_text + "\""; - concatenate(ref); - } - else if ((value = getGroup(first_text))) { - //qDebug() << "USED A GROUP TITLE" << first_text; - concatenate("\\ref " + *value + " \"" + second_text + "\""); - } - else if ((value = getModule(first_text))) { - //qDebug() << "USED A MODULE TITLE" << first_text; - concatenate("\\ref " + *value + " \"" + second_text + "\""); - } - else if ((value = getExamplePath(first_text))) { - //qDebug() << "USED AN EXAMPLE TITLE" << first_text; - first_text.remove(ws_rx); - QString ref = "\\ref " + first_text + " \"" + second_text + "\""; - concatenate(ref); - } - else if ((value = getFile(first_text))) { - //qDebug() << "USED A FILE TITLE" << first_text; - // I think this command is no longer available. - first_text.remove(ws_rx); - QString ref = "\\ref " + first_text + " \"" + second_text + "\""; - concatenate(ref); - } - else if ((value = getHeaderFile(first_text))) { - //qDebug() << "USED A HEADER FILE TITLE" << first_text; - first_text.remove(ws_rx); - QString ref = "\\ref " + first_text + " \"" + second_text + "\""; - concatenate(ref); - } - else if (isAnchor(first_text)) { - //qDebug() << "USED AN ANCHOR" << first_text; - first_text.remove(ws_rx); - QString ref = "\\ref " + first_text + " \"" + second_text + "\""; - concatenate(ref); - } - else if ((value = getPageTitle(first_text))) { - //qDebug() << "USED AN INVERSE PAGE TITLE" << first_text; - QStringList parts = first_text.split('.'); - QString ref = "\\ref " + parts[0] + " \"" + second_text + "\""; - concatenate(ref); - } - else if ((value = getExampleTitle(first_text))) { - //qDebug() << "USED AN INVERSE EXAMPLE TITLE" << first_text; - QString title = *value; - title.remove(ws_rx); - QString ref = "\\ref " + title + " \"" + second_text + "\""; - concatenate(ref); - } - else if ((value = getGroupTitle(first_text))) { - //qDebug() << "USED AN INVERSE GROUP TITLE" << first_text; - concatenate("\\ref " + first_text + " \"" + second_text + "\""); - } - else if ((value = getModuleTitle(first_text))) { - //qDebug() << "USED AN INVERSE MODULE TITLE" << first_text; - concatenate("\\ref " + first_text + " \"" + second_text + "\""); - } - else if ((value = getFileTitle(first_text))) { - qDebug() << "USED AN INVERSE FILE TITLE" << first_text; - } - else if ((value = getHeaderFileTitle(first_text))) { - qDebug() << "USED AN INVERSE HEADER FILE TITLE" << first_text; - } - else if ((first_text.indexOf("::") >= 0) || - (first_text.indexOf("()") >= 0) || - (first_text[0] == 'Q')) { - //qDebug() << "AUTO-LINKABLE" << first_text; - if (first_text == second_text) - concatenate(first_text); - else { - QString link = first_text + " " + second_text; - concatenate("\\link " + link + "\\endlink"); - } - } - else { - QString link; - QStringList propertyClasses; - QStringList variableClasses; - QStringList enumClasses; - bool p = isProperty(first_text,propertyClasses); - bool v = isVariable(first_text,variableClasses); - bool e = isEnum(first_text,enumClasses); - if (e) { - if (enumClasses.size() == 1) - link = enumClasses[0]; - else if (enumClasses.contains(currentClass)) - link = currentClass; - else { - QString msg = "Unqualified enum name: " + first_text; - QString details = "Classes: " + enumClasses.join(", "); - priv->start_loc.error(msg,details); - } - if (!link.isEmpty()) - qDebug() << "FOUND ENUM" << link << first_text; - } - else if (p && v) { - if (propertyClasses.size() == 1) { - if (variableClasses.size() == 1) { - if (propertyClasses[0] == variableClasses[0]) - link = propertyClasses[0]; - } - } - if (link.isEmpty()) { - if (propertyClasses.contains(currentClass) || - variableClasses.contains(currentClass)) - link = currentClass; - else { - propertyClasses += variableClasses; - QString msg = "Unqualified property or variable name: " - + first_text; - QString details = "Classes: " + - propertyClasses.join(", "); - priv->start_loc.error(msg,details); - } - } - } - else if (p) { - if (propertyClasses.size() == 1) - link = propertyClasses[0]; - else if (propertyClasses.contains(currentClass)) - link = currentClass; - else { - QString msg = "Unqualified property name: " + first_text; - QString details = "Classes: " + propertyClasses.join(", "); - priv->start_loc.error(msg,details); - } - } - else if (v) { - if (variableClasses.size() == 1) - link = variableClasses[0]; - else if (variableClasses.contains(currentClass)) - link = currentClass; - else { - QString msg = "Unqualified variable name: " + first_text; - QString details = "Classes: " + variableClasses.join(", "); - priv->start_loc.error(msg,details); - } - } - else { - qDebug() << "NOT AUTO-LINKABLE" << first_text; - QString s = first_text + " " + second_text; - concatenate("\\link " + s + "\\endlink"); - } - if (!link.isEmpty()) { - link += "::" + first_text + " " + second_text; - concatenate("\\link " + link + "\\endlink"); - } - } - } - else - qDebug() << "LINK with no second parameter!!!!"; - return next? next : atom; -} - -/*! - If the current line length is 0, the current line is - indented according to the context. - */ -void DoxWriter::indentLine() -{ - if (lineLength == 0) { - newText += DOXYGEN_INDENT_STRING; - lineLength = DOXYGEN_INDENT; - if (!structs.isEmpty()) { - for (int i=1; i maxLineLength) - newLine(); - indentLine(); - newText += text; - lineLength += text.size(); -} - -static bool punctuation(QChar c) -{ - switch (c.toAscii()) { - case '.': - case ',': - case ':': - case ';': - case '/': - case '+': - case '-': - case '?': - case '!': - case '\"': - return true; - default: - break; - } - return false; -} - -/*! - Concatenate the \a text string to the doxygen text, doing - line wrapping where necessary. - */ -void DoxWriter::wrap(QString text) -{ - int from = 0; - int to = -1; - - if ((lineLength == 0) || (lineLength >= maxLineLength)) { - if (!text.isEmpty() && (text[0] == ' ')) - text = text.right(text.size() - 1); - } - - indentLine(); - while (text.size()) { - int avail = maxLineLength - lineLength; - from = text.indexOf(' ',from); - if (from >= 0) { - if (from < avail) - to = from++; - else if (from == 1 && punctuation(text[0])) - to = from++; - else { - if (to >= 0) { - newText += text.left(to+1); - lineLength += to + 1; - text = text.right(text.size() - to - 1); - } - else { - newLine(); - indentLine(); - newText += text.left(from+1); - lineLength += from + 1; - text = text.right(text.size() - from - 1); - } - from = 0; - to = -1; - if (text.size() && (lineLength > maxLineLength)) { - newLine(); - indentLine(); - } - } - } - else - break; - } - if (text.size()) { - if (lineLength >= maxLineLength) { - newLine(); - indentLine(); - } - newText += text; - lineLength += text.size(); - } -} - -/*! - This will output something, but it depends on what the - \a atom string and the \a next atom string are. - */ -void DoxWriter::formattingLeft(const Atom* atom, const Atom* next) -{ - if (atom->string() == "parameter") { - concatenate("\\a "); - return; - } - else if (atom->string() == "underline") { - concatenate(""); - return; - } - else if (atom->string() == "superscript") { - concatenate(""); - return; - } - else if (atom->string() == "subscript") { - concatenate(""); - return; - } - int ws = -1; - if (next) - ws = next->string().indexOf(ws_rx); - if (atom->string() == "bold") { - if (ws < 0) - concatenate("\\b "); - else - concatenate(""); - } - else if (atom->string() == "italic") { - if (ws < 0) - concatenate("\\e "); - else - concatenate(""); - } - else if (atom->string() == "teletype") { - if (ws < 0) - concatenate("\\c "); - else - concatenate(""); - } - else - qDebug() << "UNHANDLED FormattingLeft: " << atom->string(); -} - -/*! - This will output something, but it depends on what the - \a atom string and the \a prev atom string are. - */ -void DoxWriter::formattingRight(const Atom* atom, const Atom* prev) -{ - if (atom->string() == "parameter") - return; - else if (atom->string() == "underline") { - concatenate(""); - return; - } - else if (atom->string() == "superscript") { - concatenate(""); - return; - } - else if (atom->string() == "subscript") { - concatenate(""); - return; - } - int ws = -1; - if (prev) - ws = prev->string().indexOf(ws_rx); - if (ws < 0) - return; - if (atom->string() == "bold") - concatenate(""); - else if (atom->string() == "italic") - concatenate(""); - else if (atom->string() == "teletype") - concatenate(""); - else - qDebug() << "UNHANDLED FormattingRight: " << atom->string(); -} - -/*! - Output a \c or a .... - */ -void DoxWriter::tt(const Atom* atom) -{ - if (atom->string().indexOf(ws_rx) < 0) { - concatenate("\\c "); - concatenate(atom->string()); - } - else { - concatenate(""); - concatenate(atom->string()); - concatenate(""); - } -} - -/*! - */ -void DoxWriter::formatIf(const Atom* atom) -{ - if (atom->string() == "HTML") { - newLine(); - concatenate("\\htmlonly"); - newLine(); - } -} - -/*! - */ -void DoxWriter::formatEndif() -{ - newLine(); - concatenate("\\endhtmlonly"); - newLine(); -} - -/*! - */ -void DoxWriter::formatElse() -{ - // nothing. -} - -/*! - Pass 1: Construct a section identifier and insert it into - the anchor set. - - Pass 2: Convert section1, section2, and section3 commands - to section, subsection, and subsubsection respectively. - Warn if a section command higher than 3 is seen. - */ -const Atom* DoxWriter::sectionHeading(const Atom* atom) -{ - QString heading_level = atom->string(); - QString heading_text; - const Atom* next = atom->next(); - while (next) { - next->dump(); - if (next->type() == Atom::SectionHeadingRight) { - if (next->string() == heading_level) - break; - else { - qDebug() << "WRONG SectionHeading number!!!!"; - } - } - else - heading_text += next->string(); - next = next->next(); - } - - QString heading_identifier = heading_text; - heading_identifier.remove(ws_rx); - - newLine(); - if (heading_level == "1") - heading_level = "\\section "; - else if (heading_level == "2") - heading_level = "\\subsection "; - else if (heading_level == "3") - heading_level = "\\subsubsection "; - else if (heading_level == "4") { - heading_level = "\\subsubsection "; - qDebug() << "WARNING section4 converted to \\subsubsection"; - } - else { - heading_level = "\\subsubsection "; - qDebug() << "WARNING section5 converted to \\subsubsection"; - } - concatenate(heading_level); - newText += heading_identifier + " "; - lineLength += heading_identifier.size() + 1; - newText += heading_text; - lineLength += heading_text.size(); - newLine(); - return next? next : atom; -} - -/*! - Report an unhandled atom. - */ -void DoxWriter::unhandled(const Atom* atom) -{ - qDebug() << "UNHANDLED ATOM"; - atom->dump(); -} - -/*! - Output a code/endcode block. - */ -void DoxWriter::code(const Atom* atom) -{ - newLine(); - concatenate("\\code"); - writeCode(atom->string()); - concatenate("\\endcode"); - newLine(); -} - -/*! - Output a code/endcode block depending on the - CodeQuote Command and CodeQuoteArgument parameters. - */ -const Atom* DoxWriter::codeQuoteCommand(const Atom* atom) -{ - QString command = atom->string(); - atom = atom->next(); - concatenate("\\code"); - if (command == "codeline") { - newLine(); - concatenate(atom->string()); - newLine(); - } - else if (command == "dots") { - newLine(); - concatenate(atom->string()); - newLine(); - } - else { - writeCode(atom->string()); - } - concatenate("\\endcode"); - return atom; -} - -/*! - Appends a block of code to the comment. - */ -void DoxWriter::writeCode(QString text) -{ - int cr_count = text.count('\n') - 1; - if (cr_count >= 0) { - int last_cr = text.lastIndexOf('\n'); - newText += text.left(last_cr); - lineCount += cr_count; - } - else - newText += text; - newLine(); -} - -/*! - Inserts \a text into the anchor set. This function is called - during doxygen pass 1. - */ -void DoxWriter::insertAnchor(const QString& text) -{ - anchors.insert(text); -} - -/*! - Returns true if \a text identifies an anchor, section, - subsection, subsubsection, or page. - */ -bool DoxWriter::isAnchor(const QString& text) -{ - return anchors.contains(text); -} - -/*! - Write the set of anchors to a file, one per line. - */ -void DoxWriter::writeAnchors() -{ - QFile file("anchors.txt"); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - qWarning("Unable to open anchors.txt for writing."); - return; - } - - QTextStream out(&file); - QSet::const_iterator i = anchors.constBegin(); - while (i != anchors.constEnd()) { - out << *i << "\n"; - ++i; - } - file.close(); -} - -/*! - Read the set of anchors from the anchors file, one per line, - and insert each one into the anchor set. - */ -void DoxWriter::readAnchors() -{ - QFile file("anchors.txt"); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - qWarning("Unable to open anchors.txt for reading."); - return; - } - - QTextStream in(&file); - while (!in.atEnd()) { - QString line = in.readLine(); - anchors.insert(line); - } - file.close(); -#if 0 - QSet::const_iterator i = anchors.constBegin(); - while (i != anchors.constEnd()) { - qDebug() << *i; - ++i; - } -#endif -} - -/*! - Inserts \a title into one of the title maps. \a title is - mapped to the \a node name. This function is called during - doxygen pass 1. - */ -void DoxWriter::insertTitle(FakeNode* node, const QString& title) -{ - switch (node->subType()) { - case FakeNode::Example: - if (exampleTitles.contains(title)) { - qWarning() << "DoxWriter::insertTitle():" - << "Duplicate example title:" - << title; - } - else { - exampleTitles[title] = node->name(); - exampleTitlesInverse[node->name()] = title; - } - break; - case FakeNode::HeaderFile: - if (headerFileTitles.contains(title)) { - qWarning() << "DoxWriter::insertTitle():" - << "Duplicate header file title:" - << title; - } - else { - headerFileTitles[title] = node->name(); - headerFileTitlesInverse[node->name()] = title; - } - break; - case FakeNode::File: - if (fileTitles.contains(title)) { - qWarning() << "DoxWriter::insertTitle():" - << "Duplicate file title:" - << title; - } - else { - fileTitles[title] = node->name(); - fileTitlesInverse[node->name()] = title; - } - break; - case FakeNode::Group: - if (groupTitles.contains(title)) { - qWarning() << "DoxWriter::insertTitle():" - << "Duplicate group title:" - << title; - } - else { - groupTitles[title] = node->name(); - groupTitlesInverse[node->name()] = title; - } - break; - case FakeNode::Module: - if (moduleTitles.contains(title)) { - qWarning() << "DoxWriter::insertTitle():" - << "Duplicate module title:" - << title; - } - else { - moduleTitles[title] = node->name(); - moduleTitlesInverse[node->name()] = title; - } - break; - case FakeNode::Page: - if (pageTitles.contains(title)) { - qWarning() << "DoxWriter::insertTitle():" - << "Duplicate page title:" - << title; - } - else { - pageTitles[title] = node->name(); - pageTitlesInverse[node->name()] = title; - } - break; - case FakeNode::ExternalPage: - if (externalPageTitles.contains(title)) { - qWarning() << "DoxWriter::insertTitle():" - << "Duplicate external page title:" - << title; - } - else { - externalPageTitles[title] = node->name(); - externalPageTitlesInverse[node->name()] = title; - } - break; - default: - break; - } -} - -/*! - */ -const QString* DoxWriter::getPageFile(const QString& title) -{ - QStringMapEntry entry = pageTitles.find(title); - return (entry == pageTitles.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getExamplePath(const QString& title) -{ - QStringMapEntry entry = exampleTitles.find(title); - return (entry == exampleTitles.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getFile(const QString& title) -{ - QStringMapEntry entry = fileTitles.find(title); - return (entry == fileTitles.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getHeaderFile(const QString& title) -{ - QStringMapEntry entry = headerFileTitles.find(title); - return (entry == headerFileTitles.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getGroup(const QString& title) -{ - QStringMapEntry entry = groupTitles.find(title); - return (entry == groupTitles.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getModule(const QString& title) -{ - QStringMapEntry entry = moduleTitles.find(title); - return (entry == moduleTitles.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getExternalPage(const QString& title) -{ - QStringMapEntry entry = externalPageTitles.find(title); - return (entry == externalPageTitles.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getPageTitle(const QString& text) -{ - QStringMapEntry entry = pageTitlesInverse.find(text); - return (entry == pageTitlesInverse.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getExampleTitle(const QString& text) -{ - QStringMapEntry entry = exampleTitlesInverse.find(text); - return (entry == exampleTitlesInverse.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getFileTitle(const QString& text) -{ - QStringMapEntry entry = fileTitlesInverse.find(text); - return (entry == fileTitlesInverse.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getHeaderFileTitle(const QString& text) -{ - QStringMapEntry entry = headerFileTitlesInverse.find(text); - return (entry == headerFileTitlesInverse.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getGroupTitle(const QString& text) -{ - QStringMapEntry entry = groupTitlesInverse.find(text); - return (entry == groupTitlesInverse.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getModuleTitle(const QString& text) -{ - QStringMapEntry entry = moduleTitlesInverse.find(text); - return (entry == moduleTitlesInverse.end()) ? 0 : &entry.value(); -} - -/*! - */ -const QString* DoxWriter::getExternalPageTitle(const QString& text) -{ - QStringMapEntry entry = externalPageTitlesInverse.find(text); - return (entry == externalPageTitlesInverse.end()) ? 0 : &entry.value(); -} - -/*! - Serialize \a map to file \a name. - */ -void DoxWriter::writeMap(const QStringMap& map, const QString& name) -{ - - QFile file(name); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - qWarning() << "Unable to open" << name << "for writing."; - return; - } - - QTextStream out(&file); - QStringMap::const_iterator i = map.constBegin(); - while (i != map.constEnd()) { - out << i.key() << "\n"; - out << i.value() << "\n"; - ++i; - } - file.close(); -} - -/*! - Read file \a name into the \a map. - */ -void DoxWriter::readMap(QStringMap& map, QStringMap& inverseMap, const QString& name) -{ - QFile file(name); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - qWarning() << "Unable to open" << name << "for reading."; - return; - } - - QTextStream in(&file); - while (!in.atEnd()) { - QString title = in.readLine(); - QString value = in.readLine(); - map[title] = value; - inverseMap[value] = title; - } - file.close(); -} - -/*! - Write the sets of titles to text files, one per line. - */ -void DoxWriter::writeTitles() -{ - if (!pageTitles.isEmpty()) - writeMap(pageTitles,"pagetitles.txt"); - if (!fileTitles.isEmpty()) - writeMap(fileTitles,"filetitles.txt"); - if (!headerFileTitles.isEmpty()) - writeMap(headerFileTitles,"headerfiletitles.txt"); - if (!exampleTitles.isEmpty()) - writeMap(exampleTitles,"exampletitles.txt"); - if (!moduleTitles.isEmpty()) - writeMap(moduleTitles,"moduletitles.txt"); - if (!groupTitles.isEmpty()) - writeMap(groupTitles,"grouptitles.txt"); - if (!externalPageTitles.isEmpty()) - writeMap(externalPageTitles,"externalpagetitles.txt"); -} - -/*! - Read the sets of titles from the titles files, one per line, - and insert each one into the appropriate title set. - */ -void DoxWriter::readTitles() -{ - readMap(pageTitles,pageTitlesInverse,"pagetitles.txt"); - readMap(fileTitles,fileTitlesInverse,"filetitles.txt"); - readMap(headerFileTitles,headerFileTitlesInverse,"headerfiletitles.txt"); - readMap(exampleTitles,exampleTitlesInverse,"exampletitles.txt"); - readMap(moduleTitles,moduleTitlesInverse,"moduletitles.txt"); - readMap(groupTitles,groupTitlesInverse,"grouptitles.txt"); - readMap(externalPageTitles, - externalPageTitlesInverse, - "externalpagetitles.txt"); -} - -/*! - Serialize \a map to file \a name. - */ -void DoxWriter::writeMultiMap(const QStringMultiMap& map, const QString& name) -{ - - QFile file(name); - if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { - qWarning() << "Unable to open" << name << "for writing."; - return; - } - - QTextStream out(&file); - QStringMultiMap::const_iterator i = map.constBegin(); - while (i != map.constEnd()) { - out << i.key() << "\n"; - out << i.value() << "\n"; - ++i; - } - file.close(); -} - -/*! - Write the4 property names and variable names to text files. - */ -void DoxWriter::writeMembers() -{ - if (!variables.isEmpty()) - writeMultiMap(variables,"variables.txt"); - if (!properties.isEmpty()) - writeMultiMap(properties,"properties.txt"); - if (!enums.isEmpty()) - writeMultiMap(enums,"enums.txt"); -} - -/*! - Read file \a name into the \a map. - */ -void DoxWriter::readMultiMap(QStringMultiMap& map, const QString& name) -{ - QFile file(name); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - qWarning() << "Unable to open" << name << "for reading."; - return; - } - - QTextStream in(&file); - while (!in.atEnd()) { - QString member = in.readLine(); - QString className = in.readLine(); - map.insert(member,className); - } - file.close(); -} - -/*! - Read the property names and variable names from the test files. - */ -void DoxWriter::readMembers() -{ - readMultiMap(variables,"variables.txt"); - readMultiMap(properties,"properties.txt"); - readMultiMap(enums,"enums.txt"); -} - -/*! - Return true if \a name is a property. Loads \a classes with - the names of all the classes in which \a name is a property. - */ -bool DoxWriter::isProperty(const QString& name, QStringList& classes) -{ - classes = properties.values(name); - return !classes.isEmpty(); -} - -/*! - Return true if \a name is a variable. Loads \a classes with - the names of all the classes in which \a name is a variable. - */ -bool DoxWriter::isVariable(const QString& name, QStringList& classes) -{ - classes = variables.values(name); - return !classes.isEmpty(); -} - -/*! - Return true if \a name is an enum type. Loads \a classes with - the names of all the classes in which \a name is an enum type. - */ -bool DoxWriter::isEnum(const QString& name, QStringList& classes) -{ - classes = enums.values(name); - return !classes.isEmpty(); -} -#endif - QT_END_NAMESPACE diff --git a/tools/qdoc3/doc.h b/tools/qdoc3/doc.h index 6cb6f0a..2c1d29e 100644 --- a/tools/qdoc3/doc.h +++ b/tools/qdoc3/doc.h @@ -133,183 +133,6 @@ class Doc DocPrivate *priv; }; -#ifdef QDOC2DOX - -class DoxWriter -{ - public: - DoxWriter(const QString& source, DocPrivate* docPrivate) - : commentType(OtherComment), - lineLength(0), - lineCount(0), - priv(docPrivate), - oldText(source) {} - ~DoxWriter() {} - - void pass1(); - void pass2(); - - static void setDoxPass(int pass); - static bool isDoxPass(int pass); - static bool isDoxPass(); - static void insertTitle(FakeNode* node, const QString& title); - static void writeTitles(); - static void readTitles(); - static void writeMembers(); - static void readMembers(); - static void writeAnchors(); - static void readAnchors(); - - private: - void indentLine(); - void newLine(); - void concatenate(QString text); - void wrap(QString text); - bool conversionRequired() const; - void convertMetaCommands(); - void convertText(); - const Atom* link(const Atom* atom); - void formattingLeft(const Atom* atom, const Atom* next); - void formattingRight(const Atom* atom, const Atom* prev); - void tt(const Atom* atom); - void formatIf(const Atom* atom); - void formatEndif(); - void formatElse(); - const Atom* sectionHeading(const Atom* atom); - void unhandled(const Atom* atom); - void code(const Atom* atom); - const Atom* codeQuoteCommand(const Atom* atom); - void writeCode(QString text); - void writeCommand(QCommandMap::const_iterator cmd); - - static void insertAnchor(const QString& text); - static bool isAnchor(const QString& text); - - static const QString* getPageFile(const QString& title); - static const QString* getFile(const QString& title); - static const QString* getExamplePath(const QString& title); - static const QString* getHeaderFile(const QString& title); - static const QString* getGroup(const QString& title); - static const QString* getModule(const QString& title); - static const QString* getExternalPage(const QString& title); - static const QString* getPageTitle(const QString& text); - static const QString* getFileTitle(const QString& text); - static const QString* getExampleTitle(const QString& text); - static const QString* getHeaderFileTitle(const QString& text); - static const QString* getGroupTitle(const QString& text); - static const QString* getModuleTitle(const QString& text); - static const QString* getExternalPageTitle(const QString& text); - - static bool isProperty(const QString& title, QStringList& classes); - static bool isVariable(const QString& title, QStringList& classes); - static bool isEnum(const QString& title, QStringList& classes); - - private: - static void writeMap(const QStringMap& map, const QString& name); - static void readMap(QStringMap& map, - QStringMap& inverseMap, - const QString& name); - static void writeMultiMap(const QStringMultiMap& map, const QString& name); - static void readMultiMap(QStringMultiMap& map, const QString& name); - - public: // VS 6, SunCC need this to be public - enum StructType { BulletList, NumericList, ValueList, Table }; - private: - struct StructDesc { - StructType structType; - int count; - bool nested; - bool inTableHeader; - bool inTableRow; - bool inTableItem; - bool odd; - - StructDesc() - : structType(BulletList), - count(0), - nested(false), - inTableHeader(false), - inTableRow(false), - inTableItem(false), - odd(true) { } - - StructDesc(StructType t, bool n) - : structType(t), - count(0), - nested(n), - inTableHeader(false), - inTableRow(false), - inTableItem(false), - odd(true) { } - }; - - typedef QStack StructStack; - - enum CommentType { - ClassComment, - EnumComment, - ExampleComment, - FnComment, - GroupComment, - HeaderFileComment, - MacroComment, - ModuleComment, - PageComment, - PropertyComment, - ServiceComment, - TypedefComment, - VariableComment, - OtherComment - }; - - private: - CommentType commentType; - int lineLength; - int lineCount; - DocPrivate* priv; - QString oldText; - QString newText; - StructStack structs; - - QString currentPage; - QString currentFn; - QString currentTitle; - QString currentEnum; - QString currentProperty; - QString currentVariable; - QString currentExample; - QString currentGroup; - QString currentModule; - QString currentMacro; - QString currentService; - QString currentTypedef; - QString currentHeaderFile; - static QString currentClass; - - static int doxPass; - static QSet anchors; - static QStringMap exampleTitles; - static QStringMap headerFileTitles; - static QStringMap fileTitles; - static QStringMap groupTitles; - static QStringMap moduleTitles; - static QStringMap pageTitles; - static QStringMap externalPageTitles; - static QStringMap exampleTitlesInverse; - static QStringMap headerFileTitlesInverse; - static QStringMap fileTitlesInverse; - static QStringMap groupTitlesInverse; - static QStringMap moduleTitlesInverse; - static QStringMap pageTitlesInverse; - static QStringMap externalPageTitlesInverse; - - static QStringMultiMap variables; - static QStringMultiMap properties; - static QStringMultiMap enums; -}; - -#endif - QT_END_NAMESPACE #endif diff --git a/tools/qdoc3/main.cpp b/tools/qdoc3/main.cpp index 5c247fa..514d06e 100644 --- a/tools/qdoc3/main.cpp +++ b/tools/qdoc3/main.cpp @@ -98,8 +98,6 @@ static bool slow = false; static QStringList defines; static QHash trees; -//static int doxygen = 0; - /*! Find the Tree for language \a lang and return a pointer to it. If there is no Tree for language \a lang in the Tree table, add @@ -224,18 +222,6 @@ static void processQdocconfFile(const QString &fileName) QString lang = config.getString(CONFIG_LANGUAGE); Location langLocation = config.lastLocation(); -#ifdef QDOC2DOX - // qdoc -> doxygen - if (doxygen == 2) { - qDebug() << "READING anchors.txt"; - DoxWriter::readAnchors(); - qDebug() << "READING title maps"; - DoxWriter::readTitles(); - qDebug() << "READING member multimaps"; - DoxWriter::readMembers(); - } -#endif - /* Initialize the tree where all the parsed sources will be stored. The tree gets built as the source files are parsed, and then the @@ -322,17 +308,6 @@ static void processQdocconfFile(const QString &fileName) tree->resolveGroups(); tree->resolveTargets(); -#ifdef QDOC2DOX - // qdoc -> doxygen - if (doxygen == 1) { - DoxWriter::writeAnchors(); - DoxWriter::writeTitles(); - DoxWriter::writeMembers(); - } - - if (doxygen == 0) { -#endif - /* Now the tree has been built, and all the stuff that needed resolving has been resolved. Now it is time to traverse @@ -357,11 +332,6 @@ static void processQdocconfFile(const QString &fileName) tree->setVersion(""); Generator::terminate(); - -#ifdef QDOC2DOX - } -#endif - CodeParser::terminate(); CodeMarker::terminate(); CppToQsConverter::terminate(); @@ -456,26 +426,6 @@ int main(int argc, char **argv) else if (opt == "-slow") { slow = true; } - -#ifdef QDOC2DOX - else if (opt == "-doxygen1") { - // qdoc -> doxygen - // Don't use this; it isn't ready yet. - // Now it's a fossil. - qDebug() << "doxygen pass 1"; - doxygen = 1; - DoxWriter::setDoxPass(1); - } - else if (opt == "-doxygen2") { - // qdoc -> doxygen - // Don't use this; it isn't ready yet. - // Now it's a fossil. - qDebug() << "doxygen pass 2"; - doxygen = 2; - DoxWriter::setDoxPass(2); - } -#endif - else { qdocFiles.append(opt); } -- cgit v0.12 From 49108bbc2bf79157f1be0f837db08f72408764cb Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 28 May 2009 14:46:03 +0200 Subject: small cleanup on the sub-attaq demo removed declaration of properties that are already declared in Qt --- examples/animation/sub-attaq/boat.h | 3 +-- examples/animation/sub-attaq/bomb.h | 3 +-- examples/animation/sub-attaq/graphicsscene.h | 2 +- examples/animation/sub-attaq/qanimationstate.h | 2 +- examples/animation/sub-attaq/submarine.h | 2 +- examples/animation/sub-attaq/torpedo.h | 3 +-- 6 files changed, 6 insertions(+), 9 deletions(-) diff --git a/examples/animation/sub-attaq/boat.h b/examples/animation/sub-attaq/boat.h index 08a9fa2..b412739 100644 --- a/examples/animation/sub-attaq/boat.h +++ b/examples/animation/sub-attaq/boat.h @@ -59,7 +59,6 @@ QT_END_NAMESPACE class Boat : public QGraphicsWidget { Q_OBJECT -Q_PROPERTY(QPointF pos READ pos WRITE setPos) public: enum Movement { None = 0, @@ -85,7 +84,7 @@ public: virtual int type() const; -Q_SIGNALS: +signals: void boatDestroyed(); void boatExecutionFinished(); diff --git a/examples/animation/sub-attaq/bomb.h b/examples/animation/sub-attaq/bomb.h index 226d056..cfd42e5 100644 --- a/examples/animation/sub-attaq/bomb.h +++ b/examples/animation/sub-attaq/bomb.h @@ -51,7 +51,6 @@ class PixmapItem; class Bomb : public QGraphicsWidget { Q_OBJECT -Q_PROPERTY(QPointF pos READ pos WRITE setPos) public: enum Direction { Left = 0, @@ -61,7 +60,7 @@ public: void launch(Direction direction); void destroy(); -Q_SIGNALS: +signals: void bombExplosed(); void bombExecutionFinished(); diff --git a/examples/animation/sub-attaq/graphicsscene.h b/examples/animation/sub-attaq/graphicsscene.h index 8b0ea96..1e6618a 100644 --- a/examples/animation/sub-attaq/graphicsscene.h +++ b/examples/animation/sub-attaq/graphicsscene.h @@ -90,7 +90,7 @@ public: void clearScene(); QGraphicsPixmapItem *addWelcomeItem(const QPixmap &pm); -Q_SIGNALS: +signals: void subMarineDestroyed(int); void allSubMarineDestroyed(int); diff --git a/examples/animation/sub-attaq/qanimationstate.h b/examples/animation/sub-attaq/qanimationstate.h index e5322ad..72bb2d9 100644 --- a/examples/animation/sub-attaq/qanimationstate.h +++ b/examples/animation/sub-attaq/qanimationstate.h @@ -70,7 +70,7 @@ public: void setAnimation(QAbstractAnimation *animation); QAbstractAnimation* animation() const; -Q_SIGNALS: +signals: void animationFinished(); protected: diff --git a/examples/animation/sub-attaq/submarine.h b/examples/animation/sub-attaq/submarine.h index 4001603..b8dd2da 100644 --- a/examples/animation/sub-attaq/submarine.h +++ b/examples/animation/sub-attaq/submarine.h @@ -75,7 +75,7 @@ public: virtual int type() const; -Q_SIGNALS: +signals: void subMarineDestroyed(); void subMarineExecutionFinished(); void subMarineStateChanged(); diff --git a/examples/animation/sub-attaq/torpedo.h b/examples/animation/sub-attaq/torpedo.h index 4a0f457..f5ab614 100644 --- a/examples/animation/sub-attaq/torpedo.h +++ b/examples/animation/sub-attaq/torpedo.h @@ -53,14 +53,13 @@ class PixmapItem; class Torpedo : public QGraphicsWidget { Q_OBJECT -Q_PROPERTY(QPointF pos READ pos WRITE setPos) public: Torpedo(QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0); void launch(); void setCurrentSpeed(int speed); void destroy(); -Q_SIGNALS: +signals: void torpedoExplosed(); void torpedoExecutionFinished(); -- cgit v0.12 From 8e2d3cc2e84b6d8109c30a853ea40ff9cfa29bcc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Thu, 28 May 2009 15:05:21 +0200 Subject: Minor cleanup. Reviewed-by: Kim --- tests/auto/qdatastream/tst_qdatastream.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tests/auto/qdatastream/tst_qdatastream.cpp b/tests/auto/qdatastream/tst_qdatastream.cpp index d7ca7bc..6a69fcc 100644 --- a/tests/auto/qdatastream/tst_qdatastream.cpp +++ b/tests/auto/qdatastream/tst_qdatastream.cpp @@ -462,7 +462,7 @@ void tst_QDataStream::writeQString(QDataStream* s) { QString test(QStringData(dataIndex(QTest::currentDataTag()))); *s << test; - *s << QString("Faen her spyr man"); + *s << QString("Her er det noe tekst"); *s << test; *s << QString(); *s << test; @@ -480,7 +480,7 @@ void tst_QDataStream::readQString(QDataStream *s) *s >> S; QCOMPARE(S, test); *s >> S; - QCOMPARE(S, QString("Faen her spyr man")); + QCOMPARE(S, QString("Her er det noe tekst")); *s >> S; QCOMPARE(S, test); *s >> S; @@ -533,7 +533,7 @@ void tst_QDataStream::writeQRegExp(QDataStream* s) { QRegExp test(QRegExpData(dataIndex(QTest::currentDataTag()))); *s << test; - *s << QString("Faen her spyr man"); + *s << QString("Her er det noe tekst"); *s << test; *s << QString("nonempty"); *s << test; @@ -550,7 +550,7 @@ void tst_QDataStream::readQRegExp(QDataStream *s) *s >> R; QCOMPARE(R, test); *s >> S; - QCOMPARE(S, QString("Faen her spyr man")); + QCOMPARE(S, QString("Her er det noe tekst")); *s >> R; QCOMPARE(R, test); *s >> S; -- cgit v0.12 From 408ca46193f70ff66d060f7b7c506a97fee945e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Thu, 28 May 2009 15:07:01 +0200 Subject: Fixed a problem with streaming QIcons containing multiple pixmaps. If pixmaps were added through QIcon::addFile() with different sizes than the sizes of the pixmaps themselves, streaming the icon in didn't work properly. Task-number: 254374 Reviewed-by: Kim --- src/gui/image/qicon.cpp | 9 ++++++--- tests/auto/qicon/tst_qicon.cpp | 43 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 3 deletions(-) diff --git a/src/gui/image/qicon.cpp b/src/gui/image/qicon.cpp index a880a13..0799ea7 100644 --- a/src/gui/image/qicon.cpp +++ b/src/gui/image/qicon.cpp @@ -428,10 +428,13 @@ bool QPixmapIconEngine::read(QDataStream &in) in >> sz; in >> mode; in >> state; - if (pm.isNull()) + if (pm.isNull()) { addFile(fileName, sz, QIcon::Mode(mode), QIcon::State(state)); - else - addPixmap(pm, QIcon::Mode(mode), QIcon::State(state)); + } else { + QPixmapIconEngineEntry pe(fileName, sz, QIcon::Mode(mode), QIcon::State(state)); + pe.pixmap = pm; + pixmaps += pe; + } } return true; } diff --git a/tests/auto/qicon/tst_qicon.cpp b/tests/auto/qicon/tst_qicon.cpp index 4e9a880..1dd223f 100644 --- a/tests/auto/qicon/tst_qicon.cpp +++ b/tests/auto/qicon/tst_qicon.cpp @@ -72,6 +72,8 @@ private slots: void svg(); void addFile(); void availableSizes(); + void streamAvailableSizes_data(); + void streamAvailableSizes(); void task184901_badCache(); void task223279_inconsistentAddFile(); @@ -540,6 +542,47 @@ void tst_QIcon::availableSizes() } } +void tst_QIcon::streamAvailableSizes_data() +{ + QTest::addColumn("icon"); + + QIcon icon; + icon.addFile(":/image.png", QSize(32,32)); + QTest::newRow( "32x32" ) << icon; + icon.addFile(":/image.png", QSize(64,64)); + QTest::newRow( "64x64" ) << icon; + icon.addFile(":/image.png", QSize(128,128)); + QTest::newRow( "128x128" ) << icon; + icon.addFile(":/image.png", QSize(256,256)); + QTest::newRow( "256x256" ) << icon; +} + +void tst_QIcon::streamAvailableSizes() +{ + QFETCH(QIcon, icon); + + QByteArray ba; + // write to QByteArray + { + QBuffer buffer(&ba); + buffer.open(QIODevice::WriteOnly); + QDataStream stream(&buffer); + stream << icon; + } + + // read from QByteArray + { + QBuffer buffer(&ba); + buffer.open(QIODevice::ReadOnly); + QDataStream stream(&buffer); + QIcon i; + stream >> i; + QCOMPARE(i.isNull(), icon.isNull()); + QCOMPARE(i.availableSizes(), icon.availableSizes()); + } +} + + static inline bool operator<(const QSize &lhs, const QSize &rhs) { if (lhs.width() < rhs.width()) -- cgit v0.12 From 1bf86e118a168c9aa6bed95bbe4b095f36e4a3cb Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Thu, 28 May 2009 15:03:40 +0200 Subject: Polished aboutQt dialog a little bit. Splitted text in the AboutQt dialog into several chunks to make use of advanced qmessagebox text fields Reviewed-By: Trenton Schulz --- src/gui/dialogs/qmessagebox.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/gui/dialogs/qmessagebox.cpp b/src/gui/dialogs/qmessagebox.cpp index 6790c3d..1734e85 100644 --- a/src/gui/dialogs/qmessagebox.cpp +++ b/src/gui/dialogs/qmessagebox.cpp @@ -1684,10 +1684,13 @@ void QMessageBox::aboutQt(QWidget *parent, const QString &title) } #endif - QString translatedTextAboutQt; - translatedTextAboutQt = QMessageBox::tr( + QString translatedTextAboutQtCaption; + translatedTextAboutQtCaption = QMessageBox::tr( "

    About Qt

    " "

    This program uses Qt version %1.

    " + ).arg(QLatin1String(QT_VERSION_STR)); + QString translatedTextAboutQtText; + translatedTextAboutQtText = QMessageBox::tr( "

    Qt is a C++ toolkit for cross-platform application " "development.

    " "

    Qt provides single-source portability across MS Windows, " @@ -1715,12 +1718,12 @@ void QMessageBox::aboutQt(QWidget *parent, const QString &title) "

    Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).

    " "

    Qt is a Nokia product. See www.qtsoftware.com/qt " "for more information.

    " - ).arg(QLatin1String(QT_VERSION_STR)); - + ); QMessageBox *msgBox = new QMessageBox(parent); msgBox->setAttribute(Qt::WA_DeleteOnClose); msgBox->setWindowTitle(title.isEmpty() ? tr("About Qt") : title); - msgBox->setInformativeText(translatedTextAboutQt); + msgBox->setText(translatedTextAboutQtCaption); + msgBox->setInformativeText(translatedTextAboutQtText); QPixmap pm(QLatin1String(":/trolltech/qmessagebox/images/qtlogo-64.png")); if (!pm.isNull()) -- cgit v0.12 From 7f353ae912a935b9837cd5a00de295ec64a220af Mon Sep 17 00:00:00 2001 From: Brad Hards Date: Mon, 25 May 2009 21:49:12 +1000 Subject: Remove duplicate qpdf_p.h include. --- src/gui/text/qfontengine_ft.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/gui/text/qfontengine_ft.cpp b/src/gui/text/qfontengine_ft.cpp index 6f5ee1f..a93c391 100644 --- a/src/gui/text/qfontengine_ft.cpp +++ b/src/gui/text/qfontengine_ft.cpp @@ -54,8 +54,6 @@ #include #include -#include - #include "qfontengine_ft_p.h" #include #include FT_FREETYPE_H -- cgit v0.12 From 83f4dc2ab88f64460cd8742a5d70ee6fb46e44a9 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 28 May 2009 15:55:48 +0200 Subject: oops, build was broken on embedded --- src/gui/text/qfontengine_qpf.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/text/qfontengine_qpf.cpp b/src/gui/text/qfontengine_qpf.cpp index 28eb362..8222b7f 100644 --- a/src/gui/text/qfontengine_qpf.cpp +++ b/src/gui/text/qfontengine_qpf.cpp @@ -320,7 +320,7 @@ QFontEngineQPF::QFontEngineQPF(const QFontDef &def, int fileDescriptor, QFontEng + QString::number(fontDef.pixelSize) + QLatin1Char('_') + QString::number(fontDef.weight) + (fontDef.style != QFont::StyleNormal ? - QLatin1String("_italic") : QLatin1String()) + QLatin1String("_italic") : QLatin1String("")) + QLatin1String(".qsf"); fileName.replace(QLatin1Char(' '), QLatin1Char('_')); fileName.prepend(qws_fontCacheDir()); -- cgit v0.12 From 4a44a8b4be1ba827ccaee8bf19903c6adb9c0900 Mon Sep 17 00:00:00 2001 From: Brad Hards Date: Tue, 26 May 2009 13:38:42 +1000 Subject: Fix build when compiling Qt using -no-opengl configuration. --- examples/animation/sub-attaq/mainwindow.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/examples/animation/sub-attaq/mainwindow.cpp b/examples/animation/sub-attaq/mainwindow.cpp index 9cf9eb5..5e8e259 100644 --- a/examples/animation/sub-attaq/mainwindow.cpp +++ b/examples/animation/sub-attaq/mainwindow.cpp @@ -44,9 +44,12 @@ #include "graphicsscene.h" //Qt -#include -#ifndef QT_NO_OPENGL -#include +#ifdef QT_NO_OPENGL + #include + #include + #include +#else + #include #endif MainWindow::MainWindow() : QMainWindow(0) -- cgit v0.12 From f22350c32392da6b3dc2af2c9079d312f262f441 Mon Sep 17 00:00:00 2001 From: hjk Date: Thu, 28 May 2009 16:35:24 +0200 Subject: QStringBuilder benchmark: make testing of the drop-in replacement operator+() easier. This adds a few explicit QString(...) casts around operator+() based expressions to make them acceptable for QCOMPARE. --- tests/benchmarks/qstringbuilder/main.cpp | 34 +++++++++++----------- tests/benchmarks/qstringbuilder/qstringbuilder.pro | 4 +++ 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/tests/benchmarks/qstringbuilder/main.cpp b/tests/benchmarks/qstringbuilder/main.cpp index cb76925..8eb4e78 100644 --- a/tests/benchmarks/qstringbuilder/main.cpp +++ b/tests/benchmarks/qstringbuilder/main.cpp @@ -72,7 +72,7 @@ private slots: void b_2_l1literal() { QBENCHMARK { r = l1literal % l1literal; } - COMPARE(r, l1string + l1string); + COMPARE(r, QString(l1string + l1string)); } void s_2_l1string() { QBENCHMARK { r = l1string + l1string; } @@ -84,7 +84,7 @@ private slots: void b_2_string() { QBENCHMARK { r = string % string; } - COMPARE(r, string + string); + COMPARE(r, QString(string + string)); } void s_2_string() { QBENCHMARK { r = string + string; } @@ -96,7 +96,7 @@ private slots: void b_2_stringref() { QBENCHMARK { r = stringref % stringref; } - COMPARE(r, stringref.toString() + stringref.toString()); + COMPARE(r, QString(stringref.toString() + stringref.toString())); } void s_2_stringref() { QBENCHMARK { r = stringref.toString() + stringref.toString(); } @@ -108,7 +108,7 @@ private slots: void b_3_string() { QBENCHMARK { r = string % string % string; } - COMPARE(r, string + string + string); + COMPARE(r, QString(string + string + string)); } void s_3_string() { QBENCHMARK { r = string + string + string; } @@ -120,11 +120,11 @@ private slots: void b_string_l1literal() { QBENCHMARK { r = string % l1literal; } - COMPARE(r, string + l1string); + COMPARE(r, QString(string + l1string)); } void b_string_l1string() { QBENCHMARK { r = string % l1string; } - COMPARE(r, string + l1string); + COMPARE(r, QString(string + l1string)); } void s_string_l1literal() { QBENCHMARK { r = string + l1string; } @@ -140,7 +140,7 @@ private slots: void b_3_l1literal() { QBENCHMARK { r = l1literal % l1literal % l1literal; } - COMPARE(r, l1string + l1string + l1string); + COMPARE(r, QString(l1string + l1string + l1string)); } void s_3_l1string() { QBENCHMARK { r = l1string + l1string + l1string; } @@ -152,7 +152,7 @@ private slots: void b_4_l1literal() { QBENCHMARK { r = l1literal % l1literal % l1literal % l1literal; } - COMPARE(r, l1string + l1string + l1string + l1string); + COMPARE(r, QString(l1string + l1string + l1string + l1string)); } void s_4_l1string() { QBENCHMARK { r = l1string + l1string + l1string + l1string; } @@ -164,7 +164,7 @@ private slots: void b_5_l1literal() { QBENCHMARK { r = l1literal % l1literal % l1literal % l1literal %l1literal; } - COMPARE(r, l1string + l1string + l1string + l1string + l1string); + COMPARE(r, QString(l1string + l1string + l1string + l1string + l1string)); } void s_5_l1string() { @@ -201,15 +201,15 @@ private slots: void separator_8() { SEP("string.arg"); } void b_string_arg() { - const QString pattern = l1string + "%1" + l1string; + const QString pattern = l1string + QLatin1String("%1") + l1string; QBENCHMARK { r = l1literal % string % l1literal; } - COMPARE(r, l1string + string + l1string); + COMPARE(r, QString(l1string + string + l1string)); } void s_string_arg() { - const QString pattern = l1string + "%1" + l1string; + const QString pattern = l1string + QLatin1String("%1") + l1string; QBENCHMARK { r = pattern.arg(string); } - COMPARE(r, l1string + string + l1string); + COMPARE(r, QString(l1string + string + l1string)); } void s_bytearray_arg() { @@ -225,14 +225,14 @@ private slots: r.clear(); r = string % string % string % string; } - COMPARE(r, string + string + string + string); + COMPARE(r, QString(string + string + string + string)); } void b_reserve_lit() { QBENCHMARK { r.clear(); r = string % l1literal % string % string; } - COMPARE(r, string + string + string + string); + COMPARE(r, QString(string + string + string + string)); } void s_reserve() { QBENCHMARK { @@ -243,7 +243,7 @@ private slots: r += string; r += string; } - COMPARE(r, string + string + string + string); + COMPARE(r, QString(string + string + string + string)); } void s_reserve_lit() { QBENCHMARK { @@ -256,7 +256,7 @@ private slots: r += string; r += string; } - COMPARE(r, string + string + string + string); + COMPARE(r, QString(string + string + string + string)); } private: diff --git a/tests/benchmarks/qstringbuilder/qstringbuilder.pro b/tests/benchmarks/qstringbuilder/qstringbuilder.pro index 79171b4..02daaaa 100644 --- a/tests/benchmarks/qstringbuilder/qstringbuilder.pro +++ b/tests/benchmarks/qstringbuilder/qstringbuilder.pro @@ -2,6 +2,10 @@ load(qttest_p4) TEMPLATE = app TARGET = tst_qstringbuilder +# Uncomment to test compilation of the drop-in +# replacement operator+() +#DEFINES += QT_USE_FAST_OPERATOR_PLUS + QMAKE_CXXFLAGS += -g QMAKE_CFLAGS += -g -- cgit v0.12 From 09ae2f274b417bab4abee8900c5ad0a8f01d65b1 Mon Sep 17 00:00:00 2001 From: Benjamin Poulain Date: Thu, 28 May 2009 16:39:48 +0200 Subject: Scroll the dirty region with WA_PaintOnScreen When QWidget::scroll() is called on a widget with WA_PaintOnScreen, scroll the dirty region. Task-number: 254742 Reviewed-by: bnilsen --- src/gui/kernel/qwidget_x11.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/gui/kernel/qwidget_x11.cpp b/src/gui/kernel/qwidget_x11.cpp index 6202b35..e00c37c 100644 --- a/src/gui/kernel/qwidget_x11.cpp +++ b/src/gui/kernel/qwidget_x11.cpp @@ -2487,6 +2487,8 @@ void QWidgetPrivate::scroll_sys(int dx, int dy, const QRect &r) QRect sr = valid_rect ? r : clipRect(); if (just_update) q->update(); + else if (!valid_rect) + dirty.translate(dx, dy); int x1, y1, x2, y2, w = sr.width(), h = sr.height(); if (dx > 0) { -- cgit v0.12 From 89029a54cb3adfb54736a6aafaea9ec535407592 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Thu, 28 May 2009 14:57:20 +0200 Subject: cosmetic changes to examples/dialogs/sipdialog main function has a return value now. On the HTC this example didn't work, because this stupid thing sends two resize events, if the SIP is opened (and only one if it is closed). Reviewed-by: mauricek --- examples/dialogs/sipdialog/dialog.cpp | 13 ++++++------- examples/dialogs/sipdialog/main.cpp | 2 +- 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/examples/dialogs/sipdialog/dialog.cpp b/examples/dialogs/sipdialog/dialog.cpp index 9f1b9ad..653b518 100644 --- a/examples/dialogs/sipdialog/dialog.cpp +++ b/examples/dialogs/sipdialog/dialog.cpp @@ -90,7 +90,7 @@ Dialog::Dialog() //! [Dialog constructor part4] //! [Dialog constructor part5] - connect(button, SIGNAL(pressed()), + connect(button, SIGNAL(clicked()), qApp, SLOT(closeAllWindows())); connect(QApplication::desktop(), SIGNAL(workAreaResized(int)), this, SLOT(desktopResized(int))); @@ -111,14 +111,13 @@ void Dialog::reactToSIP() { QRect availableGeometry = QApplication::desktop()->availableGeometry(0); - if (desktopGeometry.width() == availableGeometry.width()) { - if (desktopGeometry.height() > availableGeometry.height()) { + if (desktopGeometry != availableGeometry) { + if (windowState() | Qt::WindowMaximized) setWindowState(windowState() & ~Qt::WindowMaximized); - setGeometry(availableGeometry); - } else { - setWindowState(windowState() | Qt::WindowMaximized); - } + + setGeometry(availableGeometry); } + desktopGeometry = availableGeometry; } //! [reactToSIP() function] diff --git a/examples/dialogs/sipdialog/main.cpp b/examples/dialogs/sipdialog/main.cpp index 5fcbfd8..fec6de2 100644 --- a/examples/dialogs/sipdialog/main.cpp +++ b/examples/dialogs/sipdialog/main.cpp @@ -48,6 +48,6 @@ int main(int argc, char *argv[]) { QApplication app(argc, argv); Dialog dialog; - dialog.exec(); + return dialog.exec(); } //! [main() function] -- cgit v0.12 From 8e4300e2866fd28881853509df6ff054e13f841b Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Thu, 28 May 2009 14:46:39 +0200 Subject: Fix wrong sorting when using the QFileSystemModel with QTreeView An optimization was made to the sorting of QFileDialog to sort only the current root (meaning what the user see). This avoided slowness when the model was big with lots of leafs. The problem here is for the treeview, the root is always the same, we expands only nodes. In that case, a recursive sorting is needed to ensure that all expanded nodes are correctly sorted (and filtered). This will be slower that's why i use an hidden flag in the d pointer to deactivate the recursive sort for the QFileDialog. Task-number:254701 Reviewed-by:olivier BT:yes --- src/gui/dialogs/qfiledialog.cpp | 1 + src/gui/dialogs/qfilesystemmodel.cpp | 11 ++++ src/gui/dialogs/qfilesystemmodel_p.h | 7 ++- .../auto/qfilesystemmodel/tst_qfilesystemmodel.cpp | 65 +++++++++++++++++++++- 4 files changed, 80 insertions(+), 4 deletions(-) diff --git a/src/gui/dialogs/qfiledialog.cpp b/src/gui/dialogs/qfiledialog.cpp index d42775a..d4d0136 100644 --- a/src/gui/dialogs/qfiledialog.cpp +++ b/src/gui/dialogs/qfiledialog.cpp @@ -2108,6 +2108,7 @@ void QFileDialogPrivate::createWidgets() #else model->setNameFilterDisables(false); #endif + model->d_func()->disableRecursiveSort = true; QFileDialog::connect(model, SIGNAL(fileRenamed(const QString &, const QString &, const QString &)), q, SLOT(_q_fileRenamed(const QString &, const QString &, const QString &))); QFileDialog::connect(model, SIGNAL(rootPathChanged(const QString &)), q, SLOT(_q_pathChanged(const QString &))); diff --git a/src/gui/dialogs/qfilesystemmodel.cpp b/src/gui/dialogs/qfilesystemmodel.cpp index 012d3a1..03017c3 100644 --- a/src/gui/dialogs/qfilesystemmodel.cpp +++ b/src/gui/dialogs/qfilesystemmodel.cpp @@ -1083,6 +1083,7 @@ private: */ void QFileSystemModelPrivate::sortChildren(int column, const QModelIndex &parent) { + Q_Q(QFileSystemModel); QFileSystemModelPrivate::QFileSystemNode *indexNode = node(parent); if (indexNode->children.count() == 0) return; @@ -1106,6 +1107,16 @@ void QFileSystemModelPrivate::sortChildren(int column, const QModelIndex &parent indexNode->visibleChildren.append(values.at(i).first->fileName); values.at(i).first->isVisible = true; } + + if (!disableRecursiveSort) { + for (int i = 0; i < q->rowCount(parent); ++i) { + const QModelIndex childIndex = q->index(i, 0, parent); + QFileSystemModelPrivate::QFileSystemNode *indexNode = node(childIndex); + //Only do a recursive sort on visible nodes + if (indexNode->isVisible) + sortChildren(column, childIndex); + } + } } /*! diff --git a/src/gui/dialogs/qfilesystemmodel_p.h b/src/gui/dialogs/qfilesystemmodel_p.h index 61e8b4c..af4fada 100644 --- a/src/gui/dialogs/qfilesystemmodel_p.h +++ b/src/gui/dialogs/qfilesystemmodel_p.h @@ -208,7 +208,8 @@ public: readOnly(true), setRootPath(false), filters(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs), - nameFilterDisables(true) // false on windows, true on mac and unix + nameFilterDisables(true), // false on windows, true on mac and unix + disableRecursiveSort(false) { delayedSortTimer.setSingleShot(true); } @@ -294,6 +295,10 @@ public: QDir::Filters filters; QHash bypassFilters; bool nameFilterDisables; + //This flag is an optimization for the QFileDialog + //It enable a sort which is not recursive, it means + //we sort only what we see. + bool disableRecursiveSort; #ifndef QT_NO_REGEXP QList nameFilters; #endif diff --git a/tests/auto/qfilesystemmodel/tst_qfilesystemmodel.cpp b/tests/auto/qfilesystemmodel/tst_qfilesystemmodel.cpp index 59d57ce..b109d4b 100644 --- a/tests/auto/qfilesystemmodel/tst_qfilesystemmodel.cpp +++ b/tests/auto/qfilesystemmodel/tst_qfilesystemmodel.cpp @@ -43,6 +43,7 @@ #include #include "../../../src/gui/dialogs/qfilesystemmodel_p.h" #include +#include #include "../../shared/util.h" #include #include @@ -102,6 +103,7 @@ private slots: void setData_data(); void setData(); + void sort_data(); void sort(); void mkdir(); @@ -452,8 +454,12 @@ void tst_QFileSystemModel::rowsInserted() } else { QCOMPARE(model->index(model->rowCount(root) - 1, 0, root).data().toString(), QString("b")); } - if (spy0.count() > 0) - if (count == 0) QCOMPARE(spy0.count(), 0); else QVERIFY(spy0.count() >= 1); + if (spy0.count() > 0) { + if (count == 0) + QCOMPARE(spy0.count(), 0); + else + QVERIFY(spy0.count() >= 1); + } if (count == 0) QCOMPARE(spy1.count(), 0); else QVERIFY(spy1.count() >= 1); QVERIFY(createFiles(tmp, QStringList(".hidden_file"), 5 + count)); @@ -722,6 +728,19 @@ void tst_QFileSystemModel::setData() QTRY_COMPARE(model->rowCount(root), files.count()); } +class MyFriendFileSystemModel : public QFileSystemModel +{ + friend class tst_QFileSystemModel; + Q_DECLARE_PRIVATE(QFileSystemModel) +}; + +void tst_QFileSystemModel::sort_data() +{ + QTest::addColumn("fileDialogMode"); + QTest::newRow("standard usage") << false; + QTest::newRow("QFileDialog usage") << true; +} + void tst_QFileSystemModel::sort() { QTemporaryFile file; @@ -733,8 +752,48 @@ void tst_QFileSystemModel::sort() model->sort(0, Qt::AscendingOrder); model->sort(0, Qt::DescendingOrder); QVERIFY(idx.column() != 0); -} + QFETCH(bool, fileDialogMode); + + MyFriendFileSystemModel *myModel = new MyFriendFileSystemModel(); + QTreeView *tree = new QTreeView(); + + if (fileDialogMode) + myModel->d_func()->disableRecursiveSort = true; + + const QString dirPath = QString("%1/sortTemp").arg(QDir::tempPath()); + QDir dir(dirPath); + dir.mkpath(dirPath); + QVERIFY(dir.exists()); + dir.mkdir("a"); + dir.mkdir("b"); + dir.mkdir("c"); + dir.mkdir("d"); + dir.mkdir("e"); + dir.mkdir("f"); + dir.mkdir("g"); + QTemporaryFile tempFile(dirPath + "/rXXXXXX"); + tempFile.open(); + myModel->setRootPath(QDir::rootPath()); + tree->setModel(myModel); + tree->show(); + QTest::qWait(500); + tree->expand(myModel->index(dir.absolutePath(), 0)); + while (dir.cdUp()) + { + tree->expand(myModel->index(dir.absolutePath(), 0)); + } + QTest::qWait(250); + //File dialog Mode means sub trees are not sorted, only the current root + if (fileDialogMode) + QVERIFY(myModel->index(0, 1, myModel->index(dirPath, 0)).data(QFileSystemModel::FilePathRole).toString() != dirPath + QLatin1String("/a")); + else + QCOMPARE(myModel->index(0, 1, myModel->index(dirPath, 0)).data(QFileSystemModel::FilePathRole).toString(), dirPath + QLatin1String("/a")); + + delete tree; + delete myModel; + +} void tst_QFileSystemModel::mkdir() { -- cgit v0.12 From 4a82680736ace8abb46e6fb5e085e8622f154b2d Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Thu, 28 May 2009 17:24:53 +0200 Subject: Fix a ASSERT/Crash when adding two times the same QAction to a QGW. We were adding two times in the QActionPrivate list the entry for the current QGraphicsWidget if the action was existing before. Task-number:KDE Reviewed-by:bnilsen BT:yes --- src/gui/graphicsview/qgraphicswidget.cpp | 6 ++++-- tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp | 16 ++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 7f02fb9..7781258 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -1887,8 +1887,10 @@ void QGraphicsWidget::insertAction(QAction *before, QAction *action) } d->actions.insert(pos, action); - QActionPrivate *apriv = action->d_func(); - apriv->graphicsWidgets.append(this); + if (index == -1) { + QActionPrivate *apriv = action->d_func(); + apriv->graphicsWidgets.append(this); + } QActionEvent e(QEvent::ActionAdded, action, before); QApplication::sendEvent(this, &e); diff --git a/tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp b/tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp index b85abd3..1917357 100644 --- a/tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp +++ b/tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp @@ -51,6 +51,7 @@ #include #include #include +#include #include "../../shared/util.h" @@ -147,6 +148,7 @@ private slots: void setSizes(); void closePopupOnOutsideClick(); void defaultSize(); + void shortcutsDeletion(); // Task fixes void task236127_bspTreeIndexFails(); @@ -1782,6 +1784,20 @@ void tst_QGraphicsWidget::defaultSize() } +void tst_QGraphicsWidget::shortcutsDeletion() +{ + QGraphicsWidget *widget = new QGraphicsWidget; + QGraphicsWidget *widget2 = new QGraphicsWidget; + widget->setMinimumSize(40, 40); + QWidgetAction *del = new QWidgetAction(widget); + del->setIcon(QIcon("edit-delete")); + del->setShortcut(Qt::Key_Delete); + del->setShortcutContext(Qt::WidgetShortcut); + widget2->addAction(del); + widget2->addAction(del); + delete widget; +} + class ProxyStyle : public QCommonStyle { public: -- cgit v0.12 From 866813b6779a27e974c30d1023a5d734fa0318c9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 28 May 2009 19:06:42 +0200 Subject: Fixed bug in GL graphics system when painting to pixmaps. Make sure the correct texture unit is active when copying from the pixmap to the FBO in begin(). --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 75422a2..e7b6ee4 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -1009,8 +1009,11 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) } glClear(GL_COLOR_BUFFER_BIT); } else if (source) { + QGLContext *ctx = d->ctx; + d->transferMode(ImageDrawingMode); + glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT); source->bind(false); QRect rect(0, 0, source->width(), source->height()); -- cgit v0.12 From 36ae58e7a6a888d3ae7bd162d59daada550bbfb1 Mon Sep 17 00:00:00 2001 From: Anders Bakken Date: Thu, 28 May 2009 10:51:32 -0700 Subject: Warn when trying to use an unsupported format Due to incompatibilities between RGB32 in DirectFB and Qt we can't use RGB32. Reviewed-by: Donald --- src/plugins/gfxdrivers/directfb/qdirectfbscreen.cpp | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbscreen.cpp b/src/plugins/gfxdrivers/directfb/qdirectfbscreen.cpp index 98e32ed..9e35a66 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbscreen.cpp +++ b/src/plugins/gfxdrivers/directfb/qdirectfbscreen.cpp @@ -958,9 +958,6 @@ bool QDirectFBScreen::connect(const QString &displaySpec) return false; } - if (displayArgs.contains(QLatin1String("debug"), Qt::CaseInsensitive)) - printDirectFBInfo(d_ptr->dfb, d_ptr->dfbSurface); - // Work out what format we're going to use for surfaces with an alpha channel d_ptr->alphaPixmapFormat = QDirectFBScreen::getImageFormat(d_ptr->dfbSurface); setPixelFormat(d_ptr->alphaPixmapFormat); @@ -971,12 +968,17 @@ bool QDirectFBScreen::connect(const QString &displaySpec) case QImage::Format_RGB444: d_ptr->alphaPixmapFormat = QImage::Format_ARGB4444_Premultiplied; break; + case QImage::Format_RGB32: + qWarning("QDirectFBScreen::connect(). Qt/DirectFB does not work with the RGB32 pixelformat. " + "We recommmend using ARGB instead"); + return false; + case QImage::Format_Indexed8: + qWarning("QDirectFBScreen::connect(). Qt/DirectFB does not work with the LUT8 pixelformat."); + return false; case QImage::NImageFormats: case QImage::Format_Invalid: case QImage::Format_Mono: case QImage::Format_MonoLSB: - case QImage::Format_Indexed8: - case QImage::Format_RGB32: case QImage::Format_RGB888: case QImage::Format_RGB16: case QImage::Format_RGB555: @@ -1037,6 +1039,9 @@ bool QDirectFBScreen::connect(const QString &displaySpec) setGraphicsSystem(d_ptr); + if (displayArgs.contains(QLatin1String("debug"), Qt::CaseInsensitive)) + printDirectFBInfo(d_ptr->dfb, d_ptr->dfbSurface); + return true; } -- cgit v0.12 From 36bc35c451b6123b0e237430343a80db8a600b24 Mon Sep 17 00:00:00 2001 From: Anders Bakken Date: Thu, 28 May 2009 10:57:45 -0700 Subject: Remove all force raster on RGB32 stuff Previously we allowed RGB32 but forced fallbacks for all drawing operations. It turns out blitting operations doesn't work right either so we'll rather just disallow this format altogether. See also 36ae58e7a6a888d3ae7bd162d59daada550bbfb1 Reviewed-by: Donald --- .../gfxdrivers/directfb/qdirectfbpaintdevice.h | 4 -- .../gfxdrivers/directfb/qdirectfbpaintengine.cpp | 77 +++++++++------------- .../gfxdrivers/directfb/qdirectfbpixmap.cpp | 23 +------ .../gfxdrivers/directfb/qdirectfbwindowsurface.cpp | 3 - 4 files changed, 32 insertions(+), 75 deletions(-) diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbpaintdevice.h b/src/plugins/gfxdrivers/directfb/qdirectfbpaintdevice.h index 13f0a8f..180acaf 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbpaintdevice.h +++ b/src/plugins/gfxdrivers/directfb/qdirectfbpaintdevice.h @@ -61,8 +61,6 @@ public: void lockDirectFB(uint flags); void unlockDirectFB(); - inline bool forceRasterPrimitives() const { return forceRaster; } - // Reimplemented from QCustomRasterPaintDevice: void* memory() const; QImage::Format format() const; @@ -77,7 +75,6 @@ protected: dfbSurface(0), lockedImage(0), screen(scr), - forceRaster(false), lock(0), mem(0) {} @@ -95,7 +92,6 @@ protected: QImage *lockedImage; QDirectFBScreen *screen; int bpl; - bool forceRaster; uint lock; uchar *mem; private: diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp b/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp index a68bc8f..7535090 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp +++ b/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp @@ -81,7 +81,7 @@ template <> inline const bool* ptr(const bool &) { return 0; } template static void rasterFallbackWarn(const char *msg, const char *func, const device *dev, int scale, bool matrixRotShear, bool simplePen, - bool dfbHandledClip, bool forceRasterPrimitives, + bool dfbHandledClip, const char *nameOne, const T1 &one, const char *nameTwo, const T2 &two, const char *nameThree, const T3 &three) @@ -98,8 +98,7 @@ static void rasterFallbackWarn(const char *msg, const char *func, const device * dbg << "scale" << scale << "matrixRotShear" << matrixRotShear << "simplePen" << simplePen - << "dfbHandledClip" << dfbHandledClip - << "forceRasterPrimitives" << forceRasterPrimitives; + << "dfbHandledClip" << dfbHandledClip; const T1 *t1 = ptr(one); const T2 *t2 = ptr(two); @@ -125,7 +124,6 @@ static void rasterFallbackWarn(const char *msg, const char *func, const device * __FUNCTION__, state()->painter->device(), \ d_func()->scale, d_func()->matrixRotShear, \ d_func()->simplePen, d_func()->dfbCanHandleClip(), \ - d_func()->forceRasterPrimitives, \ #one, one, #two, two, #three, three); \ if (op & (QT_DIRECTFB_DISABLE_RASTERFALLBACKS)) \ return; @@ -140,7 +138,6 @@ static void rasterFallbackWarn(const char *msg, const char *func, const device * __FUNCTION__, state()->painter->device(), \ d_func()->scale, d_func()->matrixRotShear, \ d_func()->simplePen, d_func()->dfbCanHandleClip(), \ - d_func()->forceRasterPrimitives, \ #one, one, #two, two, #three, three); #else #define RASTERFALLBACK(op, one, two, three) @@ -263,7 +260,6 @@ private: QPen pen; bool antialiased; - bool forceRasterPrimitives; bool simplePen; @@ -408,8 +404,7 @@ void QDirectFBPaintEngine::drawRects(const QRect *rects, int rectCount) d->updateClip(); const QBrush &brush = state()->brush; if (!d->dfbCanHandleClip() || d->matrixRotShear - || !d->simplePen || d->forceRasterPrimitives - || !d->isSimpleBrush(brush)) { + || !d->simplePen || !d->isSimpleBrush(brush)) { RASTERFALLBACK(DRAW_RECTS, rectCount, VOID_ARG(), VOID_ARG()); d->lock(); QRasterPaintEngine::drawRects(rects, rectCount); @@ -434,8 +429,7 @@ void QDirectFBPaintEngine::drawRects(const QRectF *rects, int rectCount) d->updateClip(); const QBrush &brush = state()->brush; if (!d->dfbCanHandleClip() || d->matrixRotShear - || !d->simplePen || d->forceRasterPrimitives - || !d->isSimpleBrush(brush)) { + || !d->simplePen || !d->isSimpleBrush(brush)) { RASTERFALLBACK(DRAW_RECTS, rectCount, VOID_ARG(), VOID_ARG()); d->lock(); QRasterPaintEngine::drawRects(rects, rectCount); @@ -458,7 +452,7 @@ void QDirectFBPaintEngine::drawLines(const QLine *lines, int lineCount) { Q_D(QDirectFBPaintEngine); d->updateClip(); - if (!d->simplePen || !d->dfbCanHandleClip() || d->forceRasterPrimitives) { + if (!d->simplePen || !d->dfbCanHandleClip()) { RASTERFALLBACK(DRAW_LINES, lineCount, VOID_ARG(), VOID_ARG()); d->lock(); QRasterPaintEngine::drawLines(lines, lineCount); @@ -476,7 +470,7 @@ void QDirectFBPaintEngine::drawLines(const QLineF *lines, int lineCount) { Q_D(QDirectFBPaintEngine); d->updateClip(); - if (!d->simplePen || !d->dfbCanHandleClip() || d->forceRasterPrimitives) { + if (!d->simplePen || !d->dfbCanHandleClip()) { RASTERFALLBACK(DRAW_LINES, lineCount, VOID_ARG(), VOID_ARG()); d->lock(); QRasterPaintEngine::drawLines(lines, lineCount); @@ -691,8 +685,6 @@ void QDirectFBPaintEngine::fillRect(const QRectF &rect, const QBrush &brush) if (d->dfbCanHandleClip(rect) && !d->matrixRotShear) { switch (brush.style()) { case Qt::SolidPattern: { - if (d->forceRasterPrimitives) - break; d->unlock(); d->setDFBColor(brush.color()); const QRect r = d->transform.mapRect(rect).toRect(); @@ -720,7 +712,7 @@ void QDirectFBPaintEngine::fillRect(const QRectF &rect, const QColor &color) { Q_D(QDirectFBPaintEngine); d->updateClip(); - if (!d->dfbCanHandleClip() || d->matrixRotShear || d->forceRasterPrimitives) { + if (!d->dfbCanHandleClip() || d->matrixRotShear) { RASTERFALLBACK(FILL_RECT, rect, color, VOID_ARG()); d->lock(); QRasterPaintEngine::fillRect(rect, color); @@ -737,38 +729,32 @@ void QDirectFBPaintEngine::drawColorSpans(const QSpan *spans, int count, uint color) { Q_D(QDirectFBPaintEngine); - if (d->forceRasterPrimitives) { - RASTERFALLBACK(DRAW_COLORSPANS, count, color, VOID_ARG()); - d->lock(); - QRasterPaintEngine::drawColorSpans(spans, count, color); - } else { - color = INV_PREMUL(color); - - QVarLengthArray lines(count); - int j = 0; - for (int i = 0; i < count; ++i) { - if (spans[i].coverage == 255) { - lines[j].x1 = spans[i].x; - lines[j].y1 = spans[i].y; - lines[j].x2 = spans[i].x + spans[i].len - 1; - lines[j].y2 = spans[i].y; - ++j; - } else { - DFBSpan span = { spans[i].x, spans[i].len }; - uint c = BYTE_MUL(color, spans[i].coverage); - // ### how does this play with setDFBColor - d->surface->SetColor(d->surface, - qRed(c), qGreen(c), qBlue(c), qAlpha(c)); - d->surface->FillSpans(d->surface, spans[i].y, &span, 1); - } - } - if (j > 0) { + color = INV_PREMUL(color); + + QVarLengthArray lines(count); + int j = 0; + for (int i = 0; i < count; ++i) { + if (spans[i].coverage == 255) { + lines[j].x1 = spans[i].x; + lines[j].y1 = spans[i].y; + lines[j].x2 = spans[i].x + spans[i].len - 1; + lines[j].y2 = spans[i].y; + ++j; + } else { + DFBSpan span = { spans[i].x, spans[i].len }; + uint c = BYTE_MUL(color, spans[i].coverage); + // ### how does this play with setDFBColor d->surface->SetColor(d->surface, - qRed(color), qGreen(color), qBlue(color), - qAlpha(color)); - d->surface->DrawLines(d->surface, lines.data(), j); + qRed(c), qGreen(c), qBlue(c), qAlpha(c)); + d->surface->FillSpans(d->surface, spans[i].y, &span, 1); } } + if (j > 0) { + d->surface->SetColor(d->surface, + qRed(color), qGreen(color), qBlue(color), + qAlpha(color)); + d->surface->DrawLines(d->surface, lines.data(), j); + } } void QDirectFBPaintEngine::drawBufferSpan(const uint *buffer, int bufsize, @@ -803,7 +789,7 @@ void QDirectFBPaintEngine::initImageCache(int size) QDirectFBPaintEnginePrivate::QDirectFBPaintEnginePrivate(QDirectFBPaintEngine *p) - : surface(0), antialiased(false), forceRasterPrimitives(false), simplePen(false), + : surface(0), antialiased(false), simplePen(false), matrixRotShear(false), scale(NoScale), lastLockedHeight(-1), fbWidth(-1), fbHeight(-1), opacity(255), drawFlagsFromCompositionMode(0), blitFlagsFromCompositionMode(0), porterDuffRule(DSPD_SRC_OVER), dirtyClip(true), @@ -896,7 +882,6 @@ void QDirectFBPaintEnginePrivate::begin(QPaintDevice *device) device->devType()); } lockedMemory = 0; - forceRasterPrimitives = dfbDevice->forceRasterPrimitives(); surface->GetSize(surface, &fbWidth, &fbHeight); diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp b/src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp index c9b676a..dba1b51 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp +++ b/src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp @@ -76,7 +76,6 @@ void QDirectFBPixmapData::resize(int width, int height) format, QDirectFBScreen::TrackSurface); alpha = false; - forceRaster = (format == QImage::Format_RGB32); if (!dfbSurface) { invalidate(); qWarning("QDirectFBPixmapData::resize(): Unable to allocate surface"); @@ -187,7 +186,6 @@ void QDirectFBPixmapData::fromImage(const QImage &i, } dfbSurface = screen->copyToDFBSurface(img, format, QDirectFBScreen::TrackSurface); - forceRaster = (format == QImage::Format_RGB32); if (!dfbSurface) { qWarning("QDirectFBPixmapData::fromImage()"); invalidate(); @@ -216,7 +214,6 @@ void QDirectFBPixmapData::copy(const QPixmapData *data, const QRect &rect) invalidate(); return; } - forceRaster = (format == QImage::Format_RGB32); if (hasAlpha) { dfbSurface->Clear(dfbSurface, 0, 0, 0, 0); @@ -268,7 +265,6 @@ void QDirectFBPixmapData::fill(const QColor &color) screen->releaseDFBSurface(dfbSurface); format = screen->alphaPixmapFormat(); dfbSurface = screen->createDFBSurface(size, screen->alphaPixmapFormat(), QDirectFBScreen::TrackSurface); - forceRaster = false; setSerialNumber(++global_ser_no); if (!dfbSurface) { qWarning("QDirectFBPixmapData::fill()"); @@ -277,24 +273,7 @@ void QDirectFBPixmapData::fill(const QColor &color) } } - if (forceRaster) { - // in DSPF_RGB32 all dfb drawing causes the Alpha byte to be - // set to 0. This causes issues for the raster engine. - uchar *mem = QDirectFBScreen::lockSurface(dfbSurface, DSLF_WRITE, &bpl); - if (mem) { - const int h = QPixmapData::height(); - const int w = QPixmapData::width() * 4; // 4 bytes per 32 bit pixel - const int c = color.rgba(); - for (int i = 0; i < h; ++i) { - memset(mem, c, w); - mem += bpl; - } - dfbSurface->Unlock(dfbSurface); - } - } else { - dfbSurface->Clear(dfbSurface, color.red(), color.green(), color.blue(), - color.alpha()); - } + dfbSurface->Clear(dfbSurface, color.red(), color.green(), color.blue(), color.alpha()); } QPixmap QDirectFBPixmapData::transformed(const QTransform &transform, diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbwindowsurface.cpp b/src/plugins/gfxdrivers/directfb/qdirectfbwindowsurface.cpp index cd8796b..c7cae80 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbwindowsurface.cpp +++ b/src/plugins/gfxdrivers/directfb/qdirectfbwindowsurface.cpp @@ -127,7 +127,6 @@ void QDirectFBWindowSurface::createWindow() dfbSurface->Release(dfbSurface); dfbWindow->GetSurface(dfbWindow, &dfbSurface); - forceRaster = (format == QImage::Format_RGB32); #endif } #endif // QT_NO_DIRECTFB_WM @@ -164,7 +163,6 @@ void QDirectFBWindowSurface::setGeometry(const QRect &rect, const QRegion &mask) rect.width(), rect.height() }; result = primarySurface->GetSubSurface(primarySurface, &r, &dfbSurface); } - forceRaster = (dfbSurface && QDirectFBScreen::getImageFormat(dfbSurface) == QImage::Format_RGB32); } else { const bool isResize = rect.size() != geometry().size(); #ifdef QT_NO_DIRECTFB_WM @@ -179,7 +177,6 @@ void QDirectFBWindowSurface::setGeometry(const QRect &rect, const QRegion &mask) } dfbSurface = screen->createDFBSurface(rect.size(), screen->pixelFormat(), QDirectFBScreen::DontTrackSurface); - forceRaster = (dfbSurface && QDirectFBScreen::getImageFormat(dfbSurface) == QImage::Format_RGB32); } else { Q_ASSERT(dfbSurface); } -- cgit v0.12 From 2a986b86f841b798cc754fe5c5390c6fee95ce71 Mon Sep 17 00:00:00 2001 From: Anders Bakken Date: Thu, 28 May 2009 13:20:48 -0700 Subject: Changes for DirectFB Reviewed-by: TrustMe --- dist/changes-4.5.2 | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 1e00208..dcb77d6 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -139,6 +139,26 @@ Qt for Windows CE * Plugins * **************************************************************************** +- directfb + * Make sure we pick an approriate format for pixmaps. E.g. use the same as + the primary surface for opaque pixmaps and pick an appropriate one for + transparent pixmaps if the primary surface format is not transparent. + * Properly fall back to the raster engine for pens that aren't solidcolor + * Properly fall back to raster engine with "mirrored" scales + * Make sure window surfaces are the approriate pixel format and created in + video memory if supported + * Fix clipping bug that would cause painting errors + * Fix various crash bugs + * Fix bugs when transforming/copying pixmaps with alpha channel + * Fix various bugs with regards to painting with alpha channel/porter duff + * Optimize a coupld of internal functions to slightly speed up drawing + * Optimize raster fall backs + * Allow more customization for Flipping options + * Fix drawing with opacity != 1.0 + * Support for better logging when trying to debug performance problems. + * Fix bug in keyboard handling that caused modifiers not to work + * Get rid of some compiler warnings + **************************************************************************** * Important Behavior Changes * -- cgit v0.12 From 24e904b2ef438bafb24456f934ea93497f43f5c1 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 29 May 2009 08:18:29 +1000 Subject: Further optimized fast scaling of ARGB8565 images onto RGB16 images. This improves performance on embedded. Reviewed-by: Samuel --- src/gui/painting/qblendfunctions.cpp | 6 +++--- src/gui/painting/qdrawhelper_p.h | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/gui/painting/qblendfunctions.cpp b/src/gui/painting/qblendfunctions.cpp index f83ff7b..4bdaf0b 100644 --- a/src/gui/painting/qblendfunctions.cpp +++ b/src/gui/painting/qblendfunctions.cpp @@ -105,10 +105,10 @@ struct Blend_RGB16_on_RGB16_ConstAlpha { }; struct Blend_ARGB24_on_RGB16_SourceAlpha { - inline void write(quint16 *dst, qargb8565 src) { + inline void write(quint16 *dst, const qargb8565 &src) { const uint alpha = src.alpha(); if (alpha) { - quint16 s = qrgb565(src).rawValue(); + quint16 s = src.rawValue16(); if (alpha < 255) s += BYTE_MUL_RGB16(*dst, 255 - alpha); *dst = s; @@ -125,7 +125,7 @@ struct Blend_ARGB24_on_RGB16_SourceAndConstAlpha { src = src.byte_mul(src.alpha(m_alpha)); const uint alpha = src.alpha(); if (alpha) { - quint16 s = qrgb565(src).rawValue(); + quint16 s = src.rawValue16(); if (alpha < 255) s += BYTE_MUL_RGB16(*dst, 255 - alpha); *dst = s; diff --git a/src/gui/painting/qdrawhelper_p.h b/src/gui/painting/qdrawhelper_p.h index 019402a..38fee8d 100644 --- a/src/gui/painting/qdrawhelper_p.h +++ b/src/gui/painting/qdrawhelper_p.h @@ -447,6 +447,7 @@ public: inline bool operator==(const qargb8565 &v) const; inline quint32 rawValue() const; + inline quint16 rawValue16() const; private: friend class qrgb565; @@ -463,7 +464,7 @@ public: inline explicit qrgb565(quint32p v); inline explicit qrgb565(quint32 v); - inline explicit qrgb565(qargb8565 v); + inline explicit qrgb565(const qargb8565 &v); inline operator quint32() const; inline operator quint16() const; @@ -569,6 +570,11 @@ quint32 qargb8565::rawValue() const return (data[2] << 16) | (data[1] << 8) | data[0]; } +quint16 qargb8565::rawValue16() const +{ + return (data[2] << 8) | data[1]; +} + qrgb565::qrgb565(quint32p v) { *this = qrgb565(quint32(v)); @@ -583,7 +589,7 @@ qrgb565::qrgb565(quint32 v) data = (r & 0xf800) | (g & 0x07e0)| (b & 0x001f); } -qrgb565::qrgb565(qargb8565 v) +qrgb565::qrgb565(const qargb8565 &v) { data = (v.data[2] << 8) | v.data[1]; } -- cgit v0.12 From 890ea9c9cf35e4b3f7d9ad08bd6cba76b42f407e Mon Sep 17 00:00:00 2001 From: Rohan McGovern Date: Fri, 29 May 2009 08:22:01 +1000 Subject: Fixed WinCE compile, perhaps. Fix obvious typo: frosmUtf16 -> fromUtf16 --- src/winmain/qtmain_win.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/winmain/qtmain_win.cpp b/src/winmain/qtmain_win.cpp index b83b324..e5b3259 100644 --- a/src/winmain/qtmain_win.cpp +++ b/src/winmain/qtmain_win.cpp @@ -110,7 +110,7 @@ int APIENTRY WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR /*cmdPara #if defined(Q_OS_WINCE) TCHAR uniqueAppID[256]; GetModuleFileName(0, uniqueAppID, 255); - QString uid = QString::frosmUtf16((const unsigned short *)uniqueAppID).toLower().replace(QLatin1Char('\\'), QLatin1Char('_')); + QString uid = QString::fromUtf16((const unsigned short *)uniqueAppID).toLower().replace(QLatin1Char('\\'), QLatin1Char('_')); // If there exists an other instance of this application // it will be the owner of a mutex with the unique ID. -- cgit v0.12 From 89d3ccf6d07d6f66dd62b66c35bdfa5218afafae Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 29 May 2009 08:32:29 +1000 Subject: Export symbol needed by the declarative module. Reviewed-by: Leo --- src/corelib/animation/qvariantanimation_p.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/corelib/animation/qvariantanimation_p.h b/src/corelib/animation/qvariantanimation_p.h index 2c559cf..aee2324 100644 --- a/src/corelib/animation/qvariantanimation_p.h +++ b/src/corelib/animation/qvariantanimation_p.h @@ -102,7 +102,8 @@ public: void updateInterpolator(); - static QVariantAnimation::Interpolator getInterpolator(int interpolationType); + //XXX this is needed by dui + static Q_CORE_EXPORT QVariantAnimation::Interpolator getInterpolator(int interpolationType); }; //this should make the interpolation faster -- cgit v0.12 From 9088aeae9daf02546769377853824397458ba822 Mon Sep 17 00:00:00 2001 From: Rohan McGovern Date: Fri, 29 May 2009 08:54:20 +1000 Subject: Fixed compile of Qt/Embedded. Fix what looks like the result of a `git merge' gone wrong. --- src/gui/embedded/qkbdtty_qws.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/embedded/qkbdtty_qws.cpp b/src/gui/embedded/qkbdtty_qws.cpp index 3489278..7f10e14 100644 --- a/src/gui/embedded/qkbdtty_qws.cpp +++ b/src/gui/embedded/qkbdtty_qws.cpp @@ -210,7 +210,7 @@ QWSTtyKbPrivate::~QWSTtyKbPrivate() { if (m_tty_fd >= 0) { #if defined(Q_OS_LINUX) - ::ioctl(kbdFD, KDSKBMODE, m_originalKbdMode); + ::ioctl(m_tty_fd, KDSKBMODE, m_originalKbdMode); #endif tcsetattr(m_tty_fd, TCSANOW, &m_tty_attr); } -- cgit v0.12 From 3824fa64f8f8d24db34e3ce1c8d5c7d21cb624b7 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Fri, 29 May 2009 10:56:55 +1000 Subject: Update on gradient change. --- src/declarative/fx/qfxrect.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index 4271022..b10594e 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -308,7 +308,10 @@ QFxGradient *QFxRect::gradient() const void QFxRect::setGradient(QFxGradient *gradient) { Q_D(QFxRect); + if (d->gradient == gradient) + return; d->gradient = gradient; + update(); } -- cgit v0.12 From 9f95bd8f6e6ccf3575216285b29f2a42dcfd328d Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Fri, 29 May 2009 11:32:39 +1000 Subject: Update in reaction to GradientStops changing. --- src/declarative/fx/qfxrect.cpp | 17 +++++++++++++++++ src/declarative/fx/qfxrect.h | 14 ++++++++++++-- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index b10594e..9718344 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -133,6 +133,12 @@ void QFxPen::setWidth(int w) Sets a \e color at a \e position in a gradient. */ +void QFxGradientStop::updateGradient() +{ + if (QFxGradient *grad = qobject_cast(parent())) + grad->doUpdate(); +} + /*! \qmlclass Gradient QFxGradient \brief The Gradient item defines a gradient fill. @@ -171,6 +177,13 @@ const QGradient *QFxGradient::gradient() const return m_gradient; } +void QFxGradient::doUpdate() +{ + delete m_gradient; + m_gradient = 0; + emit updated(); +} + QML_DEFINE_TYPE(QFxRect,Rect) /*! @@ -310,7 +323,11 @@ void QFxRect::setGradient(QFxGradient *gradient) Q_D(QFxRect); if (d->gradient == gradient) return; + if (d->gradient) + disconnect(d->gradient, SIGNAL(updated()), this, SLOT(doUpdate())); d->gradient = gradient; + if (d->gradient) + connect(d->gradient, SIGNAL(updated()), this, SLOT(doUpdate())); update(); } diff --git a/src/declarative/fx/qfxrect.h b/src/declarative/fx/qfxrect.h index 864b1cd..c279a1c 100644 --- a/src/declarative/fx/qfxrect.h +++ b/src/declarative/fx/qfxrect.h @@ -90,10 +90,13 @@ public: QFxGradientStop(QObject *parent=0) : QObject(parent) {} qreal position() const { return m_position; } - void setPosition(qreal position) { m_position = position; } + void setPosition(qreal position) { m_position = position; updateGradient(); } QColor color() const { return m_color; } - void setColor(const QColor &color) { m_color = color; } + void setColor(const QColor &color) { m_color = color; updateGradient(); } + +private: + void updateGradient(); private: qreal m_position; @@ -116,9 +119,16 @@ public: const QGradient *gradient() const; +Q_SIGNALS: + void updated(); + +private: + void doUpdate(); + private: QList m_stops; mutable QGradient *m_gradient; + friend class QFxGradientStop; }; QML_DECLARE_TYPE(QFxGradient) -- cgit v0.12 From 5b542cc9faf016c9071f41fa85ab071d05b0f26a Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 29 May 2009 14:33:35 +1000 Subject: Make compile under Open GL ES 2. We will need to optimize the pixmap.toImage calls. --- .../canvas/qsimplecanvasdebugplugin.cpp | 7 +++++- src/declarative/fx/qfxhighlightfilter.cpp | 2 +- src/declarative/fx/qfximage.cpp | 2 +- src/declarative/fx/qfxpainteditem.cpp | 2 +- src/declarative/fx/qfxparticles.cpp | 2 +- src/declarative/fx/qfxrect.cpp | 28 ++++++++++------------ src/declarative/fx/qfxtext.cpp | 2 +- 7 files changed, 23 insertions(+), 22 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvasdebugplugin.cpp b/src/declarative/canvas/qsimplecanvasdebugplugin.cpp index f5f4f53..0fd0f81 100644 --- a/src/declarative/canvas/qsimplecanvasdebugplugin.cpp +++ b/src/declarative/canvas/qsimplecanvasdebugplugin.cpp @@ -122,7 +122,12 @@ void QSimpleCanvasSceneDebugPlugin::refresh(QDataStream &ds, ds << QmlDebugServerPlugin::objectToString(item) << item->x() << item->y() << item->z() << item->width() << item->height() << (int)item->transformOrigin() << item->scale() << (int)item->flip() - << item->transform() << item->hasActiveFocus() << (int)item->options(); +#ifdef QFX_RENDER_OPENGL + << item->transform().toTransform() +#elif defined(QFX_RENDER_QPAINTER) + << item->transform() +#endif + << item->hasActiveFocus() << (int)item->options(); QPixmap pix; diff --git a/src/declarative/fx/qfxhighlightfilter.cpp b/src/declarative/fx/qfxhighlightfilter.cpp index c36ba98..6bf3148 100644 --- a/src/declarative/fx/qfxhighlightfilter.cpp +++ b/src/declarative/fx/qfxhighlightfilter.cpp @@ -138,7 +138,7 @@ void QFxHighlightFilter::imageLoaded() QPixmap img = QFxPixmap(d->url); #if defined(QFX_RENDER_OPENGL2) if (!img.isNull()) - d->tex.setImage(img); + d->tex.setImage(img.toImage()); #endif emit sourceChanged(d->source); update(); diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 8f63a90..22e5d97 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -459,7 +459,7 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, void QFxImagePrivate::checkDirty() { if (_texDirty && !_pix.isNull()) { - _tex.setImage(_pix); + _tex.setImage(_pix.toImage()); _tex.setHorizontalWrap(GLTexture::Repeat); _tex.setVerticalWrap(GLTexture::Repeat); } diff --git a/src/declarative/fx/qfxpainteditem.cpp b/src/declarative/fx/qfxpainteditem.cpp index 7fd74a6..44adba7 100644 --- a/src/declarative/fx/qfxpainteditem.cpp +++ b/src/declarative/fx/qfxpainteditem.cpp @@ -315,7 +315,7 @@ void QFxPaintedItem::paintGLContents(GLPainter &p) #if defined(QFX_RENDER_QPAINTER) newitem->image = img; #else - newitem->image.setImage(img); + newitem->image.setImage(img.toImage()); #endif d->imagecache.append(newitem); QRectF target(r.x(), r.y(), r.width(), r.height()); diff --git a/src/declarative/fx/qfxparticles.cpp b/src/declarative/fx/qfxparticles.cpp index 52f24a0..41fb5bc 100644 --- a/src/declarative/fx/qfxparticles.cpp +++ b/src/declarative/fx/qfxparticles.cpp @@ -1143,7 +1143,7 @@ void QFxParticlesPainter::paintGLContents(GLPainter &p) updateSize(); if (d->texDirty && !d->image.isNull()) { - d->tex.setImage(d->image); + d->tex.setImage(d->image.toImage()); d->tex.setHorizontalWrap(GLTexture::Repeat); d->tex.setVerticalWrap(GLTexture::Repeat); } diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index 475c095..564faa6 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -652,7 +652,7 @@ void QFxRect::paintGLContents(GLPainter &p) { Q_D(QFxRect); if (d->_radius == 0 && (!d->_pen || !d->_pen->isValid())) { - if (d->_gradcolor.isValid()) { + if (d->gradient) { float widthV = width(); float heightV = height(); @@ -661,20 +661,16 @@ void QFxRect::paintGLContents(GLPainter &p) 0, 0, widthV, 0 }; - float r = d->_color.redF(); - float g = d->_color.greenF(); - float b = d->_color.blueF(); - float a = d->_color.alphaF() * p.activeOpacity; - - float r2 = d->_gradcolor.redF(); - float g2 = d->_gradcolor.greenF(); - float b2 = d->_gradcolor.blueF(); - float a2 = d->_gradcolor.alphaF() * p.activeOpacity; - - GLfloat colors[] = { r2, g2, b2, a2, - r2, g2, b2, a2, - r, g, b, a, - r, g, b, a }; + int count = d->gradient->stops()->size(); + GLfloat colors[count*8]; + for (int i = 0; i < count; i += 8) { + QFxGradientStop *g = d->gradient->stops()->at(i); + QColor c = g->color(); + colors[i] = c.redF(); colors[i+4] = colors[i]; + colors[i+1] = c.greenF(); colors[i+5] = colors[i+1]; + colors[i+2] = c.blueF(); colors[i+6] = colors[i+2]; + colors[i+3] = c.alphaF() * p.activeOpacity; colors[i+7] = colors[i+3]; + } ColorShader *shader = basicShaders()->color(); shader->enable(); @@ -682,7 +678,7 @@ void QFxRect::paintGLContents(GLPainter &p) shader->setAttributeArray(ColorShader::Vertices, vertices, 2); shader->setAttributeArray(ColorShader::Colors, colors, 4); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glDrawArrays(GL_TRIANGLE_STRIP, 0, count*2); shader->disableAttributeArray(ColorShader::Vertices); shader->disableAttributeArray(ColorShader::Colors); } else { diff --git a/src/declarative/fx/qfxtext.cpp b/src/declarative/fx/qfxtext.cpp index 2486a84..702ec81 100644 --- a/src/declarative/fx/qfxtext.cpp +++ b/src/declarative/fx/qfxtext.cpp @@ -696,7 +696,7 @@ void QFxTextPrivate::checkImgCache() } #if defined(QFX_RENDER_OPENGL) - tex.setImage(imgCache); + tex.setImage(imgCache.toImage()); #endif imgDirty = false; -- cgit v0.12 From 8acc20e525d589e0c4450fbd60141e8b9c3f40e9 Mon Sep 17 00:00:00 2001 From: Rohan McGovern Date: Fri, 29 May 2009 15:23:17 +1000 Subject: Fixed compile with MinGW. MinGW 3.4.5 can't figure out the automatic QLatin1Char -> QString conversion in this code. --- src/corelib/io/qfsfileengine_win.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/corelib/io/qfsfileengine_win.cpp b/src/corelib/io/qfsfileengine_win.cpp index 790f1eb..9da9e66 100644 --- a/src/corelib/io/qfsfileengine_win.cpp +++ b/src/corelib/io/qfsfileengine_win.cpp @@ -1770,10 +1770,10 @@ QString QFSFileEngine::fileName(FileName file) const if(slash == -1) { if(d->filePath.length() >= 2 && d->filePath.at(1) == QLatin1Char(':')) return d->filePath.left(2); - return QLatin1Char('.'); + return QString(QLatin1Char('.')); } else { if(!slash) - return QLatin1Char('/'); + return QString(QLatin1Char('/')); if(slash == 2 && d->filePath.length() >= 2 && d->filePath.at(1) == QLatin1Char(':')) slash++; return d->filePath.left(slash); @@ -1831,7 +1831,7 @@ QString QFSFileEngine::fileName(FileName file) const if (slash == -1) ret = QDir::currentPath(); else if (slash == 0) - ret = QLatin1Char('/'); + ret = QString(QLatin1Char('/')); ret = ret.left(slash); } return ret; -- cgit v0.12 From b946da648af0c5fa1c73fe1e57b0b1e08fb14d13 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Tue, 26 May 2009 18:31:01 +0200 Subject: Ensure a hierarchy of menus fade out together. On Mac OS X, when you have a large hierarchies of menus and you select the item at the end of the hierarchy. It will flash and then the rest will fade out at the same time. Qt would do a phased approach which was what no one expected. Introduce a QMacWindowFader class that can hold an arbitrary number of qwidgets and then on command fade them all down pased on the set duration. The API is a bit clumsy but is prefect for this internal API. Task-#: 251700 Reviewed-by: Richard Moe Gustavsen --- src/gui/kernel/qt_cocoa_helpers_mac.mm | 79 ++++++++++++++++++++++++++-------- src/gui/kernel/qt_mac_p.h | 15 +++++++ src/gui/widgets/qmenu.cpp | 40 +++++++++++------ src/gui/widgets/qmenu_p.h | 2 +- 4 files changed, 103 insertions(+), 33 deletions(-) diff --git a/src/gui/kernel/qt_cocoa_helpers_mac.mm b/src/gui/kernel/qt_cocoa_helpers_mac.mm index 9165836..554e9d5 100644 --- a/src/gui/kernel/qt_cocoa_helpers_mac.mm +++ b/src/gui/kernel/qt_cocoa_helpers_mac.mm @@ -88,6 +88,52 @@ QT_BEGIN_NAMESPACE +Q_GLOBAL_STATIC(QMacWindowFader, macwindowFader); + +QMacWindowFader::QMacWindowFader() + : m_duration(0.250) +{ +} + +QMacWindowFader *QMacWindowFader::currentFader() +{ + return macwindowFader(); +} + +void QMacWindowFader::registerWindowToFade(QWidget *window) +{ + m_windowsToFade.append(window); +} + +void QMacWindowFader::performFade() +{ + const QWidgetList myWidgetsToFade = m_windowsToFade; + const int widgetCount = myWidgetsToFade.count(); +#if QT_MAC_USE_COCOA + QMacCocoaAutoReleasePool pool; + [NSAnimationContext beginGrouping]; + [[NSAnimationContext currentContext] setDuration:NSTimeInterval(m_duration)]; +#endif + + for (int i = 0; i < widgetCount; ++i) { + QWidget *widget = m_windowsToFade.at(i); + OSWindowRef window = qt_mac_window_for(widget); +#if QT_MAC_USE_COCOA + [[window animator] setAlphaValue:0.0]; + QTimer::singleShot(qRound(m_duration * 1000), widget, SLOT(hide())); +#else + TransitionWindowOptions options = {0, m_duration, 0, 0}; + TransitionWindowWithOptions(window, kWindowFadeTransitionEffect, kWindowHideTransitionAction, + 0, 1, &options); +#endif + } +#if QT_MAC_USE_COCOA + [NSAnimationContext endGrouping]; +#endif + m_duration = 0.250; + m_windowsToFade.clear(); +} + extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); // qapplication.cpp; extern Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum); // qcocoaview.mm extern QWidget * mac_mouse_grabber; @@ -95,29 +141,26 @@ extern QWidget * mac_mouse_grabber; void macWindowFade(void * /*OSWindowRef*/ window, float durationSeconds) { OSWindowRef wnd = static_cast(window); - if( wnd ) { + if (wnd) { + QWidget *widget; #if QT_MAC_USE_COCOA - QMacCocoaAutoReleasePool pool; - [NSAnimationContext beginGrouping]; - [[wnd animator] setAlphaValue:0.0]; - if (durationSeconds > 0) { - [[NSAnimationContext currentContext] setDuration:NSTimeInterval(durationSeconds)]; - } else { - durationSeconds = [[NSAnimationContext currentContext] duration]; - } - [NSAnimationContext endGrouping]; - QTimer::singleShot(qRound(durationSeconds * 1000), [wnd QT_MANGLE_NAMESPACE(qt_qwidget)], SLOT(hide())); + widget = [wnd QT_MANGLE_NAMESPACE(qt_qwidget)]; #else - if (durationSeconds <= 0) - durationSeconds = 0.15; - TransitionWindowOptions options = {0, durationSeconds, 0, 0}; - TransitionWindowWithOptions(wnd, kWindowFadeTransitionEffect, kWindowHideTransitionAction, 0, 1, &options); + const UInt32 kWidgetCreatorQt = kEventClassQt; + enum { + kWidgetPropertyQWidget = 'QWId' //QWidget * + }; + if (GetWindowProperty(static_cast(window), kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(widget), 0, &widget) != noErr) + widget = 0; #endif - } + if (widget) { + QMacWindowFader::currentFader()->setFadeDuration(durationSeconds); + QMacWindowFader::currentFader()->registerWindowToFade(widget); + QMacWindowFader::currentFader()->performFade(); + } + } } - - bool macWindowIsTextured( void * /*OSWindowRef*/ window ) { OSWindowRef wnd = static_cast(window); diff --git a/src/gui/kernel/qt_mac_p.h b/src/gui/kernel/qt_mac_p.h index ca995dc..3b0f546 100644 --- a/src/gui/kernel/qt_mac_p.h +++ b/src/gui/kernel/qt_mac_p.h @@ -120,6 +120,21 @@ public: } }; +// Class for chaining to gether a bunch of fades. It pretty much is only used for qmenu fading. +class QMacWindowFader +{ + QWidgetList m_windowsToFade; + float m_duration; + Q_DISABLE_COPY(QMacWindowFader) +public: + QMacWindowFader(); // PLEASE DON'T CALL THIS. + static QMacWindowFader *currentFader(); + void registerWindowToFade(QWidget *window); + void setFadeDuration(float durationInSecs) { m_duration = durationInSecs; } + float fadeDuration() const { return m_duration; } + void performFade(); +}; + class Q_GUI_EXPORT QMacCocoaAutoReleasePool { private: diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp index 3004841..50100af 100644 --- a/src/gui/widgets/qmenu.cpp +++ b/src/gui/widgets/qmenu.cpp @@ -398,9 +398,12 @@ QRect QMenuPrivate::actionRect(QAction *act) const return ret; } +static const float MenuFadeTimeInSec = 0.150; + void QMenuPrivate::hideUpToMenuBar() { Q_Q(QMenu); + bool fadeMenus = q->style()->styleHint(QStyle::SH_Menu_FadeOutOnHide); if (!tornoff) { QWidget *caused = causedPopup.widget; hideMenu(q); //hide after getting causedPopup @@ -415,8 +418,9 @@ void QMenuPrivate::hideUpToMenuBar() if (QMenu *m = qobject_cast(caused)) { caused = m->d_func()->causedPopup.widget; if (!m->d_func()->tornoff) - hideMenu(m); - m->d_func()->setCurrentAction(0); + hideMenu(m, fadeMenus); + if (!fadeMenus) // Mac doesn't clear the action until after hidden. + m->d_func()->setCurrentAction(0); } else { #ifndef QT_NO_TOOLBUTTON if (qobject_cast(caused) == 0) @@ -425,26 +429,32 @@ void QMenuPrivate::hideUpToMenuBar() caused = 0; } } +#if defined(Q_WS_MAC) + if (fadeMenus) { + QEventLoop eventLoop; + QTimer::singleShot(int(MenuFadeTimeInSec * 1000), &eventLoop, SLOT(quit())); + QMacWindowFader::currentFader()->performFade(); + eventLoop.exec(); + } +#endif } setCurrentAction(0); } -void QMenuPrivate::hideMenu(QMenu *menu) +void QMenuPrivate::hideMenu(QMenu *menu, bool justRegister) { if (!menu) return; - #if !defined(QT_NO_EFFECTS) menu->blockSignals(true); aboutToHide = true; // Flash item which is about to trigger (if any). if (menu->style()->styleHint(QStyle::SH_Menu_FlashTriggeredItem) - && currentAction && currentAction == actionAboutToTrigger) { - + && currentAction && currentAction == actionAboutToTrigger + && menu->actions().contains(currentAction)) { QEventLoop eventLoop; QAction *activeAction = currentAction; - // Deselect and wait 60 ms. menu->setActiveAction(0); QTimer::singleShot(60, &eventLoop, SLOT(quit())); eventLoop.exec(); @@ -458,22 +468,24 @@ void QMenuPrivate::hideMenu(QMenu *menu) // Fade out. if (menu->style()->styleHint(QStyle::SH_Menu_FadeOutOnHide)) { // ### Qt 4.4: - // Should be something like: q->transitionWindow(Qt::FadeOutTransition, 150); + // Should be something like: q->transitionWindow(Qt::FadeOutTransition, MenuFadeTimeInSec); // Hopefully we'll integrate qt/research/windowtransitions into main before 4.4. // Talk to Richard, Trenton or Bjoern. #if defined(Q_WS_MAC) - macWindowFade(qt_mac_window_for(menu)); // FIXME - what is the default duration for view animations + if (justRegister) { + QMacWindowFader::currentFader()->setFadeDuration(MenuFadeTimeInSec); + QMacWindowFader::currentFader()->registerWindowToFade(menu); + } else { + macWindowFade(qt_mac_window_for(menu), MenuFadeTimeInSec); + } - // Wait for the transition to complete. - QEventLoop eventLoop; - QTimer::singleShot(150, &eventLoop, SLOT(quit())); - eventLoop.exec(); #endif // Q_WS_MAC } aboutToHide = false; menu->blockSignals(false); #endif // QT_NO_EFFECTS - menu->hide(); + if (!justRegister) + menu->hide(); } void QMenuPrivate::popupAction(QAction *action, int delay, bool activateFirst) diff --git a/src/gui/widgets/qmenu_p.h b/src/gui/widgets/qmenu_p.h index edfeee7..9654126 100644 --- a/src/gui/widgets/qmenu_p.h +++ b/src/gui/widgets/qmenu_p.h @@ -220,7 +220,7 @@ public: virtual QList > calcCausedStack() const; QMenuCaused causedPopup; void hideUpToMenuBar(); - void hideMenu(QMenu *menu); + void hideMenu(QMenu *menu, bool delay = true); //index mappings inline QAction *actionAt(int i) const { return q_func()->actions().at(i); } -- cgit v0.12 From f67bc13bc8e2d2c76d7d9f12abb1dbda85abe337 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 29 May 2009 10:22:24 +0200 Subject: Doc - marked QFileDialog::setOption() with the since 4.5 tag. Task-number: 254549 Reviewed-by: TrustMe --- src/gui/dialogs/qfiledialog.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/gui/dialogs/qfiledialog.cpp b/src/gui/dialogs/qfiledialog.cpp index d4d0136..405e71e 100644 --- a/src/gui/dialogs/qfiledialog.cpp +++ b/src/gui/dialogs/qfiledialog.cpp @@ -565,8 +565,9 @@ bool QFileDialogPrivate::canBeNativeDialog() } /*! - Sets the given \a option to be enabled if \a on is true; - otherwise, clears the given \a option. + \since 4.5 + Sets the given \a option to be enabled if \a on is true; otherwise, + clears the given \a option. \sa options, testOption() */ -- cgit v0.12 From 7bc17b5b9ff9f2e3e04f36fec8ccbb546d9b7a31 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Fri, 29 May 2009 10:48:53 +0200 Subject: Fixed build issues with MSVC in atomic operations, we declare Interlock... functions in the namespace That can confuse the compiler because they are also declared in another header outside the namespace. Same problem in clucene where we include windows.h from within the NS. Task-number: 254214 Reviewed-by: ogoffart --- src/corelib/arch/qatomic_windows.h | 14 ++++++++++++++ tools/assistant/lib/fulltextsearch/qclucene_global_p.h | 16 ++++++++-------- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/corelib/arch/qatomic_windows.h b/src/corelib/arch/qatomic_windows.h index ac26b4f..5135575 100644 --- a/src/corelib/arch/qatomic_windows.h +++ b/src/corelib/arch/qatomic_windows.h @@ -220,6 +220,9 @@ Q_INLINE_TEMPLATE T *QBasicAtomicPointer::fetchAndAddOrdered(qptrdiff valueTo #if !defined(Q_OS_WINCE) // use compiler intrinsics for all atomic functions +//those functions need to be define in the global namespace +QT_END_NAMESPACE + extern "C" { long __cdecl _InterlockedIncrement(volatile long *); long __cdecl _InterlockedDecrement(volatile long *); @@ -252,6 +255,9 @@ extern "C" { # define _InterlockedExchangeAddPointer(a,b) \ _InterlockedExchangeAdd(reinterpret_cast(a), long(b)) # endif + +QT_BEGIN_NAMESPACE + inline bool QBasicAtomicInt::ref() { return _InterlockedIncrement(reinterpret_cast(&_q_value)) != 0; @@ -335,6 +341,8 @@ Q_INLINE_TEMPLATE T *QBasicAtomicPointer::fetchAndAddOrdered(qptrdiff valueTo #define Q_ARGUMENT_TYPE #endif +QT_END_NAMESPACE + extern "C" { long __cdecl InterlockedIncrement(long Q_ARGUMENT_TYPE * lpAddend); long __cdecl InterlockedDecrement(long Q_ARGUMENT_TYPE * lpAddend); @@ -351,6 +359,8 @@ long __cdecl InterlockedExchangeAdd(long Q_ARGUMENT_TYPE * Addend, long Value); # pragma intrinsic (_InterlockedExchangeAdd) #endif +QT_BEGIN_NAMESPACE + #endif @@ -409,6 +419,8 @@ Q_INLINE_TEMPLATE T *QBasicAtomicPointer::fetchAndAddOrdered(qptrdiff valueTo // MinGW's definition, such that we pick up variations in the headers. #ifndef __INTERLOCKED_DECLARED #define __INTERLOCKED_DECLARED +QT_END_NAMESPACE + extern "C" { __declspec(dllimport) long __stdcall InterlockedCompareExchange(long *, long, long); __declspec(dllimport) long __stdcall InterlockedIncrement(long *); @@ -416,6 +428,8 @@ extern "C" { __declspec(dllimport) long __stdcall InterlockedExchange(long *, long); __declspec(dllimport) long __stdcall InterlockedExchangeAdd(long *, long); } + +QT_BEGIN_NAMESPACE #endif inline bool QBasicAtomicInt::ref() diff --git a/tools/assistant/lib/fulltextsearch/qclucene_global_p.h b/tools/assistant/lib/fulltextsearch/qclucene_global_p.h index 2a9d146..3dba45a 100644 --- a/tools/assistant/lib/fulltextsearch/qclucene_global_p.h +++ b/tools/assistant/lib/fulltextsearch/qclucene_global_p.h @@ -29,6 +29,14 @@ #include #include +#if !defined(_MSC_VER) && defined(_CL_HAVE_WCHAR_H) && defined(_CL_HAVE_WCHAR_T) +# if !defined(TCHAR) +# define TCHAR wchar_t +# endif +#else +# include +#endif + QT_BEGIN_HEADER QT_BEGIN_NAMESPACE @@ -87,14 +95,6 @@ QT_BEGIN_NAMESPACE # define CL_NS2(sub,sub2) #endif -#if !defined(_MSC_VER) && defined(_CL_HAVE_WCHAR_H) && defined(_CL_HAVE_WCHAR_T) -# if !defined(TCHAR) -# define TCHAR wchar_t -# endif -#else -# include -#endif - namespace { TCHAR* QStringToTChar(const QString &str) { -- cgit v0.12 From e08f3e7bf3dbae6036ab89248793b98330971269 Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Fri, 29 May 2009 09:21:16 +0200 Subject: Only display the choice of license if we can find the files Task-number: 254451 Reviewed-by: eskil BT: yes --- tools/configure/configureapp.cpp | 43 +++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/tools/configure/configureapp.cpp b/tools/configure/configureapp.cpp index a6b06a6..b9d172f 100644 --- a/tools/configure/configureapp.cpp +++ b/tools/configure/configureapp.cpp @@ -3483,12 +3483,15 @@ void Configure::readLicense() dictionary[ "PLATFORM NAME" ] = (QFile::exists(dictionary["QT_SOURCE_TREE"] + "/src/corelib/kernel/qfunctions_wince.h") && (dictionary.value("QMAKESPEC").startsWith("wince") || dictionary.value("XQMAKESPEC").startsWith("wince"))) ? "Qt for Windows CE" : "Qt for Windows"; + dictionary["LICENSE FILE"] = sourcePath; + bool openSource = false; + bool hasOpenSource = QFile::exists(dictionary["LICENSE FILE"] + "/LICENSE.GPL3") || QFile::exists(dictionary["LICENSE FILE"] + "/LICENSE.LGPL"); if (dictionary["BUILDNOKIA"] == "yes" || dictionary["BUILDTYPE"] == "commercial") { openSource = false; } else if (dictionary["BUILDTYPE"] == "opensource") { openSource = true; - } else { + } else if (hasOpenSource) { // No Open Source? Just display the commercial license right away forever { char accept = '?'; cout << "Which edition of Qt do you want to use ?" << endl; @@ -3506,28 +3509,23 @@ void Configure::readLicense() } } } - if (openSource) { - dictionary["LICENSE FILE"] = sourcePath; - if (QFile::exists(dictionary["LICENSE FILE"] + "/LICENSE.GPL3") || QFile::exists(dictionary["LICENSE FILE"] + "/LICENSE.LGPL")) { - cout << endl << "This is the " << dictionary["PLATFORM NAME"] << " Open Source Edition." << endl; - licenseInfo["LICENSEE"] = "Open Source"; - dictionary["EDITION"] = "OpenSource"; - dictionary["QT_EDITION"] = "QT_EDITION_OPENSOURCE"; - cout << endl; - if (!showLicense(dictionary["LICENSE FILE"])) { - cout << "Configuration aborted since license was not accepted"; - dictionary["DONE"] = "error"; - return; - } + if (hasOpenSource && openSource) { + cout << endl << "This is the " << dictionary["PLATFORM NAME"] << " Open Source Edition." << endl; + licenseInfo["LICENSEE"] = "Open Source"; + dictionary["EDITION"] = "OpenSource"; + dictionary["QT_EDITION"] = "QT_EDITION_OPENSOURCE"; + cout << endl; + if (!showLicense(dictionary["LICENSE FILE"])) { + cout << "Configuration aborted since license was not accepted"; + dictionary["DONE"] = "error"; return; } -#ifndef COMMERCIAL_VERSION - else { - cout << endl << "Cannot find the GPL license files!" << endl; + } else if (openSource) { + cout << endl << "Cannot find the GPL license files! Please download the Open Source version of the library." << endl; dictionary["DONE"] = "error"; } -#else - } else { +#ifdef COMMERCIAL_VERSION + else { Tools::checkLicense(dictionary, licenseInfo, firstLicensePath()); if (dictionary["DONE"] != "error" && dictionary["BUILDNOKIA"] != "yes") { // give the user some feedback, and prompt for license acceptance @@ -3539,7 +3537,12 @@ void Configure::readLicense() } } } -#endif // COMMERCIAL_VERSION +#else // !COMMERCIAL_VERSION + else { + cout << endl << "Cannot build commercial edition from the open source version of the library." << endl; + dictionary["DONE"] = "error"; + } +#endif } void Configure::reloadCmdLine() -- cgit v0.12 From 87acb1722d9db66aa01d238b6e4ac90dfe095ff0 Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Fri, 29 May 2009 09:25:59 +0200 Subject: New configure.exe binary Task-number: 254451 Reviewed-by: trustme BT: yes --- configure.exe | Bin 856064 -> 856064 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/configure.exe b/configure.exe index 40843b4..9da5c60 100644 Binary files a/configure.exe and b/configure.exe differ -- cgit v0.12 From 909f96a4f92ad3c9fed1dc4c3873b638421568b0 Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Fri, 29 May 2009 10:07:06 +0200 Subject: Remove the fixFilename() usage from the solution generator Only the Solution Generator was using the fixFilename() function, so under some circumstances the solution filename wouldn't find the correct vcproj file to include. This created a problem with network-chat.vcproj. Task-number: 254772 Reviewed-by: joao --- qmake/generators/win32/msvc_vcproj.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qmake/generators/win32/msvc_vcproj.cpp b/qmake/generators/win32/msvc_vcproj.cpp index 8901289..13bc05b 100644 --- a/qmake/generators/win32/msvc_vcproj.cpp +++ b/qmake/generators/win32/msvc_vcproj.cpp @@ -574,7 +574,7 @@ void VcprojGenerator::writeSubDirs(QTextStream &t) } // We assume project filename is [QMAKE_ORIG_TARGET].vcproj - QString vcproj = unescapeFilePath(fixFilename(tmp_vcproj.project->first("QMAKE_ORIG_TARGET")) + project->first("VCPROJ_EXTENSION")); + QString vcproj = unescapeFilePath(tmp_vcproj.project->first("QMAKE_ORIG_TARGET") + project->first("VCPROJ_EXTENSION")); QString vcprojDir = qmake_getpwd(); // If file doesn't exsist, then maybe the users configuration -- cgit v0.12 From 7de43fbe1dda9dd823483412cd66c44a6932023b Mon Sep 17 00:00:00 2001 From: Richard Moe Gustavsen Date: Fri, 29 May 2009 11:12:37 +0200 Subject: Mac: App menus reactivated when a sheet is used on a modal dialog. We need to check all window anchestors of the sheet to make sure that there it is not in effekt application modal Task-number: 254543 Reviewed-by: Trenton Schulz --- src/gui/widgets/qmenu_mac.mm | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/gui/widgets/qmenu_mac.mm b/src/gui/widgets/qmenu_mac.mm index cce083f..87c886c 100644 --- a/src/gui/widgets/qmenu_mac.mm +++ b/src/gui/widgets/qmenu_mac.mm @@ -1829,6 +1829,9 @@ OSMenuRef QMenuBar::macMenu() { return d_func()->macMenu(); } */ static bool qt_mac_is_ancestor(QWidget* possibleAncestor, QWidget *child) { + if (!possibleAncestor) + return false; + QWidget * current = child->parentWidget(); while (current != 0) { if (current == possibleAncestor) @@ -1847,22 +1850,19 @@ static bool qt_mac_should_disable_menu(QMenuBar *menuBar, QWidget *modalWidget) { if (modalWidget == 0 || menuBar == 0) return false; - const Qt::WindowModality modality = modalWidget->windowModality(); - if (modality == Qt::ApplicationModal) { - return true; - } else if (modality == Qt::WindowModal) { - QWidget * parent = menuBar->parentWidget(); - - // Special case for the global menu bar: It's not associated - // with a window so don't disable it. - if (parent == 0) - return false; - // Disable menu entries in menu bars that belong to ancestors of - // the modal widget, leave entries in unrelated menu bars enabled. - return qt_mac_is_ancestor(parent, modalWidget); + // If there is an application modal window on + // screen, the entries of the menubar should be disabled: + QWidget *w = modalWidget; + while (w) { + if (w->isVisible() && w->windowModality() == Qt::ApplicationModal) + return true; + w = w->parentWidget(); } - return false; // modality == NonModal + + // INVARIANT: modalWidget is window modal. Disable menu entries + // if the menu bar belongs to an ancestor of modalWidget: + return qt_mac_is_ancestor(menuBar->parentWidget(), modalWidget); } static void cancelAllMenuTracking() -- cgit v0.12 From 766cf07cbe7ebfda01dad163bb070fff7e3077d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Fri, 29 May 2009 11:58:32 +0200 Subject: Call QFormBuilderExtra::instance less Reviewed-by: Friedemann Kleint --- tools/designer/src/lib/uilib/formbuilder.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/tools/designer/src/lib/uilib/formbuilder.cpp b/tools/designer/src/lib/uilib/formbuilder.cpp index 414eb14..5a771b7 100644 --- a/tools/designer/src/lib/uilib/formbuilder.cpp +++ b/tools/designer/src/lib/uilib/formbuilder.cpp @@ -120,7 +120,8 @@ QFormBuilder::~QFormBuilder() */ QWidget *QFormBuilder::create(DomWidget *ui_widget, QWidget *parentWidget) { - QFormBuilderExtra::instance(this)->setProcessingLayoutWidget(false); + QFormBuilderExtra *fb = QFormBuilderExtra::instance(this); + fb->setProcessingLayoutWidget(false); if (ui_widget->attributeClass() == QFormBuilderStrings::instance().qWidgetClass && !ui_widget->hasAttributeNative() && parentWidget #ifndef QT_NO_MAINWINDOW @@ -145,7 +146,7 @@ QWidget *QFormBuilder::create(DomWidget *ui_widget, QWidget *parentWidget) && !qobject_cast(parentWidget) #endif ) - QFormBuilderExtra::instance(this)->setProcessingLayoutWidget(true); + fb->setProcessingLayoutWidget(true); return QAbstractFormBuilder::create(ui_widget, parentWidget); } @@ -369,9 +370,10 @@ QWidget *QFormBuilder::create(DomUI *ui, QWidget *parentWidget) */ QLayout *QFormBuilder::create(DomLayout *ui_layout, QLayout *layout, QWidget *parentWidget) { + QFormBuilderExtra *fb = QFormBuilderExtra::instance(this); // Is this a temporary layout widget used to represent QLayout hierarchies in Designer? // Set its margins to 0. - bool layoutWidget = QFormBuilderExtra::instance(this)->processingLayoutWidget(); + bool layoutWidget = fb->processingLayoutWidget(); QLayout *l = QAbstractFormBuilder::create(ui_layout, layout, parentWidget); if (layoutWidget) { const QFormBuilderStrings &strings = QFormBuilderStrings::instance(); @@ -392,7 +394,7 @@ QLayout *QFormBuilder::create(DomLayout *ui_layout, QLayout *layout, QWidget *pa bottom = prop->elementNumber(); l->setContentsMargins(left, top, right, bottom); - QFormBuilderExtra::instance(this)->setProcessingLayoutWidget(false); + fb->setProcessingLayoutWidget(false); } return l; } -- cgit v0.12 From 13815a0768236982a025833497d3e2a2f3b6acf6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Fri, 29 May 2009 12:35:40 +0200 Subject: Fixed a crash in the GL 2 paintengine when drawing text. The new glyph cache may return null images for e.g. space characters. Task-number: 253468 Reviewed-by: Samuel BT: yes --- src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index a74f044..beb4da6 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -926,6 +926,9 @@ void QGL2PaintEngineEx::drawCachedGlyphs(const QPointF &p, const QTextItemInt &t const QImage &image = cache->image(); int margin = cache->glyphMargin(); + if (image.isNull()) + return; + glActiveTexture(QT_BRUSH_TEXTURE_UNIT); d->ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); -- cgit v0.12 From 7dfe8a7980172dccde7fb7920db31c1a8f80c61c Mon Sep 17 00:00:00 2001 From: hjk Date: Thu, 28 May 2009 18:05:24 +0200 Subject: extend QStringBuilder benchmark to handle QT_NO_CAST_FROM_ASCII defined and undefined. --- tests/benchmarks/qstringbuilder/main.cpp | 174 +++++++++++++++------ tests/benchmarks/qstringbuilder/qstringbuilder.pro | 4 - 2 files changed, 122 insertions(+), 56 deletions(-) diff --git a/tests/benchmarks/qstringbuilder/main.cpp b/tests/benchmarks/qstringbuilder/main.cpp index 8eb4e78..d4e2fa0 100644 --- a/tests/benchmarks/qstringbuilder/main.cpp +++ b/tests/benchmarks/qstringbuilder/main.cpp @@ -1,17 +1,64 @@ -#include "qstringbuilder.h" +// Select one of the scenarios below +#define SCENARIO 3 + +#if SCENARIO == 1 +// this is the "no harm done" version. Only operator% is active, +// with NO_CAST * defined +#define P % +#undef QT_USE_FAST_OPERATOR_PLUS +#undef QT_USE_FAST_CONCATENATION +#define QT_NO_CAST_FROM_ASCII +#define QT_NO_CAST_TO_ASCII +#endif -#include -#include -#include +#if SCENARIO == 2 +// this is the "full" version. Operator+ is replaced by a QStringBuilder +// based version +// with NO_CAST * defined +#define P % +#define QT_USE_FAST_OPERATOR_PLUS +#define QT_USE_FAST_CONCATENATION +#define QT_NO_CAST_FROM_ASCII +#define QT_NO_CAST_TO_ASCII +#endif + +#if SCENARIO == 3 +// this is the "no harm done" version. Only operator% is active, +// with NO_CAST * _not_ defined +#define P % +#undef QT_USE_FAST_OPERATOR_PLUS +#undef QT_USE_FAST_CONCATENATION +#undef QT_NO_CAST_FROM_ASCII +#undef QT_NO_CAST_TO_ASCII +#endif + +#if SCENARIO == 4 +// this is the "full" version. Operator+ is replaced by a QStringBuilder +// based version +// with NO_CAST * _not_ defined +#define P % +#define QT_USE_FAST_OPERATOR_PLUS +#define QT_USE_FAST_CONCATENATION +#undef QT_NO_CAST_FROM_ASCII +#undef QT_NO_CAST_TO_ASCII +#endif + +#include +#include +#include +#include + +#include #define COMPARE(a, b) QCOMPARE(a, b) //#define COMPARE(a, b) #define SEP(s) qDebug() << "\n\n-------- " s " ---------"; -#define L(s) QLatin1String(s) + +#define LITERAL "some string literal" class tst_qstringbuilder : public QObject { @@ -19,12 +66,16 @@ class tst_qstringbuilder : public QObject public: tst_qstringbuilder() - : l1literal("some string literal"), - l1string("some string literal"), - ba("some string literal"), + : l1literal(LITERAL), + l1string(LITERAL), + ba(LITERAL), string(l1string), stringref(&string, 2, 10), - achar('c') + achar('c'), + r2(QLatin1String(LITERAL LITERAL)), + r3(QLatin1String(LITERAL LITERAL LITERAL)), + r4(QLatin1String(LITERAL LITERAL LITERAL LITERAL)), + r5(QLatin1String(LITERAL LITERAL LITERAL LITERAL LITERAL)) {} @@ -51,10 +102,10 @@ public: int s = 0; for (int i = 0; i < N; ++i) { #if 0 - s += QString(l1literal % l1literal).size(); - s += QString(l1literal % l1literal % l1literal).size(); - s += QString(l1literal % l1literal % l1literal % l1literal).size(); - s += QString(l1literal % l1literal % l1literal % l1literal % l1literal).size(); + s += QString(l1literal P l1literal).size(); + s += QString(l1literal P l1literal P l1literal).size(); + s += QString(l1literal P l1literal P l1literal P l1literal).size(); + s += QString(l1literal P l1literal P l1literal P l1literal P l1literal).size(); #endif s += QString(achar % l1literal % achar).size(); } @@ -71,24 +122,30 @@ private slots: void separator_1() { SEP("literal + literal (builder first)"); } void b_2_l1literal() { - QBENCHMARK { r = l1literal % l1literal; } - COMPARE(r, QString(l1string + l1string)); + QBENCHMARK { r = l1literal P l1literal; } + COMPARE(r, r2); + } + #ifndef QT_NO_CAST_FROM_ASCII + void b_l1literal_LITERAL() { + QBENCHMARK { r = l1literal P LITERAL; } + COMPARE(r, r2); } + #endif void s_2_l1string() { QBENCHMARK { r = l1string + l1string; } - COMPARE(r, QString(l1literal % l1literal)); + COMPARE(r, r2); } void separator_2() { SEP("2 strings"); } void b_2_string() { - QBENCHMARK { r = string % string; } - COMPARE(r, QString(string + string)); + QBENCHMARK { r = string P string; } + COMPARE(r, r2); } void s_2_string() { QBENCHMARK { r = string + string; } - COMPARE(r, QString(string % string)); + COMPARE(r, r2); } @@ -107,12 +164,12 @@ private slots: void separator_2b() { SEP("3 strings"); } void b_3_string() { - QBENCHMARK { r = string % string % string; } - COMPARE(r, QString(string + string + string)); + QBENCHMARK { r = string P string P string; } + COMPARE(r, r3); } void s_3_string() { QBENCHMARK { r = string + string + string; } - COMPARE(r, QString(string % string % string)); + COMPARE(r, r3); } @@ -120,56 +177,66 @@ private slots: void b_string_l1literal() { QBENCHMARK { r = string % l1literal; } - COMPARE(r, QString(string + l1string)); + COMPARE(r, r2); } + #ifndef QT_NO_CAST_FROM_ASCII + void b_string_LITERAL() { + QBENCHMARK { r = string P LITERAL; } + COMPARE(r, r2); + } + void b_LITERAL_string() { + QBENCHMARK { r = LITERAL P string; } + COMPARE(r, r2); + } + #endif void b_string_l1string() { - QBENCHMARK { r = string % l1string; } - COMPARE(r, QString(string + l1string)); + QBENCHMARK { r = string P l1string; } + COMPARE(r, r2); } void s_string_l1literal() { QBENCHMARK { r = string + l1string; } - COMPARE(r, QString(string % l1literal)); + COMPARE(r, r2); } void s_string_l1string() { QBENCHMARK { r = string + l1string; } - COMPARE(r, QString(string % l1literal)); + COMPARE(r, r2); } void separator_3() { SEP("3 literals"); } void b_3_l1literal() { - QBENCHMARK { r = l1literal % l1literal % l1literal; } - COMPARE(r, QString(l1string + l1string + l1string)); + QBENCHMARK { r = l1literal P l1literal P l1literal; } + COMPARE(r, r3); } void s_3_l1string() { QBENCHMARK { r = l1string + l1string + l1string; } - COMPARE(r, QString(l1literal % l1literal % l1literal)); + COMPARE(r, r3); } void separator_4() { SEP("4 literals"); } void b_4_l1literal() { - QBENCHMARK { r = l1literal % l1literal % l1literal % l1literal; } - COMPARE(r, QString(l1string + l1string + l1string + l1string)); + QBENCHMARK { r = l1literal P l1literal P l1literal P l1literal; } + COMPARE(r, r4); } void s_4_l1string() { QBENCHMARK { r = l1string + l1string + l1string + l1string; } - COMPARE(r, QString(l1literal % l1literal % l1literal % l1literal)); + COMPARE(r, r4); } void separator_5() { SEP("5 literals"); } void b_5_l1literal() { - QBENCHMARK { r = l1literal % l1literal % l1literal % l1literal %l1literal; } - COMPARE(r, QString(l1string + l1string + l1string + l1string + l1string)); + QBENCHMARK { r = l1literal P l1literal P l1literal P l1literal P l1literal; } + COMPARE(r, r5); } void s_5_l1string() { QBENCHMARK { r = l1string + l1string + l1string + l1string + l1string; } - COMPARE(r, QString(l1literal % l1literal % l1literal % l1literal % l1literal)); + COMPARE(r, r5); } @@ -177,12 +244,12 @@ private slots: void b_string_4_char() { QBENCHMARK { r = string + achar + achar + achar + achar; } - COMPARE(r, QString(string % achar % achar % achar % achar)); + COMPARE(r, QString(string P achar P achar P achar P achar)); } void s_string_4_char() { QBENCHMARK { r = string + achar + achar + achar + achar; } - COMPARE(r, QString(string % achar % achar % achar % achar)); + COMPARE(r, QString(string P achar P achar P achar P achar)); } @@ -190,26 +257,26 @@ private slots: void b_char_string_char() { QBENCHMARK { r = achar + string + achar; } - COMPARE(r, QString(achar % string % achar)); + COMPARE(r, QString(achar P string P achar)); } void s_char_string_char() { QBENCHMARK { r = achar + string + achar; } - COMPARE(r, QString(achar % string % achar)); + COMPARE(r, QString(achar P string P achar)); } void separator_8() { SEP("string.arg"); } void b_string_arg() { - const QString pattern = l1string + QLatin1String("%1") + l1string; - QBENCHMARK { r = l1literal % string % l1literal; } - COMPARE(r, QString(l1string + string + l1string)); + const QString pattern = l1string + QString::fromLatin1("%1") + l1string; + QBENCHMARK { r = l1literal P string P l1literal; } + COMPARE(r, r3); } void s_string_arg() { const QString pattern = l1string + QLatin1String("%1") + l1string; QBENCHMARK { r = pattern.arg(string); } - COMPARE(r, QString(l1string + string + l1string)); + COMPARE(r, r3); } void s_bytearray_arg() { @@ -223,16 +290,16 @@ private slots: void b_reserve() { QBENCHMARK { r.clear(); - r = string % string % string % string; + r = string P string P string P string; } - COMPARE(r, QString(string + string + string + string)); + COMPARE(r, r4); } void b_reserve_lit() { QBENCHMARK { r.clear(); - r = string % l1literal % string % string; + r = string P l1literal P string P string; } - COMPARE(r, QString(string + string + string + string)); + COMPARE(r, r4); } void s_reserve() { QBENCHMARK { @@ -243,7 +310,7 @@ private slots: r += string; r += string; } - COMPARE(r, QString(string + string + string + string)); + COMPARE(r, r4); } void s_reserve_lit() { QBENCHMARK { @@ -256,7 +323,7 @@ private slots: r += string; r += string; } - COMPARE(r, QString(string + string + string + string)); + COMPARE(r, r4); } private: @@ -266,6 +333,7 @@ private: const QString string; const QStringRef stringref; const QLatin1Char achar; + const QString r2, r3, r4, r5; QString r; }; @@ -280,12 +348,14 @@ int main(int argc, char *argv[]) //QString("x") % 2; // Sanity test, should only compile when the // operator%(QString, int) is visible. - if (argc == 2 && (argv[1] == L("--run-builder") || argv[1] == L("-b"))) { + if (argc == 2 && (QLatin1String(argv[1]) == QLatin1String("--run-builder") + || QLatin1String(argv[1]) == QLatin1String("-b"))) { tst_qstringbuilder test; return test.run_builder(); } - if (argc == 2 && (argv[1] == L("--run-traditional") || argv[1] == L("-t"))) { + if (argc == 2 && (QLatin1String(argv[1]) == QLatin1String("--run-traditional") + || QLatin1String(argv[1]) == QLatin1String("-t"))) { tst_qstringbuilder test; return test.run_traditional(); } diff --git a/tests/benchmarks/qstringbuilder/qstringbuilder.pro b/tests/benchmarks/qstringbuilder/qstringbuilder.pro index 02daaaa..79171b4 100644 --- a/tests/benchmarks/qstringbuilder/qstringbuilder.pro +++ b/tests/benchmarks/qstringbuilder/qstringbuilder.pro @@ -2,10 +2,6 @@ load(qttest_p4) TEMPLATE = app TARGET = tst_qstringbuilder -# Uncomment to test compilation of the drop-in -# replacement operator+() -#DEFINES += QT_USE_FAST_OPERATOR_PLUS - QMAKE_CXXFLAGS += -g QMAKE_CFLAGS += -g -- cgit v0.12 From fe3b9390872bfb03a94be8c17cdc0ce6946369bb Mon Sep 17 00:00:00 2001 From: hjk Date: Fri, 29 May 2009 13:09:59 +0200 Subject: Fix qstringbuilder documentation. It was using !fn instead of \fn accidentally. --- src/corelib/tools/qstringbuilder.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/tools/qstringbuilder.cpp b/src/corelib/tools/qstringbuilder.cpp index b807a89..1ffe2c3 100644 --- a/src/corelib/tools/qstringbuilder.cpp +++ b/src/corelib/tools/qstringbuilder.cpp @@ -122,7 +122,7 @@ \sa QLatin1Literal, QString */ -/* !fn template QStringBuilder operator%(const A &a, const B &b) +/* \fn template QStringBuilder operator%(const A &a, const B &b) Returns a \c QStringBuilder object that is converted to a QString object when assigned to a variable of QString type or passed to a function that -- cgit v0.12 From fd255177af9d946e271d67000d3867b72cb5c682 Mon Sep 17 00:00:00 2001 From: Erik Verbruggen Date: Fri, 29 May 2009 13:20:11 +0200 Subject: Added range information for lists which contains the position and length from the open bracket upto the close bracket. --- src/declarative/qml/qmldom.cpp | 24 ++++++++++++++++++++++++ src/declarative/qml/qmldom.h | 3 +++ src/declarative/qml/qmlparser_p.h | 1 + src/declarative/qml/qmlscriptparser.cpp | 5 +++++ 4 files changed, 33 insertions(+) diff --git a/src/declarative/qml/qmldom.cpp b/src/declarative/qml/qmldom.cpp index 38436b4..0ebbbfb 100644 --- a/src/declarative/qml/qmldom.cpp +++ b/src/declarative/qml/qmldom.cpp @@ -1415,6 +1415,30 @@ void QmlDomList::setValues(const QList &values) qWarning("QmlDomList::setValues(const QList &): Not implemented"); } +/*! + Returns the position in the input data where the list started, or 0 if + the property is invalid. +*/ +int QmlDomList::position() const +{ + if (d && d->property) { + return d->property->listValueRange.offset; + } else + return 0; +} + +/*! + Returns the length in the input data from where the list started upto + the end of it, or 0 if the property is invalid. +*/ +int QmlDomList::length() const +{ + if (d && d->property) + return d->property->listValueRange.length; + else + return 0; +} + /*! \class QmlDomComponent diff --git a/src/declarative/qml/qmldom.h b/src/declarative/qml/qmldom.h index 04ce8b9..86eaecb 100644 --- a/src/declarative/qml/qmldom.h +++ b/src/declarative/qml/qmldom.h @@ -262,6 +262,9 @@ public: QList values() const; void setValues(const QList &); + int position() const; + int length() const; + private: friend class QmlDomValue; QSharedDataPointer d; diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h index 020cae5..0fdd26b 100644 --- a/src/declarative/qml/qmlparser_p.h +++ b/src/declarative/qml/qmlparser_p.h @@ -276,6 +276,7 @@ namespace QmlParser bool isDefault; LocationSpan location; + LocationRange listValueRange; void dump(int = 0) const; }; diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index 75c81a7..31a20be 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -651,6 +651,11 @@ bool ProcessAST::visit(AST::UiArrayBinding *node) accept(node->members); + // For the DOM, store the position of the T_LBRACKET upto the T_RBRACKET as the range: + Property* prop = currentProperty(); + prop->listValueRange.offset = node->lbracketToken.offset; + prop->listValueRange.length = node->rbracketToken.offset + node->rbracketToken.length - node->lbracketToken.offset; + while (propertyCount--) _stateStack.pop(); -- cgit v0.12 From b34d9b67fbdc6bf74f7ada972dd9b35153f47202 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Fri, 29 May 2009 13:43:48 +0200 Subject: Added the -showinternal flag to qdoc. When you set -showinternal on the command line, qdoc will include everything marked \internal in the documentation. This flag is not very useful at the moment for two reasons: (1) It generates hundreds of qdoc errors because most of the things marked with \internal don't have any documentation anyway, or the documentation has other errors in it that weren't being detected because of the \internal. (2) There is a bus error toward the end, which I haven't tracked down yet. For now, use -showinternal at your own risk. --- tools/qdoc3/codeparser.cpp | 14 +++++++++----- tools/qdoc3/codeparser.h | 1 + tools/qdoc3/config.h | 1 + tools/qdoc3/main.cpp | 22 +++++++++++++++------- 4 files changed, 26 insertions(+), 12 deletions(-) diff --git a/tools/qdoc3/codeparser.cpp b/tools/qdoc3/codeparser.cpp index f0ff27e..20b37a0 100644 --- a/tools/qdoc3/codeparser.cpp +++ b/tools/qdoc3/codeparser.cpp @@ -47,6 +47,7 @@ #include "codeparser.h" #include "node.h" #include "tree.h" +#include "config.h" QT_BEGIN_NAMESPACE @@ -67,6 +68,7 @@ QT_BEGIN_NAMESPACE #define COMMAND_TITLE Doc::alias(QLatin1String("title")) QList CodeParser::parsers; +bool CodeParser::showInternal = false; /*! The constructor adds this code parser to the static @@ -87,11 +89,11 @@ CodeParser::~CodeParser() } /*! - Initializing a code parser is trivial. + Initialize the code parser base class. */ -void CodeParser::initializeParser(const Config & /* config */) +void CodeParser::initializeParser(const Config& config) { - // nothing. + showInternal = config.getBool(QLatin1String(CONFIG_SHOWINTERNAL)); } /*! @@ -217,8 +219,10 @@ void CodeParser::processCommonMetaCommand(const Location &location, node->setStatus(Node::Preliminary); } else if (command == COMMAND_INTERNAL) { - node->setAccess(Node::Private); - node->setStatus(Node::Internal); + if (!showInternal) { + node->setAccess(Node::Private); + node->setStatus(Node::Internal); + } } else if (command == COMMAND_REENTRANT) { node->setThreadSafeness(Node::Reentrant); diff --git a/tools/qdoc3/codeparser.h b/tools/qdoc3/codeparser.h index 019e806..0152b9c 100644 --- a/tools/qdoc3/codeparser.h +++ b/tools/qdoc3/codeparser.h @@ -87,6 +87,7 @@ class CodeParser private: static QList parsers; + static bool showInternal; }; QT_END_NAMESPACE diff --git a/tools/qdoc3/config.h b/tools/qdoc3/config.h index 9443f0d..7eb7048 100644 --- a/tools/qdoc3/config.h +++ b/tools/qdoc3/config.h @@ -147,6 +147,7 @@ class Config #define CONFIG_QHP "qhp" #define CONFIG_QUOTINGINFORMATION "quotinginformation" #define CONFIG_SLOW "slow" +#define CONFIG_SHOWINTERNAL "showinternal" #define CONFIG_SOURCEDIRS "sourcedirs" #define CONFIG_SOURCES "sources" #define CONFIG_SPURIOUS "spurious" diff --git a/tools/qdoc3/main.cpp b/tools/qdoc3/main.cpp index 514d06e..995d037 100644 --- a/tools/qdoc3/main.cpp +++ b/tools/qdoc3/main.cpp @@ -95,6 +95,7 @@ static const struct { }; static bool slow = false; +static bool showInternal = false; static QStringList defines; static QHash trees; @@ -120,14 +121,16 @@ static void printHelp() { Location::information(tr("Usage: qdoc [options] file1.qdocconf ...\n" "Options:\n" - " -help " + " -help " "Display this information and exit\n" - " -version " + " -version " "Display version of qdoc and exit\n" - " -D " + " -D " "Define as a macro while parsing sources\n" - " -slow " - "Turn on features that slow down qdoc") ); + " -slow " + "Turn on features that slow down qdoc" + " -showinternal " + "Include stuff marked internal") ); } /*! @@ -160,6 +163,8 @@ static void processQdocconfFile(const QString &fileName) ++i; } config.setStringList(CONFIG_SLOW, QStringList(slow ? "true" : "false")); + config.setStringList(CONFIG_SHOWINTERNAL, + QStringList(showInternal ? "true" : "false")); /* With the default configuration values in place, load @@ -326,10 +331,11 @@ static void processQdocconfFile(const QString &fileName) /* Generate the XML tag file, if it was requested. */ + QString tagFile = config.getString(CONFIG_TAGFILE); if (!tagFile.isEmpty()) tree->generateTagFile(tagFile); - + tree->setVersion(""); Generator::terminate(); CodeParser::terminate(); @@ -342,7 +348,6 @@ static void processQdocconfFile(const QString &fileName) foreach (QTranslator *translator, translators) delete translator; - delete tree; } @@ -426,6 +431,9 @@ int main(int argc, char **argv) else if (opt == "-slow") { slow = true; } + else if (opt == "-showinternal") { + showInternal = true; + } else { qdocFiles.append(opt); } -- cgit v0.12 From 7fc1d12ebd103539168be590b1cde91d49a3d75b Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Fri, 29 May 2009 13:35:43 +0200 Subject: Do not hide the left edge of widget in statusbar Could be caused by change d2cba538 Reviewed-by: jbache Task-number: 254083 --- src/gui/widgets/qstatusbar.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/widgets/qstatusbar.cpp b/src/gui/widgets/qstatusbar.cpp index c970838..3829bcb 100644 --- a/src/gui/widgets/qstatusbar.cpp +++ b/src/gui/widgets/qstatusbar.cpp @@ -144,7 +144,7 @@ QRect QStatusBarPrivate::messageRect() const if (rtl) left = qMax(left, item->w->x() + item->w->width() + 2); else - right = qMin(right, item->w->x()-1); + right = qMin(right, item->w->x() - 2); } break; } -- cgit v0.12 From 4193c81617e8f86f7939966465623a5170830b26 Mon Sep 17 00:00:00 2001 From: David Faure Date: Fri, 29 May 2009 14:40:01 +0200 Subject: static method, no instance needed --- src/corelib/kernel/qtranslator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/kernel/qtranslator.cpp b/src/corelib/kernel/qtranslator.cpp index 308ca24..1b42c4e 100644 --- a/src/corelib/kernel/qtranslator.cpp +++ b/src/corelib/kernel/qtranslator.cpp @@ -346,7 +346,7 @@ QTranslator::QTranslator(QObject * parent, const char * name) QTranslator::~QTranslator() { if (QCoreApplication::instance()) - QCoreApplication::instance()->removeTranslator(this); + QCoreApplication::removeTranslator(this); Q_D(QTranslator); d->clear(); } -- cgit v0.12 From 1d8a4f55ce40400fcb35a645f2e94837e6ab0a24 Mon Sep 17 00:00:00 2001 From: David Faure Date: Fri, 29 May 2009 14:40:50 +0200 Subject: typo fix --- tests/auto/test.pl | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/auto/test.pl b/tests/auto/test.pl index f2a1fe4..9fd5c9d 100755 --- a/tests/auto/test.pl +++ b/tests/auto/test.pl @@ -179,7 +179,7 @@ print " Tests started: $totalStarted \n"; print " Tests executed: $totalExecuted \n"; print " Tests timed out: $totalTimedOut \n"; -# This procedure takes care of handling death children on due time +# This procedure takes care of handling dead children on due time sub handleDeath { $buryChildren = 1; } -- cgit v0.12 From 4b00e265388ed09017702489437c79e0b1a19a44 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Fri, 29 May 2009 14:52:44 +0200 Subject: Enable overriding of the factory functions of QUiLoader. Move initialization of QAction/QActionGroups elsewhere. Detect the root widget by checking its parent against the parent widget passed in and apply only the size part of the geometry property to it. Task-number: 254824 Initial-patch-by: joao --- tools/designer/src/lib/uilib/abstractformbuilder.cpp | 7 ++----- tools/designer/src/lib/uilib/formbuilder.cpp | 15 ++++++++------- tools/designer/src/lib/uilib/formbuilderextra.cpp | 18 +++++++++++++----- tools/designer/src/lib/uilib/formbuilderextra_p.h | 8 +++++--- 4 files changed, 28 insertions(+), 20 deletions(-) diff --git a/tools/designer/src/lib/uilib/abstractformbuilder.cpp b/tools/designer/src/lib/uilib/abstractformbuilder.cpp index 4dae28e..c5aefb1 100644 --- a/tools/designer/src/lib/uilib/abstractformbuilder.cpp +++ b/tools/designer/src/lib/uilib/abstractformbuilder.cpp @@ -403,6 +403,7 @@ QAction *QAbstractFormBuilder::create(DomAction *ui_action, QObject *parent) if (!a) return 0; + m_actions.insert(ui_action->attributeName(), a); applyProperties(a, ui_action->elementProperty()); return a; } @@ -415,7 +416,7 @@ QActionGroup *QAbstractFormBuilder::create(DomActionGroup *ui_action_group, QObj QActionGroup *a = createActionGroup(parent, ui_action_group->attributeName()); if (!a) return 0; - + m_actionGroups.insert(ui_action_group->attributeName(), a); applyProperties(a, ui_action_group->elementProperty()); foreach (DomAction *ui_action, ui_action_group->elementAction()) { @@ -1184,8 +1185,6 @@ QAction *QAbstractFormBuilder::createAction(QObject *parent, const QString &name { QAction *action = new QAction(parent); action->setObjectName(name); - m_actions.insert(name, action); - return action; } @@ -1196,8 +1195,6 @@ QActionGroup *QAbstractFormBuilder::createActionGroup(QObject *parent, const QSt { QActionGroup *g = new QActionGroup(parent); g->setObjectName(name); - m_actionGroups.insert(name, g); - return g; } diff --git a/tools/designer/src/lib/uilib/formbuilder.cpp b/tools/designer/src/lib/uilib/formbuilder.cpp index 5a771b7..53d1e9d 100644 --- a/tools/designer/src/lib/uilib/formbuilder.cpp +++ b/tools/designer/src/lib/uilib/formbuilder.cpp @@ -121,6 +121,8 @@ QFormBuilder::~QFormBuilder() QWidget *QFormBuilder::create(DomWidget *ui_widget, QWidget *parentWidget) { QFormBuilderExtra *fb = QFormBuilderExtra::instance(this); + if (!fb->parentWidgetIsSet()) + fb->setParentWidget(parentWidget); fb->setProcessingLayoutWidget(false); if (ui_widget->attributeClass() == QFormBuilderStrings::instance().qWidgetClass && !ui_widget->hasAttributeNative() && parentWidget @@ -229,9 +231,6 @@ QWidget *QFormBuilder::createWidget(const QString &widgetName, QWidget *parentWi if (qobject_cast(w)) w->setParent(parentWidget); - if (!fb->rootWidget()) - fb->setRootWidget(w); - return w; } @@ -527,6 +526,7 @@ QList QFormBuilder::customWidgets() const /*! \internal */ + void QFormBuilder::applyProperties(QObject *o, const QList &properties) { typedef QList DomPropertyList; @@ -544,11 +544,12 @@ void QFormBuilder::applyProperties(QObject *o, const QList &proper continue; const QString attributeName = (*it)->attributeName(); - if (o == fb->rootWidget() && attributeName == strings.geometryProperty) { - // apply only the size for the rootWidget - fb->rootWidget()->resize(qvariant_cast(v).size()); + const bool isWidget = o->isWidgetType(); + if (isWidget && o->parent() == fb->parentWidget() && attributeName == strings.geometryProperty) { + // apply only the size part of a geometry for the root widget + static_cast(o)->resize(qvariant_cast(v).size()); } else if (fb->applyPropertyInternally(o, attributeName, v)) { - } else if (!qstrcmp("QFrame", o->metaObject()->className ()) && attributeName == strings.orientationProperty) { + } else if (isWidget && !qstrcmp("QFrame", o->metaObject()->className ()) && attributeName == strings.orientationProperty) { // ### special-casing for Line (QFrame) -- try to fix me o->setProperty("frameShape", v); // v is of QFrame::Shape enum } else { diff --git a/tools/designer/src/lib/uilib/formbuilderextra.cpp b/tools/designer/src/lib/uilib/formbuilderextra.cpp index cb82967..38fe2ae 100644 --- a/tools/designer/src/lib/uilib/formbuilderextra.cpp +++ b/tools/designer/src/lib/uilib/formbuilderextra.cpp @@ -81,7 +81,8 @@ QFormBuilderExtra::~QFormBuilderExtra() void QFormBuilderExtra::clear() { m_buddies.clear(); - m_rootWidget = 0; + m_parentWidget = 0; + m_parentWidgetIsSet = false; #ifndef QT_FORMBUILDER_NO_SCRIPT m_FormScriptRunner.clearErrors(); m_customWidgetScriptHash.clear(); @@ -136,14 +137,21 @@ bool QFormBuilderExtra::applyBuddy(const QString &buddyName, BuddyMode applyMode return false; } -const QPointer &QFormBuilderExtra::rootWidget() const +const QPointer &QFormBuilderExtra::parentWidget() const { - return m_rootWidget; + return m_parentWidget; } -void QFormBuilderExtra::setRootWidget(const QPointer &w) +bool QFormBuilderExtra::parentWidgetIsSet() const { - m_rootWidget = w; + return m_parentWidgetIsSet; +} + +void QFormBuilderExtra::setParentWidget(const QPointer &w) +{ + // Parent widget requires special handling of the geometry property. + m_parentWidget = w; + m_parentWidgetIsSet = true; } #ifndef QT_FORMBUILDER_NO_SCRIPT diff --git a/tools/designer/src/lib/uilib/formbuilderextra_p.h b/tools/designer/src/lib/uilib/formbuilderextra_p.h index f357239..9166c48 100644 --- a/tools/designer/src/lib/uilib/formbuilderextra_p.h +++ b/tools/designer/src/lib/uilib/formbuilderextra_p.h @@ -101,8 +101,9 @@ public: void applyInternalProperties() const; static bool applyBuddy(const QString &buddyName, BuddyMode applyMode, QLabel *label); - const QPointer &rootWidget() const; - void setRootWidget(const QPointer &w); + const QPointer &parentWidget() const; + bool parentWidgetIsSet() const; + void setParentWidget(const QPointer &w); #ifndef QT_FORMBUILDER_NO_SCRIPT QFormScriptRunner &formScriptRunner(); @@ -182,7 +183,8 @@ private: QResourceBuilder *m_resourceBuilder; QTextBuilder *m_textBuilder; - QPointer m_rootWidget; + QPointer m_parentWidget; + bool m_parentWidgetIsSet; }; void uiLibWarning(const QString &message); -- cgit v0.12 From 37f3aeae8198d98cf9e33990b85e9b6fc443d948 Mon Sep 17 00:00:00 2001 From: Friedemann Kleint Date: Fri, 29 May 2009 14:58:19 +0200 Subject: Fixed docs for task 254824. Task-number: 254824 --- tools/designer/src/uitools/quiloader.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tools/designer/src/uitools/quiloader.cpp b/tools/designer/src/uitools/quiloader.cpp index 2a66095..c6c2d80 100644 --- a/tools/designer/src/uitools/quiloader.cpp +++ b/tools/designer/src/uitools/quiloader.cpp @@ -613,8 +613,7 @@ void QUiLoaderPrivate::setupWidgetMap() const reason, you can subclass the QUiLoader class and reimplement these functions to intervene the process of constructing a user interface. For example, you might want to have a list of the actions created when loading - a form or creating a custom widget. However, in your reimplementation, you - must call QUiLoader's original implementation of these functions first. + a form or creating a custom widget. For a complete example using the QUiLoader class, see the \l{Calculator Builder Example}. -- cgit v0.12 From e3d744270d6ae4f1e893784e3e064d47e25c1fbe Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 29 May 2009 15:44:22 +0200 Subject: Doc - some changes to fix a qdoc warning --- src/corelib/tools/qstringbuilder.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/corelib/tools/qstringbuilder.cpp b/src/corelib/tools/qstringbuilder.cpp index 1ffe2c3..2b4a242 100644 --- a/src/corelib/tools/qstringbuilder.cpp +++ b/src/corelib/tools/qstringbuilder.cpp @@ -71,8 +71,8 @@ /*! \fn int QLatin1Literal::size() const - Returns the number of characters in the literal \i{excluding} the trailing - NUL char. + Returns the number of characters in the literal \e{excluding} the trailing + NULL char. */ /*! \fn char *QLatin1Literal::data() const -- cgit v0.12 From 28305c37a1874be6919c316be03fff2aaf3d94cb Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Fri, 29 May 2009 15:54:00 +0200 Subject: Remove unused variable. --- src/gui/kernel/qwidget_x11.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/gui/kernel/qwidget_x11.cpp b/src/gui/kernel/qwidget_x11.cpp index e00c37c..6250fb77 100644 --- a/src/gui/kernel/qwidget_x11.cpp +++ b/src/gui/kernel/qwidget_x11.cpp @@ -1509,7 +1509,6 @@ QWidget *QWidget::keyboardGrabber() void QWidget::activateWindow() { - Q_D(QWidget); QWidget *tlw = window(); if (tlw->isVisible() && !tlw->d_func()->topData()->embedded && !X11->deferred_map.contains(tlw)) { if (X11->userTime == 0) -- cgit v0.12 From 58fa04d1ac4b961bae11dd2261861201823322cc Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Fri, 29 May 2009 15:48:06 +0200 Subject: Remove icon when setting an empty window icon on X11. We used to leave _NET_WM_ICON set forever, and removing an IconPixmapHint from WMHints didn't work properly. Reviewed-by: Bradley T. Hughes --- src/gui/kernel/qwidget_x11.cpp | 53 ++++++++++++++++++++++++------------------ 1 file changed, 31 insertions(+), 22 deletions(-) diff --git a/src/gui/kernel/qwidget_x11.cpp b/src/gui/kernel/qwidget_x11.cpp index 7e41ea1..adb48a8 100644 --- a/src/gui/kernel/qwidget_x11.cpp +++ b/src/gui/kernel/qwidget_x11.cpp @@ -1359,17 +1359,10 @@ void QWidgetPrivate::setWindowIcon_sys(bool forceReset) // already been set return; - XWMHints *h = 0; - if (q->internalWinId()) - h = XGetWMHints(X11->display, q->internalWinId()); - XWMHints wm_hints; - if (!h) { - memset(&wm_hints, 0, sizeof(wm_hints)); // make valgrind happy - h = &wm_hints; - } - // preparing images to set the _NET_WM_ICON property QIcon icon = q->windowIcon(); + QVector icon_data; + Qt::HANDLE pixmap_handle = 0; if (!icon.isNull()) { QList availableSizes = icon.availableSizes(); if(availableSizes.isEmpty()) { @@ -1379,7 +1372,6 @@ void QWidgetPrivate::setWindowIcon_sys(bool forceReset) availableSizes.push_back(QSize(64,64)); availableSizes.push_back(QSize(128,128)); } - QVector icon_data; for(int i = 0; i < availableSizes.size(); ++i) { QSize size = availableSizes.at(i); QPixmap pixmap = icon.pixmap(size); @@ -1401,11 +1393,6 @@ void QWidgetPrivate::setWindowIcon_sys(bool forceReset) } } if (!icon_data.isEmpty()) { - if (q->internalWinId()) { - XChangeProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_ICON), XA_CARDINAL, 32, - PropModeReplace, (unsigned char *) icon_data.data(), - icon_data.size()); - } extern QPixmap qt_toX11Pixmap(const QPixmap &pixmap); /* if the app is running on an unknown desktop, or it is not @@ -1419,22 +1406,44 @@ void QWidgetPrivate::setWindowIcon_sys(bool forceReset) // unknown DE or non-default visual/colormap, use 1bpp bitmap if (!forceReset || !topData->iconPixmap) topData->iconPixmap = new QBitmap(qt_toX11Pixmap(icon.pixmap(QSize(64,64)))); - h->icon_pixmap = topData->iconPixmap->handle(); + pixmap_handle = topData->iconPixmap->handle(); } else { // default depth, use a normal pixmap (even though this // violates the ICCCM), since this works on all DEs known to Qt if (!forceReset || !topData->iconPixmap) topData->iconPixmap = new QPixmap(qt_toX11Pixmap(icon.pixmap(QSize(64,64)))); - h->icon_pixmap = static_cast(topData->iconPixmap->data)->x11ConvertToDefaultDepth(); + pixmap_handle = static_cast(topData->iconPixmap->data)->x11ConvertToDefaultDepth(); } - h->flags |= IconPixmapHint; - } else { - h->flags &= ~(IconPixmapHint | IconMaskHint); } } - if (q->internalWinId()) - XSetWMHints(X11->display, q->internalWinId(), h); + if (!q->internalWinId()) + return; + + if (!icon_data.isEmpty()) { + XChangeProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_ICON), XA_CARDINAL, 32, + PropModeReplace, (unsigned char *) icon_data.data(), + icon_data.size()); + } else { + XDeleteProperty(X11->display, q->internalWinId(), ATOM(_NET_WM_ICON)); + } + + XWMHints *h = XGetWMHints(X11->display, q->internalWinId()); + XWMHints wm_hints; + if (!h) { + memset(&wm_hints, 0, sizeof(wm_hints)); // make valgrind happy + h = &wm_hints; + } + + if (pixmap_handle) { + h->icon_pixmap = pixmap_handle; + h->flags |= IconPixmapHint; + } else { + h->icon_pixmap = 0; + h->flags &= ~(IconPixmapHint | IconMaskHint); + } + + XSetWMHints(X11->display, q->internalWinId(), h); if (h != &wm_hints) XFree((char *)h); } -- cgit v0.12 From 235818fdac5faf0d38f9b37c7bd5ee522935aed1 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Fri, 29 May 2009 10:11:29 +0200 Subject: Removed nested comment signature in the doc to fix a warning. Reviewed-by: David Boddie --- src/corelib/kernel/qobject.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index f1a1eb5..7e5f779 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -2066,7 +2066,7 @@ void QObject::deleteLater() or - \tt{/*: ... \starslash} + \tt{\begincomment: ... \endcomment} Examples: -- cgit v0.12 From a322d3faacdb8e5a8649b478b3eaa8aa03d789d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 29 May 2009 13:59:19 +0200 Subject: Added check in GL pixmap backend to fall back to raster if FBO fails. --- src/opengl/qpixmapdata_gl.cpp | 69 +++++++++++++++++++++++-------------------- 1 file changed, 37 insertions(+), 32 deletions(-) diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index 85bcda5..8d94c8b 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -372,45 +372,50 @@ QPaintEngine* QGLPixmapData::paintEngine() const if (m_engine) return m_engine; - else if (!useFramebufferObjects()) { - m_dirty = true; - if (m_source.size() != size()) - m_source = QImage(size(), QImage::Format_ARGB32_Premultiplied); - if (m_hasFillColor) { - m_source.fill(PREMUL(m_fillColor.rgba())); - m_hasFillColor = false; - } - return m_source.paintEngine(); - } - extern QGLWidget* qt_gl_share_widget(); + if (useFramebufferObjects()) { + extern QGLWidget* qt_gl_share_widget(); - if (!QGLContext::currentContext()) - qt_gl_share_widget()->makeCurrent(); - QGLShareContextScope ctx(qt_gl_share_widget()->context()); + if (!QGLContext::currentContext()) + qt_gl_share_widget()->makeCurrent(); + QGLShareContextScope ctx(qt_gl_share_widget()->context()); - if (textureBufferStack.size() <= currentTextureBuffer) { - textureBufferStack << createTextureBuffer(size()); - } else { - QSize sz = textureBufferStack.at(currentTextureBuffer).fbo->size(); - if (sz.width() < m_width || sz.height() < m_height) { - if (sz.width() < m_width) - sz.setWidth(qMax(m_width, qRound(sz.width() * 1.5))); - if (sz.height() < m_height) - sz.setHeight(qMax(m_height, qRound(sz.height() * 1.5))); - delete textureBufferStack.at(currentTextureBuffer).fbo; - textureBufferStack[currentTextureBuffer] = - createTextureBuffer(sz, textureBufferStack.at(currentTextureBuffer).engine); - qDebug() << "Creating new pixmap texture buffer:" << sz; + if (textureBufferStack.size() <= currentTextureBuffer) { + textureBufferStack << createTextureBuffer(size()); + } else { + QSize sz = textureBufferStack.at(currentTextureBuffer).fbo->size(); + if (sz.width() < m_width || sz.height() < m_height) { + if (sz.width() < m_width) + sz.setWidth(qMax(m_width, qRound(sz.width() * 1.5))); + if (sz.height() < m_height) + sz.setHeight(qMax(m_height, qRound(sz.height() * 1.5))); + delete textureBufferStack.at(currentTextureBuffer).fbo; + textureBufferStack[currentTextureBuffer] = + createTextureBuffer(sz, textureBufferStack.at(currentTextureBuffer).engine); + qDebug() << "Creating new pixmap texture buffer:" << sz; + } } - } - m_renderFbo = textureBufferStack.at(currentTextureBuffer).fbo; - m_engine = textureBufferStack.at(currentTextureBuffer).engine; + if (textureBufferStack.at(currentTextureBuffer).fbo->isValid()) { + m_renderFbo = textureBufferStack.at(currentTextureBuffer).fbo; + m_engine = textureBufferStack.at(currentTextureBuffer).engine; + + ++currentTextureBuffer; + + return m_engine; + } - ++currentTextureBuffer; + qWarning() << "Failed to create pixmap texture buffer of size " << size() << ", falling back to raster paint engine"; + } - return m_engine; + m_dirty = true; + if (m_source.size() != size()) + m_source = QImage(size(), QImage::Format_ARGB32_Premultiplied); + if (m_hasFillColor) { + m_source.fill(PREMUL(m_fillColor.rgba())); + m_hasFillColor = false; + } + return m_source.paintEngine(); } GLuint QGLPixmapData::bind(bool copyBack) const -- cgit v0.12 From 07fbbf76bef1845bb6c490b15a0b7caabf23d888 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 29 May 2009 14:00:45 +0200 Subject: Made GL2 engine default for QGLWidget, and added GL2 sync() function To allow mixing QPainter and raw OpenGL commands we need to have some way for the user to say that's he's about to use raw OpenGL so that we are free to do buffering optimizations in the paint engines and use either GL1 or GL2 paint engine. As there's already a syncState() function in QPaintEngine we've reused this and added QPaintEngineEx::sync() which takes care of syncing/flushing the paint engine. Reviewed-by: Trond --- dist/changes-4.6.0 | 5 +++ src/gui/painting/qpaintengine.cpp | 4 +++ src/gui/painting/qpaintengineex_p.h | 2 ++ .../gl2paintengineex/qpaintengineex_opengl2.cpp | 37 ++++++++++++++++++++++ .../gl2paintengineex/qpaintengineex_opengl2_p.h | 1 + src/opengl/qgl_p.h | 2 +- 6 files changed, 50 insertions(+), 1 deletion(-) diff --git a/dist/changes-4.6.0 b/dist/changes-4.6.0 index 6a94f26..bedf58a 100644 --- a/dist/changes-4.6.0 +++ b/dist/changes-4.6.0 @@ -49,3 +49,8 @@ information about a particular change. - QStyleOptionGraphicsItem::levelOfDetails is obsoleted and its value is always initialized to 1. For a more fine-grained value use QStyleOptionGraphicsItem::levelOfDetailFromTransform(const QTransform &). + + - When mixing OpenGL and QPainter calls you need to first call syncState() + on the paint engine, for example "painter->paintEngine()->syncState()". + This is to ensure that the engine flushes any pending drawing and sets up + the GL modelview/projection matrices properly. diff --git a/src/gui/painting/qpaintengine.cpp b/src/gui/painting/qpaintengine.cpp index 7de1ec4..9859425 100644 --- a/src/gui/painting/qpaintengine.cpp +++ b/src/gui/painting/qpaintengine.cpp @@ -49,6 +49,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -302,6 +303,9 @@ void QPaintEngine::syncState() { Q_ASSERT(state); updateState(*state); + + if (isExtended()) + static_cast(this)->sync(); } static QPaintEngine *qt_polygon_recursion = 0; diff --git a/src/gui/painting/qpaintengineex_p.h b/src/gui/painting/qpaintengineex_p.h index 593726c..1c55242 100644 --- a/src/gui/painting/qpaintengineex_p.h +++ b/src/gui/painting/qpaintengineex_p.h @@ -216,6 +216,8 @@ public: inline QPainterState *state() { return static_cast(QPaintEngine::state); } inline const QPainterState *state() const { return static_cast(QPaintEngine::state); } + virtual void sync() {} + virtual QPixmapFilter *createPixmapFilter(int /*type*/) const { return 0; } protected: diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index e7b6ee4..40f3a8d 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -449,6 +449,43 @@ void QGL2PaintEngineExPrivate::drawTexture(const QGLRect& dest, const QGLRect& s glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } +void QGL2PaintEngineEx::sync() +{ + Q_D(QGL2PaintEngineEx); + ensureActive(); + d->transferMode(BrushDrawingMode); + + QGLContext *ctx = d->ctx; + glUseProgram(0); + +#ifndef QT_OPENGL_ES_2 + // be nice to people who mix OpenGL 1.x code with QPainter commands + // by setting modelview and projection matrices to mirror the GL 1 + // paint engine + const QTransform& mtx = state()->matrix; + + float mv_matrix[4][4] = + { + { mtx.m11(), mtx.m12(), 0, mtx.m13() }, + { mtx.m21(), mtx.m22(), 0, mtx.m23() }, + { 0, 0, 1, 0 }, + { mtx.dx(), mtx.dy(), 0, mtx.m33() } + }; + + const QSize sz = d->drawable.size(); + + glMatrixMode(GL_PROJECTION); + glLoadIdentity(); + glOrtho(0, sz.width(), sz.height(), 0, -999999, 999999); + + glMatrixMode(GL_MODELVIEW); + glLoadMatrixf(&mv_matrix[0][0]); +#endif + + glDisable(GL_BLEND); + glActiveTexture(GL_TEXTURE0); +} + void QGL2PaintEngineExPrivate::transferMode(EngineMode newMode) { if (newMode == mode) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index dececa3..7213474 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -126,6 +126,7 @@ public: return static_cast(QPaintEngineEx::state()); } void updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op); + virtual void sync(); private: Q_DISABLE_COPY(QGL2PaintEngineEx) diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index b1a63b5..b3523d4 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -440,7 +440,7 @@ inline bool qt_gl_preferGL2Engine() return true; #else return (QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_0) - && !qgetenv("QT_GL_USE_OPENGL2ENGINE").isEmpty(); + && qgetenv("QT_GL_USE_OPENGL1ENGINE").isEmpty(); #endif } -- cgit v0.12 From cc10cda46329866e229eb7f190b1e0aeff09f76d Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Fri, 29 May 2009 16:29:19 +0200 Subject: Wrong default argument for my previous fix. Argh! This was a private function and I assumed that I had the boolean correct, but I was wrong. Anyway, we don't need to do the group fade be default ever, so always have it false. --- src/gui/widgets/qmenu_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/widgets/qmenu_p.h b/src/gui/widgets/qmenu_p.h index 9654126..f08283d 100644 --- a/src/gui/widgets/qmenu_p.h +++ b/src/gui/widgets/qmenu_p.h @@ -220,7 +220,7 @@ public: virtual QList > calcCausedStack() const; QMenuCaused causedPopup; void hideUpToMenuBar(); - void hideMenu(QMenu *menu, bool delay = true); + void hideMenu(QMenu *menu, bool justRegister = false); //index mappings inline QAction *actionAt(int i) const { return q_func()->actions().at(i); } -- cgit v0.12 From 3cb304990f81799e6811b699b6b6ad1c32ec1107 Mon Sep 17 00:00:00 2001 From: David Faure Date: Fri, 29 May 2009 16:36:15 +0200 Subject: Fix compilation with -pedantic --- src/corelib/animation/qabstractanimation.cpp | 2 +- src/corelib/animation/qpropertyanimation.cpp | 2 +- src/corelib/animation/qpropertyanimation.h | 2 +- src/corelib/io/qfilesystemwatcher_dnotify.cpp | 2 +- src/corelib/io/qnoncontiguousbytedevice.cpp | 36 +++++++++++++-------------- src/corelib/plugin/qfactoryloader.cpp | 2 +- src/corelib/tools/qlocale_p.h | 2 +- 7 files changed, 24 insertions(+), 24 deletions(-) diff --git a/src/corelib/animation/qabstractanimation.cpp b/src/corelib/animation/qabstractanimation.cpp index 16307e6..61d61df 100644 --- a/src/corelib/animation/qabstractanimation.cpp +++ b/src/corelib/animation/qabstractanimation.cpp @@ -159,7 +159,7 @@ QT_BEGIN_NAMESPACE -Q_GLOBAL_STATIC(QThreadStorage, unifiedTimer); +Q_GLOBAL_STATIC(QThreadStorage, unifiedTimer) QUnifiedTimer::QUnifiedTimer() : QObject(), lastTick(0), timingInterval(DEFAULT_TIMER_INTERVAL), consistentTiming(false) { diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp index 47361a5..43b5283 100644 --- a/src/corelib/animation/qpropertyanimation.cpp +++ b/src/corelib/animation/qpropertyanimation.cpp @@ -102,7 +102,7 @@ QT_BEGIN_NAMESPACE typedef QPair QPropertyAnimationPair; typedef QHash QPropertyAnimationHash; -Q_GLOBAL_STATIC(QPropertyAnimationHash, _q_runningAnimations); +Q_GLOBAL_STATIC(QPropertyAnimationHash, _q_runningAnimations) Q_GLOBAL_STATIC_WITH_ARGS(QMutex, guardHashLock, (QMutex::Recursive) ) void QPropertyAnimationPrivate::updateMetaProperty() diff --git a/src/corelib/animation/qpropertyanimation.h b/src/corelib/animation/qpropertyanimation.h index 39317ba..2fdd50c 100644 --- a/src/corelib/animation/qpropertyanimation.h +++ b/src/corelib/animation/qpropertyanimation.h @@ -76,7 +76,7 @@ protected: void updateState(QAbstractAnimation::State oldState, QAbstractAnimation::State newState); private: - Q_PRIVATE_SLOT(d_func(), void _q_targetDestroyed()); + Q_PRIVATE_SLOT(d_func(), void _q_targetDestroyed()) Q_DISABLE_COPY(QPropertyAnimation) Q_DECLARE_PRIVATE(QPropertyAnimation) }; diff --git a/src/corelib/io/qfilesystemwatcher_dnotify.cpp b/src/corelib/io/qfilesystemwatcher_dnotify.cpp index e87375a..a8397f8 100644 --- a/src/corelib/io/qfilesystemwatcher_dnotify.cpp +++ b/src/corelib/io/qfilesystemwatcher_dnotify.cpp @@ -114,7 +114,7 @@ private: bool isExecing; }; -Q_GLOBAL_STATIC(QDnotifySignalThread, dnotifySignal); +Q_GLOBAL_STATIC(QDnotifySignalThread, dnotifySignal) QDnotifySignalThread::QDnotifySignalThread() : isExecing(false) diff --git a/src/corelib/io/qnoncontiguousbytedevice.cpp b/src/corelib/io/qnoncontiguousbytedevice.cpp index f50acdb..1ff3a4c 100644 --- a/src/corelib/io/qnoncontiguousbytedevice.cpp +++ b/src/corelib/io/qnoncontiguousbytedevice.cpp @@ -143,11 +143,11 @@ QT_BEGIN_NAMESPACE QNonContiguousByteDevice::QNonContiguousByteDevice() : QObject((QObject*)0), resetDisabled(false) { -}; +} QNonContiguousByteDevice::~QNonContiguousByteDevice() { -}; +} void QNonContiguousByteDevice::disableReset() { @@ -253,7 +253,7 @@ QNonContiguousByteDeviceRingBufferImpl::QNonContiguousByteDeviceRingBufferImpl(Q QNonContiguousByteDeviceRingBufferImpl::~QNonContiguousByteDeviceRingBufferImpl() { -}; +} const char* QNonContiguousByteDeviceRingBufferImpl::readPointer(qint64 maximumLength, qint64 &len) { @@ -268,19 +268,19 @@ const char* QNonContiguousByteDeviceRingBufferImpl::readPointer(qint64 maximumLe len = qMin(len, maximumLength); return returnValue; -}; +} bool QNonContiguousByteDeviceRingBufferImpl::advanceReadPointer(qint64 amount) { currentPosition += amount; emit readProgress(currentPosition, size()); return true; -}; +} bool QNonContiguousByteDeviceRingBufferImpl::atEnd() { return currentPosition >= size(); -}; +} bool QNonContiguousByteDeviceRingBufferImpl::reset() { @@ -289,12 +289,12 @@ bool QNonContiguousByteDeviceRingBufferImpl::reset() currentPosition = 0; return true; -}; +} qint64 QNonContiguousByteDeviceRingBufferImpl::size() { return ringBuffer->size(); -}; +} QNonContiguousByteDeviceIoDeviceImpl::QNonContiguousByteDeviceIoDeviceImpl(QIODevice *d) : QNonContiguousByteDevice(), @@ -306,12 +306,12 @@ QNonContiguousByteDeviceIoDeviceImpl::QNonContiguousByteDeviceIoDeviceImpl(QIODe initialPosition = d->pos(); connect(device, SIGNAL(readyRead()), this, SIGNAL(readyRead()), Qt::QueuedConnection); connect(device, SIGNAL(readChannelFinished()), this, SIGNAL(readyRead()), Qt::QueuedConnection); -}; +} QNonContiguousByteDeviceIoDeviceImpl::~QNonContiguousByteDeviceIoDeviceImpl() { delete currentReadBuffer; -}; +} const char* QNonContiguousByteDeviceIoDeviceImpl::readPointer(qint64 maximumLength, qint64 &len) { @@ -347,7 +347,7 @@ const char* QNonContiguousByteDeviceIoDeviceImpl::readPointer(qint64 maximumLeng len = haveRead; return currentReadBuffer->data(); -}; +} bool QNonContiguousByteDeviceIoDeviceImpl::advanceReadPointer(qint64 amount) { @@ -377,12 +377,12 @@ bool QNonContiguousByteDeviceIoDeviceImpl::advanceReadPointer(qint64 amount) emit readProgress(totalAdvancements, size()); return true; -}; +} bool QNonContiguousByteDeviceIoDeviceImpl::atEnd() { return eof == true; -}; +} bool QNonContiguousByteDeviceIoDeviceImpl::reset() { @@ -395,7 +395,7 @@ bool QNonContiguousByteDeviceIoDeviceImpl::reset() } return false; -}; +} qint64 QNonContiguousByteDeviceIoDeviceImpl::size() { @@ -405,7 +405,7 @@ qint64 QNonContiguousByteDeviceIoDeviceImpl::size() return -1; return device->size() - initialPosition; -}; +} QByteDeviceWrappingIoDevice::QByteDeviceWrappingIoDevice(QNonContiguousByteDevice *bd) : QIODevice((QObject*)0) { @@ -497,7 +497,7 @@ QNonContiguousByteDevice* QNonContiguousByteDeviceFactory::create(QIODevice *dev // generic QIODevice return new QNonContiguousByteDeviceIoDeviceImpl(device); // FIXME -}; +} /*! \fn static QNonContiguousByteDevice* QNonContiguousByteDeviceFactory::create(QRingBuffer *ringBuffer); @@ -509,7 +509,7 @@ QNonContiguousByteDevice* QNonContiguousByteDeviceFactory::create(QIODevice *dev QNonContiguousByteDevice* QNonContiguousByteDeviceFactory::create(QRingBuffer *ringBuffer) { return new QNonContiguousByteDeviceRingBufferImpl(ringBuffer); -}; +} /*! \fn static QNonContiguousByteDevice* QNonContiguousByteDeviceFactory::create(QByteArray *byteArray); @@ -521,7 +521,7 @@ QNonContiguousByteDevice* QNonContiguousByteDeviceFactory::create(QRingBuffer *r QNonContiguousByteDevice* QNonContiguousByteDeviceFactory::create(QByteArray *byteArray) { return new QNonContiguousByteDeviceByteArrayImpl(byteArray); -}; +} /*! \fn static QIODevice* QNonContiguousByteDeviceFactory::wrap(QNonContiguousByteDevice* byteDevice); diff --git a/src/corelib/plugin/qfactoryloader.cpp b/src/corelib/plugin/qfactoryloader.cpp index 5163027..4740bf1 100644 --- a/src/corelib/plugin/qfactoryloader.cpp +++ b/src/corelib/plugin/qfactoryloader.cpp @@ -55,7 +55,7 @@ QT_BEGIN_NAMESPACE -Q_GLOBAL_STATIC(QList, qt_factory_loaders); +Q_GLOBAL_STATIC(QList, qt_factory_loaders) Q_GLOBAL_STATIC_WITH_ARGS(QMutex, qt_factoryloader_mutex, (QMutex::Recursive)) diff --git a/src/corelib/tools/qlocale_p.h b/src/corelib/tools/qlocale_p.h index 9d36a83..b07b948 100644 --- a/src/corelib/tools/qlocale_p.h +++ b/src/corelib/tools/qlocale_p.h @@ -96,7 +96,7 @@ public: ShowBase = 0x80, UppercaseBase = 0x100, - ForcePoint = Alternate, + ForcePoint = Alternate }; enum GroupSeparatorMode { -- cgit v0.12 From 5f1ec2a20d13b9ca9bae1b7b40692925dcd99051 Mon Sep 17 00:00:00 2001 From: Anders Bakken Date: Fri, 29 May 2009 11:17:11 -0700 Subject: Don't support porter duff |= source over DirectFB and Qt treats these things rather differently so the mapping just doesn't work very well. Only use DirectFB for SourceOver stuff (which is the default mode anyway) Reviewed-by: Donald --- .../gfxdrivers/directfb/qdirectfbpaintengine.cpp | 120 +++++---------------- 1 file changed, 24 insertions(+), 96 deletions(-) diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp b/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp index 7535090..2fb533a 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp +++ b/src/plugins/gfxdrivers/directfb/qdirectfbpaintengine.cpp @@ -215,8 +215,8 @@ public: void setTransform(const QTransform &m); void setPen(const QPen &pen); - void setCompositionMode(QPainter::CompositionMode mode); - void setOpacity(quint8 value); + inline void setCompositionMode(QPainter::CompositionMode mode); + inline void setOpacity(quint8 value); void setRenderHints(QPainter::RenderHints hints); inline void setDFBColor(const QColor &color); @@ -276,14 +276,12 @@ private: quint8 opacity; - quint32 drawFlagsFromCompositionMode, blitFlagsFromCompositionMode; - DFBSurfacePorterDuffRule porterDuffRule; - bool dirtyClip; bool dfbHandledClip; bool ignoreSystemClip; QDirectFBPaintDevice *dfbDevice; void *lockedMemory; + bool unsupportedCompositionMode; QDirectFBPaintEngine *q; friend class QDirectFBPaintEngine; @@ -403,7 +401,7 @@ void QDirectFBPaintEngine::drawRects(const QRect *rects, int rectCount) Q_D(QDirectFBPaintEngine); d->updateClip(); const QBrush &brush = state()->brush; - if (!d->dfbCanHandleClip() || d->matrixRotShear + if (d->unsupportedCompositionMode || !d->dfbCanHandleClip() || d->matrixRotShear || !d->simplePen || !d->isSimpleBrush(brush)) { RASTERFALLBACK(DRAW_RECTS, rectCount, VOID_ARG(), VOID_ARG()); d->lock(); @@ -428,7 +426,7 @@ void QDirectFBPaintEngine::drawRects(const QRectF *rects, int rectCount) Q_D(QDirectFBPaintEngine); d->updateClip(); const QBrush &brush = state()->brush; - if (!d->dfbCanHandleClip() || d->matrixRotShear + if (d->unsupportedCompositionMode || !d->dfbCanHandleClip() || d->matrixRotShear || !d->simplePen || !d->isSimpleBrush(brush)) { RASTERFALLBACK(DRAW_RECTS, rectCount, VOID_ARG(), VOID_ARG()); d->lock(); @@ -452,7 +450,7 @@ void QDirectFBPaintEngine::drawLines(const QLine *lines, int lineCount) { Q_D(QDirectFBPaintEngine); d->updateClip(); - if (!d->simplePen || !d->dfbCanHandleClip()) { + if (d->unsupportedCompositionMode || !d->simplePen || !d->dfbCanHandleClip()) { RASTERFALLBACK(DRAW_LINES, lineCount, VOID_ARG(), VOID_ARG()); d->lock(); QRasterPaintEngine::drawLines(lines, lineCount); @@ -470,7 +468,7 @@ void QDirectFBPaintEngine::drawLines(const QLineF *lines, int lineCount) { Q_D(QDirectFBPaintEngine); d->updateClip(); - if (!d->simplePen || !d->dfbCanHandleClip()) { + if (d->unsupportedCompositionMode || !d->simplePen || !d->dfbCanHandleClip()) { RASTERFALLBACK(DRAW_LINES, lineCount, VOID_ARG(), VOID_ARG()); d->lock(); QRasterPaintEngine::drawLines(lines, lineCount); @@ -510,7 +508,8 @@ void QDirectFBPaintEngine::drawImage(const QRectF &r, const QImage &image, d->updateClip(); #if !defined QT_NO_DIRECTFB_PREALLOCATED || defined QT_DIRECTFB_IMAGECACHE - if (d->matrixRotShear + if (d->unsupportedCompositionMode + || d->matrixRotShear || d->scale == QDirectFBPaintEnginePrivate::NegativeScale || !d->dfbCanHandleClip(r) #ifndef QT_DIRECTFB_IMAGECACHE @@ -554,7 +553,7 @@ void QDirectFBPaintEngine::drawPixmap(const QRectF &r, const QPixmap &pixmap, RASTERFALLBACK(DRAW_PIXMAP, r, pixmap.size(), sr); d->lock(); QRasterPaintEngine::drawPixmap(r, pixmap, sr); - } else if (!d->dfbCanHandleClip(r) || d->matrixRotShear + } else if (d->unsupportedCompositionMode || !d->dfbCanHandleClip(r) || d->matrixRotShear || d->scale == QDirectFBPaintEnginePrivate::NegativeScale) { RASTERFALLBACK(DRAW_PIXMAP, r, pixmap.size(), sr); const QImage *img = static_cast(pixmap.pixmapData())->buffer(DSLF_READ); @@ -586,7 +585,7 @@ void QDirectFBPaintEngine::drawTiledPixmap(const QRectF &r, RASTERFALLBACK(DRAW_TILED_PIXMAP, r, pixmap.size(), sp); d->lock(); QRasterPaintEngine::drawTiledPixmap(r, pixmap, sp); - } else if (!d->dfbCanHandleClip(r) || d->matrixRotShear || !sp.isNull() + } else if (d->unsupportedCompositionMode || !d->dfbCanHandleClip(r) || d->matrixRotShear || !sp.isNull() || d->scale == QDirectFBPaintEnginePrivate::NegativeScale) { RASTERFALLBACK(DRAW_TILED_PIXMAP, r, pixmap.size(), sp); const QImage *img = static_cast(pixmap.pixmapData())->buffer(DSLF_READ); @@ -682,7 +681,7 @@ void QDirectFBPaintEngine::fillRect(const QRectF &rect, const QBrush &brush) { Q_D(QDirectFBPaintEngine); d->updateClip(); - if (d->dfbCanHandleClip(rect) && !d->matrixRotShear) { + if (!d->unsupportedCompositionMode && d->dfbCanHandleClip(rect) && !d->matrixRotShear) { switch (brush.style()) { case Qt::SolidPattern: { d->unlock(); @@ -712,7 +711,7 @@ void QDirectFBPaintEngine::fillRect(const QRectF &rect, const QColor &color) { Q_D(QDirectFBPaintEngine); d->updateClip(); - if (!d->dfbCanHandleClip() || d->matrixRotShear) { + if (d->unsupportedCompositionMode || !d->dfbCanHandleClip() || d->matrixRotShear) { RASTERFALLBACK(FILL_RECT, rect, color, VOID_ARG()); d->lock(); QRasterPaintEngine::fillRect(rect, color); @@ -791,9 +790,9 @@ void QDirectFBPaintEngine::initImageCache(int size) QDirectFBPaintEnginePrivate::QDirectFBPaintEnginePrivate(QDirectFBPaintEngine *p) : surface(0), antialiased(false), simplePen(false), matrixRotShear(false), scale(NoScale), lastLockedHeight(-1), - fbWidth(-1), fbHeight(-1), opacity(255), drawFlagsFromCompositionMode(0), - blitFlagsFromCompositionMode(0), porterDuffRule(DSPD_SRC_OVER), dirtyClip(true), - dfbHandledClip(false), dfbDevice(0), lockedMemory(0), q(p) + fbWidth(-1), fbHeight(-1), opacity(255), dirtyClip(true), + dfbHandledClip(false), dfbDevice(0), lockedMemory(0), + unsupportedCompositionMode(false), q(p) { fb = QDirectFBScreen::instance()->dfb(); ignoreSystemClip = QDirectFBScreen::instance()->directFBFlags() & QDirectFBScreen::IgnoreSystemClip; @@ -887,7 +886,7 @@ void QDirectFBPaintEnginePrivate::begin(QPaintDevice *device) setTransform(QTransform()); antialiased = false; - opacity = 255; + setOpacity(255); setCompositionMode(q->state()->compositionMode()); dirtyClip = true; setPen(q->state()->pen); @@ -915,72 +914,13 @@ void QDirectFBPaintEnginePrivate::setPen(const QPen &p) void QDirectFBPaintEnginePrivate::setCompositionMode(QPainter::CompositionMode mode) { - blitFlagsFromCompositionMode = DSBLIT_NOFX; - drawFlagsFromCompositionMode = DSDRAW_NOFX; - - bool blend = true; - switch (mode) { - case QPainter::CompositionMode_SourceOver: - porterDuffRule = DSPD_SRC_OVER; - break; - case QPainter::CompositionMode_DestinationOver: - porterDuffRule = DSPD_DST_OVER; - break; - case QPainter::CompositionMode_Clear: - porterDuffRule = DSPD_CLEAR; - blend = false; - break; - case QPainter::CompositionMode_Source: - porterDuffRule = DSPD_SRC; - blend = false; - break; - case QPainter::CompositionMode_Destination: - porterDuffRule = DSPD_NONE; // ### need to double check this - blend = false; - return; - case QPainter::CompositionMode_SourceIn: - porterDuffRule = DSPD_SRC_IN; - break; - case QPainter::CompositionMode_DestinationIn: - porterDuffRule = DSPD_DST_IN; - break; - case QPainter::CompositionMode_SourceOut: - porterDuffRule = DSPD_SRC_OUT; - break; - case QPainter::CompositionMode_DestinationOut: - porterDuffRule = DSPD_DST_OUT; - break; - case QPainter::CompositionMode_Xor: - porterDuffRule = DSPD_XOR; - blitFlagsFromCompositionMode |= DSBLIT_XOR; - drawFlagsFromCompositionMode |= DSDRAW_XOR; - break; -// case QPainter::CompositionMode_Plus: // ??? -// porterDuffRule = DSPD_ADD; -// break; - default: - qWarning("QDirectFBPaintEnginePrivate::setCompositionMode(): " - "mode %d not implemented", mode); - return; - } - // intentially not comparing with current porterDuffRule. surface might have changed. - if (blend) { - blitFlagsFromCompositionMode |= DSBLIT_BLEND_ALPHACHANNEL; - drawFlagsFromCompositionMode |= DSDRAW_BLEND; - } - if (opacity != 255) { - setOpacity(opacity); - } + unsupportedCompositionMode = (mode != QPainter::CompositionMode_SourceOver); } + void QDirectFBPaintEnginePrivate::setOpacity(quint8 op) { opacity = op; - if (opacity == 255) { - blitFlagsFromCompositionMode &= ~DSBLIT_BLEND_COLORALPHA; - } else { - blitFlagsFromCompositionMode |= DSBLIT_BLEND_COLORALPHA; - } } void QDirectFBPaintEnginePrivate::setRenderHints(QPainter::RenderHints hints) @@ -994,15 +934,9 @@ void QDirectFBPaintEnginePrivate::setRenderHints(QPainter::RenderHints hints) void QDirectFBPaintEnginePrivate::prepareForBlit(bool alpha) { - quint32 blittingFlags = blitFlagsFromCompositionMode; - if (alpha) { - surface->SetPorterDuff(surface, - (blittingFlags & DSBLIT_BLEND_COLORALPHA) - ? DSPD_NONE - : porterDuffRule); - } else { - blittingFlags &= ~DSBLIT_BLEND_ALPHACHANNEL; - surface->SetPorterDuff(surface, DSPD_NONE); + quint32 blittingFlags = alpha ? DSBLIT_BLEND_ALPHACHANNEL : DSBLIT_NOFX; + if (opacity != 255) { + blittingFlags |= DSBLIT_BLEND_COLORALPHA; } surface->SetColor(surface, 0xff, 0xff, 0xff, opacity); surface->SetBlittingFlags(surface, DFBSurfaceBlittingFlags(blittingFlags)); @@ -1013,15 +947,9 @@ void QDirectFBPaintEnginePrivate::setDFBColor(const QColor &color) Q_ASSERT(surface); const quint8 alpha = (opacity == 255 ? color.alpha() : ALPHA_MUL(color.alpha(), opacity)); - surface->SetColor(surface, - color.red(), color.green(), color.blue(), alpha); - quint32 drawingFlags = drawFlagsFromCompositionMode; - if (alpha == 255) { - drawingFlags &= ~DSDRAW_BLEND; - } + surface->SetColor(surface, color.red(), color.green(), color.blue(), alpha); surface->SetPorterDuff(surface, DSPD_NONE); - // PorterDuff messes up alpha values for primitives - surface->SetDrawingFlags(surface, DFBSurfaceDrawingFlags(drawingFlags)); + surface->SetDrawingFlags(surface, alpha == 255 ? DSDRAW_NOFX : DSDRAW_BLEND); } void QDirectFBPaintEnginePrivate::drawLines(const QLine *lines, int n) -- cgit v0.12 From d8ccdc88128999febfa7cc0c9d49f8a9ae8cc118 Mon Sep 17 00:00:00 2001 From: "Thiago Marcos P. Santos" Date: Fri, 29 May 2009 18:42:51 -0400 Subject: Fixed sub-attaq example build --- examples/animation/sub-attaq/mainwindow.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/animation/sub-attaq/mainwindow.cpp b/examples/animation/sub-attaq/mainwindow.cpp index 5e8e259..123363b 100644 --- a/examples/animation/sub-attaq/mainwindow.cpp +++ b/examples/animation/sub-attaq/mainwindow.cpp @@ -44,6 +44,8 @@ #include "graphicsscene.h" //Qt +#include + #ifdef QT_NO_OPENGL #include #include -- cgit v0.12 From e4ea96a48bd6d4c8b96859fc0364a5d9c7c686d6 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Mon, 1 Jun 2009 09:48:13 +1000 Subject: Check if the text has really changed before emitting the textChanged signal. --- src/declarative/fx/qfxtextedit.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/declarative/fx/qfxtextedit.cpp b/src/declarative/fx/qfxtextedit.cpp index fc73ecd..1c70abf 100644 --- a/src/declarative/fx/qfxtextedit.cpp +++ b/src/declarative/fx/qfxtextedit.cpp @@ -158,6 +158,8 @@ QString QFxTextEdit::text() const void QFxTextEdit::setText(const QString &text) { Q_D(QFxTextEdit); + if (QFxTextEdit::text() == text) + return; d->text = text; d->richText = d->format == RichText || (d->format == AutoText && Qt::mightBeRichText(text)); if (d->richText) { -- cgit v0.12 From 54d9a58cf15e72f24cbf74281996835458bd6e23 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Mon, 1 Jun 2009 11:12:38 +1000 Subject: Remove some pointless perf metrics --- src/declarative/fx/qfxpath.cpp | 2 +- src/declarative/qml/qmlcompiler.cpp | 2 +- src/declarative/qml/qmlcomponent.cpp | 3 --- src/declarative/qml/qmlengine.cpp | 18 ------------------ src/declarative/qml/qmlmetaproperty.cpp | 4 ---- src/declarative/qml/qmlvme.cpp | 2 +- src/declarative/util/qfxperf.cpp | 30 +++++++++++------------------- src/declarative/util/qfxperf.h | 18 ++++++------------ 8 files changed, 20 insertions(+), 59 deletions(-) diff --git a/src/declarative/fx/qfxpath.cpp b/src/declarative/fx/qfxpath.cpp index 5deaaa5..be731b1 100644 --- a/src/declarative/fx/qfxpath.cpp +++ b/src/declarative/fx/qfxpath.cpp @@ -357,7 +357,7 @@ void QFxPath::createPointCache() const { Q_D(const QFxPath); #ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer pc; + QFxPerfTimer pc; #endif qreal pathLength = d->_path.length(); const int points = int(pathLength*2); diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 3029934..46695b7 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -470,7 +470,7 @@ bool QmlCompiler::compile(QmlEngine *engine, QmlCompiledComponent *out) { #ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer pc; + QFxPerfTimer pc; #endif exceptions.clear(); diff --git a/src/declarative/qml/qmlcomponent.cpp b/src/declarative/qml/qmlcomponent.cpp index 24b5dd2..78137e8 100644 --- a/src/declarative/qml/qmlcomponent.cpp +++ b/src/declarative/qml/qmlcomponent.cpp @@ -458,9 +458,6 @@ QObject *QmlComponent::beginCreate(QmlContext *context) return 0; } -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif if (!d->engine->d_func()->rootComponent) d->engine->d_func()->rootComponent = this; diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index c67c220..18f28ed 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -1275,9 +1275,6 @@ QmlContextScriptClass::queryProperty(const QScriptValue &object, QueryFlags flags, uint *id) { Q_UNUSED(flags); -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif QmlContext *bindContext = static_cast(object.data().toQObject()); QueryFlags rv = 0; @@ -1308,9 +1305,6 @@ QScriptValue QmlContextScriptClass::property(const QScriptValue &object, const QScriptString &name, uint id) { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif QmlContext *bindContext = static_cast(object.data().toQObject()); @@ -1369,9 +1363,6 @@ void QmlContextScriptClass::setProperty(QScriptValue &object, { Q_UNUSED(name); -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif QmlContext *bindContext = static_cast(object.data().toQObject()); @@ -1422,9 +1413,6 @@ QScriptClass::QueryFlags QmlObjectScriptClass::queryProperty(const QScriptValue QueryFlags flags, uint *id) { Q_UNUSED(flags); -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif QObject *obj = object.data().toQObject(); QueryFlags rv = 0; QString propName = name.toString(); @@ -1443,9 +1431,6 @@ QScriptValue QmlObjectScriptClass::property(const QScriptValue &object, const QScriptString &name, uint id) { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif QObject *obj = object.data().toQObject(); #ifdef PROPERTY_DEBUG @@ -1472,9 +1457,6 @@ void QmlObjectScriptClass::setProperty(QScriptValue &object, { Q_UNUSED(name); -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif QObject *obj = object.data().toQObject(); #ifdef PROPERTY_DEBUG diff --git a/src/declarative/qml/qmlmetaproperty.cpp b/src/declarative/qml/qmlmetaproperty.cpp index 3aa4f1d..4f39ebc 100644 --- a/src/declarative/qml/qmlmetaproperty.cpp +++ b/src/declarative/qml/qmlmetaproperty.cpp @@ -196,10 +196,6 @@ QmlMetaProperty::QmlMetaProperty(QObject *obj, const QString &name) QmlMetaProperty::QmlMetaProperty(QObject *obj, const QString &name, QmlContext *ctxt) : d(new QmlMetaPropertyPrivate) { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer perf; -#endif - d->context = ctxt; initProperty(obj, name); } diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index e68afcc..c85524f 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -201,7 +201,7 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in #ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer cr; + QFxPerfTimer cr; #endif QmlEnginePrivate::SimpleList bindValues; QmlEnginePrivate::SimpleList parserStatus; diff --git a/src/declarative/util/qfxperf.cpp b/src/declarative/util/qfxperf.cpp index 01ac878..3da52d8 100644 --- a/src/declarative/util/qfxperf.cpp +++ b/src/declarative/util/qfxperf.cpp @@ -44,32 +44,24 @@ QT_BEGIN_NAMESPACE Q_DEFINE_PERFORMANCE_LOG(QFxPerf, "QFx") { - Q_DEFINE_PERFORMANCE_METRIC(QmlParsing, "QML Parsing"); - Q_DEFINE_PERFORMANCE_METRIC(Compile, "QML Compilation"); - Q_DEFINE_PERFORMANCE_METRIC(CompileRun, "QML Compilation Run"); - Q_DEFINE_PERFORMANCE_METRIC(CreateComponent, "Component creation"); + Q_DEFINE_PERFORMANCE_METRIC(QmlParsing, "Compilation: QML Parsing"); + Q_DEFINE_PERFORMANCE_METRIC(Compilation, " QML Compilation"); + Q_DEFINE_PERFORMANCE_METRIC(VMEExecution, "Execution: QML VME Execution"); Q_DEFINE_PERFORMANCE_METRIC(BindInit, "BindValue Initialization"); - Q_DEFINE_PERFORMANCE_METRIC(BindCompile, "BindValue compile"); Q_DEFINE_PERFORMANCE_METRIC(BindValue, "BindValue execution"); Q_DEFINE_PERFORMANCE_METRIC(BindValueSSE, "BindValue execution SSE"); Q_DEFINE_PERFORMANCE_METRIC(BindValueQt, "BindValue execution QtScript"); - Q_DEFINE_PERFORMANCE_METRIC(ContextQuery, "QtScript: Query Context"); - Q_DEFINE_PERFORMANCE_METRIC(ContextProperty, "QtScript: Context Property"); - Q_DEFINE_PERFORMANCE_METRIC(ObjectQuery, "QtScript: Query Object"); - Q_DEFINE_PERFORMANCE_METRIC(ObjectProperty, "QtScript: Object Property"); - Q_DEFINE_PERFORMANCE_METRIC(ObjectSetProperty, "QtScript: Set Object Property"); Q_DEFINE_PERFORMANCE_METRIC(BindableValueUpdate, "QmlBindableValue::update"); Q_DEFINE_PERFORMANCE_METRIC(PixmapLoad, "Pixmap loading"); - Q_DEFINE_PERFORMANCE_METRIC(MetaProperty, "Meta property resolution"); - Q_DEFINE_PERFORMANCE_METRIC(PathCache, "Path cache"); - Q_DEFINE_PERFORMANCE_METRIC(CreateParticle, "Particle creation"); Q_DEFINE_PERFORMANCE_METRIC(FontDatabase, "Font database creation"); - Q_DEFINE_PERFORMANCE_METRIC(ItemComponentComplete, "QFxItem::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(ImageComponentComplete, "QFxImage::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(ComponentInstanceComponentComplete, "QFxComponentInstance::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(BaseLayoutComponentComplete, "QFxBaseLayout::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(TextComponentComplete, "QFxText::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(QFxText_setText, "QFxText::setText"); + Q_DEFINE_PERFORMANCE_METRIC(QFxPathViewPathCache, "FX Items: QFxPathView: Path cache"); + Q_DEFINE_PERFORMANCE_METRIC(CreateParticle, " QFxParticles: Particle creation"); + Q_DEFINE_PERFORMANCE_METRIC(ItemComponentComplete, " QFxItem::componentComplete"); + Q_DEFINE_PERFORMANCE_METRIC(ImageComponentComplete, " QFxImage::componentComplete"); + Q_DEFINE_PERFORMANCE_METRIC(ComponentInstanceComponentComplete, " QFxComponentInstance::componentComplete"); + Q_DEFINE_PERFORMANCE_METRIC(BaseLayoutComponentComplete, " QFxBaseLayout::componentComplete"); + Q_DEFINE_PERFORMANCE_METRIC(TextComponentComplete, " QFxText::componentComplete"); + Q_DEFINE_PERFORMANCE_METRIC(QFxText_setText, " QFxText::setText"); Q_DEFINE_PERFORMANCE_METRIC(AddScript, "QmlScript::addScriptToEngine"); } QT_END_NAMESPACE diff --git a/src/declarative/util/qfxperf.h b/src/declarative/util/qfxperf.h index 23de8b5..9fcf1d6 100644 --- a/src/declarative/util/qfxperf.h +++ b/src/declarative/util/qfxperf.h @@ -51,25 +51,19 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) Q_DECLARE_PERFORMANCE_LOG(QFxPerf) { Q_DECLARE_PERFORMANCE_METRIC(QmlParsing) - Q_DECLARE_PERFORMANCE_METRIC(Compile) - Q_DECLARE_PERFORMANCE_METRIC(CompileRun) - Q_DECLARE_PERFORMANCE_METRIC(CreateComponent) + + Q_DECLARE_PERFORMANCE_METRIC(Compilation) + Q_DECLARE_PERFORMANCE_METRIC(VMEExecution) + Q_DECLARE_PERFORMANCE_METRIC(BindInit) - Q_DECLARE_PERFORMANCE_METRIC(BindCompile) Q_DECLARE_PERFORMANCE_METRIC(BindValue) Q_DECLARE_PERFORMANCE_METRIC(BindValueSSE) Q_DECLARE_PERFORMANCE_METRIC(BindValueQt) - Q_DECLARE_PERFORMANCE_METRIC(ContextQuery) - Q_DECLARE_PERFORMANCE_METRIC(ContextProperty) - Q_DECLARE_PERFORMANCE_METRIC(ObjectQuery) - Q_DECLARE_PERFORMANCE_METRIC(ObjectProperty) - Q_DECLARE_PERFORMANCE_METRIC(ObjectSetProperty) Q_DECLARE_PERFORMANCE_METRIC(BindableValueUpdate) Q_DECLARE_PERFORMANCE_METRIC(PixmapLoad) - Q_DECLARE_PERFORMANCE_METRIC(MetaProperty) - Q_DECLARE_PERFORMANCE_METRIC(PathCache) - Q_DECLARE_PERFORMANCE_METRIC(CreateParticle) Q_DECLARE_PERFORMANCE_METRIC(FontDatabase) + Q_DECLARE_PERFORMANCE_METRIC(QFxPathViewPathCache) + Q_DECLARE_PERFORMANCE_METRIC(CreateParticle) Q_DECLARE_PERFORMANCE_METRIC(ItemComponentComplete) Q_DECLARE_PERFORMANCE_METRIC(ImageComponentComplete) Q_DECLARE_PERFORMANCE_METRIC(ComponentInstanceComponentComplete) -- cgit v0.12 From 48837f952dfb210fe9877f484dd9f922fc86fa07 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Mon, 1 Jun 2009 12:33:06 +1000 Subject: Reserved a UID for QtDeclarative library on S60 --- src/declarative/declarative.pro | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/declarative/declarative.pro b/src/declarative/declarative.pro index 0c51fc3..382f3cb 100644 --- a/src/declarative/declarative.pro +++ b/src/declarative/declarative.pro @@ -27,3 +27,5 @@ include(test/test.pri) include(debugger/debugger.pri) contains(QT_CONFIG, opengles2)|contains(QT_CONFIG, opengles1):include(opengl/opengl.pri) + +symbian:TARGET.UID3=0x2001E623 -- cgit v0.12 From 6e8bafefb9d8484c2fcd0b26c02d1af0e74e25e1 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Mon, 1 Jun 2009 12:51:32 +1000 Subject: prepend private/ for included private headers --- src/corelib/animation/qanimationgroup_p.h | 2 +- src/corelib/animation/qparallelanimationgroup_p.h | 2 +- src/corelib/animation/qpropertyanimation_p.h | 2 +- src/corelib/animation/qsequentialanimationgroup_p.h | 2 +- src/corelib/animation/qvariantanimation_p.h | 2 +- src/corelib/statemachine/qeventtransition_p.h | 2 +- src/corelib/statemachine/qhistorystate_p.h | 2 +- src/corelib/statemachine/qsignaltransition_p.h | 2 +- src/corelib/statemachine/qstate_p.h | 2 +- src/corelib/statemachine/qstatemachine_p.h | 2 +- 10 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/corelib/animation/qanimationgroup_p.h b/src/corelib/animation/qanimationgroup_p.h index a7bd0fa..0f07138 100644 --- a/src/corelib/animation/qanimationgroup_p.h +++ b/src/corelib/animation/qanimationgroup_p.h @@ -57,7 +57,7 @@ #include -#include "qabstractanimation_p.h" +#include "private/qabstractanimation_p.h" QT_BEGIN_NAMESPACE diff --git a/src/corelib/animation/qparallelanimationgroup_p.h b/src/corelib/animation/qparallelanimationgroup_p.h index f36d972..ecd6791 100644 --- a/src/corelib/animation/qparallelanimationgroup_p.h +++ b/src/corelib/animation/qparallelanimationgroup_p.h @@ -54,7 +54,7 @@ // #include "qparallelanimationgroup.h" -#include "qanimationgroup_p.h" +#include "private/qanimationgroup_p.h" #include QT_BEGIN_NAMESPACE diff --git a/src/corelib/animation/qpropertyanimation_p.h b/src/corelib/animation/qpropertyanimation_p.h index a4387dd..16c63ab 100644 --- a/src/corelib/animation/qpropertyanimation_p.h +++ b/src/corelib/animation/qpropertyanimation_p.h @@ -56,7 +56,7 @@ #include "qpropertyanimation.h" #include -#include "qvariantanimation_p.h" +#include "private/qvariantanimation_p.h" QT_BEGIN_NAMESPACE diff --git a/src/corelib/animation/qsequentialanimationgroup_p.h b/src/corelib/animation/qsequentialanimationgroup_p.h index 3ac90f8..c01aaf0 100644 --- a/src/corelib/animation/qsequentialanimationgroup_p.h +++ b/src/corelib/animation/qsequentialanimationgroup_p.h @@ -54,7 +54,7 @@ // #include "qsequentialanimationgroup.h" -#include "qanimationgroup_p.h" +#include "private/qanimationgroup_p.h" QT_BEGIN_NAMESPACE diff --git a/src/corelib/animation/qvariantanimation_p.h b/src/corelib/animation/qvariantanimation_p.h index aee2324..3ae0e39 100644 --- a/src/corelib/animation/qvariantanimation_p.h +++ b/src/corelib/animation/qvariantanimation_p.h @@ -58,7 +58,7 @@ #include #include -#include "qabstractanimation_p.h" +#include "private/qabstractanimation_p.h" QT_BEGIN_NAMESPACE diff --git a/src/corelib/statemachine/qeventtransition_p.h b/src/corelib/statemachine/qeventtransition_p.h index 600cec0..ab17ad3 100644 --- a/src/corelib/statemachine/qeventtransition_p.h +++ b/src/corelib/statemachine/qeventtransition_p.h @@ -53,7 +53,7 @@ // We mean it. // -#include "qabstracttransition_p.h" +#include "private/qabstracttransition_p.h" QT_BEGIN_NAMESPACE diff --git a/src/corelib/statemachine/qhistorystate_p.h b/src/corelib/statemachine/qhistorystate_p.h index 5aaa64c..875dac8 100644 --- a/src/corelib/statemachine/qhistorystate_p.h +++ b/src/corelib/statemachine/qhistorystate_p.h @@ -53,7 +53,7 @@ // We mean it. // -#include "qabstractstate_p.h" +#include "private/qabstractstate_p.h" #include diff --git a/src/corelib/statemachine/qsignaltransition_p.h b/src/corelib/statemachine/qsignaltransition_p.h index 339de63..aacb6fc 100644 --- a/src/corelib/statemachine/qsignaltransition_p.h +++ b/src/corelib/statemachine/qsignaltransition_p.h @@ -53,7 +53,7 @@ // We mean it. // -#include "qabstracttransition_p.h" +#include "private/qabstracttransition_p.h" QT_BEGIN_NAMESPACE diff --git a/src/corelib/statemachine/qstate_p.h b/src/corelib/statemachine/qstate_p.h index 93744b9..eddd831 100644 --- a/src/corelib/statemachine/qstate_p.h +++ b/src/corelib/statemachine/qstate_p.h @@ -53,7 +53,7 @@ // We mean it. // -#include "qabstractstate_p.h" +#include "private/qabstractstate_p.h" #include #include diff --git a/src/corelib/statemachine/qstatemachine_p.h b/src/corelib/statemachine/qstatemachine_p.h index 54953b4..24073ca 100644 --- a/src/corelib/statemachine/qstatemachine_p.h +++ b/src/corelib/statemachine/qstatemachine_p.h @@ -62,7 +62,7 @@ #include #include "qstate.h" -#include "qstate_p.h" +#include "private/qstate_p.h" QT_BEGIN_NAMESPACE -- cgit v0.12 From 049619000c031964cf33ef351d3df619a6815f5e Mon Sep 17 00:00:00 2001 From: Rohan McGovern Date: Mon, 1 Jun 2009 13:08:32 +1000 Subject: Fixed failure of tst_Selftests::checkXML. Cherry-pick of 548da9a5434d615456a7a6efda3380b7138c6000 and some earlier changes predating public repo. Note that this test is not failing if using Qt 4.5 only. However, it fails if using Qt 4.5 selftests against Qt master testlib. We want to be able to use master testlib to run 4.5 testcases, and this change does no harm when using Qt 4.5 testlib, so backport it to 4.5 for convenience. Original change description follows: A few tests use printf, which means they interfere with the XML test logging. Blacklist them for the XML test. Note that these tests happened to pass under the old test logger implementation. That was because the test logger always printed XML tags on a single line, and the printf calls contained no special XML characters. The test logs generated were technically valid XML but contained extraneous text. --- tests/auto/selftests/expected_skip.txt | 2 +- tests/auto/selftests/skip/tst_skip.cpp | 6 +++--- tests/auto/selftests/tst_selftests.cpp | 5 +++++ 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/auto/selftests/expected_skip.txt b/tests/auto/selftests/expected_skip.txt index ba41e67..f3be5b5 100644 --- a/tests/auto/selftests/expected_skip.txt +++ b/tests/auto/selftests/expected_skip.txt @@ -7,7 +7,7 @@ SKIP : tst_Skip::emptytest() skipping all Loc: [/home/fenglich/dev/qt-4.3/tests/auto/selftests/skip/tst_skip.cpp(45)] SKIP : tst_Skip::singleSkip(local 1) skipping one Loc: [/home/fenglich/dev/qt-4.3/tests/auto/selftests/skip/tst_skip.cpp(64)] -this line should only be reached once (true) +QDEBUG : tst_Skip::singleSkip(local 2) this line should only be reached once (true) PASS : tst_Skip::singleSkip() PASS : tst_Skip::cleanupTestCase() Totals: 3 passed, 0 failed, 3 skipped diff --git a/tests/auto/selftests/skip/tst_skip.cpp b/tests/auto/selftests/skip/tst_skip.cpp index b1a3936..437cf62 100644 --- a/tests/auto/selftests/skip/tst_skip.cpp +++ b/tests/auto/selftests/skip/tst_skip.cpp @@ -70,7 +70,7 @@ void tst_Skip::test_data() void tst_Skip::test() { - printf("this line should never be reached, since we skip in the _data function\n"); + qDebug("this line should never be reached, since we skip in the _data function"); } void tst_Skip::emptytest_data() @@ -80,7 +80,7 @@ void tst_Skip::emptytest_data() void tst_Skip::emptytest() { - printf("this line should never be reached, since we skip in the _data function\n"); + qDebug("this line should never be reached, since we skip in the _data function"); } void tst_Skip::singleSkip_data() @@ -95,7 +95,7 @@ void tst_Skip::singleSkip() QFETCH(bool, booll); if (!booll) QSKIP("skipping one", SkipSingle); - printf("this line should only be reached once (%s)\n", booll ? "true" : "false"); + qDebug("this line should only be reached once (%s)", booll ? "true" : "false"); } QTEST_MAIN(tst_Skip) diff --git a/tests/auto/selftests/tst_selftests.cpp b/tests/auto/selftests/tst_selftests.cpp index 103fd79..6776b12 100644 --- a/tests/auto/selftests/tst_selftests.cpp +++ b/tests/auto/selftests/tst_selftests.cpp @@ -295,6 +295,11 @@ void tst_Selftests::initTestCase() m_checkXMLBlacklist.append("differentexec"); m_checkXMLBlacklist.append("qexecstringlist"); m_checkXMLBlacklist.append("benchliboptions"); + + /* These tests use printf and therefore corrupt the testlog */ + m_checkXMLBlacklist.append("subtest"); + m_checkXMLBlacklist.append("globaldata"); + m_checkXMLBlacklist.append("warnings"); } void tst_Selftests::checkXML() const -- cgit v0.12 From b9f484ae5d415d95df897e18059c054527111374 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Mon, 1 Jun 2009 13:25:08 +1000 Subject: Add textMargin property and more flexible key handling to TextEdit --- src/declarative/fx/qfxtextedit.cpp | 34 ++++++++++++++++++++++++++++++++-- src/declarative/fx/qfxtextedit.h | 5 ++++- src/declarative/fx/qfxtextedit_p.h | 3 ++- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/src/declarative/fx/qfxtextedit.cpp b/src/declarative/fx/qfxtextedit.cpp index 1c70abf..c7a7700 100644 --- a/src/declarative/fx/qfxtextedit.cpp +++ b/src/declarative/fx/qfxtextedit.cpp @@ -49,6 +49,7 @@ #endif #include +#include "qfxevents_p.h" #include #include #include @@ -474,6 +475,21 @@ void QFxTextEdit::setPreserveSelection(bool on) d->preserveSelection = on; } +qreal QFxTextEdit::textMargin() const +{ + Q_D(const QFxTextEdit); + return d->textMargin; +} + +void QFxTextEdit::setTextMargin(qreal margin) +{ + Q_D(QFxTextEdit); + if (d->textMargin == margin) + return; + d->textMargin = margin; + d->document->setDocumentMargin(d->textMargin); +} + void QFxTextEdit::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry) { @@ -659,6 +675,13 @@ Handles the given key \a event. void QFxTextEdit::keyPressEvent(QKeyEvent *event) { Q_D(QFxTextEdit); + //### experiment with allowing 'overrides' to key events + QFxKeyEvent ke(*event); + emit keyPress(&ke); + event->setAccepted(ke.isAccepted()); + if (event->isAccepted()) + return; + QTextCursor c = textCursor(); QTextCursor::MoveOperation op = QTextCursor::NoMove; if (event == QKeySequence::MoveToNextChar) { @@ -688,6 +711,13 @@ Handles the given key \a event. void QFxTextEdit::keyReleaseEvent(QKeyEvent *event) { Q_D(QFxTextEdit); + //### experiment with allowing 'overrides' to key events + QFxKeyEvent ke(*event); + emit keyRelease(&ke); + event->setAccepted(ke.isAccepted()); + if (event->isAccepted()) + return; + d->control->processEvent(event, QPointF(0, 0)); } @@ -821,7 +851,7 @@ void QFxTextEditPrivate::init() document = control->document(); document->setDefaultFont(font.font()); - document->setDocumentMargin(0); + document->setDocumentMargin(textMargin); document->setUndoRedoEnabled(false); // flush undo buffer. document->setUndoRedoEnabled(true); updateDefaultTextOption(); @@ -851,7 +881,7 @@ void QFxTextEdit::updateSize() else if (d->vAlign == AlignVCenter) yoff = dy/2; } - setBaselineOffset(fm.ascent() + yoff); + setBaselineOffset(fm.ascent() + yoff + d->textMargin); if (!widthValid()) { int newWidth = (int)d->document->idealWidth(); d->document->setTextWidth(newWidth); // ### QTextDoc> Alignment will not work unless textWidth is set diff --git a/src/declarative/fx/qfxtextedit.h b/src/declarative/fx/qfxtextedit.h index 37bc327..e30b9ed 100644 --- a/src/declarative/fx/qfxtextedit.h +++ b/src/declarative/fx/qfxtextedit.h @@ -79,7 +79,7 @@ class Q_DECLARATIVE_EXPORT QFxTextEdit : public QFxPaintedItem Q_PROPERTY(bool cursorVisible READ isCursorVisible WRITE setCursorVisible) Q_PROPERTY(bool focusOnPress READ focusOnPress WRITE setFocusOnPress) Q_PROPERTY(bool preserveSelection READ preserveSelection WRITE setPreserveSelection) - Q_CLASSINFO("DefaultProperty", "text") + Q_PROPERTY(qreal textMargin READ textMargin WRITE setTextMargin) public: QFxTextEdit(QFxItem *parent=0); @@ -135,6 +135,9 @@ public: bool preserveSelection() const; void setPreserveSelection(bool on); + qreal textMargin() const; + void setTextMargin(qreal margin); + virtual void dump(int depth); virtual QString propertyInfo() const; diff --git a/src/declarative/fx/qfxtextedit_p.h b/src/declarative/fx/qfxtextedit_p.h index 9f26b10..f733a4c 100644 --- a/src/declarative/fx/qfxtextedit_p.h +++ b/src/declarative/fx/qfxtextedit_p.h @@ -70,7 +70,7 @@ public: QFxTextEditPrivate() : font(0), color("black"), imgDirty(true), hAlign(QFxTextEdit::AlignLeft), vAlign(QFxTextEdit::AlignTop), dirty(false), wrap(false), richText(false), cursorVisible(false), focusOnPress(false), preserveSelection(true), - format(QFxTextEdit::AutoText), document(0) + textMargin(0.0), format(QFxTextEdit::AutoText), document(0) { } @@ -99,6 +99,7 @@ public: bool cursorVisible; bool focusOnPress; bool preserveSelection; + qreal textMargin; QFxTextEdit::TextFormat format; QTextDocument *document; QTextControl *control; -- cgit v0.12 From 596d9378943755bc63b486919b5616132efa7ab3 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Mon, 1 Jun 2009 14:04:35 +1000 Subject: Flush messages after sending --- src/declarative/debugger/qmldebugserver.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/declarative/debugger/qmldebugserver.cpp b/src/declarative/debugger/qmldebugserver.cpp index a253e8c..6dcc352 100644 --- a/src/declarative/debugger/qmldebugserver.cpp +++ b/src/declarative/debugger/qmldebugserver.cpp @@ -283,6 +283,7 @@ void QmlDebugServerPlugin::sendMessage(const QByteArray &message) QPacket pack; pack << d->name << message; d->server->d_func()->protocol->send(pack); + d->server->d_func()->connection->flush(); } void QmlDebugServerPlugin::enabledChanged(bool) -- cgit v0.12 From 0ff7b68f2e3f184d809cf6fd13ff930efa493e9f Mon Sep 17 00:00:00 2001 From: Anders Bakken Date: Mon, 1 Jun 2009 09:39:37 -0700 Subject: Improve readability of QDFBWindowSurface::scroll The batch-blits buys us nothing and this is much more readable. Reviewed-by: TrustMe --- .../gfxdrivers/directfb/qdirectfbwindowsurface.cpp | 39 ++++++++++------------ 1 file changed, 18 insertions(+), 21 deletions(-) diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbwindowsurface.cpp b/src/plugins/gfxdrivers/directfb/qdirectfbwindowsurface.cpp index c7cae80..330eb88 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbwindowsurface.cpp +++ b/src/plugins/gfxdrivers/directfb/qdirectfbwindowsurface.cpp @@ -239,31 +239,28 @@ void QDirectFBWindowSurface::setPermanentState(const QByteArray &state) #endif } -bool QDirectFBWindowSurface::scroll(const QRegion ®ion, int dx, int dy) +static inline void scrollSurface(IDirectFBSurface *surface, const QRect &r, int dx, int dy) { - if (!dfbSurface || !(flipFlags & DSFLIP_BLIT)) - return false; - - const QVector rects = region.rects(); - const int n = rects.size(); - - QVarLengthArray dfbRects(n); - QVarLengthArray dfbPoints(n); + surface->SetBlittingFlags(surface, DSBLIT_NOFX); + const DFBRectangle rect = { r.x(), r.y(), r.width(), r.height() }; + surface->Blit(surface, surface, &rect, r.x() + dx, r.y() + dy); +} - for (int i = 0; i < n; ++i) { - const QRect r = rects.at(i); - dfbRects[i].x = r.x(); - dfbRects[i].y = r.y(); - dfbRects[i].w = r.width(); - dfbRects[i].h = r.height(); - dfbPoints[i].x = r.x() + dx; - dfbPoints[i].y = r.y() + dy; - } +bool QDirectFBWindowSurface::scroll(const QRegion ®ion, int dx, int dy) +{ + if (!dfbSurface || !(flipFlags & DSFLIP_BLIT) || region.isEmpty()) + return false; dfbSurface->SetBlittingFlags(dfbSurface, DSBLIT_NOFX); - dfbSurface->BatchBlit(dfbSurface, dfbSurface, - dfbRects.data(), dfbPoints.data(), n); - dfbSurface->ReleaseSource(dfbSurface); + if (region.numRects() == 1) { + ::scrollSurface(dfbSurface, region.boundingRect(), dx, dy); + } else { + const QVector rects = region.rects(); + const int n = rects.size(); + for (int i=0; i Date: Tue, 2 Jun 2009 11:15:46 +1000 Subject: Improve perf of QMatrix4x4::mapRect(const QRectF &) by 3x for scaled/translated matrix --- src/gui/math3d/qmatrix4x4.cpp | 33 +++++++++++++++++++++++++++++++++ src/gui/math3d/qmatrix4x4.h | 13 ------------- 2 files changed, 33 insertions(+), 13 deletions(-) diff --git a/src/gui/math3d/qmatrix4x4.cpp b/src/gui/math3d/qmatrix4x4.cpp index a8dabf3..976315f 100644 --- a/src/gui/math3d/qmatrix4x4.cpp +++ b/src/gui/math3d/qmatrix4x4.cpp @@ -1431,6 +1431,39 @@ QTransform QMatrix4x4::toTransform() const \sa map() */ +QRectF QMatrix4x4::mapRect(const QRectF& rect) const +{ + if (flagBits & Translation) { + if (flagBits & Scale) { + qreal x = rect.x() * m[0][0] + m[3][0]; + qreal y = rect.y() * m[1][1] + m[3][1]; + qreal w = rect.width() * m[0][0]; + qreal h = rect.height() * m[1][1]; + if (w < 0) { + w = -w; + x -= w; + } + if (h < 0) { + h = -h; + y -= h; + } + return QRectF(x, y, w, h); + } else { + return rect.translated(m[3][0], m[3][1]); + } + } + + QPointF tl = map(rect.topLeft()); QPointF tr = map(rect.topRight()); + QPointF bl = map(rect.bottomLeft()); QPointF br = map(rect.bottomRight()); + + qreal xmin = qMin(qMin(tl.x(), tr.x()), qMin(bl.x(), br.x())); + qreal xmax = qMax(qMax(tl.x(), tr.x()), qMax(bl.x(), br.x())); + qreal ymin = qMin(qMin(tl.y(), tr.y()), qMin(bl.y(), br.y())); + qreal ymax = qMax(qMax(tl.y(), tr.y()), qMax(bl.y(), br.y())); + + return QRectF(QPointF(xmin, ymin), QPointF(xmax, ymax)); +} + /*! \fn float *QMatrix4x4::data() diff --git a/src/gui/math3d/qmatrix4x4.h b/src/gui/math3d/qmatrix4x4.h index 2b485c1..f946da8 100644 --- a/src/gui/math3d/qmatrix4x4.h +++ b/src/gui/math3d/qmatrix4x4.h @@ -914,19 +914,6 @@ inline QRect QMatrix4x4::mapRect(const QRect& rect) const return QRect(QPoint(xmin, ymin), QPoint(xmax, ymax)); } -inline QRectF QMatrix4x4::mapRect(const QRectF& rect) const -{ - QPointF tl = map(rect.topLeft()); QPointF tr = map(rect.topRight()); - QPointF bl = map(rect.bottomLeft()); QPointF br = map(rect.bottomRight()); - - qreal xmin = qMin(qMin(tl.x(), tr.x()), qMin(bl.x(), br.x())); - qreal xmax = qMax(qMax(tl.x(), tr.x()), qMax(bl.x(), br.x())); - qreal ymin = qMin(qMin(tl.y(), tr.y()), qMin(bl.y(), br.y())); - qreal ymax = qMax(qMax(tl.y(), tr.y()), qMax(bl.y(), br.y())); - - return QRectF(QPointF(xmin, ymin), QPointF(xmax, ymax)); -} - inline float *QMatrix4x4::data() { // We have to assume that the caller will modify the matrix elements, -- cgit v0.12 From 1d53f42ed958b6f7c38b47272b43701c4e8ed487 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Tue, 2 Jun 2009 11:27:58 +1000 Subject: Simplify setting default graphicssystem. --- tools/qmlviewer/main.cpp | 50 +++++++++++++++++++----------------------------- 1 file changed, 20 insertions(+), 30 deletions(-) diff --git a/tools/qmlviewer/main.cpp b/tools/qmlviewer/main.cpp index ca98dbf..ed700a0 100644 --- a/tools/qmlviewer/main.cpp +++ b/tools/qmlviewer/main.cpp @@ -50,28 +50,18 @@ void usage() int main(int argc, char ** argv) { //### default to using raster graphics backend for now - int newargc = argc + 2; - char **newargv; bool gsSpecified = false; for (int i = 0; i < argc; ++i) { - if (!qstrcmp(argv[i], "-graphicssystem")) { + QString arg = argv[i]; + if (arg == "-graphicssystem") { gsSpecified = true; - newargc -= 2; break; } } - newargv = new char * [newargc]; - for (int i = 0; i < argc; ++i) { - newargv[i] = argv[i]; - } - if (!gsSpecified) { - char system[] = "-graphicssystem"; - newargv[argc] = system; - char raster[] = "raster"; - newargv[argc+1] = raster; - } + if (!gsSpecified) + QApplication::setGraphicsSystem("raster"); - QApplication app(newargc, newargv); + QApplication app(argc, argv); app.setApplicationName("viewer"); bool frameless = false; @@ -90,24 +80,24 @@ int main(int argc, char ** argv) QString testDir; QString translationFile; - for (int i = 1; i < newargc; ++i) { - QString arg = newargv[i]; + for (int i = 1; i < argc; ++i) { + QString arg = argv[i]; if (arg == "-frameless") { frameless = true; } else if (arg == "-skin") { - skin = QString(newargv[++i]); + skin = QString(argv[++i]); } else if (arg == "-cache") { cache = true; } else if (arg == "-recordperiod") { - period = QString(newargv[++i]).toInt(); + period = QString(argv[++i]).toInt(); } else if (arg == "-recordfile") { - recordfile = QString(newargv[++i]); + recordfile = QString(argv[++i]); } else if (arg == "-record") { - recordargs << QString(newargv[++i]); + recordargs << QString(argv[++i]); } else if (arg == "-recorddither") { - dither = QString(newargv[++i]); + dither = QString(argv[++i]); } else if (arg == "-autorecord") { - QString range = QString(newargv[++i]); + QString range = QString(argv[++i]); int dash = range.indexOf('-'); if (dash > 0) autorecord_from = range.left(dash).toInt(); @@ -116,26 +106,26 @@ int main(int argc, char ** argv) devkeys = true; } else if (arg == "-recordtest") { testMode = QFxTestEngine::RecordTest; - if(i + 1 >= newargc) + if(i + 1 >= argc) usage(); - testDir = newargv[i + 1]; + testDir = argv[i + 1]; ++i; } else if (arg == "-runtest") { testMode = QFxTestEngine::PlaybackTest; - if(i + 1 >= newargc) + if(i + 1 >= argc) usage(); - testDir = newargv[i + 1]; + testDir = argv[i + 1]; ++i; } else if (arg == QLatin1String("-v") || arg == QLatin1String("-version")) { fprintf(stderr, "Qt Declarative UI Viewer version %s\n", QT_VERSION_STR); return 0; } else if (arg == "-translation") { - if(i + 1 >= newargc) + if(i + 1 >= argc) usage(); - translationFile = newargv[i + 1]; + translationFile = argv[i + 1]; ++i; } else if (arg == "-L") { - libraries << QString(newargv[++i]); + libraries << QString(argv[++i]); } else if (arg[0] != '-') { fileName = arg; } else if (1 || arg == "-help") { -- cgit v0.12 From 274f20b48c42b5ed1380e152fe414a2f98795acc Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 2 Jun 2009 11:29:10 +1000 Subject: Don't calculate map rect for items with no content --- src/declarative/canvas/qsimplecanvas_opengl.cpp | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvas_opengl.cpp b/src/declarative/canvas/qsimplecanvas_opengl.cpp index 72f8324..cbe069b 100644 --- a/src/declarative/canvas/qsimplecanvas_opengl.cpp +++ b/src/declarative/canvas/qsimplecanvas_opengl.cpp @@ -240,6 +240,7 @@ void QSimpleCanvasItemPrivate::setupChildState(QSimpleCanvasItem *child) am = data()->transformActive; if (x != 0 || y != 0) am.translate(x, y); + if (scale != 1) { QPointF to = child->d_func()->transformOrigin(); if (to.x() != 0. || to.y() != 0.) @@ -256,6 +257,7 @@ void QSimpleCanvasItemPrivate::setupChildState(QSimpleCanvasItem *child) am.rotate(180, (flip & QSimpleCanvasItem::VerticalFlip)?1:0, (flip & QSimpleCanvasItem::HorizontalFlip)?1:0, 0); am.translate(-br.width() / 2., -br.height() / 2); } + child->d_func()->data()->transformValid = true; } } @@ -264,10 +266,18 @@ QRectF QSimpleCanvasItemPrivate::setupPainting(int version, const QRect &boundin { Q_Q(QSimpleCanvasItem); - QRectF filteredBoundRect = q->boundingRect(); - if (filter) - filteredBoundRect = filter->itemBoundingRect(filteredBoundRect); - QRectF rv = data()->transformActive.mapRect(filteredBoundRect); + bool hasContents = options & QSimpleCanvasItem::HasContents; + + QRectF rv; + + if (hasContents) { + QRectF filteredBoundRect = q->boundingRect(); + if (filter) + filteredBoundRect = filter->itemBoundingRect(filteredBoundRect); + const QMatrix4x4 &active = data()->transformActive; + + rv = active.mapRect(filteredBoundRect); + } for (int ii = 0; ii < children.count(); ++ii) { QSimpleCanvasItem *child = children.at(ii); -- cgit v0.12 From 215026062fb2156fe9b9d86b5c2e9999bd94be62 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 2 Jun 2009 11:39:52 +1000 Subject: Access variables directly for small, but measurable, perf gain --- src/declarative/canvas/qsimplecanvas_opengl.cpp | 56 ++++++++++++++----------- 1 file changed, 32 insertions(+), 24 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvas_opengl.cpp b/src/declarative/canvas/qsimplecanvas_opengl.cpp index cbe069b..ec809ff 100644 --- a/src/declarative/canvas/qsimplecanvas_opengl.cpp +++ b/src/declarative/canvas/qsimplecanvas_opengl.cpp @@ -224,33 +224,39 @@ void QSimpleCanvasItemPrivate::paintChild(const GLPaintParameters ¶ms, void QSimpleCanvasItemPrivate::setupChildState(QSimpleCanvasItem *child) { - qreal visible = child->visible(); - child->d_func()->data()->activeOpacity = data()->activeOpacity; - if (visible != 1) - child->d_func()->data()->activeOpacity *= visible; + QSimpleCanvasItemData *const myData = data(); + QSimpleCanvasItemPrivate *const childPrivate = child->d_func(); + QSimpleCanvasItemData *const childData = childPrivate->data(); - if (child->d_func()->data()->activeOpacity != 0) { + childData->activeOpacity = myData->activeOpacity; + if (childData->visible != 1) + childData->activeOpacity *= childData->visible; + + if (childData->activeOpacity != 0) { // Calculate child's transform - qreal x = child->x(); - qreal y = child->y(); - qreal scale = child->scale(); - QSimpleCanvasItem::Flip flip = child->flip(); - - QSimpleCanvas::Matrix &am = child->d_func()->data()->transformActive; - am = data()->transformActive; - if (x != 0 || y != 0) + const qreal x = childData->x; + const qreal y = childData->y; + const qreal scale = childPrivate->scale; + QSimpleCanvasItem::Flip flip = childData->flip; + + QSimpleCanvas::Matrix &am = childData->transformActive; + am = myData->transformActive; + if (x != 0. || y != 0.) am.translate(x, y); - if (scale != 1) { - QPointF to = child->d_func()->transformOrigin(); - if (to.x() != 0. || to.y() != 0.) + if (scale != 1.) { + QPointF to = childPrivate->transformOrigin(); + bool translate = (to.x() != 0. || to.y() != 0.); + if (translate) am.translate(to.x(), to.y()); am.scale(scale, scale); - if (to.x() != 0. || to.y() != 0.) + if (translate) am.translate(-to.x(), -to.y()); } - if (child->d_func()->data()->transformUser) - am *= *child->d_func()->data()->transformUser; + + if (childData->transformUser) + am *= *childData->transformUser; + if (flip) { QRectF br = child->boundingRect(); am.translate(br.width() / 2., br.height() / 2); @@ -258,7 +264,7 @@ void QSimpleCanvasItemPrivate::setupChildState(QSimpleCanvasItem *child) am.translate(-br.width() / 2., -br.height() / 2); } - child->d_func()->data()->transformValid = true; + childData->transformValid = true; } } @@ -268,13 +274,14 @@ QRectF QSimpleCanvasItemPrivate::setupPainting(int version, const QRect &boundin bool hasContents = options & QSimpleCanvasItem::HasContents; - QRectF rv; + QSimpleCanvasItemData *myData = data(); + QRectF rv; if (hasContents) { QRectF filteredBoundRect = q->boundingRect(); if (filter) filteredBoundRect = filter->itemBoundingRect(filteredBoundRect); - const QMatrix4x4 &active = data()->transformActive; + const QMatrix4x4 &active = myData->transformActive; rv = active.mapRect(filteredBoundRect); } @@ -283,11 +290,12 @@ QRectF QSimpleCanvasItemPrivate::setupPainting(int version, const QRect &boundin QSimpleCanvasItem *child = children.at(ii); setupChildState(child); - if (child->d_func()->data()->activeOpacity != 0) + QSimpleCanvasItemData *childData = child->d_func()->data(); + if (childData->activeOpacity != 0) rv |= child->d_func()->setupPainting(version, bounding); } - data()->lastPaintRect = rv; + myData->lastPaintRect = rv; return rv; } -- cgit v0.12 From 02a8ba7ce8e5ca07ed8e3e83f10a18acd6e38a10 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 2 Jun 2009 11:55:31 +1000 Subject: QMatrix4x4::scale(qreal,qreal) and QMatrix4x4::translate(qreal,qreal) methods --- src/gui/math3d/qmatrix4x4.cpp | 77 +++++++++++++++++++++++++++++++++++++++++++ src/gui/math3d/qmatrix4x4.h | 6 ++-- 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/src/gui/math3d/qmatrix4x4.cpp b/src/gui/math3d/qmatrix4x4.cpp index 976315f..fd4f69a 100644 --- a/src/gui/math3d/qmatrix4x4.cpp +++ b/src/gui/math3d/qmatrix4x4.cpp @@ -740,6 +740,43 @@ QMatrix4x4& QMatrix4x4::scale(const QVector3D& vector) \overload Multiplies this matrix by another that scales coordinates by the + components \a x, and \a y. Returns this matrix. + + \sa translate(), rotate() +*/ +QMatrix4x4& QMatrix4x4::scale(qreal x, qreal y) +{ + float vx(x); + float vy(y); + if (flagBits == Identity) { + m[0][0] = vx; + m[1][1] = vy; + flagBits = Scale; + } else if (flagBits == Scale || flagBits == (Scale | Translation)) { + m[0][0] *= vx; + m[1][1] *= vy; + } else if (flagBits == Translation) { + m[0][0] = vx; + m[1][1] = vy; + flagBits |= Scale; + } else { + m[0][0] *= vx; + m[0][1] *= vx; + m[0][2] *= vx; + m[0][3] *= vx; + m[1][0] *= vy; + m[1][1] *= vy; + m[1][2] *= vy; + m[1][3] *= vy; + flagBits = General; + } + return *this; +} + +/*! + \overload + + Multiplies this matrix by another that scales coordinates by the components \a x, \a y, and \a z. Returns this matrix. \sa translate(), rotate() @@ -872,6 +909,46 @@ QMatrix4x4& QMatrix4x4::translate(const QVector3D& vector) \overload Multiplies this matrix by another that translates coordinates + by the components \a x, and \a y. Returns this matrix. + + \sa scale(), rotate() +*/ +QMatrix4x4& QMatrix4x4::translate(qreal x, qreal y) +{ + float vx(x); + float vy(y); + if (flagBits == Identity) { + m[3][0] = vx; + m[3][1] = vy; + flagBits = Translation; + } else if (flagBits == Translation) { + m[3][0] += vx; + m[3][1] += vy; + } else if (flagBits == Scale) { + m[3][0] = m[0][0] * vx; + m[3][1] = m[1][1] * vy; + m[3][2] = 0.; + flagBits |= Translation; + } else if (flagBits == (Scale | Translation)) { + m[3][0] += m[0][0] * vx; + m[3][1] += m[1][1] * vy; + } else { + m[3][0] += m[0][0] * vx + m[1][0] * vy; + m[3][1] += m[0][1] * vx + m[1][1] * vy; + m[3][2] += m[0][2] * vx + m[1][2] * vy; + m[3][3] += m[0][3] * vx + m[1][3] * vy; + if (flagBits == Rotation) + flagBits |= Translation; + else if (flagBits != (Rotation | Translation)) + flagBits = General; + } + return *this; +} + +/*! + \overload + + Multiplies this matrix by another that translates coordinates by the components \a x, \a y, and \a z. Returns this matrix. \sa scale(), rotate() diff --git a/src/gui/math3d/qmatrix4x4.h b/src/gui/math3d/qmatrix4x4.h index f946da8..79613a0 100644 --- a/src/gui/math3d/qmatrix4x4.h +++ b/src/gui/math3d/qmatrix4x4.h @@ -130,9 +130,11 @@ public: QMatrix4x4& translate(const QVector3D& vector); QMatrix4x4& rotate(qreal angle, const QVector3D& vector); #endif - QMatrix4x4& scale(qreal x, qreal y, qreal z = 1.0f); + QMatrix4x4& scale(qreal x, qreal y); + QMatrix4x4& scale(qreal x, qreal y, qreal z); QMatrix4x4& scale(qreal factor); - QMatrix4x4& translate(qreal x, qreal y, qreal z = 0.0f); + QMatrix4x4& translate(qreal x, qreal y); + QMatrix4x4& translate(qreal x, qreal y, qreal z); QMatrix4x4& rotate(qreal angle, qreal x, qreal y, qreal z = 0.0f); #ifndef QT_NO_QUATERNION QMatrix4x4& rotate(const QQuaternion& quaternion); -- cgit v0.12 From c968390815e2bd578460d1a22a86ded10f373610 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Tue, 2 Jun 2009 11:57:17 +1000 Subject: Remove more unneeded semicolons. --- src/declarative/debugger/qmldebugserver.cpp | 4 +-- src/declarative/util/qfxperf.cpp | 54 ++++++++++++++--------------- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/declarative/debugger/qmldebugserver.cpp b/src/declarative/debugger/qmldebugserver.cpp index a253e8c..d52884e 100644 --- a/src/declarative/debugger/qmldebugserver.cpp +++ b/src/declarative/debugger/qmldebugserver.cpp @@ -69,7 +69,7 @@ private: class QmlDebugServerPrivate : public QObjectPrivate { - Q_DECLARE_PUBLIC(QmlDebugServer); + Q_DECLARE_PUBLIC(QmlDebugServer) public: QmlDebugServerPrivate(); void init(int port); @@ -82,7 +82,7 @@ public: class QmlDebugServerPluginPrivate : public QObjectPrivate { - Q_DECLARE_PUBLIC(QmlDebugServerPlugin); + Q_DECLARE_PUBLIC(QmlDebugServerPlugin) public: QmlDebugServerPluginPrivate(); diff --git a/src/declarative/util/qfxperf.cpp b/src/declarative/util/qfxperf.cpp index 01ac878..9b0e9b7 100644 --- a/src/declarative/util/qfxperf.cpp +++ b/src/declarative/util/qfxperf.cpp @@ -44,32 +44,32 @@ QT_BEGIN_NAMESPACE Q_DEFINE_PERFORMANCE_LOG(QFxPerf, "QFx") { - Q_DEFINE_PERFORMANCE_METRIC(QmlParsing, "QML Parsing"); - Q_DEFINE_PERFORMANCE_METRIC(Compile, "QML Compilation"); - Q_DEFINE_PERFORMANCE_METRIC(CompileRun, "QML Compilation Run"); - Q_DEFINE_PERFORMANCE_METRIC(CreateComponent, "Component creation"); - Q_DEFINE_PERFORMANCE_METRIC(BindInit, "BindValue Initialization"); - Q_DEFINE_PERFORMANCE_METRIC(BindCompile, "BindValue compile"); - Q_DEFINE_PERFORMANCE_METRIC(BindValue, "BindValue execution"); - Q_DEFINE_PERFORMANCE_METRIC(BindValueSSE, "BindValue execution SSE"); - Q_DEFINE_PERFORMANCE_METRIC(BindValueQt, "BindValue execution QtScript"); - Q_DEFINE_PERFORMANCE_METRIC(ContextQuery, "QtScript: Query Context"); - Q_DEFINE_PERFORMANCE_METRIC(ContextProperty, "QtScript: Context Property"); - Q_DEFINE_PERFORMANCE_METRIC(ObjectQuery, "QtScript: Query Object"); - Q_DEFINE_PERFORMANCE_METRIC(ObjectProperty, "QtScript: Object Property"); - Q_DEFINE_PERFORMANCE_METRIC(ObjectSetProperty, "QtScript: Set Object Property"); - Q_DEFINE_PERFORMANCE_METRIC(BindableValueUpdate, "QmlBindableValue::update"); - Q_DEFINE_PERFORMANCE_METRIC(PixmapLoad, "Pixmap loading"); - Q_DEFINE_PERFORMANCE_METRIC(MetaProperty, "Meta property resolution"); - Q_DEFINE_PERFORMANCE_METRIC(PathCache, "Path cache"); - Q_DEFINE_PERFORMANCE_METRIC(CreateParticle, "Particle creation"); - Q_DEFINE_PERFORMANCE_METRIC(FontDatabase, "Font database creation"); - Q_DEFINE_PERFORMANCE_METRIC(ItemComponentComplete, "QFxItem::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(ImageComponentComplete, "QFxImage::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(ComponentInstanceComponentComplete, "QFxComponentInstance::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(BaseLayoutComponentComplete, "QFxBaseLayout::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(TextComponentComplete, "QFxText::componentComplete"); - Q_DEFINE_PERFORMANCE_METRIC(QFxText_setText, "QFxText::setText"); - Q_DEFINE_PERFORMANCE_METRIC(AddScript, "QmlScript::addScriptToEngine"); + Q_DEFINE_PERFORMANCE_METRIC(QmlParsing, "QML Parsing") + Q_DEFINE_PERFORMANCE_METRIC(Compile, "QML Compilation") + Q_DEFINE_PERFORMANCE_METRIC(CompileRun, "QML Compilation Run") + Q_DEFINE_PERFORMANCE_METRIC(CreateComponent, "Component creation") + Q_DEFINE_PERFORMANCE_METRIC(BindInit, "BindValue Initialization") + Q_DEFINE_PERFORMANCE_METRIC(BindCompile, "BindValue compile") + Q_DEFINE_PERFORMANCE_METRIC(BindValue, "BindValue execution") + Q_DEFINE_PERFORMANCE_METRIC(BindValueSSE, "BindValue execution SSE") + Q_DEFINE_PERFORMANCE_METRIC(BindValueQt, "BindValue execution QtScript") + Q_DEFINE_PERFORMANCE_METRIC(ContextQuery, "QtScript: Query Context") + Q_DEFINE_PERFORMANCE_METRIC(ContextProperty, "QtScript: Context Property") + Q_DEFINE_PERFORMANCE_METRIC(ObjectQuery, "QtScript: Query Object") + Q_DEFINE_PERFORMANCE_METRIC(ObjectProperty, "QtScript: Object Property") + Q_DEFINE_PERFORMANCE_METRIC(ObjectSetProperty, "QtScript: Set Object Property") + Q_DEFINE_PERFORMANCE_METRIC(BindableValueUpdate, "QmlBindableValue::update") + Q_DEFINE_PERFORMANCE_METRIC(PixmapLoad, "Pixmap loading") + Q_DEFINE_PERFORMANCE_METRIC(MetaProperty, "Meta property resolution") + Q_DEFINE_PERFORMANCE_METRIC(PathCache, "Path cache") + Q_DEFINE_PERFORMANCE_METRIC(CreateParticle, "Particle creation") + Q_DEFINE_PERFORMANCE_METRIC(FontDatabase, "Font database creation") + Q_DEFINE_PERFORMANCE_METRIC(ItemComponentComplete, "QFxItem::componentComplete") + Q_DEFINE_PERFORMANCE_METRIC(ImageComponentComplete, "QFxImage::componentComplete") + Q_DEFINE_PERFORMANCE_METRIC(ComponentInstanceComponentComplete, "QFxComponentInstance::componentComplete") + Q_DEFINE_PERFORMANCE_METRIC(BaseLayoutComponentComplete, "QFxBaseLayout::componentComplete") + Q_DEFINE_PERFORMANCE_METRIC(TextComponentComplete, "QFxText::componentComplete") + Q_DEFINE_PERFORMANCE_METRIC(QFxText_setText, "QFxText::setText") + Q_DEFINE_PERFORMANCE_METRIC(AddScript, "QmlScript::addScriptToEngine") } QT_END_NAMESPACE -- cgit v0.12 From cef61c5c660410e2db8418c8a23b68d9e523c75d Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 2 Jun 2009 12:49:08 +1000 Subject: Optimize QMatrix4x4::mapRect() for translation and scale operations --- src/gui/math3d/qmatrix4x4.cpp | 69 +++++++++++++- src/gui/math3d/qmatrix4x4.h | 26 ------ tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp | 114 ++++++++++++++++++++++++ 3 files changed, 179 insertions(+), 30 deletions(-) diff --git a/src/gui/math3d/qmatrix4x4.cpp b/src/gui/math3d/qmatrix4x4.cpp index a8dabf3..d2f1ded 100644 --- a/src/gui/math3d/qmatrix4x4.cpp +++ b/src/gui/math3d/qmatrix4x4.cpp @@ -1411,8 +1411,6 @@ QTransform QMatrix4x4::toTransform() const #endif /*! - \fn QRect QMatrix4x4::mapRect(const QRect& rect) const - Maps \a rect by multiplying this matrix by the corners of \a rect and then forming a new rectangle from the results. The returned rectangle will be an ordinary 2D rectangle @@ -1420,10 +1418,43 @@ QTransform QMatrix4x4::toTransform() const \sa map() */ +QRect QMatrix4x4::mapRect(const QRect& rect) const +{ + if (flagBits == (Translation | Scale) || flagBits == Scale) { + qreal x = rect.x() * m[0][0] + m[3][0]; + qreal y = rect.y() * m[1][1] + m[3][1]; + qreal w = rect.width() * m[0][0]; + qreal h = rect.height() * m[1][1]; + if (w < 0) { + w = -w; + x -= w; + } + if (h < 0) { + h = -h; + y -= h; + } + return QRect(qRound(x), qRound(y), qRound(w), qRound(h)); + } else if (flagBits == Translation) { + return QRect(qRound(rect.x() + m[3][0]), + qRound(rect.y() + m[3][1]), + rect.width(), rect.height()); + } -/*! - \fn QRectF QMatrix4x4::mapRect(const QRectF& rect) const + QPoint tl = map(rect.topLeft()); + QPoint tr = map(QPoint(rect.x() + rect.width(), rect.y())); + QPoint bl = map(QPoint(rect.x(), rect.y() + rect.height())); + QPoint br = map(QPoint(rect.x() + rect.width(), + rect.y() + rect.height())); + + int xmin = qMin(qMin(tl.x(), tr.x()), qMin(bl.x(), br.x())); + int xmax = qMax(qMax(tl.x(), tr.x()), qMax(bl.x(), br.x())); + int ymin = qMin(qMin(tl.y(), tr.y()), qMin(bl.y(), br.y())); + int ymax = qMax(qMax(tl.y(), tr.y()), qMax(bl.y(), br.y())); + + return QRect(xmin, ymin, xmax - xmin, ymax - ymin); +} +/*! Maps \a rect by multiplying this matrix by the corners of \a rect and then forming a new rectangle from the results. The returned rectangle will be an ordinary 2D rectangle @@ -1431,6 +1462,36 @@ QTransform QMatrix4x4::toTransform() const \sa map() */ +QRectF QMatrix4x4::mapRect(const QRectF& rect) const +{ + if (flagBits == (Translation | Scale) || flagBits == Scale) { + qreal x = rect.x() * m[0][0] + m[3][0]; + qreal y = rect.y() * m[1][1] + m[3][1]; + qreal w = rect.width() * m[0][0]; + qreal h = rect.height() * m[1][1]; + if (w < 0) { + w = -w; + x -= w; + } + if (h < 0) { + h = -h; + y -= h; + } + return QRectF(x, y, w, h); + } else if (flagBits == Translation) { + return rect.translated(m[3][0], m[3][1]); + } + + QPointF tl = map(rect.topLeft()); QPointF tr = map(rect.topRight()); + QPointF bl = map(rect.bottomLeft()); QPointF br = map(rect.bottomRight()); + + qreal xmin = qMin(qMin(tl.x(), tr.x()), qMin(bl.x(), br.x())); + qreal xmax = qMax(qMax(tl.x(), tr.x()), qMax(bl.x(), br.x())); + qreal ymin = qMin(qMin(tl.y(), tr.y()), qMin(bl.y(), br.y())); + qreal ymax = qMax(qMax(tl.y(), tr.y()), qMax(bl.y(), br.y())); + + return QRectF(QPointF(xmin, ymin), QPointF(xmax, ymax)); +} /*! \fn float *QMatrix4x4::data() diff --git a/src/gui/math3d/qmatrix4x4.h b/src/gui/math3d/qmatrix4x4.h index 2b485c1..00543f5 100644 --- a/src/gui/math3d/qmatrix4x4.h +++ b/src/gui/math3d/qmatrix4x4.h @@ -901,32 +901,6 @@ inline QVector4D QMatrix4x4::map(const QVector4D& point) const #endif -inline QRect QMatrix4x4::mapRect(const QRect& rect) const -{ - QPoint tl = map(rect.topLeft()); QPoint tr = map(rect.topRight()); - QPoint bl = map(rect.bottomLeft()); QPoint br = map(rect.bottomRight()); - - int xmin = qMin(qMin(tl.x(), tr.x()), qMin(bl.x(), br.x())); - int xmax = qMax(qMax(tl.x(), tr.x()), qMax(bl.x(), br.x())); - int ymin = qMin(qMin(tl.y(), tr.y()), qMin(bl.y(), br.y())); - int ymax = qMax(qMax(tl.y(), tr.y()), qMax(bl.y(), br.y())); - - return QRect(QPoint(xmin, ymin), QPoint(xmax, ymax)); -} - -inline QRectF QMatrix4x4::mapRect(const QRectF& rect) const -{ - QPointF tl = map(rect.topLeft()); QPointF tr = map(rect.topRight()); - QPointF bl = map(rect.bottomLeft()); QPointF br = map(rect.bottomRight()); - - qreal xmin = qMin(qMin(tl.x(), tr.x()), qMin(bl.x(), br.x())); - qreal xmax = qMax(qMax(tl.x(), tr.x()), qMax(bl.x(), br.x())); - qreal ymin = qMin(qMin(tl.y(), tr.y()), qMin(bl.y(), br.y())); - qreal ymax = qMax(qMax(tl.y(), tr.y()), qMax(bl.y(), br.y())); - - return QRectF(QPointF(xmin, ymin), QPointF(xmax, ymax)); -} - inline float *QMatrix4x4::data() { // We have to assume that the caller will modify the matrix elements, diff --git a/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp b/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp index bb510fc..936f9d6 100644 --- a/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp +++ b/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp @@ -167,6 +167,9 @@ private slots: void fill(); + void mapRect_data(); + void mapRect(); + private: static void setMatrix(QMatrix2x2& m, const qreal *values); static void setMatrixFixed(QMatrix2x2& m, const qreal *values); @@ -3180,6 +3183,117 @@ void tst_QMatrix::fill() QVERIFY(isSame(m2, fillValues4x3)); } +// Test the mapRect() function for QRect and QRectF. +void tst_QMatrix::mapRect_data() +{ + QTest::addColumn("x"); + QTest::addColumn("y"); + QTest::addColumn("width"); + QTest::addColumn("height"); + + QTest::newRow("null") + << (qreal)0.0f << (qreal)0.0f << (qreal)0.0f << (qreal)0.0f; + QTest::newRow("rect") + << (qreal)1.0f << (qreal)-20.5f << (qreal)100.0f << (qreal)63.75f; +} +void tst_QMatrix::mapRect() +{ + QFETCH(qreal, x); + QFETCH(qreal, y); + QFETCH(qreal, width); + QFETCH(qreal, height); + + QRectF rect(x, y, width, height); + QRect recti(qRound(x), qRound(y), qRound(width), qRound(height)); + + QMatrix4x4 m1; + QVERIFY(m1.mapRect(rect) == rect); + QVERIFY(m1.mapRect(recti) == recti); + + QMatrix4x4 m2; + m2.translate(-100.5f, 64.0f); + QRectF translated = rect.translated(-100.5f, 64.0f); + QRect translatedi = QRect(qRound(recti.x() - 100.5f), recti.y() + 64, + recti.width(), recti.height()); + QVERIFY(m2.mapRect(rect) == translated); + QVERIFY(m2.mapRect(recti) == translatedi); + + QMatrix4x4 m3; + m3.scale(-100.5f, 64.0f); + qreal scalex = x * -100.5f; + qreal scaley = y * 64.0f; + qreal scalewid = width * -100.5f; + qreal scaleht = height * 64.0f; + if (scalewid < 0.0f) { + scalewid = -scalewid; + scalex -= scalewid; + } + if (scaleht < 0.0f) { + scaleht = -scaleht; + scaley -= scaleht; + } + QRectF scaled(scalex, scaley, scalewid, scaleht); + QVERIFY(m3.mapRect(rect) == scaled); + scalex = recti.x() * -100.5f; + scaley = recti.y() * 64.0f; + scalewid = recti.width() * -100.5f; + scaleht = recti.height() * 64.0f; + if (scalewid < 0.0f) { + scalewid = -scalewid; + scalex -= scalewid; + } + if (scaleht < 0.0f) { + scaleht = -scaleht; + scaley -= scaleht; + } + QRect scaledi(qRound(scalex), qRound(scaley), + qRound(scalewid), qRound(scaleht)); + QVERIFY(m3.mapRect(recti) == scaledi); + + QMatrix4x4 m4; + m4.translate(-100.5f, 64.0f); + m4.scale(-2.5f, 4.0f); + qreal transx1 = x * -2.5f - 100.5f; + qreal transy1 = y * 4.0f + 64.0f; + qreal transx2 = (x + width) * -2.5f - 100.5f; + qreal transy2 = (y + height) * 4.0f + 64.0f; + if (transx1 > transx2) + qSwap(transx1, transx2); + if (transy1 > transy2) + qSwap(transy1, transy2); + QRectF trans(transx1, transy1, transx2 - transx1, transy2 - transy1); + QVERIFY(m4.mapRect(rect) == trans); + transx1 = recti.x() * -2.5f - 100.5f; + transy1 = recti.y() * 4.0f + 64.0f; + transx2 = (recti.x() + recti.width()) * -2.5f - 100.5f; + transy2 = (recti.y() + recti.height()) * 4.0f + 64.0f; + if (transx1 > transx2) + qSwap(transx1, transx2); + if (transy1 > transy2) + qSwap(transy1, transy2); + QRect transi(qRound(transx1), qRound(transy1), + qRound(transx2) - qRound(transx1), + qRound(transy2) - qRound(transy1)); + QVERIFY(m4.mapRect(recti) == transi); + + m4.rotate(45.0f, 0.0f, 0.0f, 1.0f); + + QTransform t4; + t4.translate(-100.5f, 64.0f); + t4.scale(-2.5f, 4.0f); + t4.rotate(45.0f); + QRectF mr = m4.mapRect(rect); + QRectF tr = t4.mapRect(rect); + QVERIFY(fuzzyCompare(mr.x(), tr.x())); + QVERIFY(fuzzyCompare(mr.y(), tr.y())); + QVERIFY(fuzzyCompare(mr.width(), tr.width())); + QVERIFY(fuzzyCompare(mr.height(), tr.height())); + + QRect mri = m4.mapRect(recti); + QRect tri = t4.mapRect(recti); + QVERIFY(mri == tri); +} + QTEST_APPLESS_MAIN(tst_QMatrix) #include "tst_qmatrixnxn.moc" -- cgit v0.12 From 5a7d208ee0730021b79310132d4dd384d7d15801 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 2 Jun 2009 11:55:31 +1000 Subject: QMatrix4x4::scale(qreal,qreal) and QMatrix4x4::translate(qreal,qreal) methods --- src/gui/math3d/qmatrix4x4.cpp | 77 +++++++++++++++++++++++++++++++++++++++++++ src/gui/math3d/qmatrix4x4.h | 6 ++-- 2 files changed, 81 insertions(+), 2 deletions(-) diff --git a/src/gui/math3d/qmatrix4x4.cpp b/src/gui/math3d/qmatrix4x4.cpp index d2f1ded..8ef4da3 100644 --- a/src/gui/math3d/qmatrix4x4.cpp +++ b/src/gui/math3d/qmatrix4x4.cpp @@ -740,6 +740,43 @@ QMatrix4x4& QMatrix4x4::scale(const QVector3D& vector) \overload Multiplies this matrix by another that scales coordinates by the + components \a x, and \a y. Returns this matrix. + + \sa translate(), rotate() +*/ +QMatrix4x4& QMatrix4x4::scale(qreal x, qreal y) +{ + float vx(x); + float vy(y); + if (flagBits == Identity) { + m[0][0] = vx; + m[1][1] = vy; + flagBits = Scale; + } else if (flagBits == Scale || flagBits == (Scale | Translation)) { + m[0][0] *= vx; + m[1][1] *= vy; + } else if (flagBits == Translation) { + m[0][0] = vx; + m[1][1] = vy; + flagBits |= Scale; + } else { + m[0][0] *= vx; + m[0][1] *= vx; + m[0][2] *= vx; + m[0][3] *= vx; + m[1][0] *= vy; + m[1][1] *= vy; + m[1][2] *= vy; + m[1][3] *= vy; + flagBits = General; + } + return *this; +} + +/*! + \overload + + Multiplies this matrix by another that scales coordinates by the components \a x, \a y, and \a z. Returns this matrix. \sa translate(), rotate() @@ -872,6 +909,46 @@ QMatrix4x4& QMatrix4x4::translate(const QVector3D& vector) \overload Multiplies this matrix by another that translates coordinates + by the components \a x, and \a y. Returns this matrix. + + \sa scale(), rotate() +*/ +QMatrix4x4& QMatrix4x4::translate(qreal x, qreal y) +{ + float vx(x); + float vy(y); + if (flagBits == Identity) { + m[3][0] = vx; + m[3][1] = vy; + flagBits = Translation; + } else if (flagBits == Translation) { + m[3][0] += vx; + m[3][1] += vy; + } else if (flagBits == Scale) { + m[3][0] = m[0][0] * vx; + m[3][1] = m[1][1] * vy; + m[3][2] = 0.; + flagBits |= Translation; + } else if (flagBits == (Scale | Translation)) { + m[3][0] += m[0][0] * vx; + m[3][1] += m[1][1] * vy; + } else { + m[3][0] += m[0][0] * vx + m[1][0] * vy; + m[3][1] += m[0][1] * vx + m[1][1] * vy; + m[3][2] += m[0][2] * vx + m[1][2] * vy; + m[3][3] += m[0][3] * vx + m[1][3] * vy; + if (flagBits == Rotation) + flagBits |= Translation; + else if (flagBits != (Rotation | Translation)) + flagBits = General; + } + return *this; +} + +/*! + \overload + + Multiplies this matrix by another that translates coordinates by the components \a x, \a y, and \a z. Returns this matrix. \sa scale(), rotate() diff --git a/src/gui/math3d/qmatrix4x4.h b/src/gui/math3d/qmatrix4x4.h index 00543f5..cff4c1e 100644 --- a/src/gui/math3d/qmatrix4x4.h +++ b/src/gui/math3d/qmatrix4x4.h @@ -130,9 +130,11 @@ public: QMatrix4x4& translate(const QVector3D& vector); QMatrix4x4& rotate(qreal angle, const QVector3D& vector); #endif - QMatrix4x4& scale(qreal x, qreal y, qreal z = 1.0f); + QMatrix4x4& scale(qreal x, qreal y); + QMatrix4x4& scale(qreal x, qreal y, qreal z); QMatrix4x4& scale(qreal factor); - QMatrix4x4& translate(qreal x, qreal y, qreal z = 0.0f); + QMatrix4x4& translate(qreal x, qreal y); + QMatrix4x4& translate(qreal x, qreal y, qreal z); QMatrix4x4& rotate(qreal angle, qreal x, qreal y, qreal z = 0.0f); #ifndef QT_NO_QUATERNION QMatrix4x4& rotate(const QQuaternion& quaternion); -- cgit v0.12 From 32d87121d5102f01809a888dca5a42683a781b20 Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 2 Jun 2009 13:01:09 +1000 Subject: Unit tests for 2D QMatrix4x4::translate() and scale() --- tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp | 40 +++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp b/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp index 936f9d6..4d51e89 100644 --- a/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp +++ b/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp @@ -1978,6 +1978,14 @@ void tst_QMatrix::scale4x4_data() 0.0f, 0.0f, 0.0f, 1.0f}; QTest::newRow("complex") << (qreal)2.0f << (qreal)11.0f << (qreal)-6.5f << (void *)complexScale; + + static const qreal complexScale2D[] = + {2.0f, 0.0f, 0.0f, 0.0f, + 0.0f, -11.0f, 0.0f, 0.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}; + QTest::newRow("complex2D") + << (qreal)2.0f << (qreal)-11.0f << (qreal)1.0f << (void *)complexScale2D; } void tst_QMatrix::scale4x4() { @@ -1996,6 +2004,12 @@ void tst_QMatrix::scale4x4() m2.scale(x, y, z); QVERIFY(isSame(m2, (const qreal *)resultValues)); + if (z == 1.0f) { + QMatrix4x4 m2b; + m2b.scale(x, y); + QVERIFY(m2b == m2); + } + QVector3D v1(2.0f, 3.0f, -4.0f); QVector3D v2 = m1 * v1; QCOMPARE(v2.x(), (qreal)(2.0f * x)); @@ -2049,6 +2063,12 @@ void tst_QMatrix::scale4x4() QVERIFY(isSame(m5, (const qreal *)resultValues)); } + if (z == 1.0f) { + QMatrix4x4 m4b(m3); + m4b.scale(x, y); + QVERIFY(m4b == m4); + } + // Test coverage when the special matrix type is unknown. QMatrix4x4 m6; @@ -2104,6 +2124,14 @@ void tst_QMatrix::translate4x4_data() 0.0f, 0.0f, 0.0f, 1.0f}; QTest::newRow("complex") << (qreal)2.0f << (qreal)11.0f << (qreal)-6.5f << (void *)complexTranslate; + + static const qreal complexTranslate2D[] = + {1.0f, 0.0f, 0.0f, 2.0f, + 0.0f, 1.0f, 0.0f, -11.0f, + 0.0f, 0.0f, 1.0f, 0.0f, + 0.0f, 0.0f, 0.0f, 1.0f}; + QTest::newRow("complex2D") + << (qreal)2.0f << (qreal)-11.0f << (qreal)0.0f << (void *)complexTranslate2D; } void tst_QMatrix::translate4x4() { @@ -2122,6 +2150,12 @@ void tst_QMatrix::translate4x4() m2.translate(x, y, z); QVERIFY(isSame(m2, (const qreal *)resultValues)); + if (z == 0.0f) { + QMatrix4x4 m2b; + m2b.translate(x, y); + QVERIFY(m2b == m2); + } + QVector3D v1(2.0f, 3.0f, -4.0f); QVector3D v2 = m1 * v1; QCOMPARE(v2.x(), (qreal)(2.0f + x)); @@ -2156,6 +2190,12 @@ void tst_QMatrix::translate4x4() QMatrix4x4 m4(m3); m4.translate(x, y, z); QVERIFY(m4 == m3 * m1); + + if (z == 0.0f) { + QMatrix4x4 m4b(m3); + m4b.translate(x, y); + QVERIFY(m4b == m4); + } } // Test the generation and use of 4x4 rotation matrices. -- cgit v0.12 From 4636f6983aa253c7552bba5d7d8772844ea4c42c Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 2 Jun 2009 14:41:31 +1000 Subject: Add some performance tests for QMatrix4x4 --- tests/benchmarks/benchmarks.pro | 1 + tests/benchmarks/qmatrix4x4/qmatrix4x4.pro | 6 + tests/benchmarks/qmatrix4x4/tst_qmatrix4x4.cpp | 261 +++++++++++++++++++++++++ 3 files changed, 268 insertions(+) create mode 100644 tests/benchmarks/qmatrix4x4/qmatrix4x4.pro create mode 100644 tests/benchmarks/qmatrix4x4/tst_qmatrix4x4.cpp diff --git a/tests/benchmarks/benchmarks.pro b/tests/benchmarks/benchmarks.pro index 4c39373..bc41125 100644 --- a/tests/benchmarks/benchmarks.pro +++ b/tests/benchmarks/benchmarks.pro @@ -9,6 +9,7 @@ SUBDIRS = containers-associative \ qpixmap \ blendbench \ qstringlist \ + qmatrix4x4 \ qobject \ qrect \ qregexp \ diff --git a/tests/benchmarks/qmatrix4x4/qmatrix4x4.pro b/tests/benchmarks/qmatrix4x4/qmatrix4x4.pro new file mode 100644 index 0000000..e82d9de --- /dev/null +++ b/tests/benchmarks/qmatrix4x4/qmatrix4x4.pro @@ -0,0 +1,6 @@ +load(qttest_p4) +TEMPLATE = app +TARGET = tst_qmatrix4x4 + +SOURCES += tst_qmatrix4x4.cpp + diff --git a/tests/benchmarks/qmatrix4x4/tst_qmatrix4x4.cpp b/tests/benchmarks/qmatrix4x4/tst_qmatrix4x4.cpp new file mode 100644 index 0000000..5046b17 --- /dev/null +++ b/tests/benchmarks/qmatrix4x4/tst_qmatrix4x4.cpp @@ -0,0 +1,261 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtOpenGL module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include + +class tst_QMatrix4x4 : public QObject +{ + Q_OBJECT +public: + tst_QMatrix4x4() {} + ~tst_QMatrix4x4() {} + +private slots: + void multiply_data(); + void multiply(); + + void multiplyInPlace_data(); + void multiplyInPlace(); + + void multiplyDirect_data(); + void multiplyDirect(); + + void mapVector3D_data(); + void mapVector3D(); + + void mapVector2D_data(); + void mapVector2D(); + + void mapVectorDirect_data(); + void mapVectorDirect(); +}; + +static qreal const generalValues[16] = + {1.0f, 2.0f, 3.0f, 4.0f, + 5.0f, 6.0f, 7.0f, 8.0f, + 9.0f, 10.0f, 11.0f, 12.0f, + 13.0f, 14.0f, 15.0f, 16.0f}; + +void tst_QMatrix4x4::multiply_data() +{ + QTest::addColumn("m1"); + QTest::addColumn("m2"); + + QTest::newRow("identity * identity") + << QMatrix4x4() << QMatrix4x4(); + QTest::newRow("identity * general") + << QMatrix4x4() << QMatrix4x4(generalValues); + QTest::newRow("general * identity") + << QMatrix4x4(generalValues) << QMatrix4x4(); + QTest::newRow("general * general") + << QMatrix4x4(generalValues) << QMatrix4x4(generalValues); +} + +QMatrix4x4 mresult; + +void tst_QMatrix4x4::multiply() +{ + QFETCH(QMatrix4x4, m1); + QFETCH(QMatrix4x4, m2); + + QMatrix4x4 m3; + + QBENCHMARK { + m3 = m1 * m2; + } + + // Force the result to be stored so the compiler doesn't + // optimize away the contents of the benchmark loop. + mresult = m3; +} + +void tst_QMatrix4x4::multiplyInPlace_data() +{ + multiply_data(); +} + +void tst_QMatrix4x4::multiplyInPlace() +{ + QFETCH(QMatrix4x4, m1); + QFETCH(QMatrix4x4, m2); + + QMatrix4x4 m3; + + QBENCHMARK { + m3 = m1; + m3 *= m2; + } + + // Force the result to be stored so the compiler doesn't + // optimize away the contents of the benchmark loop. + mresult = m3; +} + +// Use a direct naive multiplication algorithm. This is used +// to compare against the optimized routines to see if they are +// actually faster than the naive implementation. +void tst_QMatrix4x4::multiplyDirect_data() +{ + multiply_data(); +} +void tst_QMatrix4x4::multiplyDirect() +{ + QFETCH(QMatrix4x4, m1); + QFETCH(QMatrix4x4, m2); + + QMatrix4x4 m3; + + const float *m1data = m1.constData(); + const float *m2data = m2.constData(); + float *m3data = m3.data(); + + QBENCHMARK { + for (int row = 0; row < 4; ++row) { + for (int col = 0; col < 4; ++col) { + m3data[col * 4 + row] = 0.0f; + for (int j = 0; j < 4; ++j) { + m3data[col * 4 + row] += + m1data[j * 4 + row] * m2data[col * 4 + j]; + } + } + } + } +} + +QVector3D vresult; + +void tst_QMatrix4x4::mapVector3D_data() +{ + QTest::addColumn("m1"); + + QTest::newRow("identity") << QMatrix4x4(); + QTest::newRow("general") << QMatrix4x4(generalValues); + + QMatrix4x4 t1; + t1.translate(-100.5f, 64.0f, 75.25f); + QTest::newRow("translate3D") << t1; + + QMatrix4x4 t2; + t2.translate(-100.5f, 64.0f); + QTest::newRow("translate2D") << t2; + + QMatrix4x4 s1; + s1.scale(-100.5f, 64.0f, 75.25f); + QTest::newRow("scale3D") << s1; + + QMatrix4x4 s2; + s2.scale(-100.5f, 64.0f); + QTest::newRow("scale2D") << s2; +} +void tst_QMatrix4x4::mapVector3D() +{ + QFETCH(QMatrix4x4, m1); + + QVector3D v(10.5f, -2.0f, 3.0f); + QVector3D result; + + m1.inferSpecialType(); + + QBENCHMARK { + result = m1 * v; + } + + // Force the result to be stored so the compiler doesn't + // optimize away the contents of the benchmark loop. + vresult = result; +} + +QPointF vresult2; + +void tst_QMatrix4x4::mapVector2D_data() +{ + mapVector3D_data(); +} +void tst_QMatrix4x4::mapVector2D() +{ + QFETCH(QMatrix4x4, m1); + + QPointF v(10.5f, -2.0f); + QPointF result; + + m1.inferSpecialType(); + + QBENCHMARK { + result = m1 * v; + } + + // Force the result to be stored so the compiler doesn't + // optimize away the contents of the benchmark loop. + vresult2 = result; +} + +// Use a direct naive multiplication algorithm. This is used +// to compare against the optimized routines to see if they are +// actually faster than the naive implementation. +void tst_QMatrix4x4::mapVectorDirect_data() +{ + mapVector3D_data(); +} +void tst_QMatrix4x4::mapVectorDirect() +{ + QFETCH(QMatrix4x4, m1); + + const float *m1data = m1.constData(); + float v[4] = {10.5f, -2.0f, 3.0f, 1.0f}; + float result[4]; + + QBENCHMARK { + for (int row = 0; row < 4; ++row) { + result[row] = 0.0f; + for (int col = 0; col < 4; ++col) { + result[row] += m1data[col * 4 + row] * v[col]; + } + } + result[0] /= result[3]; + result[1] /= result[3]; + result[2] /= result[3]; + } +} + +QTEST_MAIN(tst_QMatrix4x4) + +#include "tst_qmatrix4x4.moc" -- cgit v0.12 From 3245f19f8d3abbcba5fcd9adc3fc984ad4c7ddcb Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 2 Jun 2009 15:06:12 +1000 Subject: Optimize QMatrix4x4::map() for QVector3D/QPoint/QPointF Use the matrix "flagBits" to short-cut transformations when the matrix type is identity/translate/scale. --- src/gui/math3d/qmatrix4x4.h | 135 +++++++++++++++++++++++++++++--------------- 1 file changed, 90 insertions(+), 45 deletions(-) diff --git a/src/gui/math3d/qmatrix4x4.h b/src/gui/math3d/qmatrix4x4.h index cff4c1e..ba7f67f 100644 --- a/src/gui/math3d/qmatrix4x4.h +++ b/src/gui/math3d/qmatrix4x4.h @@ -631,26 +631,43 @@ inline QVector3D operator*(const QVector3D& vector, const QMatrix4x4& matrix) inline QVector3D operator*(const QMatrix4x4& matrix, const QVector3D& vector) { float x, y, z, w; - x = vector.xp * matrix.m[0][0] + - vector.yp * matrix.m[1][0] + - vector.zp * matrix.m[2][0] + - matrix.m[3][0]; - y = vector.xp * matrix.m[0][1] + - vector.yp * matrix.m[1][1] + - vector.zp * matrix.m[2][1] + - matrix.m[3][1]; - z = vector.xp * matrix.m[0][2] + - vector.yp * matrix.m[1][2] + - vector.zp * matrix.m[2][2] + - matrix.m[3][2]; - w = vector.xp * matrix.m[0][3] + - vector.yp * matrix.m[1][3] + - vector.zp * matrix.m[2][3] + - matrix.m[3][3]; - if (w == 1.0f) - return QVector3D(x, y, z, 1); - else - return QVector3D(x / w, y / w, z / w, 1); + if (matrix.flagBits == QMatrix4x4::Identity) { + return vector; + } else if (matrix.flagBits == QMatrix4x4::Translation) { + return QVector3D(vector.xp + matrix.m[3][0], + vector.yp + matrix.m[3][1], + vector.zp + matrix.m[3][2], 1); + } else if (matrix.flagBits == + (QMatrix4x4::Translation | QMatrix4x4::Scale)) { + return QVector3D(vector.xp * matrix.m[0][0] + matrix.m[3][0], + vector.yp * matrix.m[1][1] + matrix.m[3][1], + vector.zp * matrix.m[2][2] + matrix.m[3][2], 1); + } else if (matrix.flagBits == QMatrix4x4::Scale) { + return QVector3D(vector.xp * matrix.m[0][0], + vector.yp * matrix.m[1][1], + vector.zp * matrix.m[2][2], 1); + } else { + x = vector.xp * matrix.m[0][0] + + vector.yp * matrix.m[1][0] + + vector.zp * matrix.m[2][0] + + matrix.m[3][0]; + y = vector.xp * matrix.m[0][1] + + vector.yp * matrix.m[1][1] + + vector.zp * matrix.m[2][1] + + matrix.m[3][1]; + z = vector.xp * matrix.m[0][2] + + vector.yp * matrix.m[1][2] + + vector.zp * matrix.m[2][2] + + matrix.m[3][2]; + w = vector.xp * matrix.m[0][3] + + vector.yp * matrix.m[1][3] + + vector.zp * matrix.m[2][3] + + matrix.m[3][3]; + if (w == 1.0f) + return QVector3D(x, y, z, 1); + else + return QVector3D(x / w, y / w, z / w, 1); + } } #endif @@ -752,19 +769,33 @@ inline QPoint operator*(const QMatrix4x4& matrix, const QPoint& point) float x, y, w; xin = point.x(); yin = point.y(); - x = xin * matrix.m[0][0] + - yin * matrix.m[1][0] + - matrix.m[3][0]; - y = xin * matrix.m[0][1] + - yin * matrix.m[1][1] + - matrix.m[3][1]; - w = xin * matrix.m[0][3] + - yin * matrix.m[1][3] + - matrix.m[3][3]; - if (w == 1.0f) - return QPoint(qRound(x), qRound(y)); - else - return QPoint(qRound(x / w), qRound(y / w)); + if (matrix.flagBits == QMatrix4x4::Identity) { + return point; + } else if (matrix.flagBits == QMatrix4x4::Translation) { + return QPoint(qRound(xin + matrix.m[3][0]), + qRound(yin + matrix.m[3][1])); + } else if (matrix.flagBits == + (QMatrix4x4::Translation | QMatrix4x4::Scale)) { + return QPoint(qRound(xin * matrix.m[0][0] + matrix.m[3][0]), + qRound(yin * matrix.m[1][1] + matrix.m[3][1])); + } else if (matrix.flagBits == QMatrix4x4::Scale) { + return QPoint(qRound(xin * matrix.m[0][0]), + qRound(yin * matrix.m[1][1])); + } else { + x = xin * matrix.m[0][0] + + yin * matrix.m[1][0] + + matrix.m[3][0]; + y = xin * matrix.m[0][1] + + yin * matrix.m[1][1] + + matrix.m[3][1]; + w = xin * matrix.m[0][3] + + yin * matrix.m[1][3] + + matrix.m[3][3]; + if (w == 1.0f) + return QPoint(qRound(x), qRound(y)); + else + return QPoint(qRound(x / w), qRound(y / w)); + } } inline QPointF operator*(const QMatrix4x4& matrix, const QPointF& point) @@ -773,19 +804,33 @@ inline QPointF operator*(const QMatrix4x4& matrix, const QPointF& point) float x, y, w; xin = point.x(); yin = point.y(); - x = xin * matrix.m[0][0] + - yin * matrix.m[1][0] + - matrix.m[3][0]; - y = xin * matrix.m[0][1] + - yin * matrix.m[1][1] + - matrix.m[3][1]; - w = xin * matrix.m[0][3] + - yin * matrix.m[1][3] + - matrix.m[3][3]; - if (w == 1.0f) { - return QPointF(qreal(x), qreal(y)); + if (matrix.flagBits == QMatrix4x4::Identity) { + return point; + } else if (matrix.flagBits == QMatrix4x4::Translation) { + return QPointF(xin + matrix.m[3][0], + yin + matrix.m[3][1]); + } else if (matrix.flagBits == + (QMatrix4x4::Translation | QMatrix4x4::Scale)) { + return QPointF(xin * matrix.m[0][0] + matrix.m[3][0], + yin * matrix.m[1][1] + matrix.m[3][1]); + } else if (matrix.flagBits == QMatrix4x4::Scale) { + return QPointF(xin * matrix.m[0][0], + yin * matrix.m[1][1]); } else { - return QPointF(qreal(x / w), qreal(y / w)); + x = xin * matrix.m[0][0] + + yin * matrix.m[1][0] + + matrix.m[3][0]; + y = xin * matrix.m[0][1] + + yin * matrix.m[1][1] + + matrix.m[3][1]; + w = xin * matrix.m[0][3] + + yin * matrix.m[1][3] + + matrix.m[3][3]; + if (w == 1.0f) { + return QPointF(qreal(x), qreal(y)); + } else { + return QPointF(qreal(x / w), qreal(y / w)); + } } } -- cgit v0.12 From 63fba94e074c29f17e35c7cf9133d1878b18401f Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 2 Jun 2009 15:10:43 +1000 Subject: Fix signature for QGenericMatrix::fill() The signature was using qreal, when it should have used T. --- src/gui/math3d/qgenericmatrix.cpp | 2 +- src/gui/math3d/qgenericmatrix.h | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/gui/math3d/qgenericmatrix.cpp b/src/gui/math3d/qgenericmatrix.cpp index a77ca42..6ecd878 100644 --- a/src/gui/math3d/qgenericmatrix.cpp +++ b/src/gui/math3d/qgenericmatrix.cpp @@ -116,7 +116,7 @@ QT_BEGIN_NAMESPACE */ /*! - \fn void QGenericMatrix::fill(qreal value) + \fn void QGenericMatrix::fill(T value) Fills all elements of this matrix with \a value. */ diff --git a/src/gui/math3d/qgenericmatrix.h b/src/gui/math3d/qgenericmatrix.h index d0b22de..b4d3707 100644 --- a/src/gui/math3d/qgenericmatrix.h +++ b/src/gui/math3d/qgenericmatrix.h @@ -65,7 +65,7 @@ public: bool isIdentity() const; void setIdentity(); - void fill(qreal value); + void fill(T value); QGenericMatrix transposed() const; @@ -175,7 +175,7 @@ Q_OUTOFLINE_TEMPLATE void QGenericMatrix::setIdentity() } template -Q_OUTOFLINE_TEMPLATE void QGenericMatrix::fill(qreal value) +Q_OUTOFLINE_TEMPLATE void QGenericMatrix::fill(T value) { for (int col = 0; col < N; ++col) for (int row = 0; row < M; ++row) -- cgit v0.12 From b70d7a99f48d23da62683172b0088e1ffff904ee Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 2 Jun 2009 15:23:55 +1000 Subject: Minor perf tweaks --- src/declarative/canvas/qsimplecanvas.cpp | 48 ++++++++++++++++---------------- src/declarative/canvas/qsimplecanvas_p.h | 2 +- 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvas.cpp b/src/declarative/canvas/qsimplecanvas.cpp index e582226..59edf74 100644 --- a/src/declarative/canvas/qsimplecanvas.cpp +++ b/src/declarative/canvas/qsimplecanvas.cpp @@ -830,24 +830,25 @@ void QSimpleCanvas::queueUpdate() void QSimpleCanvas::addDirty(QSimpleCanvasItem *c) { + Q_ASSERT(d->isSimpleCanvas()); queueUpdate(); - if (d->isSimpleCanvas()) { - d->oldDirty |= c->d_func()->data()->lastPaintRect; + d->oldDirty |= c->d_func()->data()->lastPaintRect; #if defined(QFX_RENDER_OPENGL) - // Check for filters - QSimpleCanvasItem *fi = c->parent(); - while(fi) { - if (fi->d_func()->data()->dirty) { - break; - } else if (fi->filter()) { - fi->update(); - break; - } - fi = fi->parent(); + // ### Is this parent crawl going to be a problem for scenes with nots + // of things changing? + // Check for filters + QSimpleCanvasItem *fi = c->parent(); + while(fi) { + if (fi->d_func()->data()->dirty) { + break; + } else if (fi->filter()) { + fi->update(); + break; } -#endif - d->dirtyItems.append(c); + fi = fi->parent(); } +#endif + d->dirtyItems.append(c); } QRect QSimpleCanvasPrivate::dirtyItemClip() const @@ -867,7 +868,7 @@ QRect QSimpleCanvasPrivate::dirtyItemClip() const return rv; } -QRegion QSimpleCanvasPrivate::resetDirty() +QRect QSimpleCanvasPrivate::resetDirty() { if (isSimpleCanvas()) { #if defined(QFX_RENDER_OPENGL) @@ -883,11 +884,11 @@ QRegion QSimpleCanvasPrivate::resetDirty() oldDirty = QRect(); if (fullUpdate()) - return QRegion(); + return QRect(); else - return QRegion(r); + return r; } else { - return QRegion(); + return QRect(); } } @@ -914,6 +915,7 @@ QSimpleCanvasItem *QSimpleCanvas::focusItem(QSimpleCanvasItem *item) const bool QSimpleCanvas::event(QEvent *e) { if (e->type() == QEvent::User && d->isSimpleCanvas()) { + int tbf = d->frameTimer.restart(); d->timer = 0; d->isSetup = true; #if defined(QFX_RENDER_OPENGL1) @@ -924,9 +926,7 @@ bool QSimpleCanvas::event(QEvent *e) d->root->d_func()->setupPainting(0, rect()); #endif - QRegion r = d->resetDirty(); - - int tbf = d->frameTimer.restart(); + QRect r = d->resetDirty(); #if defined(QFX_RENDER_QPAINTER) if (r.isEmpty() || fullUpdate()) @@ -935,12 +935,12 @@ bool QSimpleCanvas::event(QEvent *e) repaint(r); emit framePainted(); #else - QRect br = r.boundingRect(); - QRect nr(br.x(), height() - br.y() - br.height(), br.width(), br.height()); + + QRect nr(r.x(), height() - r.y() - r.height(), r.width(), r.height()); if (r.isEmpty() || fullUpdate()) d->egl.updateGL(); - else + else d->egl.updateGL(nr); emit framePainted(); #endif diff --git a/src/declarative/canvas/qsimplecanvas_p.h b/src/declarative/canvas/qsimplecanvas_p.h index d9ed4ac..b284c6c 100644 --- a/src/declarative/canvas/qsimplecanvas_p.h +++ b/src/declarative/canvas/qsimplecanvas_p.h @@ -126,7 +126,7 @@ public: #else QRect oldDirty; #endif - QRegion resetDirty(); + QRect resetDirty(); void paint(QPainter &p); -- cgit v0.12 From 5dca661dc78d8eb0489e7debf342a0869ae75a43 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Tue, 2 Jun 2009 10:35:10 +0200 Subject: My changes for Qt 4.5.2. Better late than never. --- dist/changes-4.5.2 | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index dcb77d6..98ea59e 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -46,6 +46,18 @@ Third party components Plugins (r41346, r43550, r43915, r43917, r43923) Clipboard (r41360) +- QMacStyle + * [253339] Don't draw arrows on toolbuttons that have a menu and text only. + * [252301] Ensure that small and mini spin boxes are drawn correctly. + +- QFontDialog + * [252000] Ensure that QFontDialog::getFont() works on Mac OS X. + +- QWidget + * [250668] Don't send extra wheel events when using the scroll wheel in Cocoa. + * [253448] Prevent a crash when using the Qt::WA_MacBrushedMetal attribute + in conjunction with style sheets. + **************************************************************************** * Database Drivers * **************************************************************************** @@ -65,6 +77,10 @@ Qt for Windows Qt for Mac OS X --------------- +[252795] Ensure that we send Apple Events in the Cocoa port even when Cocoa isn't ready. +[252176] Fix regression in drawing parts of pixmaps on Panther. +[253402] Fix a crash when a Cocoa window that used to be a QWidget would get events + after the QWidget was destroyed. Qt for Embedded Linux @@ -101,6 +117,8 @@ Qt for Windows CE of 'Fixed' on the main cointainer. * [253278] Made it possible to set QString-type properties using QDesignerFormWindowCursor::setProperty(). + * [253539] Prevent crash in Designer with the Cocoa port when when using a scroll + wheel to change a property. - Linguist - Linguist GUI -- cgit v0.12 From d018549a25761b5e50d90939d94384f23d7a01e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Fri, 29 May 2009 19:05:29 +0200 Subject: Fixes possible infinite loop in QApplication::topLevelAt KDE Bug: https://bugs.kde.org/show_bug.cgi?id=191759 Reviewed-by: Bradley T. Hughes --- src/gui/kernel/qapplication_x11.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gui/kernel/qapplication_x11.cpp b/src/gui/kernel/qapplication_x11.cpp index a3c9406..12155f0 100644 --- a/src/gui/kernel/qapplication_x11.cpp +++ b/src/gui/kernel/qapplication_x11.cpp @@ -2955,10 +2955,10 @@ QWidget *QApplication::topLevelAt(const QPoint &p) Window wid = widget->internalWinId(); while (ctarget && !w) { X11->ignoreBadwindow(); - XTranslateCoordinates(X11->display, - QX11Info::appRootWindow(screen), - ctarget, x, y, &unused, &unused, &ctarget); - if (X11->badwindow()) + if (!XTranslateCoordinates(X11->display, + QX11Info::appRootWindow(screen), + ctarget, x, y, &unused, &unused, &ctarget) + || X11->badwindow()) break; if (ctarget == wid) { // Found! -- cgit v0.12 From d52fb58f34199e9a6e008929425cd21b92a2674a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 2 Jun 2009 10:42:21 +0200 Subject: Fixed bug in QClipData::fixup(). The bounding rect computed in fixup() is one pixel too wide, causing potential memory corruption by painting outside device boundaries. Reviewed-by: Trond --- src/gui/painting/qpaintengine_raster.cpp | 2 -- tests/auto/qpainter/tst_qpainter.cpp | 24 ++++++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 3f85095..578a815 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -4475,14 +4475,12 @@ void QClipData::fixup() if (sl != left || sr != right) isRect = false; } - ++xmax; // qDebug("xmin=%d,xmax=%d,ymin=%d,ymax=%d %s", xmin, xmax, ymin, ymax, isRect ? "rectangular" : ""); if (isRect) { hasRectClip = true; clipRect.setRect(xmin, ymin, xmax - xmin, ymax - ymin); } - } /* diff --git a/tests/auto/qpainter/tst_qpainter.cpp b/tests/auto/qpainter/tst_qpainter.cpp index 87f9c13..af0f6cf 100644 --- a/tests/auto/qpainter/tst_qpainter.cpp +++ b/tests/auto/qpainter/tst_qpainter.cpp @@ -226,6 +226,7 @@ private slots: void extendedBlendModes(); void zeroOpacity(); + void clippingBug(); private: void fillData(); @@ -4168,5 +4169,28 @@ void tst_QPainter::zeroOpacity() QCOMPARE(target.pixel(0, 0), 0xff000000); } +void tst_QPainter::clippingBug() +{ + QImage img(32, 32, QImage::Format_ARGB32_Premultiplied); + img.fill(0); + + QImage expected = img; + QPainter p(&expected); + p.fillRect(1, 1, 30, 30, Qt::red); + p.end(); + + QPainterPath path; + path.addRect(1, 1, 30, 30); + path.addRect(1, 1, 30, 30); + path.addRect(1, 1, 30, 30); + + p.begin(&img); + p.setClipPath(path); + p.fillRect(0, 0, 32, 32, Qt::red); + p.end(); + + QCOMPARE(img, expected); +} + QTEST_MAIN(tst_QPainter) #include "tst_qpainter.moc" -- cgit v0.12 From 8f16a4f1638fd661e74c6aa60822cd9ef17e5003 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 2 Jun 2009 11:02:21 +0200 Subject: My 4.5.2 changes for the changelog. --- dist/changes-4.5.2 | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 98ea59e..0cb3112 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -58,6 +58,26 @@ Third party components * [253448] Prevent a crash when using the Qt::WA_MacBrushedMetal attribute in conjunction with style sheets. +- QPainter + * [253783] Fixed text shaping bugs when using ligatures and different + scripts in a single text item. + * Fixed various inconsistencies for image drawing on non-integer + coordinates. + * Fixed bug with 0-opacity causing images to be drawn fully opaque. + * Fixed crash when drawing on a null pixmap. + * [251534] Fixed issue where text with non-opaque color from widget + palette would be blitted instead of blended. + +- QTransform + * Fixed issue in QTransform::type() causing a projective transform to be + treated as a scaling transform. + +- QtOpenGL + * [247083] Re-enabled antialiasing for large font sizes in OpenGL paint + engine. + * [251485] Fixed crash that could occur with projective transforms and + high quality antialiasing. + **************************************************************************** * Database Drivers * **************************************************************************** @@ -69,7 +89,11 @@ Third party components Qt for Linux/X11 ---------------- - +[253186] Fixed compile error in qfontengine_ft.cpp on 64-bit platforms with +legacy freetype headers. +[241361] Prevented asynchronous access to non-thread safe libfontconfig API. +[244362] Worked around X server crash when calling XFillPolygon with more than +200000 points by falling back to raster paint engine. Qt for Windows -------------- -- cgit v0.12 From 65b2f91df8376df97fed7d7096ac73db838e7d09 Mon Sep 17 00:00:00 2001 From: jieshuzheng Date: Sun, 31 May 2009 18:02:31 +0800 Subject: Remove the redundant timer kill and start when the two QTimer::start(int) is made in succession If you restart the QTimer like the following code snippet shows, the timer will get killed and started twice. QTimer timer; timer.start(100); timer.start(1000); Since QTimer::start(int msec) calls QTimer::setInterval(int msec), and QTimer::setInterval(int msec) will kill the timer and start another one if there is already a timer running. And QTimer::start() will do the same thing again. It is a performance penalty here. Under Windows, it will result in one extra call of SetTimer(). And under Symbian, it will result in one extra new and delete of CPeriodic and adding and removing it from AS. --- src/corelib/kernel/qtimer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/kernel/qtimer.cpp b/src/corelib/kernel/qtimer.cpp index 08821d4..8ca53b9 100644 --- a/src/corelib/kernel/qtimer.cpp +++ b/src/corelib/kernel/qtimer.cpp @@ -211,7 +211,7 @@ void QTimer::start() */ void QTimer::start(int msec) { - setInterval(msec); + inter = msec; start(); } -- cgit v0.12 From 7314c07a3e443b1d5349b419a03db8d41ca43f7e Mon Sep 17 00:00:00 2001 From: jasplin Date: Tue, 2 Jun 2009 10:57:42 +0200 Subject: BT: Fixed crash on Mac caused by erroneous handling of native focus events. On Mac, a widget with a NoFocus policy could still get focus (if only temporarily) as the result of a native focus event. In particular, a line edit with a completer should not lose focus (if only for a brief moment) as a result of the completer popup being shown. This will for example cause an item delegate to think that the user has navigated away from the cell and delete the line edit as a result. This will in turn cause the completer to access a null pointer. Reviewed-by: Richard Moe Gustavsen Task-number: 254456 and 254460 --- src/gui/kernel/qwidget_mac.mm | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/gui/kernel/qwidget_mac.mm b/src/gui/kernel/qwidget_mac.mm index f863428..c82b87d 100644 --- a/src/gui/kernel/qwidget_mac.mm +++ b/src/gui/kernel/qwidget_mac.mm @@ -1296,8 +1296,11 @@ OSStatus QWidgetPrivate::qt_widget_event(EventHandlerCallRef er, EventRef event, if(part == kControlFocusNoPart){ if (widget->hasFocus()) QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason); - } else + } else if (widget->focusPolicy() != Qt::NoFocus) { widget->setFocus(); + } else { + handled_event = false; + } } if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) CallNextEventHandler(er, event); -- cgit v0.12 From 39fc672795fbb60118e8f506e4f2c49b1980b7c0 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Tue, 2 Jun 2009 11:48:34 +0200 Subject: Change QDesktopServices::TempLocation on Mac to be the same as QDir. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In the past, TempLocation would return something like: /private/var/folders/4k/4k97GBy2Ha46D3DAWSLbQE+++TI/TemporaryItems Now it returns something like: /var/folders/4k/4k97GBy2Ha46D3DAWSLbQE+++TI/-Tmp- This isn't that different and it's a temporary location so it shouldn't effect many people (and it will be gone once the system reboots anyway), but the issue could be that TemporaryItems isn't there and that it's a bit more "Carbon" to use TemporaryItems. Also our own documentation claims they are equivalent and I'm happy to do that. I also enforced the Qt-style of if-statements and got rid of the extra qualifiers to make the code look nicer. Task-number: 253806 Reviewed-by: Morten Sørvig --- src/gui/util/qdesktopservices_mac.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/gui/util/qdesktopservices_mac.cpp b/src/gui/util/qdesktopservices_mac.cpp index fb1e193..4f730b7 100644 --- a/src/gui/util/qdesktopservices_mac.cpp +++ b/src/gui/util/qdesktopservices_mac.cpp @@ -134,13 +134,15 @@ static QString getFullPath(const FSRef &ref) QString QDesktopServices::storageLocation(StandardLocation type) { - if (QDesktopServices::HomeLocation == type) + if (type == HomeLocation) return QDir::homePath(); + if (type == TempLocation) + return QDir::tempPath(); + short domain = kOnAppropriateDisk; - if (QDesktopServices::DataLocation == type - || QDesktopServices::CacheLocation == type) + if (type == DataLocation || type == CacheLocation) domain = kUserDomain; // http://developer.apple.com/documentation/Carbon/Reference/Folder_Manager/Reference/reference.html @@ -152,8 +154,7 @@ QString QDesktopServices::storageLocation(StandardLocation type) QString path = getFullPath(ref); QString appName = QCoreApplication::applicationName(); - if (!appName.isEmpty() && - (QDesktopServices::DataLocation == type || QDesktopServices::CacheLocation == type)) + if (!appName.isEmpty() && (type == DataLocation || type == CacheLocation)) path += QLatin1Char('/') + appName; return path; -- cgit v0.12 From c46126179dfb12e01d5787fdd2278cfc0788d9fa Mon Sep 17 00:00:00 2001 From: "Bradley T. Hughes" Date: Tue, 2 Jun 2009 12:02:14 +0200 Subject: Improve detection of monotonic timer support Some older systems support monotonic timers, but not POSIX.1-2001. The sysconf() function is documented to return -1 if a feature is not supported, otherwise it returns a value that's dependent on it's argument. For POSIX.1-2001 compliant system, the value is 200112L, but on other systems it may just return 1, for example. Because of this, we check for the -1 return value (feature missing), instead of relying on a specific (positive) return value. --- src/corelib/kernel/qeventdispatcher_unix.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/kernel/qeventdispatcher_unix.cpp b/src/corelib/kernel/qeventdispatcher_unix.cpp index 6aa3b56..1b9cb93 100644 --- a/src/corelib/kernel/qeventdispatcher_unix.cpp +++ b/src/corelib/kernel/qeventdispatcher_unix.cpp @@ -263,7 +263,7 @@ QTimerInfoList::QTimerInfoList() # if (_POSIX_MONOTONIC_CLOCK == 0) // detect if the system support monotonic timers long x = sysconf(_SC_MONOTONIC_CLOCK); - useMonotonicTimers = x >= 200112L; + useMonotonicTimers = x != -1; # endif getTime(currentTime); -- cgit v0.12 From f001cda07f6aa026d59e448b49212c0182ed895c Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Tue, 2 Jun 2009 12:40:48 +0200 Subject: Removed an ifdef in QLocale that breaks the One Definition Rule. From a merge request #553 by Gordon Schumacher: During a build internal to Qt, if a header included by qlocale.cpp itself includes qlocale.h, then QLOCALE_CPP will never be set. If you attempt to build qmake from its own .pro file, qmake_pch.h includes qtextstream.h, which (now) includes qlocale.h, thus causing a compile error trying to call the QSystemLocale(bool) function Inspired-by: Gordon Schumacher --- src/corelib/tools/qlocale.cpp | 1 - src/corelib/tools/qlocale.h | 2 -- 2 files changed, 3 deletions(-) diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp index 9953155..4c2f59a 100644 --- a/src/corelib/tools/qlocale.cpp +++ b/src/corelib/tools/qlocale.cpp @@ -42,7 +42,6 @@ #include "qglobal.h" #ifndef QT_NO_SYSTEMLOCALE -#define QLOCALE_CPP QT_BEGIN_NAMESPACE class QSystemLocale; static QSystemLocale *QSystemLocale_globalSystemLocale(); diff --git a/src/corelib/tools/qlocale.h b/src/corelib/tools/qlocale.h index 5b611eb..987ab4e 100644 --- a/src/corelib/tools/qlocale.h +++ b/src/corelib/tools/qlocale.h @@ -99,11 +99,9 @@ public: virtual QVariant query(QueryType type, QVariant in) const; virtual QLocale fallbackLocale() const; -#ifdef QLOCALE_CPP private: QSystemLocale(bool); friend QSystemLocale *QSystemLocale_globalSystemLocale(); -#endif }; #endif -- cgit v0.12 From 9b53bb583ca7e74c737683d85593e4a97107a777 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Tue, 2 Jun 2009 13:02:27 +0200 Subject: Doc - changing the "main layout" term to "top level widget's layout" to preserve some consistency. Also added a screenshot of the Object Insepector displaying a form where its widget has no top level layout. Reviewed-By: TrustMe --- doc/src/designer-manual.qdoc | 19 ++++++++++++------- doc/src/images/rgbController-no-toplevel-layout.png | Bin 0 -> 1343 bytes 2 files changed, 12 insertions(+), 7 deletions(-) create mode 100644 doc/src/images/rgbController-no-toplevel-layout.png diff --git a/doc/src/designer-manual.qdoc b/doc/src/designer-manual.qdoc index 4b8de32..fc3adcf 100644 --- a/doc/src/designer-manual.qdoc +++ b/doc/src/designer-manual.qdoc @@ -465,18 +465,23 @@ spin boxes and sliders as well. The next step is to combine all three layouts into one \bold{main layout}. - It is important that your form has a main layout; otherwise, the widgets - on your form will not resize when your form is resized. To set the main - layout, \gui{Right click} anywhere on your form, outside of the three - separate layouts, and select \gui{Lay Out Horizontally}. Alternatively, you - could also select \gui{Lay Out in a Grid} -- you will still see the same - arrangement (shown below). + The main layout is the top level widget's (in this case, the QWidget) + layout. It is important that your top level widget has a layout; otherwise, + the widgets on your window will not resize when your window is resized. To + set the layout, \gui{Right click} anywhere on your form, outside of the + three separate layouts, and select \gui{Lay Out Horizontally}. + Alternatively, you could also select \gui{Lay Out in a Grid} -- you will + still see the same arrangement (shown below). \image rgbController-final-layout.png \note Main layouts cannot be seen on the form. To check if you have a main layout installed, try resizing your form; your widgets should resize - accordingly. + accordingly. Alternatively, you can take a look at \QD's + \gui{Object Inspector}. If your top level widget does not have a layout, + you will see the broken layout icon next to it, + \inlineimage rgbController-no-toplevel-layout.png + . When you click on the slider and drag it to a certain value, you want the spin box to display the slider's position. To accomplish this behavior, you diff --git a/doc/src/images/rgbController-no-toplevel-layout.png b/doc/src/images/rgbController-no-toplevel-layout.png new file mode 100644 index 0000000..0a9bc29 Binary files /dev/null and b/doc/src/images/rgbController-no-toplevel-layout.png differ -- cgit v0.12 From 9dc7a011e798c24b4dd8b19a74b42c61f52a1328 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Tue, 2 Jun 2009 13:08:10 +0200 Subject: Changelog for 4.5.2 --- dist/changes-4.5.2 | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 0cb3112..423bbdd 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -94,10 +94,15 @@ legacy freetype headers. [241361] Prevented asynchronous access to non-thread safe libfontconfig API. [244362] Worked around X server crash when calling XFillPolygon with more than 200000 points by falling back to raster paint engine. +[250326] Titlebar wasn't shown on X11 with Qt::CustomizeWindowHint for + fixed-size windows. +[251925] Improved showing QMessageBox on small screens. Qt for Windows -------------- +[251259] Switching to another app left text cursor in line edits with + QtMfc framework. Qt for Mac OS X --------------- -- cgit v0.12 From 983411366b3517fce2dd6fc6b72c6292e93f6824 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 2 Jun 2009 13:10:47 +0200 Subject: qdoc: Changed the css to make more people happy. No more fonts less than 100%. Toned down the green lines separating table rows, now gray (or we can try a softer green). Made the table widt 100%. More coming. the constructors still aren't aligned properly. --- tools/qdoc3/htmlgenerator.cpp | 2 +- tools/qdoc3/test/classic.css | 20 ++++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index e2e6950..4e4261f 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -2181,7 +2181,7 @@ void HtmlGenerator::generateSectionList(const Section& section, } if (name_alignment) { out() << "\n"; + << "cellspacing=\"0\" width=\"100%\">\n"; } else { if (twoColumn) diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index a6c2652..fa0167b 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -73,16 +73,16 @@ table td.memItemLeft { border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; - border-top-color: #66bc29; - border-right-color: #66bc29; - border-bottom-color: #66bc29; - border-left-color: #66bc29; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; border-top-style: solid; border-right-style: none; border-bottom-style: none; border-left-style: none; background-color: #FAFAFA; - font-size: 80%; + font-size: 100%; white-space: nowrap } table td.memItemRight { @@ -92,16 +92,16 @@ table td.memItemRight { border-right-width: 1px; border-bottom-width: 1px; border-left-width: 1px; - border-top-color: #66bc29; - border-right-color: #66bc29; - border-bottom-color: #66bc29; - border-left-color: #66bc29; + border-top-color: #E0E0E0; + border-right-color: #E0E0E0; + border-bottom-color: #E0E0E0; + border-left-color: #E0E0E0; border-top-style: solid; border-right-style: none; border-bottom-style: none; border-left-style: none; background-color: #FAFAFA; - font-size: 80%; + font-size: 100%; } table tr.odd { -- cgit v0.12 From 3be8bd20537ea215c7accaf1be3ffb6673fd897b Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Tue, 2 Jun 2009 13:37:07 +0200 Subject: Ensure small and mini headers aren't bigger than "large" ones. We were only "constraining" headers if they were large, but ignoring the small and mini ones. This resulted in the small and mini headers looking bigger than their normal ones which looked strange. Since the headers have no real small or mini size for a header, we'll make sure to constrain them all the same. Task-number: 221115 Reviewed-by: Richard Moe Gustavsen --- src/gui/styles/qmacstyle_mac.mm | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/styles/qmacstyle_mac.mm b/src/gui/styles/qmacstyle_mac.mm index 2478f20..43efedf 100644 --- a/src/gui/styles/qmacstyle_mac.mm +++ b/src/gui/styles/qmacstyle_mac.mm @@ -851,7 +851,7 @@ static QSize qt_aqua_get_known_size(QStyle::ContentsType ct, const QWidget *widg } break; case QStyle::CT_HeaderSection: - if (sz == QAquaSizeLarge && isTreeView(widg)) + if (isTreeView(widg)) ret = QSize(-1, qt_mac_aqua_get_metric(kThemeMetricListHeaderHeight)); break; case QStyle::CT_MenuBar: -- cgit v0.12 From 4ae7a683217eb2a7e9fc2fe2ed173e7da277038b Mon Sep 17 00:00:00 2001 From: Peter Hartmann Date: Tue, 2 Jun 2009 13:44:24 +0200 Subject: My Changelog for 4.5.2 --- dist/changes-4.5.2 | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 423bbdd..c87ad92 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -46,6 +46,9 @@ Third party components Plugins (r41346, r43550, r43915, r43917, r43923) Clipboard (r41360) +- QAbstractNetworkCache + * Only cache responses to HTTP GET by default, not HTTP PUT or POST + - QMacStyle * [253339] Don't draw arrows on toolbuttons that have a menu and text only. * [252301] Ensure that small and mini spin boxes are drawn correctly. @@ -53,6 +56,13 @@ Third party components - QFontDialog * [252000] Ensure that QFontDialog::getFont() works on Mac OS X. +- QNetworkCookie + * [251959] fix parsing of multiple cookies separated by a newline + +- QNetworkCookieJar + * [251467] do not allow cookies for domains like ".com" + * [228974] allow cookies whose domain attribute is missing a leading dot + - QWidget * [250668] Don't send extra wheel events when using the scroll wheel in Cocoa. * [253448] Prevent a crash when using the Qt::WA_MacBrushedMetal attribute -- cgit v0.12 From 6d28410756ab29277807d2026b4cbd8e1c707714 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 2 Jun 2009 13:59:46 +0200 Subject: Compilation fix on MSVC Reviewed-by: alexis --- src/declarative/qml/qmlprivate.h | 46 +++++++--------------------------------- src/gui/text/qtextcontrol_p.h | 2 +- 2 files changed, 9 insertions(+), 39 deletions(-) diff --git a/src/declarative/qml/qmlprivate.h b/src/declarative/qml/qmlprivate.h index 62524aa..3f41fb7 100644 --- a/src/declarative/qml/qmlprivate.h +++ b/src/declarative/qml/qmlprivate.h @@ -123,43 +123,13 @@ namespace QmlPrivate } }; - template - class has_attachedPropertiesMember - { - typedef int yes_type; - typedef char no_type; - template - struct Selector {}; - - template - static yes_type test(Selector*); - - template - static no_type test(...); - - public: - static bool const value = sizeof(test(0)) == sizeof(yes_type); - }; - - template - class has_attachedPropertiesMethod + template + struct has_qmlAttachedProperties { - typedef int yes_type; - typedef char no_type; - - template - static yes_type check(ReturnType *(*)(QObject *)); - static no_type check(...); - - public: - static bool const value = sizeof(check(&T::qmlAttachedProperties)) == sizeof(yes_type); - }; - - template - class has_attachedPropertiesMethod - { - public: - static bool const value = false; + template struct type_check; + template static char check(type_check *); + template static int check(...); + static bool const value = sizeof(check(0)) == sizeof(char); }; template @@ -191,13 +161,13 @@ namespace QmlPrivate template inline QmlAttachedPropertiesFunc attachedPropertiesFunc() { - return AttachedPropertySelector::value>::value>::func(); + return AttachedPropertySelector::value >::func(); } template inline const QMetaObject *attachedPropertiesMetaObject() { - return AttachedPropertySelector::value>::value>::metaObject(); + return AttachedPropertySelector::value >::metaObject(); } struct MetaTypeIds { diff --git a/src/gui/text/qtextcontrol_p.h b/src/gui/text/qtextcontrol_p.h index 4dac4f7..e50540a 100644 --- a/src/gui/text/qtextcontrol_p.h +++ b/src/gui/text/qtextcontrol_p.h @@ -83,7 +83,7 @@ class QAbstractScrollArea; class QEvent; class QTimerEvent; -class Q_AUTOTEST_EXPORT QTextControl : public QObject +class Q_GUI_EXPORT QTextControl : public QObject { Q_OBJECT Q_DECLARE_PRIVATE(QTextControl) -- cgit v0.12 From b78b4593410a876e0664c01ce7afade64bf37660 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 2 Jun 2009 14:47:29 +0200 Subject: fix MSVC warnings --- src/declarative/canvas/qsimplecanvasdebugplugin.cpp | 5 +++-- src/declarative/debugger/qmldebugger.cpp | 3 ++- src/declarative/debugger/qmlpropertyview.cpp | 2 +- src/declarative/qml/qmlcompiler_p.h | 2 +- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvasdebugplugin.cpp b/src/declarative/canvas/qsimplecanvasdebugplugin.cpp index 0fd0f81..12088c1 100644 --- a/src/declarative/canvas/qsimplecanvasdebugplugin.cpp +++ b/src/declarative/canvas/qsimplecanvasdebugplugin.cpp @@ -58,6 +58,7 @@ public: virtual int duration() const { return -1; } virtual void updateCurrentTime(int msecs) { + Q_UNUSED(msecs); server->frameBreak(); } @@ -66,7 +67,7 @@ private: }; QSimpleCanvasDebugPlugin::QSimpleCanvasDebugPlugin(QObject *parent) -: QmlDebugServerPlugin("CanvasFrameRate", parent), _breaks(0) +: QmlDebugServerPlugin(QLatin1String("CanvasFrameRate"), parent), _breaks(0) { _time.start(); new FrameBreakAnimation(this); @@ -95,7 +96,7 @@ void QSimpleCanvasDebugPlugin::frameBreak() } QSimpleCanvasSceneDebugPlugin::QSimpleCanvasSceneDebugPlugin(QSimpleCanvas *parent) -: QmlDebugServerPlugin("CanvasScene", parent), m_canvas(parent) +: QmlDebugServerPlugin(QLatin1String("CanvasScene"), parent), m_canvas(parent) { } diff --git a/src/declarative/debugger/qmldebugger.cpp b/src/declarative/debugger/qmldebugger.cpp index c925148..9ab3247 100644 --- a/src/declarative/debugger/qmldebugger.cpp +++ b/src/declarative/debugger/qmldebugger.cpp @@ -282,7 +282,7 @@ bool QmlDebugger::makeItem(QObject *obj, QmlDebuggerItem *item) if(!toolTipString.isEmpty()) toolTipString.prepend(QLatin1Char('\n')); toolTipString.prepend(tr("Root type: ") + text); - text = p->typeName; + text = QString::fromAscii(p->typeName); } if(!toolTipString.isEmpty()) @@ -333,6 +333,7 @@ bool operator<(const QPair > &lhs, void QmlDebugger::setCanvas(QSimpleCanvas *c) { + Q_UNUSED(c); } void QmlDebugger::setDebugObject(QObject *obj) diff --git a/src/declarative/debugger/qmlpropertyview.cpp b/src/declarative/debugger/qmlpropertyview.cpp index 0d34fd9..abe1902 100644 --- a/src/declarative/debugger/qmlpropertyview.cpp +++ b/src/declarative/debugger/qmlpropertyview.cpp @@ -210,7 +210,7 @@ void QmlPropertyView::setObject(QObject *object) ++iter) { QTreeWidgetItem *item = new QTreeWidgetItem(m_tree); - item->setText(0, iter.key()); + item->setText(0, QString::fromAscii(iter.key())); item->setForeground(0, Qt::blue); item->setText(1, iter.value()); } diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index eb24b91..6b6e1e2 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -162,7 +162,7 @@ private: int ctxt); void finalizeComponent(int patch); - class BindingReference; + struct BindingReference; void finalizeBinding(const BindingReference &); struct IdReference { -- cgit v0.12 From 5be3335436501c5e0d3f5cb047edba1371aeb187 Mon Sep 17 00:00:00 2001 From: Harald Fernengel Date: Tue, 2 Jun 2009 15:02:00 +0200 Subject: Use a QVarLengthArray instead of some hacky self-made container This won't leak on error case, and will work with arbitrary sizes. Also changed from int to short as instructed by Samuel. Reviewed-by: Samuel --- src/gui/painting/qpaintengine_raster.cpp | 15 +++------------ 1 file changed, 3 insertions(+), 12 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 847904b..58ffb02 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -3876,11 +3876,7 @@ static void qt_merge_clip(const QClipData *c1, const QClipData *c2, QClipData *r { Q_ASSERT(c1->clipSpanHeight == c2->clipSpanHeight && c1->clipSpanHeight == result->clipSpanHeight); - // ### buffer overflow possible - const int BUFFER_SIZE = 4096; - int buffer[BUFFER_SIZE]; - int *b = buffer; - int bsize = BUFFER_SIZE; + QVarLengthArray buffer; QClipData::ClipLine *c1ClipLines = const_cast(c1)->clipLines(); QClipData::ClipLine *c2ClipLines = const_cast(c2)->clipLines(); @@ -3907,11 +3903,8 @@ static void qt_merge_clip(const QClipData *c1, const QClipData *c2, QClipData *r // find required length int max = qMax(c1_spans[c1_count - 1].x + c1_spans[c1_count - 1].len, c2_spans[c2_count - 1].x + c2_spans[c2_count - 1].len); - if (max > bsize) { - b = (int *)realloc(bsize == BUFFER_SIZE ? 0 : b, max*sizeof(int)); - bsize = max; - } - memset(buffer, 0, BUFFER_SIZE * sizeof(int)); + buffer.resize(max); + memset(buffer.data(), 0, buffer.size() * sizeof(short)); // Fill with old spans. for (int i = 0; i < c1_count; ++i) { @@ -3947,8 +3940,6 @@ static void qt_merge_clip(const QClipData *c1, const QClipData *c2, QClipData *r result->appendSpan(sx, x - sx, y, coverage); } } - if (b != buffer) - free(b); } void QRasterPaintEnginePrivate::initializeRasterizer(QSpanData *data) -- cgit v0.12 From 7a095c52057633e9050e74622f8a990738c2741b Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 2 Jun 2009 15:20:04 +0200 Subject: Fixed aspect ratio on Windows - When changing the aspect ratio, the video wouldn't update. - The VMR9 can in some cases try to manage the aspect ratio itself and then fights our system. This is now disabled. --- src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp | 1 + src/3rdparty/phonon/ds9/videowidget.cpp | 2 ++ 2 files changed, 3 insertions(+) diff --git a/src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp b/src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp index 298e9fa..81ebb8b 100644 --- a/src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp +++ b/src/3rdparty/phonon/ds9/videorenderer_vmr9.cpp @@ -169,6 +169,7 @@ namespace Phonon Q_ASSERT(SUCCEEDED(hr)); ComPointer windowlessControl(m_filter, IID_IVMRWindowlessControl9); windowlessControl->SetVideoClippingWindow(reinterpret_cast(target->winId())); + windowlessControl->SetAspectRatioMode(VMR9ARMode_None); //we're in control of the size } QImage VideoRendererVMR9::snapshot() const diff --git a/src/3rdparty/phonon/ds9/videowidget.cpp b/src/3rdparty/phonon/ds9/videowidget.cpp index de7ce5f..0ef653f 100644 --- a/src/3rdparty/phonon/ds9/videowidget.cpp +++ b/src/3rdparty/phonon/ds9/videowidget.cpp @@ -261,6 +261,7 @@ namespace Phonon { m_aspectRatio = aspectRatio; updateVideoSize(); + m_widget->update(); } Phonon::VideoWidget::ScaleMode VideoWidget::scaleMode() const @@ -279,6 +280,7 @@ namespace Phonon { m_scaleMode = scaleMode; updateVideoSize(); + m_widget->update(); } void VideoWidget::setBrightness(qreal b) -- cgit v0.12 From d7700105933b3c4071f8df524915dbaa2092d82b Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Tue, 2 Jun 2009 15:48:27 +0200 Subject: Correct invalid font. QFont() returns the app font, not an invalid font. --- tests/auto/qcssparser/tst_cssparser.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/auto/qcssparser/tst_cssparser.cpp b/tests/auto/qcssparser/tst_cssparser.cpp index 7c4fac1..b41a745 100644 --- a/tests/auto/qcssparser/tst_cssparser.cpp +++ b/tests/auto/qcssparser/tst_cssparser.cpp @@ -1475,7 +1475,7 @@ void tst_CssParser::extractFontFamily_data() QTest::newRow("unquoted-family-name2") << "font-family: Times New Roman" << QString("Times New Roman"); QTest::newRow("multiple") << "font-family: Times New Roman , foobar, 'baz'" << QString("Times New Roman"); QTest::newRow("multiple2") << "font-family: invalid, Times New Roman " << QString("Times New Roman"); - QTest::newRow("invalid") << "font-family: invalid" << QFont().family(); + QTest::newRow("invalid") << "font-family: invalid" << QFontInfo(QFont("invalid font")).family(); QTest::newRow("shorthand") << "font: 12pt Times New Roman" << QString("Times New Roman"); QTest::newRow("shorthand multiple quote") << "font: 12pt invalid, \"Times New Roman\" " << QString("Times New Roman"); QTest::newRow("shorthand multiple") << "font: 12pt invalid, Times New Roman " << QString("Times New Roman"); -- cgit v0.12 From ad46e77420449ede2cb6c1ea2a810a2614520db9 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Tue, 2 Jun 2009 16:09:58 +0200 Subject: BT: Remove duplicate code and fix font parsing. QFont has a feature that you can pass a comma-separated list and it will walk through the list and match the font that it hits first. There's a nice static function that X11 and Windows uses, but the Mac was using an older copied version of it. This old version didn't handle quoting which is what happens in the style sheet. So, using the same code makes everything work well. As a bonus, Creator looks correct again. Reviewed-by: Simon Hausmann --- src/gui/text/qfontdatabase.cpp | 2 +- src/gui/text/qfontdatabase_mac.cpp | 9 +-------- 2 files changed, 2 insertions(+), 9 deletions(-) diff --git a/src/gui/text/qfontdatabase.cpp b/src/gui/text/qfontdatabase.cpp index c3fc9f5..5fb294f 100644 --- a/src/gui/text/qfontdatabase.cpp +++ b/src/gui/text/qfontdatabase.cpp @@ -827,6 +827,7 @@ static void getEngineData(const QFontPrivate *d, const QFontCache::Key &key) d->engineData->ref.ref(); } } +#endif static QStringList familyList(const QFontDef &req) { @@ -855,7 +856,6 @@ static QStringList familyList(const QFontDef &req) return family_list; } -#endif Q_GLOBAL_STATIC(QFontDatabasePrivate, privateDb) Q_GLOBAL_STATIC_WITH_ARGS(QMutex, fontDatabaseMutex, (QMutex::Recursive)) diff --git a/src/gui/text/qfontdatabase_mac.cpp b/src/gui/text/qfontdatabase_mac.cpp index 80ddbd5..26d8687 100644 --- a/src/gui/text/qfontdatabase_mac.cpp +++ b/src/gui/text/qfontdatabase_mac.cpp @@ -281,14 +281,7 @@ void QFontDatabase::load(const QFontPrivate *d, int script) } //find the font - QStringList family_list = req.family.split(QLatin1Char(',')); - // append the substitute list for each family in family_list - { - QStringList subs_list; - for(QStringList::ConstIterator it = family_list.constBegin(); it != family_list.constEnd(); ++it) - subs_list += QFont::substitutes(*it); - family_list += subs_list; - } + QStringList family_list = familyList(req); const char *stylehint = styleHint(req); if (stylehint) -- cgit v0.12 From 1a7da7096bbda17197738061902f4489af234bc0 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Tue, 2 Jun 2009 14:59:17 +0200 Subject: Setting a focus on a widget hierarchy which contains both visible and invisible widgets could cause a crash. Also, when there is a widget hierarchy A->B->C and A and C are marked as visible but B is hidden, when the user gives focus explicitely to C, we should remember that and respect it when B becomes visible. Task-number: 254563 Reviewed-by: Thierry Bastian --- src/gui/kernel/qwidget.cpp | 11 ++++++++++- tests/auto/qwidget/tst_qwidget.cpp | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index 5538c11..d436ffb 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -5674,10 +5674,15 @@ void QWidget::setFocus(Qt::FocusReason reason) w = w->isWindow() ? 0 : w->parentWidget(); } } else { - while (w) { + while (w && w->isVisible()) { w->d_func()->focus_child = f; w = w->isWindow() ? 0 : w->parentWidget(); } + // a special case, if there is an invisible parent, notify him + // about the focus_child widget, so that if it becomes + // visible, the focus widget will be respected. + if (w) + w->d_func()->focus_child = f; } #ifndef QT_NO_GRAPHICSVIEW @@ -6729,6 +6734,10 @@ void QWidgetPrivate::show_helper() if (QApplicationPrivate::hidden_focus_widget == q) { QApplicationPrivate::hidden_focus_widget = 0; q->setFocus(Qt::OtherFocusReason); + } else if (focus_child) { + // if we are shown and there is an explicit focus child widget + // set, respect it by giving him focus. + focus_child->setFocus(Qt::OtherFocusReason); } // Process events when showing a Qt::SplashScreen widget before the event loop diff --git a/tests/auto/qwidget/tst_qwidget.cpp b/tests/auto/qwidget/tst_qwidget.cpp index 23ead01..3fad366 100644 --- a/tests/auto/qwidget/tst_qwidget.cpp +++ b/tests/auto/qwidget/tst_qwidget.cpp @@ -350,6 +350,9 @@ private slots: void updateOnDestroyedSignal(); void toplevelLineEditFocus(); + void focusWidget_task254563(); + void focusWidget_mixed_widget_hierarchy(); + private: bool ensureScreenSize(int width, int height); QWidget *testWidget; @@ -8977,5 +8980,37 @@ void tst_QWidget::toplevelLineEditFocus() QCOMPARE(QApplication::focusWidget(), &w); } +void tst_QWidget::focusWidget_task254563() +{ + //having different visibility for widget is important + QWidget top; + top.show(); + QWidget container(&top); + QWidget *widget = new QWidget(&container); + widget->show(); + + widget->setFocus(); //set focus (will set the focus widget up to the toplevel to be 'widget') + container.setFocus(); + delete widget; // will call clearFocus but that doesn't help + QVERIFY(top.focusWidget() != widget); //dangling pointer +} + +void tst_QWidget::focusWidget_mixed_widget_hierarchy() +{ + QWidget top; + top.show(); + QWidget notvisible(&top); + QWidget *visible = new QWidget(¬visible); + visible->show(); + + visible->setFocus(); + notvisible.setFocus(); + notvisible.show(); + QCOMPARE(top.focusWidget(), visible); + QCOMPARE(notvisible.focusWidget(), visible); + QCOMPARE(visible->focusWidget(), visible); +} + + QTEST_MAIN(tst_QWidget) #include "tst_qwidget.moc" -- cgit v0.12 From a5b11b9031f9a2a97b65e9a6134244249845491a Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Tue, 2 Jun 2009 16:29:57 +0200 Subject: Avoid a crash when setting a focus in a widget hierarchy containing both visible and invisible widgets. This is a quick hack to avoid a crash in Qt when setting a focus on a visible widget that has invisible parent. Proper fix was committed into master 1a7da7096bbda17197738061902f4489af234bc0, see it's description for more details. Task-number: 254563 Reviewed-by: Thierry Bastian --- src/gui/kernel/qwidget.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index bbf6758..baf3278 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -5804,8 +5804,9 @@ void QWidget::setFocus(Qt::FocusReason reason) void QWidget::clearFocus() { QWidget *w = this; - while (w && w->d_func()->focus_child == this) { - w->d_func()->focus_child = 0; + while (w) { + if (w->d_func()->focus_child == this) + w->d_func()->focus_child = 0; w = w->parentWidget(); } #ifndef QT_NO_GRAPHICSVIEW -- cgit v0.12 From 0068bd9279b5f7a12f00ffea66cb264930f88138 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Tue, 2 Jun 2009 16:29:32 +0200 Subject: missing deployment rule added to examples/richtext/textobject The example SVG must be deployed on Windows CE devices to be used. Reviewed-by: mauricek BT: yes --- examples/richtext/textobject/textobject.pro | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/examples/richtext/textobject/textobject.pro b/examples/richtext/textobject/textobject.pro index fbb809c..4fa9cb0 100644 --- a/examples/richtext/textobject/textobject.pro +++ b/examples/richtext/textobject/textobject.pro @@ -12,3 +12,7 @@ sources.files = $$SOURCES $$HEADERS *.pro sources.path = $$[QT_INSTALL_EXAMPLES]/richtext/textobject INSTALLS += target sources +filesToDeploy.sources = files/*.svg +filesToDeploy.path = files +DEPLOYMENT += filesToDeploy + -- cgit v0.12 From d69f28f00fe7efda12f9bb236ecd6a0de39232e4 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Tue, 2 Jun 2009 16:50:57 +0200 Subject: my changes for 4.5.2 --- dist/changes-4.5.2 | 1 + 1 file changed, 1 insertion(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index c87ad92..f5e93f8 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -128,6 +128,7 @@ Qt for Embedded Linux Qt for Windows CE ----------------- +[248846] handle the back soft key on Windows mobile. **************************************************************************** -- cgit v0.12 From be833a4f25a8ec8c3dd7a8ac4fa4b0507c93e7ee Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Tue, 2 Jun 2009 16:51:04 +0200 Subject: Revert "Avoid a crash when setting a focus in a widget hierarchy containing" This reverts commit a5b11b9031f9a2a97b65e9a6134244249845491a. The proper fix is 1a7da7096bbda17197738061902f4489af234bc0. --- src/gui/kernel/qwidget.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index 451686f..d436ffb 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -5757,9 +5757,8 @@ void QWidget::setFocus(Qt::FocusReason reason) void QWidget::clearFocus() { QWidget *w = this; - while (w) { - if (w->d_func()->focus_child == this) - w->d_func()->focus_child = 0; + while (w && w->d_func()->focus_child == this) { + w->d_func()->focus_child = 0; w = w->parentWidget(); } #ifndef QT_NO_GRAPHICSVIEW -- cgit v0.12 From e8c6c0cf4d341572e4740940590b0301d208d239 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Tue, 2 Jun 2009 17:17:16 +0200 Subject: Update my changelog for 4.5.2 --- dist/changes-4.5.2 | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index f5e93f8..5149eba 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -46,9 +46,23 @@ Third party components Plugins (r41346, r43550, r43915, r43917, r43923) Clipboard (r41360) +- QAbstractItemView + * [250754] Changing the font of the view would not update the size of the + items if there is an application stylesheet. + * [252532] Pressing enter in a QPlainTextEdit embedded on a itemview now + insert a newline + - QAbstractNetworkCache * Only cache responses to HTTP GET by default, not HTTP PUT or POST +- QComboBox + * [253944] Changing the style doesn't reset custom item delegate anymore. + * [254589] Fixed the frame appearing if setting a stylesheet with a border + on the embedded itemview while there is a stylesheet on the application + +- QDir + * Fix reentrency (listing directories in different threads) + - QMacStyle * [253339] Don't draw arrows on toolbuttons that have a menu and text only. * [252301] Ensure that small and mini spin boxes are drawn correctly. @@ -68,6 +82,10 @@ Third party components * [253448] Prevent a crash when using the Qt::WA_MacBrushedMetal attribute in conjunction with style sheets. +- QObject + * Fixed possible race condition if two QObject connected together with + signals and slot are destroyed in different threads + - QPainter * [253783] Fixed text shaping bugs when using ligatures and different scripts in a single text item. @@ -78,16 +96,37 @@ Third party components * [251534] Fixed issue where text with non-opaque color from widget palette would be blitted instead of blended. +- QSelectionModel + * [252069] fix QSelectionModel::rowIntersectsSelection or QSelectionModel::columnsIntersectsSelection not reporting right result if some items are disabled. + +- QSortFilterProxyModel + * [250023] Fixes QSortFilterProxyModel not reporting child if the model + need to fetchMore + * [251296] In dynamic filter model, childs of temporarly filtered items + where not correctly updated. + * [252507] Show a warning instead of crashing if invalid indexes are passed. + * [254234] Fixed setDynamicSortFilter not working when setting the model initially + +- QString + * Fixed reentrency of QString::squeeze() + - QTransform * Fixed issue in QTransform::type() causing a projective transform to be treated as a scaling transform. +- QVector + * Fixed reentrency of QVector::reserve() + - QtOpenGL * [247083] Re-enabled antialiasing for large font sizes in OpenGL paint engine. * [251485] Fixed crash that could occur with projective transforms and high quality antialiasing. +- QCssParser + * [252311] "font-family:" now handle fallback font specified with a comas + separated list. + **************************************************************************** * Database Drivers * **************************************************************************** -- cgit v0.12 From b3ebeff77de9f3e53bea08bfd09eac9cb3a32be3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Tue, 2 Jun 2009 17:55:58 +0200 Subject: Fixed a byte ordering issue when using the raster graphicssystem. The R and B channels were swapped on little endian machines with BGR layout. Task-number: 254934 Reviewed-by: Samuel --- src/gui/painting/qpaintengine_x11.cpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/gui/painting/qpaintengine_x11.cpp b/src/gui/painting/qpaintengine_x11.cpp index 9cc9683..2e6d593 100644 --- a/src/gui/painting/qpaintengine_x11.cpp +++ b/src/gui/painting/qpaintengine_x11.cpp @@ -1826,9 +1826,10 @@ Q_GUI_EXPORT void qt_x11_drawImage(const QRect &rect, const QPoint &pos, const Q const int h = rect.height(); QImage im; - if ((QSysInfo::ByteOrder == QSysInfo::BigEndian - && ((ImageByteOrder(X11->display) == LSBFirst) || bgr_layout)) - || (ImageByteOrder(X11->display) == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian)) + int image_byte_order = ImageByteOrder(X11->display); + if ((QSysInfo::ByteOrder == QSysInfo::BigEndian && ((image_byte_order == LSBFirst) || bgr_layout)) + || (image_byte_order == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian) + || (image_byte_order == LSBFirst && bgr_layout)) { im = image.copy(rect); const int iw = im.bytesPerLine() / 4; @@ -1836,19 +1837,21 @@ Q_GUI_EXPORT void qt_x11_drawImage(const QRect &rect, const QPoint &pos, const Q for (int i=0; i < h; i++) { uint *p = data; uint *end = p + w; - if (bgr_layout && ImageByteOrder(X11->display) == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian) { + if (bgr_layout && image_byte_order == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian) { while (p < end) { *p = ((*p << 8) & 0xffffff00) | ((*p >> 24) & 0x000000ff); p++; } - } else if ((ImageByteOrder(X11->display) == LSBFirst && QSysInfo::ByteOrder == QSysInfo::BigEndian) - || (ImageByteOrder(X11->display) == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian)) { + } else if ((image_byte_order == LSBFirst && QSysInfo::ByteOrder == QSysInfo::BigEndian) + || (image_byte_order == MSBFirst && QSysInfo::ByteOrder == QSysInfo::LittleEndian)) { while (p < end) { *p = ((*p << 24) & 0xff000000) | ((*p << 8) & 0x00ff0000) | ((*p >> 8) & 0x0000ff00) | ((*p >> 24) & 0x000000ff); p++; } - } else if (ImageByteOrder(X11->display) == MSBFirst && QSysInfo::ByteOrder == QSysInfo::BigEndian) { + } else if ((image_byte_order == MSBFirst && QSysInfo::ByteOrder == QSysInfo::BigEndian) + || (image_byte_order == LSBFirst && bgr_layout)) + { while (p < end) { *p = ((*p << 16) & 0x00ff0000) | ((*p >> 16) & 0x000000ff) | ((*p ) & 0xff00ff00); -- cgit v0.12 From 2b051b2a7dce75eee10c166edffb41a3b56b4a27 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Tue, 2 Jun 2009 18:33:28 +0200 Subject: Merged changes to the string builder class. Reviewed-by: Trust Me --- src/corelib/tools/qstringbuilder.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/corelib/tools/qstringbuilder.cpp b/src/corelib/tools/qstringbuilder.cpp index 2b4a242..4f24f76 100644 --- a/src/corelib/tools/qstringbuilder.cpp +++ b/src/corelib/tools/qstringbuilder.cpp @@ -64,7 +64,7 @@ \sa QStringBuilder, QLatin1String, QString, QStringRef */ -/*! \fn QLatin1Literal::QLatin1Literal(const char(&string)[]) +/*! \fn QLatin1Literal::QLatin1Literal(const char(&string)[N]) Constructs a new literal from the given \a string. */ @@ -93,7 +93,7 @@ \reentrant \since 4.6 - \brief QStringBuilder is a template class that provides a facility to build + \brief The QStringBuilder class is a template class that provides a facility to build up QStrings from smaller chunks. \ingroup tools @@ -102,7 +102,7 @@ \mainclass When creating strings from smaller chunks, typically \c QString::operator+() - is used, resulting in \i{n - 1} reallocations when operating on \i{n} chunks. + is used, resulting in \e{n - 1} reallocations when operating on \e{n} chunks. QStringBuilder uses expression templates to collect the individual parts, compute the total size, allocate memory for the resulting QString object, -- cgit v0.12 From d37de8e085bdc3ee5d0185b403879bac485ef834 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Tue, 2 Jun 2009 20:07:04 +0200 Subject: Doc: Modified the property documentation to relax the restriction on const getter functions. Task-number: 254722 Reviewed-by: Trust Me --- doc/src/properties.qdoc | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/doc/src/properties.qdoc b/doc/src/properties.qdoc index d934f13..0251d3f 100644 --- a/doc/src/properties.qdoc +++ b/doc/src/properties.qdoc @@ -71,10 +71,10 @@ \list \o A \c READ accessor function is required. It is for reading the - property value. It must be const and must return either the - property's type or a pointer or reference to that type. e.g., - QWidget::focus is a read-only property with \c READ function - QWidget::hasFocus(). + property value. Ideally, a const function is used for this purpose, + and it must return either the property's type or a pointer or + reference to that type. e.g., QWidget::focus is a read-only property + with \c READ function, QWidget::hasFocus(). \o A \c WRITE accessor function is optional. It is for setting the property value. It must return void and must take exactly one -- cgit v0.12 From bb30e5e9e3d46c4e532d397db80ff90384b8b453 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Wed, 3 Jun 2009 09:06:56 +1000 Subject: Handle double clicks in TextEdit. --- src/declarative/fx/qfxtextedit.cpp | 12 ++++++++++++ src/declarative/fx/qfxtextedit.h | 1 + 2 files changed, 13 insertions(+) diff --git a/src/declarative/fx/qfxtextedit.cpp b/src/declarative/fx/qfxtextedit.cpp index c7a7700..79e1a3f 100644 --- a/src/declarative/fx/qfxtextedit.cpp +++ b/src/declarative/fx/qfxtextedit.cpp @@ -772,6 +772,18 @@ void QFxTextEdit::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) \overload Handles the given mouse \a event. */ +void QFxTextEdit::mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event) +{ + Q_D(QFxTextEdit); + d->control->processEvent(event, QPointF(0, 0)); + if (!event->isAccepted()) + QFxPaintedItem::mouseDoubleClickEvent(event); +} + +/*! +\overload +Handles the given mouse \a event. +*/ void QFxTextEdit::mouseMoveEvent(QGraphicsSceneMouseEvent *event) { Q_D(QFxTextEdit); diff --git a/src/declarative/fx/qfxtextedit.h b/src/declarative/fx/qfxtextedit.h index e30b9ed..b761a1b 100644 --- a/src/declarative/fx/qfxtextedit.h +++ b/src/declarative/fx/qfxtextedit.h @@ -190,6 +190,7 @@ protected: // mouse filter? void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); + void mouseDoubleClickEvent(QGraphicsSceneMouseEvent *event); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void inputMethodEvent(QInputMethodEvent *e); -- cgit v0.12 From bc45ef6135b6a01d7fa601765647f2607ee047c8 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 3 Jun 2009 11:56:45 +1000 Subject: OpenGL perf improvements --- src/declarative/canvas/qsimplecanvas.cpp | 3 + src/declarative/canvas/qsimplecanvas_opengl.cpp | 187 +++++++++---- src/declarative/canvas/qsimplecanvasitem.cpp | 4 +- src/declarative/canvas/qsimplecanvasitem.h | 11 +- src/declarative/canvas/qsimplecanvasitem_p.h | 4 +- src/declarative/fx/qfximage.cpp | 348 ++++++++++-------------- src/declarative/fx/qfxrect.cpp | 312 ++++++++------------- src/declarative/fx/qfxtext.cpp | 92 +------ src/declarative/opengl/gltexture.cpp | 65 +++-- src/declarative/opengl/gltexture.h | 5 +- 10 files changed, 473 insertions(+), 558 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvas.cpp b/src/declarative/canvas/qsimplecanvas.cpp index 59edf74..f1ff61b 100644 --- a/src/declarative/canvas/qsimplecanvas.cpp +++ b/src/declarative/canvas/qsimplecanvas.cpp @@ -921,6 +921,9 @@ bool QSimpleCanvas::event(QEvent *e) #if defined(QFX_RENDER_OPENGL1) unsigned int zero = 0; d->root->d_func()->setupPainting(0, rect(), &zero); +#elif defined(QFX_RENDER_OPENGL2) + ++d->paintVersion; + d->root->d_func()->setupPainting(0); #else ++d->paintVersion; d->root->d_func()->setupPainting(0, rect()); diff --git a/src/declarative/canvas/qsimplecanvas_opengl.cpp b/src/declarative/canvas/qsimplecanvas_opengl.cpp index ec809ff..dd57c14 100644 --- a/src/declarative/canvas/qsimplecanvas_opengl.cpp +++ b/src/declarative/canvas/qsimplecanvas_opengl.cpp @@ -52,7 +52,7 @@ QT_BEGIN_NAMESPACE void CanvasEGLWidget::paintGL() { - glClearColor(0.0f, 0.0f, 0.0f, 1.0f); + glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); _canvas->paintGL(); @@ -112,13 +112,16 @@ void QSimpleCanvasPrivate::paintGL() lrpTimer.start(); QSimpleCanvasItemPrivate::GLPaintParameters p; + QSimpleCanvasItem::GLPainter painter; + p.sceneRect = QRect(0, 0, q->width(), q->height()); p.clipRect = p.sceneRect; p.stencilValue = 0; p.opacity = 1; p.forceParamRefresh = false; - if (!isSetup) - root->d_func()->setupPainting(0, QRect()); + p.painter = &painter; + if (!isSetup) + root->d_func()->setupPainting(0); root->d_func()->paint(p); lrpTime = lrpTimer.elapsed(); @@ -195,7 +198,8 @@ void QSimpleCanvasItemPrivate::simplePaintChild(const GLPaintParameters ¶ms, childParams.boundingRect = child->boundingRect(); if (child->filter() && child->filter()->enabled()) { - QSimpleCanvasItem::GLPainter painter(q); + QSimpleCanvasItem::GLPainter &painter = *params.painter; + painter.item = q; painter.activeTransform = child->d_func()->data()->transformActive; painter.activeOpacity = child->d_func()->data()->activeOpacity; painter.sceneClipRect = params.clipRect; @@ -229,34 +233,35 @@ void QSimpleCanvasItemPrivate::setupChildState(QSimpleCanvasItem *child) QSimpleCanvasItemData *const childData = childPrivate->data(); childData->activeOpacity = myData->activeOpacity; - if (childData->visible != 1) + if (childData->visible != 1.) childData->activeOpacity *= childData->visible; - if (childData->activeOpacity != 0) { + if (childData->activeOpacity != 0.) { + QSimpleCanvas::Matrix &am = childData->transformActive; + am = myData->transformActive; + // Calculate child's transform const qreal x = childData->x; const qreal y = childData->y; const qreal scale = childPrivate->scale; QSimpleCanvasItem::Flip flip = childData->flip; - QSimpleCanvas::Matrix &am = childData->transformActive; - am = myData->transformActive; if (x != 0. || y != 0.) am.translate(x, y); if (scale != 1.) { - QPointF to = childPrivate->transformOrigin(); - bool translate = (to.x() != 0. || to.y() != 0.); - if (translate) + if (childPrivate->origin == QSimpleCanvasItem::TopLeft) { + am.scale(scale, scale); + } else { + QPointF to = childPrivate->transformOrigin(); am.translate(to.x(), to.y()); - am.scale(scale, scale); - if (translate) + am.scale(scale, scale); am.translate(-to.x(), -to.y()); + } } if (childData->transformUser) am *= *childData->transformUser; - if (flip) { QRectF br = child->boundingRect(); am.translate(br.width() / 2., br.height() / 2); @@ -268,8 +273,10 @@ void QSimpleCanvasItemPrivate::setupChildState(QSimpleCanvasItem *child) } } -QRectF QSimpleCanvasItemPrivate::setupPainting(int version, const QRect &bounding) +//#define QSIMPLECANVAS_DISABLE_TREE_CLIPPING +QRectF QSimpleCanvasItemPrivate::setupPainting(int version) { + static QRectF scene(-1., -1., 2., 2.); Q_Q(QSimpleCanvasItem); bool hasContents = options & QSimpleCanvasItem::HasContents; @@ -285,17 +292,34 @@ QRectF QSimpleCanvasItemPrivate::setupPainting(int version, const QRect &boundin rv = active.mapRect(filteredBoundRect); } - - for (int ii = 0; ii < children.count(); ++ii) { - QSimpleCanvasItem *child = children.at(ii); - setupChildState(child); - - QSimpleCanvasItemData *childData = child->d_func()->data(); - if (childData->activeOpacity != 0) - rv |= child->d_func()->setupPainting(version, bounding); - } +#ifdef QSIMPLECANVAS_DISABLE_TREE_CLIPPING + myData->doNotPaint = false; + myData->doNotPaintChildren = false; +#else + myData->doNotPaint = !hasContents || !rv.intersects(scene); + myData->doNotPaintChildren = hasContents && myData->doNotPaint && + (clip != QSimpleCanvasItem::NoClip); +#endif + + if (myData->doNotPaintChildren) { + rv = QRectF(); + } else { + for (int ii = 0; ii < children.count(); ++ii) { + QSimpleCanvasItem *child = children.at(ii); + setupChildState(child); + + QSimpleCanvasItemData *childData = child->d_func()->data(); + if (childData->activeOpacity != 0) + rv |= child->d_func()->setupPainting(version); + } + +#ifndef QSIMPLECANVAS_DISABLE_TREE_CLIPPING + myData->doNotPaintChildren |= !rv.intersects(scene); +#endif + } myData->lastPaintRect = rv; + return rv; } @@ -306,6 +330,10 @@ void QSimpleCanvasItemPrivate::paint(GLPaintParameters &oldParams, QSimpleCanvas Q_Q(QSimpleCanvasItem); + bool doNotPaintChildren = data()->doNotPaintChildren; + if (doNotPaintChildren) + return; + GLPaintParameters params = oldParams; qreal width = params.boundingRect.width(); @@ -327,12 +355,12 @@ void QSimpleCanvasItemPrivate::paint(GLPaintParameters &oldParams, QSimpleCanvas glStencilOp(GL_KEEP, GL_KEEP, GL_INCR); ConstantColorShader *shader = basicShaders()->constantColor(); + params.painter->invalidate(); shader->enable(); shader->setTransform(data()->transformActive); shader->setAttributeArray(ConstantColorShader::Vertices, vertices, 2); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - shader->disableAttributeArray(ConstantColorShader::Vertices); glStencilFunc(GL_EQUAL, params.stencilValue + 1, 0xFFFFFFFF); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); @@ -369,9 +397,11 @@ void QSimpleCanvasItemPrivate::paint(GLPaintParameters &oldParams, QSimpleCanvas } } - if (layer & QSimpleCanvasFilter::Item && - q->options() & QSimpleCanvasItem::HasContents) { - QSimpleCanvasItem::GLPainter painter(q); + bool doNotPaint = data()->doNotPaint; + + if (!doNotPaint && layer & QSimpleCanvasFilter::Item) { + QSimpleCanvasItem::GLPainter &painter = *params.painter; + painter.item = q; painter.activeTransform = data()->transformActive; painter.activeOpacity = data()->activeOpacity; painter.sceneClipRect = params.clipRect; @@ -390,14 +420,14 @@ void QSimpleCanvasItemPrivate::paint(GLPaintParameters &oldParams, QSimpleCanvas glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); glStencilFunc(GL_EQUAL, params.stencilValue + 1, 0xFFFFFFFF); glStencilOp(GL_KEEP, GL_KEEP, GL_DECR); - + + params.painter->invalidate(); ConstantColorShader *shader = basicShaders()->constantColor(); shader->enable(); shader->setTransform(data()->transformActive); shader->setAttributeArray(ConstantColorShader::Vertices, vertices, 2); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - shader->disableAttributeArray(ConstantColorShader::Vertices); glStencilFunc(GL_EQUAL, params.stencilValue, 0xFFFFFFFF); glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP); @@ -405,43 +435,76 @@ void QSimpleCanvasItemPrivate::paint(GLPaintParameters &oldParams, QSimpleCanvas } } +enum ShaderType { ST_None, ST_SingleTexture, ST_SingleTextureOpacity, ST_Color }; + +QSimpleCanvasItem::GLPainter::GLPainter() +: item(0), activeOpacity(1), flags(0) +{ +} + +QSimpleCanvasItem::GLPainter::GLPainter(QSimpleCanvasItem *i) +: item(i), activeOpacity(1), flags(0) +{ +} + QGLShaderProgram *QSimpleCanvasItem::GLPainter::useTextureShader() { if (activeOpacity == 1.) { - item->basicShaders()->singleTexture()->enable(); - item->basicShaders()->singleTexture()->setTransform(activeTransform); - return item->basicShaders()->singleTexture(); + SingleTextureShader *shader = item->basicShaders()->singleTexture(); + if (flags != ST_SingleTexture) { + shader->enable(); + flags = ST_SingleTexture; + } + + shader->setTransform(activeTransform); + return shader; } else { - item->basicShaders()->singleTextureOpacity()->enable(); - item->basicShaders()->singleTextureOpacity()->setTransform(activeTransform); - item->basicShaders()->singleTextureOpacity()->setOpacity(activeOpacity); - return item->basicShaders()->singleTextureOpacity(); + SingleTextureOpacityShader *shader = item->basicShaders()->singleTextureOpacity(); + + if (flags != ST_SingleTextureOpacity) { + shader->enable(); + flags = ST_SingleTextureOpacity; + } + + shader->setTransform(activeTransform); + shader->setOpacity(activeOpacity); + return shader; } +} +void QSimpleCanvasItem::GLPainter::invalidate() +{ + flags = ST_None; } QGLShaderProgram *QSimpleCanvasItem::GLPainter::useColorShader(const QColor &color) { - QColor c = color; - item->basicShaders()->constantColor()->enable(); - if (activeOpacity != 1.) { - c.setAlpha(int(c.alpha() * activeOpacity)); + QColor c = color; + + ConstantColorShader *shader = item->basicShaders()->constantColor(); + + if (flags != ST_Color) { + shader->enable(); + flags = ST_Color; } - item->basicShaders()->constantColor()->setColor(c); - item->basicShaders()->constantColor()->setTransform(activeTransform); + if (activeOpacity != 1.) + c.setAlpha(int(c.alpha() * activeOpacity)); + + shader->setColor(c); + shader->setTransform(activeTransform); - return item->basicShaders()->constantColor(); + return shader; } -void QSimpleCanvasItem::GLPainter::drawPixmap(const QPointF &point, - const GLTexture &texture) +void QSimpleCanvasItem::GLPainter::drawPixmap(const QPointF &point, + const GLTexture &texture) { drawPixmap(QRectF(point, QSizeF(texture.width(), texture.height())), texture); } -void QSimpleCanvasItem::GLPainter::drawPixmap(const QRectF &rect, - const GLTexture &img) +void QSimpleCanvasItem::GLPainter::drawPixmap(const QRectF &rect, + const GLTexture &img) { QGLShaderProgram *shader = useTextureShader(); @@ -466,9 +529,33 @@ void QSimpleCanvasItem::GLPainter::drawPixmap(const QRectF &rect, glBindTexture(GL_TEXTURE_2D, img.texture()); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); +} + +void QSimpleCanvasItem::GLPainter::fillRect(const QRectF &rect, + const QColor &color) +{ + if (color.alpha() == 0xFF) + glDisable(GL_BLEND); + + QGLShaderProgram *shader = useColorShader(color); + float x = rect.x(); + float y = rect.y(); + float width = rect.width(); + float height = rect.height(); + + GLfloat vertices[] = { x, height, + width, height, + x, y, + + width, height, + x, y, + width, y }; + + shader->setAttributeArray(ConstantColorShader::Vertices, vertices, 2); + glDrawArrays(GL_TRIANGLES, 0, 6); - shader->disableAttributeArray(SingleTextureShader::Vertices); - shader->disableAttributeArray(SingleTextureShader::TextureCoords); + if (color.alpha() == 0xFF) + glEnable(GL_BLEND); } QT_END_NAMESPACE diff --git a/src/declarative/canvas/qsimplecanvasitem.cpp b/src/declarative/canvas/qsimplecanvasitem.cpp index f2222a9..7451a5f 100644 --- a/src/declarative/canvas/qsimplecanvasitem.cpp +++ b/src/declarative/canvas/qsimplecanvasitem.cpp @@ -51,8 +51,8 @@ QT_BEGIN_NAMESPACE QSimpleCanvasItemData::QSimpleCanvasItemData() : buttons(Qt::NoButton), flip(QSimpleCanvasItem::NoFlip), dirty(false), transformValid(true), doNotPaint(false), - doNotPaintChildren(false), x(0), y(0), z(0), visible(1), - transformUser(0), transformVersion(0), activeOpacity(1) + doNotPaintChildren(false), x(0), y(0), z(0), + visible(1), transformUser(0), transformVersion(0), activeOpacity(1) { } diff --git a/src/declarative/canvas/qsimplecanvasitem.h b/src/declarative/canvas/qsimplecanvasitem.h index f817799..68219de 100644 --- a/src/declarative/canvas/qsimplecanvasitem.h +++ b/src/declarative/canvas/qsimplecanvasitem.h @@ -167,7 +167,8 @@ public: class GLPainter { public: - GLPainter(QSimpleCanvasItem *i) : item(i), activeOpacity(1) {} + GLPainter(); + GLPainter(QSimpleCanvasItem *i); QSimpleCanvasItem *item; QSimpleCanvas::Matrix activeTransform; qreal activeOpacity; @@ -175,9 +176,13 @@ public: QGLShaderProgram *useTextureShader(); QGLShaderProgram *useColorShader(const QColor &); - void drawPixmap(const QPointF &, const GLTexture &); - void drawPixmap(const QRectF &, const GLTexture &); + void drawPixmap(const QPointF &, const GLTexture &); + void drawPixmap(const QRectF &, const GLTexture &); + void fillRect(const QRectF &, const QColor &); + + void invalidate(); private: + int flags; GLPainter(const GLPainter &); GLPainter &operator=(const GLPainter &); }; diff --git a/src/declarative/canvas/qsimplecanvasitem_p.h b/src/declarative/canvas/qsimplecanvasitem_p.h index e2deab2..27ee0a2 100644 --- a/src/declarative/canvas/qsimplecanvasitem_p.h +++ b/src/declarative/canvas/qsimplecanvasitem_p.h @@ -218,9 +218,11 @@ public: #endif float opacity; bool forceParamRefresh; + + QSimpleCanvasItem::GLPainter *painter; }; #if defined(QFX_RENDER_OPENGL2) - QRectF setupPainting(int version, const QRect &bounding); + QRectF setupPainting(int version); #elif defined(QFX_RENDER_OPENGL1) QRectF setupPainting(int version, const QRect &bounding, unsigned int *zero); #endif diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 22e5d97..1fc84eb 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -448,9 +448,9 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, texVertices[6] = tileWidth; texVertices[7] = tileHeight; } else { texVertices[0] = 0; texVertices[1] = 0; - texVertices[2] = 1; texVertices[3] = 0; - texVertices[4] = 0; texVertices[5] = 1; - texVertices[6] = 1; texVertices[7] = 1; + texVertices[2] = d->_tex.glWidth(); texVertices[3] = 0; + texVertices[4] = 0; texVertices[5] = d->_tex.glHeight(); + texVertices[6] = d->_tex.glWidth(); texVertices[7] = d->_tex.glHeight(); } return 8; @@ -481,25 +481,57 @@ void QFxImage::paintGLContents(GLPainter &p) restoreBlend = true; } + d->checkDirty(); + if (d->_tiled || (!d->_scaleGrid || d->_scaleGrid->isNull())) { - GLfloat vertices[8]; - GLfloat texVertices[8]; - GLTexture *tex = 0; + if (!d->_tiled) { + + float widthV = width(); + float heightV = height(); + float glWidth = d->_tex.glWidth(); + float glHeight = d->_tex.glHeight(); + + float vert[] = { + 0, heightV, + widthV, heightV, + 0, 0, - QFxImage::glSimpleItemData(vertices, texVertices, &tex, 8); + widthV, heightV, + 0, 0, + widthV, 0 }; - shader->setAttributeArray(SingleTextureShader::Vertices, vertices, 2); - shader->setAttributeArray(SingleTextureShader::TextureCoords, texVertices, 2); + float tex[] = { + 0, 0, + glWidth, 0, + 0, glHeight, + + glWidth, 0, + 0, glHeight, + glWidth, glHeight + }; + + shader->setAttributeArray(SingleTextureShader::Vertices, vert, 2); + shader->setAttributeArray(SingleTextureShader::TextureCoords, tex, 2); + glBindTexture(GL_TEXTURE_2D, d->_tex.texture()); + glDrawArrays(GL_TRIANGLES, 0, 6); + + } else { - glBindTexture(GL_TEXTURE_2D, tex->texture()); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + GLfloat vertices[8]; + GLfloat texVertices[8]; + GLTexture *tex = 0; - shader->disableAttributeArray(SingleTextureShader::Vertices); - shader->disableAttributeArray(SingleTextureShader::TextureCoords); + QFxImage::glSimpleItemData(vertices, texVertices, &tex, 8); + + shader->setAttributeArray(SingleTextureShader::Vertices, vertices, 2); + shader->setAttributeArray(SingleTextureShader::TextureCoords, texVertices, 2); + + glBindTexture(GL_TEXTURE_2D, tex->texture()); + glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + } } else { - d->checkDirty(); float imgWidth = d->_pix.width(); float imgHeight = d->_pix.height(); @@ -546,235 +578,155 @@ void QFxImage::paintGLContents(GLPainter &p) float vert1[] = { 0, 0, 0, imgtop, imgleft, 0, + + 0, imgtop, + imgleft, 0, + imgleft, imgtop, + + imgleft, 0, imgleft, imgtop, imgright, 0, - imgright, imgtop, - widthV, 0, - widthV, imgtop }; - float tex1[] = { 0, 1, - 0, textop, - texleft, 1, - texleft, textop, - texright, 1, - texright, textop, - 1, 1, - 1, textop }; - float vert2[] = { 0, imgtop, - 0, imgbottom, + imgleft, imgtop, - imgleft, imgbottom, + imgright, 0, imgright, imgtop, - imgright, imgbottom, - widthV, imgtop, - widthV, imgbottom }; - float tex2[] = { 0, textop, - 0, texbottom, - texleft, textop, - texleft, texbottom, - texright, textop, - texright, texbottom, - 1, textop, - 1, texbottom }; - float vert3[] = { 0, imgbottom, - 0, heightV, - imgleft, imgbottom, - imgleft, heightV, - imgright, imgbottom, - imgright, heightV, - widthV, imgbottom, - widthV, heightV }; - float tex3[] = { 0, texbottom, - 0, 0, - texleft, texbottom, - texleft, 0, - texright, texbottom, - texright, 0, - 1, texbottom, - 1, 0 }; - - glBindTexture(GL_TEXTURE_2D, d->_tex.texture()); - shader->setAttributeArray(SingleTextureShader::Vertices, vert1, 2); - shader->setAttributeArray(SingleTextureShader::TextureCoords, tex1, 2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - shader->setAttributeArray(SingleTextureShader::Vertices, vert2, 2); - shader->setAttributeArray(SingleTextureShader::TextureCoords, tex2, 2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - shader->setAttributeArray(SingleTextureShader::Vertices, vert3, 2); - shader->setAttributeArray(SingleTextureShader::TextureCoords, tex3, 2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - - shader->disableAttributeArray(SingleTextureShader::Vertices); - shader->disableAttributeArray(SingleTextureShader::TextureCoords); - } + imgright, 0, + imgright, imgtop, + widthV, 0, - if (restoreBlend) - glEnable(GL_BLEND); -} -#elif defined(QFX_RENDER_OPENGL1) -void QFxImage::paintGLContents(GLPainter &p) -{ - Q_D(QFxImage); - if (d->_pix.isNull()) - return; + imgright, imgtop, + widthV, 0, + widthV, imgtop, - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(p.activeTransform.data()); + 0, imgtop, + 0, imgbottom, + imgleft, imgtop, - bool restoreBlend = false; - if (isOpaque() && p.activeOpacity == 1) { - glDisable(GL_BLEND); - restoreBlend = true; - } + 0, imgbottom, + imgleft, imgtop, + imgleft, imgbottom, - glEnable(GL_TEXTURE_2D); - if (p.activeOpacity == 1.) { - GLint i = GL_REPLACE; - glTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &i); - } else { - GLint i = GL_MODULATE; - glTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &i); - glColor4f(1, 1, 1, p.activeOpacity); - } + imgleft, imgtop, + imgleft, imgbottom, + imgright, imgtop, - if (d->_tiled || !d->_scaleGrid || d->_scaleGrid->isNull()) { + imgleft, imgbottom, + imgright, imgtop, + imgright, imgbottom, - GLfloat vertices[8]; - GLfloat texVertices[8]; - GLTexture *tex = 0; + imgright, imgtop, + imgright, imgbottom, + widthV, imgtop, - QFxImage::glSimpleItemData(vertices, texVertices, &tex, 8); + imgright, imgbottom, + widthV, imgtop, + widthV, imgbottom, - glBindTexture(GL_TEXTURE_2D, tex->texture()); + 0, imgbottom, + 0, heightV, + imgleft, imgbottom, - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); + 0, heightV, + imgleft, imgbottom, + imgleft, heightV, - glVertexPointer(2, GL_FLOAT, 0, vertices); - glTexCoordPointer(2, GL_FLOAT, 0, texVertices); + imgleft, imgbottom, + imgleft, heightV, + imgright, imgbottom, + imgleft, heightV, + imgright, imgbottom, + imgright, heightV, - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + imgright, imgbottom, + imgright, heightV, + widthV, imgbottom, - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisable(GL_TEXTURE_2D); + imgright, heightV, + widthV, imgbottom, + widthV, heightV }; - } else { - d->checkDirty(); + float tex1[] = { 0, 1, + 0, textop, + texleft, 1, - float imgWidth = d->_pix.width(); - float imgHeight = d->_pix.height(); - if (!imgWidth || !imgHeight) { - if (restoreBlend) - glEnable(GL_BLEND); - return; - } + 0, textop, + texleft, 1, + texleft, textop, - float widthV = width(); - float heightV = height(); + texleft, 1, + texleft, textop, + texright, 1, - float texleft = 0; - float texright = 1; - float textop = 1; - float texbottom = 0; - float imgleft = 0; - float imgright = widthV; - float imgtop = 0; - float imgbottom = heightV; + texleft, textop, + texright, 1, + texright, textop, - const int sgl = d->_scaleGrid->left(); - const int sgr = d->_scaleGrid->right(); - const int sgt = d->_scaleGrid->top(); - const int sgb = d->_scaleGrid->bottom(); + texright, 1, + texright, textop, + 1, 1, - if (sgl) { - texleft = float(sgl) / imgWidth; - imgleft = sgl; - } - if (sgr) { - texright = 1. - float(sgr) / imgWidth; - imgright = widthV - sgr; - } - if (sgt) { - textop = 1. - float(sgb) / imgHeight; - imgtop = sgt; - } - if (sgb) { - texbottom = float(sgt) / imgHeight; - imgbottom = heightV - sgb; - } + texright, textop, + 1, 1, + 1, textop, - float vert1[] = { 0, 0, - 0, imgtop, - imgleft, 0, - imgleft, imgtop, - imgright, 0, - imgright, imgtop, - widthV, 0, - widthV, imgtop }; - float tex1[] = { 0, 1, 0, textop, - texleft, 1, + 0, texbottom, texleft, textop, - texright, 1, - texright, textop, - 1, 1, - 1, textop }; - float vert2[] = { 0, imgtop, - 0, imgbottom, - imgleft, imgtop, - imgleft, imgbottom, - imgright, imgtop, - imgright, imgbottom, - widthV, imgtop, - widthV, imgbottom }; - float tex2[] = { 0, textop, + 0, texbottom, texleft, textop, texleft, texbottom, + + texleft, textop, + texleft, texbottom, + texright, textop, + + texleft, texbottom, + texright, textop, + texright, texbottom, + texright, textop, texright, texbottom, 1, textop, - 1, texbottom }; - float vert3[] = { 0, imgbottom, - 0, heightV, - imgleft, imgbottom, - imgleft, heightV, - imgright, imgbottom, - imgright, heightV, - widthV, imgbottom, - widthV, heightV }; - float tex3[] = { 0, texbottom, + + texright, texbottom, + 1, textop, + 1, texbottom, + + 0, texbottom, + 0, 0, + texleft, texbottom, + 0, 0, texleft, texbottom, texleft, 0, + + texleft, texbottom, + texleft, 0, + texright, texbottom, + + texleft, 0, + texright, texbottom, + texright, 0, + texright, texbottom, texright, 0, 1, texbottom, + + texright, 0, + 1, texbottom, 1, 0 }; glBindTexture(GL_TEXTURE_2D, d->_tex.texture()); - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - - glVertexPointer(2, GL_FLOAT, 0, vert1); - glTexCoordPointer(2, GL_FLOAT, 0, tex1); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - glVertexPointer(2, GL_FLOAT, 0, vert2); - glTexCoordPointer(2, GL_FLOAT, 0, tex2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - glVertexPointer(2, GL_FLOAT, 0, vert3); - glTexCoordPointer(2, GL_FLOAT, 0, tex3); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisable(GL_TEXTURE_2D); + shader->setAttributeArray(SingleTextureShader::Vertices, vert1, 2); + shader->setAttributeArray(SingleTextureShader::TextureCoords, tex1, 2); + glDrawArrays(GL_TRIANGLES, 0, 54); } - if (restoreBlend) + if (restoreBlend) glEnable(GL_BLEND); } #endif diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index c156753..3d6897e 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -692,6 +692,7 @@ void QFxRect::paintGLContents(GLPainter &p) colors[i+3] = c.alphaF() * p.activeOpacity; colors[i+7] = colors[i+3]; } + p.invalidate(); ColorShader *shader = basicShaders()->color(); shader->enable(); shader->setTransform(p.activeTransform); @@ -702,19 +703,9 @@ void QFxRect::paintGLContents(GLPainter &p) shader->disableAttributeArray(ColorShader::Vertices); shader->disableAttributeArray(ColorShader::Colors); } else { - QGLShaderProgram *shader = p.useColorShader(d->getColor()); - float widthV = width(); - float heightV = height(); - - GLfloat vertices[] = { 0, heightV, - widthV, heightV, - 0, 0, - widthV, 0 }; + p.fillRect(QRectF(0, 0, width(), height()), d->getColor()); - shader->setAttributeArray(ConstantColorShader::Vertices, vertices, 2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - shader->disableAttributeArray(ConstantColorShader::Vertices); } } else { qreal offset = 0; @@ -768,236 +759,155 @@ void QFxRect::paintGLContents(GLPainter &p) float vert1[] = { -pw/2, -pw/2, -pw/2, imgtop, imgleft, -pw/2, + + -pw/2, imgtop, + imgleft, -pw/2, + imgleft, imgtop, + + imgleft, -pw/2, + imgleft, imgtop, + imgright, -pw/2, + imgleft, imgtop, imgright, -pw/2, imgright, imgtop, + + imgright, -pw/2, + imgright, imgtop, widthV, -pw/2, - widthV, imgtop }; - float tex1[] = { 0, 0, - 0, textop, - texleft, 0, - texleft, textop, - texright, 0, - texright, textop, - 1, 0, - 1, textop }; - float vert2[] = { -pw/2, imgtop, - -pw/2, imgbottom, - imgleft, imgtop, - imgleft, imgbottom, + imgright, imgtop, - imgright, imgbottom, + widthV, -pw/2, widthV, imgtop, - widthV, imgbottom }; - float tex2[] = { 0, textop, - 0, texbottom, - texleft, textop, - texleft, texbottom, - texright, textop, - texright, texbottom, - 1, textop, - 1, texbottom }; - float vert3[] = { -pw/2, heightV, + + -pw/2, heightV, -pw/2, imgbottom, imgleft, heightV, + + -pw/2, imgbottom, + imgleft, heightV, + imgleft, imgbottom, + + imgleft, heightV, imgleft, imgbottom, imgright, heightV, + + imgleft, imgbottom, + imgright, heightV, + imgright, imgbottom, + + imgright, heightV, imgright, imgbottom, widthV, heightV, - widthV, imgbottom }; - float tex3[] = { 0, 1, - 0, texbottom, - texleft, 1, - texleft, texbottom, - texright, 1, - texright, texbottom, - 1, 1, - 1, texbottom }; - glBindTexture(GL_TEXTURE_2D, d->_rectTexture.texture()); + imgright, imgbottom, + widthV, heightV, + widthV, imgbottom, - shader->setAttributeArray(SingleTextureShader::Vertices, vert1, 2); - shader->setAttributeArray(SingleTextureShader::TextureCoords, tex1, 2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - if (yMiddles) { - shader->setAttributeArray(SingleTextureShader::Vertices, vert2, 2); - shader->setAttributeArray(SingleTextureShader::TextureCoords, tex2, 2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - } - shader->setAttributeArray(SingleTextureShader::Vertices, vert3, 2); - shader->setAttributeArray(SingleTextureShader::TextureCoords, tex3, 2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); + -pw/2, imgtop, + -pw/2, imgbottom, + imgleft, imgtop, - shader->disableAttributeArray(SingleTextureShader::Vertices); - shader->disableAttributeArray(SingleTextureShader::TextureCoords); - } -} -#elif defined(QFX_RENDER_OPENGL1) -void QFxRect::paintGLContents(GLPainter &p) -{ - Q_D(QFxRect); + -pw/2, imgbottom, + imgleft, imgtop, + imgleft, imgbottom, - float widthV = width(); - float heightV = height(); - - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(p.activeTransform.data()); - - if (d->_radius == 0 && (!d->_pen || !d->_pen->isValid())) { - GLfloat vertices[] = { 0, heightV, - widthV, heightV, - 0, 0, - widthV, 0 }; + imgleft, imgtop, + imgleft, imgbottom, + imgright, imgtop, - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(2,GL_FLOAT,0,vertices); + imgleft, imgbottom, + imgright, imgtop, + imgright, imgbottom, - QColor c; - if (d->_gradcolor.isValid()) - c = d->_color; - else - c = d->getColor(); - float r = c.redF(); - float g = c.greenF(); - float b = c.blueF(); - float a = c.alphaF() * p.activeOpacity; - - float r2 = r; float g2 = g; float b2 = b; float a2 = a; - - if (d->_gradcolor.isValid()) { - r2 = d->_gradcolor.redF(); - g2 = d->_gradcolor.greenF(); - b2 = d->_gradcolor.blueF(); - a2 = d->_gradcolor.alphaF() * p.activeOpacity; - } + imgright, imgtop, + imgright, imgbottom, + widthV, imgtop, + + imgright, imgbottom, + widthV, imgtop, + widthV, imgbottom }; - GLfloat colors[] = { r2, g2, b2, a2, - r2, g2, b2, a2, - r, g, b, a, - r, g, b, a }; - glEnableClientState(GL_COLOR_ARRAY); - glColorPointer(4,GL_FLOAT,0,colors); + float tex1[] = { 0, 0, + 0, textop, + texleft, 0, - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + 0, textop, + texleft, 0, + texleft, textop, - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); - } else { - qreal offset = 0; - if (d->_radius > 0) { - generateRoundedRect(); - offset = d->_radius; - } else { - generateBorderedRect(); - offset = d->pen()->width(); - } + texleft, 0, + texleft, textop, + texright, 0, - if (p.activeOpacity == 1.) { - GLint i = GL_REPLACE; - glTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &i); - } else { - GLint i = GL_MODULATE; - glTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &i); - glColor4f(1, 1, 1, p.activeOpacity); - } + texleft, textop, + texright, 0, + texright, textop, - float texWidth = d->_rectTexture.width(); - float texHeight = d->_rectTexture.height(); - if (!texWidth || !texHeight) - return; + texright, 0, + texright, textop, + 1, 0, - float widthV = width(); - float heightV = height(); - - float texleft = 0; - float texright = 1; - float textop = 1; - float texbottom = 0; - float imgleft = 0; - float imgright = widthV; - float imgtop = 0; - float imgbottom = heightV; - - texleft = float(offset) / texWidth; - imgleft = offset; - texright = 1. - float(offset) / texWidth; - imgright = widthV - offset; - textop = 1. - float(offset) / texHeight; - imgtop = offset; - texbottom = float(offset) / texHeight; - imgbottom = heightV - offset; - - float vert1[] = { 0, 0, - 0, imgtop, - imgleft, 0, - imgleft, imgtop, - imgright, 0, - imgright, imgtop, - widthV, 0, - widthV, imgtop }; - float tex1[] = { 0, 1, - 0, textop, + texright, textop, + 1, 0, + 1, textop, + + 0, 1, + 0, texbottom, texleft, 1, - texleft, textop, + + 0, texbottom, + texleft, 1, + texleft, texbottom, + + texleft, 1, + texleft, texbottom, texright, 1, - texright, textop, + + texleft, texbottom, + texright, 1, + texright, texbottom, + + texright, 1, + texright, texbottom, 1, 1, - 1, textop }; - float vert2[] = { 0, imgtop, - 0, imgbottom, - imgleft, imgtop, - imgleft, imgbottom, - imgright, imgtop, - imgright, imgbottom, - widthV, imgtop, - widthV, imgbottom }; - float tex2[] = { 0, textop, + + texright, texbottom, + 1, 1, + 1, texbottom, + + 0, textop, 0, texbottom, texleft, textop, + + 0, texbottom, + texleft, textop, + texleft, texbottom, + + texleft, textop, texleft, texbottom, texright, textop, - texright, texbottom, - 1, textop, - 1, texbottom }; - float vert3[] = { 0, imgbottom, - 0, heightV, - imgleft, imgbottom, - imgleft, heightV, - imgright, imgbottom, - imgright, heightV, - widthV, imgbottom, - widthV, heightV }; - float tex3[] = { 0, texbottom, - 0, 0, + texleft, texbottom, - texleft, 0, + texright, textop, texright, texbottom, - texright, 0, - 1, texbottom, - 1, 0 }; - glEnable(GL_TEXTURE_2D); - glBindTexture(GL_TEXTURE_2D, d->_rectTexture.texture()); + texright, textop, + texright, texbottom, + 1, textop, - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); + texright, texbottom, + 1, textop, + 1, texbottom }; - glVertexPointer(2, GL_FLOAT, 0, vert1); - glTexCoordPointer(2, GL_FLOAT, 0, tex1); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - glVertexPointer(2, GL_FLOAT, 0, vert2); - glTexCoordPointer(2, GL_FLOAT, 0, tex2); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); - glVertexPointer(2, GL_FLOAT, 0, vert3); - glTexCoordPointer(2, GL_FLOAT, 0, tex3); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 8); + glBindTexture(GL_TEXTURE_2D, d->_rectTexture.texture()); - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisable(GL_TEXTURE_2D); + shader->setAttributeArray(SingleTextureShader::Vertices, vert1, 2); + shader->setAttributeArray(SingleTextureShader::TextureCoords, tex1, 2); + glDrawArrays(GL_TRIANGLES, 0, 36 + (yMiddles?18:0)); } } #endif diff --git a/src/declarative/fx/qfxtext.cpp b/src/declarative/fx/qfxtext.cpp index 702ec81..1b5c080 100644 --- a/src/declarative/fx/qfxtext.cpp +++ b/src/declarative/fx/qfxtext.cpp @@ -796,103 +796,31 @@ void QFxText::paintGLContents(GLPainter &p) QGLShaderProgram *shader = p.useTextureShader(); GLfloat vertices[] = { x, y + heightV, - x + widthV, y + heightV, - x, y, - x + widthV, y }; + x + widthV, y + heightV, + x, y, + + x + widthV, y + heightV, + x, y, + x + widthV, y }; GLfloat texVertices[] = { 0, 0, 1, 0, 0, 1, + + 1, 0, + 0, 1, 1, 1 }; shader->setAttributeArray(SingleTextureShader::Vertices, vertices, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, texVertices, 2); glBindTexture(GL_TEXTURE_2D, d->tex.texture()); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); + glDrawArrays(GL_TRIANGLES, 0, 6); shader->disableAttributeArray(SingleTextureShader::Vertices); shader->disableAttributeArray(SingleTextureShader::TextureCoords); } -#elif defined(QFX_RENDER_OPENGL) -void QFxText::paintGLContents(GLPainter &p) -{ - Q_D(QFxText); - d->checkImgCache(); - if (d->imgCache.isNull()) - return; - - int w = width(); - int h = height(); - - float x = 0; - float y = 0; - - switch (d->hAlign) { - case AlignLeft: - x = 0; - break; - case AlignRight: - x = w - d->imgCache.width(); - break; - case AlignHCenter: - x = (w - d->imgCache.width()) / 2; - break; - } - - switch (d->vAlign) { - case AlignTop: - y = 0; - break; - case AlignBottom: - y = h - d->imgCache.height(); - break; - case AlignVCenter: - y = (h - d->imgCache.height()) / 2; - break; - } - - float widthV = d->imgCache.width(); - float heightV = d->imgCache.height(); - - GLfloat vertices[] = { x, y + heightV, - x + widthV, y + heightV, - x, y, - x + widthV, y }; - - GLfloat texVertices[] = { 0, 0, - 1, 0, - 0, 1, - 1, 1 }; - - glMatrixMode(GL_MODELVIEW); - glLoadMatrixf(p.activeTransform.data()); - glEnable(GL_TEXTURE_2D); - if (p.activeOpacity == 1.) { - GLint i = GL_REPLACE; - glTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &i); - } else { - GLint i = GL_MODULATE; - glTexEnviv(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, &i); - glColor4f(1, 1, 1, p.activeOpacity); - } - - glBindTexture(GL_TEXTURE_2D, d->tex.texture()); - - glEnableClientState(GL_VERTEX_ARRAY); - glEnableClientState(GL_TEXTURE_COORD_ARRAY); - - glVertexPointer(2, GL_FLOAT, 0, vertices); - glTexCoordPointer(2, GL_FLOAT, 0, texVertices); - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisable(GL_TEXTURE_2D); -} - #endif void QFxText::componentComplete() diff --git a/src/declarative/opengl/gltexture.cpp b/src/declarative/opengl/gltexture.cpp index 199b362..bebee08 100644 --- a/src/declarative/opengl/gltexture.cpp +++ b/src/declarative/opengl/gltexture.cpp @@ -79,7 +79,8 @@ public: GLTexturePrivate(GLTexture *_q) : q(_q), texture(0), width(0), height(0), horizWrap(GLTexture::Repeat), vertWrap(GLTexture::Repeat), - minFilter(GLTexture::Linear), magFilter(GLTexture::Linear) + minFilter(GLTexture::Linear), magFilter(GLTexture::Linear), + glWidth(1.), glHeight(1.) { } @@ -92,6 +93,9 @@ public: GLTexture::FilterMode minFilter; GLTexture::FilterMode magFilter; + qreal glWidth; + qreal glHeight; + void genTexture(); }; @@ -167,32 +171,43 @@ static inline int npot(int size) by explicitly setting the size, or by previously setting an image), it will be destroyed and a new texture created with \a img's contents and size. */ -void GLTexture::setImage(const QImage &img) +void GLTexture::setImage(const QImage &img, ImageMode mode) { if (img.isNull()) return; d->genTexture(); - //QImage dataImage = img.scaled(npot(img.width()), npot(img.height()), Qt::IgnoreAspectRatio, Qt::SmoothTransformation); - QImage dataImage = QGLWidget_convertToGLFormat(img); - glBindTexture(GL_TEXTURE_2D, d->texture); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dataImage.width(), - dataImage.height(), 0, - (dataImage.format() == QImage::Format_ARGB32)?GL_RGBA:GL_RGB, - GL_UNSIGNED_BYTE, dataImage.bits()); - d->width = dataImage.width(); - d->height = dataImage.height(); - -#if 0 - glGenerateMipmap(GL_TEXTURE_2D); - int e = glGetError(); - if (d->magFilter == Linear) - setMagFilter(MipmapLinear); - if (d->minFilter == Linear) - setMinFilter((GLTexture::FilterMode)GL_LINEAR_MIPMAP_LINEAR); -#endif + + // ### Need to respect mode + if (img.format() == QImage::Format_RGB16) { + QImage dataImage = img.mirrored(); + int max = (img.width() > img.height())?img.width():img.height(); + max = npot(max); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, max, + max, 0, + GL_RGB, + GL_UNSIGNED_SHORT_5_6_5, 0); + + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dataImage.width(), + dataImage.height(), GL_RGB, GL_UNSIGNED_SHORT_5_6_5, + dataImage.bits()); + + d->glWidth = qreal(dataImage.width()) / qreal(max); + d->glHeight = qreal(dataImage.height()) / qreal(max); + } else { + QImage dataImage = QGLWidget_convertToGLFormat(img); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dataImage.width(), + dataImage.height(), 0, + (dataImage.format() == QImage::Format_ARGB32)?GL_RGBA:GL_RGB, + GL_UNSIGNED_BYTE, dataImage.bits()); + } + + d->width = img.width(); + d->height = img.height(); } void GLTexture::copyImage(const QImage &img, const QPoint &point, @@ -219,6 +234,16 @@ int GLTexture::height() const return d->height; } +qreal GLTexture::glWidth() const +{ + return d->glWidth; +} + +qreal GLTexture::glHeight() const +{ + return d->glHeight; +} + /*! Sets the \a size of the texture. This will destroy the current contents of the texture. If an image has been assigned, it will need to be reassigned diff --git a/src/declarative/opengl/gltexture.h b/src/declarative/opengl/gltexture.h index 787c9a5..d301d8a 100644 --- a/src/declarative/opengl/gltexture.h +++ b/src/declarative/opengl/gltexture.h @@ -69,11 +69,14 @@ public: bool isNull() const; void clear(); - void setImage(const QImage &); + enum ImageMode { NonPowerOfTwo, PowerOfTwo }; + void setImage(const QImage &, ImageMode = NonPowerOfTwo); void copyImage(const QImage &, const QPoint & = QPoint(0, 0), const QRect & = QRect()); int width() const; int height() const; + qreal glWidth() const; + qreal glHeight() const; QSize size() const; void setSize(const QSize &); -- cgit v0.12 From 5ee5a67cfb74a3b6d0e1fc781352302e7216cbef Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Wed, 3 Jun 2009 12:05:59 +1000 Subject: Resize TextEdit as text changes if no explicit width has been set. --- src/declarative/fx/qfxtextedit.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/declarative/fx/qfxtextedit.cpp b/src/declarative/fx/qfxtextedit.cpp index 79e1a3f..5492aaa 100644 --- a/src/declarative/fx/qfxtextedit.cpp +++ b/src/declarative/fx/qfxtextedit.cpp @@ -871,9 +871,13 @@ void QFxTextEditPrivate::init() void QFxTextEdit::q_textChanged() { + if (!widthValid()) + updateSize(); //### optimize: we get 3 calls to updateSize every time a letter is typed emit textChanged(text()); } +//### we should perhaps be a bit smarter here -- depending on what has changed, we shouldn't +// need to do all the calculations each time void QFxTextEdit::updateSize() { Q_D(QFxTextEdit); -- cgit v0.12 From e5146042141f92c6bf83f5222e4f2ff36c83d793 Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Wed, 3 Jun 2009 14:55:20 +1000 Subject: Make Q_DECLARE_PERFORMANCE_* empty if Q_ENABLE_PERFORMANCE_LOG undefined --- src/declarative/util/qperformancelog.h | 46 +++------------------------------- 1 file changed, 3 insertions(+), 43 deletions(-) diff --git a/src/declarative/util/qperformancelog.h b/src/declarative/util/qperformancelog.h index 6bb9037..3203685 100644 --- a/src/declarative/util/qperformancelog.h +++ b/src/declarative/util/qperformancelog.h @@ -126,49 +126,9 @@ namespace QPerformanceLog #else // Q_ENABLE_PERFORMANCE_LOG -#define Q_DECLARE_PERFORMANCE_METRIC(name) \ - enum { name = ValueChoice<0, ValueTracker<0, __LINE__>::value, __LINE__>::value }; \ - template \ - struct ValueTracker \ - { \ - enum { value = name }; \ - }; \ - -#define Q_DECLARE_PERFORMANCE_LOG(name) \ - namespace name { \ - inline void displayData() { }; \ - inline void clear() { }; \ - } \ - template \ - class name ## Timer { \ - public: \ - name ## Timer() { \ - } \ - ~ name ## Timer() { \ - } \ - }; \ - namespace name { \ - template \ - struct ValueTracker \ - { \ - enum { value = -1 }; \ - }; \ - template \ - struct ValueChoice \ - { \ - enum { value = ValueChoice::value, L>::value }; \ - }; \ - template \ - struct ValueChoice \ - { \ - enum { value = DefNextValue }; \ - }; \ - } \ - namespace name - -#define Q_DEFINE_PERFORMANCE_LOG(name, desc) \ - namespace name - +#define Q_DECLARE_PERFORMANCE_METRIC(name) +#define Q_DECLARE_PERFORMANCE_LOG(name) namespace name +#define Q_DEFINE_PERFORMANCE_LOG(name, desc) namespace name #define Q_DEFINE_PERFORMANCE_METRIC(name, desc) #endif // Q_ENABLE_PERFORMANCE_LOG -- cgit v0.12 From 694b270d78d99e94c8ab7543b7371edbe16ecaab Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 3 Jun 2009 16:09:39 +1000 Subject: Render items with z-order, and render opaque objects first. --- src/declarative/canvas/qsimplecanvas.cpp | 4 +- src/declarative/canvas/qsimplecanvas_opengl.cpp | 55 +++++++++++++++++++++---- src/declarative/canvas/qsimplecanvas_p.h | 1 + src/declarative/canvas/qsimplecanvasitem.h | 6 ++- src/declarative/canvas/qsimplecanvasitem_p.h | 6 ++- src/declarative/fx/qfximage.cpp | 5 ++- 6 files changed, 63 insertions(+), 14 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvas.cpp b/src/declarative/canvas/qsimplecanvas.cpp index f1ff61b..cb46f94 100644 --- a/src/declarative/canvas/qsimplecanvas.cpp +++ b/src/declarative/canvas/qsimplecanvas.cpp @@ -923,7 +923,9 @@ bool QSimpleCanvas::event(QEvent *e) d->root->d_func()->setupPainting(0, rect(), &zero); #elif defined(QFX_RENDER_OPENGL2) ++d->paintVersion; - d->root->d_func()->setupPainting(0); + d->opaqueList = 0; + int z = 0; + d->root->d_func()->setupPainting(0, z, &d->opaqueList); #else ++d->paintVersion; d->root->d_func()->setupPainting(0, rect()); diff --git a/src/declarative/canvas/qsimplecanvas_opengl.cpp b/src/declarative/canvas/qsimplecanvas_opengl.cpp index dd57c14..659104d 100644 --- a/src/declarative/canvas/qsimplecanvas_opengl.cpp +++ b/src/declarative/canvas/qsimplecanvas_opengl.cpp @@ -53,7 +53,7 @@ QT_BEGIN_NAMESPACE void CanvasEGLWidget::paintGL() { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); - glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT); + glClear(GL_COLOR_BUFFER_BIT | GL_STENCIL_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); _canvas->paintGL(); } @@ -120,8 +120,29 @@ void QSimpleCanvasPrivate::paintGL() p.opacity = 1; p.forceParamRefresh = false; p.painter = &painter; - if (!isSetup) - root->d_func()->setupPainting(0); + if (!isSetup) { + opaqueList = 0; + int z = 0; + root->d_func()->setupPainting(0, z, &opaqueList); + } + + glEnable(GL_DEPTH_TEST); + + glDisable(GL_BLEND); + painter.blendEnabled = false; + painter.activeOpacity = 1; + while (opaqueList) { + painter.item = opaqueList; + painter.activeTransform = opaqueList->d_func()->data()->transformActive; + // ### - I don't think this is right + painter.sceneClipRect = p.clipRect; + + opaqueList->paintGLContents(painter); + opaqueList = opaqueList->d_func()->nextOpaque; + } + glEnable(GL_BLEND); + painter.blendEnabled = true; + root->d_func()->paint(p); lrpTime = lrpTimer.elapsed(); @@ -274,7 +295,7 @@ void QSimpleCanvasItemPrivate::setupChildState(QSimpleCanvasItem *child) } //#define QSIMPLECANVAS_DISABLE_TREE_CLIPPING -QRectF QSimpleCanvasItemPrivate::setupPainting(int version) +QRectF QSimpleCanvasItemPrivate::setupPainting(int version, int &z, QSimpleCanvasItem **opaqueList) { static QRectF scene(-1., -1., 2., 2.); Q_Q(QSimpleCanvasItem); @@ -301,16 +322,31 @@ QRectF QSimpleCanvasItemPrivate::setupPainting(int version) (clip != QSimpleCanvasItem::NoClip); #endif + if (!myData->doNotPaint && + (options & QSimpleCanvasItem::IsOpaque) && + (myData->activeOpacity == 1.) && + (clip == 0)) { + + nextOpaque = *opaqueList; + *opaqueList = q; + myData->doNotPaint = true; + + } + + int myZ = z++; + if (myData->doNotPaintChildren) { rv = QRectF(); } else { + zOrderChildren(); + for (int ii = 0; ii < children.count(); ++ii) { QSimpleCanvasItem *child = children.at(ii); setupChildState(child); QSimpleCanvasItemData *childData = child->d_func()->data(); if (childData->activeOpacity != 0) - rv |= child->d_func()->setupPainting(version); + rv |= child->d_func()->setupPainting(version, z, opaqueList); } #ifndef QSIMPLECANVAS_DISABLE_TREE_CLIPPING @@ -318,11 +354,14 @@ QRectF QSimpleCanvasItemPrivate::setupPainting(int version) #endif } + myData->transformActive.translate(0, 0, myZ); + myData->lastPaintRect = rv; return rv; } + void QSimpleCanvasItemPrivate::paint(GLPaintParameters &oldParams, QSimpleCanvasFilter::Layer layer) { if (!layer) @@ -384,8 +423,6 @@ void QSimpleCanvasItemPrivate::paint(GLPaintParameters &oldParams, QSimpleCanvas params.clipRect = sr; } - zOrderChildren(); - int upto = 0; for (upto = 0; upto < children.count(); ++upto) { QSimpleCanvasItem *c = children.at(upto); @@ -438,12 +475,12 @@ void QSimpleCanvasItemPrivate::paint(GLPaintParameters &oldParams, QSimpleCanvas enum ShaderType { ST_None, ST_SingleTexture, ST_SingleTextureOpacity, ST_Color }; QSimpleCanvasItem::GLPainter::GLPainter() -: item(0), activeOpacity(1), flags(0) +: item(0), activeOpacity(1), blendEnabled(true), flags(0) { } QSimpleCanvasItem::GLPainter::GLPainter(QSimpleCanvasItem *i) -: item(i), activeOpacity(1), flags(0) +: item(i), activeOpacity(1), blendEnabled(true), flags(0) { } diff --git a/src/declarative/canvas/qsimplecanvas_p.h b/src/declarative/canvas/qsimplecanvas_p.h index b284c6c..5fc0c48 100644 --- a/src/declarative/canvas/qsimplecanvas_p.h +++ b/src/declarative/canvas/qsimplecanvas_p.h @@ -129,6 +129,7 @@ public: QRect resetDirty(); void paint(QPainter &p); + QSimpleCanvasItem *opaqueList; int timer; diff --git a/src/declarative/canvas/qsimplecanvasitem.h b/src/declarative/canvas/qsimplecanvasitem.h index 68219de..ee07a21 100644 --- a/src/declarative/canvas/qsimplecanvasitem.h +++ b/src/declarative/canvas/qsimplecanvasitem.h @@ -90,7 +90,8 @@ public: SimpleItem = 0x00000020, IsFocusPanel = 0x00000040, IsFocusRealm = 0x00000080, - AcceptsInputMethods = 0x00000100}; + AcceptsInputMethods = 0x00000100, + IsOpaque = 0x00000200 }; Q_DECLARE_FLAGS(Options, Option) QSimpleCanvasItem(QSimpleCanvasItem *parent=0); @@ -181,6 +182,9 @@ public: void fillRect(const QRectF &, const QColor &); void invalidate(); + + bool blendEnabled; + private: int flags; GLPainter(const GLPainter &); diff --git a/src/declarative/canvas/qsimplecanvasitem_p.h b/src/declarative/canvas/qsimplecanvasitem_p.h index 27ee0a2..6c21d9f 100644 --- a/src/declarative/canvas/qsimplecanvasitem_p.h +++ b/src/declarative/canvas/qsimplecanvasitem_p.h @@ -161,7 +161,7 @@ public: QSimpleCanvasItem::ClipType clip:3; QSimpleCanvasItem::TransformOrigin origin:4; - int options:9; + int options:10; bool focusable:1; bool wantsActiveFocusPanelPendingCanvas:1; bool hasBeenActiveFocusPanel:1; @@ -222,7 +222,7 @@ public: QSimpleCanvasItem::GLPainter *painter; }; #if defined(QFX_RENDER_OPENGL2) - QRectF setupPainting(int version); + QRectF setupPainting(int version, int &z, QSimpleCanvasItem **); #elif defined(QFX_RENDER_OPENGL1) QRectF setupPainting(int version, const QRect &bounding, unsigned int *zero); #endif @@ -241,6 +241,8 @@ public: #endif + QSimpleCanvasItem *nextOpaque; + void zOrderChildren(); bool freshenNeeded() const; void doFreshenTransforms() const; diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 1fc84eb..d28cf7d 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -254,6 +254,9 @@ void QFxImage::setOpaque(bool o) if (o == d->_opaque) return; d->_opaque = o; + + setOptions(IsOpaque, o); + update(); } @@ -476,7 +479,7 @@ void QFxImage::paintGLContents(GLPainter &p) QGLShaderProgram *shader = p.useTextureShader(); bool restoreBlend = false; - if (isOpaque() && p.activeOpacity == 1) { + if (p.blendEnabled && isOpaque() && p.activeOpacity == 1) { glDisable(GL_BLEND); restoreBlend = true; } -- cgit v0.12 From fa95af38594b09718b9eb9048b75b9628dc9a0da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 2 Jun 2009 15:25:07 +0200 Subject: Implemented QGLTextureGlyphCache to avoid wasting glyph cache memory. Now there's only a copy of the texture glyph cache in graphics memory, avoiding the system memory copy that we used earlier. In addition the texture will use the GL_ALPHA texture format when possible, making it consume less graphics memory as well. Reviewed-by: Tom --- src/gui/painting/qtextureglyphcache.cpp | 69 ++++--- src/gui/painting/qtextureglyphcache_p.h | 3 +- .../gl2paintengineex/qglengineshadermanager.cpp | 29 +++ .../gl2paintengineex/qglengineshadermanager_p.h | 4 + .../gl2paintengineex/qglengineshadersource_p.h | 9 +- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 198 ++++++++++++++++++--- src/opengl/qgl.h | 1 + 7 files changed, 255 insertions(+), 58 deletions(-) diff --git a/src/gui/painting/qtextureglyphcache.cpp b/src/gui/painting/qtextureglyphcache.cpp index 89df869..6b195bf 100644 --- a/src/gui/painting/qtextureglyphcache.cpp +++ b/src/gui/painting/qtextureglyphcache.cpp @@ -157,6 +157,46 @@ void QTextureGlyphCache::populate(const QTextItemInt &ti, } +QImage QTextureGlyphCache::textureMapForGlyph(glyph_t g) const +{ +#if defined(Q_WS_X11) + if (m_transform.type() > QTransform::TxTranslate) { + QFontEngineFT::GlyphFormat format = QFontEngineFT::Format_None; + QImage::Format imageFormat = QImage::Format_Invalid; + switch (m_type) { + case Raster_RGBMask: + format = QFontEngineFT::Format_A32; + imageFormat = QImage::Format_RGB32; + break; + case Raster_A8: + format = QFontEngineFT::Format_A8; + imageFormat = QImage::Format_Indexed8; + break; + case Raster_Mono: + format = QFontEngineFT::Format_Mono; + imageFormat = QImage::Format_Mono; + break; + }; + + QFontEngineFT *ft = static_cast (m_current_textitem->fontEngine); + QFontEngineFT::QGlyphSet *gset = ft->loadTransformedGlyphSet(m_transform); + + if (gset && ft->loadGlyphs(gset, &g, 1, format)) { + QFontEngineFT::Glyph *glyph = gset->glyph_data.value(g); + const int bytesPerLine = (format == QFontEngineFT::Format_Mono ? ((glyph->width + 31) & ~31) >> 3 + : (glyph->width + 3) & ~3); + return QImage(glyph->data, glyph->width, glyph->height, bytesPerLine, imageFormat); + } + } else +#endif + if (m_type == QFontEngineGlyphCache::Raster_RGBMask) + return m_current_textitem->fontEngine->alphaRGBMapForGlyph(g, glyphMargin(), m_transform); + else + return m_current_textitem->fontEngine->alphaMapForGlyph(g, m_transform); + + return QImage(); +} + /************************************************************************ * QImageTextureGlyphCache */ @@ -198,34 +238,7 @@ int QImageTextureGlyphCache::glyphMargin() const void QImageTextureGlyphCache::fillTexture(const Coord &c, glyph_t g) { - QImage mask; -#if defined(Q_WS_X11) - if (m_transform.type() > QTransform::TxTranslate) { - QFontEngineFT::GlyphFormat format = QFontEngineFT::Format_None; - switch (m_type) { - case Raster_RGBMask: - format = QFontEngineFT::Format_A32; break; - case Raster_A8: - format = QFontEngineFT::Format_A8; break; - case Raster_Mono: - format = QFontEngineFT::Format_Mono; break; - }; - - QFontEngineFT *ft = static_cast (m_current_textitem->fontEngine); - QFontEngineFT::QGlyphSet *gset = ft->loadTransformedGlyphSet(m_transform); - - if (gset && ft->loadGlyphs(gset, &g, 1, format)) { - QFontEngineFT::Glyph *glyph = gset->glyph_data.value(g); - const int bytesPerLine = (format == QFontEngineFT::Format_Mono ? ((glyph->width + 31) & ~31) >> 3 - : (glyph->width + 3) & ~3); - mask = QImage(glyph->data, glyph->width, glyph->height, bytesPerLine, m_image.format()); - } - } else -#endif - if (m_type == QFontEngineGlyphCache::Raster_RGBMask) - mask = m_current_textitem->fontEngine->alphaRGBMapForGlyph(g, glyphMargin(), m_transform); - else - mask = m_current_textitem->fontEngine->alphaMapForGlyph(g, m_transform); + QImage mask = textureMapForGlyph(g); #ifdef CACHE_DEBUG printf("fillTexture of %dx%d at %d,%d in the cache of %dx%d\n", c.w, c.h, c.x, c.y, m_image.width(), m_image.height()); diff --git a/src/gui/painting/qtextureglyphcache_p.h b/src/gui/painting/qtextureglyphcache_p.h index 7f2c478..cb5be75 100644 --- a/src/gui/painting/qtextureglyphcache_p.h +++ b/src/gui/painting/qtextureglyphcache_p.h @@ -108,6 +108,8 @@ public: QHash coords; + QImage textureMapForGlyph(glyph_t g) const; + protected: const QTextItemInt *m_current_textitem; @@ -116,7 +118,6 @@ protected: int m_cx; // current x int m_cy; // current y QFontEngineGlyphCache::Type m_type; - }; diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index f64af85..3159cbb 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -64,6 +64,7 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) maskType(NoMask), useTextureCoords(false), compositionMode(QPainter::CompositionMode_SourceOver), + blitShaderProg(0), simpleShaderProg(0), currentShaderProg(0) { @@ -83,6 +84,7 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) code[MainVertexShader] = qglslMainVertexShader; code[MainWithTexCoordsVertexShader] = qglslMainWithTexCoordsVertexShader; + code[UntransformedPositionVertexShader] = qglslUntransformedPositionVertexShader; code[PositionOnlyVertexShader] = qglslPositionOnlyVertexShader; code[PositionWithPatternBrushVertexShader] = qglslPositionWithPatternBrushVertexShader; code[PositionWithLinearGradientBrushVertexShader] = qglslPositionWithLinearGradientBrushVertexShader; @@ -160,6 +162,24 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) qCritical() << "Errors linking simple shader:" << simpleShaderProg->log(); } + + // Compile the blit shader: + blitShaderProg = new QGLShaderProgram(ctx, this); + compileNamedShader(MainWithTexCoordsVertexShader, QGLShader::PartialVertexShader); + compileNamedShader(UntransformedPositionVertexShader, QGLShader::PartialVertexShader); + compileNamedShader(MainFragmentShader, QGLShader::PartialFragmentShader); + compileNamedShader(ImageSrcFragmentShader, QGLShader::PartialFragmentShader); + blitShaderProg->addShader(compiledShaders[MainWithTexCoordsVertexShader]); + blitShaderProg->addShader(compiledShaders[UntransformedPositionVertexShader]); + blitShaderProg->addShader(compiledShaders[MainFragmentShader]); + blitShaderProg->addShader(compiledShaders[ImageSrcFragmentShader]); + blitShaderProg->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR); + blitShaderProg->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR); + blitShaderProg->link(); + if (!blitShaderProg->isLinked()) { + qCritical() << "Errors linking blit shader:" + << blitShaderProg->log(); + } } QGLEngineShaderManager::~QGLEngineShaderManager() @@ -176,6 +196,11 @@ void QGLEngineShaderManager::optimiseForBrushTransform(const QTransform &transfo Q_UNUSED(transform); // Currently ignored } +void QGLEngineShaderManager::setDirty() +{ + shaderProgNeedsChanging = true; +} + void QGLEngineShaderManager::setSrcPixelType(Qt::BrushStyle style) { srcPixelType = style; @@ -222,6 +247,10 @@ QGLShaderProgram* QGLEngineShaderManager::simpleProgram() return simpleShaderProg; } +QGLShaderProgram* QGLEngineShaderManager::blitProgram() +{ + return blitShaderProg; +} diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index b8b2745..9bc81ef 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -279,15 +279,18 @@ public: void setMaskType(MaskType); void setCompositionMode(QPainter::CompositionMode); + void setDirty(); // someone has manually changed the current shader program bool useCorrectShaderProg(); // returns true if the shader program needed to be changed QGLShaderProgram* currentProgram(); // Returns pointer to the shader the manager has chosen QGLShaderProgram* simpleProgram(); // Used to draw into e.g. stencil buffers + QGLShaderProgram* blitProgram(); // Used to blit a texture into the framebuffer enum ShaderName { MainVertexShader, MainWithTexCoordsVertexShader, + UntransformedPositionVertexShader, PositionOnlyVertexShader, PositionWithPatternBrushVertexShader, PositionWithLinearGradientBrushVertexShader, @@ -365,6 +368,7 @@ private: bool useTextureCoords; QPainter::CompositionMode compositionMode; + QGLShaderProgram* blitShaderProg; QGLShaderProgram* simpleShaderProg; QGLShaderProgram* currentShaderProg; diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index fdbba72..920d0bc 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -89,6 +89,12 @@ static const char* const qglslPositionOnlyVertexShader = "\ gl_Position = pmvMatrix * vertexCoordsArray;\ }"; +static const char* const qglslUntransformedPositionVertexShader = "\ + attribute highp vec4 vertexCoordsArray;\ + void setPosition(void)\ + {\ + gl_Position = vertexCoordsArray;\ + }"; // Pattern Brush - This assumes the texture size is 8x8 and thus, the inverted size is 0.125 static const char* const qglslPositionWithPatternBrushVertexShader = "\ @@ -354,7 +360,7 @@ static const char* const qglslMaskFragmentShader = "\ lowp vec4 applyMask(lowp vec4 src) \ {\ lowp vec4 mask = texture2D(maskTexture, textureCoords); \ - return src * mask.r; \ + return src * mask.a; \ }"; /* @@ -375,7 +381,6 @@ static const char* const qglslMaskFragmentShader = "\ ExclusionCompositionModeFragmentShader, */ - QT_END_NAMESPACE QT_END_HEADER diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 40f3a8d..868adcf 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -79,18 +79,165 @@ #include "qglengineshadermanager_p.h" #include "qgl2pexvertexarray_p.h" - #include QT_BEGIN_NAMESPACE -extern QImage qt_imageForBrush(int brushStyle, bool invert); - static const GLuint QT_BRUSH_TEXTURE_UNIT = 0; static const GLuint QT_IMAGE_TEXTURE_UNIT = 0; //Can be the same as brush texture unit static const GLuint QT_MASK_TEXTURE_UNIT = 1; static const GLuint QT_BACKGROUND_TEXTURE_UNIT = 2; +class QGLTextureGlyphCache : public QTextureGlyphCache +{ +public: + QGLTextureGlyphCache(QGLContext *context, QFontEngineGlyphCache::Type type, const QTransform &matrix); + ~QGLTextureGlyphCache(); + + virtual void createTextureData(int width, int height); + virtual void resizeTextureData(int width, int height); + virtual void fillTexture(const Coord &c, glyph_t glyph); + + inline GLuint texture() const { return m_texture; } + + inline int width() const { return m_width; } + inline int height() const { return m_height; } + + inline void setPaintEnginePrivate(QGL2PaintEngineExPrivate *p) { pex = p; } + +private: + QGLContext *ctx; + + QGL2PaintEngineExPrivate *pex; + + GLuint m_texture; + GLuint m_fbo; + + int m_width; + int m_height; + + QGLShaderProgram *m_program; +}; + +QGLTextureGlyphCache::QGLTextureGlyphCache(QGLContext *context, QFontEngineGlyphCache::Type type, const QTransform &matrix) + : QTextureGlyphCache(type, matrix) + , ctx(context) + , m_width(0) + , m_height(0) +{ + glGenFramebuffers(1, &m_fbo); +} + +QGLTextureGlyphCache::~QGLTextureGlyphCache() +{ + glDeleteFramebuffers(1, &m_fbo); + + if (m_width || m_height) + glDeleteTextures(1, &m_texture); +} + +void QGLTextureGlyphCache::createTextureData(int width, int height) +{ + glGenTextures(1, &m_texture); + glBindTexture(GL_TEXTURE_2D, m_texture); + + m_width = width; + m_height = height; + + QVarLengthArray data(width * height); + for (int i = 0; i < width * height; ++i) + data[i] = 0; + + if (m_type == QFontEngineGlyphCache::Raster_RGBMask) + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &data[0]); + else + glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &data[0]); + + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); + glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); +} + +void QGLTextureGlyphCache::resizeTextureData(int width, int height) +{ + // ### the QTextureGlyphCache API needs to be reworked to allow + // ### resizeTextureData to fail + + int oldWidth = m_width; + int oldHeight = m_height; + + GLuint oldTexture = m_texture; + createTextureData(width, height); + + glBindFramebuffer(GL_FRAMEBUFFER_EXT, m_fbo); + + GLuint colorBuffer; + glGenRenderbuffers(1, &colorBuffer); + glBindRenderbuffer(GL_RENDERBUFFER_EXT, colorBuffer); + glRenderbufferStorage(GL_RENDERBUFFER_EXT, GL_RGBA, oldWidth, oldHeight); + glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + GL_RENDERBUFFER_EXT, colorBuffer); + glBindRenderbuffer(GL_RENDERBUFFER_EXT, 0); + + glActiveTexture(GL_TEXTURE0 + QT_IMAGE_TEXTURE_UNIT); + glBindTexture(GL_TEXTURE_2D, oldTexture); + + pex->transferMode(BrushDrawingMode); + + glDisable(GL_SCISSOR_TEST); + glDisable(GL_DEPTH_TEST); + + glViewport(0, 0, oldWidth, oldHeight); + + float vertexCoordinateArray[] = { -1, -1, 1, -1, 1, 1, -1, 1 }; + float textureCoordinateArray[] = { 0, 0, 1, 0, 1, 1, 0, 1 }; + + glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); + glEnableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); + + glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, vertexCoordinateArray); + glVertexAttribPointer(QT_TEXTURE_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinateArray); + + pex->shaderManager->blitProgram()->enable(); + pex->shaderManager->blitProgram()->setUniformValue("imageTexture", QT_IMAGE_TEXTURE_UNIT); + pex->shaderManager->setDirty(); + + glDrawArrays(GL_TRIANGLE_FAN, 0, 4); + + glDisableVertexAttribArray(QT_VERTEX_COORDS_ATTR); + glDisableVertexAttribArray(QT_TEXTURE_COORDS_ATTR); + + glBindTexture(GL_TEXTURE_2D, m_texture); + glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, oldWidth, oldHeight); + + glFramebufferRenderbuffer(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, + GL_RENDERBUFFER_EXT, 0); + glDeleteRenderbuffers(1, &colorBuffer); + glDeleteTextures(1, &oldTexture); + + glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); + + glViewport(0, 0, pex->width, pex->height); + pex->updateDepthClip(); +} + +void QGLTextureGlyphCache::fillTexture(const Coord &c, glyph_t glyph) +{ + QImage mask = textureMapForGlyph(glyph); + + const uint maskWidth = mask.width(); + const uint maskHeight = mask.height(); + + glBindTexture(GL_TEXTURE_2D, m_texture); + if (mask.format() == QImage::Format_RGB32) { + glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, m_height - c.y, maskWidth, maskHeight, GL_BGRA, GL_UNSIGNED_BYTE, mask.bits()); + } else { + mask = mask.convertToFormat(QImage::Format_Indexed8); + glTexSubImage2D(GL_TEXTURE_2D, 0, c.x, c.y, maskWidth, maskHeight, GL_ALPHA, GL_UNSIGNED_BYTE, mask.bits()); + } +} + +extern QImage qt_imageForBrush(int brushStyle, bool invert); + ////////////////////////////////// Private Methods ////////////////////////////////////////// QGL2PaintEngineExPrivate::~QGL2PaintEngineExPrivate() @@ -141,6 +288,7 @@ void QGL2PaintEngineExPrivate::setBrush(const QBrush* brush) void QGL2PaintEngineExPrivate::useSimpleShader() { shaderManager->simpleProgram()->enable(); + shaderManager->setDirty(); if (matrixDirty) updateMatrix(); @@ -905,8 +1053,6 @@ void QGL2PaintEngineEx::drawTextItem(const QPointF &p, const QTextItem &textItem void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextItemInt &ti) { - transferMode(TextDrawingMode); - Q_Q(QGL2PaintEngineEx); QOpenGL2PaintEngineState *s = q->state(); @@ -921,34 +1067,32 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat) : QFontEngineGlyphCache::Raster_A8; - GLenum maskFormat = GL_RGBA; - if (glyphType == QFontEngineGlyphCache::Raster_A8) { - shaderManager->setMaskType(QGLEngineShaderManager::PixelMask); -// maskFormat = GL_ALPHA; + QGLTextureGlyphCache *cache = + (QGLTextureGlyphCache *) ti.fontEngine->glyphCache(ctx, s->matrix); + if (!cache) { + cache = new QGLTextureGlyphCache(ctx, glyphType, s->matrix); + ti.fontEngine->setGlyphCache(ctx, cache); } + + cache->setPaintEnginePrivate(this); + cache->populate(ti, glyphs, positions); + + if (cache->width() == 0 || cache->height() == 0) + return; + + transferMode(TextDrawingMode); + + if (glyphType == QFontEngineGlyphCache::Raster_A8) + shaderManager->setMaskType(QGLEngineShaderManager::PixelMask); else if (glyphType == QFontEngineGlyphCache::Raster_RGBMask) shaderManager->setMaskType(QGLEngineShaderManager::SubPixelMask); //### TODO: Gamma correction shaderManager->setTextureCoordsEnabled(true); - - QImageTextureGlyphCache *cache = - (QImageTextureGlyphCache *) ti.fontEngine->glyphCache(glyphType, s->matrix); - if (!cache) { - cache = new QImageTextureGlyphCache(glyphType, s->matrix); - ti.fontEngine->setGlyphCache(glyphType, cache); - } - - cache->populate(ti, glyphs, positions); - - const QImage &image = cache->image(); int margin = cache->glyphMargin(); - if (image.isNull()) - return; - - GLfloat dx = 1.0 / image.width(); - GLfloat dy = 1.0 / image.height(); + GLfloat dx = 1.0 / cache->width(); + GLfloat dy = 1.0 / cache->height(); QGLPoint *oldVertexCoordinateDataPtr = vertexCoordinateArray.data(); QGLPoint *oldTextureCoordinateDataPtr = textureCoordinateArray.data(); @@ -962,11 +1106,11 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte int y = positions[i].y.toInt() - c.baseLineY - margin; vertexCoordinateArray.addRect(QRectF(x, y, c.w, c.h)); - textureCoordinateArray.addRect(QRectF(c.x*dx, 1 - c.y*dy, c.w * dx, -c.h * dy)); + textureCoordinateArray.addRect(QRectF(c.x*dx, c.y*dy, c.w * dx, c.h * dy)); } glActiveTexture(GL_TEXTURE0 + QT_MASK_TEXTURE_UNIT); - ctx->d_func()->bindTexture(image, GL_TEXTURE_2D, GL_RGBA, true); + glBindTexture(GL_TEXTURE_2D, cache->texture()); updateTextureFilter(GL_TEXTURE_2D, GL_REPEAT, false); QBrush pensBrush = q->state()->pen.brush(); diff --git a/src/opengl/qgl.h b/src/opengl/qgl.h index 19d779a..6b511e2 100644 --- a/src/opengl/qgl.h +++ b/src/opengl/qgl.h @@ -363,6 +363,7 @@ private: friend class QGLWindowSurface; friend class QGLPixmapData; friend class QGLPixmapFilterBase; + friend class QGLTextureGlyphCache; friend QGLFormat::OpenGLVersionFlags QGLFormat::openGLVersionFlags(); #ifdef Q_WS_MAC public: -- cgit v0.12 From b469fd9aac5c0e4a87ea1a9be254b566c0353702 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Wed, 3 Jun 2009 09:15:57 +0200 Subject: _networktest compile fix Reviewed-by: mauricek --- tests/auto/_networkselftest/tst_networkselftest.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/auto/_networkselftest/tst_networkselftest.cpp b/tests/auto/_networkselftest/tst_networkselftest.cpp index dab4433..0fa001a 100644 --- a/tests/auto/_networkselftest/tst_networkselftest.cpp +++ b/tests/auto/_networkselftest/tst_networkselftest.cpp @@ -463,7 +463,7 @@ void tst_NetworkSelfTest::httpsServer() << Chat::expect("200 ") << Chat::DiscardUntilDisconnect); #else - QSKIP("SSL not enabled, cannot test"); + QSKIP("SSL not enabled, cannot test", SkipAll); #endif } -- cgit v0.12 From e11ff338951954f08866aef15607e8fae2bc150c Mon Sep 17 00:00:00 2001 From: Frederik Schwarzer Date: Wed, 3 Jun 2009 09:25:20 +0200 Subject: missing opening paragraph tag Merge-request: 578 Reviewed-by: Simon Hausmann --- src/gui/dialogs/qmessagebox.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/dialogs/qmessagebox.cpp b/src/gui/dialogs/qmessagebox.cpp index 1734e85..648cda8 100644 --- a/src/gui/dialogs/qmessagebox.cpp +++ b/src/gui/dialogs/qmessagebox.cpp @@ -1699,7 +1699,7 @@ void QMessageBox::aboutQt(QWidget *parent, const QString &title) "and Qt for Windows CE.

    " "

    Qt is available under three different licensing options designed " "to accommodate the needs of our various users.

    " - "Qt licensed under our commercial license agreement is appropriate " + "

    Qt licensed under our commercial license agreement is appropriate " "for development of proprietary/commercial software where you do not " "want to share any source code with third parties or otherwise cannot " "comply with the terms of the GNU LGPL version 2.1 or GNU GPL version " -- cgit v0.12 From 10b1e68d07746fde5ec6d6d2fc3f46fb803a2462 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Wed, 3 Jun 2009 10:14:49 +0200 Subject: Doc - fixed a typo Reviewed-By: TrustMe --- doc/src/tutorials/addressbook.qdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc index 3b0d2bc..3ec883f 100644 --- a/doc/src/tutorials/addressbook.qdoc +++ b/doc/src/tutorials/addressbook.qdoc @@ -303,7 +303,7 @@ Within the constructor of \c AddressBook, we set the \c nameLine and \c addressText to read-only, so that we can only display but not edit - existing cotact details. + existing contact details. \dots \snippet tutorials/addressbook/part2/addressbook.cpp setting readonly 1 -- cgit v0.12 From e91dff94de4851b4b8ac48cadccd516893fe4661 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 3 Jun 2009 19:07:45 +1000 Subject: Use POT textures only --- src/declarative/fx/qfximage.cpp | 14 ++++---- src/declarative/fx/qfxrect.cpp | 41 +++++++++++---------- src/declarative/fx/qfxtext.cpp | 13 +++---- src/declarative/opengl/gltexture.cpp | 69 +++++++++++++++++++++++++----------- 4 files changed, 86 insertions(+), 51 deletions(-) diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index d28cf7d..d3ac38f 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -462,7 +462,7 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, void QFxImagePrivate::checkDirty() { if (_texDirty && !_pix.isNull()) { - _tex.setImage(_pix.toImage()); + _tex.setImage(_pix.toImage(), GLTexture::PowerOfTwo); _tex.setHorizontalWrap(GLTexture::Repeat); _tex.setVerticalWrap(GLTexture::Repeat); } @@ -548,8 +548,8 @@ void QFxImage::paintGLContents(GLPainter &p) float heightV = height(); float texleft = 0; - float texright = 1; - float textop = 1; + float texright = d->_tex.glWidth(); + float textop = d->_tex.glHeight(); float texbottom = 0; float imgleft = 0; float imgright = widthV; @@ -562,19 +562,19 @@ void QFxImage::paintGLContents(GLPainter &p) const int sgb = d->_scaleGrid->bottom(); if (sgl) { - texleft = float(sgl) / imgWidth; + texleft = d->_tex.glWidth() * float(sgl) / imgWidth; imgleft = sgl; } if (sgr) { - texright = 1. - float(sgr) / imgWidth; + texright = d->_tex.glWidth() - float(sgr) / imgWidth; imgright = widthV - sgr; } if (sgt) { - textop = 1. - float(sgb) / imgHeight; + textop = d->_tex.glHeight() - float(sgb) / imgHeight; imgtop = sgt; } if (sgb) { - texbottom = float(sgt) / imgHeight; + texbottom = d->_tex.glHeight() * float(sgt) / imgHeight; imgbottom = heightV - sgb; } diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index 3d6897e..c053001 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -535,7 +535,7 @@ void QFxRect::generateRoundedRect() } p.setBrush(d->_color); p.drawRoundedRect((pw+1)/2, (pw+1)/2, roundRect.width()-(pw+1)/2*2, roundRect.height()-(pw+1)/2*2, d->_radius, d->_radius); - d->_rectTexture.setImage(roundRect); + d->_rectTexture.setImage(roundRect, GLTexture::PowerOfTwo); } } @@ -556,7 +556,7 @@ void QFxRect::generateBorderedRect() } p.setBrush(d->_color); p.drawRect(qreal(pw+1)/2, qreal(pw+1)/2, borderedRect.width()-(pw+1)/2*2, borderedRect.height()-(pw+1)/2*2); - d->_rectTexture.setImage(borderedRect); + d->_rectTexture.setImage(borderedRect, GLTexture::PowerOfTwo); } } #endif @@ -756,6 +756,11 @@ void QFxRect::paintGLContents(GLPainter &p) if (offset==1) texleft=texright=textop=texbottom=0.5; + texleft *= d->_rectTexture.glWidth(); + texright *= d->_rectTexture.glWidth(); + textop *= d->_rectTexture.glHeight(); + texbottom *= d->_rectTexture.glHeight(); + float vert1[] = { -pw/2, -pw/2, -pw/2, imgtop, imgleft, -pw/2, @@ -847,35 +852,35 @@ void QFxRect::paintGLContents(GLPainter &p) texright, 0, texright, textop, - 1, 0, + d->_rectTexture.glWidth(), 0, texright, textop, - 1, 0, - 1, textop, + d->_rectTexture.glWidth(), 0, + d->_rectTexture.glWidth(), textop, - 0, 1, + 0, d->_rectTexture.glHeight(), 0, texbottom, - texleft, 1, + texleft, d->_rectTexture.glHeight(), 0, texbottom, - texleft, 1, + texleft, d->_rectTexture.glHeight(), texleft, texbottom, - texleft, 1, + texleft, d->_rectTexture.glHeight(), texleft, texbottom, - texright, 1, + texright, d->_rectTexture.glHeight(), texleft, texbottom, - texright, 1, + texright, d->_rectTexture.glHeight(), texright, texbottom, - texright, 1, + texright, d->_rectTexture.glHeight(), texright, texbottom, - 1, 1, + d->_rectTexture.glWidth(), d->_rectTexture.glHeight(), texright, texbottom, - 1, 1, - 1, texbottom, + d->_rectTexture.glWidth(), d->_rectTexture.glHeight(), + d->_rectTexture.glWidth(), texbottom, 0, textop, 0, texbottom, @@ -895,11 +900,11 @@ void QFxRect::paintGLContents(GLPainter &p) texright, textop, texright, texbottom, - 1, textop, + d->_rectTexture.glWidth(), textop, texright, texbottom, - 1, textop, - 1, texbottom }; + d->_rectTexture.glWidth(), textop, + d->_rectTexture.glWidth(), texbottom }; diff --git a/src/declarative/fx/qfxtext.cpp b/src/declarative/fx/qfxtext.cpp index 1b5c080..7a2dd8d 100644 --- a/src/declarative/fx/qfxtext.cpp +++ b/src/declarative/fx/qfxtext.cpp @@ -696,7 +696,7 @@ void QFxTextPrivate::checkImgCache() } #if defined(QFX_RENDER_OPENGL) - tex.setImage(imgCache.toImage()); + tex.setImage(imgCache.toImage(), GLTexture::PowerOfTwo); #endif imgDirty = false; @@ -755,6 +755,7 @@ void QFxText::paintContents(QPainter &p) #elif defined(QFX_RENDER_OPENGL2) void QFxText::paintGLContents(GLPainter &p) { + //return; Q_D(QFxText); d->checkImgCache(); if (d->imgCache.isNull()) @@ -804,12 +805,12 @@ void QFxText::paintGLContents(GLPainter &p) x + widthV, y }; GLfloat texVertices[] = { 0, 0, - 1, 0, - 0, 1, + d->tex.glWidth(), 0, + 0, d->tex.glHeight(), - 1, 0, - 0, 1, - 1, 1 }; + d->tex.glWidth(), 0, + 0, d->tex.glHeight(), + d->tex.glWidth(), d->tex.glHeight() }; shader->setAttributeArray(SingleTextureShader::Vertices, vertices, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, texVertices, 2); diff --git a/src/declarative/opengl/gltexture.cpp b/src/declarative/opengl/gltexture.cpp index bebee08..cd9c406 100644 --- a/src/declarative/opengl/gltexture.cpp +++ b/src/declarative/opengl/gltexture.cpp @@ -180,30 +180,59 @@ void GLTexture::setImage(const QImage &img, ImageMode mode) glBindTexture(GL_TEXTURE_2D, d->texture); - // ### Need to respect mode - if (img.format() == QImage::Format_RGB16) { - QImage dataImage = img.mirrored(); + if (mode == NonPowerOfTwo) { + + if (img.format() == QImage::Format_RGB16) { + QImage dataImage = img.mirrored(); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, dataImage.width(), + dataImage.height(), 0, + GL_RGB, + GL_UNSIGNED_SHORT_5_6_5, dataImage.bits()); + } else { + QImage dataImage = QGLWidget_convertToGLFormat(img); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dataImage.width(), + dataImage.height(), 0, + (dataImage.format() == QImage::Format_ARGB32)?GL_RGBA:GL_RGB, + GL_UNSIGNED_BYTE, dataImage.bits()); + } + d->glWidth = 1.; + d->glHeight = 1.; + + } else { + // mode == PowerOfTwo int max = (img.width() > img.height())?img.width():img.height(); max = npot(max); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, max, - max, 0, - GL_RGB, - GL_UNSIGNED_SHORT_5_6_5, 0); - - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dataImage.width(), - dataImage.height(), GL_RGB, GL_UNSIGNED_SHORT_5_6_5, - dataImage.bits()); - - d->glWidth = qreal(dataImage.width()) / qreal(max); - d->glHeight = qreal(dataImage.height()) / qreal(max); - } else { - QImage dataImage = QGLWidget_convertToGLFormat(img); + if (img.format() == QImage::Format_RGB16) { + QImage dataImage = img.mirrored(); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, max, + max, 0, + GL_RGB, + GL_UNSIGNED_SHORT_5_6_5, 0); + + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dataImage.width(), + dataImage.height(), GL_RGB, GL_UNSIGNED_SHORT_5_6_5, + dataImage.bits()); + + } else { + QImage dataImage = QGLWidget_convertToGLFormat(img); + + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, max, + max, 0, + (dataImage.format() == QImage::Format_ARGB32)?GL_RGBA:GL_RGB, + GL_UNSIGNED_BYTE, 0); + + glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, dataImage.width(), + dataImage.height(), + (dataImage.format() == QImage::Format_ARGB32)?GL_RGBA:GL_RGB, + GL_UNSIGNED_BYTE, dataImage.bits()); + } - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, dataImage.width(), - dataImage.height(), 0, - (dataImage.format() == QImage::Format_ARGB32)?GL_RGBA:GL_RGB, - GL_UNSIGNED_BYTE, dataImage.bits()); + d->glWidth = qreal(img.width()) / qreal(max); + d->glHeight = qreal(img.height()) / qreal(max); } d->width = img.width(); -- cgit v0.12 From 716e2105dce4487baa32a4e11b69f1d394515a86 Mon Sep 17 00:00:00 2001 From: Andy Shaw Date: Wed, 3 Jun 2009 11:11:41 +0200 Subject: Add a note about what happens when passing 0 to qobject_cast in the doc Reviewed-by: Kavindra Palaraja --- src/corelib/kernel/qobject.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index 7e5f779..6583b85 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -912,7 +912,8 @@ QObject::~QObject() \relates QObject Returns the given \a object cast to type T if the object is of type - T (or of a subclass); otherwise returns 0. + T (or of a subclass); otherwise returns 0. If \a object is 0 then + it will also return 0. The class T must inherit (directly or indirectly) QObject and be declared with the \l Q_OBJECT macro. -- cgit v0.12 From ee735a39a333ddff4d5d0734062093ba553850f2 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 3 Jun 2009 11:23:33 +0200 Subject: use of QMutexPool to reduce the number of Q_GLOBAL_STATIC in the animation framework --- src/corelib/animation/qpropertyanimation.cpp | 47 +++++++++++++++------------- src/corelib/animation/qvariantanimation.cpp | 29 ++++++++--------- 2 files changed, 40 insertions(+), 36 deletions(-) diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp index 43b5283..357a6ac 100644 --- a/src/corelib/animation/qpropertyanimation.cpp +++ b/src/corelib/animation/qpropertyanimation.cpp @@ -91,19 +91,17 @@ #include "qpropertyanimation.h" #include "qanimationgroup.h" -#include - #include "qpropertyanimation_p.h" #include #include +#include QT_BEGIN_NAMESPACE typedef QPair QPropertyAnimationPair; typedef QHash QPropertyAnimationHash; Q_GLOBAL_STATIC(QPropertyAnimationHash, _q_runningAnimations) -Q_GLOBAL_STATIC_WITH_ARGS(QMutex, guardHashLock, (QMutex::Recursive) ) void QPropertyAnimationPrivate::updateMetaProperty() { @@ -284,27 +282,32 @@ void QPropertyAnimation::updateState(QAbstractAnimation::State oldState, } QVariantAnimation::updateState(oldState, newState); - QMutexLocker locker(guardHashLock()); - QPropertyAnimationHash * hash = _q_runningAnimations(); - QPropertyAnimationPair key(d->target, d->propertyName); - if (newState == Running) { - d->updateMetaProperty(); - QPropertyAnimation *oldAnim = hash->value(key, 0); - if (oldAnim) { - // try to stop the top level group - QAbstractAnimation *current = oldAnim; - while (current->group() && current->state() != Stopped) - current = current->group(); - current->stop(); - } - hash->insert(key, this); - // update the default start value - if (oldState == Stopped) { - d->setDefaultStartValue(d->target->property(d->propertyName.constData())); + QPropertyAnimation *animToStop = 0; + { + QPropertyAnimationHash * hash = _q_runningAnimations(); + QMutexLocker locker(QMutexPool::globalInstanceGet(hash)); + QPropertyAnimationPair key(d->target, d->propertyName); + if (newState == Running) { + d->updateMetaProperty(); + animToStop = hash->value(key, 0); + hash->insert(key, this); + // update the default start value + if (oldState == Stopped) { + d->setDefaultStartValue(d->target->property(d->propertyName.constData())); + } + } else if (hash->value(key) == this) { + hash->remove(key); } - } else if (hash->value(key) == this) { - hash->remove(key); + } + + //we need to do that after the mutex was unlocked + if (animToStop) { + // try to stop the top level group + QAbstractAnimation *current = animToStop; + while (current->group() && current->state() != Stopped) + current = current->group(); + current->stop(); } } diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp index e973ec5..a3fa93a 100644 --- a/src/corelib/animation/qvariantanimation.cpp +++ b/src/corelib/animation/qvariantanimation.cpp @@ -44,11 +44,10 @@ #include "qvariantanimation.h" #include "qvariantanimation_p.h" -#include -#include -#include -#include -#include +#include +#include +#include +#include QT_BEGIN_NAMESPACE @@ -365,8 +364,8 @@ void QVariantAnimation::setEasingCurve(const QEasingCurve &easing) d->recalculateCurrentInterval(); } -Q_GLOBAL_STATIC(QVector, registeredInterpolators) -Q_GLOBAL_STATIC(QReadWriteLock, registeredInterpolatorsLock) +typedef QVector QInterpolatorVector; +Q_GLOBAL_STATIC(QInterpolatorVector, registeredInterpolators) /*! \fn void qRegisterAnimationInterpolator(QVariant (*func)(const T &from, const T &to, qreal progress)) @@ -398,10 +397,11 @@ Q_GLOBAL_STATIC(QReadWriteLock, registeredInterpolatorsLock) void QVariantAnimation::registerInterpolator(QVariantAnimation::Interpolator func, int interpolationType) { // will override any existing interpolators - QWriteLocker locker(registeredInterpolatorsLock()); - if (int(interpolationType) >= registeredInterpolators()->count()) - registeredInterpolators()->resize(int(interpolationType) + 1); - registeredInterpolators()->replace(interpolationType, func); + QInterpolatorVector *interpolators = registeredInterpolators(); + QMutexLocker locker(QMutexPool::globalInstanceGet(interpolators)); + if (int(interpolationType) >= interpolators->count()) + interpolators->resize(int(interpolationType) + 1); + interpolators->replace(interpolationType, func); } @@ -412,10 +412,11 @@ template static inline QVariantAnimation::Interpolator castToInterpo QVariantAnimation::Interpolator QVariantAnimationPrivate::getInterpolator(int interpolationType) { - QReadLocker locker(registeredInterpolatorsLock()); + QInterpolatorVector *interpolators = registeredInterpolators(); + QMutexLocker locker(QMutexPool::globalInstanceGet(interpolators)); QVariantAnimation::Interpolator ret = 0; - if (interpolationType < registeredInterpolators()->count()) { - ret = registeredInterpolators()->at(interpolationType); + if (interpolationType < interpolators->count()) { + ret = interpolators->at(interpolationType); if (ret) return ret; } -- cgit v0.12 From 4948f4b188c6aa40e628d74d6d6fce747ee535bd Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 2 Jun 2009 15:26:43 +0200 Subject: open pipes in overlapped mode also on the client side otherwise PeekNamedPipe() may block in threaded environments. Reviewed-by: thiago --- src/network/socket/qlocalsocket_win.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/network/socket/qlocalsocket_win.cpp b/src/network/socket/qlocalsocket_win.cpp index 39c9284..ace3bc5 100644 --- a/src/network/socket/qlocalsocket_win.cpp +++ b/src/network/socket/qlocalsocket_win.cpp @@ -144,7 +144,7 @@ void QLocalSocket::connectToServer(const QString &name, OpenMode openMode) 0, // no sharing NULL, // default security attributes OPEN_EXISTING, // opens existing pipe - 0, // default attributes + FILE_FLAG_OVERLAPPED, NULL); // no template file }, { localSocket = CreateFileA( @@ -153,7 +153,7 @@ void QLocalSocket::connectToServer(const QString &name, OpenMode openMode) 0, // no sharing NULL, // default security attributes OPEN_EXISTING, // opens existing pipe - 0, // default attributes + FILE_FLAG_OVERLAPPED, NULL); // no template file }); if (localSocket != INVALID_HANDLE_VALUE) -- cgit v0.12 From 61926772f3c628baefbfe61c28004ffb9ae2b175 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 2 Jun 2009 18:17:13 +0200 Subject: centralize removeServer() invocation for some more determinism --- tests/auto/qlocalsocket/tst_qlocalsocket.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/tests/auto/qlocalsocket/tst_qlocalsocket.cpp b/tests/auto/qlocalsocket/tst_qlocalsocket.cpp index deabda6..12be540 100644 --- a/tests/auto/qlocalsocket/tst_qlocalsocket.cpp +++ b/tests/auto/qlocalsocket/tst_qlocalsocket.cpp @@ -113,8 +113,6 @@ tst_QLocalSocket::tst_QLocalSocket() #endif )) qWarning() << "lackey executable doesn't exists!"; - - QLocalServer::removeServer("tst_localsocket"); } tst_QLocalSocket::~tst_QLocalSocket() @@ -139,7 +137,13 @@ public: LocalServer() : QLocalServer() { connect(this, SIGNAL(newConnection()), this, SLOT(slotNewConnection())); - }; + } + + bool listen(const QString &name) + { + removeServer(name); + return QLocalServer::listen(name); + } QList hits; @@ -528,7 +532,7 @@ void tst_QLocalSocket::sendData() // QLocalSocket/Server can take a name or path, check that it works as expected void tst_QLocalSocket::fullPath() { - QLocalServer server; + LocalServer server; QString name = "qlocalsocket_pathtest"; #if defined(QT_LOCALSOCKET_TCP) QString path = "QLocalServer"; @@ -822,7 +826,7 @@ void tst_QLocalSocket::removeServer() void tst_QLocalSocket::recycleServer() { - QLocalServer server; + LocalServer server; QLocalSocket client; QVERIFY(server.listen("recycletest1")); -- cgit v0.12 From 517ebf6f06db90a46d62c397d8e4c940cd7ac62b Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 2 Jun 2009 13:05:13 +0200 Subject: fix lithuanian plural rules --- tools/linguist/shared/numerus.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/linguist/shared/numerus.cpp b/tools/linguist/shared/numerus.cpp index f3a29cc..dd9c5ee 100644 --- a/tools/linguist/shared/numerus.cpp +++ b/tools/linguist/shared/numerus.cpp @@ -74,7 +74,7 @@ static const uchar macedonianRules[] = Q_MOD_10 | Q_EQ, 2 }; static const uchar lithuanianRules[] = { Q_MOD_10 | Q_EQ, 1, Q_AND, Q_MOD_100 | Q_NEQ, 11, Q_NEWRULE, - Q_MOD_10 | Q_EQ, 2, Q_AND, Q_MOD_100 | Q_NOT_BETWEEN, 10, 19 }; + Q_MOD_10 | Q_NEQ, 0, Q_AND, Q_MOD_100 | Q_NOT_BETWEEN, 10, 19 }; static const uchar russianStyleRules[] = { Q_MOD_10 | Q_EQ, 1, Q_AND, Q_MOD_100 | Q_NEQ, 11, Q_NEWRULE, Q_MOD_10 | Q_BETWEEN, 2, 4, Q_AND, Q_MOD_100 | Q_NOT_BETWEEN, 10, 19 }; @@ -112,7 +112,7 @@ static const char * const irishStyleForms[] = { "Singular", "Dual", "Plural", 0 static const char * const czechForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const slovakForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const macedonianForms[] = { "Singular", "Dual", "Plural", 0 }; -static const char * const lithuanianForms[] = { "Singular", "Dual", "Plural", 0 }; +static const char * const lithuanianForms[] = { "Singular", "Paucal", "Plural", 0 }; static const char * const russianStyleForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const polishForms[] = { "Singular", "Paucal", "Plural", 0 }; static const char * const romanianForms[] = -- cgit v0.12 From 70be10968c8f547b464b3150ba582766e679ec7d Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 2 Jun 2009 14:11:31 +0200 Subject: fix icelandic plural forms --- tools/linguist/shared/numerus.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tools/linguist/shared/numerus.cpp b/tools/linguist/shared/numerus.cpp index dd9c5ee..8ca6ef6 100644 --- a/tools/linguist/shared/numerus.cpp +++ b/tools/linguist/shared/numerus.cpp @@ -60,6 +60,8 @@ static const uchar frenchStyleRules[] = static const uchar latvianRules[] = { Q_MOD_10 | Q_EQ, 1, Q_AND, Q_MOD_100 | Q_NEQ, 11, Q_NEWRULE, Q_NEQ, 0 }; +static const uchar icelandicRules[] = + { Q_MOD_10 | Q_EQ, 1, Q_AND, Q_MOD_100 | Q_NEQ, 11 }; static const uchar irishStyleRules[] = { Q_EQ, 1, Q_NEWRULE, Q_EQ, 2 }; @@ -107,6 +109,7 @@ static const uchar arabicRules[] = static const char * const japaneseStyleForms[] = { "Universal Form", 0 }; static const char * const englishStyleForms[] = { "Singular", "Plural", 0 }; static const char * const frenchStyleForms[] = { "Singular", "Plural", 0 }; +static const char * const icelandicForms[] = { "Singular", "Plural", 0 }; static const char * const latvianForms[] = { "Singular", "Plural", "Nullar", 0 }; static const char * const irishStyleForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const czechForms[] = { "Singular", "Dual", "Plural", 0 }; @@ -190,7 +193,6 @@ static const QLocale::Language englishStyleLanguages[] = { QLocale::Hausa, QLocale::Hebrew, QLocale::Hindi, - QLocale::Icelandic, QLocale::Interlingua, QLocale::Interlingue, QLocale::Italian, @@ -261,6 +263,7 @@ static const QLocale::Language frenchStyleLanguages[] = { EOL }; static const QLocale::Language latvianLanguage[] = { QLocale::Latvian, EOL }; +static const QLocale::Language icelandicLanguage[] = { QLocale::Icelandic, EOL }; static const QLocale::Language irishStyleLanguages[] = { QLocale::Divehi, QLocale::Gaelic, @@ -320,6 +323,7 @@ static const NumerusTableEntry numerusTable[] = { { frenchStyleRules, sizeof(frenchStyleRules), frenchStyleForms, frenchStyleLanguages, frenchStyleCountries }, { latvianRules, sizeof(latvianRules), latvianForms, latvianLanguage, 0 }, + { icelandicRules, sizeof(icelandicRules), icelandicForms, icelandicLanguage, 0 }, { irishStyleRules, sizeof(irishStyleRules), irishStyleForms, irishStyleLanguages, 0 }, { czechRules, sizeof(czechRules), czechForms, czechLanguage, 0 }, { slovakRules, sizeof(slovakRules), slovakForms, slovakLanguage, 0 }, -- cgit v0.12 From a9472cb582fe155dd21f7bd3189afb64d5b08ab8 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 2 Jun 2009 14:40:51 +0200 Subject: fix tagalog plural forms --- tools/linguist/shared/numerus.cpp | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tools/linguist/shared/numerus.cpp b/tools/linguist/shared/numerus.cpp index 8ca6ef6..239b4c7 100644 --- a/tools/linguist/shared/numerus.cpp +++ b/tools/linguist/shared/numerus.cpp @@ -105,6 +105,9 @@ static const uchar arabicRules[] = Q_EQ, 2, Q_NEWRULE, Q_MOD_100 | Q_BETWEEN, 3, 10, Q_NEWRULE, Q_MOD_100 | Q_NEQ, 0 }; +static const uchar tagalogRules[] = + { Q_LEQ, 1, Q_NEWRULE, + Q_MOD_10 | Q_EQ, 4, Q_OR, Q_MOD_10 | Q_EQ, 6, Q_OR, Q_MOD_10 | Q_EQ, 9 }; static const char * const japaneseStyleForms[] = { "Universal Form", 0 }; static const char * const englishStyleForms[] = { "Singular", "Plural", 0 }; @@ -127,6 +130,8 @@ static const char * const welshForms[] = { "Nullar", "Singular", "Dual", "Sexal", "Plural", 0 }; static const char * const arabicForms[] = { "Nullar", "Singular", "Dual", "Minority Plural", "Plural", "Plural Form for 100, 200, ...", 0 }; +static const char * const tagalogForms[] = + { "Singular", "Plural (consonant-ended)", "Plural (vowel-ended)", 0 }; #define EOL QLocale::C @@ -233,7 +238,6 @@ static const QLocale::Language englishStyleLanguages[] = { QLocale::Spanish, QLocale::Swahili, QLocale::Swedish, - QLocale::Tagalog, QLocale::Tajik, QLocale::Tamil, QLocale::Tatar, @@ -301,6 +305,7 @@ static const QLocale::Language slovenianLanguage[] = { QLocale::Slovenian, EOL } static const QLocale::Language malteseLanguage[] = { QLocale::Maltese, EOL }; static const QLocale::Language welshLanguage[] = { QLocale::Welsh, EOL }; static const QLocale::Language arabicLanguage[] = { QLocale::Arabic, EOL }; +static const QLocale::Language tagalogLanguage[] = { QLocale::Tagalog, EOL }; static const QLocale::Country frenchStyleCountries[] = { // keep synchronized with frenchStyleLanguages @@ -335,7 +340,8 @@ static const NumerusTableEntry numerusTable[] = { { slovenianRules, sizeof(slovenianRules), slovenianForms, slovenianLanguage, 0 }, { malteseRules, sizeof(malteseRules), malteseForms, malteseLanguage, 0 }, { welshRules, sizeof(welshRules), welshForms, welshLanguage, 0 }, - { arabicRules, sizeof(arabicRules), arabicForms, arabicLanguage, 0 } + { arabicRules, sizeof(arabicRules), arabicForms, arabicLanguage, 0 }, + { tagalogRules, sizeof(tagalogRules), tagalogForms, tagalogLanguage, 0 } }; static const int NumerusTableSize = sizeof(numerusTable) / sizeof(numerusTable[0]); -- cgit v0.12 From 4cc2d62669b1638d34b6588bd3b164fb17138596 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Tue, 2 Jun 2009 14:42:24 +0200 Subject: fix turkish plural forms --- tools/linguist/shared/numerus.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/linguist/shared/numerus.cpp b/tools/linguist/shared/numerus.cpp index 239b4c7..3a06065 100644 --- a/tools/linguist/shared/numerus.cpp +++ b/tools/linguist/shared/numerus.cpp @@ -155,6 +155,7 @@ static const QLocale::Language japaneseStyleLanguages[] = { QLocale::Sundanese, QLocale::Thai, QLocale::Tibetan, + QLocale::Turkish, QLocale::Vietnamese, QLocale::Yoruba, QLocale::Zhuang, @@ -244,7 +245,6 @@ static const QLocale::Language englishStyleLanguages[] = { QLocale::Telugu, QLocale::TongaLanguage, QLocale::Tsonga, - QLocale::Turkish, QLocale::Turkmen, QLocale::Twi, QLocale::Uigur, -- cgit v0.12 From 78b44fdb2b505833a9b60fcd63e1fe8c8a59d9ed Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Wed, 3 Jun 2009 11:14:46 +0200 Subject: drop traditional czech plural rules in favor of today's slovak-like rules --- tools/linguist/shared/numerus.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/tools/linguist/shared/numerus.cpp b/tools/linguist/shared/numerus.cpp index 3a06065..408877f 100644 --- a/tools/linguist/shared/numerus.cpp +++ b/tools/linguist/shared/numerus.cpp @@ -65,9 +65,6 @@ static const uchar icelandicRules[] = static const uchar irishStyleRules[] = { Q_EQ, 1, Q_NEWRULE, Q_EQ, 2 }; -static const uchar czechRules[] = - { Q_MOD_100 | Q_EQ, 1, Q_NEWRULE, - Q_MOD_100 | Q_BETWEEN, 2, 4 }; static const uchar slovakRules[] = { Q_EQ, 1, Q_NEWRULE, Q_BETWEEN, 2, 4 }; @@ -115,7 +112,6 @@ static const char * const frenchStyleForms[] = { "Singular", "Plural", 0 }; static const char * const icelandicForms[] = { "Singular", "Plural", 0 }; static const char * const latvianForms[] = { "Singular", "Plural", "Nullar", 0 }; static const char * const irishStyleForms[] = { "Singular", "Dual", "Plural", 0 }; -static const char * const czechForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const slovakForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const macedonianForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const lithuanianForms[] = { "Singular", "Paucal", "Plural", 0 }; @@ -281,8 +277,7 @@ static const QLocale::Language irishStyleLanguages[] = { QLocale::Sanskrit, EOL }; -static const QLocale::Language czechLanguage[] = { QLocale::Czech, EOL }; -static const QLocale::Language slovakLanguage[] = { QLocale::Slovak, EOL }; +static const QLocale::Language slovakLanguages[] = { QLocale::Slovak, QLocale::Czech, EOL }; static const QLocale::Language macedonianLanguage[] = { QLocale::Macedonian, EOL }; static const QLocale::Language lithuanianLanguage[] = { QLocale::Lithuanian, EOL }; static const QLocale::Language russianStyleLanguages[] = { @@ -330,8 +325,7 @@ static const NumerusTableEntry numerusTable[] = { { latvianRules, sizeof(latvianRules), latvianForms, latvianLanguage, 0 }, { icelandicRules, sizeof(icelandicRules), icelandicForms, icelandicLanguage, 0 }, { irishStyleRules, sizeof(irishStyleRules), irishStyleForms, irishStyleLanguages, 0 }, - { czechRules, sizeof(czechRules), czechForms, czechLanguage, 0 }, - { slovakRules, sizeof(slovakRules), slovakForms, slovakLanguage, 0 }, + { slovakRules, sizeof(slovakRules), slovakForms, slovakLanguages, 0 }, { macedonianRules, sizeof(macedonianRules), macedonianForms, macedonianLanguage, 0 }, { lithuanianRules, sizeof(lithuanianRules), lithuanianForms, lithuanianLanguage, 0 }, { russianStyleRules, sizeof(russianStyleRules), russianStyleForms, russianStyleLanguages, 0 }, -- cgit v0.12 From 3e663dcad5e9fbfd2a5466d464747a1a87f036b3 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Wed, 3 Jun 2009 11:06:14 +0200 Subject: rename some plural forms --- tools/linguist/shared/numerus.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/tools/linguist/shared/numerus.cpp b/tools/linguist/shared/numerus.cpp index 408877f..2fe1c78 100644 --- a/tools/linguist/shared/numerus.cpp +++ b/tools/linguist/shared/numerus.cpp @@ -112,16 +112,15 @@ static const char * const frenchStyleForms[] = { "Singular", "Plural", 0 }; static const char * const icelandicForms[] = { "Singular", "Plural", 0 }; static const char * const latvianForms[] = { "Singular", "Plural", "Nullar", 0 }; static const char * const irishStyleForms[] = { "Singular", "Dual", "Plural", 0 }; -static const char * const slovakForms[] = { "Singular", "Dual", "Plural", 0 }; +static const char * const slovakForms[] = { "Singular", "Paucal", "Plural", 0 }; static const char * const macedonianForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const lithuanianForms[] = { "Singular", "Paucal", "Plural", 0 }; static const char * const russianStyleForms[] = { "Singular", "Dual", "Plural", 0 }; static const char * const polishForms[] = { "Singular", "Paucal", "Plural", 0 }; -static const char * const romanianForms[] = - { "Singular", "Plural Form for 2 to 19", "Plural", 0 }; +static const char * const romanianForms[] = { "Singular", "Paucal", "Plural", 0 }; static const char * const slovenianForms[] = { "Singular", "Dual", "Trial", "Plural", 0 }; static const char * const malteseForms[] = - { "Singular", "Plural Form for 2 to 10", "Plural Form for 11 to 19", "Plural", 0 }; + { "Singular", "Paucal", "Greater Paucal", "Plural", 0 }; static const char * const welshForms[] = { "Nullar", "Singular", "Dual", "Sexal", "Plural", 0 }; static const char * const arabicForms[] = -- cgit v0.12 From a3c0fd23dcac2389e20cf0731166c18374d481ec Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 3 Jun 2009 11:38:45 +0200 Subject: fix typos Copy&paste error; the classes are in Gui, not Core. --- src/gui/statemachine/qkeyeventtransition.h | 2 +- src/gui/statemachine/qmouseeventtransition.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/statemachine/qkeyeventtransition.h b/src/gui/statemachine/qkeyeventtransition.h index 3c8295f..d9c7760 100644 --- a/src/gui/statemachine/qkeyeventtransition.h +++ b/src/gui/statemachine/qkeyeventtransition.h @@ -48,7 +48,7 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE -QT_MODULE(Core) +QT_MODULE(Gui) class QKeyEventTransitionPrivate; class Q_GUI_EXPORT QKeyEventTransition : public QEventTransition diff --git a/src/gui/statemachine/qmouseeventtransition.h b/src/gui/statemachine/qmouseeventtransition.h index 3f5f3ac..9c7af5b 100644 --- a/src/gui/statemachine/qmouseeventtransition.h +++ b/src/gui/statemachine/qmouseeventtransition.h @@ -48,7 +48,7 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE -QT_MODULE(Core) +QT_MODULE(Gui) class QMouseEventTransitionPrivate; class QPainterPath; -- cgit v0.12 From f9aa7cbaea69168a4e7b9411cfdceb9e27cf75a9 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 3 Jun 2009 11:44:28 +0200 Subject: fix qdoc warning No need to link to the class in its own doc page. --- src/corelib/statemachine/qstatemachine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp index 84619d7..be816a6 100644 --- a/src/corelib/statemachine/qstatemachine.cpp +++ b/src/corelib/statemachine/qstatemachine.cpp @@ -92,7 +92,7 @@ QT_BEGIN_NAMESPACE QAbstractState) and transitions (descendants of QAbstractTransition) between those states; these states and transitions define a state graph. Once a state graph has been - built, the state machine can execute it. \l{QStateMachine}'s + built, the state machine can execute it. QStateMachine's execution algorithm is based on the \l{State Chart XML: State Machine Notation for Control Abstraction}{State Chart XML (SCXML)} algorithm. The framework's \l{The State Machine -- cgit v0.12 From ae5b1555676cef4058157431c3af2e7ff9ead8ce Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Wed, 3 Jun 2009 12:58:08 +0200 Subject: Doc - minor fixes to beautify the sentence Reviewed-By: TrustMe --- doc/src/tutorials/addressbook.qdoc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc index 3ec883f..15fdd83 100644 --- a/doc/src/tutorials/addressbook.qdoc +++ b/doc/src/tutorials/addressbook.qdoc @@ -374,8 +374,8 @@ \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part2 If the contact already exists, again, we display a QMessageBox to inform - the user about this, to prevent the user from adding duplicate contacts. - Our \c contacts object is based on key-value pairs of name and addresses, + the user about this, preventing the user from adding duplicate contacts. + Our \c contacts object is based on key-value pairs of name and address, hence, we want to ensure that \e key is unique. \o Once we have handled both cases mentioned above, we restore the push -- cgit v0.12 From 259b65c2f5d736dd7f6d81b6390f54464dd5f183 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Tue, 2 Jun 2009 18:16:37 +0200 Subject: BT: qt demo takes 100% of the cpu on X11 The tick timer is always active, even if the moving gree Qt logo is not visible. But the code that is supposed to pause it when the app loose the focus doesn't works if the moving Qt logo is not visible. Also the call to syncX makes Xorg takes lot of cpu. It doesn't fix the fact that the timer is still running while the green logo is not visible, but at least doesn't take the cpu anymore if qtdemo loose the focus. Task-number: 255020 Reviewed-by: Richard Moe Gustavsen --- demos/qtdemo/colors.cpp | 2 +- demos/qtdemo/mainwindow.cpp | 13 ++----------- 2 files changed, 3 insertions(+), 12 deletions(-) diff --git a/demos/qtdemo/colors.cpp b/demos/qtdemo/colors.cpp index 41bbfb3..883b0fb 100644 --- a/demos/qtdemo/colors.cpp +++ b/demos/qtdemo/colors.cpp @@ -97,7 +97,7 @@ bool Colors::noTickerMorph = false; bool Colors::adapted = false; bool Colors::verbose = false; bool Colors::pause = true; -int Colors::fps = 100; +int Colors::fps = 60; int Colors::menuCount = 18; float Colors::animSpeed = 1.0; float Colors::animSpeedButtons = 1.0; diff --git a/demos/qtdemo/mainwindow.cpp b/demos/qtdemo/mainwindow.cpp index 8723823..16ca95f 100644 --- a/demos/qtdemo/mainwindow.cpp +++ b/demos/qtdemo/mainwindow.cpp @@ -190,7 +190,6 @@ void MainWindow::switchTimerOnOff(bool on) if (on && !Colors::noTimerUpdate){ this->useTimer = true; - this->setViewportUpdateMode(QGraphicsView::NoViewportUpdate); this->fpsTime = QTime::currentTime(); this->updateTimer.start(int(1000 / Colors::fps)); } @@ -262,10 +261,6 @@ void MainWindow::tick() if (MenuManager::instance()->ticker) MenuManager::instance()->ticker->tick(); - this->viewport()->update(); - if (Colors::softwareRendering) - QApplication::syncX(); - if (this->useTimer) this->updateTimer.start(int(1000 / Colors::fps)); } @@ -435,9 +430,7 @@ void MainWindow::focusInEvent(QFocusEvent *) if (MenuManager::instance()->ticker) MenuManager::instance()->ticker->pause(false); - int code = MenuManager::instance()->currentMenuCode; - if (code == MenuManager::ROOT || code == MenuManager::MENU1) - this->switchTimerOnOff(true); + this->switchTimerOnOff(true); this->pausedLabel->setRecursiveVisible(false); } @@ -450,9 +443,7 @@ void MainWindow::focusOutEvent(QFocusEvent *) if (MenuManager::instance()->ticker) MenuManager::instance()->ticker->pause(true); - int code = MenuManager::instance()->currentMenuCode; - if (code == MenuManager::ROOT || code == MenuManager::MENU1) - this->switchTimerOnOff(false); + this->switchTimerOnOff(false); this->pausedLabel->setRecursiveVisible(true); } -- cgit v0.12 From e72285b0108f7649366a106f1c16ea73611dbcd4 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 3 Jun 2009 13:17:37 +0200 Subject: don't require use of SIGNAL macro in calls to addTransition() Just as with the QSignalTransition::signal property, this makes it possible to use the function from language bindings (e.g. QtScript). --- src/corelib/statemachine/qstate.cpp | 5 +++-- tests/auto/qstatemachine/tst_qstatemachine.cpp | 28 ++++++++++++++++++++++++++ 2 files changed, 31 insertions(+), 2 deletions(-) diff --git a/src/corelib/statemachine/qstate.cpp b/src/corelib/statemachine/qstate.cpp index 5463059..ebb0b47 100644 --- a/src/corelib/statemachine/qstate.cpp +++ b/src/corelib/statemachine/qstate.cpp @@ -329,9 +329,10 @@ QSignalTransition *QState::addTransition(QObject *sender, const char *signal, qWarning("QState::addTransition: cannot add transition to null state"); return 0; } - if (*signal && sender->metaObject()->indexOfSignal(signal+1) == -1) { + int offset = (*signal == '0'+QSIGNAL_CODE) ? 1 : 0; + if (sender->metaObject()->indexOfSignal(signal+offset) == -1) { qWarning("QState::addTransition: no such signal %s::%s", - sender->metaObject()->className(), signal+1); + sender->metaObject()->className(), signal+offset); return 0; } QSignalTransition *trans = new QSignalTransition(sender, signal, QList() << target); diff --git a/tests/auto/qstatemachine/tst_qstatemachine.cpp b/tests/auto/qstatemachine/tst_qstatemachine.cpp index 768a683..66e50ba 100644 --- a/tests/auto/qstatemachine/tst_qstatemachine.cpp +++ b/tests/auto/qstatemachine/tst_qstatemachine.cpp @@ -1768,6 +1768,34 @@ void tst_QStateMachine::signalTransitions() QState *s0 = new QState(machine.rootState()); QFinalState *s1 = new QFinalState(machine.rootState()); SignalEmitter emitter; + QSignalTransition *trans = s0->addTransition(&emitter, "signalWithNoArg()", s1); + QVERIFY(trans != 0); + QCOMPARE(trans->sourceState(), s0); + QCOMPARE(trans->targetState(), (QAbstractState*)s1); + QCOMPARE(trans->senderObject(), (QObject*)&emitter); + QCOMPARE(trans->signal(), QByteArray("signalWithNoArg()")); + + QSignalSpy finishedSpy(&machine, SIGNAL(finished())); + machine.setInitialState(s0); + machine.start(); + QCoreApplication::processEvents(); + + emitter.emitSignalWithNoArg(); + + QTRY_COMPARE(finishedSpy.count(), 1); + + trans->setSignal("signalWithIntArg(int)"); + QCOMPARE(trans->signal(), QByteArray("signalWithIntArg(int)")); + machine.start(); + QCoreApplication::processEvents(); + emitter.emitSignalWithIntArg(123); + QTRY_COMPARE(finishedSpy.count(), 2); + } + { + QStateMachine machine; + QState *s0 = new QState(machine.rootState()); + QFinalState *s1 = new QFinalState(machine.rootState()); + SignalEmitter emitter; TestSignalTransition *trans = new TestSignalTransition(&emitter, SIGNAL(signalWithIntArg(int)), s1); s0->addTransition(trans); -- cgit v0.12 From a6cb0edd2f8f69ea7b878d65756d47ed166f4224 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 3 Jun 2009 13:21:43 +0200 Subject: fix signal signature bug in debug output The signal code (first character of const char *signal) is stripped internally, so the debug output code should not skip any characters. --- src/corelib/statemachine/qstatemachine.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp index be816a6..d5f6b76 100644 --- a/src/corelib/statemachine/qstatemachine.cpp +++ b/src/corelib/statemachine/qstatemachine.cpp @@ -1329,7 +1329,7 @@ void QStateMachinePrivate::registerSignalTransition(QSignalTransition *transitio if (!ok) { #ifdef QSTATEMACHINE_DEBUG qDebug() << q << ": FAILED to add signal transition from" << transition->sourceState() - << ": ( sender =" << sender << ", signal =" << (signal.mid(1)) + << ": ( sender =" << sender << ", signal =" << signal << ", targets =" << transition->targetStates() << ')'; #endif return; @@ -1339,7 +1339,7 @@ void QStateMachinePrivate::registerSignalTransition(QSignalTransition *transitio QSignalTransitionPrivate::get(transition)->signalIndex = signalIndex; #ifdef QSTATEMACHINE_DEBUG qDebug() << q << ": added signal transition from" << transition->sourceState() - << ": ( sender =" << sender << ", signal =" << (signal.mid(1)) + << ": ( sender =" << sender << ", signal =" << signal << ", targets =" << transition->targetStates() << ')'; #endif } -- cgit v0.12 From 34d003341c5286354e8277a4cc33182c94549ac0 Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Wed, 3 Jun 2009 13:21:21 +0200 Subject: Fix BOM for UTF-32 codec The BOM was created correctly, but half of the BOM was then overwritten by the converted data afterwards. Also made the autotest also do reverse encoding tests where possible. Task-number: 255095 Reviewed-by: lars --- src/corelib/codecs/qutfcodec.cpp | 2 +- tests/auto/qtextcodec/tst_qtextcodec.cpp | 15 ++++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/corelib/codecs/qutfcodec.cpp b/src/corelib/codecs/qutfcodec.cpp index 1ac592e..d9defe1 100644 --- a/src/corelib/codecs/qutfcodec.cpp +++ b/src/corelib/codecs/qutfcodec.cpp @@ -478,7 +478,7 @@ QByteArray QUtf32Codec::convertFromUnicode(const QChar *uc, int len, ConverterSt data[2] = 0; data[3] = 0; } - data += 2; + data += 4; } if (endian == BE) { for (int i = 0; i < len; ++i) { diff --git a/tests/auto/qtextcodec/tst_qtextcodec.cpp b/tests/auto/qtextcodec/tst_qtextcodec.cpp index cf4135b..566b20e 100644 --- a/tests/auto/qtextcodec/tst_qtextcodec.cpp +++ b/tests/auto/qtextcodec/tst_qtextcodec.cpp @@ -1537,7 +1537,7 @@ void tst_QTextCodec::utfHeaders_data() << QByteArray("\xef\xbb\xbfhello") << (QString(QChar(0xfeff)) + QString::fromLatin1("hello")) << true; - QTest::newRow("utf8 nobom") + QTest::newRow("utf8 nobom ignore header") << QByteArray("UTF-8") << (int)QTextCodec::IgnoreHeader << QByteArray("hello") @@ -1718,14 +1718,23 @@ void tst_QTextCodec::utfHeaders() QFETCH(bool, toUnicode); + QLatin1String ignoreReverseTestOn = (QSysInfo::ByteOrder == QSysInfo::BigEndian) ? QLatin1String(" le") : QLatin1String(" be"); + QString rowName(QTest::currentDataTag()); + for (int i = 0; i < encoded.length(); ++i) qDebug() << hex << " " << (uint)(uchar)encoded.at(i); if (toUnicode) { QString result = codec->toUnicode(encoded.constData(), encoded.length(), &state); - for (int i = 0; i < result.length(); ++i) - qDebug() << hex << " " << (uint)result.at(i).unicode(); + for (int i = 0; i < result.length(); ++i) + qDebug() << hex << " " << (uint)result.at(i).unicode(); QCOMPARE(result.length(), unicode.length()); QCOMPARE(result, unicode); + + if (!rowName.endsWith("nobom") && !rowName.contains(ignoreReverseTestOn)) { + QTextCodec::ConverterState state2(cFlags); + QByteArray reencoded = codec->fromUnicode(unicode.unicode(), unicode.length(), &state2); + QCOMPARE(reencoded, encoded); + } } else { QByteArray result = codec->fromUnicode(unicode.unicode(), unicode.length(), &state); QCOMPARE(result, encoded); -- cgit v0.12 From d16b52d5346a3b652ad7507b24373c51fc0d530c Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Wed, 3 Jun 2009 13:49:22 +0200 Subject: Doc - some sentence clean ups Reviewed-by: TrustMe --- doc/src/tutorials/addressbook.qdoc | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc index 15fdd83..bf202b2 100644 --- a/doc/src/tutorials/addressbook.qdoc +++ b/doc/src/tutorials/addressbook.qdoc @@ -296,8 +296,8 @@ We also declare two private QString objects, \c oldName and \c oldAddress. These objects are needed to hold the name and address of the contact that - was last displayed, before the user clicked "Add". So, when the user clicks - "Cancel", we can revert to displaying the details of the last contact. + was last displayed, before the user clicked \gui Add. So, when the user clicks + \gui Cancel, we can revert to displaying the details of the last contact. \section1 Implementing the AddressBook Class @@ -318,7 +318,7 @@ The \c addButton is displayed by invoking the \l{QPushButton::show()} {show()} function, while the \c submitButton and \c cancelButton are hidden by invoking \l{QPushButton::hide()}{hide()}. These two push - buttons will only be displayed when the user clicks "Add" and this is + buttons will only be displayed when the user clicks \gui Add and this is handled by the \c addContact() function discussed below. \snippet tutorials/addressbook/part2/addressbook.cpp connecting signals and slots @@ -362,7 +362,7 @@ \list 1 \o We extract the contact's details from \c nameLine and \c addressText and store them in QString objects. We also validate to make sure that the - user did not click "Submit" with empty input fields; otherwise, a + user did not click \gui Submit with empty input fields; otherwise, a QMessageBox is displayed to remind the user for a name and address. \snippet tutorials/addressbook/part2/addressbook.cpp submitContact part1 @@ -396,9 +396,9 @@ \snippet tutorials/addressbook/part2/addressbook.cpp cancel - The general idea to add a contact is to give the user the flexibility to - click "Submit" or "Cancel" at any time. The flowchart below further - explains this concept: + The general idea behind adding a contact is to give the user the + flexibility to click \gui Submit or \gui Cancel at any time. The flowchart below + further explains this concept: \image addressbook-tutorial-part2-add-flowchart.png */ -- cgit v0.12 From 94376c5ab5caf1889caef29db66f981e34e7c4d5 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Wed, 3 Jun 2009 10:53:11 +0200 Subject: qdoc: Fixed constructor position in summary lists. The constructors had been displayed in the left column of the table in the summary list, because there was no type. It was caused by a strange test of the match index for 0, which was true for constructors and destructors, anything without a type. I removed that test, since I couldn't figure out what it was for. We might see problems elsewhere in the docs because of this, so beware. I didn't see any, but that test must have been there for some reason. --- tools/qdoc3/htmlgenerator.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index 4e4261f..db70862 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -2317,7 +2317,7 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode, static const QString linkTag("link"); for (int i = 0, n = src.size(); i < n;) { if (src.at(i) == charLangle && src.at(i + 1).unicode() == '@') { - if (nameAlignment && (i != 0)) + if (nameAlignment) // && (i != 0)) Why was this here? html += " 

    + + + + + + + + @@ -621,12 +629,14 @@ in the \l{Qt for Windows CE Requirements} document. + + -- cgit v0.12 From ff8dd08c1ec66905a271c528b18c1e6738d2da77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 3 Jun 2009 20:42:42 +0200 Subject: My changes for 4.5.2 --- dist/changes-4.5.2 | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 5149eba..378d565 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -127,6 +127,22 @@ Third party components * [252311] "font-family:" now handle fallback font specified with a comas separated list. +- QFile and QTemporaryFile + * [165920] QFile::copy leaves the source file open after the file has been copied + * [191467] & [252293] QFile::copy of resource files to the filesystem fails on Windows + * [197857] QFile::copy of resource files leaves temporary files on filesystem + * [248223] QTemporaryFile: Access denied error when (re-)opening through QFile interface + * [252659] QTemporaryFile::rename may leave source file behind + +- QByteArrayMatcher + * [251958] Assignment operator and copy constructor miss data + +- QCompleter + * [253125] QCompleter doesn't expand entries with UnfilteredPopupCompletion + +- QPrintDialog + * [253135] Crash in QPrintDialog when editing output filename + **************************************************************************** * Database Drivers * **************************************************************************** @@ -180,6 +196,7 @@ Qt for Windows CE **************************************************************************** - Build System + * [253053] Linker in macx-g++42 spec is gcc instead of gcc-4.2 - Assistant -- cgit v0.12 From 8021218dd5ab2d7ad9314b1c2a54168de4694065 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Abecasis?= Date: Wed, 3 Jun 2009 21:32:55 +0200 Subject: More changes for 4.5.2 --- dist/changes-4.5.2 | 1 + 1 file changed, 1 insertion(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 378d565..6772405 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -128,6 +128,7 @@ Third party components separated list. - QFile and QTemporaryFile + * Fixed a leak of file descriptors in QTemporaryFile::rename, introduced in 4.5.1 * [165920] QFile::copy leaves the source file open after the file has been copied * [191467] & [252293] QFile::copy of resource files to the filesystem fails on Windows * [197857] QFile::copy of resource files leaves temporary files on filesystem -- cgit v0.12 From c45a3295dd926d37ee9d16b109ad6678c850c965 Mon Sep 17 00:00:00 2001 From: Rohan McGovern Date: Thu, 4 Jun 2009 09:10:21 +1000 Subject: Fixes failure when attempting to run all tests. auto.pro added `qtransition' to SUBDIRS but there is no such directory. --- tests/auto/auto.pro | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro index 27e3c74..a65c172 100644 --- a/tests/auto/auto.pro +++ b/tests/auto/auto.pro @@ -349,7 +349,6 @@ SUBDIRS += _networkselftest \ qtranslator \ qtransform \ qtransformedscreen \ - qtransition \ qtreeview \ qtreewidget \ qtreewidgetitemiterator \ -- cgit v0.12 From 7010a53cbd6bc6d9cc6d63e2170a7300ce2750d8 Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Thu, 4 Jun 2009 10:13:54 +1000 Subject: Improvements to shader API in response to API review Task-number: QT-80 Reviewed-by: Ian Walters --- demos/boxes/scene.cpp | 2 +- examples/opengl/hellogl_es2/glwidget.cpp | 8 +- .../gl2paintengineex/qglengineshadermanager.cpp | 3 +- src/opengl/qglshaderprogram.cpp | 158 ++++++++++----------- src/opengl/qglshaderprogram.h | 16 +-- 5 files changed, 88 insertions(+), 99 deletions(-) diff --git a/demos/boxes/scene.cpp b/demos/boxes/scene.cpp index e2aa16b..2376782 100644 --- a/demos/boxes/scene.cpp +++ b/demos/boxes/scene.cpp @@ -559,7 +559,7 @@ void Scene::initGL() << ":/res/boxes/cubemap_negy.jpg" << ":/res/boxes/cubemap_posz.jpg" << ":/res/boxes/cubemap_negz.jpg"; m_environment = new GLTextureCube(list, qMin(1024, m_maxTextureSize)); m_environmentShader = new QGLShader(QGLShader::FragmentShader); - m_environmentShader->setSourceCode(environmentShaderText); + m_environmentShader->compile(environmentShaderText); m_environmentProgram = new QGLShaderProgram; m_environmentProgram->addShader(m_vertexShader); m_environmentProgram->addShader(m_environmentShader); diff --git a/examples/opengl/hellogl_es2/glwidget.cpp b/examples/opengl/hellogl_es2/glwidget.cpp index ee50670..cb4a48d 100644 --- a/examples/opengl/hellogl_es2/glwidget.cpp +++ b/examples/opengl/hellogl_es2/glwidget.cpp @@ -190,7 +190,7 @@ void GLWidget::initializeGL () " color = clamp(color, 0.0, 1.0);\n" " gl_Position = matrix * vertex;\n" "}\n"; - vshader1->setSourceCode(vsrc1); + vshader1->compile(vsrc1); QGLShader *fshader1 = new QGLShader(QGLShader::FragmentShader, this); const char *fsrc1 = @@ -199,7 +199,7 @@ void GLWidget::initializeGL () "{\n" " gl_FragColor = color;\n" "}\n"; - fshader1->setSourceCode(fsrc1); + fshader1->compile(fsrc1); program1.addShader(vshader1); program1.addShader(fshader1); @@ -224,7 +224,7 @@ void GLWidget::initializeGL () " gl_Position = matrix * vertex;\n" " texc = texCoord;\n" "}\n"; - vshader2->setSourceCode(vsrc2); + vshader2->compile(vsrc2); QGLShader *fshader2 = new QGLShader(QGLShader::FragmentShader); const char *fsrc2 = @@ -237,7 +237,7 @@ void GLWidget::initializeGL () " color = color * 0.2 + color * 0.8 * angle;\n" " gl_FragColor = vec4(clamp(color, 0.0, 1.0), 1.0);\n" "}\n"; - fshader2->setSourceCode(fsrc2); + fshader2->compile(fsrc2); program2.addShader(vshader2); program2.addShader(fshader2); diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index 3159cbb..ea57fdf 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -481,8 +481,7 @@ void QGLEngineShaderManager::compileNamedShader(QGLEngineShaderManager::ShaderNa return; QGLShader *newShader = new QGLShader(type, ctx, this); - newShader->setSourceCode(qglEngineShaderSourceCode[name]); - // newShader->compile(); ### does not exist? + newShader->compile(qglEngineShaderSourceCode[name]); #if defined(QT_DEBUG) // Name the shader for easier debugging diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp index d74b930..67fd9d0 100644 --- a/src/opengl/qglshaderprogram.cpp +++ b/src/opengl/qglshaderprogram.cpp @@ -71,7 +71,7 @@ QT_BEGIN_NAMESPACE \code QGLShader shader(QGLShader::VertexShader); - shader.setSourceCode(code); + shader.compile(code); QGLShaderProgram program(context); program.addShader(shader); @@ -265,7 +265,7 @@ public: QByteArray partialSource; bool create(); - bool compile(); + bool compile(QGLShader *q); }; #define ctx context @@ -293,7 +293,7 @@ bool QGLShaderPrivate::create() } } -bool QGLShaderPrivate::compile() +bool QGLShaderPrivate::compile(QGLShader *q) { // Partial shaders are compiled during QGLShaderProgram::link(). if (isPartial && hasPartialSource) { @@ -313,7 +313,11 @@ bool QGLShaderPrivate::compile() GLint len; glGetShaderInfoLog(shader, value, &len, logbuf); log = QString::fromLatin1(logbuf); - qWarning() << "QGLShader::compile:" << log; + QString name = q->objectName(); + if (name.isEmpty()) + qWarning() << "QGLShader::compile:" << log; + else + qWarning() << "QGLShader::compile[" << name << "]:" << log; delete [] logbuf; } return compiled; @@ -325,14 +329,14 @@ bool QGLShaderPrivate::compile() /*! Constructs a new QGLShader object of the specified \a type and attaches it to \a parent. If shader programs are not supported, - then isValid() will return false. + QGLShaderProgram::hasShaderPrograms() will return false. - This constructor is normally followed by a call to setSourceCode() - or setSourceCodeFile(). + This constructor is normally followed by a call to compile() + or compileFile(). The shader will be associated with the current QGLContext. - \sa setSourceCode(), setSourceCodeFile(), isValid() + \sa compile(), compileFile() */ QGLShader::QGLShader(QGLShader::ShaderType type, QObject *parent) : QObject(parent) @@ -346,11 +350,11 @@ QGLShader::QGLShader(QGLShader::ShaderType type, QObject *parent) and attaches it to \a parent. If the filename ends in \c{.fsh}, it is assumed to be a fragment shader, otherwise it is assumed to be a vertex shader (normally the extension is \c{.vsh} for vertex shaders). - If the shader could not be loaded, then isValid() will return false. + If the shader could not be loaded, then isCompiled() will return false. The shader will be associated with the current QGLContext. - \sa isValid() + \sa isCompiled() */ QGLShader::QGLShader(const QString& fileName, QObject *parent) : QObject(parent) @@ -359,7 +363,7 @@ QGLShader::QGLShader(const QString& fileName, QObject *parent) d = new QGLShaderPrivate(QGLShader::FragmentShader, QGLContext::currentContext()); else d = new QGLShaderPrivate(QGLShader::VertexShader, QGLContext::currentContext()); - if (d->create() && !setSourceCodeFile(fileName)) { + if (d->create() && !compileFile(fileName)) { if (d->shader) glDeleteShader(d->shader); d->shader = 0; @@ -369,18 +373,18 @@ QGLShader::QGLShader(const QString& fileName, QObject *parent) /*! Constructs a new QGLShader object of the specified \a type from the source code in \a fileName and attaches it to \a parent. - If the shader could not be loaded, then isValid() will return false. + If the shader could not be loaded, then isCompiled() will return false. The shader will be associated with the current QGLContext. - \sa isValid() + \sa isCompiled() */ QGLShader::QGLShader (const QString& fileName, QGLShader::ShaderType type, QObject *parent) : QObject(parent) { d = new QGLShaderPrivate(type, QGLContext::currentContext()); - if (d->create() && !setSourceCodeFile(fileName)) { + if (d->create() && !compileFile(fileName)) { if (d->shader) glDeleteShader(d->shader); d->shader = 0; @@ -390,14 +394,14 @@ QGLShader::QGLShader /*! Constructs a new QGLShader object of the specified \a type and attaches it to \a parent. If shader programs are not supported, - then isValid() will return false. + then QGLShaderProgram::hasShaderPrograms() will return false. - This constructor is normally followed by a call to setSourceCode() - or setSourceCodeFile(). + This constructor is normally followed by a call to compile() + or compileFile(). The shader will be associated with \a context. - \sa setSourceCode(), setSourceCodeFile(), isValid() + \sa compile(), compileFile() */ QGLShader::QGLShader(QGLShader::ShaderType type, const QGLContext *context, QObject *parent) : QObject(parent) @@ -411,11 +415,11 @@ QGLShader::QGLShader(QGLShader::ShaderType type, const QGLContext *context, QObj and attaches it to \a parent. If the filename ends in \c{.fsh}, it is assumed to be a fragment shader, otherwise it is assumed to be a vertex shader (normally the extension is \c{.vsh} for vertex shaders). - If the shader could not be loaded, then isValid() will return false. + If the shader could not be loaded, then isCompiled() will return false. The shader will be associated with \a context. - \sa isValid() + \sa isCompiled() */ QGLShader::QGLShader(const QString& fileName, const QGLContext *context, QObject *parent) : QObject(parent) @@ -424,7 +428,7 @@ QGLShader::QGLShader(const QString& fileName, const QGLContext *context, QObject d = new QGLShaderPrivate(QGLShader::FragmentShader, context); else d = new QGLShaderPrivate(QGLShader::VertexShader, context); - if (d->create() && !setSourceCodeFile(fileName)) { + if (d->create() && !compileFile(fileName)) { if (d->shader) glDeleteShader(d->shader); d->shader = 0; @@ -434,18 +438,18 @@ QGLShader::QGLShader(const QString& fileName, const QGLContext *context, QObject /*! Constructs a new QGLShader object of the specified \a type from the source code in \a fileName and attaches it to \a parent. - If the shader could not be loaded, then isValid() will return false. + If the shader could not be loaded, then isCompiled() will return false. The shader will be associated with \a context. - \sa isValid() + \sa isCompiled() */ QGLShader::QGLShader (const QString& fileName, QGLShader::ShaderType type, const QGLContext *context, QObject *parent) : QObject(parent) { d = new QGLShaderPrivate(type, context); - if (d->create() && !setSourceCodeFile(fileName)) { + if (d->create() && !compileFile(fileName)) { if (d->shader) glDeleteShader(d->shader); d->shader = 0; @@ -465,24 +469,6 @@ QGLShader::~QGLShader() } /*! - Returns true if this shader is valid. Shaders become invalid - when they are destroyed and no longer attached to a QGLShaderProgram. -*/ -bool QGLShader::isValid() const -{ - if (d->isPartial && d->hasPartialSource) - return true; - if (!d->shader) - return false; -#if defined(QT_OPENGL_ES_2) - return glIsShader(d->shader); -#else - // glIsShader() may not exist on some systems. - return (!glIsShader || glIsShader(d->shader)); -#endif -} - -/*! Returns the type of this shader. */ QGLShader::ShaderType QGLShader::shaderType() const @@ -509,13 +495,15 @@ static const char qualifierDefines[] = then this function will always return true, even if the source code is invalid. Partial shaders are compiled when QGLShaderProgram::link() is called. + + \sa compileFile() */ -bool QGLShader::setSourceCode(const char *source) +bool QGLShader::compile(const char *source) { if (d->isPartial) { d->partialSource = QByteArray(source); d->hasPartialSource = true; - return d->compile(); + return d->compile(this); } else if (d->shader) { QVarLengthArray src; #ifdef QGL_DEFINE_QUALIFIERS @@ -523,7 +511,7 @@ bool QGLShader::setSourceCode(const char *source) #endif src.append(source); glShaderSource(d->shader, src.size(), src.data(), 0); - return d->compile(); + return d->compile(this); } else { return false; } @@ -539,10 +527,12 @@ bool QGLShader::setSourceCode(const char *source) then this function will always return true, even if the source code is invalid. Partial shaders are compiled when QGLShaderProgram::link() is called. + + \sa compileFile() */ -bool QGLShader::setSourceCode(const QByteArray& source) +bool QGLShader::compile(const QByteArray& source) { - return setSourceCode(source.constData()); + return compile(source.constData()); } /*! @@ -555,10 +545,12 @@ bool QGLShader::setSourceCode(const QByteArray& source) then this function will always return true, even if the source code is invalid. Partial shaders are compiled when QGLShaderProgram::link() is called. + + \sa compileFile() */ -bool QGLShader::setSourceCode(const QString& source) +bool QGLShader::compile(const QString& source) { - return setSourceCode(source.toLatin1().constData()); + return compile(source.toLatin1().constData()); } /*! @@ -570,8 +562,10 @@ bool QGLShader::setSourceCode(const QString& source) then this function will always return true, even if the source code is invalid. Partial shaders are compiled when QGLShaderProgram::link() is called. + + \sa compile() */ -bool QGLShader::setSourceCodeFile(const QString& fileName) +bool QGLShader::compileFile(const QString& fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly)) { @@ -580,7 +574,7 @@ bool QGLShader::setSourceCodeFile(const QString& fileName) } QByteArray contents = file.readAll(); - return setSourceCode(contents.constData()); + return compile(contents.constData()); } /*! @@ -592,9 +586,11 @@ bool QGLShader::setSourceCodeFile(const QString& fileName) This function cannot be used with PartialVertexShader or PartialFragmentShader. + If this function succeeds, then the shader will be considered compiled. + \sa shaderBinaryFormats() */ -bool QGLShader::setBinaryCode(GLenum format, const void *binary, int length) +bool QGLShader::setShaderBinary(GLenum format, const void *binary, int length) { #if !defined(QT_OPENGL_ES_2) if (!glShaderBinary) @@ -604,7 +600,8 @@ bool QGLShader::setBinaryCode(GLenum format, const void *binary, int length) return false; glGetError(); // Clear error state. glShaderBinary(1, &(d->shader), format, binary, length); - return (glGetError() == GL_NO_ERROR); + d->compiled = (glGetError() == GL_NO_ERROR); + return d->compiled; } /*! @@ -620,9 +617,11 @@ bool QGLShader::setBinaryCode(GLenum format, const void *binary, int length) This function cannot be used with PartialVertexShader or PartialFragmentShader. + If this function succeeds, then the shader will be considered compiled. + \sa shaderBinaryFormats() */ -bool QGLShader::setBinaryCode +bool QGLShader::setShaderBinary (QGLShader& otherShader, GLenum format, const void *binary, int length) { #if !defined(QT_OPENGL_ES_2) @@ -638,14 +637,16 @@ bool QGLShader::setBinaryCode shaders[0] = d->shader; shaders[1] = otherShader.d->shader; glShaderBinary(2, shaders, format, binary, length); - return (glGetError() == GL_NO_ERROR); + d->compiled = (glGetError() == GL_NO_ERROR); + otherShader.d->compiled = d->compiled; + return d->compiled; } /*! Returns a list of all binary formats that are supported by - setBinaryCode() on this system. + setShaderBinary() on this system. - \sa setBinaryCode() + \sa setShaderBinary() */ QList QGLShader::shaderBinaryFormats() { @@ -665,7 +666,7 @@ QList QGLShader::shaderBinaryFormats() /*! Returns the source code for this shader. - \sa setSourceCode() + \sa compile() */ QByteArray QGLShader::sourceCode() const { @@ -688,7 +689,7 @@ QByteArray QGLShader::sourceCode() const /*! Returns true if this shader has been compiled; false otherwise. - \sa setSourceCode() + \sa compile() */ bool QGLShader::isCompiled() const { @@ -698,7 +699,7 @@ bool QGLShader::isCompiled() const /*! Returns the errors and warnings that occurred during the last compile. - \sa setSourceCode() + \sa compile() */ QString QGLShader::log() const { @@ -762,7 +763,7 @@ public: The shader program will be associated with the current QGLContext. - \sa isValid(), addShader() + \sa addShader() */ QGLShaderProgram::QGLShaderProgram(QObject *parent) : QObject(parent) @@ -776,7 +777,7 @@ QGLShaderProgram::QGLShaderProgram(QObject *parent) The shader program will be associated with \a context. - \sa isValid(), addShader() + \sa addShader() */ QGLShaderProgram::QGLShaderProgram(const QGLContext *context, QObject *parent) : QObject(parent) @@ -815,21 +816,6 @@ bool QGLShaderProgram::init() } /*! - Returns true if this shader program object is valid, false otherwise. -*/ -bool QGLShaderProgram::isValid() const -{ - if (!d->program) - return false; -#if defined(QT_OPENGL_ES_2) - return glIsProgram(d->program); -#else - // glIsProgram() may not exist on some systems. - return (!glIsProgram || glIsProgram(d->program)); -#endif -} - -/*! Adds a compiled \a shader to this shader program. Returns true if the shader could be added, or false otherwise. @@ -881,7 +867,7 @@ bool QGLShaderProgram::addShader(QGLShader::ShaderType type, const char *source) if (!init()) return false; QGLShader *shader = new QGLShader(type, this); - if (!shader->setSourceCode(source)) { + if (!shader->compile(source)) { d->log = shader->log(); delete shader; return false; @@ -1058,7 +1044,11 @@ bool QGLShaderProgram::setProgramBinary(int format, const QByteArray& binary) GLint len; glGetProgramInfoLog(d->program, value, &len, logbuf); d->log = QString::fromLatin1(logbuf); - qWarning() << "QGLShaderProgram::setProgramBinary:" << d->log; + QString name = objectName(); + if (name.isEmpty()) + qWarning() << "QGLShader::setProgramBinary:" << d->log; + else + qWarning() << "QGLShader::setProgramBinary[" << name << "]:" << d->log; delete [] logbuf; } return d->linked; @@ -1130,7 +1120,7 @@ bool QGLShaderProgram::link() d->vertexShader = new QGLShader(QGLShader::VertexShader, this); } - if (!d->vertexShader->setSourceCode(vertexSource)) { + if (!d->vertexShader->compile(vertexSource)) { d->log = d->vertexShader->log(); return false; } @@ -1147,7 +1137,7 @@ bool QGLShaderProgram::link() d->fragmentShader = new QGLShader(QGLShader::FragmentShader, this); } - if (!d->fragmentShader->setSourceCode(fragmentSource)) { + if (!d->fragmentShader->compile(fragmentSource)) { d->log = d->fragmentShader->log(); return false; } @@ -1166,7 +1156,11 @@ bool QGLShaderProgram::link() GLint len; glGetProgramInfoLog(d->program, value, &len, logbuf); d->log = QString::fromLatin1(logbuf); - qWarning() << "QGLShaderProgram::link:" << d->log; + QString name = objectName(); + if (name.isEmpty()) + qWarning() << "QGLShader::link:" << d->log; + else + qWarning() << "QGLShader::link[" << name << "]:" << d->log; delete [] logbuf; } return d->linked; diff --git a/src/opengl/qglshaderprogram.h b/src/opengl/qglshaderprogram.h index b69d28e..ab30c32 100644 --- a/src/opengl/qglshaderprogram.h +++ b/src/opengl/qglshaderprogram.h @@ -79,17 +79,15 @@ public: QGLShader(const QString& fileName, QGLShader::ShaderType type, const QGLContext *context, QObject *parent = 0); virtual ~QGLShader(); - bool isValid() const; - QGLShader::ShaderType shaderType() const; - bool setSourceCode(const char *source); - bool setSourceCode(const QByteArray& source); - bool setSourceCode(const QString& source); - bool setSourceCodeFile(const QString& fileName); + bool compile(const char *source); + bool compile(const QByteArray& source); + bool compile(const QString& source); + bool compileFile(const QString& fileName); - bool setBinaryCode(GLenum format, const void *binary, int length); - bool setBinaryCode(QGLShader& otherShader, GLenum format, const void *binary, int length); + bool setShaderBinary(GLenum format, const void *binary, int length); + bool setShaderBinary(QGLShader& otherShader, GLenum format, const void *binary, int length); static QList shaderBinaryFormats(); @@ -118,8 +116,6 @@ public: explicit QGLShaderProgram(const QGLContext *context, QObject *parent = 0); virtual ~QGLShaderProgram(); - bool isValid() const; - bool addShader(QGLShader *shader); void removeShader(QGLShader *shader); QList shaders() const; -- cgit v0.12 From bf50ad866fc787b7787fd102566993c284622112 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Thu, 4 Jun 2009 11:12:02 +1000 Subject: Cleanup private class member names --- src/declarative/fx/qfximage.cpp | 134 ++++++++++++++++++++-------------------- src/declarative/fx/qfximage_p.h | 28 ++++----- 2 files changed, 81 insertions(+), 81 deletions(-) diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index d3ac38f..509323a 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -141,22 +141,22 @@ QFxImage::~QFxImage() QPixmap QFxImage::pixmap() const { Q_D(const QFxImage); - return d->_pix; + return d->pix; } void QFxImage::setPixmap(const QPixmap &pix) { Q_D(QFxImage); d->url = QUrl(); - d->_pix = pix; - d->_opaque=false; + d->pix = pix; + d->opaque=false; - setImplicitWidth(d->_pix.width()); - setImplicitHeight(d->_pix.height()); + setImplicitWidth(d->pix.width()); + setImplicitHeight(d->pix.height()); #if defined(QFX_RENDER_OPENGL) - d->_texDirty = true; - d->_tex.clear(); + d->texDirty = true; + d->tex.clear(); #endif update(); } @@ -189,7 +189,7 @@ void QFxImage::setPixmap(const QPixmap &pix) QFxScaleGrid *QFxImage::scaleGrid() { Q_D(QFxImage); - return d->scaleGrid(); + return d->getScaleGrid(); } /*! @@ -213,13 +213,13 @@ QFxScaleGrid *QFxImage::scaleGrid() bool QFxImage::isTiled() const { Q_D(const QFxImage); - return d->_tiled; + return d->tiled; } void QFxImage::setTiled(bool tile) { Q_D(QFxImage); - d->_tiled = tile; + d->tiled = tile; } /*! @@ -245,15 +245,15 @@ void QFxImage::setTiled(bool tile) bool QFxImage::isOpaque() const { Q_D(const QFxImage); - return d->_opaque; + return d->opaque; } void QFxImage::setOpaque(bool o) { Q_D(QFxImage); - if (o == d->_opaque) + if (o == d->opaque) return; - d->_opaque = o; + d->opaque = o; setOptions(IsOpaque, o); @@ -296,15 +296,15 @@ void QFxImage::componentComplete() bool QFxImage::smoothTransform() const { Q_D(const QFxImage); - return d->_smooth; + return d->smooth; } void QFxImage::setSmoothTransform(bool s) { Q_D(QFxImage); - if (d->_smooth == s) + if (d->smooth == s) return; - d->_smooth = s; + d->smooth = s; update(); } @@ -320,16 +320,16 @@ void QFxImage::dump(int depth) void QFxImage::paintContents(QPainter &p) { Q_D(QFxImage); - if (d->_pix.isNull()) + if (d->pix.isNull()) return; QPainter::RenderHints oldHints = p.renderHints(); - if (d->_smooth) - p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->_smooth); + if (d->smooth) + p.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform, d->smooth); - QPixmap pix = d->_pix; + QPixmap pix = d->pix; - if (d->_tiled) { + if (d->tiled) { p.save(); p.setClipRect(0, 0, width(), height(), Qt::IntersectClip); QRect me = QRect(0, 0, width(), height()); @@ -348,7 +348,7 @@ void QFxImage::paintContents(QPainter &p) } p.restore(); - } else if (!d->_scaleGrid || d->_scaleGrid->isNull()) { + } else if (!d->scaleGrid || d->scaleGrid->isNull()) { if (width() != pix.width() || height() != pix.height()) { QTransform scale; scale.scale(width() / qreal(pix.width()), @@ -361,10 +361,10 @@ void QFxImage::paintContents(QPainter &p) p.drawPixmap(0, 0, pix); } } else { - int sgl = d->_scaleGrid->left(); - int sgr = d->_scaleGrid->right(); - int sgt = d->_scaleGrid->top(); - int sgb = d->_scaleGrid->bottom(); + int sgl = d->scaleGrid->left(); + int sgr = d->scaleGrid->right(); + int sgt = d->scaleGrid->top(); + int sgb = d->scaleGrid->bottom(); int w = width(); int h = height(); @@ -415,7 +415,7 @@ void QFxImage::paintContents(QPainter &p) QRect(pix.width()-sgr, pix.height() - sgb, sgr, sgb)); } - if (d->_smooth) + if (d->smooth) p.setRenderHints(oldHints); } #elif defined(QFX_RENDER_OPENGL) @@ -424,7 +424,7 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, { Q_D(QFxImage); - if (d->_pix.isNull() || (d->_scaleGrid && !d->_scaleGrid->isNull())) + if (d->pix.isNull() || (d->scaleGrid && !d->scaleGrid->isNull())) return 0; if (count < 8) @@ -440,20 +440,20 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, vertices[4] = 0; vertices[5] = 0; vertices[6] = widthV; vertices[7] = 0; - *texture = &d->_tex; + *texture = &d->tex; - if (d->_tiled) { - float tileWidth = widthV / d->_pix.width(); - float tileHeight = heightV / d->_pix.height(); + if (d->tiled) { + float tileWidth = widthV / d->pix.width(); + float tileHeight = heightV / d->pix.height(); texVertices[0] = 0; texVertices[1] = 0; texVertices[2] = tileWidth; texVertices[3] = 0; texVertices[4] = 0; texVertices[5] = tileHeight; texVertices[6] = tileWidth; texVertices[7] = tileHeight; } else { texVertices[0] = 0; texVertices[1] = 0; - texVertices[2] = d->_tex.glWidth(); texVertices[3] = 0; - texVertices[4] = 0; texVertices[5] = d->_tex.glHeight(); - texVertices[6] = d->_tex.glWidth(); texVertices[7] = d->_tex.glHeight(); + texVertices[2] = d->tex.glWidth(); texVertices[3] = 0; + texVertices[4] = 0; texVertices[5] = d->tex.glHeight(); + texVertices[6] = d->tex.glWidth(); texVertices[7] = d->tex.glHeight(); } return 8; @@ -461,19 +461,19 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, void QFxImagePrivate::checkDirty() { - if (_texDirty && !_pix.isNull()) { - _tex.setImage(_pix.toImage(), GLTexture::PowerOfTwo); - _tex.setHorizontalWrap(GLTexture::Repeat); - _tex.setVerticalWrap(GLTexture::Repeat); + if (texDirty && !pix.isNull()) { + tex.setImage(pix.toImage(), GLTexture::PowerOfTwo); + tex.setHorizontalWrap(GLTexture::Repeat); + tex.setVerticalWrap(GLTexture::Repeat); } - _texDirty = false; + texDirty = false; } #if defined(QFX_RENDER_OPENGL2) void QFxImage::paintGLContents(GLPainter &p) { Q_D(QFxImage); - if (d->_pix.isNull()) + if (d->pix.isNull()) return; QGLShaderProgram *shader = p.useTextureShader(); @@ -486,14 +486,14 @@ void QFxImage::paintGLContents(GLPainter &p) d->checkDirty(); - if (d->_tiled || (!d->_scaleGrid || d->_scaleGrid->isNull())) { + if (d->tiled || (!d->scaleGrid || d->scaleGrid->isNull())) { - if (!d->_tiled) { + if (!d->tiled) { float widthV = width(); float heightV = height(); - float glWidth = d->_tex.glWidth(); - float glHeight = d->_tex.glHeight(); + float glWidth = d->tex.glWidth(); + float glHeight = d->tex.glHeight(); float vert[] = { 0, heightV, @@ -516,7 +516,7 @@ void QFxImage::paintGLContents(GLPainter &p) shader->setAttributeArray(SingleTextureShader::Vertices, vert, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, tex, 2); - glBindTexture(GL_TEXTURE_2D, d->_tex.texture()); + glBindTexture(GL_TEXTURE_2D, d->tex.texture()); glDrawArrays(GL_TRIANGLES, 0, 6); } else { @@ -536,8 +536,8 @@ void QFxImage::paintGLContents(GLPainter &p) } else { - float imgWidth = d->_pix.width(); - float imgHeight = d->_pix.height(); + float imgWidth = d->pix.width(); + float imgHeight = d->pix.height(); if (!imgWidth || !imgHeight) { if (restoreBlend) glEnable(GL_BLEND); @@ -548,33 +548,33 @@ void QFxImage::paintGLContents(GLPainter &p) float heightV = height(); float texleft = 0; - float texright = d->_tex.glWidth(); - float textop = d->_tex.glHeight(); + float texright = d->tex.glWidth(); + float textop = d->tex.glHeight(); float texbottom = 0; float imgleft = 0; float imgright = widthV; float imgtop = 0; float imgbottom = heightV; - const int sgl = d->_scaleGrid->left(); - const int sgr = d->_scaleGrid->right(); - const int sgt = d->_scaleGrid->top(); - const int sgb = d->_scaleGrid->bottom(); + const int sgl = d->scaleGrid->left(); + const int sgr = d->scaleGrid->right(); + const int sgt = d->scaleGrid->top(); + const int sgb = d->scaleGrid->bottom(); if (sgl) { - texleft = d->_tex.glWidth() * float(sgl) / imgWidth; + texleft = d->tex.glWidth() * float(sgl) / imgWidth; imgleft = sgl; } if (sgr) { - texright = d->_tex.glWidth() - float(sgr) / imgWidth; + texright = d->tex.glWidth() - float(sgr) / imgWidth; imgright = widthV - sgr; } if (sgt) { - textop = d->_tex.glHeight() - float(sgb) / imgHeight; + textop = d->tex.glHeight() - float(sgb) / imgHeight; imgtop = sgt; } if (sgb) { - texbottom = d->_tex.glHeight() * float(sgt) / imgHeight; + texbottom = d->tex.glHeight() * float(sgt) / imgHeight; imgbottom = heightV - sgb; } @@ -722,7 +722,7 @@ void QFxImage::paintGLContents(GLPainter &p) 1, texbottom, 1, 0 }; - glBindTexture(GL_TEXTURE_2D, d->_tex.texture()); + glBindTexture(GL_TEXTURE_2D, d->tex.texture()); shader->setAttributeArray(SingleTextureShader::Vertices, vert1, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, tex1, 2); @@ -846,8 +846,8 @@ void QFxImage::setSource(const QString &url) setImplicitWidth(0); setImplicitHeight(0); #if defined(QFX_RENDER_OPENGL) - d->_texDirty = true; - d->_tex.clear(); + d->texDirty = true; + d->tex.clear(); #endif emit statusChanged(d->status); emit sourceChanged(d->source); @@ -889,7 +889,7 @@ void QFxImage::requestFinished() { Q_D(QFxImage); if (d->url.path().endsWith(QLatin1String(".sci"))) { - d->_pix = QFxPixmap(d->sciurl); + d->pix = QFxPixmap(d->sciurl); } else { if (d->reply) { disconnect(d->reply, SIGNAL(downloadProgress(qint64,qint64)), @@ -897,18 +897,18 @@ void QFxImage::requestFinished() if (d->reply->error() != QNetworkReply::NoError) d->status = Error; } - d->_pix = QFxPixmap(d->url); + d->pix = QFxPixmap(d->url); setOptions(QFxImage::SimpleItem, true); } - setImplicitWidth(d->_pix.width()); - setImplicitHeight(d->_pix.height()); + setImplicitWidth(d->pix.width()); + setImplicitHeight(d->pix.height()); if (d->status == Loading) d->status = Idle; d->progress = 1.0; #if defined(QFX_RENDER_OPENGL) - d->_texDirty = true; - d->_tex.clear(); + d->texDirty = true; + d->tex.clear(); #endif emit statusChanged(d->status); emit sourceChanged(d->source); diff --git a/src/declarative/fx/qfximage_p.h b/src/declarative/fx/qfximage_p.h index b3cccf9..b5c6055 100644 --- a/src/declarative/fx/qfximage_p.h +++ b/src/declarative/fx/qfximage_p.h @@ -72,9 +72,9 @@ class QFxImagePrivate : public QFxItemPrivate public: QFxImagePrivate() - : _scaleGrid(0), _tiled(false), _smooth(false), _opaque(false), + : scaleGrid(0), tiled(false), smooth(false), opaque(false), #if defined(QFX_RENDER_OPENGL) - _texDirty(true), + texDirty(true), #endif status(QFxImage::Idle), sciReply(0), progress(0.0) { @@ -82,27 +82,27 @@ public: ~QFxImagePrivate() { - delete _scaleGrid; + delete scaleGrid; } void setContent(QIODevice* dev, const QString &url); - QFxScaleGrid *scaleGrid() + QFxScaleGrid *getScaleGrid() { - if (!_scaleGrid) - _scaleGrid = new QFxScaleGrid; - return _scaleGrid; + if (!scaleGrid) + scaleGrid = new QFxScaleGrid; + return scaleGrid; } - QFxScaleGrid *_scaleGrid; - QPixmap _pix; - bool _tiled : 1; - bool _smooth : 1; - bool _opaque : 1; + QFxScaleGrid *scaleGrid; + QPixmap pix; + bool tiled : 1; + bool smooth : 1; + bool opaque : 1; #if defined(QFX_RENDER_OPENGL) + bool texDirty : 1; void checkDirty(); - bool _texDirty; - GLTexture _tex; + GLTexture tex; #endif QFxImage::Status status; -- cgit v0.12 From b1b09172aee658e085423ddf6abfea291a072c74 Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Thu, 4 Jun 2009 11:41:44 +1000 Subject: Code cleanup - use constructor initializers in shader classes. Task-number: QT-80 Reviewed-by: Ian Walters --- src/opengl/qglshaderprogram.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/opengl/qglshaderprogram.cpp b/src/opengl/qglshaderprogram.cpp index 67fd9d0..37732dd 100644 --- a/src/opengl/qglshaderprogram.cpp +++ b/src/opengl/qglshaderprogram.cpp @@ -245,14 +245,14 @@ class QGLShaderPrivate { public: QGLShaderPrivate(QGLShader::ShaderType type, const QGLContext *ctx) + : context(ctx) + , shader(0) + , shaderType(type) + , compiled(false) + , isPartial(type == QGLShader::PartialVertexShader || + type == QGLShader::PartialFragmentShader) + , hasPartialSource(false) { - context = ctx; - shader = 0; - shaderType = type; - compiled = false; - isPartial = (type == QGLShader::PartialVertexShader || - type == QGLShader::PartialFragmentShader); - hasPartialSource = false; } const QGLContext *context; @@ -727,14 +727,14 @@ class QGLShaderProgramPrivate { public: QGLShaderProgramPrivate(const QGLContext *ctx) + : context(ctx) + , program(0) + , linked(false) + , inited(false) + , hasPartialShaders(false) + , vertexShader(0) + , fragmentShader(0) { - context = ctx; - program = 0; - linked = false; - inited = false; - hasPartialShaders = false; - vertexShader = 0; - fragmentShader = 0; } ~QGLShaderProgramPrivate() { -- cgit v0.12 From 0288e838e9d2ab80cea65134861692cc09f528fb Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Thu, 4 Jun 2009 11:54:14 +1000 Subject: Only run loading animation when visible. --- demos/declarative/flickr/content/Loading.qml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/demos/declarative/flickr/content/Loading.qml b/demos/declarative/flickr/content/Loading.qml index cf27e38..7488a66 100644 --- a/demos/declarative/flickr/content/Loading.qml +++ b/demos/declarative/flickr/content/Loading.qml @@ -1,6 +1,6 @@ Image { id: Loading; source: "pics/loading.png"; transformOrigin: "Center" rotation: NumericAnimation { - id: "RotationAnimation"; from: 0; to: 360; running:true; repeat: true; duration: 900 + id: "RotationAnimation"; from: 0; to: 360; running: Loading.visible == true; repeat: true; duration: 900 } } -- cgit v0.12 From f7cf2cdc0b6c83a639d155987f871f7932c1d845 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Thu, 4 Jun 2009 12:32:47 +1000 Subject: Cleanup private class member names --- src/declarative/fx/qfxrect.cpp | 212 ++++++++++++++++++++--------------------- src/declarative/fx/qfxrect_p.h | 26 ++--- 2 files changed, 119 insertions(+), 119 deletions(-) diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index c053001..d52e31c 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -253,13 +253,13 @@ void QFxRect::doUpdate() { #if defined(QFX_RENDER_QPAINTER) Q_D(QFxRect); - d->_rectImage = QPixmap(); + d->rectImage = QPixmap(); #endif #if defined(QFX_RENDER_OPENGL) Q_D(QFxRect); - d->_rectTexture.clear(); + d->rectTexture.clear(); #endif - const int pw = d->_pen && d->_pen->isValid() ? d->_pen->width() : 0; + const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0; setPaintMargin((pw+1)/2); update(); } @@ -277,7 +277,7 @@ void QFxRect::doUpdate() QFxPen *QFxRect::pen() { Q_D(QFxRect); - return d->pen(); + return d->getPen(); } /*! @@ -348,20 +348,20 @@ void QFxRect::setGradient(QFxGradient *gradient) qreal QFxRect::radius() const { Q_D(const QFxRect); - return d->_radius; + return d->radius; } void QFxRect::setRadius(qreal radius) { Q_D(QFxRect); - if (d->_radius == radius) + if (d->radius == radius) return; - d->_radius = radius; + d->radius = radius; #if defined(QFX_RENDER_QPAINTER) - d->_rectImage = QPixmap(); + d->rectImage = QPixmap(); #elif defined(QFX_RENDER_OPENGL) - d->_rectTexture.clear(); + d->rectTexture.clear(); #endif update(); } @@ -370,7 +370,7 @@ void QFxRect::dump(int depth) { Q_D(QFxRect); QByteArray ba(depth * 4, ' '); - qWarning() << ba.constData() << "QFxRect:" << d->_color; + qWarning() << ba.constData() << "QFxRect:" << d->color; QFxItem::dump(depth); } @@ -394,21 +394,21 @@ void QFxRect::dump(int depth) QColor QFxRect::color() const { Q_D(const QFxRect); - return d->_color; + return d->color; } void QFxRect::setColor(const QColor &c) { Q_D(QFxRect); - if (d->_color == c) + if (d->color == c) return; - d->_color = c; + d->color = c; #if defined(QFX_RENDER_QPAINTER) - d->_rectImage = QPixmap(); + d->rectImage = QPixmap(); #endif #if defined(QFX_RENDER_OPENGL) - d->_rectTexture.clear(); + d->rectTexture.clear(); #endif update(); } @@ -437,30 +437,30 @@ void QFxRect::setColor(const QColor &c) QColor QFxRect::tintColor() const { Q_D(const QFxRect); - return d->_tintColor; + return d->tintColor; } void QFxRect::setTintColor(const QColor &c) { Q_D(QFxRect); - if (d->_tintColor == c) + if (d->tintColor == c) return; - d->_tintColor = c; + d->tintColor = c; update(); } QColor QFxRectPrivate::getColor() { - if (_tintColor.isValid()) { - int a = _tintColor.alpha(); + if (tintColor.isValid()) { + int a = tintColor.alpha(); if (a == 0xFF) - return _tintColor; + return tintColor; else if (a == 0x00) - return _color; + return color; else { - uint src = _tintColor.rgba(); - uint dest = _color.rgba(); + uint src = tintColor.rgba(); + uint dest = color.rgba(); uint res = (((a * (src & 0xFF00FF)) + ((0xFF - a) * (dest & 0xFF00FF))) >> 8) & 0xFF00FF; @@ -472,7 +472,7 @@ QColor QFxRectPrivate::getColor() return QColor::fromRgba(res); } } else { - return _color; + return color; } } @@ -481,82 +481,82 @@ QColor QFxRectPrivate::getColor() void QFxRect::generateRoundedRect() { Q_D(QFxRect); - if (d->_rectImage.isNull()) { - const int pw = d->_pen && d->_pen->isValid() ? d->_pen->width() : 0; - d->_rectImage = QPixmap(d->_radius*2 + 3 + pw*2, d->_radius*2 + 3 + pw*2); - d->_rectImage.fill(Qt::transparent); - QPainter p(&(d->_rectImage)); + if (d->rectImage.isNull()) { + const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0; + d->rectImage = QPixmap(d->radius*2 + 3 + pw*2, d->radius*2 + 3 + pw*2); + d->rectImage.fill(Qt::transparent); + QPainter p(&(d->rectImage)); p.setRenderHint(QPainter::Antialiasing); - if (d->_pen && d->_pen->isValid()) { - QPen pn(QColor(pen()->color()), pen()->width()); + if (d->pen && d->pen->isValid()) { + QPen pn(QColor(getPen()->color()), getPen()->width()); p.setPen(pn); } else { p.setPen(Qt::NoPen); } - p.setBrush(d->_color); - p.drawRoundedRect((pw+1)/2, (pw+1)/2, d->_rectImage.width()-(pw+1)/2*2, d->_rectImage.height()-(pw+1)/2*2, d->_radius, d->_radius); + p.setBrush(d->color); + p.drawRoundedRect((pw+1)/2, (pw+1)/2, d->rectImage.width()-(pw+1)/2*2, d->rectImage.height()-(pw+1)/2*2, d->radius, d->radius); } } void QFxRect::generateBorderedRect() { Q_D(QFxRect); - if (d->_rectImage.isNull()) { - const int pw = d->_pen && d->_pen->isValid() ? d->_pen->width() : 0; - d->_rectImage = QPixmap(d->pen()->width()*2 + 3 + pw*2, d->pen()->width()*2 + 3 + pw*2); - d->_rectImage.fill(Qt::transparent); - QPainter p(&(d->_rectImage)); + if (d->rectImage.isNull()) { + const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0; + d->rectImage = QPixmap(d->getPen()->width()*2 + 3 + pw*2, d->getPen()->width()*2 + 3 + pw*2); + d->rectImage.fill(Qt::transparent); + QPainter p(&(d->rectImage)); p.setRenderHint(QPainter::Antialiasing); - if (d->_pen && d->_pen->isValid()) { - QPen pn(QColor(pen()->color()), pen()->width()); + if (d->pen && d->pen->isValid()) { + QPen pn(QColor(getPen()->color()), getPen()->width()); p.setPen(pn); } else { p.setPen(Qt::NoPen); } - p.setBrush(d->_color); - p.drawRect(qreal(pw+1)/2, qreal(pw+1)/2, d->_rectImage.width()-(pw+1)/2*2, d->_rectImage.height()-(pw+1)/2*2); + p.setBrush(d->color); + p.drawRect(qreal(pw+1)/2, qreal(pw+1)/2, d->rectImage.width()-(pw+1)/2*2, d->rectImage.height()-(pw+1)/2*2); } } #elif defined(QFX_RENDER_OPENGL) void QFxRect::generateRoundedRect() { Q_D(QFxRect); - if (d->_rectTexture.isNull()) { - const int pw = d->_pen && d->_pen->isValid() ? d->_pen->width() : 0; - QImage roundRect(d->_radius*2 + 4 + pw*2, d->_radius*2 + 4 + pw*2, QImage::Format_ARGB32_Premultiplied); + if (d->rectTexture.isNull()) { + const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0; + QImage roundRect(d->radius*2 + 4 + pw*2, d->radius*2 + 4 + pw*2, QImage::Format_ARGB32_Premultiplied); roundRect.fill(0); QPainter p(&roundRect); p.setRenderHint(QPainter::Antialiasing); - if (d->_pen && d->_pen->isValid()) { + if (d->pen && d->pen->isValid()) { QPen pn(QColor(pen()->color()), pen()->width()); p.setPen(pn); } else { p.setPen(Qt::NoPen); } - p.setBrush(d->_color); - p.drawRoundedRect((pw+1)/2, (pw+1)/2, roundRect.width()-(pw+1)/2*2, roundRect.height()-(pw+1)/2*2, d->_radius, d->_radius); - d->_rectTexture.setImage(roundRect, GLTexture::PowerOfTwo); + p.setBrush(d->color); + p.drawRoundedRect((pw+1)/2, (pw+1)/2, roundRect.width()-(pw+1)/2*2, roundRect.height()-(pw+1)/2*2, d->radius, d->radius); + d->rectTexture.setImage(roundRect, GLTexture::PowerOfTwo); } } void QFxRect::generateBorderedRect() { Q_D(QFxRect); - if (d->_rectTexture.isNull()) { - const int pw = d->_pen && d->_pen->isValid() ? d->_pen->width() : 0; + if (d->rectTexture.isNull()) { + const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0; QImage borderedRect(pw*2 + 4, pw*2 + 4, QImage::Format_ARGB32_Premultiplied); borderedRect.fill(0); QPainter p(&(borderedRect)); p.setRenderHint(QPainter::Antialiasing); - if (d->_pen && d->_pen->isValid()) { + if (d->pen && d->pen->isValid()) { QPen pn(QColor(pen()->color()), pen()->width()); p.setPen(pn); } else { p.setPen(Qt::NoPen); } - p.setBrush(d->_color); + p.setBrush(d->color); p.drawRect(qreal(pw+1)/2, qreal(pw+1)/2, borderedRect.width()-(pw+1)/2*2, borderedRect.height()-(pw+1)/2*2); - d->_rectTexture.setImage(borderedRect, GLTexture::PowerOfTwo); + d->rectTexture.setImage(borderedRect, GLTexture::PowerOfTwo); } } #endif @@ -566,7 +566,7 @@ void QFxRect::generateBorderedRect() void QFxRect::paintContents(QPainter &p) { Q_D(QFxRect); - if (d->_radius > 0 || (d->_pen && d->_pen->isValid()) + if (d->radius > 0 || (d->pen && d->pen->isValid()) || (d->gradient && d->gradient->gradient()) ) drawRect(p); else @@ -581,26 +581,26 @@ void QFxRect::drawRect(QPainter &p) // Image path won't work for gradients though QPainter::RenderHints oldHints = p.renderHints(); p.setRenderHint(QPainter::Antialiasing); - if (d->_pen && d->_pen->isValid()) { - QPen pn(QColor(pen()->color()), pen()->width()); + if (d->pen && d->pen->isValid()) { + QPen pn(QColor(getPen()->color()), getPen()->width()); p.setPen(pn); } else { p.setPen(Qt::NoPen); } p.setBrush(*d->gradient->gradient()); - if (d->_radius > 0.) - p.drawRoundedRect(0, 0, width(), height(), d->_radius, d->_radius); + if (d->radius > 0.) + p.drawRoundedRect(0, 0, width(), height(), d->radius, d->radius); else p.drawRect(0, 0, width(), height()); p.setRenderHints(oldHints); } else { int offset = 0; - const int pw = d->_pen && d->_pen->isValid() ? (d->_pen->width()+1)/2*2 : 0; + const int pw = d->pen && d->pen->isValid() ? (d->pen->width()+1)/2*2 : 0; - if (d->_radius > 0) { + if (d->radius > 0) { generateRoundedRect(); //### implicit conversion to int - offset = int(d->_radius+1.5+pw); + offset = int(d->radius+1.5+pw); } else { generateBorderedRect(); offset = pw+1; @@ -627,40 +627,40 @@ void QFxRect::drawRect(QPainter &p) } // Upper left - p.drawPixmap(QRect(-pw/2, -pw/2, xOffset, yOffset), d->_rectImage, QRect(0, 0, xOffset, yOffset)); + p.drawPixmap(QRect(-pw/2, -pw/2, xOffset, yOffset), d->rectImage, QRect(0, 0, xOffset, yOffset)); // Upper middle if (xMiddles) - p.drawPixmap(QRect(xOffset-pw/2, -pw/2, width() - xSide + pw, yOffset), d->_rectImage, - QRect(d->_rectImage.width()/2, 0, 1, yOffset)); + p.drawPixmap(QRect(xOffset-pw/2, -pw/2, width() - xSide + pw, yOffset), d->rectImage, + QRect(d->rectImage.width()/2, 0, 1, yOffset)); // Upper right - p.drawPixmap(QPoint(width()-xOffset+pw/2, -pw/2), d->_rectImage, - QRect(d->_rectImage.width()-xOffset, 0, xOffset, yOffset)); + p.drawPixmap(QPoint(width()-xOffset+pw/2, -pw/2), d->rectImage, + QRect(d->rectImage.width()-xOffset, 0, xOffset, yOffset)); // Middle left if (yMiddles) - p.drawPixmap(QRect(-pw/2, yOffset-pw/2, xOffset, height() - ySide + pw), d->_rectImage, - QRect(0, d->_rectImage.height()/2, xOffset, 1)); + p.drawPixmap(QRect(-pw/2, yOffset-pw/2, xOffset, height() - ySide + pw), d->rectImage, + QRect(0, d->rectImage.height()/2, xOffset, 1)); // Middle if (xMiddles && yMiddles) // XXX paint errors in animation example //p.fillRect(xOffset-pw/2, yOffset-pw/2, width() - xSide + pw, height() - ySide + pw, d->getColor()); - p.drawPixmap(QRect(xOffset-pw/2, yOffset-pw/2, width() - xSide + pw, height() - ySide + pw), d->_rectImage, - QRect(d->_rectImage.width()/2, d->_rectImage.height()/2, 1, 1)); + p.drawPixmap(QRect(xOffset-pw/2, yOffset-pw/2, width() - xSide + pw, height() - ySide + pw), d->rectImage, + QRect(d->rectImage.width()/2, d->rectImage.height()/2, 1, 1)); // Middle right if (yMiddles) - p.drawPixmap(QRect(width()-xOffset+pw/2, yOffset-pw/2, xOffset, height() - ySide + pw), d->_rectImage, - QRect(d->_rectImage.width()-xOffset, d->_rectImage.height()/2, xOffset, 1)); + p.drawPixmap(QRect(width()-xOffset+pw/2, yOffset-pw/2, xOffset, height() - ySide + pw), d->rectImage, + QRect(d->rectImage.width()-xOffset, d->rectImage.height()/2, xOffset, 1)); // Lower left - p.drawPixmap(QPoint(-pw/2, height() - yOffset + pw/2), d->_rectImage, QRect(0, d->_rectImage.height() - yOffset, xOffset, yOffset)); + p.drawPixmap(QPoint(-pw/2, height() - yOffset + pw/2), d->rectImage, QRect(0, d->rectImage.height() - yOffset, xOffset, yOffset)); // Lower Middle if (xMiddles) - p.drawPixmap(QRect(xOffset-pw/2, height() - yOffset +pw/2, width() - xSide + pw, yOffset), d->_rectImage, - QRect(d->_rectImage.width()/2, d->_rectImage.height() - yOffset, 1, yOffset)); + p.drawPixmap(QRect(xOffset-pw/2, height() - yOffset +pw/2, width() - xSide + pw, yOffset), d->rectImage, + QRect(d->rectImage.width()/2, d->rectImage.height() - yOffset, 1, yOffset)); // Lower Right - p.drawPixmap(QPoint(width()-xOffset+pw/2, height() - yOffset+pw/2), d->_rectImage, - QRect(d->_rectImage.width()-xOffset, d->_rectImage.height() - yOffset, xOffset, yOffset)); + p.drawPixmap(QPoint(width()-xOffset+pw/2, height() - yOffset+pw/2), d->rectImage, + QRect(d->rectImage.width()-xOffset, d->rectImage.height() - yOffset, xOffset, yOffset)); } } #endif @@ -671,7 +671,7 @@ void QFxRect::drawRect(QPainter &p) void QFxRect::paintGLContents(GLPainter &p) { Q_D(QFxRect); - if (d->_radius == 0 && (!d->_pen || !d->_pen->isValid())) { + if (d->radius == 0 && (!d->pen || !d->pen->isValid())) { if (d->gradient) { float widthV = width(); float heightV = height(); @@ -709,11 +709,11 @@ void QFxRect::paintGLContents(GLPainter &p) } } else { qreal offset = 0; - qreal pw = d->_pen && d->_pen->isValid() ? d->_pen->width() : 0.0; + qreal pw = d->pen && d->pen->isValid() ? d->pen->width() : 0.0; - if (d->_radius > 0) { + if (d->radius > 0) { generateRoundedRect(); - offset = d->_radius + pw+1.5; + offset = d->radius + pw+1.5; } else { generateBorderedRect(); offset = pw+1.5; @@ -721,8 +721,8 @@ void QFxRect::paintGLContents(GLPainter &p) QGLShaderProgram *shader = p.useTextureShader(); - float texWidth = d->_rectTexture.width(); - float texHeight = d->_rectTexture.height(); + float texWidth = d->rectTexture.width(); + float texHeight = d->rectTexture.height(); if (!texWidth || !texHeight) return; @@ -756,10 +756,10 @@ void QFxRect::paintGLContents(GLPainter &p) if (offset==1) texleft=texright=textop=texbottom=0.5; - texleft *= d->_rectTexture.glWidth(); - texright *= d->_rectTexture.glWidth(); - textop *= d->_rectTexture.glHeight(); - texbottom *= d->_rectTexture.glHeight(); + texleft *= d->rectTexture.glWidth(); + texright *= d->rectTexture.glWidth(); + textop *= d->rectTexture.glHeight(); + texbottom *= d->rectTexture.glHeight(); float vert1[] = { -pw/2, -pw/2, -pw/2, imgtop, @@ -852,35 +852,35 @@ void QFxRect::paintGLContents(GLPainter &p) texright, 0, texright, textop, - d->_rectTexture.glWidth(), 0, + d->rectTexture.glWidth(), 0, texright, textop, - d->_rectTexture.glWidth(), 0, - d->_rectTexture.glWidth(), textop, + d->rectTexture.glWidth(), 0, + d->rectTexture.glWidth(), textop, - 0, d->_rectTexture.glHeight(), + 0, d->rectTexture.glHeight(), 0, texbottom, - texleft, d->_rectTexture.glHeight(), + texleft, d->rectTexture.glHeight(), 0, texbottom, - texleft, d->_rectTexture.glHeight(), + texleft, d->rectTexture.glHeight(), texleft, texbottom, - texleft, d->_rectTexture.glHeight(), + texleft, d->rectTexture.glHeight(), texleft, texbottom, - texright, d->_rectTexture.glHeight(), + texright, d->rectTexture.glHeight(), texleft, texbottom, - texright, d->_rectTexture.glHeight(), + texright, d->rectTexture.glHeight(), texright, texbottom, - texright, d->_rectTexture.glHeight(), + texright, d->rectTexture.glHeight(), texright, texbottom, - d->_rectTexture.glWidth(), d->_rectTexture.glHeight(), + d->rectTexture.glWidth(), d->rectTexture.glHeight(), texright, texbottom, - d->_rectTexture.glWidth(), d->_rectTexture.glHeight(), - d->_rectTexture.glWidth(), texbottom, + d->rectTexture.glWidth(), d->rectTexture.glHeight(), + d->rectTexture.glWidth(), texbottom, 0, textop, 0, texbottom, @@ -900,15 +900,15 @@ void QFxRect::paintGLContents(GLPainter &p) texright, textop, texright, texbottom, - d->_rectTexture.glWidth(), textop, + d->rectTexture.glWidth(), textop, texright, texbottom, - d->_rectTexture.glWidth(), textop, - d->_rectTexture.glWidth(), texbottom }; + d->rectTexture.glWidth(), textop, + d->rectTexture.glWidth(), texbottom }; - glBindTexture(GL_TEXTURE_2D, d->_rectTexture.texture()); + glBindTexture(GL_TEXTURE_2D, d->rectTexture.texture()); shader->setAttributeArray(SingleTextureShader::Vertices, vert1, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, tex1, 2); diff --git a/src/declarative/fx/qfxrect_p.h b/src/declarative/fx/qfxrect_p.h index 8cafcbb..6d11917 100644 --- a/src/declarative/fx/qfxrect_p.h +++ b/src/declarative/fx/qfxrect_p.h @@ -69,13 +69,13 @@ class QFxRectPrivate : public QFxItemPrivate public: QFxRectPrivate() - : gradient(0), _pen(0), _radius(0) + : gradient(0), pen(0), radius(0) { } ~QFxRectPrivate() { - delete _pen; + delete pen; } void init() @@ -83,24 +83,24 @@ public: } #if defined(QFX_RENDER_OPENGL) - GLTexture _rectTexture; + GLTexture rectTexture; #endif QColor getColor(); - QColor _color; + QColor color; QFxGradient *gradient; - QColor _tintColor; - QFxPen *pen() { - if (!_pen) { + QColor tintColor; + QFxPen *getPen() { + if (!pen) { Q_Q(QFxRect); - _pen = new QFxPen; - QObject::connect(_pen, SIGNAL(updated()), q, SLOT(doUpdate())); + pen = new QFxPen; + QObject::connect(pen, SIGNAL(updated()), q, SLOT(doUpdate())); } - return _pen; + return pen; } - QFxPen *_pen; - qreal _radius; + QFxPen *pen; + qreal radius; #if defined(QFX_RENDER_QPAINTER) - QPixmap _rectImage; + QPixmap rectImage; #endif }; -- cgit v0.12 From a276e872e83e0c2f04a367299580ef787b6efc51 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Thu, 4 Jun 2009 13:35:15 +1000 Subject: Share GL textures where possible --- src/declarative/canvas/qsimplecanvas_opengl.cpp | 84 +++++++++++++++- src/declarative/canvas/qsimplecanvas_p.h | 3 + src/declarative/canvas/qsimplecanvasitem.h | 23 +++++ src/declarative/fx/qfximage.cpp | 57 ++++++----- src/declarative/fx/qfximage_p.h | 4 +- src/declarative/fx/qfxrect.cpp | 126 ++++++++++++++---------- src/declarative/fx/qfxrect_p.h | 4 +- 7 files changed, 221 insertions(+), 80 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvas_opengl.cpp b/src/declarative/canvas/qsimplecanvas_opengl.cpp index 659104d..7969a2a 100644 --- a/src/declarative/canvas/qsimplecanvas_opengl.cpp +++ b/src/declarative/canvas/qsimplecanvas_opengl.cpp @@ -294,7 +294,7 @@ void QSimpleCanvasItemPrivate::setupChildState(QSimpleCanvasItem *child) } } -//#define QSIMPLECANVAS_DISABLE_TREE_CLIPPING +#define QSIMPLECANVAS_DISABLE_TREE_CLIPPING QRectF QSimpleCanvasItemPrivate::setupPainting(int version, int &z, QSimpleCanvasItem **opaqueList) { static QRectF scene(-1., -1., 2., 2.); @@ -595,4 +595,86 @@ void QSimpleCanvasItem::GLPainter::fillRect(const QRectF &rect, glEnable(GL_BLEND); } +void QSimpleCanvasItem::CachedTexture::addRef() +{ + ++r; +} + +void QSimpleCanvasItem::CachedTexture::release() +{ + Q_ASSERT(r > 0); + --r; + + if (r == 0) { + if (!s.isEmpty()) + d->cachedTextures.remove(s); + delete this; + } +} + +int QSimpleCanvasItem::CachedTexture::pixmapWidth() const +{ + return w; +} + +int QSimpleCanvasItem::CachedTexture::pixmapHeight() const +{ + return h; +} + +QSimpleCanvasItem::CachedTexture::CachedTexture() +: r(0), w(0), h(0) +{ +} + +QSimpleCanvasItem::CachedTexture * +QSimpleCanvasItem::cachedTexture(const QString &key) +{ + Q_D(QSimpleCanvasItem); + if (!d->canvas || key.isEmpty()) + return 0; + + QSimpleCanvasPrivate *canvas = d->canvas->d; + QHash::ConstIterator iter = + canvas->cachedTextures.find(key); + if (iter != canvas->cachedTextures.end()) { + (*iter)->addRef(); + return (*iter); + } else { + return 0; + } +} + +QSimpleCanvasItem::CachedTexture * +QSimpleCanvasItem::cachedTexture(const QString &key, const QPixmap &pix) +{ + Q_D(QSimpleCanvasItem); + if (!d->canvas) + return 0; + + QSimpleCanvasPrivate *canvas = d->canvas->d; + QHash::ConstIterator iter = + canvas->cachedTextures.end(); + if (!key.isEmpty()) + iter = canvas->cachedTextures.find(key); + + if (iter != canvas->cachedTextures.end()) { + (*iter)->addRef(); + return (*iter); + } else { + CachedTexture *rv = new CachedTexture; + rv->s = key; + rv->d = canvas; + rv->w = pix.width(); + rv->h = pix.height(); + rv->setImage(pix.toImage(), GLTexture::PowerOfTwo); + rv->setHorizontalWrap(GLTexture::Repeat); + rv->setVerticalWrap(GLTexture::Repeat); + rv->addRef(); + if (!key.isEmpty()) + canvas->cachedTextures.insert(key, rv); + return rv; + } +} + QT_END_NAMESPACE diff --git a/src/declarative/canvas/qsimplecanvas_p.h b/src/declarative/canvas/qsimplecanvas_p.h index 5fc0c48..3a0186e 100644 --- a/src/declarative/canvas/qsimplecanvas_p.h +++ b/src/declarative/canvas/qsimplecanvas_p.h @@ -43,6 +43,7 @@ #define QSIMPLECANVAS_P_H #include "qsimplecanvas.h" +#include "qsimplecanvasitem.h" #include #include @@ -187,6 +188,8 @@ public: } mutable GLBasicShaders *basicShadersInstance; + QHash cachedTextures; + QList frameBuffers; QGLFramebufferObject *acquire(int, int); void release(QGLFramebufferObject *); diff --git a/src/declarative/canvas/qsimplecanvasitem.h b/src/declarative/canvas/qsimplecanvasitem.h index ee07a21..e62c56d 100644 --- a/src/declarative/canvas/qsimplecanvasitem.h +++ b/src/declarative/canvas/qsimplecanvasitem.h @@ -45,6 +45,7 @@ #include #include #include +#include #include #include @@ -236,6 +237,28 @@ public: static QSimpleCanvasItem *findNextFocus(QSimpleCanvasItem *item); GLBasicShaders *basicShaders() const; + +#if defined(QFX_RENDER_OPENGL) + class CachedTexture : public GLTexture + { + public: + void addRef(); + void release(); + + int pixmapWidth() const; + int pixmapHeight() const; + + private: + CachedTexture(); + friend class QSimpleCanvasItem; + QSimpleCanvasPrivate *d; + QString s; + int r, w, h; + }; + + CachedTexture *cachedTexture(const QString &); + CachedTexture *cachedTexture(const QString &, const QPixmap &); +#endif static QPixmap string(const QString &, const QColor & = Qt::black, const QFont & = QFont()); diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 509323a..03a674d 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -124,9 +124,13 @@ QFxImage::QFxImage(QFxImagePrivate &dd, QFxItem *parent) QFxImage::~QFxImage() { - Q_D(const QFxImage); + Q_D(QFxImage); if (d->sciReply) d->sciReply->deleteLater(); + if (d->tex) { + d->tex->release(); + d->tex = 0; + } } /*! @@ -156,7 +160,10 @@ void QFxImage::setPixmap(const QPixmap &pix) #if defined(QFX_RENDER_OPENGL) d->texDirty = true; - d->tex.clear(); + if (d->tex) { + d->tex->release(); + d->tex = 0; + } #endif update(); } @@ -440,7 +447,7 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, vertices[4] = 0; vertices[5] = 0; vertices[6] = widthV; vertices[7] = 0; - *texture = &d->tex; + *texture = d->tex; if (d->tiled) { float tileWidth = widthV / d->pix.width(); @@ -451,9 +458,9 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, texVertices[6] = tileWidth; texVertices[7] = tileHeight; } else { texVertices[0] = 0; texVertices[1] = 0; - texVertices[2] = d->tex.glWidth(); texVertices[3] = 0; - texVertices[4] = 0; texVertices[5] = d->tex.glHeight(); - texVertices[6] = d->tex.glWidth(); texVertices[7] = d->tex.glHeight(); + texVertices[2] = d->tex->glWidth(); texVertices[3] = 0; + texVertices[4] = 0; texVertices[5] = d->tex->glHeight(); + texVertices[6] = d->tex->glWidth(); texVertices[7] = d->tex->glHeight(); } return 8; @@ -461,11 +468,9 @@ uint QFxImage::glSimpleItemData(float *vertices, float *texVertices, void QFxImagePrivate::checkDirty() { - if (texDirty && !pix.isNull()) { - tex.setImage(pix.toImage(), GLTexture::PowerOfTwo); - tex.setHorizontalWrap(GLTexture::Repeat); - tex.setVerticalWrap(GLTexture::Repeat); - } + Q_Q(QFxImage); + if (texDirty && !pix.isNull()) + tex = q->cachedTexture(url.toString(), pix); texDirty = false; } @@ -492,8 +497,8 @@ void QFxImage::paintGLContents(GLPainter &p) float widthV = width(); float heightV = height(); - float glWidth = d->tex.glWidth(); - float glHeight = d->tex.glHeight(); + float glWidth = d->tex->glWidth(); + float glHeight = d->tex->glHeight(); float vert[] = { 0, heightV, @@ -516,7 +521,7 @@ void QFxImage::paintGLContents(GLPainter &p) shader->setAttributeArray(SingleTextureShader::Vertices, vert, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, tex, 2); - glBindTexture(GL_TEXTURE_2D, d->tex.texture()); + glBindTexture(GL_TEXTURE_2D, d->tex->texture()); glDrawArrays(GL_TRIANGLES, 0, 6); } else { @@ -548,8 +553,8 @@ void QFxImage::paintGLContents(GLPainter &p) float heightV = height(); float texleft = 0; - float texright = d->tex.glWidth(); - float textop = d->tex.glHeight(); + float texright = d->tex->glWidth(); + float textop = d->tex->glHeight(); float texbottom = 0; float imgleft = 0; float imgright = widthV; @@ -562,19 +567,19 @@ void QFxImage::paintGLContents(GLPainter &p) const int sgb = d->scaleGrid->bottom(); if (sgl) { - texleft = d->tex.glWidth() * float(sgl) / imgWidth; + texleft = d->tex->glWidth() * float(sgl) / imgWidth; imgleft = sgl; } if (sgr) { - texright = d->tex.glWidth() - float(sgr) / imgWidth; + texright = d->tex->glWidth() - float(sgr) / imgWidth; imgright = widthV - sgr; } if (sgt) { - textop = d->tex.glHeight() - float(sgb) / imgHeight; + textop = d->tex->glHeight() - float(sgb) / imgHeight; imgtop = sgt; } if (sgb) { - texbottom = d->tex.glHeight() * float(sgt) / imgHeight; + texbottom = d->tex->glHeight() * float(sgt) / imgHeight; imgbottom = heightV - sgb; } @@ -722,7 +727,7 @@ void QFxImage::paintGLContents(GLPainter &p) 1, texbottom, 1, 0 }; - glBindTexture(GL_TEXTURE_2D, d->tex.texture()); + glBindTexture(GL_TEXTURE_2D, d->tex->texture()); shader->setAttributeArray(SingleTextureShader::Vertices, vert1, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, tex1, 2); @@ -847,7 +852,10 @@ void QFxImage::setSource(const QString &url) setImplicitHeight(0); #if defined(QFX_RENDER_OPENGL) d->texDirty = true; - d->tex.clear(); + if (d->tex) { + d->tex->release(); + d->tex = 0; + } #endif emit statusChanged(d->status); emit sourceChanged(d->source); @@ -908,7 +916,10 @@ void QFxImage::requestFinished() d->progress = 1.0; #if defined(QFX_RENDER_OPENGL) d->texDirty = true; - d->tex.clear(); + if (d->tex) { + d->tex->release(); + d->tex = 0; + } #endif emit statusChanged(d->status); emit sourceChanged(d->source); diff --git a/src/declarative/fx/qfximage_p.h b/src/declarative/fx/qfximage_p.h index b5c6055..cd07a37 100644 --- a/src/declarative/fx/qfximage_p.h +++ b/src/declarative/fx/qfximage_p.h @@ -74,7 +74,7 @@ public: QFxImagePrivate() : scaleGrid(0), tiled(false), smooth(false), opaque(false), #if defined(QFX_RENDER_OPENGL) - texDirty(true), + texDirty(true), tex(0), #endif status(QFxImage::Idle), sciReply(0), progress(0.0) { @@ -102,7 +102,7 @@ public: #if defined(QFX_RENDER_OPENGL) bool texDirty : 1; void checkDirty(); - GLTexture tex; + QSimpleCanvasItem::CachedTexture *tex; #endif QFxImage::Status status; diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index d52e31c..eacc85e 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -257,7 +257,10 @@ void QFxRect::doUpdate() #endif #if defined(QFX_RENDER_OPENGL) Q_D(QFxRect); - d->rectTexture.clear(); + if (d->rectTexture) { + d->rectTexture->release(); + d->rectTexture = 0; + } #endif const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0; setPaintMargin((pw+1)/2); @@ -361,7 +364,10 @@ void QFxRect::setRadius(qreal radius) #if defined(QFX_RENDER_QPAINTER) d->rectImage = QPixmap(); #elif defined(QFX_RENDER_OPENGL) - d->rectTexture.clear(); + if (d->rectTexture) { + d->rectTexture->release(); + d->rectTexture = 0; + } #endif update(); } @@ -408,7 +414,10 @@ void QFxRect::setColor(const QColor &c) d->rectImage = QPixmap(); #endif #if defined(QFX_RENDER_OPENGL) - d->rectTexture.clear(); + if (d->rectTexture) { + d->rectTexture->release(); + d->rectTexture = 0; + } #endif update(); } @@ -521,42 +530,55 @@ void QFxRect::generateBorderedRect() void QFxRect::generateRoundedRect() { Q_D(QFxRect); - if (d->rectTexture.isNull()) { + if (!d->rectTexture) { const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0; - QImage roundRect(d->radius*2 + 4 + pw*2, d->radius*2 + 4 + pw*2, QImage::Format_ARGB32_Premultiplied); - roundRect.fill(0); - QPainter p(&roundRect); - p.setRenderHint(QPainter::Antialiasing); - if (d->pen && d->pen->isValid()) { - QPen pn(QColor(pen()->color()), pen()->width()); - p.setPen(pn); - } else { - p.setPen(Qt::NoPen); + QString key = QString("QFxRect://r_%1_%2_%3_%4").arg(pw).arg(d->radius).arg((d->pen && d->pen->isValid())?d->pen->color().name():QString()).arg(d->color.name()); + + d->rectTexture = cachedTexture(key); + + if (!d->rectTexture) { + QPixmap roundRect(d->radius*2 + 4 + pw*2, d->radius*2 + 4 + pw*2); + roundRect.fill(Qt::transparent); + QPainter p(&roundRect); + p.setRenderHint(QPainter::Antialiasing); + if (d->pen && d->pen->isValid()) { + QPen pn(QColor(pen()->color()), pen()->width()); + p.setPen(pn); + } else { + p.setPen(Qt::NoPen); + } + p.setBrush(d->color); + p.drawRoundedRect((pw+1)/2, (pw+1)/2, roundRect.width()-(pw+1)/2*2, roundRect.height()-(pw+1)/2*2, d->radius, d->radius); + + d->rectTexture = cachedTexture(key, roundRect); } - p.setBrush(d->color); - p.drawRoundedRect((pw+1)/2, (pw+1)/2, roundRect.width()-(pw+1)/2*2, roundRect.height()-(pw+1)/2*2, d->radius, d->radius); - d->rectTexture.setImage(roundRect, GLTexture::PowerOfTwo); } } void QFxRect::generateBorderedRect() { Q_D(QFxRect); - if (d->rectTexture.isNull()) { + if (!d->rectTexture) { const int pw = d->pen && d->pen->isValid() ? d->pen->width() : 0; - QImage borderedRect(pw*2 + 4, pw*2 + 4, QImage::Format_ARGB32_Premultiplied); - borderedRect.fill(0); - QPainter p(&(borderedRect)); - p.setRenderHint(QPainter::Antialiasing); - if (d->pen && d->pen->isValid()) { - QPen pn(QColor(pen()->color()), pen()->width()); - p.setPen(pn); - } else { - p.setPen(Qt::NoPen); + QString key = QString("QFxRect://b_%1_%2_%3_%4").arg(pw).arg(d->radius).arg((d->pen && d->pen->isValid())?d->pen->color().name():QString()).arg(d->color.name()); + + d->rectTexture = cachedTexture(key); + + if (!d->rectTexture) { + QPixmap borderedRect(pw*2 + 4, pw*2 + 4); + borderedRect.fill(Qt::transparent); + QPainter p(&(borderedRect)); + p.setRenderHint(QPainter::Antialiasing); + if (d->pen && d->pen->isValid()) { + QPen pn(QColor(pen()->color()), pen()->width()); + p.setPen(pn); + } else { + p.setPen(Qt::NoPen); + } + p.setBrush(d->color); + p.drawRect(qreal(pw+1)/2, qreal(pw+1)/2, borderedRect.width()-(pw+1)/2*2, borderedRect.height()-(pw+1)/2*2); + d->rectTexture = cachedTexture(key, borderedRect); } - p.setBrush(d->color); - p.drawRect(qreal(pw+1)/2, qreal(pw+1)/2, borderedRect.width()-(pw+1)/2*2, borderedRect.height()-(pw+1)/2*2); - d->rectTexture.setImage(borderedRect, GLTexture::PowerOfTwo); } } #endif @@ -721,8 +743,8 @@ void QFxRect::paintGLContents(GLPainter &p) QGLShaderProgram *shader = p.useTextureShader(); - float texWidth = d->rectTexture.width(); - float texHeight = d->rectTexture.height(); + float texWidth = d->rectTexture->width(); + float texHeight = d->rectTexture->height(); if (!texWidth || !texHeight) return; @@ -756,10 +778,10 @@ void QFxRect::paintGLContents(GLPainter &p) if (offset==1) texleft=texright=textop=texbottom=0.5; - texleft *= d->rectTexture.glWidth(); - texright *= d->rectTexture.glWidth(); - textop *= d->rectTexture.glHeight(); - texbottom *= d->rectTexture.glHeight(); + texleft *= d->rectTexture->glWidth(); + texright *= d->rectTexture->glWidth(); + textop *= d->rectTexture->glHeight(); + texbottom *= d->rectTexture->glHeight(); float vert1[] = { -pw/2, -pw/2, -pw/2, imgtop, @@ -852,35 +874,35 @@ void QFxRect::paintGLContents(GLPainter &p) texright, 0, texright, textop, - d->rectTexture.glWidth(), 0, + d->rectTexture->glWidth(), 0, texright, textop, - d->rectTexture.glWidth(), 0, - d->rectTexture.glWidth(), textop, + d->rectTexture->glWidth(), 0, + d->rectTexture->glWidth(), textop, - 0, d->rectTexture.glHeight(), + 0, d->rectTexture->glHeight(), 0, texbottom, - texleft, d->rectTexture.glHeight(), + texleft, d->rectTexture->glHeight(), 0, texbottom, - texleft, d->rectTexture.glHeight(), + texleft, d->rectTexture->glHeight(), texleft, texbottom, - texleft, d->rectTexture.glHeight(), + texleft, d->rectTexture->glHeight(), texleft, texbottom, - texright, d->rectTexture.glHeight(), + texright, d->rectTexture->glHeight(), texleft, texbottom, - texright, d->rectTexture.glHeight(), + texright, d->rectTexture->glHeight(), texright, texbottom, - texright, d->rectTexture.glHeight(), + texright, d->rectTexture->glHeight(), texright, texbottom, - d->rectTexture.glWidth(), d->rectTexture.glHeight(), + d->rectTexture->glWidth(), d->rectTexture->glHeight(), texright, texbottom, - d->rectTexture.glWidth(), d->rectTexture.glHeight(), - d->rectTexture.glWidth(), texbottom, + d->rectTexture->glWidth(), d->rectTexture->glHeight(), + d->rectTexture->glWidth(), texbottom, 0, textop, 0, texbottom, @@ -900,15 +922,15 @@ void QFxRect::paintGLContents(GLPainter &p) texright, textop, texright, texbottom, - d->rectTexture.glWidth(), textop, + d->rectTexture->glWidth(), textop, texright, texbottom, - d->rectTexture.glWidth(), textop, - d->rectTexture.glWidth(), texbottom }; + d->rectTexture->glWidth(), textop, + d->rectTexture->glWidth(), texbottom }; - glBindTexture(GL_TEXTURE_2D, d->rectTexture.texture()); + glBindTexture(GL_TEXTURE_2D, d->rectTexture->texture()); shader->setAttributeArray(SingleTextureShader::Vertices, vert1, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, tex1, 2); diff --git a/src/declarative/fx/qfxrect_p.h b/src/declarative/fx/qfxrect_p.h index 6d11917..d68eb4e 100644 --- a/src/declarative/fx/qfxrect_p.h +++ b/src/declarative/fx/qfxrect_p.h @@ -69,7 +69,7 @@ class QFxRectPrivate : public QFxItemPrivate public: QFxRectPrivate() - : gradient(0), pen(0), radius(0) + : rectTexture(0), gradient(0), pen(0), radius(0) { } @@ -83,7 +83,7 @@ public: } #if defined(QFX_RENDER_OPENGL) - GLTexture rectTexture; + QSimpleCanvasItem::CachedTexture *rectTexture; #endif QColor getColor(); QColor color; -- cgit v0.12 From 289c098c15a359c4e5d142a997230db5df554f8d Mon Sep 17 00:00:00 2001 From: Andy Date: Thu, 4 Jun 2009 08:44:35 +0200 Subject: Silence compile warning in the test Reviewed-by: TrustMe --- tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp b/tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp index 2383767..2f6180f 100644 --- a/tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp +++ b/tests/auto/qnetworkdiskcache/tst_qnetworkdiskcache.cpp @@ -76,7 +76,7 @@ private slots: void oldCacheVersionFile_data(); void oldCacheVersionFile(); - + void sync(); }; @@ -486,7 +486,7 @@ public: void run() { QByteArray longString = "Hello World, this is some long string, well not really that long"; - for (int i = 0; i < 10; ++i) + for (int j = 0; j < 10; ++j) longString += longString; QByteArray longString2 = "Help, I am stuck in an autotest!"; QUrl url(EXAMPLE_URL); -- cgit v0.12 From 85d6409aa650272e1956a7e8f2064d453a6203ad Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Thu, 4 Jun 2009 08:57:43 +0200 Subject: qdoc: Reset the memItemLeft width property to 200. --- tools/qdoc3/htmlgenerator.cpp | 2 +- tools/qdoc3/test/classic.css | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index 422e956..a2a7184 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -2323,7 +2323,7 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode, for (int i = 0, n = src.size(); i < n;) { if (src.at(i) == charLangle && src.at(i + 1).unicode() == '@') { if (nameAlignment) // && (i != 0)) Why was this here? - html += " \n"; - } else { + } + else { while (currentOffsetInParagraph[i] == paragraph[currentParagraphNo[i]].count()) { ++currentParagraphNo[i]; currentOffsetInParagraph[i] = 0; @@ -1959,7 +1961,9 @@ void HtmlGenerator::generateCompactList(const Node *relative, CodeMarker *marker out() << "\n"; @@ -1972,7 +1976,9 @@ void HtmlGenerator::generateCompactList(const Node *relative, CodeMarker *marker out() << "
    "; i += 2; if (parseArg(src, linkTag, &i, n, &arg, &par1)) { -- cgit v0.12 From 8ccecbfef54fbb59eedb3e717c1e2838b96e4fe3 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Wed, 3 Jun 2009 14:06:49 +0200 Subject: qdoc: Fixed some spacing problems. --- tools/qdoc3/htmlgenerator.cpp | 31 +++++++++++++++++++------------ tools/qdoc3/test/classic.css | 2 +- 2 files changed, 20 insertions(+), 13 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index db70862..422e956 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -1118,29 +1118,34 @@ void HtmlGenerator::generateClassLikeNode(const InnerNode *inner, names << (*m)->name(); if ((*m)->type() == Node::Function) { const FunctionNode *func = reinterpret_cast(*m); - if (func->metaness() == FunctionNode::Ctor || func->metaness() == FunctionNode::Dtor - || func->overloadNumber() != 1) + if (func->metaness() == FunctionNode::Ctor || + func->metaness() == FunctionNode::Dtor || + func->overloadNumber() != 1) names.clear(); - } else if ((*m)->type() == Node::Property) { + } + else if ((*m)->type() == Node::Property) { const PropertyNode *prop = reinterpret_cast(*m); - if (!prop->getters().isEmpty() && !names.contains(prop->getters().first()->name())) + if (!prop->getters().isEmpty() && + !names.contains(prop->getters().first()->name())) names << prop->getters().first()->name(); if (!prop->setters().isEmpty()) names << prop->setters().first()->name(); if (!prop->resetters().isEmpty()) names << prop->resetters().first()->name(); - } else if ((*m)->type() == Node::Enum) { - const EnumNode *enume = reinterpret_cast(*m); + } + else if ((*m)->type() == Node::Enum) { + const EnumNode *enume = reinterpret_cast(*m); if (enume->flagsType()) names << enume->flagsType()->name(); foreach (const QString &enumName, - enume->doc().enumItemNames().toSet() - - enume->doc().omitEnumItemNames().toSet()) - names << plainCode(marker->markedUpEnumValue(enumName, enume)); + enume->doc().enumItemNames().toSet() - + enume->doc().omitEnumItemNames().toSet()) + names << plainCode(marker->markedUpEnumValue(enumName, + enume)); } foreach (const QString &name, names) - classSection.keywords += qMakePair(name, linkForNode(*m, 0)); + classSection.keywords += qMakePair(name,linkForNode(*m,0)); } ++m; } @@ -3099,7 +3104,8 @@ void HtmlGenerator::generateDetailedMember(const Node *node, << " type is a typedef for " << "QFlags<" << protect(enume->name()) - << ">. It stores an OR combination of " << protect(enume->name()) + << ">. It stores an OR combination of " + << protect(enume->name()) << " values.

    \n"; } } @@ -3113,7 +3119,8 @@ void HtmlGenerator::findAllClasses(const InnerNode *node) if ((*c)->access() != Node::Private && (*c)->url().isEmpty()) { if ((*c)->type() == Node::Class && !(*c)->doc().isEmpty()) { QString className = (*c)->name(); - if ((*c)->parent() && (*c)->parent()->type() == Node::Namespace && + if ((*c)->parent() && + (*c)->parent()->type() == Node::Namespace && !(*c)->parent()->name().isEmpty()) className = (*c)->parent()->name()+"::"+className; diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index fa0167b..5239856 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -66,7 +66,7 @@ body } table td.memItemLeft { - width: 200px; + width: 100px; padding: 1px 0px 0px 8px; margin: 4px; border-top-width: 1px; -- cgit v0.12 From ab873250fc93df5f5290fedbd5b17872cb1294c6 Mon Sep 17 00:00:00 2001 From: Simon Hausmann Date: Wed, 3 Jun 2009 13:31:44 +0200 Subject: Fix webkit import from the trunk. Updated the file list, the SVG filters have been removed. Reviewed-by: Trust me --- util/webkit/mkdist-webkit | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/util/webkit/mkdist-webkit b/util/webkit/mkdist-webkit index 62264ec..730e8eb 100755 --- a/util/webkit/mkdist-webkit +++ b/util/webkit/mkdist-webkit @@ -109,6 +109,7 @@ excluded_directories="$excluded_directories WebCore/platform/image-decoders/png" excluded_directories="$excluded_directories WebCore/platform/image-decoders/ico" excluded_directories="$excluded_directories WebCore/platform/image-decoders/jpeg" excluded_directories="$excluded_directories WebCore/platform/image-decoders/xbm" +excluded_directories="$excluded_directories WebCore/platform/image-decoders/skia" excluded_directories="$excluded_directories WebCore/plugins/gtk" excluded_directories="$excluded_directories WebCore/plugins/chromium" @@ -120,11 +121,6 @@ excluded_directories="$excluded_directories WebKit/mac" excluded_directories="$excluded_directories WebKit/wx" excluded_directories="$excluded_directories WebKit/cf" -excluded_directories="$excluded_directories WebCore/svg/graphics/cg" -excluded_directories="$excluded_directories WebCore/svg/graphics/cairo" -excluded_directories="$excluded_directories WebCore/svg/graphics/filters/cg" -excluded_directories="$excluded_directories WebCore/svg/graphics/mac" - excluded_directories="$excluded_directories WebKit/English.lproj WebKit/WebKit.xcodeproj" excluded_directories="$excluded_directories WebCore/English.lproj" -- cgit v0.12 From 91f5c7314afdfd43c867266fc1bc418e0f70bac7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 3 Jun 2009 14:16:39 +0200 Subject: Fixed raster bug causing fully clipped images to be partially blended. The blend functions assume the width / height of the images being blended to be greater than 0. A width of 0 caused the first iteration of a duff's device memcpy (QT_MEMCPY_USHORT) to be executed, thus blending 8 pixels instead of none. BT: yes Task-number: 255014 Reviewed-by: Trond --- src/gui/painting/qpaintengine_raster.cpp | 4 ++-- tests/auto/qpainter/tst_qpainter.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 58ffb02..1a1c204 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -1053,7 +1053,7 @@ void QRasterPaintEnginePrivate::drawImage(const QPointF &pt, int d = x + iw - cx2; iw -= d; } - if (iw < 0) + if (iw <= 0) return; // adapt the y paremeters... @@ -1070,7 +1070,7 @@ void QRasterPaintEnginePrivate::drawImage(const QPointF &pt, int d = y + ih - cy2; ih -= d; } - if (ih < 0) + if (ih <= 0) return; // call the blend function... diff --git a/tests/auto/qpainter/tst_qpainter.cpp b/tests/auto/qpainter/tst_qpainter.cpp index 87f9c13..8d6c9d2 100644 --- a/tests/auto/qpainter/tst_qpainter.cpp +++ b/tests/auto/qpainter/tst_qpainter.cpp @@ -215,6 +215,7 @@ private slots: void imageCoordinateLimit(); void imageBlending_data(); void imageBlending(); + void imageBlending_clipped(); void paintOnNullPixmap(); void checkCompositionMode(); @@ -3792,6 +3793,31 @@ void tst_QPainter::imageBlending() } } +void tst_QPainter::imageBlending_clipped() +{ + QImage src(20, 20, QImage::Format_RGB16); + QPainter p(&src); + p.fillRect(src.rect(), Qt::red); + p.end(); + + QImage dst(40, 20, QImage::Format_RGB16); + p.begin(&dst); + p.fillRect(dst.rect(), Qt::white); + p.end(); + + QImage expected = dst; + + p.begin(&dst); + p.setClipRect(QRect(23, 0, 20, 20)); + + // should be completely clipped + p.drawImage(QRectF(3, 0, 20, 20), src); + p.end(); + + // dst should be left unchanged + QCOMPARE(dst, expected); +} + void tst_QPainter::paintOnNullPixmap() { QPixmap pix(16, 16); -- cgit v0.12 From c9c8742b20c025ad893bdde48cf382267e0b646e Mon Sep 17 00:00:00 2001 From: Jason Barron Date: Wed, 3 Jun 2009 15:03:03 +0200 Subject: Allow qmake to compile using it's .pro file. This fixes a problem where qmake would not compile when it was built from it's .pro file because this method uses the pre-compiled header. This header was causing a compile error in qlocale.cpp because qtextstream.h was included and this includes qlocale.h. The problem in qlocale.cpp was that it uses a define called QLOCALE_CPP to enable extra functions in the class declaration, but the pre-compiled header was preventing the qlocale.h from being re-processed and therefore the function was never compiled in. Reviewed-by: Marius Storm-Olsen --- qmake/qmake_pch.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qmake/qmake_pch.h b/qmake/qmake_pch.h index 1fec856..676c806 100644 --- a/qmake/qmake_pch.h +++ b/qmake/qmake_pch.h @@ -53,7 +53,7 @@ //#include "meta.h" #include //#include "winmakefile.h" -#include +//#include //#include "project.h" #include #include -- cgit v0.12 From 826b2ec2067e725561db2892dd432c01f1d36bc7 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Wed, 3 Jun 2009 15:25:46 +0200 Subject: BT: Fix a crash in the SDI example in Cocoa This was quite a bug and it showed to some issues that I hadn't taken into account when doing the initial port to Cocoa. The issue was that we weren't "merging" items into the application menu if an item had already been associated with it. Which seems OK for applications that create one window with one menubar, but breaks down horrible when you have multiple windows with each having their own menubar. The result is that items in the application menu potentially go to the wrong window (and the potential crash). Since there can only ever be one "Quit", "About", or "Preferences" menu item in Cocoa, we need to make sure that we keep these items in sync whenever we switch the menubar or remove actions that are being deleted. That's what we do here. FWIW, QActions with "ApplicationSpecificRole" for their menu role have potential to cause memory leaks or other bugs if abused. If you are a happy open source hacker who wants a thankless job, solving them would get you lots of goodwill in my book. Task-number: 255038 Reviewed-by: Richard Moe Gustavsen --- src/gui/widgets/qmenu_mac.mm | 52 +++++++++++++++++++++++++++++++------------- 1 file changed, 37 insertions(+), 15 deletions(-) diff --git a/src/gui/widgets/qmenu_mac.mm b/src/gui/widgets/qmenu_mac.mm index ad848c9..2560cfa 100644 --- a/src/gui/widgets/qmenu_mac.mm +++ b/src/gui/widgets/qmenu_mac.mm @@ -871,8 +871,6 @@ static NSMenuItem *qt_mac_menu_merge_action(OSMenuRef merge, QMacMenuAction *act } } - if ([ret tag] != 0) - ret = 0; // already taken #endif return ret; } @@ -1131,15 +1129,15 @@ QMenuPrivate::QMacMenuPrivate::addAction(QMacMenuAction *action, QMacMenuAction GetMenuItemAttributes(action->menu, itemCount , &testattr); if (mergedItems.contains(action->command) && (testattr & kMenuItemAttrSeparator)) { - InsertMenuItemTextWithCFString(action->menu, 0, qMax(itemCount - 1, 0), attr, action->command); - index = itemCount; - } else { - MenuItemIndex tmpIndex; - AppendMenuItemTextWithCFString(action->menu, 0, attr, action->command, &tmpIndex); - index = tmpIndex; - if (mergedItems.contains(action->command)) - AppendMenuItemTextWithCFString(action->menu, 0, kMenuItemAttrSeparator, 0, &tmpIndex); - } + InsertMenuItemTextWithCFString(action->menu, 0, qMax(itemCount - 1, 0), attr, action->command); + index = itemCount; + } else { + MenuItemIndex tmpIndex; + AppendMenuItemTextWithCFString(action->menu, 0, attr, action->command, &tmpIndex); + index = tmpIndex; + if (mergedItems.contains(action->command)) + AppendMenuItemTextWithCFString(action->menu, 0, kMenuItemAttrSeparator, 0, &tmpIndex); + } #else [menu addItem:newItem]; #endif @@ -1477,11 +1475,18 @@ QMenuPrivate::QMacMenuPrivate::removeAction(QMacMenuAction *action) DeleteMenuItem(action->menu, qt_mac_menu_find_action(action->menu, action)); #else QMacCocoaAutoReleasePool pool; - QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader(); - if (action->menuItem == [loader quitMenuItem] || action->menuItem == [loader preferencesMenuItem]) - [action->menuItem setEnabled:false]; - else + if (action->merged) { + if (reinterpret_cast([action->menuItem tag]) == action->action) { + QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *loader = getMenuLoader(); + [action->menuItem setEnabled:false]; + if (action->menuItem != [loader quitMenuItem] + && action->menuItem != [loader preferencesMenuItem]) { + [[action->menuItem menu] removeItem:action->menuItem]; + } + } + } else { [[action->menuItem menu] removeItem:action->menuItem]; + } #endif actionItems.removeAll(action); } @@ -1934,6 +1939,23 @@ bool QMenuBar::macUpdateMenuBar() [loader ensureAppMenuInMenu:menu]; [NSApp setMainMenu:menu]; syncMenuBarItemsVisiblity(mb->d_func()->mac_menubar); + + if (OSMenuRef tmpMerge = QMenuPrivate::mergeMenuHash.value(menu)) { + if (QMenuMergeList *mergeList + = QMenuPrivate::mergeMenuItemsHash.value(tmpMerge)) { + const int mergeListSize = mergeList->size(); + + for (int i = 0; i < mergeListSize; ++i) { + const QMenuMergeItem &mergeItem = mergeList->at(i); + // Ideally we would call QMenuPrivate::syncAction, but that requires finding + // the original QMen and likely doing more work than we need. + // For example, enabled is handled below. + [mergeItem.menuItem setTag:reinterpret_cast( + static_cast(mergeItem.action->action))]; + [mergeItem.menuItem setHidden:!(mergeItem.action->action->isVisible())]; + } + } + } #endif QWidget *modalWidget = qApp->activeModalWidget(); if (mb != menubars()->value(modalWidget)) { -- cgit v0.12 From c890793e7a58e1d75d1f88f5e2c88162eddcca44 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Thu, 28 May 2009 17:22:54 +0200 Subject: force activation of minimized windows on Windows mobile When pressing the <- key on a Windows mobile device, the window gets a minimized event (no other soft keys behave like that). Restoring the window via the app menu isn't possible, because the window get a WM_ACTIVATE but its internal state is still minimized. It makes sense to unminimize activated apps on Windows mobile. Task-number: 254673 Reviewed-by: thartman --- src/gui/kernel/qapplication_win.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 670058b..7e97784 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -2063,9 +2063,13 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam // WM_ACTIVATEAPP handles the "true" false case, as this is only when the application // loses focus. Doing it here would result in the widget getting focus to not know // where it got it from; it would simply get a 0 value as the old focus widget. +#ifndef Q_WS_WINCE_WM if (!(widget->windowState() & Qt::WindowMinimized)) { // Ignore the activate message send by WindowsXP to a minimized window -#ifdef Q_WS_WINCE_WM +#else + { + if (widget->windowState() & Qt::WindowMinimized) + widget->dataPtr()->window_state &= ~Qt::WindowMinimized; if (widget->windowState() & Qt::WindowFullScreen) qt_wince_hide_taskbar(widget->winId()); #endif -- cgit v0.12 From 11e77b1e47d527a2c4bca6c72d4597bfd8b8a1c3 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Wed, 3 Jun 2009 14:28:55 +0200 Subject: use a yes/no message box for a yes/no question in http example Using a OK/Cancel message box is weird for a yes/no question, esp. on a Windows CE device where such a message box doesn't have real push buttons but must be OK'ed / cancelled via system buttons in the title bar. Task-number: 255112 Reviewed-by: thartman --- examples/network/http/httpwindow.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/network/http/httpwindow.cpp b/examples/network/http/httpwindow.cpp index ebde770..7aded07 100644 --- a/examples/network/http/httpwindow.cpp +++ b/examples/network/http/httpwindow.cpp @@ -116,8 +116,8 @@ void HttpWindow::downloadFile() if (QMessageBox::question(this, tr("HTTP"), tr("There already exists a file called %1 in " "the current directory. Overwrite?").arg(fileName), - QMessageBox::Ok|QMessageBox::Cancel, QMessageBox::Cancel) - == QMessageBox::Cancel) + QMessageBox::Yes|QMessageBox::No, QMessageBox::No) + == QMessageBox::No) return; QFile::remove(fileName); } -- cgit v0.12 From 5e0aef012a90598b88b547b1b73785f59ef135c1 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Wed, 3 Jun 2009 15:44:20 +0200 Subject: fix silly typo Yeesh. The function worked for the common case of the argument being a plain script object (obviously, otherwise this would have been discovered sooner), but it would never pick the less expensive path when replacing the QObject pointer of an existing proxy. And if you passed in a QVariant proxy (now who would ever do something like that...?), it would assert. --- src/script/qscriptengine.cpp | 2 +- tests/auto/qscriptengine/tst_qscriptengine.cpp | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/script/qscriptengine.cpp b/src/script/qscriptengine.cpp index d8908ed..97021fc 100644 --- a/src/script/qscriptengine.cpp +++ b/src/script/qscriptengine.cpp @@ -587,7 +587,7 @@ QScriptValue QScriptEngine::newQObject(const QScriptValue &scriptObject, QScriptValuePrivate *p = QScriptValuePrivate::get(scriptObject); if (!p || !p->value.isObject()) return newQObject(qtObject, ownership, options); - if (p->value.isVariant()) { + if (p->value.isQObject()) { QScript::ExtQObject::Instance *data; data = d->qobjectConstructor->get(p->value); Q_ASSERT(data != 0); diff --git a/tests/auto/qscriptengine/tst_qscriptengine.cpp b/tests/auto/qscriptengine/tst_qscriptengine.cpp index 5339fb4..fe60cd0 100644 --- a/tests/auto/qscriptengine/tst_qscriptengine.cpp +++ b/tests/auto/qscriptengine/tst_qscriptengine.cpp @@ -636,9 +636,21 @@ void tst_QScriptEngine::newQObject() QScriptValue val = ret.property("objectName"); QVERIFY(val.isString()); } + // "promote" variant object to QObject + { + QScriptValue obj = eng.newVariant(123); + QVERIFY(obj.isVariant()); + QScriptValue originalProto = obj.prototype(); + QScriptValue ret = eng.newQObject(obj, this); + QVERIFY(ret.isQObject()); + QVERIFY(ret.strictlyEquals(obj)); + QVERIFY(obj.isQObject()); + QCOMPARE(ret.toQObject(), (QObject *)this); + QVERIFY(ret.prototype().strictlyEquals(originalProto)); + } // replace QObject* of existing object { - QScriptValue object = eng.newQObject(this); + QScriptValue object = eng.newVariant(123); QScriptValue originalProto = object.prototype(); QObject otherQObject; QScriptValue ret = eng.newQObject(object, &otherQObject); -- cgit v0.12 From bd14a25c84fc2c12bfaa594b338aa2d0c0d4d940 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 3 Jun 2009 11:53:27 +0200 Subject: Removed a warning (qreal should be used, and not float) --- src/gui/widgets/qmenu.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp index 50100af..bcfe0fb 100644 --- a/src/gui/widgets/qmenu.cpp +++ b/src/gui/widgets/qmenu.cpp @@ -398,7 +398,7 @@ QRect QMenuPrivate::actionRect(QAction *act) const return ret; } -static const float MenuFadeTimeInSec = 0.150; +static const qreal MenuFadeTimeInSec = 0.150; void QMenuPrivate::hideUpToMenuBar() { -- cgit v0.12 From a04e1c4733feb643eb8da7b4a94c175153691b38 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 3 Jun 2009 15:59:18 +0200 Subject: Fixed the QMenu to open submenus even if the pointing device is moving but the current highlighted item doesn't change Task-number: 254238 Reviewed-by: ogoffart --- src/gui/widgets/qmenu.cpp | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp index bcfe0fb..711f1f4 100644 --- a/src/gui/widgets/qmenu.cpp +++ b/src/gui/widgets/qmenu.cpp @@ -547,10 +547,12 @@ void QMenuPrivate::setCurrentAction(QAction *action, int popup, SelectionReason { Q_Q(QMenu); tearoffHighlighted = 0; - if (action == currentAction && !(action && action->menu() && action->menu() != activeMenu)) { - if(QMenu *menu = qobject_cast(causedPopup.widget)) { - if(causedPopup.action && menu->d_func()->activeMenu == q) - menu->d_func()->setCurrentAction(causedPopup.action, 0, reason, false); + if (action == currentAction) { + if (!action || !action->menu() || action->menu() == activeMenu) { + if(QMenu *menu = qobject_cast(causedPopup.widget)) { + if(causedPopup.action && menu->d_func()->activeMenu == q) + menu->d_func()->setCurrentAction(causedPopup.action, 0, reason, false); + } } return; } @@ -565,7 +567,7 @@ void QMenuPrivate::setCurrentAction(QAction *action, int popup, SelectionReason QAction *previousAction = currentAction; #endif #ifdef QT3_SUPPORT - emitHighlighted = (action && action != currentAction); + emitHighlighted = action; #endif currentAction = action; if (action) { -- cgit v0.12 From 9d42ae152f660cfacad104060741b17b96269cd2 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Wed, 3 Jun 2009 16:07:26 +0200 Subject: Change crazy casts from QString to NSSting to qt_mac_QStringToNSString. These function exist for making code not look so crazy, so let's actually use that in code where it didn't exist before. --- src/gui/widgets/qmenu_mac.mm | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/gui/widgets/qmenu_mac.mm b/src/gui/widgets/qmenu_mac.mm index 87c886c..786633c 100644 --- a/src/gui/widgets/qmenu_mac.mm +++ b/src/gui/widgets/qmenu_mac.mm @@ -623,7 +623,7 @@ static inline QT_MANGLE_NAMESPACE(QCocoaMenuLoader) *getMenuLoader() static NSMenuItem *createNSMenuItem(const QString &title) { NSMenuItem *item = [[NSMenuItem alloc] - initWithTitle:reinterpret_cast(static_cast(QCFString(title))) + initWithTitle:qt_mac_QStringToNSString(title) action:@selector(qtDispatcherToQAction:) keyEquivalent:@""]; [item setTarget:getMenuLoader()]; return item; @@ -1381,18 +1381,18 @@ QMenuPrivate::QMacMenuPrivate::syncAction(QMacMenuAction *action) // Cocoa Font and title if (action->action->font().resolve()) { const QFont &actionFont = action->action->font(); - NSFont *customMenuFont = [NSFont fontWithName:reinterpret_cast(static_cast(QCFString(actionFont.family()))) + NSFont *customMenuFont = [NSFont fontWithName:qt_mac_QStringToNSString(actionFont.family()) size:actionFont.pointSize()]; NSArray *keys = [NSArray arrayWithObjects:NSFontAttributeName, nil]; NSArray *objects = [NSArray arrayWithObjects:customMenuFont, nil]; NSDictionary *attributes = [NSDictionary dictionaryWithObjects:objects forKeys:keys]; - NSAttributedString *str = [[[NSAttributedString alloc] initWithString:reinterpret_cast(static_cast(QCFString(finalString))) + NSAttributedString *str = [[[NSAttributedString alloc] initWithString:qt_mac_QStringToNSString(finalString) attributes:attributes] autorelease]; [item setAttributedTitle: str]; } else { - [item setTitle: reinterpret_cast(static_cast(QCFString(finalString)))]; + [item setTitle: qt_mac_QStringToNSString(finalString)]; } - [item setTitle:reinterpret_cast(static_cast(QCFString(qt_mac_removeMnemonics(text))))]; + [item setTitle:qt_mac_QStringToNSString(qt_mac_removeMnemonics(text))]; // Cocoa Enabled [item setEnabled: action->action->isEnabled()]; @@ -1694,7 +1694,7 @@ QMenuBarPrivate::QMacMenuBarPrivate::syncAction(QMacMenuAction *action) ChangeMenuAttributes(submenu, kMenuAttrHidden, 0); #else [item setSubmenu: submenu]; - [submenu setTitle:reinterpret_cast(static_cast(QCFString(qt_mac_removeMnemonics(action->action->text()))))]; + [submenu setTitle:qt_mac_QStringToNSString(qt_mac_removeMnemonics(action->action->text()))]; syncNSMenuItemVisiblity(item, visible); #endif if (release_submenu) { //no pointers to it @@ -1786,7 +1786,7 @@ OSMenuRef QMenuBarPrivate::macMenu() SetMenuItemHierarchicalMenu(mac_menubar->menu, index, mac_menubar->apple_menu); SetMenuItemProperty(mac_menubar->apple_menu, 0, kMenuCreatorQt, kMenuPropertyQWidget, sizeof(q), &q); #else - [mac_menubar->apple_menu setTitle:reinterpret_cast(static_cast(QCFString(QString(QChar(0x14)))))]; + [mac_menubar->apple_menu setTitle:qt_mac_QStringToNSString(QString(QChar(0x14)))]; NSMenuItem *apple_menuItem = [[NSMenuItem alloc] init]; [apple_menuItem setSubmenu:mac_menubar->menu]; [mac_menubar->apple_menu addItem:apple_menuItem]; -- cgit v0.12 From f1e471b561012f90938766c00aefff417593e71f Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Wed, 3 Jun 2009 13:49:09 +0200 Subject: fix catalan plural rules --- src/corelib/kernel/qtranslator.cpp | 3 +++ src/corelib/kernel/qtranslator_p.h | 1 + tools/linguist/shared/numerus.cpp | 9 +++++++-- 3 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/corelib/kernel/qtranslator.cpp b/src/corelib/kernel/qtranslator.cpp index 3e4b467..df904a6 100644 --- a/src/corelib/kernel/qtranslator.cpp +++ b/src/corelib/kernel/qtranslator.cpp @@ -149,6 +149,9 @@ static int numerusHelper(int n, const uchar *rules, int rulesSize) leftOperand %= 10; } else if (opcode & Q_MOD_100) { leftOperand %= 100; + } else if (opcode & Q_LEAD_1000) { + while (leftOperand >= 1000) + leftOperand /= 1000; } int op = opcode & Q_OP_MASK; diff --git a/src/corelib/kernel/qtranslator_p.h b/src/corelib/kernel/qtranslator_p.h index 77ec8f5..a7d58c5 100644 --- a/src/corelib/kernel/qtranslator_p.h +++ b/src/corelib/kernel/qtranslator_p.h @@ -62,6 +62,7 @@ enum { Q_NOT = 0x08, Q_MOD_10 = 0x10, Q_MOD_100 = 0x20, + Q_LEAD_1000 = 0x40, Q_AND = 0xFD, Q_OR = 0xFE, diff --git a/tools/linguist/shared/numerus.cpp b/tools/linguist/shared/numerus.cpp index 2fe1c78..50e85cb 100644 --- a/tools/linguist/shared/numerus.cpp +++ b/tools/linguist/shared/numerus.cpp @@ -105,6 +105,9 @@ static const uchar arabicRules[] = static const uchar tagalogRules[] = { Q_LEQ, 1, Q_NEWRULE, Q_MOD_10 | Q_EQ, 4, Q_OR, Q_MOD_10 | Q_EQ, 6, Q_OR, Q_MOD_10 | Q_EQ, 9 }; +static const uchar catalanRules[] = + { Q_EQ, 1, Q_NEWRULE, + Q_LEAD_1000 | Q_EQ, 11 }; static const char * const japaneseStyleForms[] = { "Universal Form", 0 }; static const char * const englishStyleForms[] = { "Singular", "Plural", 0 }; @@ -127,6 +130,7 @@ static const char * const arabicForms[] = { "Nullar", "Singular", "Dual", "Minority Plural", "Plural", "Plural Form for 100, 200, ...", 0 }; static const char * const tagalogForms[] = { "Singular", "Plural (consonant-ended)", "Plural (vowel-ended)", 0 }; +static const char * const catalanForms[] = { "Singular", "Undecal (11)", "Plural", 0 }; #define EOL QLocale::C @@ -173,7 +177,6 @@ static const QLocale::Language englishStyleLanguages[] = { // Missing: Bokmal, QLocale::Bulgarian, QLocale::Cambodian, - QLocale::Catalan, QLocale::Cornish, QLocale::Corsican, QLocale::Danish, @@ -300,6 +303,7 @@ static const QLocale::Language malteseLanguage[] = { QLocale::Maltese, EOL }; static const QLocale::Language welshLanguage[] = { QLocale::Welsh, EOL }; static const QLocale::Language arabicLanguage[] = { QLocale::Arabic, EOL }; static const QLocale::Language tagalogLanguage[] = { QLocale::Tagalog, EOL }; +static const QLocale::Language catalanLanguage[] = { QLocale::Catalan, EOL }; static const QLocale::Country frenchStyleCountries[] = { // keep synchronized with frenchStyleLanguages @@ -334,7 +338,8 @@ static const NumerusTableEntry numerusTable[] = { { malteseRules, sizeof(malteseRules), malteseForms, malteseLanguage, 0 }, { welshRules, sizeof(welshRules), welshForms, welshLanguage, 0 }, { arabicRules, sizeof(arabicRules), arabicForms, arabicLanguage, 0 }, - { tagalogRules, sizeof(tagalogRules), tagalogForms, tagalogLanguage, 0 } + { tagalogRules, sizeof(tagalogRules), tagalogForms, tagalogLanguage, 0 }, + { catalanRules, sizeof(catalanRules), catalanForms, catalanLanguage, 0 } }; static const int NumerusTableSize = sizeof(numerusTable) / sizeof(numerusTable[0]); -- cgit v0.12 From 43de28ba040bea21e2aee5b13be1351127503336 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Wed, 3 Jun 2009 17:27:03 +0200 Subject: Doc fix: moved the cldr version outside of the double-to-string license header --- src/corelib/tools/qlocale.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp index 4c2f59a..8c740bd 100644 --- a/src/corelib/tools/qlocale.cpp +++ b/src/corelib/tools/qlocale.cpp @@ -1601,6 +1601,8 @@ QDataStream &operator>>(QDataStream &ds, QLocale &l) This constructor converts the locale name to a language/country pair; it does not use the system locale database. + QLocale's data is based on Common Locale Data Repository v1.6.1. + The double-to-string and string-to-double conversion functions are covered by the following licenses: @@ -1621,8 +1623,6 @@ QDataStream &operator>>(QDataStream &ds, QLocale &l) This product includes software developed by the University of California, Berkeley and its contributors. - QLocale's data is based on Common Locale Data Repository v1.6.1. - \sa QString::arg(), QString::toInt(), QString::toDouble() */ -- cgit v0.12 From ba2e1015f9efe584a1ea671ff1db00f743f4ee3c Mon Sep 17 00:00:00 2001 From: David Boddie Date: Wed, 3 Jun 2009 18:36:32 +0200 Subject: Doc: Added information about the Fontconfig and FreeType dependencies. Task-number: 250349 Reviewed-by: Trust Me --- doc/src/installation.qdoc | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/doc/src/installation.qdoc b/doc/src/installation.qdoc index 6a689f9..bc310c9 100644 --- a/doc/src/installation.qdoc +++ b/doc/src/installation.qdoc @@ -612,6 +612,14 @@ in the \l{Qt for Windows CE Requirements} document.
    Xinerama libXinerama Multi-head support -xinerama or auto-detected1.1.0
    Fontconfig libfontconfig Font customization and configuration-fontconfig or auto-detected2.1
    FreeType libfreetype Font engine2.1.3
    Xi libXi X11 Input Extensions -xinput or auto-detected1.3.0 Xext libXext X Extensions6.4.3
    X11 libX11 X11 Client-Side Library6.2.1
    SM libSM X Session Management -sm or auto-detected6.0.4
    ICE libICE Inter-Client Exchange -sm or auto-detected6.3.5
    glib libglib-2.0 Common event loop handling -glib or auto-detected2.8.3"; + html += ""; i += 2; if (parseArg(src, linkTag, &i, n, &arg, &par1)) { QString link = linkForNode( diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index 5239856..fa0167b 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -66,7 +66,7 @@ body } table td.memItemLeft { - width: 100px; + width: 200px; padding: 1px 0px 0px 8px; margin: 4px; border-top-width: 1px; -- cgit v0.12 From cbe3119db5380c41d44d4e936c7da4889c02f147 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 4 Jun 2009 09:30:17 +0200 Subject: BT: Fixes Crash when deleting a QProgressBar which has been styled with QMotifStyle Same fix as in e9a7e43031d7c1ee712e43be682c4e2c183759c4 but with motif Reported by https://bugs.kde.org/show_bug.cgi?id=193911 Task-number: 255138 Reviewed-by: jbache --- dist/changes-4.5.2 | 3 +++ src/gui/styles/qmotifstyle.cpp | 5 ++++- tests/auto/qprogressbar/tst_qprogressbar.cpp | 20 ++++++++++++++++++-- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 6772405..a54d8ba 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -67,6 +67,9 @@ Third party components * [253339] Don't draw arrows on toolbuttons that have a menu and text only. * [252301] Ensure that small and mini spin boxes are drawn correctly. +- QMotifStyle + * Fix crash when changing style and destroying progressbar. + - QFontDialog * [252000] Ensure that QFontDialog::getFont() works on Mac OS X. diff --git a/src/gui/styles/qmotifstyle.cpp b/src/gui/styles/qmotifstyle.cpp index 7d4fab8..d19750f 100644 --- a/src/gui/styles/qmotifstyle.cpp +++ b/src/gui/styles/qmotifstyle.cpp @@ -298,8 +298,11 @@ void QMotifStyle::unpolish(QWidget* widget) { QCommonStyle::unpolish(widget); #ifndef QT_NO_PROGRESSBAR - if (qobject_cast(widget)) + if (qobject_cast(widget)) { + Q_D(QMotifStyle); widget->removeEventFilter(this); + d->bars.removeAll(static_cast(widget)); + } #endif } diff --git a/tests/auto/qprogressbar/tst_qprogressbar.cpp b/tests/auto/qprogressbar/tst_qprogressbar.cpp index d6379d3..cb037e0 100644 --- a/tests/auto/qprogressbar/tst_qprogressbar.cpp +++ b/tests/auto/qprogressbar/tst_qprogressbar.cpp @@ -63,6 +63,7 @@ private slots: void setValueRepaint(); void sizeHint(); + void task245201_testChangeStyleAndDelete_data(); void task245201_testChangeStyleAndDelete(); }; @@ -224,15 +225,30 @@ void tst_QProgressBar::sizeHint() QCOMPARE(barSize.height(), size.height()); } +void tst_QProgressBar::task245201_testChangeStyleAndDelete_data() +{ + QTest::addColumn("style1_str"); + QTest::addColumn("style2_str"); + + QTest::newRow("plastique-windows") << QString::fromLatin1("plastique") << QString::fromLatin1("windows"); + QTest::newRow("mlotif-windows") << QString::fromLatin1("motif") << QString::fromLatin1("windows"); + QTest::newRow("cleanlooks-cde") << QString::fromLatin1("cleanlooks") << QString::fromLatin1("cde"); + QTest::newRow("gtk-plastique") << QString::fromLatin1("gtk") << QString::fromLatin1("plastique"); +} + void tst_QProgressBar::task245201_testChangeStyleAndDelete() { + QFETCH(QString, style1_str); + QFETCH(QString, style2_str); + QProgressBar *bar = new QProgressBar; - QStyle *style = QStyleFactory::create("plastique"); + QStyle *style = QStyleFactory::create(style1_str); bar->setStyle(style); bar->show(); - QStyle *style2 = QStyleFactory::create("windows"); + QStyle *style2 = QStyleFactory::create(style2_str); bar->setStyle(style2); + QTest::qWait(10); delete bar; QTest::qWait(100); //should not crash -- cgit v0.12 From d227b12495bb88a78b98436eac38f240429dfa98 Mon Sep 17 00:00:00 2001 From: hjk Date: Tue, 2 Jun 2009 11:25:21 +0200 Subject: Add some comparisons with std::string to the QStringBuilder benchmarks. --- tests/benchmarks/qstringbuilder/main.cpp | 86 +++++++++++++++++++++++++------- 1 file changed, 68 insertions(+), 18 deletions(-) diff --git a/tests/benchmarks/qstringbuilder/main.cpp b/tests/benchmarks/qstringbuilder/main.cpp index d4e2fa0..8b769a6 100644 --- a/tests/benchmarks/qstringbuilder/main.cpp +++ b/tests/benchmarks/qstringbuilder/main.cpp @@ -1,6 +1,6 @@ // Select one of the scenarios below -#define SCENARIO 3 +#define SCENARIO 1 #if SCENARIO == 1 // this is the "no harm done" version. Only operator% is active, @@ -17,7 +17,7 @@ // this is the "full" version. Operator+ is replaced by a QStringBuilder // based version // with NO_CAST * defined -#define P % +#define P + #define QT_USE_FAST_OPERATOR_PLUS #define QT_USE_FAST_CONCATENATION #define QT_NO_CAST_FROM_ASCII @@ -38,7 +38,7 @@ // this is the "full" version. Operator+ is replaced by a QStringBuilder // based version // with NO_CAST * _not_ defined -#define P % +#define P + #define QT_USE_FAST_OPERATOR_PLUS #define QT_USE_FAST_CONCATENATION #undef QT_NO_CAST_FROM_ASCII @@ -53,6 +53,8 @@ #include +#include + #define COMPARE(a, b) QCOMPARE(a, b) //#define COMPARE(a, b) @@ -70,6 +72,7 @@ public: l1string(LITERAL), ba(LITERAL), string(l1string), + stdstring(LITERAL), stringref(&string, 2, 10), achar('c'), r2(QLatin1String(LITERAL LITERAL)), @@ -115,8 +118,9 @@ public: private slots: void separator_0() { - qDebug() << "\nIn each block the QStringBuilder based result appear first, " - "QStringBased second.\n"; + qDebug() << "\nIn each block the QStringBuilder based result appear first " + "(with a 'b_' prefix), QStringBased second ('q_' prefix), std::string " + "last ('s_' prefix)\n"; } void separator_1() { SEP("literal + literal (builder first)"); } @@ -131,7 +135,7 @@ private slots: COMPARE(r, r2); } #endif - void s_2_l1string() { + void q_2_l1string() { QBENCHMARK { r = l1string + l1string; } COMPARE(r, r2); } @@ -143,10 +147,14 @@ private slots: QBENCHMARK { r = string P string; } COMPARE(r, r2); } - void s_2_string() { + void q_2_string() { QBENCHMARK { r = string + string; } COMPARE(r, r2); } + void s_2_string() { + QBENCHMARK { stdr = stdstring + stdstring; } + COMPARE(stdr, stdstring + stdstring); + } void separator_2c() { SEP("2 string refs"); } @@ -155,7 +163,7 @@ private slots: QBENCHMARK { r = stringref % stringref; } COMPARE(r, QString(stringref.toString() + stringref.toString())); } - void s_2_stringref() { + void q_2_stringref() { QBENCHMARK { r = stringref.toString() + stringref.toString(); } COMPARE(r, QString(stringref % stringref)); } @@ -167,10 +175,30 @@ private slots: QBENCHMARK { r = string P string P string; } COMPARE(r, r3); } - void s_3_string() { + void q_3_string() { QBENCHMARK { r = string + string + string; } COMPARE(r, r3); } + void s_3_string() { + QBENCHMARK { stdr = stdstring + stdstring + stdstring; } + COMPARE(stdr, stdstring + stdstring + stdstring); + } + + void separator_2e() { SEP("4 strings"); } + + void b_4_string() { + QBENCHMARK { r = string P string P string P string; } + COMPARE(r, r4); + } + void q_4_string() { + QBENCHMARK { r = string + string + string + string; } + COMPARE(r, r4); + } + void s_4_string() { + QBENCHMARK { stdr = stdstring + stdstring + stdstring + stdstring; } + COMPARE(stdr, stdstring + stdstring + stdstring + stdstring); + } + void separator_2a() { SEP("string + literal (builder first)"); } @@ -193,14 +221,18 @@ private slots: QBENCHMARK { r = string P l1string; } COMPARE(r, r2); } - void s_string_l1literal() { + void q_string_l1literal() { QBENCHMARK { r = string + l1string; } COMPARE(r, r2); } - void s_string_l1string() { + void q_string_l1string() { QBENCHMARK { r = string + l1string; } COMPARE(r, r2); } + void s_LITERAL_string() { + QBENCHMARK { stdr = LITERAL + stdstring; } + COMPARE(stdr, stdstring + stdstring); + } void separator_3() { SEP("3 literals"); } @@ -209,10 +241,14 @@ private slots: QBENCHMARK { r = l1literal P l1literal P l1literal; } COMPARE(r, r3); } - void s_3_l1string() { + void q_3_l1string() { QBENCHMARK { r = l1string + l1string + l1string; } COMPARE(r, r3); } + void s_3_l1string() { + QBENCHMARK { stdr = stdstring + LITERAL + LITERAL; } + COMPARE(stdr, stdstring + stdstring + stdstring); + } void separator_4() { SEP("4 literals"); } @@ -221,7 +257,7 @@ private slots: QBENCHMARK { r = l1literal P l1literal P l1literal P l1literal; } COMPARE(r, r4); } - void s_4_l1string() { + void q_4_l1string() { QBENCHMARK { r = l1string + l1string + l1string + l1string; } COMPARE(r, r4); } @@ -234,7 +270,7 @@ private slots: COMPARE(r, r5); } - void s_5_l1string() { + void q_5_l1string() { QBENCHMARK { r = l1string + l1string + l1string + l1string + l1string; } COMPARE(r, r5); } @@ -247,11 +283,16 @@ private slots: COMPARE(r, QString(string P achar P achar P achar P achar)); } - void s_string_4_char() { + void q_string_4_char() { QBENCHMARK { r = string + achar + achar + achar + achar; } COMPARE(r, QString(string P achar P achar P achar P achar)); } + void s_string_4_char() { + QBENCHMARK { stdr = stdstring + 'c' + 'c' + 'c' + 'c'; } + COMPARE(stdr, stdstring + 'c' + 'c' + 'c' + 'c'); + } + void separator_7() { SEP("char + string + char"); } @@ -260,11 +301,17 @@ private slots: COMPARE(r, QString(achar P string P achar)); } - void s_char_string_char() { + void q_char_string_char() { QBENCHMARK { r = achar + string + achar; } COMPARE(r, QString(achar P string P achar)); } + void s_char_string_char() { + QBENCHMARK { stdr = 'c' + stdstring + 'c'; } + COMPARE(stdr, 'c' + stdstring + 'c'); + } + + void separator_8() { SEP("string.arg"); } void b_string_arg() { @@ -273,13 +320,13 @@ private slots: COMPARE(r, r3); } - void s_string_arg() { + void q_string_arg() { const QString pattern = l1string + QLatin1String("%1") + l1string; QBENCHMARK { r = pattern.arg(string); } COMPARE(r, r3); } - void s_bytearray_arg() { + void q_bytearray_arg() { QByteArray result; QBENCHMARK { result = ba + ba + ba; } } @@ -331,11 +378,14 @@ private: const QLatin1String l1string; const QByteArray ba; const QString string; + const std::string stdstring; const QStringRef stringref; const QLatin1Char achar; const QString r2, r3, r4, r5; + // short cuts for results QString r; + std::string stdr; }; -- cgit v0.12 From d167d50234a977eae5c03cca20a78850437d5b87 Mon Sep 17 00:00:00 2001 From: hjk Date: Thu, 4 Jun 2009 10:22:10 +0200 Subject: compile fix with namespaces --- demos/boxes/glbuffers.h | 2 ++ demos/boxes/scene.h | 3 +++ 2 files changed, 5 insertions(+) diff --git a/demos/boxes/glbuffers.h b/demos/boxes/glbuffers.h index 392924e..9e05fad 100644 --- a/demos/boxes/glbuffers.h +++ b/demos/boxes/glbuffers.h @@ -58,7 +58,9 @@ if (m_failed || !(assertion)) { returnStatement; \ } +QT_BEGIN_NAMESPACE class QMatrix4x4; +QT_END_NAMESPACE class GLTexture { diff --git a/demos/boxes/scene.h b/demos/boxes/scene.h index 48ecaba..9f8d2af 100644 --- a/demos/boxes/scene.h +++ b/demos/boxes/scene.h @@ -56,7 +56,10 @@ #define PI 3.14159265358979 +QT_BEGIN_NAMESPACE class QMatrix4x4; +QT_END_NAMESPACE + class ParameterEdit : public QWidget { public: -- cgit v0.12 From 397c3bb494e220af5ef1cf6e47cfdfc84b61540b Mon Sep 17 00:00:00 2001 From: jasplin Date: Thu, 4 Jun 2009 10:39:29 +0200 Subject: Fixed build error with Sun CC 5.5. Reviewed-by: TrustMe --- src/corelib/tools/qvector.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/corelib/tools/qvector.h b/src/corelib/tools/qvector.h index 7bdcba0..38254cd 100644 --- a/src/corelib/tools/qvector.h +++ b/src/corelib/tools/qvector.h @@ -94,7 +94,14 @@ template class QVector { typedef QVectorTypedData Data; - union { QVectorData *d; Data *p; }; + union { + QVectorData *d; +#if defined(Q_CC_SUN) && (__SUNPRO_CC <= 0x550) + QVectorTypedData *p; +#else + Data *p; +#endif + }; public: inline QVector() : d(&QVectorData::shared_null) { d->ref.ref(); } -- cgit v0.12 From c755c1d3c6fe60a9018308e1ce13bae6821bc214 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Thu, 4 Jun 2009 10:10:19 +0200 Subject: Document that textVisible is optional when it comes to styles. No progress bars on the mac show text and it would be bad if we allowed it. There's nothing stopping people from connecting the valueChanged() signal to a slot and have a real label layed out correctly that actually updates with the amount of time it takes to complete, etc. This is more what they do on Mac OS X if they decide to show a label. --- src/gui/widgets/qprogressbar.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/gui/widgets/qprogressbar.cpp b/src/gui/widgets/qprogressbar.cpp index cdb3836..1a7f878 100644 --- a/src/gui/widgets/qprogressbar.cpp +++ b/src/gui/widgets/qprogressbar.cpp @@ -349,6 +349,8 @@ void QProgressBar::setRange(int minimum, int maximum) \property QProgressBar::textVisible \brief whether the current completed percentage should be displayed + This property may be ignored by the style (e.g., QMacStyle never draws the text). + \sa textDirection */ void QProgressBar::setTextVisible(bool visible) -- cgit v0.12 From df5c557e7777c8844ac866d730346178ad33a0a6 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Thu, 4 Jun 2009 10:39:20 +0200 Subject: Document the proper signals that the ::open() convenience connects to. We were saying that it connected to accepted it all these cases, but it actually is doing some nice magic that makes sense assuming you document it. --- src/gui/dialogs/qcolordialog.cpp | 2 +- src/gui/dialogs/qfiledialog.cpp | 5 +++-- src/gui/dialogs/qfontdialog.cpp | 2 +- src/gui/dialogs/qinputdialog.cpp | 12 ++++++++++-- 4 files changed, 15 insertions(+), 6 deletions(-) diff --git a/src/gui/dialogs/qcolordialog.cpp b/src/gui/dialogs/qcolordialog.cpp index 3aa04f6..4702d14 100644 --- a/src/gui/dialogs/qcolordialog.cpp +++ b/src/gui/dialogs/qcolordialog.cpp @@ -1749,7 +1749,7 @@ void QColorDialog::setVisible(bool visible) \overload \since 4.5 - Opens the dialog and connects its accepted() signal to the slot specified + Opens the dialog and connects its colorSelected() signal to the slot specified by \a receiver and \a member. The signal will be disconnected from the slot when the dialog is closed. diff --git a/src/gui/dialogs/qfiledialog.cpp b/src/gui/dialogs/qfiledialog.cpp index 405e71e..77382a7 100644 --- a/src/gui/dialogs/qfiledialog.cpp +++ b/src/gui/dialogs/qfiledialog.cpp @@ -638,8 +638,9 @@ QFileDialog::Options QFileDialog::options() const \since 4.5 - Opens the dialog and connects its accepted() signal to the slot specified - by \a receiver and \a member. + This function connects one of its signals to the slot specified by \a receiver + and \a member. The specific signal depends is filesSelected() if fileMode is + ExistingFiles and fileSelected() if fileMode is anything else. The signal will be disconnected from the slot when the dialog is closed. */ diff --git a/src/gui/dialogs/qfontdialog.cpp b/src/gui/dialogs/qfontdialog.cpp index aa1c553..9ea06ac 100644 --- a/src/gui/dialogs/qfontdialog.cpp +++ b/src/gui/dialogs/qfontdialog.cpp @@ -940,7 +940,7 @@ bool QFontDialogPrivate::sharedFontPanelAvailable = true; \since 4.5 \overload - Opens the dialog and connects its accepted() signal to the slot specified + Opens the dialog and connects its fontSelected() signal to the slot specified by \a receiver and \a member. The signal will be disconnected from the slot when the dialog is closed. diff --git a/src/gui/dialogs/qinputdialog.cpp b/src/gui/dialogs/qinputdialog.cpp index 78d99e3..8754324 100644 --- a/src/gui/dialogs/qinputdialog.cpp +++ b/src/gui/dialogs/qinputdialog.cpp @@ -1020,8 +1020,16 @@ QString QInputDialog::cancelButtonText() const \since 4.5 \overload - Opens the dialog and connects its accepted() signal to the slot specified - by \a receiver and \a member. + This function connects one of its signals to the slot specified by \a receiver + and \a member. The specific signal depends on the arguments that are specified + in \a member. These are: + + \list + \o textValueSelected() if \a member has a QString for its first argument. + \o intValueSelected() if \a member has an int for its first argument. + \o doubleValueSelected() if \a member has a double for its first argument. + \o accepted() if \a member has NO arguments. + \endlist The signal will be disconnected from the slot when the dialog is closed. */ -- cgit v0.12 From c116ffaa7abb26373475921db7410503a79b4207 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 4 Jun 2009 10:45:17 +0200 Subject: Fixed the frame that would sometimes not be painted around widgets in a QStatusBar Task-number: 253717 Reviewed-by: ogoffart --- src/gui/widgets/qstatusbar.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/widgets/qstatusbar.cpp b/src/gui/widgets/qstatusbar.cpp index 3829bcb..a248346 100644 --- a/src/gui/widgets/qstatusbar.cpp +++ b/src/gui/widgets/qstatusbar.cpp @@ -728,7 +728,7 @@ void QStatusBar::paintEvent(QPaintEvent *event) QStatusBarPrivate::SBItem* item = d->items.at(i); if (item && item->w->isVisible() && (!haveMessage || item->p)) { QRect ir = item->w->geometry().adjusted(-2, -1, 2, 1); - if (event->rect().contains(ir)) { + if (event->rect().intersects(ir)) { QStyleOption opt(0); opt.rect = ir; opt.palette = palette(); -- cgit v0.12 From 470716d0d0e06e4032f469f7c4c629a3d2a3b133 Mon Sep 17 00:00:00 2001 From: jasplin Date: Thu, 4 Jun 2009 10:44:06 +0200 Subject: Fixed build error with Sun CC 5.5.. Note that the fix is simply to swap the order of the two v_construct() overloads. Sun CC 5.5 requires the version with the default argument to occur first. Reviewed-by: TrustMe --- src/corelib/kernel/qvariant_p.h | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/corelib/kernel/qvariant_p.h b/src/corelib/kernel/qvariant_p.h index 033b760..02b507e 100644 --- a/src/corelib/kernel/qvariant_p.h +++ b/src/corelib/kernel/qvariant_p.h @@ -105,28 +105,28 @@ private: // constructs a new variant if copy is 0, otherwise copy-constructs template -inline void v_construct(QVariant::Private *x, const T &t) +inline void v_construct(QVariant::Private *x, const void *copy, T * = 0) { if (sizeof(T) > sizeof(QVariant::Private::Data)) { - x->data.shared = new QVariantPrivateSharedEx(t); + x->data.shared = copy ? new QVariantPrivateSharedEx(*static_cast(copy)) + : new QVariantPrivateSharedEx; x->is_shared = true; } else { - new (&x->data.ptr) T(t); + if (copy) + new (&x->data.ptr) T(*static_cast(copy)); + else + new (&x->data.ptr) T; } } template -inline void v_construct(QVariant::Private *x, const void *copy, T * = 0) +inline void v_construct(QVariant::Private *x, const T &t) { if (sizeof(T) > sizeof(QVariant::Private::Data)) { - x->data.shared = copy ? new QVariantPrivateSharedEx(*static_cast(copy)) - : new QVariantPrivateSharedEx; + x->data.shared = new QVariantPrivateSharedEx(t); x->is_shared = true; } else { - if (copy) - new (&x->data.ptr) T(*static_cast(copy)); - else - new (&x->data.ptr) T; + new (&x->data.ptr) T(t); } } -- cgit v0.12 From d5231e0593dcbf226e0ca3d679c2547e8e1c9697 Mon Sep 17 00:00:00 2001 From: jasplin Date: Thu, 4 Jun 2009 10:54:26 +0200 Subject: Fixed build error with Sun CC 5.5. Reviewed-by: tbastian --- src/gui/animation/qguivariantanimation.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/gui/animation/qguivariantanimation.cpp b/src/gui/animation/qguivariantanimation.cpp index 37ca6a1..75532f6 100644 --- a/src/gui/animation/qguivariantanimation.cpp +++ b/src/gui/animation/qguivariantanimation.cpp @@ -66,6 +66,9 @@ Q_CONSTRUCTOR_FUNCTION(qRegisterGuiGetInterpolator) static int qUnregisterGuiGetInterpolator() { qRegisterAnimationInterpolator(0); + qRegisterAnimationInterpolator( + (QVariant (*)(const QColor &, const QColor &, qreal))0); // cast required by Sun CC 5.5 + return 1; } Q_DESTRUCTOR_FUNCTION(qUnregisterGuiGetInterpolator) -- cgit v0.12 From 0a37c9bbf9dc95e0ad422007718a7af11b046deb Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Thu, 4 Jun 2009 11:11:15 +0200 Subject: Make the bench a bit faster. Reviewed-by:TrustMe --- tests/benchmarks/qpixmapcache/tst_qpixmapcache.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/benchmarks/qpixmapcache/tst_qpixmapcache.cpp b/tests/benchmarks/qpixmapcache/tst_qpixmapcache.cpp index f3c1134..9dafff5 100644 --- a/tests/benchmarks/qpixmapcache/tst_qpixmapcache.cpp +++ b/tests/benchmarks/qpixmapcache/tst_qpixmapcache.cpp @@ -156,9 +156,9 @@ struct styleStruct { int height; bool operator==(const styleStruct &str) const { - return str.key == key && str.state == state && str.direction == direction + return str.state == state && str.direction == direction && str.complex == complex && str.palette == palette && str.width == width - && str.height == height; + && str.height == height && str.key == key; } }; -- cgit v0.12 From 59653437cbc37f9644aa540c46701c2142939198 Mon Sep 17 00:00:00 2001 From: jasplin Date: Thu, 4 Jun 2009 11:37:08 +0200 Subject: Removed the internal UsePixmapCache flag in the style code. In the style code, the internal UsePixmapCache flag made no sense in practice, so it was removed. A fortunate side-effect of the patch is that the code is now accepted by Sun CC 5.5. Reviewed-by: jbache --- src/gui/styles/qcleanlooksstyle.cpp | 30 ++++++++----------- src/gui/styles/qgtkstyle.cpp | 1 - src/gui/styles/qplastiquestyle.cpp | 57 ++++++++++++++----------------------- src/gui/styles/qstyle_p.h | 2 +- src/gui/styles/qstylehelper.cpp | 1 - src/gui/styles/qstylehelper_p.h | 1 - 6 files changed, 35 insertions(+), 57 deletions(-) diff --git a/src/gui/styles/qcleanlooksstyle.cpp b/src/gui/styles/qcleanlooksstyle.cpp index 5c37794..b33dfc1 100644 --- a/src/gui/styles/qcleanlooksstyle.cpp +++ b/src/gui/styles/qcleanlooksstyle.cpp @@ -1664,7 +1664,7 @@ void QCleanlooksStyle::drawControl(ControlElement element, const QStyleOption *o } painter->fillRect(r, gradient); - if (!UsePixmapCache || !QPixmapCache::find(pixmapName, cache)) { + if (!QPixmapCache::find(pixmapName, cache)) { cache = QPixmap(r.size()); cache.fill(Qt::transparent); QRect pixmapRect(0, 0, r.width(), r.height()); @@ -1683,8 +1683,7 @@ void QCleanlooksStyle::drawControl(ControlElement element, const QStyleOption *o cachePainter.drawLine(pixmapRect.topRight() + QPoint(-1, 3), pixmapRect.bottomRight() + QPoint(-1, -3)); cachePainter.setPen(QPen(option->palette.light().color())); cachePainter.drawLine(pixmapRect.topRight() + QPoint(0, 3), pixmapRect.bottomRight() + QPoint(0, -3)); } cachePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(pixmapName, cache); + QPixmapCache::insert(pixmapName, cache); } painter->drawPixmap(r.topLeft(), cache); } @@ -2438,7 +2437,7 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp if (const QStyleOptionSpinBox *spinBox = qstyleoption_cast(option)) { QPixmap cache; QString pixmapName = QStyleHelper::uniqueName(QLatin1String("spinbox"), spinBox, spinBox->rect.size()); - if (!UsePixmapCache || !QPixmapCache::find(pixmapName, cache)) { + if (!QPixmapCache::find(pixmapName, cache)) { cache = QPixmap(spinBox->rect.size()); cache.fill(Qt::transparent); QRect pixmapRect(0, 0, spinBox->rect.width(), spinBox->rect.height()); @@ -2655,8 +2654,7 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp cachePainter.fillRect(downRect.adjusted(1, 0, 0, 0), disabledColor); } cachePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(pixmapName, cache); + QPixmapCache::insert(pixmapName, cache); } painter->drawPixmap(spinBox->rect.topLeft(), cache); } @@ -3187,7 +3185,7 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp if (isEnabled) pixmapName += QLatin1String("-enabled"); - if (!UsePixmapCache || !QPixmapCache::find(pixmapName, cache)) { + if (!QPixmapCache::find(pixmapName, cache)) { cache = QPixmap(comboBox->rect.size()); cache.fill(Qt::transparent); QPainter cachePainter(&cache); @@ -3314,8 +3312,7 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp drawPrimitive(PE_FrameFocusRect, &focus, &cachePainter, widget); } cachePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(pixmapName, cache); + QPixmapCache::insert(pixmapName, cache); } painter->drawPixmap(comboBox->rect.topLeft(), cache); } @@ -3406,7 +3403,7 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp QRect pixmapRect(0, 0, groove.width(), groove.height()); // draw background groove - if (!UsePixmapCache || !QPixmapCache::find(groovePixmapName, cache)) { + if (!QPixmapCache::find(groovePixmapName, cache)) { cache = QPixmap(pixmapRect.size()); cache.fill(Qt::transparent); QPainter groovePainter(&cache); @@ -3433,15 +3430,14 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp groovePainter.setBrush(gradient); groovePainter.drawRect(pixmapRect.adjusted(1, 1, -2, -2)); groovePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(groovePixmapName, cache); + QPixmapCache::insert(groovePixmapName, cache); } painter->drawPixmap(groove.topLeft(), cache); // draw blue groove highlight QRect clipRect; groovePixmapName += QLatin1String("_blue"); - if (!UsePixmapCache || !QPixmapCache::find(groovePixmapName, cache)) { + if (!QPixmapCache::find(groovePixmapName, cache)) { cache = QPixmap(pixmapRect.size()); cache.fill(Qt::transparent); QPainter groovePainter(&cache); @@ -3460,8 +3456,7 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp groovePainter.setBrush(gradient); groovePainter.drawRect(pixmapRect.adjusted(1, 1, -2, -2)); groovePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(groovePixmapName, cache); + QPixmapCache::insert(groovePixmapName, cache); } if (horizontal) { if (slider->upsideDown) @@ -3483,7 +3478,7 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp // draw handle if ((option->subControls & SC_SliderHandle) ) { QString handlePixmapName = QStyleHelper::uniqueName(QLatin1String("slider_handle"), option, handle.size()); - if (!UsePixmapCache || !QPixmapCache::find(handlePixmapName, cache)) { + if (!QPixmapCache::find(handlePixmapName, cache)) { cache = QPixmap(handle.size()); cache.fill(Qt::transparent); QRect pixmapRect(0, 0, handle.width(), handle.height()); @@ -3564,8 +3559,7 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp } } handlePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(handlePixmapName, cache); + QPixmapCache::insert(handlePixmapName, cache); } painter->drawPixmap(handle.topLeft(), cache); diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index 151dab0..1fe4627 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -176,7 +176,6 @@ public: static const int groupBoxBottomMargin = 2; // space below the groupbox static const int groupBoxTitleMargin = 6; // space between contents and title static const int groupBoxTopMargin = 2; -static bool UsePixmapCache = true; // Get size of the arrow controls in a GtkSpinButton static int spinboxArrowSize() diff --git a/src/gui/styles/qplastiquestyle.cpp b/src/gui/styles/qplastiquestyle.cpp index 91ad64e..01c0e44 100644 --- a/src/gui/styles/qplastiquestyle.cpp +++ b/src/gui/styles/qplastiquestyle.cpp @@ -43,7 +43,6 @@ #if !defined(QT_NO_STYLE_PLASTIQUE) || defined(QT_PLUGIN) -static bool UsePixmapCache = true; static const bool AnimateBusyProgressBar = true; static const bool AnimateProgressBar = false; // #define QPlastique_MaskButtons @@ -491,7 +490,7 @@ static void qBrushSetAlphaF(QBrush *brush, qreal alpha) QPixmap texture = brush->texture(); QPixmap pixmap; QString name = QString::fromLatin1("qbrushtexture-alpha-%1-%2").arg(alpha).arg(texture.cacheKey()); - if (UsePixmapCache && !QPixmapCache::find(name, pixmap)) { + if (!QPixmapCache::find(name, pixmap)) { QImage image = texture.toImage(); QRgb *rgb = reinterpret_cast(image.bits()); int pixels = image.width() * image.height(); @@ -552,7 +551,7 @@ static QBrush qBrushLight(QBrush brush, int light) QPixmap texture = brush.texture(); QPixmap pixmap; QString name = QString::fromLatin1("qbrushtexture-light-%1-%2").arg(light).arg(texture.cacheKey()); - if (UsePixmapCache && !QPixmapCache::find(name, pixmap)) { + if (!QPixmapCache::find(name, pixmap)) { QImage image = texture.toImage(); QRgb *rgb = reinterpret_cast(image.bits()); int pixels = image.width() * image.height(); @@ -611,7 +610,7 @@ static QBrush qBrushDark(QBrush brush, int dark) QPixmap texture = brush.texture(); QPixmap pixmap; QString name = QString::fromLatin1("qbrushtexture-dark-%1-%2").arg(dark).arg(brush.texture().cacheKey()); - if (UsePixmapCache && !QPixmapCache::find(name, pixmap)) { + if (!QPixmapCache::find(name, pixmap)) { QImage image = texture.toImage(); QRgb *rgb = reinterpret_cast(image.bits()); int pixels = image.width() * image.height(); @@ -750,8 +749,7 @@ static void qt_plastique_draw_gradient(QPainter *painter, const QRect &rect, con QPainter *p = painter; QRect r = rect; - bool doPixmapCache = UsePixmapCache - && painter->deviceTransform().isIdentity() + bool doPixmapCache = painter->deviceTransform().isIdentity() && painter->worldMatrix().isIdentity(); if (doPixmapCache && QPixmapCache::find(gradientName, cache)) { painter->drawPixmap(rect, cache); @@ -1006,8 +1004,6 @@ QPlastiqueStylePrivate::QPlastiqueStylePrivate() : , progressBarAnimateTimer(0) #endif { - if (!qgetenv("QT_STYLE_NO_PIXMAPCACHE").isNull()) - UsePixmapCache = false; } /*! @@ -1517,7 +1513,7 @@ void QPlastiqueStyle::drawPrimitive(PrimitiveElement element, const QStyleOption } #endif QString pixmapName = uniqueName(QLatin1String("toolbarhandle"), option, rect.size()); - if (!UsePixmapCache || !QPixmapCache::find(pixmapName, cache)) { + if (!QPixmapCache::find(pixmapName, cache)) { cache = QPixmap(rect.size()); cache.fill(Qt::transparent); QPainter cachePainter(&cache); @@ -1547,8 +1543,7 @@ void QPlastiqueStyle::drawPrimitive(PrimitiveElement element, const QStyleOption handle); } cachePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(pixmapName, cache); + QPixmapCache::insert(pixmapName, cache); } painter->drawPixmap(rect.topLeft(), cache); break; @@ -2786,7 +2781,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op QString progressBarName = uniqueName(QLatin1String("progressBarContents"), option, rect.size()); QPixmap cache; - if ((!UsePixmapCache || !QPixmapCache::find(progressBarName, cache)) && rect.height() > 7) { + if (!QPixmapCache::find(progressBarName, cache) && rect.height() > 7) { QSize size = rect.size(); cache = QPixmap(QSize(size.width() - 6 + 30, size.height() - 6)); cache.fill(Qt::white); @@ -2819,8 +2814,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op leftEdge += 10; } - if (UsePixmapCache) - QPixmapCache::insert(progressBarName, cache); + QPixmapCache::insert(progressBarName, cache); } painter->setClipRect(progressBar.adjusted(1, 0, -1, -1)); @@ -2848,7 +2842,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op pixmapName += QString::number(- int(header->position)); pixmapName += QString::number(- int(header->orientation)); - if (!UsePixmapCache || !QPixmapCache::find(pixmapName, cache)) { + if (!QPixmapCache::find(pixmapName, cache)) { cache = QPixmap(option->rect.size()); cache.fill(Qt::white); QRect pixmapRect(0, 0, option->rect.width(), option->rect.height()); @@ -2892,8 +2886,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op cachePainter.drawLines(lines, 2); cachePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(pixmapName, cache); + QPixmapCache::insert(pixmapName, cache); } painter->drawPixmap(option->rect.topLeft(), cache); @@ -3093,7 +3086,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op if ((option->state & State_Selected)) { QPixmap cache; QString pixmapName = uniqueName(QLatin1String("menubaritem"), option, option->rect.size()); - if (!UsePixmapCache || !QPixmapCache::find(pixmapName, cache)) { + if (!QPixmapCache::find(pixmapName, cache)) { cache = QPixmap(option->rect.size()); cache.fill(Qt::white); QRect pixmapRect(0, 0, option->rect.width(), option->rect.height()); @@ -3143,8 +3136,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op lines[1] = QLine(rect.right() - 1, rect.top() + 1, rect.right() - 1, rect.bottom() - 2); cachePainter.drawLines(lines, 2); cachePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(pixmapName, cache); + QPixmapCache::insert(pixmapName, cache); } painter->drawPixmap(option->rect.topLeft(), cache); } else { @@ -3458,7 +3450,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op QString addLinePixmapName = uniqueName(QLatin1String("scrollbar_addline"), option, option->rect.size()); QPixmap cache; - if (!UsePixmapCache || !QPixmapCache::find(addLinePixmapName, cache)) { + if (!QPixmapCache::find(addLinePixmapName, cache)) { cache = QPixmap(option->rect.size()); cache.fill(Qt::white); QRect pixmapRect(0, 0, cache.width(), cache.height()); @@ -3517,8 +3509,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op addLinePainter.drawImage(QPoint(pixmapRect.center().x() - 3, pixmapRect.center().y() - 2), arrow); } addLinePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(addLinePixmapName, cache); + QPixmapCache::insert(addLinePixmapName, cache); } painter->drawPixmap(option->rect.topLeft(), cache); } @@ -3536,7 +3527,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op groovePixmapName += QLatin1String("-addpage"); QPixmap cache; - if (!UsePixmapCache || !QPixmapCache::find(groovePixmapName, cache)) { + if (!QPixmapCache::find(groovePixmapName, cache)) { cache = QPixmap(option->rect.size()); cache.fill(option->palette.background().color()); QPainter groovePainter(&cache); @@ -3562,8 +3553,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op } groovePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(groovePixmapName, cache); + QPixmapCache::insert(groovePixmapName, cache); } painter->drawPixmap(option->rect.topLeft(), cache); } @@ -3591,7 +3581,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op QString subLinePixmapName = uniqueName(QLatin1String("scrollbar_subline"), option, button1.size()); QPixmap cache; - if (!UsePixmapCache || !QPixmapCache::find(subLinePixmapName, cache)) { + if (!QPixmapCache::find(subLinePixmapName, cache)) { cache = QPixmap(button1.size()); cache.fill(Qt::white); QRect pixmapRect(0, 0, cache.width(), cache.height()); @@ -3651,8 +3641,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op subLinePainter.drawImage(QPoint(pixmapRect.center().x() - 3, pixmapRect.center().y() - 2), arrow); } subLinePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(subLinePixmapName, cache); + QPixmapCache::insert(subLinePixmapName, cache); } painter->drawPixmap(button1.topLeft(), cache); painter->drawPixmap(button2.topLeft(), cache); @@ -3670,7 +3659,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op sliderPixmapName += QLatin1String("-horizontal"); QPixmap cache; - if (!UsePixmapCache || !QPixmapCache::find(sliderPixmapName, cache)) { + if (!QPixmapCache::find(sliderPixmapName, cache)) { cache = QPixmap(option->rect.size()); cache.fill(Qt::white); QRect pixmapRect(0, 0, cache.width(), cache.height()); @@ -3741,8 +3730,7 @@ void QPlastiqueStyle::drawControl(ControlElement element, const QStyleOption *op } sliderPainter.end(); // insert the slider into the cache - if (UsePixmapCache) - QPixmapCache::insert(sliderPixmapName, cache); + QPixmapCache::insert(sliderPixmapName, cache); } painter->drawPixmap(option->rect.topLeft(), cache); } @@ -3892,7 +3880,7 @@ void QPlastiqueStyle::drawComplexControl(ComplexControl control, const QStyleOpt if ((option->activeSubControls & SC_SliderHandle) && (option->state & State_Sunken)) handlePixmapName += QLatin1String("-sunken"); - if (!UsePixmapCache || !QPixmapCache::find(handlePixmapName, cache)) { + if (!QPixmapCache::find(handlePixmapName, cache)) { cache = QPixmap(handle.size()); cache.fill(Qt::white); QRect pixmapRect(0, 0, handle.width(), handle.height()); @@ -3975,8 +3963,7 @@ void QPlastiqueStyle::drawComplexControl(ComplexControl control, const QStyleOpt } handlePainter.drawImage(pixmapRect, image); handlePainter.end(); - if (UsePixmapCache) - QPixmapCache::insert(handlePixmapName, cache); + QPixmapCache::insert(handlePixmapName, cache); } painter->drawPixmap(handle.topLeft(), cache); diff --git a/src/gui/styles/qstyle_p.h b/src/gui/styles/qstyle_p.h index 848bad6..154321a 100644 --- a/src/gui/styles/qstyle_p.h +++ b/src/gui/styles/qstyle_p.h @@ -77,7 +77,7 @@ public: QPainter *p = painter; \ QString unique = uniqueName((a), option, option->rect.size()); \ int txType = painter->deviceTransform().type() | painter->worldTransform().type(); \ - bool doPixmapCache = UsePixmapCache && txType <= QTransform::TxTranslate; \ + bool doPixmapCache = txType <= QTransform::TxTranslate; \ if (doPixmapCache && QPixmapCache::find(unique, internalPixmapCache)) { \ painter->drawPixmap(option->rect.topLeft(), internalPixmapCache); \ } else { \ diff --git a/src/gui/styles/qstylehelper.cpp b/src/gui/styles/qstylehelper.cpp index 69f8cd2..20de892 100644 --- a/src/gui/styles/qstylehelper.cpp +++ b/src/gui/styles/qstylehelper.cpp @@ -51,7 +51,6 @@ QT_BEGIN_NAMESPACE namespace QStyleHelper { -const bool UsePixmapCache = true; QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size) { diff --git a/src/gui/styles/qstylehelper_p.h b/src/gui/styles/qstylehelper_p.h index 5385d9f..ef6e66c 100644 --- a/src/gui/styles/qstylehelper_p.h +++ b/src/gui/styles/qstylehelper_p.h @@ -66,7 +66,6 @@ class QStyleOption; namespace QStyleHelper { - extern const bool UsePixmapCache; QString uniqueName(const QString &key, const QStyleOption *option, const QSize &size); #ifndef QT_NO_DIAL qreal angle(const QPointF &p1, const QPointF &p2); -- cgit v0.12 From 57ba2d64ba2f261e869ec5242350fc41906e5f96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Morten=20S=C3=B8rvig?= Date: Thu, 4 Jun 2009 12:16:36 +0200 Subject: Enable valgrind on Mac OS X as well. --- src/testlib/qbenchmark_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/testlib/qbenchmark_p.h b/src/testlib/qbenchmark_p.h index b6340f8..f3cd094 100644 --- a/src/testlib/qbenchmark_p.h +++ b/src/testlib/qbenchmark_p.h @@ -55,7 +55,7 @@ #include -#if defined(Q_OS_LINUX) && !defined(QT_NO_PROCESS) +#if (defined(Q_OS_LINUX) || defined Q_OS_MAC) && !defined(QT_NO_PROCESS) #define QTESTLIB_USE_VALGRIND #else #undef QTESTLIB_USE_VALGRIND -- cgit v0.12 From ba4d556e7c9f0f6f2c02893326eec76c21f46fc7 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Thu, 4 Jun 2009 12:34:31 +0200 Subject: qdoc: Put ... around accessor names. --- tools/qdoc3/htmlgenerator.cpp | 45 ++++++++++++++++++++++++++++--------------- tools/qdoc3/htmlgenerator.h | 1 + 2 files changed, 31 insertions(+), 15 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index a2a7184..ab26d08 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -447,21 +447,24 @@ int HtmlGenerator::generateAtom(const Atom *atom, out() << formattingRightMap()[ATOM_FORMATTING_TELETYPE]; break; case Atom::Code: - out() << "
    " << trimmedTrailing(highlightedCode(indent(codeIndent, atom->string()),
    -                                                            marker, relative))
    +	out() << "
    "
    +              << trimmedTrailing(highlightedCode(indent(codeIndent,atom->string()),
    +                                                 marker,relative))
                   << "
    \n"; break; #ifdef QDOC_QML case Atom::Qml: - out() << "
    " << trimmedTrailing(highlightedCode(indent(codeIndent, atom->string()),
    -                                                            marker, relative))
    +	out() << "
    "
    +              << trimmedTrailing(highlightedCode(indent(codeIndent,atom->string()),
    +                                                 marker,relative))
                   << "
    \n"; break; #endif case Atom::CodeNew: out() << "

    you can rewrite it as

    \n" - << "
    " << trimmedTrailing(highlightedCode(indent(codeIndent, atom->string()),
    -                                                            marker, relative))
    +              << "
    "
    +              << trimmedTrailing(highlightedCode(indent(codeIndent,atom->string()),
    +                                                 marker,relative))
                   << "
    \n"; break; case Atom::CodeOld: @@ -469,7 +472,7 @@ int HtmlGenerator::generateAtom(const Atom *atom, // fallthrough case Atom::CodeBad: out() << "
    "
    -              << trimmedTrailing(protect(plainCode(indent(codeIndent, atom->string()))))
    +              << trimmedTrailing(protect(plainCode(indent(codeIndent,atom->string()))))
                   << "
    \n"; break; case Atom::FootnoteLeft: @@ -1533,17 +1536,19 @@ void HtmlGenerator::generateBrief(const Node *node, CodeMarker *marker, void HtmlGenerator::generateIncludes(const InnerNode *inner, CodeMarker *marker) { if (!inner->includes().isEmpty()) { - out() << "
    " << trimmedTrailing(highlightedCode(indent(codeIndent,
    -                                                                   marker->markedUpIncludes(
    -                                                                        inner->includes())),
    -                                                                        marker, inner))
    +        out() << "
    "
    +              << trimmedTrailing(highlightedCode(indent(codeIndent,
    +                                                        marker->markedUpIncludes(inner->includes())),
    +                                                 marker,inner))
                   << "
    "; } } -void HtmlGenerator::generateTableOfContents(const Node *node, CodeMarker *marker, +void HtmlGenerator::generateTableOfContents(const Node *node, + CodeMarker *marker, Doc::SectioningUnit sectioningUnit, - int numColumns, const Node *relative) + int numColumns, + const Node *relative) { if (!node->doc().hasTableOfContents()) @@ -2302,12 +2307,13 @@ void HtmlGenerator::generateSynopsis(const Node *node, marked.replace("<@type>", ""); marked.replace("", ""); } - out() << highlightedCode(marked, marker, relative, nameAlignment); + out() << highlightedCode(marked, marker, relative, style, nameAlignment); } QString HtmlGenerator::highlightedCode(const QString& markedCode, CodeMarker *marker, const Node *relative, + CodeMarker::SynopsisStyle style, bool nameAlignment) { QString src = markedCode; @@ -2320,15 +2326,24 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode, // replace all <@link> tags: "(<@link node=\"([^\"]+)\">).*()" static const QString linkTag("link"); + if (src.contains("setAcceptDrops")) + qDebug() << "SRC:" << src; + bool done = false; for (int i = 0, n = src.size(); i < n;) { if (src.at(i) == charLangle && src.at(i + 1).unicode() == '@') { - if (nameAlignment) // && (i != 0)) Why was this here? + if (nameAlignment && !done) {// && (i != 0)) Why was this here? html += "
    "; + done = true; + } i += 2; if (parseArg(src, linkTag, &i, n, &arg, &par1)) { + if (style == CodeMarker::Accessors) + html += ""; QString link = linkForNode( CodeMarker::nodeForString(par1.toString()), relative); addLink(link, arg, &html); + if (style == CodeMarker::Accessors) + html += ""; } else { html += charLangle; diff --git a/tools/qdoc3/htmlgenerator.h b/tools/qdoc3/htmlgenerator.h index ec9532f..36a2e30 100644 --- a/tools/qdoc3/htmlgenerator.h +++ b/tools/qdoc3/htmlgenerator.h @@ -158,6 +158,7 @@ class HtmlGenerator : public PageGenerator QString highlightedCode(const QString& markedCode, CodeMarker *marker, const Node *relative, + CodeMarker::SynopsisStyle style = CodeMarker::Accessors, bool nameAlignment = false); #else void generateSynopsis(const Node *node, -- cgit v0.12 From c2bad7dba5eccd5450eaf7eddaebc75b8410fa95 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Thu, 4 Jun 2009 12:36:16 +0200 Subject: Add an extra explanation for the API extension. Reviewed-by:David Boddie --- src/gui/image/qpixmapcache.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/gui/image/qpixmapcache.cpp b/src/gui/image/qpixmapcache.cpp index 82b42b4..bdcddfd 100644 --- a/src/gui/image/qpixmapcache.cpp +++ b/src/gui/image/qpixmapcache.cpp @@ -65,7 +65,10 @@ QT_BEGIN_NAMESPACE object for caching the pixmaps. The cache associates a pixmap with a string as a key or with a QPixmapCache::Key. - The QPixmapCache::Key is faster than using strings as key. + The QPixmapCache::Key is faster than using strings as key. The string API is + very convenient for complex keys but the QPixmapCache::Key API will be very efficient + and convenient for a 1 object <-> 1 pixmap mapping (then you can store the key as + a member). If two pixmaps are inserted into the cache using equal keys, then the last pixmap will hide the first pixmap. The QHash and QCache classes do exactly the same. -- cgit v0.12 From e3a562e8d2e5767eef0070dacc01859c0acc142f Mon Sep 17 00:00:00 2001 From: jasplin Date: Thu, 4 Jun 2009 13:07:20 +0200 Subject: Forgot to remove old code in d5231e0593dcbf226e0ca3d679c2547e8e1c9697. Reviewed-by: TrustMe --- src/gui/animation/qguivariantanimation.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/gui/animation/qguivariantanimation.cpp b/src/gui/animation/qguivariantanimation.cpp index 75532f6..bcffb85 100644 --- a/src/gui/animation/qguivariantanimation.cpp +++ b/src/gui/animation/qguivariantanimation.cpp @@ -65,7 +65,6 @@ Q_CONSTRUCTOR_FUNCTION(qRegisterGuiGetInterpolator) static int qUnregisterGuiGetInterpolator() { - qRegisterAnimationInterpolator(0); qRegisterAnimationInterpolator( (QVariant (*)(const QColor &, const QColor &, qreal))0); // cast required by Sun CC 5.5 -- cgit v0.12 From c4773c1b2372ac9119244c5af6d0f0dae3e8f685 Mon Sep 17 00:00:00 2001 From: Thomas Sondergaard Date: Thu, 4 Jun 2009 13:06:31 +0200 Subject: Don't use inactivatable timers to calculate time to wait for next timer. This patch prevents the eventloop from waking up needlessly. Without this patch the event loop will not sleep at all if a 0-timer is already 'inTimerEvent' Merge-request: 550 Reviewed-by: Olivier Goffart --- src/corelib/kernel/qeventdispatcher_unix.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/corelib/kernel/qeventdispatcher_unix.cpp b/src/corelib/kernel/qeventdispatcher_unix.cpp index 6aa3b56..f7293d4 100644 --- a/src/corelib/kernel/qeventdispatcher_unix.cpp +++ b/src/corelib/kernel/qeventdispatcher_unix.cpp @@ -420,10 +420,18 @@ bool QTimerInfoList::timerWait(timeval &tm) timeval currentTime = updateCurrentTime(); repairTimersIfNeeded(); - if (isEmpty()) - return false; + // Find first waiting timer not already active + QTimerInfo *t = 0; + for (QTimerInfoList::const_iterator it = constBegin(); it != constEnd(); ++it) { + if (!(*it)->inTimerEvent) { + t = *it; + break; + } + } + + if (!t) + return false; - QTimerInfo *t = first(); // first waiting timer if (currentTime < t->timeout) { // time to wait tm = t->timeout - currentTime; -- cgit v0.12 From 84e2c537c48122ec6ada0becca701b3b4b6715b1 Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Thu, 4 Jun 2009 13:45:00 +0200 Subject: Make inverted appearance work for progressbar in QMacStyle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HITheme doesn't seem to support the reverse thing. I filled a bug about it, but this is easy to emulate in the horizontal case and the "Inverted" orientation works great for vertical. Task-number: 217594 Reviewed-by: Morten Sørvig --- src/gui/styles/qmacstyle_mac.mm | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/gui/styles/qmacstyle_mac.mm b/src/gui/styles/qmacstyle_mac.mm index 43efedf..99894ad 100644 --- a/src/gui/styles/qmacstyle_mac.mm +++ b/src/gui/styles/qmacstyle_mac.mm @@ -4339,7 +4339,19 @@ void QMacStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter tdi.enableState = kThemeTrackDisabled; else tdi.enableState = kThemeTrackActive; - HIThemeDrawTrack(&tdi, 0, cg, kHIThemeOrientationNormal); + HIThemeOrientation drawOrientation = kHIThemeOrientationNormal; + if (reverse) { + if (vertical) { + drawOrientation = kHIThemeOrientationInverted; + } else { + CGContextSaveGState(cg); + CGContextTranslateCTM(cg, pb->rect.width(), 0); + CGContextScaleCTM(cg, -1, 1); + } + } + HIThemeDrawTrack(&tdi, 0, cg, drawOrientation); + if (reverse && !vertical) + CGContextRestoreGState(cg); } break; case CE_ProgressBarLabel: -- cgit v0.12 From 788a05859a2e6b4533c7b5727952818c95c49568 Mon Sep 17 00:00:00 2001 From: hjk Date: Thu, 4 Jun 2009 13:23:21 +0200 Subject: Add some compile tests for QStringBuilder. --- tests/auto/qstringbuilder/qstringbuilder.pro | 5 + tests/auto/qstringbuilder/scenario1.cpp | 1 + tests/auto/qstringbuilder/scenario1.pro | 8 + tests/auto/qstringbuilder/scenario2.cpp | 1 + tests/auto/qstringbuilder/scenario2.pro | 7 + tests/auto/qstringbuilder/scenario3.cpp | 1 + tests/auto/qstringbuilder/scenario3.pro | 7 + tests/auto/qstringbuilder/scenario4.cpp | 1 + tests/auto/qstringbuilder/scenario4.pro | 7 + tests/auto/qstringbuilder/tst_qstringbuilder.cpp | 182 +++++++++++++++++++++++ 10 files changed, 220 insertions(+) create mode 100644 tests/auto/qstringbuilder/qstringbuilder.pro create mode 100644 tests/auto/qstringbuilder/scenario1.cpp create mode 100644 tests/auto/qstringbuilder/scenario1.pro create mode 100644 tests/auto/qstringbuilder/scenario2.cpp create mode 100644 tests/auto/qstringbuilder/scenario2.pro create mode 100644 tests/auto/qstringbuilder/scenario3.cpp create mode 100644 tests/auto/qstringbuilder/scenario3.pro create mode 100644 tests/auto/qstringbuilder/scenario4.cpp create mode 100644 tests/auto/qstringbuilder/scenario4.pro create mode 100644 tests/auto/qstringbuilder/tst_qstringbuilder.cpp diff --git a/tests/auto/qstringbuilder/qstringbuilder.pro b/tests/auto/qstringbuilder/qstringbuilder.pro new file mode 100644 index 0000000..c5a26d3 --- /dev/null +++ b/tests/auto/qstringbuilder/qstringbuilder.pro @@ -0,0 +1,5 @@ + +TEMPLATE = subdirs +SUBDIRS = scenario1.pro scenario2.pro scenario3.pro scenario4.pro + + diff --git a/tests/auto/qstringbuilder/scenario1.cpp b/tests/auto/qstringbuilder/scenario1.cpp new file mode 100644 index 0000000..26b4ed3 --- /dev/null +++ b/tests/auto/qstringbuilder/scenario1.cpp @@ -0,0 +1 @@ +#include "tst_qstringbuilder.cpp" diff --git a/tests/auto/qstringbuilder/scenario1.pro b/tests/auto/qstringbuilder/scenario1.pro new file mode 100644 index 0000000..4ce7156 --- /dev/null +++ b/tests/auto/qstringbuilder/scenario1.pro @@ -0,0 +1,8 @@ +load(qttest_p4) + +QT = core + +SOURCES += scenario1.cpp + +DEFINES += SCENARIO=1 + diff --git a/tests/auto/qstringbuilder/scenario2.cpp b/tests/auto/qstringbuilder/scenario2.cpp new file mode 100644 index 0000000..26b4ed3 --- /dev/null +++ b/tests/auto/qstringbuilder/scenario2.cpp @@ -0,0 +1 @@ +#include "tst_qstringbuilder.cpp" diff --git a/tests/auto/qstringbuilder/scenario2.pro b/tests/auto/qstringbuilder/scenario2.pro new file mode 100644 index 0000000..64c46e2 --- /dev/null +++ b/tests/auto/qstringbuilder/scenario2.pro @@ -0,0 +1,7 @@ +load(qttest_p4) + +QT = core + +SOURCES += scenario2.cpp + +DEFINES += SCENARIO=2 diff --git a/tests/auto/qstringbuilder/scenario3.cpp b/tests/auto/qstringbuilder/scenario3.cpp new file mode 100644 index 0000000..26b4ed3 --- /dev/null +++ b/tests/auto/qstringbuilder/scenario3.cpp @@ -0,0 +1 @@ +#include "tst_qstringbuilder.cpp" diff --git a/tests/auto/qstringbuilder/scenario3.pro b/tests/auto/qstringbuilder/scenario3.pro new file mode 100644 index 0000000..beedffd --- /dev/null +++ b/tests/auto/qstringbuilder/scenario3.pro @@ -0,0 +1,7 @@ +load(qttest_p4) + +QT = core + +SOURCES += scenario3.cpp + +DEFINES += SCENARIO=3 diff --git a/tests/auto/qstringbuilder/scenario4.cpp b/tests/auto/qstringbuilder/scenario4.cpp new file mode 100644 index 0000000..26b4ed3 --- /dev/null +++ b/tests/auto/qstringbuilder/scenario4.cpp @@ -0,0 +1 @@ +#include "tst_qstringbuilder.cpp" diff --git a/tests/auto/qstringbuilder/scenario4.pro b/tests/auto/qstringbuilder/scenario4.pro new file mode 100644 index 0000000..1c45a70 --- /dev/null +++ b/tests/auto/qstringbuilder/scenario4.pro @@ -0,0 +1,7 @@ +load(qttest_p4) + +QT = core + +SOURCES += scenario4.cpp + +DEFINES += SCENARIO=4 diff --git a/tests/auto/qstringbuilder/tst_qstringbuilder.cpp b/tests/auto/qstringbuilder/tst_qstringbuilder.cpp new file mode 100644 index 0000000..f5df79e --- /dev/null +++ b/tests/auto/qstringbuilder/tst_qstringbuilder.cpp @@ -0,0 +1,182 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// This is included in various .cpp files as a compile test for various scenarios +// depending on NO_CAST_* and QT_USE_FAST_OPERATOR_PLUS and QT_USE_FAST_CONCATENATION + +#if SCENARIO == 1 +// this is the "no harm done" version. Only operator% is active, +// with NO_CAST * defined +#define P % +#undef QT_USE_FAST_OPERATOR_PLUS +#undef QT_USE_FAST_CONCATENATION +#define QT_NO_CAST_FROM_ASCII +#define QT_NO_CAST_TO_ASCII +#endif + + +#if SCENARIO == 2 +// this is the "full" version. Operator+ is replaced by a QStringBuilder +// based version +// with NO_CAST * defined +#define P + +#define QT_USE_FAST_OPERATOR_PLUS +#define QT_USE_FAST_CONCATENATION +#define QT_NO_CAST_FROM_ASCII +#define QT_NO_CAST_TO_ASCII +#endif + +#if SCENARIO == 3 +// this is the "no harm done" version. Only operator% is active, +// with NO_CAST * _not_ defined +#define P % +#undef QT_USE_FAST_OPERATOR_PLUS +#undef QT_USE_FAST_CONCATENATION +#undef QT_NO_CAST_FROM_ASCII +#undef QT_NO_CAST_TO_ASCII +#endif + +#if SCENARIO == 4 +// this is the "full" version. Operator+ is replaced by a QStringBuilder +// based version +// with NO_CAST * _not_ defined +#define P + +#define QT_USE_FAST_OPERATOR_PLUS +#define QT_USE_FAST_CONCATENATION +#undef QT_NO_CAST_FROM_ASCII +#undef QT_NO_CAST_TO_ASCII +#endif + + +#include + +//TESTED_CLASS=QStringBuilder +//TESTED_FILES=qstringbuilder.cpp + +#include + +#define LITERAL "some literal" + +#ifndef QT_NO_CAST_FROM_ASCII + +// Plan is to move the QConcatenable specialications below +// to qstringbuilder.h as soon as the QByteArray builder is +// implemented. + +QT_BEGIN_NAMESPACE + +template struct QConcatenable +{ + typedef char type[N]; + static int size(const char *) { return N - 1; } + static inline void appendTo(const type &a, QChar *&out) + { + memcpy(out, a, N - 1); + out += N - 1; + } +}; + +template struct QConcatenable +{ + typedef char type[N]; + static int size(const char *) { return N - 1; } + static inline void appendTo(const type &a, QChar *&out) + { + memcpy(out, a, N - 1); + out += N - 1; + } +}; + +QT_END_NAMESPACE + +#endif + + +class tst_QStringBuilder : public QObject +{ + Q_OBJECT + +public: + tst_QStringBuilder() {} + ~tst_QStringBuilder() {} + +public slots: + void init() {} + void cleanup() {} + + void scenario(); +}; + +void tst_QStringBuilder::scenario() +{ + QLatin1Literal l1literal(LITERAL); + QLatin1String l1string(LITERAL); + QString string(l1string); + QStringRef stringref(&string, 2, 10); + QLatin1Char achar('c'); + QString r2(QLatin1String(LITERAL LITERAL)); + QString r; + + r = l1literal P l1literal; + QCOMPARE(r, r2); + r = string P string; + QCOMPARE(r, r2); + r = stringref P stringref; + QCOMPARE(r, QString(stringref.toString() + stringref.toString())); + r = string P l1literal; + QCOMPARE(r, r2); + r = string P l1string; + QCOMPARE(r, r2); + r = string + achar; + QCOMPARE(r, QString(string P achar)); + r = achar + string; + QCOMPARE(r, QString(achar P string)); +#ifndef QT_NO_CAST_FROM_ASCII + r = string P LITERAL; + QCOMPARE(r, r2); + r = LITERAL P string; + QCOMPARE(r, r2); +#endif +} + +QTEST_APPLESS_MAIN(tst_QStringBuilder) + +#include "tst_qstringbuilder.moc" -- cgit v0.12 From 58900297b27f063b1b838a0c542218dd6d7246dd Mon Sep 17 00:00:00 2001 From: hjk Date: Thu, 4 Jun 2009 13:48:43 +0200 Subject: qdoc3: define QT_NO_CAST_TO_ASCII for safety, no code changes needed. --- tools/qdoc3/qdoc3.pro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/qdoc3/qdoc3.pro b/tools/qdoc3/qdoc3.pro index 2bba8fb..ead7b88 100644 --- a/tools/qdoc3/qdoc3.pro +++ b/tools/qdoc3/qdoc3.pro @@ -1,5 +1,5 @@ DEFINES += QDOC2_COMPAT -#DEFINES += QT_NO_CAST_TO_ASCII +DEFINES += QT_NO_CAST_TO_ASCII #DEFINES += QT_NO_CAST_FROM_ASCII QT = core xml -- cgit v0.12 From 7e6b33b29057556903c37aadd0f48650641591fa Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Thu, 4 Jun 2009 14:11:01 +0200 Subject: kill usage of QT_STATEMACHINE_SOLUTION The define no longer exists. --- examples/statemachine/eventtransitions/main.cpp | 5 ----- examples/statemachine/factorial/main.cpp | 6 ------ examples/statemachine/pingpong/main.cpp | 5 ----- examples/statemachine/trafficlight/main.cpp | 5 ----- examples/statemachine/twowaybutton/main.cpp | 4 ---- 5 files changed, 25 deletions(-) diff --git a/examples/statemachine/eventtransitions/main.cpp b/examples/statemachine/eventtransitions/main.cpp index aba0c73..5959016 100644 --- a/examples/statemachine/eventtransitions/main.cpp +++ b/examples/statemachine/eventtransitions/main.cpp @@ -40,11 +40,6 @@ ****************************************************************************/ #include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#include -#endif //! [0] class Window : public QWidget diff --git a/examples/statemachine/factorial/main.cpp b/examples/statemachine/factorial/main.cpp index 1065eb8..bf3f80e 100644 --- a/examples/statemachine/factorial/main.cpp +++ b/examples/statemachine/factorial/main.cpp @@ -41,12 +41,6 @@ #include #include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#include -#include -#endif //! [0] class Factorial : public QObject diff --git a/examples/statemachine/pingpong/main.cpp b/examples/statemachine/pingpong/main.cpp index 331627e..586b422 100644 --- a/examples/statemachine/pingpong/main.cpp +++ b/examples/statemachine/pingpong/main.cpp @@ -41,11 +41,6 @@ #include #include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#include -#endif //! [0] class PingEvent : public QEvent diff --git a/examples/statemachine/trafficlight/main.cpp b/examples/statemachine/trafficlight/main.cpp index 8a46fff..23f4bed 100644 --- a/examples/statemachine/trafficlight/main.cpp +++ b/examples/statemachine/trafficlight/main.cpp @@ -40,11 +40,6 @@ ****************************************************************************/ #include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#include -#endif //! [0] class LightWidget : public QWidget diff --git a/examples/statemachine/twowaybutton/main.cpp b/examples/statemachine/twowaybutton/main.cpp index a2c6e45..f5afeca 100644 --- a/examples/statemachine/twowaybutton/main.cpp +++ b/examples/statemachine/twowaybutton/main.cpp @@ -40,10 +40,6 @@ ****************************************************************************/ #include -#ifdef QT_STATEMACHINE_SOLUTION -#include -#include -#endif //! [0] int main(int argc, char **argv) -- cgit v0.12 From 5ad68ce1cb5e80fa14e549f087e957030ef4baf0 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 4 Jun 2009 14:30:20 +0200 Subject: Add my changelog for 4.5.2 --- dist/changes-4.5.2 | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index a54d8ba..4246a6b 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -46,6 +46,10 @@ Third party components Plugins (r41346, r43550, r43915, r43917, r43923) Clipboard (r41360) +- QtDBus + * [236955] Fixed an issue that would cause QtDBus to crash when + relaying a signal emitted from a class under certain conditions + - QAbstractItemView * [250754] Changing the font of the view would not update the size of the items if there is an application stylesheet. @@ -80,6 +84,10 @@ Third party components * [251467] do not allow cookies for domains like ".com" * [228974] allow cookies whose domain attribute is missing a leading dot +- QNetworkAccessManager + * [248838] Make QNetworkAccessManager reject invalid HTTP input + earlier + - QWidget * [250668] Don't send extra wheel events when using the scroll wheel in Cocoa. * [253448] Prevent a crash when using the Qt::WA_MacBrushedMetal attribute @@ -166,6 +174,7 @@ legacy freetype headers. [250326] Titlebar wasn't shown on X11 with Qt::CustomizeWindowHint for fixed-size windows. [251925] Improved showing QMessageBox on small screens. +[252042] Fixed the loading of the OpenSSL libraries on OpenBSD. Qt for Windows -------------- -- cgit v0.12 From f0f7da04358c82bb80c6670ca336ebd2154163a6 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 4 Jun 2009 14:30:51 +0200 Subject: Remove a Q_ASSERT that could be triggered under some conditions. Whenever an argument failed to marshall, this assert would be triggered. It's technically an error in the application, but it's hard to track it down. So remove it and let the execution continue (the function returns false indicating failure already and there's a warning from the marshalling code itself) Reviewed-by: TrustMe --- src/dbus/qdbusmessage.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/dbus/qdbusmessage.cpp b/src/dbus/qdbusmessage.cpp index 19f0b04..96dcd3b 100644 --- a/src/dbus/qdbusmessage.cpp +++ b/src/dbus/qdbusmessage.cpp @@ -161,7 +161,6 @@ DBusMessage *QDBusMessagePrivate::toDBusMessage(const QDBusMessage &message) // not ok; q_dbus_message_unref(msg); - Q_ASSERT(false); return 0; } -- cgit v0.12 From e2382d731249dc57e7c538ec60b3f1f714741cfd Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 4 Jun 2009 14:32:33 +0200 Subject: move the QT_NO_ANIMATION macro to the right place (ie after other includes) --- src/corelib/animation/qabstractanimation.cpp | 4 ++-- src/corelib/animation/qanimationgroup.cpp | 4 ++-- src/corelib/animation/qparallelanimationgroup.cpp | 4 +++- src/corelib/animation/qpauseanimation.cpp | 4 ++-- src/corelib/animation/qpropertyanimation.cpp | 4 ++-- src/corelib/animation/qsequentialanimationgroup.cpp | 6 ++---- src/corelib/animation/qvariantanimation.cpp | 4 ++-- 7 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/corelib/animation/qabstractanimation.cpp b/src/corelib/animation/qabstractanimation.cpp index 61d61df..fcc63a4 100644 --- a/src/corelib/animation/qabstractanimation.cpp +++ b/src/corelib/animation/qabstractanimation.cpp @@ -142,8 +142,6 @@ \sa direction */ -#ifndef QT_NO_ANIMATION - #include "qabstractanimation.h" #include "qanimationgroup.h" #include @@ -155,6 +153,8 @@ #include #include +#ifndef QT_NO_ANIMATION + #define DEFAULT_TIMER_INTERVAL 16 QT_BEGIN_NAMESPACE diff --git a/src/corelib/animation/qanimationgroup.cpp b/src/corelib/animation/qanimationgroup.cpp index 839b522..e192a6c 100644 --- a/src/corelib/animation/qanimationgroup.cpp +++ b/src/corelib/animation/qanimationgroup.cpp @@ -89,13 +89,13 @@ \sa QAbstractAnimation, QVariantAnimation, {The Animation Framework} */ -#ifndef QT_NO_ANIMATION - #include "qanimationgroup.h" #include #include #include "qanimationgroup_p.h" +#ifndef QT_NO_ANIMATION + QT_BEGIN_NAMESPACE diff --git a/src/corelib/animation/qparallelanimationgroup.cpp b/src/corelib/animation/qparallelanimationgroup.cpp index 13f6073..c148cb5d 100644 --- a/src/corelib/animation/qparallelanimationgroup.cpp +++ b/src/corelib/animation/qparallelanimationgroup.cpp @@ -68,11 +68,13 @@ \sa QAnimationGroup, QPropertyAnimation, {The Animation Framework} */ -#ifndef QT_NO_ANIMATION #include "qparallelanimationgroup.h" #include "qparallelanimationgroup_p.h" //#define QANIMATION_DEBUG + +#ifndef QT_NO_ANIMATION + QT_BEGIN_NAMESPACE /*! diff --git a/src/corelib/animation/qpauseanimation.cpp b/src/corelib/animation/qpauseanimation.cpp index b175f0c..93043c2 100644 --- a/src/corelib/animation/qpauseanimation.cpp +++ b/src/corelib/animation/qpauseanimation.cpp @@ -62,12 +62,12 @@ \sa QSequentialAnimationGroup */ -#ifndef QT_NO_ANIMATION - #include "qpauseanimation.h" #include "qabstractanimation_p.h" +#ifndef QT_NO_ANIMATION + QT_BEGIN_NAMESPACE class QPauseAnimationPrivate : public QAbstractAnimationPrivate diff --git a/src/corelib/animation/qpropertyanimation.cpp b/src/corelib/animation/qpropertyanimation.cpp index 357a6ac..65f1361 100644 --- a/src/corelib/animation/qpropertyanimation.cpp +++ b/src/corelib/animation/qpropertyanimation.cpp @@ -87,8 +87,6 @@ \sa QVariantAnimation, QAnimationGroup, {The Animation Framework} */ -#ifndef QT_NO_ANIMATION - #include "qpropertyanimation.h" #include "qanimationgroup.h" #include "qpropertyanimation_p.h" @@ -97,6 +95,8 @@ #include #include +#ifndef QT_NO_ANIMATION + QT_BEGIN_NAMESPACE typedef QPair QPropertyAnimationPair; diff --git a/src/corelib/animation/qsequentialanimationgroup.cpp b/src/corelib/animation/qsequentialanimationgroup.cpp index 14814a7..25db52f 100644 --- a/src/corelib/animation/qsequentialanimationgroup.cpp +++ b/src/corelib/animation/qsequentialanimationgroup.cpp @@ -77,8 +77,6 @@ \sa QAnimationGroup, QAbstractAnimation, {The Animation Framework} */ -#ifndef QT_NO_ANIMATION - #include "qsequentialanimationgroup.h" #include "qsequentialanimationgroup_p.h" @@ -86,9 +84,9 @@ #include -QT_BEGIN_NAMESPACE - +#ifndef QT_NO_ANIMATION +QT_BEGIN_NAMESPACE bool QSequentialAnimationGroupPrivate::atEnd() const { diff --git a/src/corelib/animation/qvariantanimation.cpp b/src/corelib/animation/qvariantanimation.cpp index a3fa93a..ab73373 100644 --- a/src/corelib/animation/qvariantanimation.cpp +++ b/src/corelib/animation/qvariantanimation.cpp @@ -39,8 +39,6 @@ ** ****************************************************************************/ -#ifndef QT_NO_ANIMATION - #include "qvariantanimation.h" #include "qvariantanimation_p.h" @@ -49,6 +47,8 @@ #include #include +#ifndef QT_NO_ANIMATION + QT_BEGIN_NAMESPACE /*! -- cgit v0.12 From 80b63705a64a2029800805e1fefe350543b15a70 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 4 Jun 2009 14:35:10 +0200 Subject: Autotest: add some tests for sending (or failing to) invalid D-Bus calls Reviewed-by: TrustMe --- tests/auto/qdbusmarshall/tst_qdbusmarshall.cpp | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/tests/auto/qdbusmarshall/tst_qdbusmarshall.cpp b/tests/auto/qdbusmarshall/tst_qdbusmarshall.cpp index ad1a1b8..58bfabc 100644 --- a/tests/auto/qdbusmarshall/tst_qdbusmarshall.cpp +++ b/tests/auto/qdbusmarshall/tst_qdbusmarshall.cpp @@ -84,6 +84,8 @@ private slots: void sendArgument_data(); void sendArgument(); + void sendErrors(); + private: QProcess proc; }; @@ -782,5 +784,28 @@ void tst_QDBusMarshall::sendArgument() QCOMPARE(extracted, value); } +void tst_QDBusMarshall::sendErrors() +{ + QDBusConnection con = QDBusConnection::sessionBus(); + + QVERIFY(con.isConnected()); + QDBusMessage msg = QDBusMessage::createSignal("/foo", "local.interfaceName", + "signalName"); + msg << qVariantFromValue(QDBusObjectPath()); + + QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal path \"/foo\" interface \"local.interfaceName\" member \"signalName\""); + QVERIFY(!con.send(msg)); + + msg.setArguments(QVariantList()); + QDBusObjectPath path; + + QTest::ignoreMessage(QtWarningMsg, "QDBusObjectPath: invalid path \"abc\""); + path.setPath("abc"); + msg << qVariantFromValue(path); + + QTest::ignoreMessage(QtWarningMsg, "QDBusConnection: error: could not send signal path \"/foo\" interface \"local.interfaceName\" member \"signalName\""); + QVERIFY(!con.send(msg)); +} + QTEST_MAIN(tst_QDBusMarshall) #include "tst_qdbusmarshall.moc" -- cgit v0.12 From 398c022e8adefc6e71a6048da40c19f6169be831 Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Thu, 4 Jun 2009 15:22:13 +0200 Subject: my public task ... --- dist/changes-4.5.2 | 3 +++ 1 file changed, 3 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 4246a6b..04a29ba 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -77,6 +77,9 @@ Third party components - QFontDialog * [252000] Ensure that QFontDialog::getFont() works on Mac OS X. +- QLocalSocket + * [247144] correctly handle remote disconnects + - QNetworkCookie * [251959] fix parsing of multiple cookies separated by a newline -- cgit v0.12 From 7eb85cdd2a507b6fa1f8023b26f8b34e2fe6f2c4 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 4 Jun 2009 15:12:00 +0200 Subject: Autotest: fix detection of generated files and strip the first line Reviewed-by: TrustMe --- tests/auto/headers/tst_headers.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/auto/headers/tst_headers.cpp b/tests/auto/headers/tst_headers.cpp index 607d655..7e32deb 100644 --- a/tests/auto/headers/tst_headers.cpp +++ b/tests/auto/headers/tst_headers.cpp @@ -135,6 +135,9 @@ void tst_Headers::licenseCheck() QByteArray data = f.readAll(); QStringList content = QString::fromLocal8Bit(data.replace('\r',"")).split("\n"); + if (content.first().contains("generated")) + content.takeFirst(); + QVERIFY(licensePattern.exactMatch(content.at(7)) || licensePattern.exactMatch(content.at(4))); QString licenseType = licensePattern.cap(1); -- cgit v0.12 From 0d47438a75bef93ac15aba011d7bf931791e32f9 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 4 Jun 2009 15:27:17 +0200 Subject: Fix headers in the XUnit feature. All Qt headers must have QT_BEGIN_HEADER, QT_END_HEADER and QT_MODULE. These headers didn't have this. Reviewed-by: TrustMe --- src/testlib/qtestbasicstreamer.h | 6 ++++++ src/testlib/qtestcoreelement.h | 10 ++++++++-- src/testlib/qtestcorelist.h | 6 ++++++ src/testlib/qtestelement.h | 8 +++++++- src/testlib/qtestelementattribute.h | 8 +++++++- src/testlib/qtestfilelogger.h | 6 ++++++ src/testlib/qtestlightxmlstreamer.h | 8 +++++++- src/testlib/qtestxmlstreamer.h | 8 +++++++- src/testlib/qtestxunitstreamer.h | 8 +++++++- 9 files changed, 61 insertions(+), 7 deletions(-) diff --git a/src/testlib/qtestbasicstreamer.h b/src/testlib/qtestbasicstreamer.h index 527b1d4..61cdfd5 100644 --- a/src/testlib/qtestbasicstreamer.h +++ b/src/testlib/qtestbasicstreamer.h @@ -44,8 +44,12 @@ #include +QT_BEGIN_HEADER + QT_BEGIN_NAMESPACE +QT_MODULE(Test) + class QTestElement; class QTestElementAttribute; class QTestLogger; @@ -81,4 +85,6 @@ class QTestBasicStreamer QT_END_NAMESPACE +QT_END_HEADER + #endif diff --git a/src/testlib/qtestcoreelement.h b/src/testlib/qtestcoreelement.h index 4cf8fcb..907041f 100644 --- a/src/testlib/qtestcoreelement.h +++ b/src/testlib/qtestcoreelement.h @@ -42,11 +42,15 @@ #ifndef QTESTCOREELEMENT_H #define QTESTCOREELEMENT_H -#include "qtestcorelist.h" -#include "qtestelementattribute.h" +#include +#include + +QT_BEGIN_HEADER QT_BEGIN_NAMESPACE +QT_MODULE(Test) + template class QTestCoreElement: public QTestCoreList { @@ -163,4 +167,6 @@ const QTestElementAttribute *QTestCoreElement::attribute(QTest::Att QT_END_NAMESPACE +QT_END_HEADER + #endif diff --git a/src/testlib/qtestcorelist.h b/src/testlib/qtestcorelist.h index 686e157..9983b27 100644 --- a/src/testlib/qtestcorelist.h +++ b/src/testlib/qtestcorelist.h @@ -44,8 +44,12 @@ #include +QT_BEGIN_HEADER + QT_BEGIN_NAMESPACE +QT_MODULE(Test) + template class QTestCoreList { @@ -127,4 +131,6 @@ int QTestCoreList::count() QT_END_NAMESPACE +QT_END_HEADER + #endif diff --git a/src/testlib/qtestelement.h b/src/testlib/qtestelement.h index c1932da..e75689a 100644 --- a/src/testlib/qtestelement.h +++ b/src/testlib/qtestelement.h @@ -42,10 +42,14 @@ #ifndef QTESTELEMENT_H #define QTESTELEMENT_H -#include "qtestcoreelement.h" +#include + +QT_BEGIN_HEADER QT_BEGIN_NAMESPACE +QT_MODULE(Test) + class QTestElement: public QTestCoreElement { public: @@ -66,4 +70,6 @@ class QTestElement: public QTestCoreElement QT_END_NAMESPACE +QT_END_HEADER + #endif diff --git a/src/testlib/qtestelementattribute.h b/src/testlib/qtestelementattribute.h index 261f3f7..944d9c0 100644 --- a/src/testlib/qtestelementattribute.h +++ b/src/testlib/qtestelementattribute.h @@ -42,10 +42,14 @@ #ifndef QTESTELEMENTATTRIBUTE_H #define QTESTELEMENTATTRIBUTE_H -#include "qtestcorelist.h" +#include + +QT_BEGIN_HEADER QT_BEGIN_NAMESPACE +QT_MODULE(Test) + namespace QTest { enum AttributeIndex @@ -102,4 +106,6 @@ class QTestElementAttribute: public QTestCoreList QT_END_NAMESPACE +QT_END_HEADER + #endif diff --git a/src/testlib/qtestfilelogger.h b/src/testlib/qtestfilelogger.h index 892657d..f6a993d 100644 --- a/src/testlib/qtestfilelogger.h +++ b/src/testlib/qtestfilelogger.h @@ -44,8 +44,12 @@ #include +QT_BEGIN_HEADER + QT_BEGIN_NAMESPACE +QT_MODULE(Test) + class QTestFileLogger { public: @@ -58,4 +62,6 @@ class QTestFileLogger QT_END_NAMESPACE +QT_END_HEADER + #endif // QTESTFILELOGGER_H diff --git a/src/testlib/qtestlightxmlstreamer.h b/src/testlib/qtestlightxmlstreamer.h index 382a14a..3f564a8 100644 --- a/src/testlib/qtestlightxmlstreamer.h +++ b/src/testlib/qtestlightxmlstreamer.h @@ -42,10 +42,14 @@ #ifndef QTESTLIGHTXMLSTREAMER_H #define QTESTLIGHTXMLSTREAMER_H -#include "qtestbasicstreamer.h" +#include + +QT_BEGIN_HEADER QT_BEGIN_NAMESPACE +QT_MODULE(Test) + class QTestElement; class QTestElementAttribute; @@ -63,4 +67,6 @@ class QTestLightXmlStreamer: public QTestBasicStreamer QT_END_NAMESPACE +QT_END_HEADER + #endif diff --git a/src/testlib/qtestxmlstreamer.h b/src/testlib/qtestxmlstreamer.h index 58544a4..814bffc 100644 --- a/src/testlib/qtestxmlstreamer.h +++ b/src/testlib/qtestxmlstreamer.h @@ -42,10 +42,14 @@ #ifndef QTESTXMLSTREAMER_H #define QTESXMLSTREAMER_H -#include "qtestbasicstreamer.h" +#include + +QT_BEGIN_HEADER QT_BEGIN_NAMESPACE +QT_MODULE(Test) + class QTestElement; class QTestElementAttribute; @@ -63,4 +67,6 @@ class QTestXmlStreamer: public QTestBasicStreamer QT_END_NAMESPACE +QT_END_HEADER + #endif diff --git a/src/testlib/qtestxunitstreamer.h b/src/testlib/qtestxunitstreamer.h index b4b82f0..0e48b2c 100644 --- a/src/testlib/qtestxunitstreamer.h +++ b/src/testlib/qtestxunitstreamer.h @@ -42,10 +42,14 @@ #ifndef QTESTXUNITSTREAMER_H #define QTESTXUNITSTREAMER_H -#include "qtestbasicstreamer.h" +#include + +QT_BEGIN_HEADER QT_BEGIN_NAMESPACE +QT_MODULE(Test) + class QTestLogger; class QTestXunitStreamer: public QTestBasicStreamer @@ -68,4 +72,6 @@ class QTestXunitStreamer: public QTestBasicStreamer QT_END_NAMESPACE +QT_END_HEADER + #endif -- cgit v0.12 From 30971fa4ffaeb4c2a3a1267cca73311fb9834241 Mon Sep 17 00:00:00 2001 From: Erik Verbruggen Date: Thu, 4 Jun 2009 15:35:22 +0200 Subject: Added offsets of automatically inserted semicolons to the DOM and the QML script parser. --- src/declarative/qml/qmldom.cpp | 10 ++++++++++ src/declarative/qml/qmldom.h | 3 +++ src/declarative/qml/qmldom_p.h | 1 + src/declarative/qml/qmlscriptparser.cpp | 11 +++++++++++ src/declarative/qml/qmlscriptparser_p.h | 4 ++++ 5 files changed, 29 insertions(+) diff --git a/src/declarative/qml/qmldom.cpp b/src/declarative/qml/qmldom.cpp index 0ebbbfb..e06afb5 100644 --- a/src/declarative/qml/qmldom.cpp +++ b/src/declarative/qml/qmldom.cpp @@ -194,6 +194,8 @@ bool QmlDomDocument::load(QmlEngine *engine, const QByteArray &data, const QUrl d->imports += QUrl(td->data.imports().at(i).uri); } + d->automaticSemicolonOffsets = td->data.automaticSemicolonOffsets(); + if (td->data.tree()) { if (compilerDump()) { qWarning() << "-AST------------------------------------------------------------------------------"; @@ -251,6 +253,14 @@ QmlDomObject QmlDomDocument::rootObject() const return rv; } +QList QmlDomDocument::automaticSemicolonOffsets() const +{ + if (d) + return d->automaticSemicolonOffsets; + else + return QList(); +} + QmlDomPropertyPrivate::QmlDomPropertyPrivate() : property(0) { diff --git a/src/declarative/qml/qmldom.h b/src/declarative/qml/qmldom.h index 86eaecb..442a4fc 100644 --- a/src/declarative/qml/qmldom.h +++ b/src/declarative/qml/qmldom.h @@ -78,6 +78,9 @@ public: QByteArray save() const; QmlDomObject rootObject() const; + + QList automaticSemicolonOffsets() const; + private: QSharedDataPointer d; }; diff --git a/src/declarative/qml/qmldom_p.h b/src/declarative/qml/qmldom_p.h index 74edd47..441269c 100644 --- a/src/declarative/qml/qmldom_p.h +++ b/src/declarative/qml/qmldom_p.h @@ -62,6 +62,7 @@ public: QList errors; QList imports; QmlParser::Object *root; + QList automaticSemicolonOffsets; }; class QmlDomObjectPrivate : public QSharedData diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index 31a20be..5207292 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -178,6 +178,8 @@ protected: virtual bool visit(AST::UiArrayBinding *node); virtual bool visit(AST::UiSourceElement *node); + virtual bool visit(AST::ExpressionStatement *node); + void accept(AST::Node *node); QString asString(AST::UiQualifiedId *node) const; @@ -638,6 +640,14 @@ bool ProcessAST::visit(AST::UiScriptBinding *node) return true; } +bool ProcessAST::visit(AST::ExpressionStatement *node) +{ + if (!node->semicolonToken.isValid()) + _parser->addAutomaticSemicolonOffset(node->semicolonToken.offset); + + return true; +} + // UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiObjectMemberList T_RBRACKET ; bool ProcessAST::visit(AST::UiArrayBinding *node) { @@ -825,6 +835,7 @@ void QmlScriptParser::clear() _nameSpacePaths.clear(); _typeNames.clear(); _errors.clear(); + _automaticSemicolonOffsets.clear(); if (data) { delete data; diff --git a/src/declarative/qml/qmlscriptparser_p.h b/src/declarative/qml/qmlscriptparser_p.h index 3993194..b057e2b 100644 --- a/src/declarative/qml/qmlscriptparser_p.h +++ b/src/declarative/qml/qmlscriptparser_p.h @@ -82,6 +82,9 @@ public: QList errors() const; + QList automaticSemicolonOffsets() const { return _automaticSemicolonOffsets; } + void addAutomaticSemicolonOffset(int offset) { _automaticSemicolonOffsets.append(offset); } + // ### private: int findOrCreateTypeId(const QString &name); void setTree(QmlParser::Object *tree); @@ -100,6 +103,7 @@ public: QStringList _typeNames; QString _scriptFile; QmlScriptParserJsASTData *data; + QList _automaticSemicolonOffsets; }; QT_END_NAMESPACE -- cgit v0.12 From fcd1059f05be695b78f42c02446b17ab143ce9c0 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Thu, 4 Jun 2009 15:35:19 +0200 Subject: kill bad QT_END_HEADER There should be no QT_{BEGIN,END}_HEADER here; this is a private header. --- src/gui/statemachine/qbasicmouseeventtransition_p.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/gui/statemachine/qbasicmouseeventtransition_p.h b/src/gui/statemachine/qbasicmouseeventtransition_p.h index 6c0afe4..3161844 100644 --- a/src/gui/statemachine/qbasicmouseeventtransition_p.h +++ b/src/gui/statemachine/qbasicmouseeventtransition_p.h @@ -93,6 +93,4 @@ private: QT_END_NAMESPACE -QT_END_HEADER - #endif -- cgit v0.12 From 5c23548a0a60ca25631cff2fa7f296fdbd15b78a Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Thu, 4 Jun 2009 16:05:19 +0200 Subject: add QT_NO_STATEMACHINE define so state machine can be compiled out Reviewed-by: Thierry Bastian --- src/corelib/global/qfeatures.txt | 7 +++++++ src/corelib/statemachine/qabstractstate.cpp | 5 +++++ src/corelib/statemachine/qabstractstate.h | 4 ++++ src/corelib/statemachine/qabstracttransition.cpp | 5 +++++ src/corelib/statemachine/qabstracttransition.h | 4 ++++ src/corelib/statemachine/qeventtransition.cpp | 5 +++++ src/corelib/statemachine/qeventtransition.h | 4 ++++ src/corelib/statemachine/qfinalstate.cpp | 5 +++++ src/corelib/statemachine/qfinalstate.h | 4 ++++ src/corelib/statemachine/qhistorystate.cpp | 5 +++++ src/corelib/statemachine/qhistorystate.h | 4 ++++ src/corelib/statemachine/qsignalevent.h | 4 ++++ src/corelib/statemachine/qsignaltransition.cpp | 5 +++++ src/corelib/statemachine/qsignaltransition.h | 4 ++++ src/corelib/statemachine/qstate.cpp | 5 +++++ src/corelib/statemachine/qstate.h | 4 ++++ src/corelib/statemachine/qstatemachine.cpp | 5 +++++ src/corelib/statemachine/qstatemachine.h | 4 ++++ src/corelib/statemachine/qwrappedevent.h | 4 ++++ src/gui/kernel/qapplication.cpp | 4 ++++ src/gui/statemachine/qbasickeyeventtransition.cpp | 5 +++++ src/gui/statemachine/qbasickeyeventtransition_p.h | 5 +++++ src/gui/statemachine/qbasicmouseeventtransition.cpp | 5 +++++ src/gui/statemachine/qbasicmouseeventtransition_p.h | 5 +++++ src/gui/statemachine/qguistatemachine.cpp | 5 +++++ src/gui/statemachine/qkeyeventtransition.cpp | 5 +++++ src/gui/statemachine/qkeyeventtransition.h | 4 ++++ src/gui/statemachine/qmouseeventtransition.cpp | 5 +++++ src/gui/statemachine/qmouseeventtransition.h | 4 ++++ 29 files changed, 134 insertions(+) diff --git a/src/corelib/global/qfeatures.txt b/src/corelib/global/qfeatures.txt index 23ec7b0..9408a5b 100644 --- a/src/corelib/global/qfeatures.txt +++ b/src/corelib/global/qfeatures.txt @@ -1164,6 +1164,13 @@ Requires: PROPERTIES Name: Animation SeeAlso: ??? +Feature: STATEMACHINE +Description: Provides hierarchical finite state machines. +Section: Utilities +Requires: PROPERTIES +Name: State machine +SeeAlso: ??? + # SVG diff --git a/src/corelib/statemachine/qabstractstate.cpp b/src/corelib/statemachine/qabstractstate.cpp index 942722f..b9a50a2 100644 --- a/src/corelib/statemachine/qabstractstate.cpp +++ b/src/corelib/statemachine/qabstractstate.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qabstractstate.h" + +#ifndef QT_NO_STATEMACHINE + #include "qabstractstate_p.h" #include "qstate.h" #include "qstate_p.h" @@ -200,3 +203,5 @@ bool QAbstractState::event(QEvent *e) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/corelib/statemachine/qabstractstate.h b/src/corelib/statemachine/qabstractstate.h index d0ebb52..ee55541 100644 --- a/src/corelib/statemachine/qabstractstate.h +++ b/src/corelib/statemachine/qabstractstate.h @@ -50,6 +50,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QState; class QStateMachine; @@ -83,6 +85,8 @@ private: Q_DECLARE_PRIVATE(QAbstractState) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qabstracttransition.cpp b/src/corelib/statemachine/qabstracttransition.cpp index dfcafeb..f582b8c 100644 --- a/src/corelib/statemachine/qabstracttransition.cpp +++ b/src/corelib/statemachine/qabstracttransition.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qabstracttransition.h" + +#ifndef QT_NO_STATEMACHINE + #include "qabstracttransition_p.h" #include "qabstractstate.h" #include "qstate.h" @@ -340,3 +343,5 @@ bool QAbstractTransition::event(QEvent *e) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/corelib/statemachine/qabstracttransition.h b/src/corelib/statemachine/qabstracttransition.h index c63d55a..a1a62c9 100644 --- a/src/corelib/statemachine/qabstracttransition.h +++ b/src/corelib/statemachine/qabstracttransition.h @@ -52,6 +52,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QEvent; class QAbstractState; class QState; @@ -104,6 +106,8 @@ private: Q_DECLARE_PRIVATE(QAbstractTransition) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qeventtransition.cpp b/src/corelib/statemachine/qeventtransition.cpp index f25d821..4c40256 100644 --- a/src/corelib/statemachine/qeventtransition.cpp +++ b/src/corelib/statemachine/qeventtransition.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qeventtransition.h" + +#ifndef QT_NO_STATEMACHINE + #include "qeventtransition_p.h" #include "qwrappedevent.h" #include "qstate.h" @@ -283,3 +286,5 @@ bool QEventTransition::event(QEvent *e) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/corelib/statemachine/qeventtransition.h b/src/corelib/statemachine/qeventtransition.h index 3530bdd..40ffecf 100644 --- a/src/corelib/statemachine/qeventtransition.h +++ b/src/corelib/statemachine/qeventtransition.h @@ -51,6 +51,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QEventTransitionPrivate; class Q_CORE_EXPORT QEventTransition : public QAbstractTransition { @@ -89,6 +91,8 @@ private: Q_DECLARE_PRIVATE(QEventTransition) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qfinalstate.cpp b/src/corelib/statemachine/qfinalstate.cpp index 0980336..0eb531f 100644 --- a/src/corelib/statemachine/qfinalstate.cpp +++ b/src/corelib/statemachine/qfinalstate.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qfinalstate.h" + +#ifndef QT_NO_STATEMACHINE + #include "qabstractstate_p.h" QT_BEGIN_NAMESPACE @@ -132,3 +135,5 @@ bool QFinalState::event(QEvent *e) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/corelib/statemachine/qfinalstate.h b/src/corelib/statemachine/qfinalstate.h index fa68394..865f333 100644 --- a/src/corelib/statemachine/qfinalstate.h +++ b/src/corelib/statemachine/qfinalstate.h @@ -50,6 +50,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QFinalStatePrivate; class Q_CORE_EXPORT QFinalState : public QAbstractState { @@ -69,6 +71,8 @@ private: Q_DECLARE_PRIVATE(QFinalState) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qhistorystate.cpp b/src/corelib/statemachine/qhistorystate.cpp index 517faa8..4304da3 100644 --- a/src/corelib/statemachine/qhistorystate.cpp +++ b/src/corelib/statemachine/qhistorystate.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qhistorystate.h" + +#ifndef QT_NO_STATEMACHINE + #include "qhistorystate_p.h" QT_BEGIN_NAMESPACE @@ -221,3 +224,5 @@ bool QHistoryState::event(QEvent *e) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/corelib/statemachine/qhistorystate.h b/src/corelib/statemachine/qhistorystate.h index a0682bd..eee43d1 100644 --- a/src/corelib/statemachine/qhistorystate.h +++ b/src/corelib/statemachine/qhistorystate.h @@ -50,6 +50,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QHistoryStatePrivate; class Q_CORE_EXPORT QHistoryState : public QAbstractState { @@ -84,6 +86,8 @@ private: Q_DECLARE_PRIVATE(QHistoryState) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qsignalevent.h b/src/corelib/statemachine/qsignalevent.h index 8221f68..79d1053 100644 --- a/src/corelib/statemachine/qsignalevent.h +++ b/src/corelib/statemachine/qsignalevent.h @@ -53,6 +53,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class Q_CORE_EXPORT QSignalEvent : public QEvent { public: @@ -70,6 +72,8 @@ private: QList m_arguments; }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qsignaltransition.cpp b/src/corelib/statemachine/qsignaltransition.cpp index 9ffcb9c..2e150a7 100644 --- a/src/corelib/statemachine/qsignaltransition.cpp +++ b/src/corelib/statemachine/qsignaltransition.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qsignaltransition.h" + +#ifndef QT_NO_STATEMACHINE + #include "qsignaltransition_p.h" #include "qsignalevent.h" #include "qstate.h" @@ -258,3 +261,5 @@ bool QSignalTransition::event(QEvent *e) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/corelib/statemachine/qsignaltransition.h b/src/corelib/statemachine/qsignaltransition.h index b485785..02b1de9 100644 --- a/src/corelib/statemachine/qsignaltransition.h +++ b/src/corelib/statemachine/qsignaltransition.h @@ -50,6 +50,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QSignalTransitionPrivate; class Q_CORE_EXPORT QSignalTransition : public QAbstractTransition { @@ -82,6 +84,8 @@ private: Q_DECLARE_PRIVATE(QSignalTransition) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qstate.cpp b/src/corelib/statemachine/qstate.cpp index ebb0b47..5dd56c0 100644 --- a/src/corelib/statemachine/qstate.cpp +++ b/src/corelib/statemachine/qstate.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qstate.h" + +#ifndef QT_NO_STATEMACHINE + #include "qstate_p.h" #include "qhistorystate.h" #include "qhistorystate_p.h" @@ -482,3 +485,5 @@ bool QState::event(QEvent *e) */ QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/corelib/statemachine/qstate.h b/src/corelib/statemachine/qstate.h index 6729c69..c98bb64 100644 --- a/src/corelib/statemachine/qstate.h +++ b/src/corelib/statemachine/qstate.h @@ -50,6 +50,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QAbstractTransition; class QSignalTransition; @@ -106,6 +108,8 @@ private: Q_DECLARE_PRIVATE(QState) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qstatemachine.cpp b/src/corelib/statemachine/qstatemachine.cpp index d5f6b76..64b33ac 100644 --- a/src/corelib/statemachine/qstatemachine.cpp +++ b/src/corelib/statemachine/qstatemachine.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qstatemachine.h" + +#ifndef QT_NO_STATEMACHINE + #include "qstate.h" #include "qstate_p.h" #include "qstatemachine_p.h" @@ -2207,3 +2210,5 @@ QWrappedEvent::~QWrappedEvent() QT_END_NAMESPACE #include "moc_qstatemachine.cpp" + +#endif //QT_NO_STATEMACHINE diff --git a/src/corelib/statemachine/qstatemachine.h b/src/corelib/statemachine/qstatemachine.h index 2a98a9a..0b3c728 100644 --- a/src/corelib/statemachine/qstatemachine.h +++ b/src/corelib/statemachine/qstatemachine.h @@ -54,6 +54,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QEvent; class QAbstractState; class QState; @@ -159,6 +161,8 @@ private: #endif }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/corelib/statemachine/qwrappedevent.h b/src/corelib/statemachine/qwrappedevent.h index b01c608..cb4261b 100644 --- a/src/corelib/statemachine/qwrappedevent.h +++ b/src/corelib/statemachine/qwrappedevent.h @@ -50,6 +50,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Core) +#ifndef QT_NO_STATEMACHINE + class QObject; class Q_CORE_EXPORT QWrappedEvent : public QEvent @@ -69,6 +71,8 @@ private: Q_DISABLE_COPY(QWrappedEvent) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp index a9424db..f2a3498 100644 --- a/src/gui/kernel/qapplication.cpp +++ b/src/gui/kernel/qapplication.cpp @@ -838,9 +838,11 @@ void QApplicationPrivate::initialize() // trigger registering of QVariant's GUI types extern int qRegisterGuiVariant(); qRegisterGuiVariant(); +#ifndef QT_NO_STATEMACHINE // trigger registering of QStateMachine's GUI types extern int qRegisterGuiStateMachine(); qRegisterGuiStateMachine(); +#endif is_app_running = true; // no longer starting up @@ -1062,9 +1064,11 @@ QApplication::~QApplication() QApplicationPrivate::fade_tooltip = false; QApplicationPrivate::widgetCount = false; +#ifndef QT_NO_STATEMACHINE // trigger unregistering of QStateMachine's GUI types extern int qUnregisterGuiStateMachine(); qUnregisterGuiStateMachine(); +#endif // trigger unregistering of QVariant's GUI types extern int qUnregisterGuiVariant(); qUnregisterGuiVariant(); diff --git a/src/gui/statemachine/qbasickeyeventtransition.cpp b/src/gui/statemachine/qbasickeyeventtransition.cpp index f7f1eb6..61362b2 100644 --- a/src/gui/statemachine/qbasickeyeventtransition.cpp +++ b/src/gui/statemachine/qbasickeyeventtransition.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qbasickeyeventtransition_p.h" + +#ifndef QT_NO_STATEMACHINE + #include #include #include @@ -201,3 +204,5 @@ void QBasicKeyEventTransition::onTransition(QEvent *) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/gui/statemachine/qbasickeyeventtransition_p.h b/src/gui/statemachine/qbasickeyeventtransition_p.h index 39fa6ad..aef1f99 100644 --- a/src/gui/statemachine/qbasickeyeventtransition_p.h +++ b/src/gui/statemachine/qbasickeyeventtransition_p.h @@ -54,6 +54,9 @@ // #include + +#ifndef QT_NO_STATEMACHINE + #include QT_BEGIN_NAMESPACE @@ -90,4 +93,6 @@ private: QT_END_NAMESPACE +#endif //QT_NO_STATEMACHINE + #endif diff --git a/src/gui/statemachine/qbasicmouseeventtransition.cpp b/src/gui/statemachine/qbasicmouseeventtransition.cpp index 20dd792..0304e28 100644 --- a/src/gui/statemachine/qbasicmouseeventtransition.cpp +++ b/src/gui/statemachine/qbasicmouseeventtransition.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qbasicmouseeventtransition_p.h" + +#ifndef QT_NO_STATEMACHINE + #include #include #include @@ -206,3 +209,5 @@ void QBasicMouseEventTransition::onTransition(QEvent *) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/gui/statemachine/qbasicmouseeventtransition_p.h b/src/gui/statemachine/qbasicmouseeventtransition_p.h index 3161844..ed0022a 100644 --- a/src/gui/statemachine/qbasicmouseeventtransition_p.h +++ b/src/gui/statemachine/qbasicmouseeventtransition_p.h @@ -54,6 +54,9 @@ // #include + +#ifndef QT_NO_STATEMACHINE + #include QT_BEGIN_NAMESPACE @@ -93,4 +96,6 @@ private: QT_END_NAMESPACE +#endif //QT_NO_STATEMACHINE + #endif diff --git a/src/gui/statemachine/qguistatemachine.cpp b/src/gui/statemachine/qguistatemachine.cpp index 612e43e..69155a9 100644 --- a/src/gui/statemachine/qguistatemachine.cpp +++ b/src/gui/statemachine/qguistatemachine.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include + +#ifndef QT_NO_STATEMACHINE + #include #include #include @@ -557,3 +560,5 @@ int qUnregisterGuiStateMachine() Q_DESTRUCTOR_FUNCTION(qUnregisterGuiStateMachine) QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/gui/statemachine/qkeyeventtransition.cpp b/src/gui/statemachine/qkeyeventtransition.cpp index f803711..fee9f81 100644 --- a/src/gui/statemachine/qkeyeventtransition.cpp +++ b/src/gui/statemachine/qkeyeventtransition.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qkeyeventtransition.h" + +#ifndef QT_NO_STATEMACHINE + #include "qbasickeyeventtransition_p.h" #include #include @@ -184,3 +187,5 @@ void QKeyEventTransition::onTransition(QEvent *event) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/gui/statemachine/qkeyeventtransition.h b/src/gui/statemachine/qkeyeventtransition.h index d9c7760..c9e06f5 100644 --- a/src/gui/statemachine/qkeyeventtransition.h +++ b/src/gui/statemachine/qkeyeventtransition.h @@ -50,6 +50,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) +#ifndef QT_NO_STATEMACHINE + class QKeyEventTransitionPrivate; class Q_GUI_EXPORT QKeyEventTransition : public QEventTransition { @@ -80,6 +82,8 @@ private: Q_DECLARE_PRIVATE(QKeyEventTransition) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER diff --git a/src/gui/statemachine/qmouseeventtransition.cpp b/src/gui/statemachine/qmouseeventtransition.cpp index e4e18eb..6ae3d36 100644 --- a/src/gui/statemachine/qmouseeventtransition.cpp +++ b/src/gui/statemachine/qmouseeventtransition.cpp @@ -40,6 +40,9 @@ ****************************************************************************/ #include "qmouseeventtransition.h" + +#ifndef QT_NO_STATEMACHINE + #include "qbasicmouseeventtransition_p.h" #include #include @@ -214,3 +217,5 @@ void QMouseEventTransition::onTransition(QEvent *event) } QT_END_NAMESPACE + +#endif //QT_NO_STATEMACHINE diff --git a/src/gui/statemachine/qmouseeventtransition.h b/src/gui/statemachine/qmouseeventtransition.h index 9c7af5b..557b2c3 100644 --- a/src/gui/statemachine/qmouseeventtransition.h +++ b/src/gui/statemachine/qmouseeventtransition.h @@ -50,6 +50,8 @@ QT_BEGIN_NAMESPACE QT_MODULE(Gui) +#ifndef QT_NO_STATEMACHINE + class QMouseEventTransitionPrivate; class QPainterPath; class Q_GUI_EXPORT QMouseEventTransition : public QEventTransition @@ -85,6 +87,8 @@ private: Q_DECLARE_PRIVATE(QMouseEventTransition) }; +#endif //QT_NO_STATEMACHINE + QT_END_NAMESPACE QT_END_HEADER -- cgit v0.12 From b70c535fb096652def0c4f6df6f9cd2827fa9c97 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 4 Jun 2009 17:19:46 +0200 Subject: regeneration of qfeatures.h --- src/corelib/global/qfeatures.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/corelib/global/qfeatures.h b/src/corelib/global/qfeatures.h index f11c9df..9f7c7ba 100644 --- a/src/corelib/global/qfeatures.h +++ b/src/corelib/global/qfeatures.h @@ -311,6 +311,11 @@ #define QT_NO_ACCESSIBILITY #endif +// Animation +#if !defined(QT_NO_ANIMATION) && (defined(QT_NO_PROPERTIES)) +#define QT_NO_ANIMATION +#endif + // QButtonGroup #if !defined(QT_NO_BUTTONGROUP) && (defined(QT_NO_GROUPBOX)) #define QT_NO_BUTTONGROUP -- cgit v0.12 From f7338759ef86deba18b27ee72b3afcf40f3a5aaf Mon Sep 17 00:00:00 2001 From: Anders Bakken Date: Thu, 4 Jun 2009 09:07:38 -0700 Subject: Make sure to retain alpha information in copy We need to set alpha to the right value when copying pixmaps. Reviewed-by: Donald --- src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp b/src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp index dba1b51..18754f5 100644 --- a/src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp +++ b/src/plugins/gfxdrivers/directfb/qdirectfbpixmap.cpp @@ -202,11 +202,12 @@ void QDirectFBPixmapData::copy(const QPixmapData *data, const QRect &rect) } IDirectFBSurface *src = static_cast(data)->directFBSurface(); - const bool hasAlpha = data->hasAlphaChannel(); - format = (hasAlpha + alpha = data->hasAlphaChannel(); + format = (alpha ? QDirectFBScreen::instance()->alphaPixmapFormat() : QDirectFBScreen::instance()->pixelFormat()); + dfbSurface = screen->createDFBSurface(rect.size(), format, QDirectFBScreen::TrackSurface); if (!dfbSurface) { @@ -215,7 +216,7 @@ void QDirectFBPixmapData::copy(const QPixmapData *data, const QRect &rect) return; } - if (hasAlpha) { + if (alpha) { dfbSurface->Clear(dfbSurface, 0, 0, 0, 0); dfbSurface->SetBlittingFlags(dfbSurface, DSBLIT_BLEND_ALPHACHANNEL); } else { -- cgit v0.12 From 89e2640fa285e9e8d62634a2c30b8e1496ece70a Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 5 Jun 2009 09:05:43 +1000 Subject: Compile fix for WinCE. --- src/declarative/qml/qmlprivate.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/qml/qmlprivate.h b/src/declarative/qml/qmlprivate.h index 3f41fb7..25e60e0 100644 --- a/src/declarative/qml/qmlprivate.h +++ b/src/declarative/qml/qmlprivate.h @@ -43,7 +43,7 @@ #define QMLPRIVATE_H #include -#ifndef Q_OS_WIN32 +#ifndef Q_OS_WIN #include #endif #include -- cgit v0.12 From 58c5df4109acf44982c3a2a7b2318da52606232d Mon Sep 17 00:00:00 2001 From: David Faure Date: Fri, 5 Jun 2009 09:55:21 +1000 Subject: Fix compilation with gcc-4.3.3 (due to std::system) Merge-request: 594 Reviewed-by: Rohan McGovern --- src/opengl/util/generator.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/opengl/util/generator.cpp b/src/opengl/util/generator.cpp index dac5a2d..430ced1 100644 --- a/src/opengl/util/generator.cpp +++ b/src/opengl/util/generator.cpp @@ -48,6 +48,7 @@ #include #include +#include QT_BEGIN_NAMESPACE -- cgit v0.12 From ef0d1c839aed75201da10f8db7e515d9fb55bb16 Mon Sep 17 00:00:00 2001 From: David Faure Date: Fri, 5 Jun 2009 09:55:22 +1000 Subject: All of Qt's own code compiles with -pedantic now (but pcre and webkit don't seem fixable easily) Merge-request: 594 Reviewed-by: Rohan McGovern --- src/3rdparty/webkit/JavaScriptCore/wtf/unicode/Unicode.h | 2 +- src/dbus/qdbus_symbols_p.h | 2 +- src/dbus/qdbusthreaddebug_p.h | 2 +- src/gui/accessible/qaccessible.cpp | 2 +- src/gui/image/qpixmapdatafactory.cpp | 2 +- src/gui/kernel/qaction.cpp | 2 +- src/gui/kernel/qapplication.cpp | 2 +- src/gui/painting/qdrawhelper.cpp | 8 ++++---- src/gui/painting/qpainter_p.h | 4 ++-- src/gui/painting/qpdf_p.h | 2 +- src/gui/painting/qvectorpath_p.h | 2 +- src/gui/text/qfontdatabase_x11.cpp | 2 +- src/gui/widgets/qplaintextedit.cpp | 4 ++-- src/gui/widgets/qvalidator.cpp | 2 +- src/network/kernel/qnetworkproxy.cpp | 2 +- src/opengl/gl2paintengineex/qglengineshadermanager_p.h | 4 ++-- src/opengl/qgl.cpp | 8 ++++---- src/opengl/qgl_x11.cpp | 2 +- src/opengl/qglshaderprogram.h | 4 ++-- src/opengl/util/fragmentprograms_p.h | 8 ++++---- src/qt3support/widgets/q3action.cpp | 2 +- src/script/qscriptsyntaxchecker_p.h | 2 +- src/script/qscriptvalueimplfwd_p.h | 2 +- src/testlib/qtestcase.cpp | 6 +++--- src/testlib/qtestresult.cpp | 2 +- 25 files changed, 40 insertions(+), 40 deletions(-) diff --git a/src/3rdparty/webkit/JavaScriptCore/wtf/unicode/Unicode.h b/src/3rdparty/webkit/JavaScriptCore/wtf/unicode/Unicode.h index e6e8f23..5b849e4 100644 --- a/src/3rdparty/webkit/JavaScriptCore/wtf/unicode/Unicode.h +++ b/src/3rdparty/webkit/JavaScriptCore/wtf/unicode/Unicode.h @@ -32,6 +32,6 @@ #error "Unknown Unicode implementation" #endif -COMPILE_ASSERT(sizeof(UChar) == 2, UCharIsTwoBytes); +COMPILE_ASSERT(sizeof(UChar) == 2, UCharIsTwoBytes) #endif // WTF_UNICODE_H diff --git a/src/dbus/qdbus_symbols_p.h b/src/dbus/qdbus_symbols_p.h index 764d368..db5e1bb 100644 --- a/src/dbus/qdbus_symbols_p.h +++ b/src/dbus/qdbus_symbols_p.h @@ -353,7 +353,7 @@ DEFINEFUNC(dbus_bool_t , dbus_signature_validate_single, (const char * DBusError *error), (signature, error), return) DEFINEFUNC(dbus_bool_t , dbus_type_is_basic, (int typecode), - (typecode), return); + (typecode), return) DEFINEFUNC(dbus_bool_t , dbus_type_is_fixed, (int typecode), (typecode), return) diff --git a/src/dbus/qdbusthreaddebug_p.h b/src/dbus/qdbusthreaddebug_p.h index 20d819f..f2ac598 100644 --- a/src/dbus/qdbusthreaddebug_p.h +++ b/src/dbus/qdbusthreaddebug_p.h @@ -100,7 +100,7 @@ enum ThreadAction { RemoveWatchAction = 61, ToggleWatchAction = 62, SocketReadAction = 63, - SocketWriteAction = 64, + SocketWriteAction = 64 }; struct QDBusLockerBase diff --git a/src/gui/accessible/qaccessible.cpp b/src/gui/accessible/qaccessible.cpp index b0878ab..bd8a9ec 100644 --- a/src/gui/accessible/qaccessible.cpp +++ b/src/gui/accessible/qaccessible.cpp @@ -394,7 +394,7 @@ Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader, (QAccessibleFactoryInterface_iid, QLatin1String("/accessible"))) #endif -Q_GLOBAL_STATIC(QList, qAccessibleFactories); +Q_GLOBAL_STATIC(QList, qAccessibleFactories) QAccessible::UpdateHandler QAccessible::updateHandler = 0; QAccessible::RootObjectHandler QAccessible::rootObjectHandler = 0; diff --git a/src/gui/image/qpixmapdatafactory.cpp b/src/gui/image/qpixmapdatafactory.cpp index 699489d..bba7378 100644 --- a/src/gui/image/qpixmapdatafactory.cpp +++ b/src/gui/image/qpixmapdatafactory.cpp @@ -84,7 +84,7 @@ QPixmapData* QSimplePixmapDataFactory::create(QPixmapData::PixelType type) #endif } -Q_GLOBAL_STATIC(QSimplePixmapDataFactory, factory); +Q_GLOBAL_STATIC(QSimplePixmapDataFactory, factory) #endif // !defined(Q_WS_QWS) diff --git a/src/gui/kernel/qaction.cpp b/src/gui/kernel/qaction.cpp index b2afbd0..051b6a6 100644 --- a/src/gui/kernel/qaction.cpp +++ b/src/gui/kernel/qaction.cpp @@ -76,7 +76,7 @@ static QString qt_strippedText(QString s) s.remove(i-1,1); } return s.trimmed(); -}; +} QActionPrivate::QActionPrivate() : group(0), enabled(1), forceDisabled(0), diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp index f2a3498..4923d23 100644 --- a/src/gui/kernel/qapplication.cpp +++ b/src/gui/kernel/qapplication.cpp @@ -405,7 +405,7 @@ QPalette *QApplicationPrivate::set_pal = 0; // default palette set by pro QGraphicsSystem *QApplicationPrivate::graphics_system = 0; // default graphics system QString QApplicationPrivate::graphics_system_name; // graphics system id - for delayed initialization -Q_GLOBAL_STATIC(QMutex, applicationFontMutex); +Q_GLOBAL_STATIC(QMutex, applicationFontMutex) QFont *QApplicationPrivate::app_font = 0; // default application font QFont *QApplicationPrivate::sys_font = 0; // default system font QFont *QApplicationPrivate::set_font = 0; // default font set by programmer diff --git a/src/gui/painting/qdrawhelper.cpp b/src/gui/painting/qdrawhelper.cpp index bbe1a76..0d1da54 100644 --- a/src/gui/painting/qdrawhelper.cpp +++ b/src/gui/painting/qdrawhelper.cpp @@ -7225,13 +7225,13 @@ inline void qt_rectfill_template(QRasterBuffer *rasterBuffer, QT_RECTFILL(quint32) QT_RECTFILL(quint16) QT_RECTFILL(qargb8565) -QT_RECTFILL(qrgb666); -QT_RECTFILL(qargb6666); +QT_RECTFILL(qrgb666) +QT_RECTFILL(qargb6666) QT_RECTFILL(qrgb555) QT_RECTFILL(qargb8555) QT_RECTFILL(qrgb888) -QT_RECTFILL(qrgb444); -QT_RECTFILL(qargb4444); +QT_RECTFILL(qrgb444) +QT_RECTFILL(qargb4444) #undef QT_RECTFILL diff --git a/src/gui/painting/qpainter_p.h b/src/gui/painting/qpainter_p.h index 258b25a..6c8821a 100644 --- a/src/gui/painting/qpainter_p.h +++ b/src/gui/painting/qpainter_p.h @@ -92,8 +92,8 @@ inline Qt::PenJoinStyle qpen_joinStyle(const QPen &p) { return data_ptr(p)->join // QBrush inline functions... inline QBrush::DataPtr &data_ptr(const QBrush &p) { return const_cast(p).data_ptr(); } inline bool qbrush_fast_equals(const QBrush &a, const QBrush &b) { return data_ptr(a) == data_ptr(b); } -inline Qt::BrushStyle qbrush_style(const QBrush &b) { return data_ptr(b)->style; }; -inline const QColor &qbrush_color(const QBrush &b) { return data_ptr(b)->color; }; +inline Qt::BrushStyle qbrush_style(const QBrush &b) { return data_ptr(b)->style; } +inline const QColor &qbrush_color(const QBrush &b) { return data_ptr(b)->color; } inline bool qbrush_has_transform(const QBrush &b) { return data_ptr(b)->transform.type() > QTransform::TxNone; } class QPainterClipInfo diff --git a/src/gui/painting/qpdf_p.h b/src/gui/painting/qpdf_p.h index 1d45ca1..7d92c0c 100644 --- a/src/gui/painting/qpdf_p.h +++ b/src/gui/painting/qpdf_p.h @@ -158,7 +158,7 @@ namespace QPdf { QByteArray stripSpecialCharacters(const QByteArray &string); -}; +} class QPdfPage : public QPdf::ByteStream diff --git a/src/gui/painting/qvectorpath_p.h b/src/gui/painting/qvectorpath_p.h index 2713cda..2602a3d 100644 --- a/src/gui/painting/qvectorpath_p.h +++ b/src/gui/painting/qvectorpath_p.h @@ -94,7 +94,7 @@ public: // Shape rendering specifiers... OddEvenFill = 0x1000, WindingFill = 0x2000, - ImplicitClose = 0x4000, + ImplicitClose = 0x4000 }; // ### Falcon: introduca a struct XY for points so lars is not so confused... diff --git a/src/gui/text/qfontdatabase_x11.cpp b/src/gui/text/qfontdatabase_x11.cpp index 605a7dd..8f67cec 100644 --- a/src/gui/text/qfontdatabase_x11.cpp +++ b/src/gui/text/qfontdatabase_x11.cpp @@ -392,7 +392,7 @@ int qt_mib_for_xlfd_encoding(const char *encoding) int id = qt_xlfd_encoding_id(encoding); if (id != -1) return xlfd_encoding[id].mib; return 0; -}; +} int qt_encoding_id_for_mib(int mib) { diff --git a/src/gui/widgets/qplaintextedit.cpp b/src/gui/widgets/qplaintextedit.cpp index f317742..af11aa7 100644 --- a/src/gui/widgets/qplaintextedit.cpp +++ b/src/gui/widgets/qplaintextedit.cpp @@ -444,7 +444,7 @@ QPlainTextEditControl::QPlainTextEditControl(QPlainTextEdit *parent) void QPlainTextEditPrivate::_q_cursorPositionChanged() { pageUpDownLastCursorYIsValid = false; -}; +} void QPlainTextEditPrivate::_q_verticalScrollbarActionTriggered(int action) { if (action == QAbstractSlider::SliderPageStepAdd) { @@ -1756,7 +1756,7 @@ void QPlainTextEdit::paintEvent(QPaintEvent *e) QTextBlock block = firstVisibleBlock(); qreal maximumWidth = document()->documentLayout()->documentSize().width(); - + // keep right margin clean from full-width selection int maxX = offset.x() + qMax((qreal)viewportRect.width(), maximumWidth) - document()->documentMargin(); diff --git a/src/gui/widgets/qvalidator.cpp b/src/gui/widgets/qvalidator.cpp index 3aca13d..0a7c43c 100644 --- a/src/gui/widgets/qvalidator.cpp +++ b/src/gui/widgets/qvalidator.cpp @@ -370,7 +370,7 @@ static int numDigits(qlonglong n) if (n == 0) return 1; return (int)log10(double(n)) + 1; -}; +} static qlonglong pow10(int exp) { diff --git a/src/network/kernel/qnetworkproxy.cpp b/src/network/kernel/qnetworkproxy.cpp index fd3a85a..a5fd60e 100644 --- a/src/network/kernel/qnetworkproxy.cpp +++ b/src/network/kernel/qnetworkproxy.cpp @@ -324,7 +324,7 @@ QList QGlobalNetworkProxy::proxyForQuery(const QNetworkProxyQuery return result; } -Q_GLOBAL_STATIC(QGlobalNetworkProxy, globalNetworkProxy); +Q_GLOBAL_STATIC(QGlobalNetworkProxy, globalNetworkProxy) namespace { template struct StaticAssertTest; diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h index 9bc81ef..afbc918 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadermanager_p.h @@ -257,7 +257,7 @@ static const GLuint QT_TEXTURE_COORDS_ATTR = 1; class QGLEngineShaderManager : public QObject { - Q_OBJECT; + Q_OBJECT public: QGLEngineShaderManager(QGLContext* context); ~QGLEngineShaderManager(); @@ -352,7 +352,7 @@ public: */ #if defined (QT_DEBUG) - Q_ENUMS(ShaderName); + Q_ENUMS(ShaderName) #endif diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 60039eb..2e72851 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -1456,7 +1456,7 @@ struct DDSFormat { #define GL_GENERATE_MIPMAP_HINT_SGIS 0x8192 #endif -Q_GLOBAL_STATIC(QGLShareRegister, _qgl_share_reg); +Q_GLOBAL_STATIC(QGLShareRegister, _qgl_share_reg) Q_OPENGL_EXPORT QGLShareRegister* qgl_share_reg() { return _qgl_share_reg(); @@ -2609,7 +2609,7 @@ const QGLContext* QGLContext::currentContext() */ /*! \fn int QGLContext::choosePixelFormat(void* dummyPfd, HDC pdc) - + \bold{Win32 only:} This virtual function chooses a pixel format that matches the OpenGL \link setFormat() format\endlink. Reimplement this function in a subclass if you need a custom @@ -2623,7 +2623,7 @@ const QGLContext* QGLContext::currentContext() */ /*! \fn void *QGLContext::chooseVisual() - + \bold{X11 only:} This virtual function tries to find a visual that matches the format, reducing the demands if the original request cannot be met. @@ -4354,7 +4354,7 @@ void QGLWidgetPrivate::initContext(QGLContext *context, const QGLWidget* shareWi } #if defined(Q_WS_X11) || defined(Q_WS_MAC) || defined(Q_WS_QWS) -Q_GLOBAL_STATIC(QString, qt_gl_lib_name); +Q_GLOBAL_STATIC(QString, qt_gl_lib_name) Q_OPENGL_EXPORT void qt_set_gl_library_name(const QString& name) { diff --git a/src/opengl/qgl_x11.cpp b/src/opengl/qgl_x11.cpp index 28a50bd..da61634 100644 --- a/src/opengl/qgl_x11.cpp +++ b/src/opengl/qgl_x11.cpp @@ -129,7 +129,7 @@ struct QGLCMapCleanupHandler { CMapEntryHash *cmap_hash; GLCMapHash *qglcmap_hash; }; -Q_GLOBAL_STATIC(QGLCMapCleanupHandler, cmap_handler); +Q_GLOBAL_STATIC(QGLCMapCleanupHandler, cmap_handler) static void cleanup_cmaps() { diff --git a/src/opengl/qglshaderprogram.h b/src/opengl/qglshaderprogram.h index ab30c32..06bff42 100644 --- a/src/opengl/qglshaderprogram.h +++ b/src/opengl/qglshaderprogram.h @@ -103,7 +103,7 @@ private: friend class QGLShaderProgram; - Q_DISABLE_COPY(QGLShader); + Q_DISABLE_COPY(QGLShader) }; class QGLShaderProgramPrivate; @@ -279,7 +279,7 @@ public: private: QGLShaderProgramPrivate *d; - Q_DISABLE_COPY(QGLShaderProgram); + Q_DISABLE_COPY(QGLShaderProgram) bool init(); }; diff --git a/src/opengl/util/fragmentprograms_p.h b/src/opengl/util/fragmentprograms_p.h index ecf0bf8..d4b54d4 100644 --- a/src/opengl/util/fragmentprograms_p.h +++ b/src/opengl/util/fragmentprograms_p.h @@ -71,7 +71,7 @@ enum FragmentVariable { VAR_FMP2_M_RADIUS2, VAR_FMP, VAR_INV_MATRIX_M0, - VAR_ANGLE, + VAR_ANGLE }; enum FragmentBrushType { @@ -80,7 +80,7 @@ enum FragmentBrushType { FRAGMENT_PROGRAM_BRUSH_CONICAL, FRAGMENT_PROGRAM_BRUSH_LINEAR, FRAGMENT_PROGRAM_BRUSH_TEXTURE, - FRAGMENT_PROGRAM_BRUSH_PATTERN, + FRAGMENT_PROGRAM_BRUSH_PATTERN }; enum FragmentCompositionModeType { @@ -109,12 +109,12 @@ enum FragmentCompositionModeType { COMPOSITION_MODES_DIFFERENCE_NOMASK, COMPOSITION_MODES_EXCLUSION_NOMASK, COMPOSITION_MODE_BLEND_MODE_MASK, - COMPOSITION_MODE_BLEND_MODE_NOMASK, + COMPOSITION_MODE_BLEND_MODE_NOMASK }; enum FragmentMaskType { FRAGMENT_PROGRAM_MASK_TRAPEZOID_AA, - FRAGMENT_PROGRAM_MASK_ELLIPSE_AA, + FRAGMENT_PROGRAM_MASK_ELLIPSE_AA }; static const unsigned int num_fragment_variables = 19; diff --git a/src/qt3support/widgets/q3action.cpp b/src/qt3support/widgets/q3action.cpp index 311212a..caca47b 100644 --- a/src/qt3support/widgets/q3action.cpp +++ b/src/qt3support/widgets/q3action.cpp @@ -415,7 +415,7 @@ static QString qt_stripMenuText(QString s) s.remove(QLatin1String("...")); s.remove(QLatin1Char('&')); return s.trimmed(); -}; +} /*! Constructs an action called \a name with parent \a parent. diff --git a/src/script/qscriptsyntaxchecker_p.h b/src/script/qscriptsyntaxchecker_p.h index 0c02d24..18f0611 100644 --- a/src/script/qscriptsyntaxchecker_p.h +++ b/src/script/qscriptsyntaxchecker_p.h @@ -71,7 +71,7 @@ public: enum State { Error, Intermediate, - Valid, + Valid }; struct Result { diff --git a/src/script/qscriptvalueimplfwd_p.h b/src/script/qscriptvalueimplfwd_p.h index 059842e..aa0c86f 100644 --- a/src/script/qscriptvalueimplfwd_p.h +++ b/src/script/qscriptvalueimplfwd_p.h @@ -77,7 +77,7 @@ class QScriptEnginePrivate; namespace QScript { class Member; -}; +} class QScriptValueImpl { diff --git a/src/testlib/qtestcase.cpp b/src/testlib/qtestcase.cpp index 041f2db..af0df3e 100644 --- a/src/testlib/qtestcase.cpp +++ b/src/testlib/qtestcase.cpp @@ -1469,7 +1469,7 @@ int QTest::qExec(QObject *testObject, int argc, char **argv) #ifdef Q_OS_WIN chartLocation += QLatin1String("/../tools/qtestlib/chart/release/chart.exe"); #else - chartLocation += QLatin1String("/../tools/qtestlib/chart/chart"); + chartLocation += QLatin1String("/../tools/qtestlib/chart/chart"); #endif if (QFile::exists(chartLocation)) { QProcess p; @@ -1801,8 +1801,8 @@ COMPARE_IMPL2(quint64, %llu) #endif COMPARE_IMPL2(bool, %d) COMPARE_IMPL2(char, %c) -COMPARE_IMPL2(float, %g); -COMPARE_IMPL2(double, %lg); +COMPARE_IMPL2(float, %g) +COMPARE_IMPL2(double, %lg) /*! \internal */ diff --git a/src/testlib/qtestresult.cpp b/src/testlib/qtestresult.cpp index 39759b5..0f21378 100644 --- a/src/testlib/qtestresult.cpp +++ b/src/testlib/qtestresult.cpp @@ -68,7 +68,7 @@ namespace QTest static const char *expectFailComment = 0; static int expectFailMode = 0; -}; +} void QTestResult::reset() { -- cgit v0.12 From bac90c22ded20525e43d7d9002f8fb03e6e41c93 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 5 Jun 2009 09:57:28 +1000 Subject: Compile fix for OpenGL. --- src/declarative/opengl/glbasicshaders.cpp | 38 +++++++++++++++---------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/declarative/opengl/glbasicshaders.cpp b/src/declarative/opengl/glbasicshaders.cpp index f546c0b..7c1d730 100644 --- a/src/declarative/opengl/glbasicshaders.cpp +++ b/src/declarative/opengl/glbasicshaders.cpp @@ -50,7 +50,7 @@ SingleTextureVertexOpacityShader::SingleTextureVertexOpacityShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ attribute highp vec4 myVertex;\ attribute lowp float myOpacity;\ attribute mediump vec4 myUV;\ @@ -65,7 +65,7 @@ SingleTextureVertexOpacityShader::SingleTextureVertexOpacityShader() }" ); - frag.setSourceCode("\ + frag.compile("\ uniform sampler2D sampler2d;\ varying mediump vec2 myTexCoord;\ varying lowp float myFragOpacity;\ @@ -105,7 +105,7 @@ BlurTextureShader::BlurTextureShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ attribute highp vec4 myVertex;\ attribute mediump vec4 myUV;\ uniform mediump mat4 myPMVMatrix;\ @@ -118,7 +118,7 @@ BlurTextureShader::BlurTextureShader() ); #if 0 - frag.setSourceCode("\ + frag.compile("\ uniform sampler2D sampler2d;\ uniform bool horizontal; \ uniform mediump float blurStep; \ @@ -140,7 +140,7 @@ BlurTextureShader::BlurTextureShader() }" ); #else - frag.setSourceCode("\ + frag.compile("\ uniform sampler2D sampler2d;\ uniform bool horizontal; \ uniform mediump float blurStep; \ @@ -223,7 +223,7 @@ DualTextureBlendShader::DualTextureBlendShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ attribute highp vec4 myVertex;\ attribute mediump vec4 myUV;\ attribute mediump vec4 myBlendUV;\ @@ -238,7 +238,7 @@ DualTextureBlendShader::DualTextureBlendShader() }" ); - frag.setSourceCode("\ + frag.compile("\ uniform sampler2D sampler2d;\ uniform sampler2D sampler2dBlend;\ uniform lowp float myOpacity;\ @@ -295,7 +295,7 @@ DualTextureAddShader::DualTextureAddShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ attribute highp vec4 myVertex;\ attribute mediump vec4 myUV;\ attribute mediump vec4 myAddUV;\ @@ -310,7 +310,7 @@ DualTextureAddShader::DualTextureAddShader() }" ); - frag.setSourceCode("\ + frag.compile("\ uniform sampler2D sampler2d;\ uniform sampler2D sampler2dAdd;\ uniform lowp float myOpacity;\ @@ -362,7 +362,7 @@ SingleTextureShader::SingleTextureShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ attribute highp vec4 myVertex;\ attribute mediump vec4 myUV;\ uniform mediump mat4 myPMVMatrix;\ @@ -374,7 +374,7 @@ SingleTextureShader::SingleTextureShader() }" ); - frag.setSourceCode("\ + frag.compile("\ uniform sampler2D sampler2d;\ varying mediump vec2 myTexCoord;\ void main(void)\ @@ -411,7 +411,7 @@ ConstantColorShader::ConstantColorShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ uniform mediump mat4 myPMVMatrix;\ attribute highp vec4 myVertex;\ void main(void)\ @@ -420,7 +420,7 @@ ConstantColorShader::ConstantColorShader() }" ); - frag.setSourceCode("\ + frag.compile("\ uniform lowp vec4 myColor;\ void main(void)\ {\ @@ -458,7 +458,7 @@ ColorShader::ColorShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ uniform mediump mat4 myPMVMatrix;\ attribute highp vec4 myVertex;\ attribute lowp vec4 myColors;\ @@ -470,7 +470,7 @@ ColorShader::ColorShader() }" ); - frag.setSourceCode("\ + frag.compile("\ varying lowp vec4 myColor;\ void main(void)\ {\ @@ -596,7 +596,7 @@ SingleTextureOpacityShader::SingleTextureOpacityShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ attribute highp vec4 myVertex;\ attribute mediump vec4 myUV;\ uniform mediump mat4 myPMVMatrix;\ @@ -608,7 +608,7 @@ SingleTextureOpacityShader::SingleTextureOpacityShader() }" ); - frag.setSourceCode("\ + frag.compile("\ uniform sampler2D sampler2d;\ uniform lowp float myOpacity;\ varying mediump vec2 myTexCoord;\ @@ -653,7 +653,7 @@ SingleTextureShadowShader::SingleTextureShadowShader() QGLShader vert(QGLShader::VertexShader); QGLShader frag(QGLShader::FragmentShader); - vert.setSourceCode("\ + vert.compile("\ attribute highp vec4 myVertex;\ attribute mediump vec4 myUV;\ uniform mediump mat4 myPMVMatrix;\ @@ -665,7 +665,7 @@ SingleTextureShadowShader::SingleTextureShadowShader() }" ); - frag.setSourceCode("\ + frag.compile("\ uniform sampler2D sampler2d;\ uniform lowp float myOpacity;\ varying mediump vec2 myTexCoord;\ -- cgit v0.12 From beeaf4d2e8097bb8f61b02508bb4a75407373440 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 5 Jun 2009 11:44:37 +1000 Subject: Another compile fix for WinCE. --- src/declarative/fx/qfxgridview.cpp | 2 +- src/declarative/fx/qfxlistview.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/declarative/fx/qfxgridview.cpp b/src/declarative/fx/qfxgridview.cpp index dde8fcf..801d32a 100644 --- a/src/declarative/fx/qfxgridview.cpp +++ b/src/declarative/fx/qfxgridview.cpp @@ -283,7 +283,7 @@ public: qDebug() << "index" << visibleIndex << i << listItem->index; for (int j = 0; j < visibleItems.count(); j++) qDebug() << " index" << j << "item index" << visibleItems.at(j)->index; - abort(); + qFatal(); } } } diff --git a/src/declarative/fx/qfxlistview.cpp b/src/declarative/fx/qfxlistview.cpp index 432c6ac..4c76267 100644 --- a/src/declarative/fx/qfxlistview.cpp +++ b/src/declarative/fx/qfxlistview.cpp @@ -325,7 +325,7 @@ public: ++skip; } else if (listItem->index != visibleIndex + i - skip) { qDebug() << "index" << visibleIndex << i << listItem->index; - abort(); + qFatal(); } } } -- cgit v0.12 From 7475ea3c1c883375843d6935d18edba4d3aa15e2 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 5 Jun 2009 11:56:11 +1000 Subject: Compile fix. --- src/declarative/fx/qfxgridview.cpp | 3 +-- src/declarative/fx/qfxlistview.cpp | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/declarative/fx/qfxgridview.cpp b/src/declarative/fx/qfxgridview.cpp index 801d32a..0ca9393 100644 --- a/src/declarative/fx/qfxgridview.cpp +++ b/src/declarative/fx/qfxgridview.cpp @@ -280,10 +280,9 @@ public: if (listItem->index == -1) { ++skip; } else if (listItem->index != visibleIndex + i - skip) { - qDebug() << "index" << visibleIndex << i << listItem->index; for (int j = 0; j < visibleItems.count(); j++) qDebug() << " index" << j << "item index" << visibleItems.at(j)->index; - qFatal(); + qFatal("index %d %d %d", visibleIndex, i, listItem->index); } } } diff --git a/src/declarative/fx/qfxlistview.cpp b/src/declarative/fx/qfxlistview.cpp index 4c76267..a8c0747 100644 --- a/src/declarative/fx/qfxlistview.cpp +++ b/src/declarative/fx/qfxlistview.cpp @@ -324,8 +324,7 @@ public: if (listItem->index == -1) { ++skip; } else if (listItem->index != visibleIndex + i - skip) { - qDebug() << "index" << visibleIndex << i << listItem->index; - qFatal(); + qFatal("index %d %d %d", visibleIndex, i, listItem->index); } } } -- cgit v0.12 From d0f47dfb66f10034a7b4336272f5aec63daad4fe Mon Sep 17 00:00:00 2001 From: Sarah Smith Date: Fri, 5 Jun 2009 14:35:42 +1000 Subject: Compile when -no-qt3-support is on. As checked in was compiling with QDataStream(QByteArray *, int) and that method is only available when compiling with qt3 support. Reviewed-by: Julian de Bhal --- src/network/kernel/qauthenticator.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/network/kernel/qauthenticator.cpp b/src/network/kernel/qauthenticator.cpp index b672765..cae3024 100644 --- a/src/network/kernel/qauthenticator.cpp +++ b/src/network/kernel/qauthenticator.cpp @@ -46,6 +46,7 @@ #include #include #include +#include #include #include #include -- cgit v0.12 From afaa509b0e44d3ab0235abfdda0f1ae6068bd1d6 Mon Sep 17 00:00:00 2001 From: jasplin Date: Fri, 5 Jun 2009 07:49:33 +0200 Subject: Made configure work with older versions of /bin/sh. Some older versions of the Bourne shell (/bin/sh) don't support the ! operator for negating the exit code of a pipeline. In particular, this is true on certain (all?) Solaris 9 platforms. The patch replaces all occurrences of the ! operator with equivalent (but slightly less elegant) expressions that test the $? variable instead. Reviewed-by: msorvig --- configure | 45 ++++++++++++++++++++++++++++++--------------- 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/configure b/configure index 764840e..58ab08c 100755 --- a/configure +++ b/configure @@ -4240,7 +4240,8 @@ fi # check iWMMXt support if [ "$CFG_IWMMXT" = "yes" ]; then - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/iwmmxt "iwmmxt" $L_FLAGS $I_FLAGS $l_FLAGS "-mcpu=iwmmxt"; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/iwmmxt "iwmmxt" $L_FLAGS $I_FLAGS $l_FLAGS "-mcpu=iwmmxt" + if [ $? != "0" ]; then echo "The iWMMXt functionality test failed!" echo " Please make sure your compiler supports iWMMXt intrinsics!" exit 1 @@ -4759,7 +4760,8 @@ if [ "$PLATFORM_X11" = "yes" ]; then fi # Check we actually have X11 :-) - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/x11/xlib "XLib" $L_FLAGS $I_FLAGS $l_FLAGS $X11TESTS_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/x11/xlib "XLib" $L_FLAGS $I_FLAGS $l_FLAGS $X11TESTS_FLAGS + if [ $? != "0" ]; then echo "Basic XLib functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR_X11 and QMAKE_LIBDIR_X11 in ${XQMAKESPEC}." @@ -4790,7 +4792,8 @@ if [ "$PLATFORM_X11" = "yes" ]; then hpux*) # HP-UX have buggy glx headers; check if we really need to define the GLXFBConfig struct. if [ "$CFG_OPENGL" = "desktop" ]; then - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/x11/glxfbconfig "OpenGL" $L_FLAGS $I_FLAGS $l_FLAGS $X11TESTS_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/x11/glxfbconfig "OpenGL" $L_FLAGS $I_FLAGS $l_FLAGS $X11TESTS_FLAGS + if [ $? != "0" ]; then QMakeVar add DEFINES QT_DEFINE_GLXFBCONFIG_STRUCT fi fi @@ -4800,7 +4803,8 @@ if [ "$PLATFORM_X11" = "yes" ]; then esac elif [ "$CFG_OPENGL" = "es1cl" ]; then # OpenGL ES 1.x common lite - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles1cl "OpenGL ES 1.x Lite" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles1cl "OpenGL ES 1.x Lite" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then echo "The OpenGL ES 1.x Common Lite Profile functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR_OPENGL, QMAKE_LIBDIR_OPENGL and QMAKE_LIBS_OPENGL in" @@ -4809,7 +4813,8 @@ if [ "$PLATFORM_X11" = "yes" ]; then fi elif [ "$CFG_OPENGL" = "es1" ]; then # OpenGL ES 1.x - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles1 "OpenGL ES 1.x" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles1 "OpenGL ES 1.x" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then echo "The OpenGL ES 1.x functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR_OPENGL, QMAKE_LIBDIR_OPENGL and QMAKE_LIBS_OPENGL in" @@ -4818,7 +4823,8 @@ if [ "$PLATFORM_X11" = "yes" ]; then fi elif [ "$CFG_OPENGL" = "es2" ]; then #OpenGL ES 2.x - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles2 "OpenGL ES 2.x" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles2 "OpenGL ES 2.x" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then echo "The OpenGL ES 2.0 functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR_OPENGL, QMAKE_LIBDIR_OPENGL and QMAKE_LIBS_OPENGL in" @@ -4827,7 +4833,8 @@ if [ "$PLATFORM_X11" = "yes" ]; then fi elif [ "$CFG_OPENGL" = "desktop" ]; then # Desktop OpenGL support - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/x11/opengl "OpenGL" $L_FLAGS $I_FLAGS $l_FLAGS $X11TESTS_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/x11/opengl "OpenGL" $L_FLAGS $I_FLAGS $l_FLAGS $X11TESTS_FLAGS + if [ $? != "0" ]; then echo "The OpenGL functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR_OPENGL, QMAKE_LIBDIR_OPENGL and QMAKE_LIBS_OPENGL in" @@ -4837,7 +4844,8 @@ if [ "$PLATFORM_X11" = "yes" ]; then case "$PLATFORM" in hpux*) # HP-UX have buggy glx headers; check if we really need to define the GLXFBConfig struct. - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/x11/glxfbconfig "OpenGL" $L_FLAGS $I_FLAGS $l_FLAGS $X11TESTS_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/x11/glxfbconfig "OpenGL" $L_FLAGS $I_FLAGS $l_FLAGS $X11TESTS_FLAGS + if [ $? != "0" ]; then QMakeVar add DEFINES QT_DEFINE_GLXFBCONFIG_STRUCT fi ;; @@ -5112,7 +5120,8 @@ if [ "$PLATFORM_QWS" = "yes" ]; then fi elif [ "$CFG_OPENGL" = "es1" ]; then # OpenGL ES 1.x - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles1 "OpenGL ES 1.x" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles1 "OpenGL ES 1.x" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then echo "The OpenGL ES 1.x functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR_OPENGL, QMAKE_LIBDIR_OPENGL and QMAKE_LIBS_OPENGL in" @@ -5121,7 +5130,8 @@ if [ "$PLATFORM_QWS" = "yes" ]; then fi elif [ "$CFG_OPENGL" = "es2" ]; then #OpenGL ES 2.x - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles2 "OpenGL ES 2.x" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/opengles2 "OpenGL ES 2.x" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then echo "The OpenGL ES 2.0 functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR_OPENGL, QMAKE_LIBDIR_OPENGL and QMAKE_LIBS_OPENGL in" @@ -5137,7 +5147,8 @@ if [ "$PLATFORM_QWS" = "yes" ]; then # screen drivers for screen in ${CFG_GFX_ON} ${CFG_GFX_PLUGIN}; do if [ "${screen}" = "ahi" ] && [ "${CFG_CONFIGURE_EXIT_ON_ERROR}" = "yes" ]; then - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/qws/ahi "Ahi" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/qws/ahi "Ahi" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then echo "The Ahi screen driver functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR and QMAKE_LIBDIR in" @@ -5147,7 +5158,8 @@ if [ "$PLATFORM_QWS" = "yes" ]; then fi if [ "${screen}" = "svgalib" ] && [ "${CFG_CONFIGURE_EXIT_ON_ERROR}" = "yes" ]; then - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/qws/svgalib "SVGAlib" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/qws/svgalib "SVGAlib" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then echo "The SVGAlib screen driver functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR and QMAKE_LIBDIR in" @@ -5176,7 +5188,8 @@ if [ "$PLATFORM_QWS" = "yes" ]; then QMakeVar set QT_DEFINES_DIRECTFB "QT3_SUPPORT" fi - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/qws/directfb "DirectFB" $L_FLAGS $I_FLAGS $l_FLAGS $QT_CFLAGS_DIRECTFB $QT_LIBS_DIRECTFB; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/qws/directfb "DirectFB" $L_FLAGS $I_FLAGS $l_FLAGS $QT_CFLAGS_DIRECTFB $QT_LIBS_DIRECTFB + if [ $? != "0" ]; then echo "The DirectFB screen driver functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QT_CFLAGS_DIRECTFB and QT_LIBS_DIRECTFB in" @@ -5190,7 +5203,8 @@ if [ "$PLATFORM_QWS" = "yes" ]; then # mouse drivers for mouse in ${CFG_MOUSE_ON} ${CFG_MOUSE_PLUGIN}; do if [ "${mouse}" = "tslib" ] && [ "${CFG_CONFIGURE_EXIT_ON_ERROR}" = "yes" ]; then - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/tslib "tslib" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/tslib "tslib" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then echo "The tslib functionality test failed!" echo " You might need to modify the include and library search paths by editing" echo " QMAKE_INCDIR and QMAKE_LIBDIR in" @@ -5203,7 +5217,8 @@ if [ "$PLATFORM_QWS" = "yes" ]; then CFG_QGTKSTYLE=no # sound - if ! "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/qws/sound "sound" $L_FLAGS $I_FLAGS $l_FLAGS; then + "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/qws/sound "sound" $L_FLAGS $I_FLAGS $l_FLAGS + if [ $? != "0" ]; then QCONFIG_FLAGS="$QCONFIG_FLAGS QT_NO_SOUND" fi -- cgit v0.12 From 555018baf3115cb2587d2217bf1a5b8f49564ad2 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Fri, 5 Jun 2009 09:06:54 +0200 Subject: qdoc: Put ... around names in each summary section. --- tools/qdoc3/htmlgenerator.cpp | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index ab26d08..0c4aab3 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -1744,8 +1744,9 @@ QString HtmlGenerator::generateLowStatusMemberFile(const InnerNode *inner, CodeM return fileName; } -void HtmlGenerator::generateClassHierarchy(const Node *relative, CodeMarker *marker, - const QMap &classMap) +void HtmlGenerator::generateClassHierarchy(const Node *relative, + CodeMarker *marker, + const QMap &classMap) { if (classMap.isEmpty()) return; @@ -1950,7 +1951,8 @@ void HtmlGenerator::generateCompactList(const Node *relative, CodeMarker *marker if (currentOffset[i] >= firstOffset[i + 1]) { // this column is finished out() << "\n"; if (currentOffsetInParagraph[i] == 0) { // start a new paragraph - out() << "" << paragraphName[currentParagraphNo[i]] << " "; + out() << "" + << paragraphName[currentParagraphNo[i]] + << " "; } out() << ""; // Previously, we used generateFullName() for this, but we // require some special formatting. - out() << ""; + out() << ""; QStringList pieces = fullName(it.value(), relative, marker).split("::"); out() << protect(pieces.last()); out() << ""; @@ -1992,7 +1998,8 @@ void HtmlGenerator::generateCompactList(const Node *relative, CodeMarker *marker out() << "

    \n"; } -void HtmlGenerator::generateFunctionIndex(const Node *relative, CodeMarker *marker) +void HtmlGenerator::generateFunctionIndex(const Node *relative, + CodeMarker *marker) { out() << "

    "; for (int i = 0; i < 26; i++) { @@ -2337,13 +2344,11 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode, } i += 2; if (parseArg(src, linkTag, &i, n, &arg, &par1)) { - if (style == CodeMarker::Accessors) - html += ""; + html += ""; QString link = linkForNode( CodeMarker::nodeForString(par1.toString()), relative); addLink(link, arg, &html); - if (style == CodeMarker::Accessors) - html += ""; + html += ""; } else { html += charLangle; -- cgit v0.12 From e50916796adc0dee112505ed617f9b83e99526fb Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Fri, 5 Jun 2009 10:32:25 +0200 Subject: qdoc: Changed to use h2 for section headers instead of h3. --- tools/qdoc3/htmlgenerator.cpp | 43 +++++++++++++++++++++++++++++-------------- 1 file changed, 29 insertions(+), 14 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index 0c4aab3..90d3b04 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -1048,12 +1048,16 @@ void HtmlGenerator::generateClassLikeNode(const InnerNode *inner, out() << "

  • " << "List of all members, including inherited members
  • \n"; - QString obsoleteLink = generateLowStatusMemberFile(inner, marker, CodeMarker::Obsolete); + QString obsoleteLink = generateLowStatusMemberFile(inner, + marker, + CodeMarker::Obsolete); if (!obsoleteLink.isEmpty()) out() << "
  • " << "Obsolete members
  • \n"; - QString compatLink = generateLowStatusMemberFile(inner, marker, CodeMarker::Compat); + QString compatLink = generateLowStatusMemberFile(inner, + marker, + CodeMarker::Compat); if (!compatLink.isEmpty()) out() << "
  • " << "Qt 3 support members
  • \n"; @@ -1069,9 +1073,10 @@ void HtmlGenerator::generateClassLikeNode(const InnerNode *inner, if (!s->inherited.isEmpty()) needOtherSection = true; } else { - out() << "\n"; - out() << "

    " << protect((*s).name) << "

    \n"; - + out() << "\n"; + out() << "

    " << protect((*s).name) << "

    \n"; generateSectionList(*s, inner, marker, CodeMarker::Summary); } ++s; @@ -1224,12 +1229,16 @@ void HtmlGenerator::generateFakeNode(const FakeNode *fake, CodeMarker *marker) out() << "
  • " << "List of all members, including inherited members
  • \n"; - QString obsoleteLink = generateLowStatusMemberFile(fake, marker, CodeMarker::Obsolete); + QString obsoleteLink = generateLowStatusMemberFile(fake, + marker, + CodeMarker::Obsolete); if (!obsoleteLink.isEmpty()) out() << "
  • " << "Obsolete members
  • \n"; - QString compatLink = generateLowStatusMemberFile(fake, marker, CodeMarker::Compat); + QString compatLink = generateLowStatusMemberFile(fake, + marker, + CodeMarker::Compat); if (!compatLink.isEmpty()) out() << "
  • " << "Qt 3 support members
  • \n"; @@ -1260,7 +1269,7 @@ void HtmlGenerator::generateFakeNode(const FakeNode *fake, CodeMarker *marker) s = sections.begin(); while (s != sections.end()) { out() << "\n"; - out() << "

    " << protect((*s).name) << "

    \n"; + out() << "

    " << protect((*s).name) << "

    \n"; generateSectionList(*s, fake, marker, CodeMarker::Summary); ++s; } @@ -1656,7 +1665,9 @@ QString HtmlGenerator::generateListOfAllMemberFile(const InnerNode *inner, CodeM QList
    sections; QList
    ::ConstIterator s; - sections = marker->sections(inner, CodeMarker::SeparateList, CodeMarker::Okay); + sections = marker->sections(inner, + CodeMarker::SeparateList, + CodeMarker::Okay); if (sections.isEmpty()) return QString(); @@ -1677,10 +1688,13 @@ QString HtmlGenerator::generateListOfAllMemberFile(const InnerNode *inner, CodeM return fileName; } -QString HtmlGenerator::generateLowStatusMemberFile(const InnerNode *inner, CodeMarker *marker, +QString HtmlGenerator::generateLowStatusMemberFile(const InnerNode *inner, + CodeMarker *marker, CodeMarker::Status status) { - QList
    sections = marker->sections(inner, CodeMarker::Summary, status); + QList
    sections = marker->sections(inner, + CodeMarker::Summary, + status); QMutableListIterator
    j(sections); while (j.hasNext()) { if (j.next().members.size() == 0) @@ -1717,12 +1731,13 @@ QString HtmlGenerator::generateLowStatusMemberFile(const InnerNode *inner, CodeM "code.

    \n"; } - out() << "

    • " << protect(inner->name()) + out() << "

      \n"; for (i = 0; i < sections.size(); ++i) { - out() << "

      " << protect(sections.at(i).name) << "

      \n"; - + out() << "

      " << protect(sections.at(i).name) << "

      \n"; generateSectionList(sections.at(i), inner, marker, CodeMarker::Summary); } -- cgit v0.12 From cdb0222129a139dfe1b7e4fb4b401556989901b4 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Fri, 5 Jun 2009 10:45:26 +0200 Subject: My changelog for 4.5.2 --- dist/changes-4.5.2 | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 04a29ba..5de0dbe 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -67,6 +67,17 @@ Third party components - QDir * Fix reentrency (listing directories in different threads) +- QFileSystemModel + * [254701] QFileSystemModel doesn't sort subfolders when using it in a QTreeView + * [251295] Windows path names incorrectly constructed in calls to updateIcon() + +- QFileDialog + * [251341] It is not possible to remove a directory of the sidebar if the directory does not exist + * [251321] Hidden path in QFileDialog's sidebar cannot be opened + * [226483] setSidebarUrls() handles the urls case sensitive so that adding the same directory twice is possible - Windows + * [252068] QFileDialog with QSortFilterProxyModel crashes + * [254490] QFileDialog selectFile doesn't clear the selection if we call it several times. + - QMacStyle * [253339] Don't draw arrows on toolbuttons that have a menu and text only. * [252301] Ensure that small and mini spin boxes are drawn correctly. -- cgit v0.12 From 3e1bbbda44258005b20862effe495cfb664627ca Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Fri, 5 Jun 2009 10:52:01 +0200 Subject: link qmake without /DEBUG on Windows Reviewed-by: mariusSO --- qmake/Makefile.win32 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/qmake/Makefile.win32 b/qmake/Makefile.win32 index 39bac81..53130aa 100644 --- a/qmake/Makefile.win32 +++ b/qmake/Makefile.win32 @@ -41,7 +41,7 @@ CFLAGS = -c -Fo$@ \ CXXFLAGS = $(CFLAGS) LFLAGS = LIBS = ole32.lib advapi32.lib -LINKQMAKE = $(LINK) $(LFLAGS) -DEBUG -OUT:qmake.exe $(OBJS) $(QTOBJS) $(LIBS) +LINKQMAKE = $(LINK) $(LFLAGS) -OUT:qmake.exe $(OBJS) $(QTOBJS) $(LIBS) ADDCLEAN = vc60.pdb vc70.pdb qmake.pdb qmake.ilk !ELSE -- cgit v0.12 From 6fff92a31c4acd270d0ecb4cda336ba098801ffb Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 5 Jun 2009 12:12:21 +0200 Subject: Doc - cleaned up a sentence to improve clarity Reviewed-By: TrustMe --- doc/src/tutorials/addressbook.qdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc index bf202b2..5a49901 100644 --- a/doc/src/tutorials/addressbook.qdoc +++ b/doc/src/tutorials/addressbook.qdoc @@ -454,7 +454,7 @@ \snippet tutorials/addressbook/part3/addressbook.cpp connecting navigation signals The image below is our expected graphical user interface. Notice that it - is getting closer to our expected final output. + is getting closer to our final application. \image addressbook-tutorial-part3-screenshot.png -- cgit v0.12 From 95ceabf52d79b922a87f7c023c9606e633ab1ea2 Mon Sep 17 00:00:00 2001 From: Thiago Macieira Date: Thu, 4 Jun 2009 15:03:31 +0200 Subject: Autotest: Fixed a race condition in the network self test. Some of the tests (including the httpsServer one) requested that the server close the connection (Connection: close). It could happen that, well, the server did close the connection and we noticed it while doing the waitForBytesWritten in the doSocketFlush function. Then we'd create an error in the next step because the socket wasn't connected. Reviewed-by: TrustMe --- tests/auto/_networkselftest/tst_networkselftest.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/tests/auto/_networkselftest/tst_networkselftest.cpp b/tests/auto/_networkselftest/tst_networkselftest.cpp index 0fa001a..eac603f 100644 --- a/tests/auto/_networkselftest/tst_networkselftest.cpp +++ b/tests/auto/_networkselftest/tst_networkselftest.cpp @@ -190,12 +190,6 @@ static void netChat(int port, const QList &chat) // now start the chat QList::ConstIterator it = chat.constBegin(); for (int i = 1; it != chat.constEnd(); ++it, ++i) { - if (it->type != Chat::Reconnect - && socket.state() != QAbstractSocket::ConnectedState - && socket.state() != QAbstractSocket::ClosingState) - QFAIL(QString("Internal error: socket is in invalid state %1 in step %2") - .arg(socket.state()).arg(i).toLocal8Bit()); - switch (it->type) { case Chat::Expect: { qDebug() << i << "Expecting" << prettyByteArray(it->data); -- cgit v0.12 From 754f8968332e712d590a6ee984118536c0447348 Mon Sep 17 00:00:00 2001 From: jasplin Date: Fri, 5 Jun 2009 12:06:46 +0200 Subject: Compile with Sun CC 5.5. An alternative solution is to swap the order of -I../../include and -I../../include/QtOpenGL when compiling the opengl module. Reviewed-by: TrustMe --- src/opengl/gl2paintengineex/qglgradientcache_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/opengl/gl2paintengineex/qglgradientcache_p.h b/src/opengl/gl2paintengineex/qglgradientcache_p.h index 9bf58c7..f088359 100644 --- a/src/opengl/gl2paintengineex/qglgradientcache_p.h +++ b/src/opengl/gl2paintengineex/qglgradientcache_p.h @@ -52,7 +52,7 @@ #include #include -#include +#include QT_BEGIN_NAMESPACE -- cgit v0.12 From 799a9ddf0a53ecdd6e097b2efd7418fd6ab9b655 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 5 Jun 2009 12:29:27 +0200 Subject: Doc - fixed a typo Reviewed-By: TrustMe --- doc/src/tutorials/addressbook.qdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc index 5a49901..4ab549a 100644 --- a/doc/src/tutorials/addressbook.qdoc +++ b/doc/src/tutorials/addressbook.qdoc @@ -510,7 +510,7 @@ \list \o If the iterator is at the end of \c contacts, we clear the display and return. - \o If the iterator is the beginning of \c contacts, we move it to + \o If the iterator is at the beginning of \c contacts, we move it to the end. \o We then decrement the iterator by one. \endlist -- cgit v0.12 From 35bdd8942716c716113e5b795186ca76199e8d96 Mon Sep 17 00:00:00 2001 From: Trond Kjernaasen Date: Fri, 5 Jun 2009 12:32:51 +0200 Subject: Fixed text drawing on Windows in 16 bit mode. There were several problems with antialiased text in 16 bit mode under Windows. No gamma correction was done, yet we prepared the cached glyphs for gamma correction. The mask format we rendered the glyphs into was also set to the desktop depth, which implied that information was lost and the text looked rather odd. Reviewed-by: Samuel BT: yes --- src/gui/text/qfontengine_win.cpp | 26 ++++++++++++++------------ src/gui/text/qfontengine_win_p.h | 3 ++- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/gui/text/qfontengine_win.cpp b/src/gui/text/qfontengine_win.cpp index 7341665..dc2e1ff 100644 --- a/src/gui/text/qfontengine_win.cpp +++ b/src/gui/text/qfontengine_win.cpp @@ -1335,7 +1335,7 @@ bool QFontEngineWin::getSfntTableData(uint tag, uchar *buffer, uint *length) con QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin, - const QTransform &t) + const QTransform &t, QImage::Format mask_format) { glyph_metrics_t gm = boundingBox(glyph); @@ -1408,7 +1408,7 @@ QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin QNativeImage *ni = new QNativeImage(iw + 2 * margin + 4, ih + 2 * margin + 4, - QNativeImage::systemFormat(), true); + mask_format, true); ni->image.fill(0xffffffff); HDC hdc = ni->hdc; @@ -1448,8 +1448,12 @@ QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph, const QTransform &xform) lf.lfQuality = ANTIALIASED_QUALITY; font = CreateFontIndirectW(&lf); } + QImage::Format mask_format = QNativeImage::systemFormat(); +#ifndef Q_OS_WINCE + mask_format = QImage::Format_RGB32; +#endif - QNativeImage *mask = drawGDIGlyph(font, glyph, 0, xform); + QNativeImage *mask = drawGDIGlyph(font, glyph, 0, xform, mask_format); if (mask == 0) return QImage(); @@ -1466,22 +1470,20 @@ QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph, const QTransform &xform) // Alpha channel of the ni.image pixels... for (int y=0; yheight(); ++y) { uchar *dest = indexed.scanLine(y); - if (mask->systemFormat() == QImage::Format_RGB16) { + if (mask->image.format() == QImage::Format_RGB16) { const qint16 *src = (qint16 *) ((const QImage &) mask->image).scanLine(y); - for (int x=0; xwidth(); ++x) { -#ifdef Q_OS_WINCE + for (int x=0; xwidth(); ++x) dest[x] = 255 - qGray(src[x]); -#else - dest[x] = 255 - (qt_pow_gamma[qGray(src[x])] * 255. / 2047.); -#endif - } } else { const uint *src = (uint *) ((const QImage &) mask->image).scanLine(y); for (int x=0; xwidth(); ++x) { #ifdef Q_OS_WINCE dest[x] = 255 - qGray(src[x]); #else - dest[x] = 255 - (qt_pow_gamma[qGray(src[x])] * 255. / 2047.); + if (QNativeImage::systemFormat() == QImage::Format_RGB16) + dest[x] = 255 - qGray(src[x]); + else + dest[x] = 255 - (qt_pow_gamma[qGray(src[x])] * 255. / 2047.); #endif } } @@ -1507,7 +1509,7 @@ QImage QFontEngineWin::alphaRGBMapForGlyph(glyph_t glyph, int margin, const QTra SystemParametersInfo(SPI_GETFONTSMOOTHINGCONTRAST, 0, &contrast, 0); SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, (void *) 1000, 0); - QNativeImage *mask = drawGDIGlyph(font, glyph, margin, t); + QNativeImage *mask = drawGDIGlyph(font, glyph, margin, t, QImage::Format_RGB32); SystemParametersInfo(SPI_SETFONTSMOOTHINGCONTRAST, 0, (void *) contrast, 0); if (mask == 0) diff --git a/src/gui/text/qfontengine_win_p.h b/src/gui/text/qfontengine_win_p.h index 6f37e91..f78bc6a 100644 --- a/src/gui/text/qfontengine_win_p.h +++ b/src/gui/text/qfontengine_win_p.h @@ -138,7 +138,8 @@ public: mutable int designAdvancesSize; private: - QNativeImage *drawGDIGlyph(HFONT font, glyph_t, int margin, const QTransform &xform); + QNativeImage *drawGDIGlyph(HFONT font, glyph_t, int margin, const QTransform &xform, + QImage::Format mask_format); }; -- cgit v0.12 From f04af57ba71e8a4cd3c19f6e1a283290cc5280d4 Mon Sep 17 00:00:00 2001 From: miniak Date: Fri, 5 Jun 2009 12:50:31 +0200 Subject: Fix for Qt issue #218037 - Add support for the WM_MOUSEHWHEEL message on Windows Merge-request: 384 Reviewed-by: Marius Storm-Olsen --- src/corelib/global/qt_windows.h | 3 +++ src/corelib/kernel/qcoreapplication_win.cpp | 4 ++++ src/corelib/kernel/qeventdispatcher_win.cpp | 3 ++- src/gui/kernel/qapplication_win.cpp | 14 ++++++++++++-- 4 files changed, 21 insertions(+), 3 deletions(-) diff --git a/src/corelib/global/qt_windows.h b/src/corelib/global/qt_windows.h index 2ce4059..7fc7f47 100644 --- a/src/corelib/global/qt_windows.h +++ b/src/corelib/global/qt_windows.h @@ -106,6 +106,9 @@ #ifndef WM_MOUSEWHEEL #define WM_MOUSEWHEEL 0x020A #endif +#ifndef WM_MOUSEHWHEEL +#define WM_MOUSEHWHEEL 0x020E +#endif #ifndef ETO_PDY #define ETO_PDY 0x2000 #endif diff --git a/src/corelib/kernel/qcoreapplication_win.cpp b/src/corelib/kernel/qcoreapplication_win.cpp index 815a558..9c1c235 100644 --- a/src/corelib/kernel/qcoreapplication_win.cpp +++ b/src/corelib/kernel/qcoreapplication_win.cpp @@ -409,6 +409,7 @@ struct { { 0x020B, "WM_XBUTTONDOWN" }, { 0x020C, "WM_XBUTTONUP" }, { 0x020D, "WM_XBUTTONDBLCLK" }, + { 0x020E, "WM_MOUSEHWHEEL" }, { 0x0210, "WM_PARENTNOTIFY" }, { 0x0211, "WM_ENTERMENULOOP" }, { 0x0212, "WM_EXITMENULOOP" }, @@ -898,6 +899,9 @@ QString decodeMSG(const MSG& msg) #ifdef WM_MOUSEWHEEL case WM_MOUSEWHEEL: #endif +#ifdef WM_MOUSEHWHEEL + case WM_MOUSEHWHEEL: +#endif #ifdef WM_LBUTTONDBLCLK case WM_LBUTTONDBLCLK: #endif diff --git a/src/corelib/kernel/qeventdispatcher_win.cpp b/src/corelib/kernel/qeventdispatcher_win.cpp index 2dd5534..7d3a13a 100644 --- a/src/corelib/kernel/qeventdispatcher_win.cpp +++ b/src/corelib/kernel/qeventdispatcher_win.cpp @@ -696,7 +696,8 @@ bool QEventDispatcherWin32::processEvents(QEventLoop::ProcessEventsFlags flags) && msg.message <= WM_KEYLAST) || (msg.message >= WM_MOUSEFIRST && msg.message <= WM_MOUSELAST) - || msg.message == WM_MOUSEWHEEL)) { + || msg.message == WM_MOUSEWHEEL + || msg.message == WM_MOUSEHWHEEL)) { // queue user input events for later processing haveMessage = false; d->queuedUserInputEvents.append(msg); diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 7e97784..60f3edf 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -1408,6 +1408,7 @@ static bool qt_is_translatable_mouse_event(UINT message) return (message >= WM_MOUSEFIRST && message <= WM_MOUSELAST || message >= WM_XBUTTONDOWN && message <= WM_XBUTTONDBLCLK) && message != WM_MOUSEWHEEL + && message != WM_MOUSEHWHEEL #ifndef Q_WS_WINCE || message >= WM_NCMOUSEMOVE && message <= WM_NCMBUTTONDBLCLK @@ -1758,6 +1759,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam break; case WM_MOUSEWHEEL: + case WM_MOUSEHWHEEL: result = widget->translateWheelEvent(msg); break; @@ -2657,6 +2659,7 @@ bool qt_try_modal(QWidget *widget, MSG *msg, int& ret) #endif if ((type >= WM_MOUSEFIRST && type <= WM_MOUSELAST) || type == WM_MOUSEWHEEL || type == (int)WM95_MOUSEWHEEL || + type == WM_MOUSEHWHEEL || type == WM_MOUSELEAVE || (type >= WM_KEYFIRST && type <= WM_KEYLAST) #ifndef Q_WS_WINCE @@ -3268,12 +3271,12 @@ bool QETWidget::translateWheelEvent(const MSG &msg) state = translateButtonState(GET_KEYSTATE_WPARAM(msg.wParam), 0, 0); int delta; - if (msg.message == WM_MOUSEWHEEL) + if (msg.message == WM_MOUSEWHEEL || msg.message == WM_MOUSEHWHEEL) delta = (short) HIWORD (msg.wParam); else delta = (int) msg.wParam; - Qt::Orientation orient = (state&Qt::AltModifier + Qt::Orientation orient = (msg.message == WM_MOUSEHWHEEL || state&Qt::AltModifier #if 0 // disabled for now - Trenton's one-wheel mouse makes trouble... // "delta" for usual wheels is +-120. +-240 seems to indicate @@ -3287,6 +3290,13 @@ bool QETWidget::translateWheelEvent(const MSG &msg) #endif ) ? Qt::Horizontal : Qt::Vertical; + // according to the MSDN documentation on WM_MOUSEHWHEEL: + // a positive value indicates that the wheel was rotated to the right; + // a negative value indicates that the wheel was rotated to the left. + // Qt defines this value as the exact opposite, so we have to flip the value! + if (msg.message == WM_MOUSEHWHEEL) + delta = -delta; + QPoint globalPos; globalPos.rx() = (short)LOWORD (msg.lParam); -- cgit v0.12 From 84f381b98a9a100007a9d40a26e30f0bf705037b Mon Sep 17 00:00:00 2001 From: J-P Nurmi Date: Fri, 5 Jun 2009 13:06:06 +0200 Subject: Made qmake handle "no_default" config for sub targets Merge-request: 395 Reviewed-by: Marius Storm-Olsen --- qmake/generators/makefile.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/qmake/generators/makefile.cpp b/qmake/generators/makefile.cpp index 67e5bfb..2d4658e 100644 --- a/qmake/generators/makefile.cpp +++ b/qmake/generators/makefile.cpp @@ -2463,7 +2463,12 @@ MakefileGenerator::writeSubTargets(QTextStream &t, QListtarget + "-" + suffix; + SubTarget *subTarget = targets.at(target); + if((suffix == "make_first" || suffix == "make_default") + && project->values(subTarget->name + ".CONFIG").indexOf("no_default_target") != -1) { + continue; + } + QString targetRule = subTarget->target + "-" + suffix; if(flags & SubTargetOrdered) targetRule += "-ordered"; t << " " << targetRule; -- cgit v0.12 From e6b3c48159f479d82740988a6104b9f5aee16a59 Mon Sep 17 00:00:00 2001 From: hjk Date: Fri, 5 Jun 2009 11:39:54 +0200 Subject: Make QStringBuilder work out-of-the-box if QT_NO_CAST_FROM_ASCII is defined So far, only operator% was working for concatenation in those circumnstances. Now, defining QT_USE_FAST_OPERATOR_PLUS and QT_USE_FAST_CONCATENATION is enough, so user code will work without any source changes. Reviewed-by: joao --- src/corelib/tools/qstringbuilder.h | 24 ++++++++++++++++ tests/auto/qstringbuilder/tst_qstringbuilder.cpp | 35 ------------------------ 2 files changed, 24 insertions(+), 35 deletions(-) diff --git a/src/corelib/tools/qstringbuilder.h b/src/corelib/tools/qstringbuilder.h index 1e67b7d..7b16197 100644 --- a/src/corelib/tools/qstringbuilder.h +++ b/src/corelib/tools/qstringbuilder.h @@ -169,6 +169,30 @@ template <> struct QConcatenable } }; +#ifndef QT_NO_CAST_FROM_ASCII +template struct QConcatenable +{ + typedef char type[N]; + static int size(const char *) { return N - 1; } + static inline void appendTo(const char *a, QChar *&out) + { + for (int i = 0; i < N - 1; ++i) + *out++ = QLatin1Char(a[i]); + } +}; + +template <> struct QConcatenable +{ + typedef char const *type; + static int size(const char *a) { return qstrlen(a); } + static inline void appendTo(const char *a, QChar *&out) + { + while (*a) + *out++ = QLatin1Char(*a++); + } +}; +#endif + template struct QConcatenable< QStringBuilder > { diff --git a/tests/auto/qstringbuilder/tst_qstringbuilder.cpp b/tests/auto/qstringbuilder/tst_qstringbuilder.cpp index f5df79e..5501204 100644 --- a/tests/auto/qstringbuilder/tst_qstringbuilder.cpp +++ b/tests/auto/qstringbuilder/tst_qstringbuilder.cpp @@ -95,41 +95,6 @@ #define LITERAL "some literal" -#ifndef QT_NO_CAST_FROM_ASCII - -// Plan is to move the QConcatenable specialications below -// to qstringbuilder.h as soon as the QByteArray builder is -// implemented. - -QT_BEGIN_NAMESPACE - -template struct QConcatenable -{ - typedef char type[N]; - static int size(const char *) { return N - 1; } - static inline void appendTo(const type &a, QChar *&out) - { - memcpy(out, a, N - 1); - out += N - 1; - } -}; - -template struct QConcatenable -{ - typedef char type[N]; - static int size(const char *) { return N - 1; } - static inline void appendTo(const type &a, QChar *&out) - { - memcpy(out, a, N - 1); - out += N - 1; - } -}; - -QT_END_NAMESPACE - -#endif - - class tst_QStringBuilder : public QObject { Q_OBJECT -- cgit v0.12 From a8738d7a11f8eea0164977c4c478d04a1a337f3a Mon Sep 17 00:00:00 2001 From: jasplin Date: Fri, 5 Jun 2009 13:28:46 +0200 Subject: Fixed build issue with Sun CC 5.5. Reviewed-by: TrustMe --- tools/linguist/lupdate/cpp.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/linguist/lupdate/cpp.cpp b/tools/linguist/lupdate/cpp.cpp index 42aa2f0..9f28d1d 100644 --- a/tools/linguist/lupdate/cpp.cpp +++ b/tools/linguist/lupdate/cpp.cpp @@ -145,7 +145,6 @@ public: const ParseResults *getResults() const { return results; } void deleteResults() { delete results; } -private: struct SavedState { QStringList namespaces; QStack namespaceDepths; @@ -154,6 +153,7 @@ private: QString pendingContext; }; +private: struct IfdefState { IfdefState() {} IfdefState(int _braceDepth, int _parenDepth) : -- cgit v0.12 From f101435831bb06f342bb0e2241e3011073341617 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Fri, 5 Jun 2009 13:35:49 +0200 Subject: Fix wrong sizing of toolbars when they have anough space What could happen starting with 4.4 is that you could move a toolbar. If you then added actions, the toolbar would grom and make the other toolbars move to the right although it had enough space already to show the newly created actions. Autotest will follow shortly. Task-number: 226060 --- src/gui/widgets/qmainwindowlayout_p.h | 30 ------------ src/gui/widgets/qtoolbararealayout.cpp | 86 ++++++++++++++++++++-------------- src/gui/widgets/qtoolbararealayout_p.h | 57 ++++++++++++++++++++-- 3 files changed, 104 insertions(+), 69 deletions(-) diff --git a/src/gui/widgets/qmainwindowlayout_p.h b/src/gui/widgets/qmainwindowlayout_p.h index 1159aac..24a58a6 100644 --- a/src/gui/widgets/qmainwindowlayout_p.h +++ b/src/gui/widgets/qmainwindowlayout_p.h @@ -341,34 +341,4 @@ QT_END_NAMESPACE #endif // QT_NO_MAINWINDOW -QT_BEGIN_NAMESPACE -static inline int pick(Qt::Orientation o, const QPoint &pos) -{ return o == Qt::Horizontal ? pos.x() : pos.y(); } - -static inline int pick(Qt::Orientation o, const QSize &size) -{ return o == Qt::Horizontal ? size.width() : size.height(); } - -static inline int &rpick(Qt::Orientation o, QPoint &pos) -{ return o == Qt::Horizontal ? pos.rx() : pos.ry(); } - -static inline int &rpick(Qt::Orientation o, QSize &size) -{ return o == Qt::Horizontal ? size.rwidth() : size.rheight(); } - -static inline QSizePolicy::Policy pick(Qt::Orientation o, const QSizePolicy &policy) -{ return o == Qt::Horizontal ? policy.horizontalPolicy() : policy.verticalPolicy(); } - -static inline int perp(Qt::Orientation o, const QPoint &pos) -{ return o == Qt::Vertical ? pos.x() : pos.y(); } - -static inline int perp(Qt::Orientation o, const QSize &size) -{ return o == Qt::Vertical ? size.width() : size.height(); } - -static inline int &rperp(Qt::Orientation o, QPoint &pos) -{ return o == Qt::Vertical ? pos.rx() : pos.ry(); } - -static inline int &rperp(Qt::Orientation o, QSize &size) -{ return o == Qt::Vertical ? size.rwidth() : size.rheight(); } - -QT_END_NAMESPACE - #endif // QDYNAMICMAINWINDOWLAYOUT_P_H diff --git a/src/gui/widgets/qtoolbararealayout.cpp b/src/gui/widgets/qtoolbararealayout.cpp index 49f4a9e..240d059 100644 --- a/src/gui/widgets/qtoolbararealayout.cpp +++ b/src/gui/widgets/qtoolbararealayout.cpp @@ -113,7 +113,7 @@ QSize QToolBarAreaLayoutLine::sizeHint() const continue; QSize sh = item.sizeHint(); - a += pick(o, sh) + item.extraSpace; + a += item.preferredSize > 0 ? item.preferredSize : pick(o, sh); b = qMax(b, perp(o, sh)); } @@ -163,12 +163,17 @@ void QToolBarAreaLayoutLine::fitLayout() int itemMin = pick(o, item.minimumSize()); int itemHint = pick(o, item.sizeHint()); //we ensure the extraspace is not too low - item.extraSpace = qMax(itemMin - itemHint, item.extraSpace); - itemHint += item.extraSpace; - int itemExtra = qMin(itemHint - itemMin, extra); + item.size = qMax(item.size, itemHint); + if (item.preferredSize > 0) { + //preferredSize would be the default size + item.size = item.preferredSize; + } + + //the extraspace is the space above the item minimum sizehint + int extraSpace = qMin(item.size - itemMin, extra); + item.size = itemMin + extraSpace; //that is the real size - item.size = itemMin + itemExtra; - extra -= itemExtra; + extra -= extraSpace; last = i; } @@ -395,17 +400,15 @@ void QToolBarAreaLayoutInfo::removeToolBarBreak(QToolBar *before) void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos) { - if (dirty) { + if (dirty) fitLayout(); - } dirty = true; - if (o == Qt::Vertical) { + if (o == Qt::Vertical) pos -= rect.top(); - } - //here we actually update the extraSpace for the line containing the toolbar so that we move it + //here we actually update the preferredSize for the line containing the toolbar so that we move it for (int j = 0; j < lines.count(); ++j) { QToolBarAreaLayoutLine &line = lines[j]; @@ -432,22 +435,21 @@ void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos) newPos = qMin(pos, maxPos); } - //let's update the previous extra space + //extra is the number of pixels to add to the previous toolbar int extra = newPos - current.pos; - if (qAbs(previous.extraSpace + extra) < QApplication::startDragDistance()) { + //we check if the previous is near its size hint + //in which case we try to stick to it + if (qAbs(pick(o, previous.sizeHint()) - (previous.size + extra)) < QApplication::startDragDistance()) { //we stick to the default space extra = 0; } //update for the current item - current.extraSpace -= extra; - //this ensures the toolbars to be pushed to the right when necessary - current.extraSpace = qMax(pick(o,current.minimumSize())- pick(o,current.sizeHint()), current.extraSpace); - - if (extra >= 0) { - previous.extraSpace += extra; + current.extendSize(line.o, -extra); + if (extra >= 0) { + previous.extendSize(line.o, extra); } else { //we need to push the toolbars on the left starting with previous extra = -extra; // we just need to know the number of pixels @@ -455,13 +457,13 @@ void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos) for(int l = previousIndex; l >=0; --l) { QToolBarAreaLayoutItem &item = line.toolBarItems[l]; if (!item.skip()) { - const int minExtraSpace = pick(o, item.minimumSize()) - pick(o, item.sizeHint()); - const int margin = item.extraSpace - minExtraSpace; + const int minPreferredSize = pick(o, item.minimumSize()); + const int margin = item.size - minPreferredSize; if (margin < extra) { - item.extraSpace = minExtraSpace; + item.resize(line.o, minPreferredSize); extra -= margin; } else { - item.extraSpace -= extra; + item.extendSize(line.o, -extra); extra = 0; } } @@ -536,13 +538,22 @@ bool QToolBarAreaLayoutInfo::insertGap(QList path, QLayoutItem *item) gap_item.gap = true; gap_item.widgetItem = item; - //update the previous item's extra space + //update the previous item's preferred size for(int p = k - 1 ; p >= 0; --p) { QToolBarAreaLayoutItem &previous = line.toolBarItems[p]; if (!previous.skip()) { //we found the previous one - gap_item.extraSpace = qMax(0, previous.extraSpace - pick(o, gap_item.sizeHint())); - previous.extraSpace = qMin(previous.extraSpace, 0); + int previousSizeHint = pick(line.o, previous.sizeHint()); + int previousExtraSpace = previous.size - previousSizeHint; + + if (previousExtraSpace > 0) { + //in this case we reset the space + previous.preferredSize = -1; + previous.size = previousSizeHint; + + gap_item.resize(o, previousExtraSpace); + } + break; } } @@ -1132,15 +1143,22 @@ QLayoutItem *QToolBarAreaLayout::unplug(QList path, QToolBarAreaLayout *oth //update the leading space here QToolBarAreaLayoutInfo &info = docks[path.at(0)]; QToolBarAreaLayoutLine &line = info.lines[path.at(1)]; - if (item.extraSpace != 0) { + if (item.size != pick(line.o, item.realSizeHint())) { + //the item doesn't have its default size + //so we'll give this to the next item int newExtraSpace = 0; + //let's iterate over the siblings of the current item that pare placed before it + //we need to find just the one before for (int i = path.at(2) - 1; i >= 0; --i) { QToolBarAreaLayoutItem &previous = line.toolBarItems[i]; if (!previous.skip()) { + //we need to check if it has a previous element and a next one + //the previous will get its size changed for (int j = path.at(2) + 1; j < line.toolBarItems.count(); ++j) { const QToolBarAreaLayoutItem &next = line.toolBarItems.at(j); if (!next.skip()) { - newExtraSpace = previous.extraSpace = next.pos - previous.pos - pick(line.o, previous.sizeHint()); + newExtraSpace = next.pos - previous.pos - pick(line.o, previous.sizeHint()); + previous.resize(line.o, next.pos - previous.pos); } break; } @@ -1154,7 +1172,7 @@ QLayoutItem *QToolBarAreaLayout::unplug(QList path, QToolBarAreaLayout *oth for (int i = path.at(2) - 1; i >= 0; --i) { QToolBarAreaLayoutItem &previous = line.toolBarItems[i]; if (!previous.skip()) { - previous.extraSpace = newExtraSpace; + previous.resize(line.o, pick(line.o, previous.sizeHint()) + newExtraSpace); break; } } @@ -1162,7 +1180,6 @@ QLayoutItem *QToolBarAreaLayout::unplug(QList path, QToolBarAreaLayout *oth } } - Q_ASSERT(!item.gap); item.gap = true; return item.widgetItem; @@ -1253,8 +1270,8 @@ void QToolBarAreaLayout::saveState(QDataStream &stream) const } stream << shownOrientation; stream << item.pos; - //if extraSpace is 0 the item has its "normal" size, so no need to store the size (we store -1) - stream << (item.extraSpace == 0 ? -1 : (pick(line.o, item.realSizeHint()) + item.extraSpace)); + //we store the preferred size. If the use rdidn't resize the toolbars it will be -1 + stream << item.preferredSize; uint geom0, geom1; packRect(&geom0, &geom1, widget->geometry(), widget->isWindow()); @@ -1339,10 +1356,7 @@ bool QToolBarAreaLayout::restoreState(QDataStream &stream, const QListsetVisible(shown & 1); toolBar->d_func()->setWindowState(floating, true, rect); - //if it is -1, it means we should use the default size - item.extraSpace = (item.size == -1) ? 0 : item.size - pick(line.o, item.realSizeHint()); - - + item.preferredSize = item.size; line.toolBarItems.append(item); } } diff --git a/src/gui/widgets/qtoolbararealayout_p.h b/src/gui/widgets/qtoolbararealayout_p.h index 574e366..5662ffc 100644 --- a/src/gui/widgets/qtoolbararealayout_p.h +++ b/src/gui/widgets/qtoolbararealayout_p.h @@ -59,6 +59,33 @@ QT_BEGIN_NAMESPACE +static inline int pick(Qt::Orientation o, const QPoint &pos) +{ return o == Qt::Horizontal ? pos.x() : pos.y(); } + +static inline int pick(Qt::Orientation o, const QSize &size) +{ return o == Qt::Horizontal ? size.width() : size.height(); } + +static inline int &rpick(Qt::Orientation o, QPoint &pos) +{ return o == Qt::Horizontal ? pos.rx() : pos.ry(); } + +static inline int &rpick(Qt::Orientation o, QSize &size) +{ return o == Qt::Horizontal ? size.rwidth() : size.rheight(); } + +static inline QSizePolicy::Policy pick(Qt::Orientation o, const QSizePolicy &policy) +{ return o == Qt::Horizontal ? policy.horizontalPolicy() : policy.verticalPolicy(); } + +static inline int perp(Qt::Orientation o, const QPoint &pos) +{ return o == Qt::Vertical ? pos.x() : pos.y(); } + +static inline int perp(Qt::Orientation o, const QSize &size) +{ return o == Qt::Vertical ? size.width() : size.height(); } + +static inline int &rperp(Qt::Orientation o, QPoint &pos) +{ return o == Qt::Vertical ? pos.rx() : pos.ry(); } + +static inline int &rperp(Qt::Orientation o, QSize &size) +{ return o == Qt::Vertical ? size.rwidth() : size.rheight(); } + #ifndef QT_NO_TOOLBAR class QToolBar; @@ -70,17 +97,41 @@ class QToolBarAreaLayoutItem { public: QToolBarAreaLayoutItem(QLayoutItem *item = 0) - : widgetItem(item), pos(0), size(-1), extraSpace(0), gap(false) {} + : widgetItem(item), pos(0), size(-1), preferredSize(-1), gap(false) {} bool skip() const; QSize minimumSize() const; QSize sizeHint() const; - QSize realSizeHint() const; + QSize realSizeHint() const; + + void resize(Qt::Orientation o, int newSize) + { + newSize = qMax(pick(o, minimumSize()), newSize); + int sizeh = pick(o, sizeHint()); + if (newSize == sizeh) { + preferredSize = -1; + size = sizeh; + } else { + preferredSize = newSize; + } + } + + void extendSize(Qt::Orientation o, int extent) + { + int newSize = qMax(pick(o, minimumSize()), (preferredSize > 0 ? preferredSize : size) + extent); + int sizeh = pick(o, sizeHint()); + if (newSize == sizeh) { + preferredSize = -1; + size = sizeh; + } else { + preferredSize = newSize; + } + } QLayoutItem *widgetItem; int pos; int size; - int extraSpace; + int preferredSize; bool gap; }; -- cgit v0.12 From 5740b034811794e0c33496cf0eeb81ba471cc018 Mon Sep 17 00:00:00 2001 From: Richard Moe Gustavsen Date: Fri, 5 Jun 2009 13:30:03 +0200 Subject: Example MDI: keybord focus not working correctly! The reason is that cocoa looses the first responder when we raise the fake window inside the MDA area. So we need to re-set the first responder again Task-number: 255040 Reviewed-by: Trenton Schulz --- src/gui/kernel/qwidget_mac.mm | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/gui/kernel/qwidget_mac.mm b/src/gui/kernel/qwidget_mac.mm index c82b87d..68eaf6f 100644 --- a/src/gui/kernel/qwidget_mac.mm +++ b/src/gui/kernel/qwidget_mac.mm @@ -3603,11 +3603,15 @@ void QWidgetPrivate::raise_sys() } } else { // Cocoa doesn't really have an idea of Z-ordering, but you can - // fake it by changing the order of it. + // fake it by changing the order of it. But beware, removing an + // NSView will also remove it as the first responder. So we re-set + // the first responder just in case: NSView *view = qt_mac_nativeview_for(q); NSView *parentView = [view superview]; + NSResponder *firstResponder = [[view window] firstResponder]; [view removeFromSuperview]; [parentView addSubview:view]; + [[view window] makeFirstResponder:firstResponder]; } #else if(q->isWindow()) { @@ -3645,6 +3649,7 @@ void QWidgetPrivate::lower_sys() NSArray *tmpViews = [parentView subviews]; NSMutableArray *subviews = [[NSMutableArray alloc] initWithCapacity:[tmpViews count]]; [subviews addObjectsFromArray:tmpViews]; + NSResponder *firstResponder = [[myview window] firstResponder]; // Implicit assumption that myViewIndex is included in subviews, that's why I'm not checking // myViewIndex. NSUInteger index = 0; @@ -3664,6 +3669,7 @@ void QWidgetPrivate::lower_sys() for (NSView *subview in subviews) [parentView addSubview:subview]; [subviews release]; + [[myview window] makeFirstResponder:firstResponder]; } #else if(q->isWindow()) { -- cgit v0.12 From a45ba34ead80d7e19e62eff571d094c9417fd876 Mon Sep 17 00:00:00 2001 From: jasplin Date: Fri, 5 Jun 2009 13:46:14 +0200 Subject: Revert "BT: Fixed crash on Mac caused by erroneous handling of native focus events." This reverts commit 7314c07a3e443b1d5349b419a03db8d41ca43f7e. As reported by Eike, this patch caused several problems for Qt Creator. Potentially it may cause problems for other (external) applications as well. An alternative fix (scheduled for 4.5.x) needs to be found for tasks 254456 and 254460. Reviewed-by: Richard Moe Gustavsen --- src/gui/kernel/qwidget_mac.mm | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/gui/kernel/qwidget_mac.mm b/src/gui/kernel/qwidget_mac.mm index 68eaf6f..b2256cd 100644 --- a/src/gui/kernel/qwidget_mac.mm +++ b/src/gui/kernel/qwidget_mac.mm @@ -1296,11 +1296,8 @@ OSStatus QWidgetPrivate::qt_widget_event(EventHandlerCallRef er, EventRef event, if(part == kControlFocusNoPart){ if (widget->hasFocus()) QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason); - } else if (widget->focusPolicy() != Qt::NoFocus) { + } else widget->setFocus(); - } else { - handled_event = false; - } } if(!HIObjectIsOfClass((HIObjectRef)hiview, kObjectQWidget)) CallNextEventHandler(er, event); -- cgit v0.12 From 4acabb3abd0ff109b9abeedb6832f5b1c3e0cc4e Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 5 Jun 2009 13:05:24 +0200 Subject: handle qreal properties correctly in the meta-object system When cross-compiling, it's possible that the size of qreal for moc itself (host platform) is different from the size of qreal on the target platform. Thus, we should not encode the metatype-id of qreal at moc time. Instead, use QMetaType::QReal in the generated code so that the the property flags are only derived at compile time. We also need to support the pesky QT_COORD_TYPE. In this case, qreal can be _any_ type (not just float or double), so we encode the property type as 0 and have a special check in QMetaProperty::type() that resolves the correct type at runtime. Reviewed-by: Simon Hausmann --- src/corelib/global/qglobal.h | 1 + src/corelib/kernel/qmetaobject.cpp | 5 +++++ src/corelib/kernel/qmetatype.cpp | 1 + src/corelib/kernel/qmetatype.h | 9 +++++++++ src/corelib/kernel/qobjectdefs.h | 2 +- src/tools/moc/generator.cpp | 20 +++++++++++++++----- src/tools/moc/outputrevision.h | 2 +- tests/auto/qobject/tst_qobject.cpp | 27 +++++++++++++++++++++++++++ 8 files changed, 60 insertions(+), 7 deletions(-) diff --git a/src/corelib/global/qglobal.h b/src/corelib/global/qglobal.h index 3990c7d..a10b6d6 100644 --- a/src/corelib/global/qglobal.h +++ b/src/corelib/global/qglobal.h @@ -1004,6 +1004,7 @@ typedef int QNoImplicitBoolCast; #define QT_NO_FPU #endif +// This logic must match the one in qmetatype.h #if defined(QT_COORD_TYPE) typedef QT_COORD_TYPE qreal; #elif defined(QT_NO_FPU) || defined(QT_ARCH_ARM) || defined(QT_ARCH_WINDOWSCE) diff --git a/src/corelib/kernel/qmetaobject.cpp b/src/corelib/kernel/qmetaobject.cpp index b65f956..6f3316c 100644 --- a/src/corelib/kernel/qmetaobject.cpp +++ b/src/corelib/kernel/qmetaobject.cpp @@ -2003,6 +2003,11 @@ QVariant::Type QMetaProperty::type() const if (enumMetaTypeId == 0) return QVariant::Int; } +#ifdef QT_COORD_TYPE + // qreal metatype must be resolved at runtime. + if (strcmp(typeName(), "qreal") == 0) + return QVariant::Type(qMetaTypeId()); +#endif return QVariant::UserType; } diff --git a/src/corelib/kernel/qmetatype.cpp b/src/corelib/kernel/qmetatype.cpp index ce10bae..a0b954f 100644 --- a/src/corelib/kernel/qmetatype.cpp +++ b/src/corelib/kernel/qmetatype.cpp @@ -179,6 +179,7 @@ QT_BEGIN_NAMESPACE \omitvalue LastCoreExtType \omitvalue LastCoreType \omitvalue LastGuiType + \omitvalue QReal Additional types can be registered using Q_DECLARE_METATYPE(). diff --git a/src/corelib/kernel/qmetatype.h b/src/corelib/kernel/qmetatype.h index 648f933..be8a667 100644 --- a/src/corelib/kernel/qmetatype.h +++ b/src/corelib/kernel/qmetatype.h @@ -86,6 +86,15 @@ public: UShort = 133, UChar = 134, Float = 135, QObjectStar = 136, QWidgetStar = 137, LastCoreExtType = 137 /* QWidgetStar */, +// This logic must match the one in qglobal.h +#if defined(QT_COORD_TYPE) + QReal = 0, +#elif defined(QT_NO_FPU) || defined(QT_ARCH_ARM) || defined(QT_ARCH_WINDOWSCE) + QReal = Float, +#else + QReal = Double, +#endif + User = 256 }; diff --git a/src/corelib/kernel/qobjectdefs.h b/src/corelib/kernel/qobjectdefs.h index 3a22323..f5d08ce 100644 --- a/src/corelib/kernel/qobjectdefs.h +++ b/src/corelib/kernel/qobjectdefs.h @@ -55,7 +55,7 @@ class QByteArray; class QString; #ifndef Q_MOC_OUTPUT_REVISION -#define Q_MOC_OUTPUT_REVISION 61 +#define Q_MOC_OUTPUT_REVISION 62 #endif // The following macros are our "extensions" to C++ diff --git a/src/tools/moc/generator.cpp b/src/tools/moc/generator.cpp index e94bb77..e4ad068 100644 --- a/src/tools/moc/generator.cpp +++ b/src/tools/moc/generator.cpp @@ -109,6 +109,14 @@ bool isVariantType(const char* type) return qvariant_nameToType(type) != 0; } +/*! + Returns true if the type is qreal. +*/ +static bool isQRealType(const char *type) +{ + return strcmp(type, "qreal") == 0; +} + Generator::Generator(ClassDef *classDef, const QList &metaTypes, FILE *outfile) : out(outfile), cdef(classDef), metaTypes(metaTypes) { @@ -545,7 +553,7 @@ void Generator::generateProperties() uint flags = Invalid; if (!isVariantType(p.type)) { flags |= EnumOrFlag; - } else { + } else if (!isQRealType(p.type)) { flags |= qvariant_nameToType(p.type) << 24; } if (!p.read.isEmpty()) @@ -589,10 +597,12 @@ void Generator::generateProperties() if (p.notifyId != -1) flags |= Notify; - fprintf(out, " %4d, %4d, 0x%.8x,\n", - strreg(p.name), - strreg(p.type), - flags); + fprintf(out, " %4d, %4d, ", + strreg(p.name), + strreg(p.type)); + if (!(flags >> 24) && isQRealType(p.type)) + fprintf(out, "(QMetaType::QReal << 24) | "); + fprintf(out, "0x%.8x,\n", flags); } if(cdef->notifyableProperties) { diff --git a/src/tools/moc/outputrevision.h b/src/tools/moc/outputrevision.h index 1e1d640..f577f6c 100644 --- a/src/tools/moc/outputrevision.h +++ b/src/tools/moc/outputrevision.h @@ -43,6 +43,6 @@ #define OUTPUTREVISION_H // if the output revision changes, you MUST change it in qobjectdefs.h too -enum { mocOutputRevision = 61 }; // moc format output revision +enum { mocOutputRevision = 62 }; // moc format output revision #endif // OUTPUTREVISION_H diff --git a/tests/auto/qobject/tst_qobject.cpp b/tests/auto/qobject/tst_qobject.cpp index 399d021..d76c7d4 100644 --- a/tests/auto/qobject/tst_qobject.cpp +++ b/tests/auto/qobject/tst_qobject.cpp @@ -106,6 +106,7 @@ private slots: void childDeletesItsSibling(); void dynamicProperties(); void floatProperty(); + void qrealProperty(); void property(); void recursiveSignalEmission(); void blockingQueuedConnection(); @@ -1113,6 +1114,7 @@ class PropertyObject : public QObject Q_PROPERTY(QVariant variant READ variant WRITE setVariant) Q_PROPERTY(CustomType* custom READ custom WRITE setCustom) Q_PROPERTY(float myFloat READ myFloat WRITE setMyFloat) + Q_PROPERTY(qreal myQReal READ myQReal WRITE setMyQReal) public: enum Alpha { @@ -1148,6 +1150,9 @@ public: void setMyFloat(float value) { m_float = value; } inline float myFloat() const { return m_float; } + void setMyQReal(qreal value) { m_qreal = value; } + qreal myQReal() const { return m_qreal; } + private: Alpha m_alpha; Priority m_priority; @@ -1156,6 +1161,7 @@ private: QVariant m_variant; CustomType *m_custom; float m_float; + qreal m_qreal; }; Q_DECLARE_METATYPE(PropertyObject::Priority) @@ -2348,6 +2354,27 @@ void tst_QObject::floatProperty() QVERIFY(qVariantValue(v) == 128.0f); } +void tst_QObject::qrealProperty() +{ + PropertyObject obj; + const int idx = obj.metaObject()->indexOfProperty("myQReal"); + QVERIFY(idx > 0); + QMetaProperty prop = obj.metaObject()->property(idx); + QVERIFY(prop.isValid()); + QVERIFY(prop.type() == uint(QMetaType::type("qreal"))); + QVERIFY(!prop.write(&obj, QVariant("Hello"))); + + QVERIFY(prop.write(&obj, qVariantFromValue(128.0f))); + QVariant v = prop.read(&obj); + QCOMPARE(v.userType(), qMetaTypeId()); + QVERIFY(qVariantValue(v) == 128.0); + + QVERIFY(prop.write(&obj, qVariantFromValue(double(127)))); + v = prop.read(&obj); + QCOMPARE(v.userType(), qMetaTypeId()); + QVERIFY(qVariantValue(v) == 127.0); +} + class DynamicPropertyObject : public PropertyObject { public: -- cgit v0.12 From 5455f9c7a3ec8ed591666a2f4384c10de31f6a60 Mon Sep 17 00:00:00 2001 From: Thomas Hartmann Date: Fri, 5 Jun 2009 14:06:03 +0200 Subject: My changes for 4.5.2 --- dist/changes-4.5.2 | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 5de0dbe..84460e3 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -210,7 +210,9 @@ Qt for Embedded Linux Qt for Windows CE ----------------- -[248846] handle the back soft key on Windows mobile. +[248846] Handle the back soft key on Windows mobile. +[252319] Fix regression in native menu integration. +[242484] Fixed crash if Qt::WindowCancelButtonHint is used for a QDialog **************************************************************************** -- cgit v0.12 From a468e2f12536600abff582e8770ec42e1782bdab Mon Sep 17 00:00:00 2001 From: Norwegian Rock Cat Date: Fri, 5 Jun 2009 10:13:16 +0200 Subject: Add a callback so Qt updates its color stuff when the profile changes. We've had a problem with a stale cache for color profiles this should make things work well. We get the callback for each display whether it needs it or not, but honesly I would rather that we update this a few times too many when people change their display profile than not at all. FWIW, this code is inspired from Apple's Tech Note TN2035. --- src/gui/kernel/qapplication_mac.mm | 28 ++++++++++++++++++++++++++++ src/gui/painting/qpaintengine_mac_p.h | 2 ++ 2 files changed, 30 insertions(+) diff --git a/src/gui/kernel/qapplication_mac.mm b/src/gui/kernel/qapplication_mac.mm index d5fa9ea..6a592e4 100644 --- a/src/gui/kernel/qapplication_mac.mm +++ b/src/gui/kernel/qapplication_mac.mm @@ -154,6 +154,10 @@ #define kThemeBrushAlternatePrimaryHighlightColor -5 #endif +#define kCMDeviceUnregisteredNotification CFSTR("CMDeviceUnregisteredNotification") +#define kCMDefaultDeviceNotification CFSTR("CMDefaultDeviceNotification") +#define kCMDeviceProfilesNotification CFSTR("CMDeviceProfilesNotification") +#define kCMDefaultDeviceProfileNotification CFSTR("CMDefaultDeviceProfileNotification") QT_BEGIN_NAMESPACE @@ -1040,11 +1044,29 @@ void qt_release_app_proc_handler() #endif } +void qt_color_profile_changed(CFNotificationCenterRef, void *, CFStringRef, const void *, + CFDictionaryRef) +{ + QCoreGraphicsPaintEngine::cleanUpMacColorSpaces(); +} /* platform specific implementations */ void qt_init(QApplicationPrivate *priv, int) { if (qt_is_gui_used) { CGDisplayRegisterReconfigurationCallback(qt_mac_display_change_callbk, 0); + CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter(); + CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed, + kCMDeviceUnregisteredNotification, 0, + CFNotificationSuspensionBehaviorDeliverImmediately); + CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed, + kCMDefaultDeviceNotification, 0, + CFNotificationSuspensionBehaviorDeliverImmediately); + CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed, + kCMDeviceProfilesNotification, 0, + CFNotificationSuspensionBehaviorDeliverImmediately); + CFNotificationCenterAddObserver(center, qApp, qt_color_profile_changed, + kCMDefaultDeviceProfileNotification, 0, + CFNotificationSuspensionBehaviorDeliverImmediately); ProcessSerialNumber psn; if (GetCurrentProcess(&psn) == noErr) { // Jambi needs to transform itself since most people aren't "used" @@ -1224,6 +1246,12 @@ void qt_release_apple_event_handler() void qt_cleanup() { CGDisplayRemoveReconfigurationCallback(qt_mac_display_change_callbk, 0); + CFNotificationCenterRef center = CFNotificationCenterGetDistributedCenter(); + CFNotificationCenterRemoveObserver(center, qApp, kCMDeviceUnregisteredNotification, 0); + CFNotificationCenterRemoveObserver(center, qApp, kCMDefaultDeviceNotification, 0); + CFNotificationCenterRemoveObserver(center, qApp, kCMDeviceProfilesNotification, 0); + CFNotificationCenterRemoveObserver(center, qApp, kCMDefaultDeviceProfileNotification, 0); + #ifndef QT_MAC_USE_COCOA qt_release_app_proc_handler(); if (app_proc_handlerUPP) { diff --git a/src/gui/painting/qpaintengine_mac_p.h b/src/gui/painting/qpaintengine_mac_p.h index 298c145..9b85800 100644 --- a/src/gui/painting/qpaintengine_mac_p.h +++ b/src/gui/painting/qpaintengine_mac_p.h @@ -233,6 +233,8 @@ protected: friend class QMacPrintEngine; friend class QMacPrintEnginePrivate; friend void qt_mac_display_change_callbk(CGDirectDisplayID, CGDisplayChangeSummaryFlags, void *); + friend void qt_color_profile_changed(CFNotificationCenterRef center, void *, + CFStringRef , const void *, CFDictionaryRef); QCoreGraphicsPaintEngine(QPaintEnginePrivate &dptr); private: -- cgit v0.12 From 2ddf5be9627b7c93729838522bb37f47f41a6435 Mon Sep 17 00:00:00 2001 From: jasplin Date: Fri, 5 Jun 2009 14:31:39 +0200 Subject: Fixed compile error with Sun CC 5.5. Reviewed-by: TrustMe --- examples/animation/stickman/node.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/animation/stickman/node.h b/examples/animation/stickman/node.h index 72eae87..8654144 100644 --- a/examples/animation/stickman/node.h +++ b/examples/animation/stickman/node.h @@ -47,7 +47,7 @@ class Node: public QObject, public QGraphicsItem { Q_OBJECT - Q_PROPERTY(QPointF position READ pos WRITE setPos); + Q_PROPERTY(QPointF position READ pos WRITE setPos) public: Node(const QPointF &pos, QGraphicsItem *parent = 0); ~Node(); -- cgit v0.12 From 2734d8fa8c26c8498091348305b2616ecacfad85 Mon Sep 17 00:00:00 2001 From: jasplin Date: Fri, 5 Jun 2009 15:01:16 +0200 Subject: My changes for 4.5.2. --- dist/changes-4.5.2 | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 84460e3..1984881 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -59,6 +59,10 @@ Third party components - QAbstractNetworkCache * Only cache responses to HTTP GET by default, not HTTP PUT or POST +- QApplication + * [249589] Fixed bug that prevented any part of the application to receive + focus when Graphics View was disabled using QT_NO_GRAPHICSVIEW. + - QComboBox * [253944] Changing the style doesn't reset custom item delegate anymore. * [254589] Fixed the frame appearing if setting a stylesheet with a border @@ -88,6 +92,9 @@ Third party components - QFontDialog * [252000] Ensure that QFontDialog::getFont() works on Mac OS X. +- QGraphicsWidget + * Fixed a bug with Qt::WidgetWithChildren shortcut context. + - QLocalSocket * [247144] correctly handle remote disconnects @@ -107,6 +114,10 @@ Third party components * [253448] Prevent a crash when using the Qt::WA_MacBrushedMetal attribute in conjunction with style sheets. +- QWizard + * [252662] Fixed crash that could happen when compiling on Windows XP and + running on older Windows versions like 98 and 2000. + - QObject * Fixed possible race condition if two QObject connected together with signals and slot are destroyed in different threads @@ -121,6 +132,9 @@ Third party components * [251534] Fixed issue where text with non-opaque color from widget palette would be blitted instead of blended. +- QProgressBar + * [252283] Fixed busy indicator for a QProgressBar with a style sheet applied to it. + - QSelectionModel * [252069] fix QSelectionModel::rowIntersectsSelection or QSelectionModel::columnsIntersectsSelection not reporting right result if some items are disabled. @@ -135,6 +149,10 @@ Third party components - QString * Fixed reentrency of QString::squeeze() +- QTabBar + * [252472] Fixed problem with the current tab not being visible after calling + setTabButton() on a scrolled tab bar. + - QTransform * Fixed issue in QTransform::type() causing a projective transform to be treated as a scaling transform. -- cgit v0.12 From 65f6422401f7dfeb5f3a7fcc3791528b4cf2cee4 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 5 Jun 2009 15:34:32 +0200 Subject: kill dead code --- src/script/qscriptextqobject.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/script/qscriptextqobject.cpp b/src/script/qscriptextqobject.cpp index 4522807..0a346f0 100644 --- a/src/script/qscriptextqobject.cpp +++ b/src/script/qscriptextqobject.cpp @@ -1883,8 +1883,6 @@ void QScript::QtFunction::execute(QScriptContextPrivate *context) return; } - QScriptValueImpl result = eng_p->undefinedValue(); - const QMetaObject *meta = qobj->metaObject(); QObject *thisQObject = context->thisObject().toQObject(); -- cgit v0.12 From f6fc34ea5b247d1b56e113663958176b095a58a6 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 5 Jun 2009 15:44:24 +0200 Subject: Doc - fixed a typo Reviewed-By: TrustMe --- doc/src/tutorials/addressbook.qdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc index 4ab549a..e5657e7 100644 --- a/doc/src/tutorials/addressbook.qdoc +++ b/doc/src/tutorials/addressbook.qdoc @@ -529,7 +529,7 @@ \example tutorials/addressbook/part4 \title Address Book 4 - Editing and Removing Addresses - In this chapter, we look at ways to modify the contents of contact stored + In this chapter, we look at ways to modify the contents of contacts stored in the address book application. \image addressbook-tutorial-screenshot.png -- cgit v0.12 From 407a77cb2660cf122b08a388216f3a2da8cfd1c3 Mon Sep 17 00:00:00 2001 From: Thomas Hartmann Date: Fri, 5 Jun 2009 15:40:17 +0200 Subject: Fixes anti-aliased text rendering on smartphones (Windows Mobile) The check for cleartype in qt_win_read_cleartype_settings() was not correct for Windows Mobile For anti-aliased text rendering we also have to use another pixel format for the native image. Task-number: 249642 Reviewed-by: mauricek --- src/gui/kernel/qapplication_win.cpp | 8 ++++++++ src/gui/text/qfontengine_win.cpp | 8 ++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 60f3edf..b21eb36 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -625,6 +625,13 @@ static void qt_set_windows_font_resources() static void qt_win_read_cleartype_settings() { +#ifdef Q_OS_WINCE + UINT result; + BOOL ok; + ok = SystemParametersInfo(SPI_GETFONTSMOOTHING, 0, &result, 0); + if (ok) + qt_cleartype_enabled = result; +#else QT_WA({ UINT result; BOOL ok; @@ -638,6 +645,7 @@ static void qt_win_read_cleartype_settings() if (ok) qt_cleartype_enabled = (result == FE_FONTSMOOTHINGCLEARTYPE); }); +#endif } diff --git a/src/gui/text/qfontengine_win.cpp b/src/gui/text/qfontengine_win.cpp index 002e670..d172a81 100644 --- a/src/gui/text/qfontengine_win.cpp +++ b/src/gui/text/qfontengine_win.cpp @@ -1333,6 +1333,7 @@ bool QFontEngineWin::getSfntTableData(uint tag, uchar *buffer, uint *length) con # define CLEARTYPE_QUALITY 5 #endif +extern bool qt_cleartype_enabled; QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin, const QTransform &t) @@ -1408,7 +1409,11 @@ QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin QNativeImage *ni = new QNativeImage(iw + 2 * margin + 4, ih + 2 * margin + 4, - QNativeImage::systemFormat(), true); + QNativeImage::systemFormat(), !qt_cleartype_enabled); + + /*If cleartype is enabled we use the standard system format even on Windows CE + and not the special textbuffer format we have to use if cleartype is disabled*/ + ni->image.fill(0xffffffff); HDC hdc = ni->hdc; @@ -1437,7 +1442,6 @@ QNativeImage *QFontEngineWin::drawGDIGlyph(HFONT font, glyph_t glyph, int margin } -extern bool qt_cleartype_enabled; extern uint qt_pow_gamma[256]; QImage QFontEngineWin::alphaMapForGlyph(glyph_t glyph, const QTransform &xform) -- cgit v0.12 From 1ad2cba32bc34786cdfd92ad16e3212b8830be3d Mon Sep 17 00:00:00 2001 From: Thomas Hartmann Date: Fri, 5 Jun 2009 15:43:31 +0200 Subject: Compilefix for QT_NO_CURSOR in qgraphicsscene.cpp Reviewed-by: Joerg --- src/gui/graphicsview/qgraphicsscene.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 1fc4567..49c2329 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -2924,11 +2924,13 @@ void QGraphicsScene::addItem(QGraphicsItem *item) d->allItemsIgnoreHoverEvents = false; d->enableMouseTrackingOnViews(); } +#ifndef QT_NO_CURSOR if (d->allItemsUseDefaultCursor && item->hasCursor()) { d->allItemsUseDefaultCursor = false; if (d->allItemsIgnoreHoverEvents) // already enabled otherwise d->enableMouseTrackingOnViews(); } +#endif //QT_NO_CURSOR // Update selection lists if (item->isSelected()) -- cgit v0.12 From 4515b690829a639283a9b660893ff3f0f7ff598b Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 5 Jun 2009 15:59:59 +0200 Subject: Doc - fixed another typo Reviewed-By: TrustMe --- doc/src/tutorials/addressbook.qdoc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc index e5657e7..4de334d 100644 --- a/doc/src/tutorials/addressbook.qdoc +++ b/doc/src/tutorials/addressbook.qdoc @@ -539,7 +539,7 @@ edit and remove functions so that a contact's details can be changed when needed. However, this requires a little improvement, in the form of enums. In our previous chapters, we had two modes: \c{AddingMode} and - \c{NavigationMode} - but they weren't defined as enums. Instead, we + \c{NavigationMode} - but they were not defined as enums. Instead, we enabled and disabled the corresponding buttons manually, resulting in multiple lines of repeated code. -- cgit v0.12 From b59d84fe67caedeb8c11d2530ddee2017a376920 Mon Sep 17 00:00:00 2001 From: Kavindra Devi Palaraja Date: Fri, 5 Jun 2009 16:31:24 +0200 Subject: Doc - fixed a typo Reviewed-By: TrustMe --- doc/src/tutorials/addressbook.qdoc | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/doc/src/tutorials/addressbook.qdoc b/doc/src/tutorials/addressbook.qdoc index 4de334d..9a1af85 100644 --- a/doc/src/tutorials/addressbook.qdoc +++ b/doc/src/tutorials/addressbook.qdoc @@ -573,8 +573,7 @@ \dots \snippet tutorials/addressbook/part4/addressbook.h mode declaration - Lastly, we declare \c currentMode to keep track of the current mode of the - enum. + Lastly, we declare \c currentMode to keep track of the enum's current mode. \section1 Implementing the AddressBook Class -- cgit v0.12 From 100b55e4ddc9e4846ab877ea670473e2a9ed641e Mon Sep 17 00:00:00 2001 From: Peter Hartmann Date: Tue, 10 Mar 2009 17:35:17 +0100 Subject: add HTTP DELETE support to Network Access API added new method QNetworkAccessManager::deleteResource (naming the method "delete" was not possible since it is a reserverd word in C++) and adjusted all the internals necessary. Task-number: 242916 Reviewed-by: Thiago --- src/network/access/qnetworkaccesshttpbackend.cpp | 10 +++ src/network/access/qnetworkaccessmanager.cpp | 19 ++++- src/network/access/qnetworkaccessmanager.h | 2 + tests/auto/qnetworkreply/tst_qnetworkreply.cpp | 99 ++++++++++++++++++++++++ 4 files changed, 128 insertions(+), 2 deletions(-) diff --git a/src/network/access/qnetworkaccesshttpbackend.cpp b/src/network/access/qnetworkaccesshttpbackend.cpp index bd364cb..7517000 100644 --- a/src/network/access/qnetworkaccesshttpbackend.cpp +++ b/src/network/access/qnetworkaccesshttpbackend.cpp @@ -212,6 +212,7 @@ QNetworkAccessHttpBackendFactory::create(QNetworkAccessManager::Operation op, case QNetworkAccessManager::PostOperation: case QNetworkAccessManager::HeadOperation: case QNetworkAccessManager::PutOperation: + case QNetworkAccessManager::DeleteOperation: break; default: @@ -244,6 +245,10 @@ static QNetworkReply::NetworkError statusCodeFromHttp(int httpStatusCode, const code = QNetworkReply::ContentNotFoundError; break; + case 405: // Method Not Allowed + code = QNetworkReply::ContentOperationNotPermittedError; + break; + case 407: code = QNetworkReply::ProxyAuthenticationRequiredError; break; @@ -485,6 +490,11 @@ void QNetworkAccessHttpBackend::postRequest() httpRequest.setUploadByteDevice(createUploadByteDevice()); break; + case QNetworkAccessManager::DeleteOperation: + invalidateCache(); + httpRequest.setOperation(QHttpNetworkRequest::Delete); + break; + default: break; // can't happen } diff --git a/src/network/access/qnetworkaccessmanager.cpp b/src/network/access/qnetworkaccessmanager.cpp index bf06ede..7ca5f78 100644 --- a/src/network/access/qnetworkaccessmanager.cpp +++ b/src/network/access/qnetworkaccessmanager.cpp @@ -148,6 +148,9 @@ static void ensureInitialized() \value PostOperation send the contents of an HTML form for processing via HTTP POST (created with post()) + \value DeleteOperation delete contents operation (created with + deleteResource()) + \omitvalue UnknownOperation \sa QNetworkReply::operation() @@ -555,7 +558,7 @@ QNetworkReply *QNetworkAccessManager::head(const QNetworkRequest &request) a new QNetworkReply object opened for reading which emits its QIODevice::readyRead() signal whenever new data arrives. - \sa post(), put() + \sa post(), put(), deleteResource() */ QNetworkReply *QNetworkAccessManager::get(const QNetworkRequest &request) { @@ -577,7 +580,7 @@ QNetworkReply *QNetworkAccessManager::get(const QNetworkRequest &request) Note: sending a POST request on protocols other than HTTP and HTTPS is undefined and will probably fail. - \sa get(), put() + \sa get(), put(), deleteResource() */ QNetworkReply *QNetworkAccessManager::post(const QNetworkRequest &request, QIODevice *data) { @@ -642,6 +645,18 @@ QNetworkReply *QNetworkAccessManager::put(const QNetworkRequest &request, const } /*! + This function is used to send a request to delete the resource + identified by the URL of \a request. + This feature is currently available for HTTP only, performing an HTTP DELETE request. + + \sa get(), post(), put() +*/ +QNetworkReply *QNetworkAccessManager::deleteResource(const QNetworkRequest &request) +{ + return d_func()->postProcess(createRequest(QNetworkAccessManager::DeleteOperation, request)); +} + +/*! Returns a new QNetworkReply object to handle the operation \a op and request \a req. The device \a outgoingData is always 0 for Get and Head requests, but is the value passed to post() and put() in diff --git a/src/network/access/qnetworkaccessmanager.h b/src/network/access/qnetworkaccessmanager.h index 4fe218e..79f512c 100644 --- a/src/network/access/qnetworkaccessmanager.h +++ b/src/network/access/qnetworkaccessmanager.h @@ -74,6 +74,7 @@ public: GetOperation, PutOperation, PostOperation, + DeleteOperation, UnknownOperation = 0 }; @@ -100,6 +101,7 @@ public: QNetworkReply *post(const QNetworkRequest &request, const QByteArray &data); QNetworkReply *put(const QNetworkRequest &request, QIODevice *data); QNetworkReply *put(const QNetworkRequest &request, const QByteArray &data); + QNetworkReply *deleteResource(const QNetworkRequest &request); Q_SIGNALS: #ifndef QT_NO_NETWORKPROXY diff --git a/tests/auto/qnetworkreply/tst_qnetworkreply.cpp b/tests/auto/qnetworkreply/tst_qnetworkreply.cpp index b76a4e6..43b4ea9 100644 --- a/tests/auto/qnetworkreply/tst_qnetworkreply.cpp +++ b/tests/auto/qnetworkreply/tst_qnetworkreply.cpp @@ -161,6 +161,10 @@ private Q_SLOTS: void putToHttp(); void postToHttp_data(); void postToHttp(); + void deleteFromHttp_data(); + void deleteFromHttp(); + void putGetDeleteGetFromHttp_data(); + void putGetDeleteGetFromHttp(); void ioGetFromData_data(); void ioGetFromData(); @@ -903,6 +907,10 @@ QString tst_QNetworkReply::runSimpleRequest(QNetworkAccessManager::Operation op, reply = manager.post(request, data); break; + case QNetworkAccessManager::DeleteOperation: + reply = manager.deleteResource(request); + break; + default: Q_ASSERT_X(false, "tst_QNetworkReply", "Invalid/unknown operation requested"); } @@ -1478,6 +1486,97 @@ void tst_QNetworkReply::postToHttp() QCOMPARE(uploadedData, md5sum.toHex()); } +void tst_QNetworkReply::deleteFromHttp_data() +{ + QTest::addColumn("url"); + QTest::addColumn("resultCode"); + QTest::addColumn("error"); + + // for status codes to expect, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html + + QTest::newRow("405-method-not-allowed") << QUrl("http://" + QtNetworkSettings::serverName() + "/index.html") << 405 << QNetworkReply::ContentOperationNotPermittedError; + QTest::newRow("200-ok") << QUrl("http://" + QtNetworkSettings::serverName() + "/cgi-bin/http-delete.cgi?200-ok") << 200 << QNetworkReply::NoError; + QTest::newRow("202-accepted") << QUrl("http://" + QtNetworkSettings::serverName() + "/cgi-bin/http-delete.cgi?202-accepted") << 202 << QNetworkReply::NoError; + QTest::newRow("204-no-content") << QUrl("http://" + QtNetworkSettings::serverName() + "/cgi-bin/http-delete.cgi?204-no-content") << 204 << QNetworkReply::NoError; + QTest::newRow("404-not-found") << QUrl("http://" + QtNetworkSettings::serverName() + "/cgi-bin/http-delete.cgi?404-not-found") << 404 << QNetworkReply::ContentNotFoundError; +} + +void tst_QNetworkReply::deleteFromHttp() +{ + QFETCH(QUrl, url); + QFETCH(int, resultCode); + QFETCH(QNetworkReply::NetworkError, error); + QNetworkRequest request(url); + QNetworkReplyPtr reply; + runSimpleRequest(QNetworkAccessManager::DeleteOperation, request, reply, 0); + QCOMPARE(reply->url(), url); + QCOMPARE(reply->error(), error); + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), resultCode); +} + +void tst_QNetworkReply::putGetDeleteGetFromHttp_data() +{ + QTest::addColumn("putUrl"); + QTest::addColumn("putResultCode"); + QTest::addColumn("putError"); + QTest::addColumn("deleteUrl"); + QTest::addColumn("deleteResultCode"); + QTest::addColumn("deleteError"); + QTest::addColumn("get2Url"); + QTest::addColumn("get2ResultCode"); + QTest::addColumn("get2Error"); + + QUrl url("http://" + QtNetworkSettings::serverName()); + url.setPath(QString("/dav/qnetworkaccess-putToHttp-%1-%2") + .arg(QTest::currentDataTag()) + .arg(uniqueExtension)); + + // first use case: put, get (to check it is there), delete, get (to check it is not there anymore) + QTest::newRow("success") << url << 201 << QNetworkReply::NoError << url << 204 << QNetworkReply::NoError << url << 404 << QNetworkReply::ContentNotFoundError; + + QUrl wrongUrl("http://" + QtNetworkSettings::serverName()); + wrongUrl.setPath(QString("/dav/qnetworkaccess-thisURLisNotAvailable")); + + // second use case: put, get (to check it is there), delete wrong URL, get (to check it is still there) + QTest::newRow("delete-error") << url << 201 << QNetworkReply::NoError << wrongUrl << 404 << QNetworkReply::ContentNotFoundError << url << 200 << QNetworkReply::NoError; + +} + +void tst_QNetworkReply::putGetDeleteGetFromHttp() +{ + QFETCH(QUrl, putUrl); + QFETCH(int, putResultCode); + QFETCH(QNetworkReply::NetworkError, putError); + QFETCH(QUrl, deleteUrl); + QFETCH(int, deleteResultCode); + QFETCH(QNetworkReply::NetworkError, deleteError); + QFETCH(QUrl, get2Url); + QFETCH(int, get2ResultCode); + QFETCH(QNetworkReply::NetworkError, get2Error); + + QNetworkRequest putRequest(putUrl); + QNetworkRequest deleteRequest(deleteUrl); + QNetworkRequest get2Request(get2Url); + QNetworkReplyPtr reply; + + RUN_REQUEST(runSimpleRequest(QNetworkAccessManager::PutOperation, putRequest, reply, 0)); + QCOMPARE(reply->error(), putError); + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), putResultCode); + + runSimpleRequest(QNetworkAccessManager::GetOperation, putRequest, reply, 0); + QCOMPARE(reply->error(), QNetworkReply::NoError); + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), 200); + + runSimpleRequest(QNetworkAccessManager::DeleteOperation, deleteRequest, reply, 0); + QCOMPARE(reply->error(), deleteError); + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), deleteResultCode); + + runSimpleRequest(QNetworkAccessManager::GetOperation, get2Request, reply, 0); + QCOMPARE(reply->error(), get2Error); + QCOMPARE(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(), get2ResultCode); + +} + void tst_QNetworkReply::ioGetFromData_data() { QTest::addColumn("urlStr"); -- cgit v0.12 From 0302c0103da731b7af8d749b1643c50e39d81c00 Mon Sep 17 00:00:00 2001 From: Peter Hartmann Date: Fri, 5 Jun 2009 16:35:37 +0200 Subject: QNetworkAccessManager: forgot the "since" tag in my previous commit Reviewed-by: trustMe --- src/network/access/qnetworkaccessmanager.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/network/access/qnetworkaccessmanager.cpp b/src/network/access/qnetworkaccessmanager.cpp index 7ca5f78..024f191 100644 --- a/src/network/access/qnetworkaccessmanager.cpp +++ b/src/network/access/qnetworkaccessmanager.cpp @@ -645,6 +645,8 @@ QNetworkReply *QNetworkAccessManager::put(const QNetworkRequest &request, const } /*! + \since 4.6 + This function is used to send a request to delete the resource identified by the URL of \a request. This feature is currently available for HTTP only, performing an HTTP DELETE request. -- cgit v0.12 From ff9497f82d605688453e2f027bab7c719048f0d2 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Fri, 5 Jun 2009 15:38:44 +0200 Subject: Revert two of my commits, restoring the original fix for focus handling. The fix that was introduced adds regressions, and I don't see a way we can fix it without breaking someone elses code. So restoring the original fix that just avoid a crash (autotest by Thierry is included). Revert "Revert Avoid a crash when setting a focus in a widget hierarchy containing" Revert "Setting a focus on a widget hierarchy which contains both visible and invisible widgets could cause a crash." This reverts commit be833a4f25a8ec8c3dd7a8ac4fa4b0507c93e7ee. This partially reverts commit 1a7da7096bbda17197738061902f4489af234bc0 Reviewed-by: Thierry Bastian Reviewed-by: Prasanth Ullattil --- src/gui/kernel/qwidget.cpp | 16 ++++------------ tests/auto/qwidget/tst_qwidget.cpp | 18 ------------------ 2 files changed, 4 insertions(+), 30 deletions(-) diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index d436ffb..6026821 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -5674,15 +5674,10 @@ void QWidget::setFocus(Qt::FocusReason reason) w = w->isWindow() ? 0 : w->parentWidget(); } } else { - while (w && w->isVisible()) { + while (w) { w->d_func()->focus_child = f; w = w->isWindow() ? 0 : w->parentWidget(); } - // a special case, if there is an invisible parent, notify him - // about the focus_child widget, so that if it becomes - // visible, the focus widget will be respected. - if (w) - w->d_func()->focus_child = f; } #ifndef QT_NO_GRAPHICSVIEW @@ -5757,8 +5752,9 @@ void QWidget::setFocus(Qt::FocusReason reason) void QWidget::clearFocus() { QWidget *w = this; - while (w && w->d_func()->focus_child == this) { - w->d_func()->focus_child = 0; + while (w) { + if (w->d_func()->focus_child == this) + w->d_func()->focus_child = 0; w = w->parentWidget(); } #ifndef QT_NO_GRAPHICSVIEW @@ -6734,10 +6730,6 @@ void QWidgetPrivate::show_helper() if (QApplicationPrivate::hidden_focus_widget == q) { QApplicationPrivate::hidden_focus_widget = 0; q->setFocus(Qt::OtherFocusReason); - } else if (focus_child) { - // if we are shown and there is an explicit focus child widget - // set, respect it by giving him focus. - focus_child->setFocus(Qt::OtherFocusReason); } // Process events when showing a Qt::SplashScreen widget before the event loop diff --git a/tests/auto/qwidget/tst_qwidget.cpp b/tests/auto/qwidget/tst_qwidget.cpp index 3fad366..041aa7a 100644 --- a/tests/auto/qwidget/tst_qwidget.cpp +++ b/tests/auto/qwidget/tst_qwidget.cpp @@ -351,7 +351,6 @@ private slots: void toplevelLineEditFocus(); void focusWidget_task254563(); - void focusWidget_mixed_widget_hierarchy(); private: bool ensureScreenSize(int width, int height); @@ -8995,22 +8994,5 @@ void tst_QWidget::focusWidget_task254563() QVERIFY(top.focusWidget() != widget); //dangling pointer } -void tst_QWidget::focusWidget_mixed_widget_hierarchy() -{ - QWidget top; - top.show(); - QWidget notvisible(&top); - QWidget *visible = new QWidget(¬visible); - visible->show(); - - visible->setFocus(); - notvisible.setFocus(); - notvisible.show(); - QCOMPARE(top.focusWidget(), visible); - QCOMPARE(notvisible.focusWidget(), visible); - QCOMPARE(visible->focusWidget(), visible); -} - - QTEST_MAIN(tst_QWidget) #include "tst_qwidget.moc" -- cgit v0.12 From d29da4699a2887cdf0836ff39652524d015431c0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Fri, 5 Jun 2009 16:41:23 +0200 Subject: Fixed an issue with graphicssystem raster on 8 and 16 bit X servers. We didn't actually check the depth of the target window before calling the qt_x11_drawImage() fu, that will only work with depths >= 24. Task-number: 255311 Reviewed-by: Samuel BT: yes --- src/gui/painting/qwindowsurface_raster.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/painting/qwindowsurface_raster.cpp b/src/gui/painting/qwindowsurface_raster.cpp index 110ba2f..0a6a04e 100644 --- a/src/gui/painting/qwindowsurface_raster.cpp +++ b/src/gui/painting/qwindowsurface_raster.cpp @@ -229,7 +229,7 @@ void QRasterWindowSurface::flush(QWidget *widget, const QRegion &rgn, const QPoi { const QImage &src = d->image->image; br = br.intersected(src.rect()); - if (src.format() != QImage::Format_RGB32) { + if (src.format() != QImage::Format_RGB32 || widget->x11Info().depth() < 24) { QX11PixmapData *data = new QX11PixmapData(QPixmapData::PixmapType); data->xinfo = widget->x11Info(); data->fromImage(src, Qt::AutoColor); -- cgit v0.12 From 9691523b796c6acc6a837a5f5a34fef16aa74c48 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 5 Jun 2009 16:48:52 +0200 Subject: have QScriptValue::toVariant() convert Array objects to QVariantLists Converting the array to its string representation is not very useful. Now round-trip conversion will work as well. Reviewed-by: Ariya Hidayat --- src/script/qscriptvalue.cpp | 1 + src/script/qscriptvalueimpl.cpp | 2 ++ tests/auto/qscriptvalue/tst_qscriptvalue.cpp | 21 +++++++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/src/script/qscriptvalue.cpp b/src/script/qscriptvalue.cpp index a253985..f72d1db 100644 --- a/src/script/qscriptvalue.cpp +++ b/src/script/qscriptvalue.cpp @@ -904,6 +904,7 @@ qsreal QScriptValue::toInteger() const \row \o QObject Object \o A QVariant containing a pointer to the QObject. \row \o Date Object \o A QVariant containing the date value (toDateTime()). \row \o RegExp Object \o A QVariant containing the regular expression value (toRegExp()). + \row \o Array Object \o The array is converted to a QVariantList. \row \o Object \o If the value is primitive, then the result is converted to a QVariant according to the above rules; otherwise, an invalid QVariant is returned. \endtable diff --git a/src/script/qscriptvalueimpl.cpp b/src/script/qscriptvalueimpl.cpp index a890839..7c7b711 100644 --- a/src/script/qscriptvalueimpl.cpp +++ b/src/script/qscriptvalueimpl.cpp @@ -339,6 +339,8 @@ QVariant QScriptValueImpl::toVariant() const if (isQObject()) return qVariantFromValue(toQObject()); #endif + if (isArray()) + return QScriptEnginePrivate::variantListFromArray(*this); QScriptValueImpl v = engine()->toPrimitive(*this); if (!v.isObject()) diff --git a/tests/auto/qscriptvalue/tst_qscriptvalue.cpp b/tests/auto/qscriptvalue/tst_qscriptvalue.cpp index bf91001..ad1080a 100644 --- a/tests/auto/qscriptvalue/tst_qscriptvalue.cpp +++ b/tests/auto/qscriptvalue/tst_qscriptvalue.cpp @@ -1301,6 +1301,27 @@ void tst_QScriptValue::toVariant() QCOMPARE(str.toVariant(), QVariant(QString("ciao"))); QCOMPARE(qscriptvalue_cast(str), QVariant(QString("ciao"))); } + + // array + { + QVariantList listIn; + listIn << 123 << "hello"; + QScriptValue array = qScriptValueFromValue(&eng, listIn); + QVERIFY(array.isArray()); + QCOMPARE(array.property("length").toInt32(), 2); + QVariant ret = array.toVariant(); + QCOMPARE(ret.type(), QVariant::List); + QVariantList listOut = ret.toList(); + QCOMPARE(listOut.size(), listIn.size()); + for (int i = 0; i < listIn.size(); ++i) + QVERIFY(listOut.at(i) == listIn.at(i)); + // round-trip conversion + QScriptValue array2 = qScriptValueFromValue(&eng, ret); + QVERIFY(array2.isArray()); + QCOMPARE(array2.property("length").toInt32(), array.property("length").toInt32()); + for (int i = 0; i < array.property("length").toInt32(); ++i) + QVERIFY(array2.property(i).strictlyEquals(array.property(i))); + } } // unfortunately, this is necessary in order to do qscriptvalue_cast(...) -- cgit v0.12 From 7f21512826689df38678c4cb954e9c347c01df8b Mon Sep 17 00:00:00 2001 From: Oswald Buddenhagen Date: Fri, 5 Jun 2009 17:13:17 +0200 Subject: explicitly handle windows and mac9 line endings in practice, this matters only for backslashed line continuations Task-number: 255336 --- tools/linguist/shared/cpp.cpp | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/tools/linguist/shared/cpp.cpp b/tools/linguist/shared/cpp.cpp index 2e137cf..0aab661 100644 --- a/tools/linguist/shared/cpp.cpp +++ b/tools/linguist/shared/cpp.cpp @@ -134,13 +134,28 @@ static uint getChar() if (yyInPos >= yyInStr.size()) return EOF; uint c = yyInStr[yyInPos++].unicode(); - if (c == '\\' && yyInPos < yyInStr.size() && yyInStr[yyInPos].unicode() == '\n') { - ++yyCurLineNo; - ++yyInPos; - continue; + if (c == '\\' && yyInPos < yyInStr.size()) { + if (yyInStr[yyInPos].unicode() == '\n') { + ++yyCurLineNo; + ++yyInPos; + continue; + } + if (yyInStr[yyInPos].unicode() == '\r') { + ++yyCurLineNo; + ++yyInPos; + if (yyInPos < yyInStr.size() && yyInStr[yyInPos].unicode() == '\n') + ++yyInPos; + continue; + } } - if (c == '\n') + if (c == '\r') { + if (yyInPos < yyInStr.size() && yyInStr[yyInPos].unicode() == '\n') + ++yyInPos; + c = '\n'; ++yyCurLineNo; + } else if (c == '\n') { + ++yyCurLineNo; + } return c; } } -- cgit v0.12 From 508c9cd681244a5ad566c12733aa70f5bd522b57 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 5 Jun 2009 17:38:39 +0200 Subject: make signal handlers understand QVariant again Also, issue a warning if a type is not known to the meta-type system. Task-number: 248129 --- src/script/qscriptextqobject.cpp | 21 ++++++++++++++--- tests/auto/qscriptqobject/tst_qscriptqobject.cpp | 29 ++++++++++++++++++++++++ 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/src/script/qscriptextqobject.cpp b/src/script/qscriptextqobject.cpp index 0a346f0..47c04d4 100644 --- a/src/script/qscriptextqobject.cpp +++ b/src/script/qscriptextqobject.cpp @@ -1667,12 +1667,27 @@ void QScript::QObjectConnectionManager::execute(int slotIndex, void **argv) activation_data->m_members[i].object(nameId, i, QScriptValue::Undeletable | QScriptValue::SkipInEnumeration); + QScriptValueImpl actual; if (i < argc) { - int argType = QMetaType::type(parameterTypes.at(i)); - activation_data->m_values[i] = eng->create(argType, argv[i + 1]); + void *arg = argv[i + 1]; + QByteArray typeName = parameterTypes.at(i); + int argType = QMetaType::type(typeName); + if (!argType) { + if (typeName == "QVariant") { + actual = eng->valueFromVariant(*reinterpret_cast(arg)); + } else { + qWarning("QScriptEngine: Unable to handle unregistered datatype '%s' " + "when invoking handler of signal %s::%s", + typeName.constData(), meta->className(), method.signature()); + actual = eng->undefinedValue(); + } + } else { + actual = eng->create(argType, arg); + } } else { - activation_data->m_values[i] = eng->undefinedValue(); + actual = eng->undefinedValue(); } + activation_data->m_values[i] = actual; } QScriptValueImpl senderObject; diff --git a/tests/auto/qscriptqobject/tst_qscriptqobject.cpp b/tests/auto/qscriptqobject/tst_qscriptqobject.cpp index 1025d2a..2c47c49 100644 --- a/tests/auto/qscriptqobject/tst_qscriptqobject.cpp +++ b/tests/auto/qscriptqobject/tst_qscriptqobject.cpp @@ -333,6 +333,10 @@ public: { emit mySignalWithDefaultArg(arg); } void emitMySignalWithDefaultArg() { emit mySignalWithDefaultArg(); } + void emitMySignalWithVariantArg(const QVariant &arg) + { emit mySignalWithVariantArg(arg); } + void emitMySignalWithScriptEngineArg(QScriptEngine *arg) + { emit mySignalWithScriptEngineArg(arg); } public Q_SLOTS: void mySlot() @@ -395,6 +399,8 @@ Q_SIGNALS: void myOtherOverloadedSignal(const QString &arg); void myOtherOverloadedSignal(int arg); void mySignalWithDefaultArg(int arg = 123); + void mySignalWithVariantArg(const QVariant &arg); + void mySignalWithScriptEngineArg(QScriptEngine *arg); protected: void connectNotify(const char *signal) { @@ -1553,6 +1559,29 @@ void tst_QScriptExtQObject::connectAndDisconnect() m_myObject->emitMyOtherOverloadedSignal(123); QVERIFY(!m_engine->evaluate("gotSignal").toBoolean()); + // signal with QVariant arg: argument conversion should work + m_myObject->clearConnectedSignal(); + QVERIFY(m_engine->evaluate("myObject.mySignalWithVariantArg.connect(myHandler)").isUndefined()); + QCOMPARE(m_myObject->connectedSignal().constData(), SIGNAL(mySignalWithVariantArg(QVariant))); + m_engine->evaluate("gotSignal = false"); + m_myObject->emitMySignalWithVariantArg(123); + QCOMPARE(m_engine->evaluate("gotSignal").toBoolean(), true); + QCOMPARE(m_engine->evaluate("signalArgs.length").toNumber(), 1.0); + QCOMPARE(m_engine->evaluate("signalArgs[0]").toNumber(), 123.0); + QVERIFY(m_engine->evaluate("myObject.mySignalWithVariantArg.disconnect(myHandler)").isUndefined()); + + // signal with argument type that's unknown to the meta-type system + m_myObject->clearConnectedSignal(); + QVERIFY(m_engine->evaluate("myObject.mySignalWithScriptEngineArg.connect(myHandler)").isUndefined()); + QCOMPARE(m_myObject->connectedSignal().constData(), SIGNAL(mySignalWithScriptEngineArg(QScriptEngine*))); + m_engine->evaluate("gotSignal = false"); + QTest::ignoreMessage(QtWarningMsg, "QScriptEngine: Unable to handle unregistered datatype 'QScriptEngine*' when invoking handler of signal MyQObject::mySignalWithScriptEngineArg(QScriptEngine*)"); + m_myObject->emitMySignalWithScriptEngineArg(m_engine); + QCOMPARE(m_engine->evaluate("gotSignal").toBoolean(), true); + QCOMPARE(m_engine->evaluate("signalArgs.length").toNumber(), 1.0); + QVERIFY(m_engine->evaluate("signalArgs[0]").isUndefined()); + QVERIFY(m_engine->evaluate("myObject.mySignalWithScriptEngineArg.disconnect(myHandler)").isUndefined()); + // connect(object, function) m_engine->evaluate("otherObject = { name:'foo' }"); QVERIFY(m_engine->evaluate("myObject.mySignal.connect(otherObject, myHandler)").isUndefined()); -- cgit v0.12 From dabeec5e1d3f43b54a58b2f8667ac552a7c24685 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Fri, 5 Jun 2009 17:46:48 +0200 Subject: My 4.5.2 changes. --- dist/changes-4.5.2 | 44 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 43 insertions(+), 1 deletion(-) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 1984881..810c022 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -131,6 +131,8 @@ Third party components * Fixed crash when drawing on a null pixmap. * [251534] Fixed issue where text with non-opaque color from widget palette would be blitted instead of blended. + * [253663] Fixed an issue with implicitly closed poly lines when using + perspective transforms. - QProgressBar * [252283] Fixed busy indicator for a QProgressBar with a style sheet applied to it. @@ -165,6 +167,8 @@ Third party components engine. * [251485] Fixed crash that could occur with projective transforms and high quality antialiasing. + * [253468] Fixed a crash in the GL 2 paint engine that could occur + when drawing text. - QCssParser * [252311] "font-family:" now handle fallback font specified with a comas @@ -186,6 +190,28 @@ Third party components - QPrintDialog * [253135] Crash in QPrintDialog when editing output filename + * [252873] Fixed an issue that could cause QPrintDialog to invalidate + a valid QPrinter object. + * [224728] Fixed an issue under X11 where QPrintDialog didn't update + the print-to-file state, if it was passed a QPrinter set up to + print PDF or PostScript. + +- QPrinter + * [252873] Fixed an issue with QPrinter::NativeFormat printers not + being valid. + * [248881] Fixed an issue under Windows where QPrinter::pageRect() returned + the wrong rect when QPrinter::fullPage() was set. + * [199271] Fixed an issue with QPrinter::setPrinterName()/printerName() + on Mac. + +- QSvg + * [253614] Fixed an issue with parsing the 'stroke-dasharray' SVG attribute. + +- QSvgIconEngine + * [251106] Fixed an issue that would cause QIcon::actualSize() to reparse + the SVG file for each acutalSize() call, until QIcon::pixmap() was called. + * [248848] Fixed an issue that would cause QIcon::pixmap() to reparse the + SVG file, even though there was a cached pixmap for that size available. **************************************************************************** * Database Drivers * @@ -202,17 +228,30 @@ Qt for Linux/X11 legacy freetype headers. [241361] Prevented asynchronous access to non-thread safe libfontconfig API. [244362] Worked around X server crash when calling XFillPolygon with more than -200000 points by falling back to raster paint engine. + 200000 points by falling back to raster paint engine. [250326] Titlebar wasn't shown on X11 with Qt::CustomizeWindowHint for fixed-size windows. [251925] Improved showing QMessageBox on small screens. [252042] Fixed the loading of the OpenSSL libraries on OpenBSD. +[255311] Fixed an issue with '-graphicssystem raster' on 8 and 16 bit X servers. +[252328] Fixed an issue when rendering old XLFD fonts on X11 with Xrender and + fontconfig enabled. +[248720] Fixed and issue with using '-graphicssystem raster' on X servers with + BGR color layout. +[196152] Fixed a problem with QPixmap::toImage() on big endian systems that + would cause the R and B channels to be swapped for 32 bit pixmaps. Qt for Windows -------------- +Fixed and issue with text rendering in 16 bit mode. + +[246196] Fixed an issue with clipped glyphs when rendering text with + certain fonts. [251259] Switching to another app left text cursor in line edits with QtMfc framework. +[253367] Fixed a memory leak when loading system icons on Windows. + Qt for Mac OS X --------------- @@ -220,6 +259,9 @@ Qt for Mac OS X [252176] Fix regression in drawing parts of pixmaps on Panther. [253402] Fix a crash when a Cocoa window that used to be a QWidget would get events after the QWidget was destroyed. +[249178] Fixed an issue with drawing text to QImages on Mac/Cocoa. +[250066] Fixed an issue that caused reparenting of QGLWidgets to output warnings + on Mac/Cocoa. Qt for Embedded Linux -- cgit v0.12 From f2b307342a0effed58436dd199a0d80c5e651755 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Trond=20Kjern=C3=A5sen?= Date: Fri, 5 Jun 2009 17:48:37 +0200 Subject: Fixed typos. --- dist/changes-4.5.2 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 810c022..39082f6 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -236,7 +236,7 @@ legacy freetype headers. [255311] Fixed an issue with '-graphicssystem raster' on 8 and 16 bit X servers. [252328] Fixed an issue when rendering old XLFD fonts on X11 with Xrender and fontconfig enabled. -[248720] Fixed and issue with using '-graphicssystem raster' on X servers with +[248720] Fixed an issue with using '-graphicssystem raster' on X servers with BGR color layout. [196152] Fixed a problem with QPixmap::toImage() on big endian systems that would cause the R and B channels to be swapped for 32 bit pixmaps. @@ -244,7 +244,7 @@ legacy freetype headers. Qt for Windows -------------- -Fixed and issue with text rendering in 16 bit mode. +Fixed an issue with text rendering in 16 bit mode. [246196] Fixed an issue with clipped glyphs when rendering text with certain fonts. -- cgit v0.12 From 8411fe233021f8609250b7cf47353e3128521406 Mon Sep 17 00:00:00 2001 From: Andy Shaw Date: Sat, 6 Jun 2009 23:17:29 +0200 Subject: Add a comment for the translator so the placeholders are described Reviewed-by: TrustMe --- tools/assistant/lib/qhelpdbreader.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tools/assistant/lib/qhelpdbreader.cpp b/tools/assistant/lib/qhelpdbreader.cpp index 76994a7..27bc4d7 100644 --- a/tools/assistant/lib/qhelpdbreader.cpp +++ b/tools/assistant/lib/qhelpdbreader.cpp @@ -92,6 +92,9 @@ bool QHelpDBReader::init() QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), m_uniqueId); db.setDatabaseName(m_dbName); if (!db.open()) { + /*: The placeholders are: %1 - The name of the database which cannot be opened + %2 - The unique id for the connection + %3 - The actual error string */ m_error = tr("Cannot open database '%1' '%2': %3").arg(m_dbName, m_uniqueId, db.lastError().text()); QSqlDatabase::removeDatabase(m_uniqueId); return false; -- cgit v0.12 From 0fafad31feb518453c7c25b2e29a8b26d7018978 Mon Sep 17 00:00:00 2001 From: Andy Shaw Date: Mon, 8 Jun 2009 07:53:58 +0200 Subject: Ensure that the manifest files are placed correctly If OBJECTS_DIR was empty then it would create a directory for the manifest files in the root directory. This is not desired as it should create a directory in the build directory instead. Reviewed-by: Marius Storm-Olsen --- mkspecs/features/win32/embed_manifest_dll.prf | 8 +++++--- mkspecs/features/win32/embed_manifest_exe.prf | 8 +++++--- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/mkspecs/features/win32/embed_manifest_dll.prf b/mkspecs/features/win32/embed_manifest_dll.prf index 90d9a2b..76a8ed1 100644 --- a/mkspecs/features/win32/embed_manifest_dll.prf +++ b/mkspecs/features/win32/embed_manifest_dll.prf @@ -1,11 +1,13 @@ +MANIFEST_DIR = $$OBJECTS_DIR +isEmpty(MANIFEST_DIR):MANIFEST_DIR = . !if(plugin:no_plugin_manifest):if(win32-msvc2005|win32-msvc2008):!static:!equals(TEMPLATE_PREFIX, "vc"):equals(TEMPLATE, "lib") { NOPATH_TARGET = $$TARGET NOPATH_TARGET ~= s,\\ , ,q # Remove space escaping (NOPATH_TARGET is quoted) NOPATH_TARGET ~= s,\\,/,g # Change to single type separators NOPATH_TARGET ~= s,^(.*/)+,, # Remove all paths - QMAKE_LFLAGS += /MANIFEST $$quote(/MANIFESTFILE:\"$${OBJECTS_DIR}\\$${NOPATH_TARGET}.intermediate.manifest\") + QMAKE_LFLAGS += /MANIFEST $$quote(/MANIFESTFILE:\"$${MANIFEST_DIR}\\$${NOPATH_TARGET}.intermediate.manifest\") QMAKE_PREV_POST_LINK = $$QMAKE_POST_LINK - QMAKE_POST_LINK = $$quote(mt.exe -nologo -manifest \"$$replace(OBJECTS_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" -outputresource:$(DESTDIR_TARGET);2$$escape_expand(\n\t)) + QMAKE_POST_LINK = $$quote(mt.exe -nologo -manifest \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" -outputresource:$(DESTDIR_TARGET);2$$escape_expand(\n\t)) QMAKE_POST_LINK += $$QMAKE_PREV_POST_LINK - QMAKE_CLEAN += \"$$replace(OBJECTS_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" + QMAKE_CLEAN += \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" } diff --git a/mkspecs/features/win32/embed_manifest_exe.prf b/mkspecs/features/win32/embed_manifest_exe.prf index e1747f1..d2800a1 100644 --- a/mkspecs/features/win32/embed_manifest_exe.prf +++ b/mkspecs/features/win32/embed_manifest_exe.prf @@ -1,11 +1,13 @@ +MANIFEST_DIR = $$OBJECTS_DIR +isEmpty(MANIFEST_DIR):MANIFEST_DIR = . if(win32-msvc2005|win32-msvc2008):!equals(TEMPLATE_PREFIX, "vc"):equals(TEMPLATE, "app") { NOPATH_TARGET = $$TARGET NOPATH_TARGET ~= s,\\ , ,q # Remove space escaping (NOPATH_TARGET is quoted) NOPATH_TARGET ~= s,\\,/,g # Change to single type separators NOPATH_TARGET ~= s,^(.*/)+,, # Remove all paths - QMAKE_LFLAGS += /MANIFEST $$quote(/MANIFESTFILE:\"$${OBJECTS_DIR}\\$${NOPATH_TARGET}.intermediate.manifest\") + QMAKE_LFLAGS += /MANIFEST $$quote(/MANIFESTFILE:\"$${MANIFEST_DIR}\\$${NOPATH_TARGET}.intermediate.manifest\") QMAKE_PREV_POST_LINK = $$QMAKE_POST_LINK - QMAKE_POST_LINK = $$quote(mt.exe -nologo -manifest \"$$replace(OBJECTS_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" -outputresource:$(DESTDIR_TARGET);1$$escape_expand(\n\t)) + QMAKE_POST_LINK = $$quote(mt.exe -nologo -manifest \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" -outputresource:$(DESTDIR_TARGET);1$$escape_expand(\n\t)) QMAKE_POST_LINK += $$QMAKE_PREV_POST_LINK - QMAKE_CLEAN += \"$$replace(OBJECTS_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" + QMAKE_CLEAN += \"$$replace(MANIFEST_DIR,/,\\)\\$${NOPATH_TARGET}.intermediate.manifest\" } -- cgit v0.12 From 3b2b9d727f0fadf607968c73003e7550c8bd0296 Mon Sep 17 00:00:00 2001 From: Andy Shaw Date: Mon, 8 Jun 2009 08:03:17 +0200 Subject: Set the error to be HostUnreacheable if WSAEHOSTUNREACH is recieved This was a contribution sent via the public bugs channel. Task-number: 255161 Reviewed-by: Marius Storm-Olsen --- src/network/socket/qnativesocketengine_win.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/network/socket/qnativesocketengine_win.cpp b/src/network/socket/qnativesocketengine_win.cpp index b08d7b0..8c6cd31 100644 --- a/src/network/socket/qnativesocketengine_win.cpp +++ b/src/network/socket/qnativesocketengine_win.cpp @@ -570,6 +570,11 @@ bool QNativeSocketEnginePrivate::nativeConnect(const QHostAddress &address, quin socketState = QAbstractSocket::UnconnectedState; break; } + if (value == WSAEHOSTUNREACH) { + setError(QAbstractSocket::NetworkError, HostUnreachableErrorString); + socketState = QAbstractSocket::UnconnectedState; + break; + } } // fall through } -- cgit v0.12 From 779bd72aaad2cd8cd5af23214cd812bf2e5528a7 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Mon, 8 Jun 2009 08:47:22 +0200 Subject: make moc-generated code compile again Needed due to commit 4acabb3abd0ff109b9abeedb6832f5b1c3e0cc4e --- src/tools/moc/moc.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tools/moc/moc.cpp b/src/tools/moc/moc.cpp index 8ca2823..4629ac5 100644 --- a/src/tools/moc/moc.cpp +++ b/src/tools/moc/moc.cpp @@ -767,6 +767,8 @@ void Moc::generate(FILE *out) if (classList.size() && classList.first().classname == "Qt") fprintf(out, "#include \n"); + fprintf(out, "#include \n"); + fprintf(out, "#if !defined(Q_MOC_OUTPUT_REVISION)\n" "#error \"The header file '%s' doesn't include .\"\n", (const char *)fn); fprintf(out, "#elif Q_MOC_OUTPUT_REVISION != %d\n", mocOutputRevision); -- cgit v0.12 From 38a5b31a8ae87f5e833d7f4383af9dc4592bf122 Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Mon, 8 Jun 2009 09:12:10 +0200 Subject: New binary Fixes the no qconfig.h output issue in main Reviewed by: trustme --- configure.exe | Bin 856064 -> 847872 bytes 1 file changed, 0 insertions(+), 0 deletions(-) diff --git a/configure.exe b/configure.exe index 9da5c60..cfad2dd 100644 Binary files a/configure.exe and b/configure.exe differ -- cgit v0.12 From d3bda146c4076dce3e260b4ef47f6bbc2d191b25 Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 8 Jun 2009 08:46:32 +0200 Subject: Use QT_USE_FAST_OPERATOR_PLUS and QT_USE_FAST_CONCATENATION in qdoc3. Reduces the number of qmalloc calls by 9% and reduces the instruction count as reported by valgrind by 2% in a release build. --- tools/qdoc3/qdoc3.pro | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tools/qdoc3/qdoc3.pro b/tools/qdoc3/qdoc3.pro index ead7b88..5438e5f 100644 --- a/tools/qdoc3/qdoc3.pro +++ b/tools/qdoc3/qdoc3.pro @@ -1,6 +1,8 @@ DEFINES += QDOC2_COMPAT DEFINES += QT_NO_CAST_TO_ASCII #DEFINES += QT_NO_CAST_FROM_ASCII +DEFINES += QT_USE_FAST_OPERATOR_PLUS +DEFINES += QT_USE_FAST_CONCATENATION QT = core xml CONFIG += console -- cgit v0.12 From ac30cbdceac428fa206a939e5d820b2bd77227fc Mon Sep 17 00:00:00 2001 From: hjk Date: Mon, 8 Jun 2009 09:14:19 +0200 Subject: Make QCharRef known to QStringBuilder. --- src/corelib/tools/qstringbuilder.cpp | 4 ++-- src/corelib/tools/qstringbuilder.h | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/corelib/tools/qstringbuilder.cpp b/src/corelib/tools/qstringbuilder.cpp index 4f24f76..03d8160 100644 --- a/src/corelib/tools/qstringbuilder.cpp +++ b/src/corelib/tools/qstringbuilder.cpp @@ -111,7 +111,7 @@ The QStringBuilder class is not to be used explicitly in user code. Instances of the class are created as return values of the operator%() function, acting on objects of type \c QString, \c QLatin1String, - \c QLatin1Literal, \c \QStringRef, \c QChar, + \c QLatin1Literal, \c \QStringRef, \c QChar, \c QCharRef, \c QLatin1Char, and \c char. Concatenating strings with operator%() generally yields better @@ -130,6 +130,6 @@ This function is usable with arguments of type \c QString, \c QLatin1String, \c QLatin1Literal, \c QStringRef, - \c QChar, \c QLatin1Char, and \c char. + \c QChar, \c QCharRef, \c QLatin1Char, and \c char. */ diff --git a/src/corelib/tools/qstringbuilder.h b/src/corelib/tools/qstringbuilder.h index 7b16197..2c31476 100644 --- a/src/corelib/tools/qstringbuilder.h +++ b/src/corelib/tools/qstringbuilder.h @@ -122,6 +122,16 @@ template <> struct QConcatenable } }; +template <> struct QConcatenable +{ + typedef QCharRef type; + static int size(const QCharRef &) { return 1; } + static inline void appendTo(const QCharRef &c, QChar *&out) + { + *out++ = QChar(c); + } +}; + template <> struct QConcatenable { typedef QLatin1String type; @@ -173,8 +183,8 @@ template <> struct QConcatenable template struct QConcatenable { typedef char type[N]; - static int size(const char *) { return N - 1; } - static inline void appendTo(const char *a, QChar *&out) + static int size(const char[N]) { return N - 1; } + static inline void appendTo(const char a[N], QChar *&out) { for (int i = 0; i < N - 1; ++i) *out++ = QLatin1Char(a[i]); -- cgit v0.12 From eb8789ba06949974eb4108b115a30f96e1500a81 Mon Sep 17 00:00:00 2001 From: Ritt Konstantin Date: Mon, 8 Jun 2009 10:42:42 +0200 Subject: Fix QT_NO_DATASTREAM macro checks and improve readability Some checks where in the wrong locations, and some endifs where hard to read. Merge-request: 611 Reviewed-by: Marius Storm-Olsen --- src/corelib/io/qdatastream.h | 3 +-- src/corelib/kernel/qmetatype.cpp | 4 ++-- src/corelib/kernel/qmetatype.h | 2 +- src/corelib/plugin/quuid.cpp | 2 +- src/corelib/tools/qbitarray.cpp | 5 +++-- src/corelib/tools/qbytearray.cpp | 5 +++-- src/corelib/tools/qchar.cpp | 2 +- src/corelib/tools/qlocale.cpp | 2 +- src/corelib/tools/qregexp.cpp | 2 +- src/corelib/tools/qsize.h | 4 ++++ src/gui/embedded/qkbd_qws_p.h | 3 ++- src/gui/image/qimage.cpp | 2 +- src/gui/image/qpicture.cpp | 2 ++ src/gui/image/qpicture.h | 2 ++ src/gui/image/qpixmap.cpp | 2 +- src/gui/itemviews/qheaderview.cpp | 10 ++++++---- src/gui/itemviews/qlistwidget.cpp | 3 +++ src/gui/itemviews/qstandarditemmodel.cpp | 2 +- src/gui/itemviews/qtreewidget.cpp | 3 +-- src/gui/kernel/qlayout.cpp | 4 +--- src/gui/kernel/qpalette.cpp | 4 ++-- src/gui/kernel/qsizepolicy.h | 2 ++ src/gui/painting/qcolor.cpp | 4 +--- src/gui/painting/qfixed_p.h | 2 ++ src/gui/painting/qmatrix.h | 2 ++ src/gui/painting/qpainterpath.cpp | 2 +- src/gui/painting/qpolygon.cpp | 2 +- src/gui/painting/qtransform.h | 2 ++ src/gui/text/qtextformat.cpp | 4 ++++ src/gui/text/qtextformat.h | 4 ++++ 30 files changed, 59 insertions(+), 33 deletions(-) diff --git a/src/corelib/io/qdatastream.h b/src/corelib/io/qdatastream.h index ec5780c..077e720 100644 --- a/src/corelib/io/qdatastream.h +++ b/src/corelib/io/qdatastream.h @@ -65,9 +65,8 @@ template class QSet; template class QHash; template class QMap; -class QDataStreamPrivate; - #ifndef QT_NO_DATASTREAM +class QDataStreamPrivate; class Q_CORE_EXPORT QDataStream { public: diff --git a/src/corelib/kernel/qmetatype.cpp b/src/corelib/kernel/qmetatype.cpp index a0b954f..6b40f46 100644 --- a/src/corelib/kernel/qmetatype.cpp +++ b/src/corelib/kernel/qmetatype.cpp @@ -360,7 +360,7 @@ void QMetaType::registerStreamOperators(const char *typeName, SaveOperator saveO inf.saveOp = saveOp; inf.loadOp = loadOp; } -#endif +#endif // QT_NO_DATASTREAM /*! Returns the type name associated with the given \a type, or 0 if no @@ -885,7 +885,7 @@ bool QMetaType::load(QDataStream &stream, int type, void *data) } return true; } -#endif +#endif // QT_NO_DATASTREAM /*! Returns a copy of \a copy, assuming it is of type \a type. If \a diff --git a/src/corelib/kernel/qmetatype.h b/src/corelib/kernel/qmetatype.h index be8a667..22214a4 100644 --- a/src/corelib/kernel/qmetatype.h +++ b/src/corelib/kernel/qmetatype.h @@ -183,7 +183,7 @@ void qRegisterMetaTypeStreamOperators(const char *typeName QMetaType::registerStreamOperators(typeName, reinterpret_cast(sptr), reinterpret_cast(lptr)); } -#endif +#endif // QT_NO_DATASTREAM template struct QMetaTypeId diff --git a/src/corelib/plugin/quuid.cpp b/src/corelib/plugin/quuid.cpp index 3e05d28..cee8bf7 100644 --- a/src/corelib/plugin/quuid.cpp +++ b/src/corelib/plugin/quuid.cpp @@ -405,7 +405,7 @@ QDataStream &operator>>(QDataStream &s, QUuid &id) } return s; } -#endif +#endif // QT_NO_DATASTREAM /*! Returns true if this is the null UUID diff --git a/src/corelib/tools/qbitarray.cpp b/src/corelib/tools/qbitarray.cpp index a947ab5..591cfa9 100644 --- a/src/corelib/tools/qbitarray.cpp +++ b/src/corelib/tools/qbitarray.cpp @@ -653,6 +653,7 @@ QBitArray operator^(const QBitArray &a1, const QBitArray &a2) QBitArray stream functions *****************************************************************************/ +#ifndef QT_NO_DATASTREAM /*! \relates QBitArray @@ -660,7 +661,7 @@ QBitArray operator^(const QBitArray &a1, const QBitArray &a2) \sa \link datastreamformat.html Format of the QDataStream operators \endlink */ -#ifndef QT_NO_DATASTREAM + QDataStream &operator<<(QDataStream &out, const QBitArray &ba) { quint32 len = ba.size(); @@ -713,7 +714,7 @@ QDataStream &operator>>(QDataStream &in, QBitArray &ba) *ba.d.data() = ba.d.size() * 8 - len; return in; } -#endif +#endif // QT_NO_DATASTREAM /*! \fn DataPtr &QBitArray::data_ptr() diff --git a/src/corelib/tools/qbytearray.cpp b/src/corelib/tools/qbytearray.cpp index 49dd52d..cbd9d4e 100644 --- a/src/corelib/tools/qbytearray.cpp +++ b/src/corelib/tools/qbytearray.cpp @@ -2591,6 +2591,8 @@ void QByteArray::clear() d->ref.ref(); } +#ifndef QT_NO_DATASTREAM + /*! \relates QByteArray Writes byte array \a ba to the stream \a out and returns a reference @@ -2598,7 +2600,6 @@ void QByteArray::clear() \sa {Format of the QDataStream operators} */ -#ifndef QT_NO_DATASTREAM QDataStream &operator<<(QDataStream &out, const QByteArray &ba) { @@ -2641,7 +2642,7 @@ QDataStream &operator>>(QDataStream &in, QByteArray &ba) return in; } -#endif //QT_NO_DATASTREAM +#endif // QT_NO_DATASTREAM /*! \fn bool QByteArray::operator==(const QString &str) const diff --git a/src/corelib/tools/qchar.cpp b/src/corelib/tools/qchar.cpp index a940cda..250dad0 100644 --- a/src/corelib/tools/qchar.cpp +++ b/src/corelib/tools/qchar.cpp @@ -1321,7 +1321,7 @@ QDataStream &operator>>(QDataStream &in, QChar &chr) chr.unicode() = ushort(u); return in; } -#endif +#endif // QT_NO_DATASTREAM /*! \fn ushort & QChar::unicode() diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp index 8c740bd..00132d7 100644 --- a/src/corelib/tools/qlocale.cpp +++ b/src/corelib/tools/qlocale.cpp @@ -1533,7 +1533,7 @@ QDataStream &operator>>(QDataStream &ds, QLocale &l) l = QLocale(s); return ds; } -#endif +#endif // QT_NO_DATASTREAM /*! diff --git a/src/corelib/tools/qregexp.cpp b/src/corelib/tools/qregexp.cpp index e1c3921..9c62c7a 100644 --- a/src/corelib/tools/qregexp.cpp +++ b/src/corelib/tools/qregexp.cpp @@ -4065,6 +4065,6 @@ QDataStream &operator>>(QDataStream &in, QRegExp ®Exp) regExp = newRegExp; return in; } -#endif +#endif // QT_NO_DATASTREAM QT_END_NAMESPACE diff --git a/src/corelib/tools/qsize.h b/src/corelib/tools/qsize.h index 34a6c99..237625e 100644 --- a/src/corelib/tools/qsize.h +++ b/src/corelib/tools/qsize.h @@ -98,8 +98,10 @@ Q_DECLARE_TYPEINFO(QSize, Q_MOVABLE_TYPE); QSize stream functions *****************************************************************************/ +#ifndef QT_NO_DATASTREAM Q_CORE_EXPORT QDataStream &operator<<(QDataStream &, const QSize &); Q_CORE_EXPORT QDataStream &operator>>(QDataStream &, QSize &); +#endif /***************************************************************************** @@ -249,8 +251,10 @@ Q_DECLARE_TYPEINFO(QSizeF, Q_MOVABLE_TYPE); QSizeF stream functions *****************************************************************************/ +#ifndef QT_NO_DATASTREAM Q_CORE_EXPORT QDataStream &operator<<(QDataStream &, const QSizeF &); Q_CORE_EXPORT QDataStream &operator>>(QDataStream &, QSizeF &); +#endif /***************************************************************************** diff --git a/src/gui/embedded/qkbd_qws_p.h b/src/gui/embedded/qkbd_qws_p.h index 3224da2..2ef1d0c 100644 --- a/src/gui/embedded/qkbd_qws_p.h +++ b/src/gui/embedded/qkbd_qws_p.h @@ -105,6 +105,7 @@ namespace QWSKeyboard { }; }; +#ifndef QT_NO_DATASTREAM inline QDataStream &operator>>(QDataStream &ds, QWSKeyboard::Mapping &m) { return ds >> m.keycode >> m.unicode >> m.qtcode >> m.modifiers >> m.flags >> m.special; @@ -124,6 +125,6 @@ inline QDataStream &operator<<(QDataStream &ds, const QWSKeyboard::Composing &c) { return ds << c.first << c.second << c.result; } - +#endif // QT_NO_DATASTREAM #endif // QWSKEYBOARD_H diff --git a/src/gui/image/qimage.cpp b/src/gui/image/qimage.cpp index c1c5631..0377ca7 100644 --- a/src/gui/image/qimage.cpp +++ b/src/gui/image/qimage.cpp @@ -4763,7 +4763,7 @@ QDataStream &operator>>(QDataStream &s, QImage &image) image = QImageReader(s.device(), 0).read(); return s; } -#endif +#endif // QT_NO_DATASTREAM #ifdef QT3_SUPPORT diff --git a/src/gui/image/qpicture.cpp b/src/gui/image/qpicture.cpp index 92023e0..23baa96 100644 --- a/src/gui/image/qpicture.cpp +++ b/src/gui/image/qpicture.cpp @@ -1143,6 +1143,7 @@ QPaintEngine *QPicture::paintEngine() const QPicture stream functions *****************************************************************************/ +#ifndef QT_NO_DATASTREAM /*! \relates QPicture @@ -1188,6 +1189,7 @@ QDataStream &operator>>(QDataStream &s, QPicture &r) r.d_func()->resetFormat(); return s; } +#endif // QT_NO_DATASTREAM #ifndef QT_NO_PICTUREIO diff --git a/src/gui/image/qpicture.h b/src/gui/image/qpicture.h index fe86e8d..edfac71 100644 --- a/src/gui/image/qpicture.h +++ b/src/gui/image/qpicture.h @@ -184,8 +184,10 @@ private: QPicture stream functions *****************************************************************************/ +#ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QPicture &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QPicture &); +#endif #endif // QT_NO_PICTURE diff --git a/src/gui/image/qpixmap.cpp b/src/gui/image/qpixmap.cpp index 8ed9e93..f6b5de2 100644 --- a/src/gui/image/qpixmap.cpp +++ b/src/gui/image/qpixmap.cpp @@ -1317,7 +1317,7 @@ QDataStream &operator>>(QDataStream &stream, QPixmap &pixmap) return stream; } -#endif //QT_NO_DATASTREAM +#endif // QT_NO_DATASTREAM #ifdef QT3_SUPPORT Q_GUI_EXPORT void copyBlt(QPixmap *dst, int dx, int dy, diff --git a/src/gui/itemviews/qheaderview.cpp b/src/gui/itemviews/qheaderview.cpp index ad93922..d28c08a 100644 --- a/src/gui/itemviews/qheaderview.cpp +++ b/src/gui/itemviews/qheaderview.cpp @@ -62,9 +62,11 @@ #ifndef QT_NO_DATASTREAM #include +#endif QT_BEGIN_NAMESPACE +#ifndef QT_NO_DATASTREAM QDataStream &operator<<(QDataStream &out, const QHeaderViewPrivate::SectionSpan &span) { span.write(out); @@ -76,7 +78,7 @@ QDataStream &operator>>(QDataStream &in, QHeaderViewPrivate::SectionSpan &span) span.read(in); return in; } -#endif +#endif // QT_NO_DATASTREAM /*! @@ -1535,7 +1537,7 @@ bool QHeaderView::restoreState(const QByteArray &state) } return false; } -#endif +#endif // QT_NO_DATASTREAM /*! \reimp @@ -3571,9 +3573,9 @@ bool QHeaderViewPrivate::read(QDataStream &in) return true; } -QT_END_NAMESPACE +#endif // QT_NO_DATASTREAM -#endif // QT_NO_DATASTREAEM +QT_END_NAMESPACE #endif // QT_NO_ITEMVIEWS diff --git a/src/gui/itemviews/qlistwidget.cpp b/src/gui/itemviews/qlistwidget.cpp index bf3b43c..e1e509d 100644 --- a/src/gui/itemviews/qlistwidget.cpp +++ b/src/gui/itemviews/qlistwidget.cpp @@ -711,6 +711,7 @@ void QListWidgetItem::write(QDataStream &out) const { out << d->values; } +#endif // QT_NO_DATASTREAM /*! \since 4.1 @@ -745,6 +746,8 @@ QListWidgetItem &QListWidgetItem::operator=(const QListWidgetItem &other) return *this; } +#ifndef QT_NO_DATASTREAM + /*! \relates QListWidgetItem diff --git a/src/gui/itemviews/qstandarditemmodel.cpp b/src/gui/itemviews/qstandarditemmodel.cpp index 10aac9a..d8adbd2 100644 --- a/src/gui/itemviews/qstandarditemmodel.cpp +++ b/src/gui/itemviews/qstandarditemmodel.cpp @@ -1938,7 +1938,7 @@ QDataStream &operator<<(QDataStream &out, const QStandardItem &item) return out; } -#endif // !QT_NO_DATASTREAM +#endif // QT_NO_DATASTREAM /*! \class QStandardItemModel diff --git a/src/gui/itemviews/qtreewidget.cpp b/src/gui/itemviews/qtreewidget.cpp index 6103225..a2bfe45 100644 --- a/src/gui/itemviews/qtreewidget.cpp +++ b/src/gui/itemviews/qtreewidget.cpp @@ -1827,6 +1827,7 @@ void QTreeWidgetItem::write(QDataStream &out) const { out << values << d->display; } +#endif // QT_NO_DATASTREAM /*! \since 4.1 @@ -1863,8 +1864,6 @@ QTreeWidgetItem &QTreeWidgetItem::operator=(const QTreeWidgetItem &other) return *this; } -#endif // QT_NO_DATASTREAM - /*! Appends the \a child item to the list of children. diff --git a/src/gui/kernel/qlayout.cpp b/src/gui/kernel/qlayout.cpp index 4463aab..0a233d5 100644 --- a/src/gui/kernel/qlayout.cpp +++ b/src/gui/kernel/qlayout.cpp @@ -1583,8 +1583,6 @@ QDataStream &operator>>(QDataStream &stream, QSizePolicy &policy) { return stream >> policy.data; } - -#endif - +#endif // QT_NO_DATASTREAM QT_END_NAMESPACE diff --git a/src/gui/kernel/qpalette.cpp b/src/gui/kernel/qpalette.cpp index 6541510..18a2142 100644 --- a/src/gui/kernel/qpalette.cpp +++ b/src/gui/kernel/qpalette.cpp @@ -125,7 +125,7 @@ QDataStream &operator>>(QDataStream &s, QColorGroup &g) { return qt_stream_in_qcolorgroup(s, g); } -#endif +#endif // QT_NO_DATASTREAM /*! Constructs a palette with the specified \a active, \a disabled and @@ -158,7 +158,7 @@ void QPalette::setColorGroup(ColorGroup cg, const QColorGroup &g) g.brush(LinkVisited), g.brush(ToolTipBase), g.brush(ToolTipText)); } -#endif +#endif // QT3_SUPPORT /*! \fn const QColor &QPalette::color(ColorRole role) const diff --git a/src/gui/kernel/qsizepolicy.h b/src/gui/kernel/qsizepolicy.h index 652fda1..32b3b4f 100644 --- a/src/gui/kernel/qsizepolicy.h +++ b/src/gui/kernel/qsizepolicy.h @@ -203,9 +203,11 @@ private: Q_DECLARE_OPERATORS_FOR_FLAGS(QSizePolicy::ControlTypes) +#ifndef QT_NO_DATASTREAM // implemented in qlayout.cpp Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QSizePolicy &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QSizePolicy &); +#endif inline void QSizePolicy::transpose() { Policy hData = horizontalPolicy(); diff --git a/src/gui/painting/qcolor.cpp b/src/gui/painting/qcolor.cpp index b1fe3aa..fa833db 100644 --- a/src/gui/painting/qcolor.cpp +++ b/src/gui/painting/qcolor.cpp @@ -2116,9 +2116,7 @@ QDataStream &operator>>(QDataStream &stream, QColor &color) return stream; } -#endif - - +#endif // QT_NO_DATASTREAM /***************************************************************************** diff --git a/src/gui/painting/qfixed_p.h b/src/gui/painting/qfixed_p.h index 2e49615..c89d97a 100644 --- a/src/gui/painting/qfixed_p.h +++ b/src/gui/painting/qfixed_p.h @@ -181,8 +181,10 @@ inline bool operator<(int i, const QFixed &f) { return (i<<6) < f.value(); } inline bool operator>(const QFixed &f, int i) { return f.value() > (i<<6); } inline bool operator>(int i, const QFixed &f) { return (i<<6) > f.value(); } +#ifndef QT_NO_DEBUG_STREAM inline QDebug &operator<<(QDebug &dbg, const QFixed &f) { return dbg << f.toReal(); } +#endif struct QFixedPoint { QFixed x; diff --git a/src/gui/painting/qmatrix.h b/src/gui/painting/qmatrix.h index 1e5fbb4..1df2395 100644 --- a/src/gui/painting/qmatrix.h +++ b/src/gui/painting/qmatrix.h @@ -169,8 +169,10 @@ inline bool QMatrix::isIdentity() const QMatrix stream functions *****************************************************************************/ +#ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QMatrix &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QMatrix &); +#endif #ifndef QT_NO_DEBUG_STREAM Q_GUI_EXPORT QDebug operator<<(QDebug, const QMatrix &); diff --git a/src/gui/painting/qpainterpath.cpp b/src/gui/painting/qpainterpath.cpp index bd91dfc..e1bb317 100644 --- a/src/gui/painting/qpainterpath.cpp +++ b/src/gui/painting/qpainterpath.cpp @@ -2366,7 +2366,7 @@ QDataStream &operator>>(QDataStream &s, QPainterPath &p) p.d_func()->dirtyControlBounds = true; return s; } -#endif +#endif // QT_NO_DATASTREAM /******************************************************************************* diff --git a/src/gui/painting/qpolygon.cpp b/src/gui/painting/qpolygon.cpp index 769c095..b79c288 100644 --- a/src/gui/painting/qpolygon.cpp +++ b/src/gui/painting/qpolygon.cpp @@ -742,7 +742,7 @@ QDataStream &operator>>(QDataStream &s, QPolygon &a) QVector &v = a; return s >> v; } -#endif +#endif // QT_NO_DATASTREAM /***************************************************************************** QPolygonF stream functions diff --git a/src/gui/painting/qtransform.h b/src/gui/painting/qtransform.h index aac7c31..a5002ca 100644 --- a/src/gui/painting/qtransform.h +++ b/src/gui/painting/qtransform.h @@ -332,8 +332,10 @@ inline QTransform &QTransform::operator-=(qreal num) } /****** stream functions *******************/ +#ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QTransform &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QTransform &); +#endif #ifndef QT_NO_DEBUG_STREAM Q_GUI_EXPORT QDebug operator<<(QDebug, const QTransform &); diff --git a/src/gui/text/qtextformat.cpp b/src/gui/text/qtextformat.cpp index 38ac4ca..d93f084 100644 --- a/src/gui/text/qtextformat.cpp +++ b/src/gui/text/qtextformat.cpp @@ -142,6 +142,7 @@ QTextLength::operator QVariant() const return QVariant(QVariant::TextLength, this); } +#ifndef QT_NO_DATASTREAM QDataStream &operator<<(QDataStream &stream, const QTextLength &length) { return stream << qint32(length.lengthType) << double(length.fixedValueOrPercentage); @@ -156,6 +157,7 @@ QDataStream &operator>>(QDataStream &stream, QTextLength &length) length.lengthType = QTextLength::Type(type); return stream; } +#endif // QT_NO_DATASTREAM class QTextFormatPrivate : public QSharedData { @@ -374,6 +376,7 @@ void QTextFormatPrivate::recalcFont() const fontDirty = false; } +#ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &stream, const QTextFormat &fmt) { stream << fmt.format_type << fmt.properties(); @@ -396,6 +399,7 @@ Q_GUI_EXPORT QDataStream &operator>>(QDataStream &stream, QTextFormat &fmt) return stream; } +#endif // QT_NO_DATASTREAM /*! \class QTextFormat diff --git a/src/gui/text/qtextformat.h b/src/gui/text/qtextformat.h index 8eaeeb1..96c0739 100644 --- a/src/gui/text/qtextformat.h +++ b/src/gui/text/qtextformat.h @@ -76,8 +76,10 @@ class QTextCursor; class QTextDocument; class QTextLength; +#ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QTextLength &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QTextLength &); +#endif class Q_GUI_EXPORT QTextLength { @@ -119,8 +121,10 @@ private: inline QTextLength::QTextLength(Type atype, qreal avalue) : lengthType(atype), fixedValueOrPercentage(avalue) {} +#ifndef QT_NO_DATASTREAM Q_GUI_EXPORT QDataStream &operator<<(QDataStream &, const QTextFormat &); Q_GUI_EXPORT QDataStream &operator>>(QDataStream &, QTextFormat &); +#endif class Q_GUI_EXPORT QTextFormat { -- cgit v0.12 From ec110c41175daae436d49b1e2369f80587ba5b65 Mon Sep 17 00:00:00 2001 From: Jarek Kobus Date: Mon, 8 Jun 2009 10:55:45 +0200 Subject: My changes for 4.5.2 --- dist/changes-4.5.2 | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/dist/changes-4.5.2 b/dist/changes-4.5.2 index 39082f6..6049a4d 100644 --- a/dist/changes-4.5.2 +++ b/dist/changes-4.5.2 @@ -304,6 +304,10 @@ Qt for Windows CE QDesignerFormWindowCursor::setProperty(). * [253539] Prevent crash in Designer with the Cocoa port when when using a scroll wheel to change a property. + * [252333] Fixed a regression crash in uic triggered when icon was set with different modes + than normal off. + * [252414, 252416, 252502] Fixed a crash in case of setting invalid point size + of font property in property editor - Linguist - Linguist GUI -- cgit v0.12 From 6a2202b544e3d7809312f74b0cf0b2b392bd78b7 Mon Sep 17 00:00:00 2001 From: Markus Goetz Date: Mon, 8 Jun 2009 10:53:05 +0200 Subject: Doc typo fix in QSslSocket Reviewed-by: TrustMe --- src/network/ssl/qsslsocket.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/network/ssl/qsslsocket.cpp b/src/network/ssl/qsslsocket.cpp index ea64042..cf2512e 100644 --- a/src/network/ssl/qsslsocket.cpp +++ b/src/network/ssl/qsslsocket.cpp @@ -450,7 +450,7 @@ QSslSocket::SslMode QSslSocket::mode() const Returns true if the socket is encrypted; otherwise, false is returned. An encrypted socket encrypts all data that is written by calling write() - or putChar() before the data is written to the network, and descrypts all + or putChar() before the data is written to the network, and decrypts all incoming data as the data is received from the network, before you call read(), readLine() or getChar(). -- cgit v0.12 From 61d1dcea0efa6b0809639b781bb49baf252b3aad Mon Sep 17 00:00:00 2001 From: Richard Moe Gustavsen Date: Mon, 8 Jun 2009 09:09:29 +0200 Subject: Mac: play music from CD does not work in Phonon ...because it was never implemented. This patch does that. Task-number: 255377 --- src/3rdparty/phonon/qt7/mediaobject.h | 18 ++- src/3rdparty/phonon/qt7/mediaobject.mm | 147 +++++++++++++-------- src/3rdparty/phonon/qt7/quicktimemetadata.h | 8 +- src/3rdparty/phonon/qt7/quicktimemetadata.mm | 41 ++++-- src/3rdparty/phonon/qt7/quicktimevideoplayer.h | 19 ++- src/3rdparty/phonon/qt7/quicktimevideoplayer.mm | 163 ++++++++++++++++++++++-- 6 files changed, 313 insertions(+), 83 deletions(-) diff --git a/src/3rdparty/phonon/qt7/mediaobject.h b/src/3rdparty/phonon/qt7/mediaobject.h index 27949ec..d59ee77 100644 --- a/src/3rdparty/phonon/qt7/mediaobject.h +++ b/src/3rdparty/phonon/qt7/mediaobject.h @@ -38,7 +38,10 @@ namespace QT7 class MediaObjectAudioNode; class MediaObject : public MediaNode, - public Phonon::MediaObjectInterface, public Phonon::AddonInterface + public Phonon::MediaObjectInterface +#ifndef QT_NO_PHONON_MEDIACONTROLLER + , public Phonon::AddonInterface +#endif { Q_OBJECT Q_INTERFACES(Phonon::MediaObjectInterface Phonon::AddonInterface) @@ -105,6 +108,16 @@ namespace QT7 void metaDataChanged(QMultiMap); void currentSourceChanged(const MediaSource &newSource); + // Add-on interface: + void availableSubtitlesChanged(); + void availableAudioChannelsChanged(); + void titleChanged(int); + void availableTitlesChanged(int); + void chapterChanged(int); + void availableChaptersChanged(int); + void angleChanged(int); + void availableAnglesChanged(int); + protected: void mediaNodeEvent(const MediaNodeEvent *event); bool event(QEvent *event); @@ -118,7 +131,6 @@ namespace QT7 QuickTimeVideoPlayer *m_nextVideoPlayer; QuickTimeAudioPlayer *m_nextAudioPlayer; MediaObjectAudioNode *m_mediaObjectAudioNode; - QuickTimeMetaData *m_metaData; qint32 m_tickInterval; qint32 m_transitionTime; @@ -133,6 +145,7 @@ namespace QT7 bool m_waitNextSwap; int m_swapTimeLeft; QTime m_swapTime; + bool m_autoplayTitles; void synchAudioVideo(); void updateCurrentTime(); @@ -154,6 +167,7 @@ namespace QT7 void inspectVideoGraphRecursive(MediaNode *node, int &effectCount, int &outputCount); void inspectGraph(); bool isCrossFading(); + void setCurrentTrack(int track); QString m_errorString; Phonon::ErrorType m_errorType; diff --git a/src/3rdparty/phonon/qt7/mediaobject.mm b/src/3rdparty/phonon/qt7/mediaobject.mm index 002c337..95859ef 100644 --- a/src/3rdparty/phonon/qt7/mediaobject.mm +++ b/src/3rdparty/phonon/qt7/mediaobject.mm @@ -46,7 +46,6 @@ MediaObject::MediaObject(QObject *parent) : MediaNode(AudioSource | VideoSource, m_mediaObjectAudioNode = new MediaObjectAudioNode(m_audioPlayer, m_nextAudioPlayer); setAudioNode(m_mediaObjectAudioNode); - m_metaData = new QuickTimeMetaData(); m_audioGraph = new AudioGraph(this); m_tickInterval = 0; @@ -55,6 +54,7 @@ MediaObject::MediaObject(QObject *parent) : MediaNode(AudioSource | VideoSource, m_transitionTime = 0; m_percentageLoaded = 0; m_waitNextSwap = false; + m_autoplayTitles = true; m_audioEffectCount = 0; m_audioOutputCount = 0; m_videoEffectCount = 0; @@ -70,13 +70,12 @@ MediaObject::MediaObject(QObject *parent) : MediaNode(AudioSource | VideoSource, } MediaObject::~MediaObject() -{ +{ // m_mediaObjectAudioNode is owned by super class. m_audioPlayer->unsetVideoPlayer(); m_nextAudioPlayer->unsetVideoPlayer(); delete m_videoPlayer; delete m_nextVideoPlayer; - delete m_metaData; checkForError(); } @@ -122,7 +121,7 @@ void MediaObject::inspectGraph() // Inspect the graph to check wether there are any // effects or outputs connected. This will have // influence on the audio system and video system that ends up beeing used: - int prevVideoOutputCount = m_videoOutputCount; + int prevVideoOutputCount = m_videoOutputCount; m_audioEffectCount = 0; m_audioOutputCount = 0; m_videoEffectCount = 0; @@ -134,7 +133,7 @@ void MediaObject::inspectGraph() if (m_videoOutputCount != prevVideoOutputCount){ MediaNodeEvent e1(MediaNodeEvent::VideoOutputCountChanged, &m_videoOutputCount); notify(&e1); - } + } } void MediaObject::setupAudioSystem() @@ -167,14 +166,14 @@ void MediaObject::setupAudioSystem() if (newAudioSystem == m_audioSystem) return; - + // Enable selected audio system: - m_audioSystem = newAudioSystem; + m_audioSystem = newAudioSystem; switch (newAudioSystem){ case AS_Silent: m_audioGraph->stop(); m_videoPlayer->enableAudio(false); - m_nextVideoPlayer->enableAudio(false); + m_nextVideoPlayer->enableAudio(false); m_audioPlayer->enableAudio(false); m_nextAudioPlayer->enableAudio(false); break; @@ -214,28 +213,28 @@ void MediaObject::setSource(const MediaSource &source) IMPLEMENTED; PhononAutoReleasePool pool; setState(Phonon::LoadingState); - + // Save current state for event/signal handling below: bool prevHasVideo = m_videoPlayer->hasVideo(); qint64 prevTotalTime = totalTime(); + int prevTrackCount = m_videoPlayer->trackCount(); m_waitNextSwap = false; - + // Cancel cross-fade if any: m_nextVideoPlayer->pause(); m_nextAudioPlayer->pause(); m_mediaObjectAudioNode->cancelCrossFade(); - + // Set new source: m_audioPlayer->unsetVideoPlayer(); m_videoPlayer->setMediaSource(source); m_audioPlayer->setVideoPlayer(m_videoPlayer); - m_metaData->setVideo(m_videoPlayer); - m_audioGraph->updateStreamSpecifications(); + m_audioGraph->updateStreamSpecifications(); m_nextAudioPlayer->unsetVideoPlayer(); - m_nextVideoPlayer->unsetVideo(); + m_nextVideoPlayer->unsetCurrentMediaSource(); m_currentTime = 0; - + // Emit/notify information about the new source: QRect videoRect = m_videoPlayer->videoRect(); MediaNodeEvent e1(MediaNodeEvent::VideoFrameSizeChanged, &videoRect); @@ -246,12 +245,14 @@ void MediaObject::setSource(const MediaSource &source) updateVideo(emptyFrame); emit currentSourceChanged(source); - emit metaDataChanged(m_metaData->metaData()); + emit metaDataChanged(m_videoPlayer->metaData()); if (prevHasVideo != m_videoPlayer->hasVideo()) - emit hasVideoChanged(m_videoPlayer->hasVideo()); + emit hasVideoChanged(m_videoPlayer->hasVideo()); if (prevTotalTime != totalTime()) - emit totalTimeChanged(totalTime()); + emit totalTimeChanged(totalTime()); + if (prevTrackCount != m_videoPlayer->trackCount()) + emit availableTitlesChanged(m_videoPlayer->trackCount()); if (checkForError()) return; if (!m_videoPlayer->isDrmAuthorized()) @@ -260,7 +261,7 @@ void MediaObject::setSource(const MediaSource &source) return; if (!m_videoPlayer->canPlayMedia()) SET_ERROR("Cannot play media.", FATAL_ERROR) - + // The state might have changed from LoadingState // as a response to an error state change. So we // need to check it before stopping: @@ -287,28 +288,30 @@ void MediaObject::swapCurrentWithNext(qint32 transitionTime) // Save current state for event/signal handling below: bool prevHasVideo = m_videoPlayer->hasVideo(); qint64 prevTotalTime = totalTime(); + int prevTrackCount = m_videoPlayer->trackCount(); qSwap(m_audioPlayer, m_nextAudioPlayer); qSwap(m_videoPlayer, m_nextVideoPlayer); m_mediaObjectAudioNode->startCrossFade(transitionTime); m_audioGraph->updateStreamSpecifications(); - m_metaData->setVideo(m_videoPlayer); m_waitNextSwap = false; m_currentTime = 0; - + // Emit/notify information about the new source: QRect videoRect = m_videoPlayer->videoRect(); MediaNodeEvent e1(MediaNodeEvent::VideoFrameSizeChanged, &videoRect); notify(&e1); emit currentSourceChanged(m_videoPlayer->mediaSource()); - emit metaDataChanged(m_metaData->metaData()); + emit metaDataChanged(m_videoPlayer->metaData()); if (prevHasVideo != m_videoPlayer->hasVideo()) - emit hasVideoChanged(m_videoPlayer->hasVideo()); + emit hasVideoChanged(m_videoPlayer->hasVideo()); if (prevTotalTime != totalTime()) emit totalTimeChanged(totalTime()); + if (prevTrackCount != m_videoPlayer->trackCount()) + emit availableTitlesChanged(m_videoPlayer->trackCount()); if (checkForError()) return; if (!m_videoPlayer->isDrmAuthorized()) @@ -332,15 +335,15 @@ void MediaObject::updateTimer(int &timer, int interval) if (timer) killTimer(timer); timer = 0; - if (interval >= 0) - timer = startTimer(interval); + if (interval >= 0) + timer = startTimer(interval); } void MediaObject::play_internal() { // Play main audio/video: m_videoPlayer->play(); - m_audioPlayer->play(); + m_audioPlayer->play(); updateLipSynch(0); // Play old audio/video to finish cross-fade: if (m_nextVideoPlayer->currentTime() > 0){ @@ -382,7 +385,7 @@ void MediaObject::play() if (!m_videoPlayer->canPlayMedia()) return; if (!setState(Phonon::PlayingState)) - return; + return; if (m_audioSystem == AS_Graph){ m_audioGraph->start(); m_mediaObjectAudioNode->setMute(true); @@ -423,7 +426,7 @@ void MediaObject::stop() if (!setState(Phonon::StoppedState)) return; m_waitNextSwap = false; - m_nextVideoPlayer->unsetVideo(); + m_nextVideoPlayer->unsetCurrentMediaSource(); m_nextAudioPlayer->unsetVideoPlayer(); pause_internal(); seek(0); @@ -435,9 +438,9 @@ void MediaObject::seek(qint64 milliseconds) IMPLEMENTED; if (m_state == Phonon::ErrorState) return; - + // Stop cross-fade if any: - m_nextVideoPlayer->unsetVideo(); + m_nextVideoPlayer->unsetCurrentMediaSource(); m_nextAudioPlayer->unsetVideoPlayer(); m_mediaObjectAudioNode->cancelCrossFade(); @@ -446,7 +449,7 @@ void MediaObject::seek(qint64 milliseconds) m_videoPlayer->seek(milliseconds); m_audioPlayer->seek(m_videoPlayer->currentTime()); m_mediaObjectAudioNode->setMute(false); - + // Update time and cancel pending swap: if (m_currentTime < m_videoPlayer->duration()) m_waitNextSwap = false; @@ -557,7 +560,7 @@ bool MediaObject::isSeekable() const qint64 MediaObject::currentTime() const { IMPLEMENTED_SILENT; - const_cast(this)->updateCurrentTime(); + const_cast(this)->updateCurrentTime(); return m_currentTime; } @@ -567,19 +570,24 @@ void MediaObject::updateCurrentTime() m_currentTime = (m_audioSystem == AS_Graph) ? m_audioPlayer->currentTime() : m_videoPlayer->currentTime(); quint64 total = m_videoPlayer->duration(); - // Check if it's time to emit aboutToFinish: - quint32 mark = qMax(quint64(0), qMin(total, total + m_transitionTime - 2000)); - if (lastUpdateTime < mark && mark <= m_currentTime) - emit aboutToFinish(); - - // Check if it's time to emit prefinishMarkReached: - mark = qMax(quint64(0), total - m_prefinishMark); - if (lastUpdateTime < mark && mark <= m_currentTime) - emit prefinishMarkReached(total - m_currentTime); + if (m_videoPlayer->currentTrack() < m_videoPlayer->trackCount() - 1){ + // There are still more tracks to play after the current track. + if (m_autoplayTitles) { + if (lastUpdateTime < m_currentTime && m_currentTime == total) + setCurrentTrack(m_videoPlayer->currentTrack() + 1); + } + } else if (m_nextVideoPlayer->state() == QuickTimeVideoPlayer::NoMedia){ + // There is no more sources or tracks to play after the current source. + // Check if it's time to emit aboutToFinish: + quint32 mark = qMax(quint64(0), qMin(total, total + m_transitionTime - 2000)); + if (lastUpdateTime < mark && mark <= m_currentTime) + emit aboutToFinish(); + + // Check if it's time to emit prefinishMarkReached: + mark = qMax(quint64(0), total - m_prefinishMark); + if (lastUpdateTime < mark && mark <= m_currentTime) + emit prefinishMarkReached(total - m_currentTime); - if (m_nextVideoPlayer->state() == QuickTimeVideoPlayer::NoMedia){ - // There is no next source in que. - // Check if it's time to emit finished: if (lastUpdateTime < m_currentTime && m_currentTime == total){ emit finished(); m_currentTime = (m_audioSystem == AS_Graph) ? m_audioPlayer->currentTime() : m_videoPlayer->currentTime(); @@ -589,7 +597,7 @@ void MediaObject::updateCurrentTime() } else { // We have a next source. // Check if it's time to swap to next source: - mark = qMax(quint64(0), total + m_transitionTime); + quint32 mark = qMax(quint64(0), total + m_transitionTime); if (m_waitNextSwap && m_state == Phonon::PlayingState && m_transitionTime < m_swapTime.msecsTo(QTime::currentTime())){ swapCurrentWithNext(0); @@ -692,14 +700,14 @@ bool MediaObject::setAudioDeviceOnMovie(int id) void MediaObject::updateCrossFade() { - m_mediaObjectAudioNode->updateCrossFade(m_currentTime); + m_mediaObjectAudioNode->updateCrossFade(m_currentTime); // Clean-up previous movie if done fading: if (m_mediaObjectAudioNode->m_fadeDuration == 0){ if (m_nextVideoPlayer->isPlaying() || m_nextAudioPlayer->isPlaying()){ - m_nextVideoPlayer->unsetVideo(); + m_nextVideoPlayer->unsetCurrentMediaSource(); m_nextAudioPlayer->unsetVideoPlayer(); } - } + } } void MediaObject::updateBufferStatus() @@ -728,7 +736,7 @@ void MediaObject::updateVideoFrames() // Draw next frame if awailable: if (m_videoPlayer->videoFrameChanged()){ updateLipSynch(50); - VideoFrame frame(m_videoPlayer); + VideoFrame frame(m_videoPlayer); if (m_nextVideoPlayer->isPlaying() && m_nextVideoPlayer->hasVideo() && isCrossFading()){ @@ -736,9 +744,9 @@ void MediaObject::updateVideoFrames() frame.setBackgroundFrame(bgFrame); frame.setBaseOpacity(m_mediaObjectAudioNode->m_volume1); } - + // Send the frame through the graph: - updateVideo(frame); + updateVideo(frame); checkForError(); } } @@ -749,7 +757,7 @@ void MediaObject::updateLipSynch(int allowedOffset) return; if (m_videoSinkList.isEmpty() || m_audioSinkList.isEmpty()) return; - + if (m_videoPlayer->hasVideo()){ qint64 diff = m_audioPlayer->currentTime() - m_videoPlayer->currentTime(); if (-allowedOffset > diff || diff > allowedOffset) @@ -834,13 +842,42 @@ bool MediaObject::event(QEvent *event) return QObject::event(event); } -bool MediaObject::hasInterface(Interface /*interface*/) const +void MediaObject::setCurrentTrack(int track) +{ + if (track == m_videoPlayer->currentTrack() || track < 0 || track >= m_videoPlayer->trackCount()) + return; + + m_videoPlayer->setCurrentTrack(track); + emit titleChanged(track); + emit metaDataChanged(m_videoPlayer->metaData()); +} + +bool MediaObject::hasInterface(Interface iface) const { - return false; + return iface == AddonInterface::TitleInterface; } -QVariant MediaObject::interfaceCall(Interface /*interface*/, int /*command*/, const QList &/*arguments*/) +QVariant MediaObject::interfaceCall(Interface iface, int command, const QList ¶ms) { + switch (iface) { + case TitleInterface: + switch (command) { + case availableTitles: + return m_videoPlayer->trackCount(); + case title: + return m_videoPlayer->currentTrack(); + case setTitle: + setCurrentTrack(params.first().toInt()); + break; + case autoplayTitles: + return m_autoplayTitles; + case setAutoplayTitles: + m_autoplayTitles = params.first().toBool(); + break; + } + default: + break; + } return QVariant(); } diff --git a/src/3rdparty/phonon/qt7/quicktimemetadata.h b/src/3rdparty/phonon/qt7/quicktimemetadata.h index d524183..c589535 100644 --- a/src/3rdparty/phonon/qt7/quicktimemetadata.h +++ b/src/3rdparty/phonon/qt7/quicktimemetadata.h @@ -38,10 +38,8 @@ namespace QT7 class QuickTimeMetaData { public: - QuickTimeMetaData(); - virtual ~QuickTimeMetaData(); - - void setVideo(QuickTimeVideoPlayer *videoPlayer); + QuickTimeMetaData(QuickTimeVideoPlayer *videoPlayer); + void update(); QMultiMap metaData(); private: @@ -49,6 +47,8 @@ namespace QT7 bool m_movieChanged; QuickTimeVideoPlayer *m_videoPlayer; void readMetaData(); + void guessMetaDataForCD(); + void readMetaDataFromMovie(); #ifdef QUICKTIME_C_API_AVAILABLE QString stripCopyRightSymbol(const QString &key); diff --git a/src/3rdparty/phonon/qt7/quicktimemetadata.mm b/src/3rdparty/phonon/qt7/quicktimemetadata.mm index 851e707..2dcc152 100644 --- a/src/3rdparty/phonon/qt7/quicktimemetadata.mm +++ b/src/3rdparty/phonon/qt7/quicktimemetadata.mm @@ -15,6 +15,7 @@ along with this library. If not, see . */ +#include #include "quicktimemetadata.h" #include "quicktimevideoplayer.h" @@ -25,19 +26,14 @@ namespace Phonon namespace QT7 { -QuickTimeMetaData::QuickTimeMetaData() +QuickTimeMetaData::QuickTimeMetaData(QuickTimeVideoPlayer *videoPlayer) { - m_videoPlayer = 0; + m_videoPlayer = videoPlayer; m_movieChanged = false; } -QuickTimeMetaData::~QuickTimeMetaData() +void QuickTimeMetaData::update() { -} - -void QuickTimeMetaData::setVideo(QuickTimeVideoPlayer *videoPlayer) -{ - m_videoPlayer = videoPlayer; m_movieChanged = true; m_metaData.clear(); } @@ -145,14 +141,22 @@ void QuickTimeMetaData::readFormattedData(QTMetaDataRef metaDataRef, OSType form #endif // QUICKTIME_C_API_AVAILABLE -void QuickTimeMetaData::readMetaData() +void QuickTimeMetaData::guessMetaDataForCD() +{ + QString album = QFileInfo(m_videoPlayer->movieCompactDiscPath()).fileName(); + QString title = QFileInfo(m_videoPlayer->currentTrackPath()).fileName(); + title = title.left(title.lastIndexOf('.')); + m_metaData.insert(QLatin1String("ALBUM"), album); + m_metaData.insert(QLatin1String("TITLE"), title); + m_metaData.insert(QLatin1String("TRACKNUMBER"), QString::number(m_videoPlayer->currentTrack())); +} + +void QuickTimeMetaData::readMetaDataFromMovie() { - if (!m_videoPlayer) - return; QMultiMap metaMap; - + #ifdef QUICKTIME_C_API_AVAILABLE - QTMetaDataRef metaDataRef; + QTMetaDataRef metaDataRef; OSStatus err = QTCopyMovieMetaData([m_videoPlayer->qtMovie() quickTimeMovie], &metaDataRef); BACKEND_ASSERT2(err == noErr, "Could not read QuickTime meta data", NORMAL_ERROR) @@ -173,6 +177,17 @@ void QuickTimeMetaData::readMetaData() m_metaData.insert(QLatin1String("DESCRIPTION"), metaMap.value(QLatin1String("des"))); } +void QuickTimeMetaData::readMetaData() +{ + if (!m_videoPlayer) + return; + + if (m_videoPlayer->mediaSource().type() == Phonon::MediaSource::Disc) + guessMetaDataForCD(); + else + readMetaDataFromMovie(); +} + QMultiMap QuickTimeMetaData::metaData() { if (m_videoPlayer && m_videoPlayer->hasMovie() && m_movieChanged) diff --git a/src/3rdparty/phonon/qt7/quicktimevideoplayer.h b/src/3rdparty/phonon/qt7/quicktimevideoplayer.h index b80570a..8495e18 100644 --- a/src/3rdparty/phonon/qt7/quicktimevideoplayer.h +++ b/src/3rdparty/phonon/qt7/quicktimevideoplayer.h @@ -39,6 +39,7 @@ namespace Phonon namespace QT7 { class QuickTimeStreamReader; + class QuickTimeMetaData; class VideoRenderWidgetQTMovieView; class QuickTimeVideoPlayer : QObject @@ -56,7 +57,7 @@ namespace QT7 void setMediaSource(const MediaSource &source); MediaSource mediaSource() const; - void unsetVideo(); + void unsetCurrentMediaSource(); void play(); void pause(); @@ -84,6 +85,7 @@ namespace QT7 bool setAudioDevice(int id); void setPlaybackRate(float rate); QTMovie *qtMovie() const; + QMultiMap metaData(); float playbackRate() const; float prefferedPlaybackRate() const; @@ -103,6 +105,12 @@ namespace QT7 float percentageLoaded(); quint64 timeLoaded(); + int trackCount() const; + int currentTrack() const; + void setCurrentTrack(int track); + QString movieCompactDiscPath() const; + QString currentTrackPath() const; + static QString timeToString(quint64 ms); // Help functions when drawing to more that one widget in cocoa 64: @@ -116,6 +124,7 @@ namespace QT7 QTMovie *m_QTMovie; State m_state; QGLPixelBuffer *m_QImagePixelBuffer; + QuickTimeMetaData *m_metaData; bool m_playbackRateSat; bool m_isDrmProtected; @@ -133,6 +142,9 @@ namespace QT7 qreal m_contrast; qreal m_hue; qreal m_saturation; + NSArray *m_folderTracks; + int m_currentTrack; + QString m_movieCompactDiscPath; #ifdef QUICKTIME_C_API_AVAILABLE QTVisualContextRef m_visualContext; @@ -140,16 +152,21 @@ namespace QT7 VideoFrame m_currentFrame; QuickTimeStreamReader *m_streamReader; + void prepareCurrentMovieForPlayback(); void createVisualContext(); void openMovieFromCurrentMediaSource(); void openMovieFromDataRef(QTDataReference *dataRef); void openMovieFromFile(); void openMovieFromUrl(); void openMovieFromStream(); + void openMovieFromCompactDisc(); void openMovieFromData(QByteArray *data, char *fileType); void openMovieFromDataGuessType(QByteArray *data); QString mediaSourcePath(); bool codecExistsAccordingToSuffix(const QString &fileName); + NSString* pathToCompactDisc(); + bool isCompactDisc(NSString *path); + NSArray* scanFolder(NSString *path); void setError(NSError *error); bool errorOccured(); diff --git a/src/3rdparty/phonon/qt7/quicktimevideoplayer.mm b/src/3rdparty/phonon/qt7/quicktimevideoplayer.mm index 3f76132..93867e2 100644 --- a/src/3rdparty/phonon/qt7/quicktimevideoplayer.mm +++ b/src/3rdparty/phonon/qt7/quicktimevideoplayer.mm @@ -20,6 +20,7 @@ #include "videowidget.h" #include "audiodevice.h" #include "quicktimestreamreader.h" +#include "quicktimemetadata.h" #include #include @@ -52,6 +53,7 @@ QuickTimeVideoPlayer::QuickTimeVideoPlayer() : QObject(0) { m_state = NoMedia; m_mediaSource = MediaSource(); + m_metaData = new QuickTimeMetaData(this); m_QTMovie = 0; m_streamReader = 0; m_playbackRate = 1.0f; @@ -67,6 +69,8 @@ QuickTimeVideoPlayer::QuickTimeVideoPlayer() : QObject(0) m_primaryRenderingTarget = 0; m_primaryRenderingCIImage = 0; m_QImagePixelBuffer = 0; + m_folderTracks = 0; + m_currentTrack = 0; #ifdef QUICKTIME_C_API_AVAILABLE OSStatus err = EnterMovies(); @@ -77,7 +81,8 @@ QuickTimeVideoPlayer::QuickTimeVideoPlayer() : QObject(0) QuickTimeVideoPlayer::~QuickTimeVideoPlayer() { - unsetVideo(); + unsetCurrentMediaSource(); + delete m_metaData; [(NSObject*)m_primaryRenderingTarget release]; m_primaryRenderingTarget = 0; #ifdef QUICKTIME_C_API_AVAILABLE @@ -397,7 +402,7 @@ QRect QuickTimeVideoPlayer::videoRect() const return QRect(0, 0, size.width, size.height); } -void QuickTimeVideoPlayer::unsetVideo() +void QuickTimeVideoPlayer::unsetCurrentMediaSource() { if (!m_QTMovie) return; @@ -411,10 +416,13 @@ void QuickTimeVideoPlayer::unsetVideo() m_isDrmProtected = false; m_isDrmAuthorized = true; m_mediaSource = MediaSource(); + m_movieCompactDiscPath.clear(); [(CIImage *)m_primaryRenderingCIImage release]; m_primaryRenderingCIImage = 0; delete m_QImagePixelBuffer; m_QImagePixelBuffer = 0; + [m_folderTracks release]; + m_folderTracks = 0; } QuickTimeVideoPlayer::State QuickTimeVideoPlayer::state() const @@ -524,18 +532,25 @@ bool QuickTimeVideoPlayer::codecExistsAccordingToSuffix(const QString &fileName) void QuickTimeVideoPlayer::setMediaSource(const MediaSource &mediaSource) { PhononAutoReleasePool pool; - unsetVideo(); + unsetCurrentMediaSource(); + m_mediaSource = mediaSource; if (mediaSource.type() == MediaSource::Empty || mediaSource.type() == MediaSource::Invalid){ m_state = NoMedia; return; } + openMovieFromCurrentMediaSource(); if (errorOccured()){ - unsetVideo(); + unsetCurrentMediaSource(); return; } + prepareCurrentMovieForPlayback(); +} + +void QuickTimeVideoPlayer::prepareCurrentMovieForPlayback() +{ #ifdef QUICKTIME_C_API_AVAILABLE if (m_visualContext) SetMovieVisualContext([m_QTMovie quickTimeMovie], m_visualContext); @@ -543,14 +558,14 @@ void QuickTimeVideoPlayer::setMediaSource(const MediaSource &mediaSource) waitStatePlayable(); if (errorOccured()){ - unsetVideo(); + unsetCurrentMediaSource(); return; } readProtection(); preRollMovie(); if (errorOccured()){ - unsetVideo(); + unsetCurrentMediaSource(); return; } @@ -560,6 +575,7 @@ void QuickTimeVideoPlayer::setMediaSource(const MediaSource &mediaSource) enableAudio(m_audioEnabled); setMute(m_mute); setVolume(m_masterVolume, m_relativeVolume); + m_metaData->update(); pause(); } @@ -573,7 +589,7 @@ void QuickTimeVideoPlayer::openMovieFromCurrentMediaSource() openMovieFromUrl(); break; case MediaSource::Disc: - CASE_UNSUPPORTED("Could not open media source.", FATAL_ERROR) + openMovieFromCompactDisc(); break; case MediaSource::Stream: openMovieFromStream(); @@ -635,7 +651,7 @@ void QuickTimeVideoPlayer::openMovieFromDataGuessType(QByteArray *data) // than using e.g [QTMovie movieFileTypes:QTIncludeCommonTypes]. Some // codecs *think* they can decode the stream, and crash... #define TryOpenMovieWithCodec(type) gClearError(); \ - openMovieFromData(data, "."type); \ + openMovieFromData(data, (char *)"."type); \ if (m_QTMovie) return; TryOpenMovieWithCodec("avi"); @@ -675,6 +691,50 @@ void QuickTimeVideoPlayer::openMovieFromStream() openMovieFromDataGuessType(m_streamReader->pointerToData()); } +typedef void (*qt_sighandler_t)(int); +static void sigtest(int) { + qApp->exit(0); +} + +void QuickTimeVideoPlayer::openMovieFromCompactDisc() +{ + // Interrupting the application while the device is open + // causes the application to hang. So we need to handle + // this in a more graceful way: + qt_sighandler_t hndl = signal(SIGINT, sigtest); + if (hndl) + signal(SIGINT, hndl); + + PhononAutoReleasePool pool; + NSString *cd = 0; + QString devName = m_mediaSource.deviceName(); + if (devName.isEmpty()) { + cd = pathToCompactDisc(); + if (!cd) { + SET_ERROR("Could not open media source.", NORMAL_ERROR) + return; + } + m_movieCompactDiscPath = PhononCFString::toQString(reinterpret_cast(cd)); + } else { + if (!QFileInfo(devName).isAbsolute()) + devName = QLatin1String("/Volumes/") + devName; + cd = [reinterpret_cast(PhononCFString::toCFStringRef(devName)) autorelease]; + if (!isCompactDisc(cd)) { + SET_ERROR("Could not open media source.", NORMAL_ERROR) + return; + } + m_movieCompactDiscPath = devName; + } + + m_folderTracks = [scanFolder(cd) retain]; + setCurrentTrack(0); +} + +QString QuickTimeVideoPlayer::movieCompactDiscPath() const +{ + return m_movieCompactDiscPath; +} + MediaSource QuickTimeVideoPlayer::mediaSource() const { return m_mediaSource; @@ -950,6 +1010,93 @@ void QuickTimeVideoPlayer::readProtection() } } +QMultiMap QuickTimeVideoPlayer::metaData() +{ + return m_metaData->metaData(); +} + +int QuickTimeVideoPlayer::trackCount() const +{ + if (!m_folderTracks) + return 0; + return [m_folderTracks count]; +} + +int QuickTimeVideoPlayer::currentTrack() const +{ + return m_currentTrack; +} + +QString QuickTimeVideoPlayer::currentTrackPath() const +{ + if (!m_folderTracks) + return QString(); + + PhononAutoReleasePool pool; + NSString *trackPath = [m_folderTracks objectAtIndex:m_currentTrack]; + return PhononCFString::toQString(reinterpret_cast(trackPath)); +} + +NSString* QuickTimeVideoPlayer::pathToCompactDisc() +{ + PhononAutoReleasePool pool; + NSArray *devices = [[NSWorkspace sharedWorkspace] mountedRemovableMedia]; + for (NSString *dev in devices) { + if (isCompactDisc(dev)) + return [dev retain]; + } + return 0; +} + +bool QuickTimeVideoPlayer::isCompactDisc(NSString *path) +{ + PhononAutoReleasePool pool; + NSString *type = [NSString string]; + [[NSWorkspace sharedWorkspace] getFileSystemInfoForPath:path + isRemovable:0 + isWritable:0 + isUnmountable:0 + description:0 + type:&type]; + return [type hasPrefix:@"cdd"]; +} + +NSArray* QuickTimeVideoPlayer::scanFolder(NSString *path) +{ + NSMutableArray *tracks = [NSMutableArray arrayWithCapacity:20]; + if (!path) + return tracks; + + NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:path]; + while (NSString *track = [enumerator nextObject]) { + if (![track hasPrefix:@"."]) + [tracks addObject:[path stringByAppendingPathComponent:track]]; + } + return tracks; +} + +void QuickTimeVideoPlayer::setCurrentTrack(int track) +{ + PhononAutoReleasePool pool; + [m_QTMovie release]; + m_QTMovie = 0; + m_currentTime = 0; + m_currentTrack = track; + + if (!m_folderTracks) + return; + if (track < 0 || track >= (int)[m_folderTracks count]) + return; + + NSString *trackPath = [m_folderTracks objectAtIndex:track]; + QTDataReference *dataRef = [QTDataReference dataReferenceWithReferenceToFile:trackPath]; + State currentState = m_state; + openMovieFromDataRef(dataRef); + prepareCurrentMovieForPlayback(); + if (currentState == Playing) + play(); +} + }} QT_END_NAMESPACE -- cgit v0.12 From b5579e01a023800a6fd81193209db00e000a3620 Mon Sep 17 00:00:00 2001 From: J-P Nurmi Date: Mon, 8 Jun 2009 11:05:35 +0200 Subject: Made QTreeWidgetItem::operator<() check if the data is numerical when comparing. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit More information in task 166873. Merge-request: 514 Reviewed-by: Jan-Arve Sæther --- src/gui/itemviews/qtreewidget.cpp | 33 +++++++++++++++++++++++++++--- src/gui/itemviews/qtreewidget_p.h | 1 + tests/auto/qtreewidget/tst_qtreewidget.cpp | 4 ++++ 3 files changed, 35 insertions(+), 3 deletions(-) diff --git a/src/gui/itemviews/qtreewidget.cpp b/src/gui/itemviews/qtreewidget.cpp index a2bfe45..1c87580 100644 --- a/src/gui/itemviews/qtreewidget.cpp +++ b/src/gui/itemviews/qtreewidget.cpp @@ -577,7 +577,7 @@ void QTreeModel::sort(int column, Qt::SortOrder order) if (column < 0 || column >= columnCount()) return; - //layoutAboutToBeChanged and layoutChanged will be called by sortChildren + //layoutAboutToBeChanged and layoutChanged will be called by sortChildren rootItem->sortChildren(column, order, true); } @@ -695,6 +695,29 @@ bool QTreeModel::itemGreaterThan(const QPair &left, } /*! + \internal + + Returns true if the type of the variant \a value + can be casted as double. +*/ +bool QTreeModel::canConvertToDouble(const QVariant &value) +{ + switch (value.type()) { + case QVariant::Bool: + case QVariant::Int: + case QVariant::UInt: + case QVariant::LongLong: + case QVariant::ULongLong: + case QVariant::Double: + case QVariant::Char: + return true; + default: + return false; + } + return false; +} + +/*! \internal */ QList::iterator QTreeModel::sortedInsertionIterator( @@ -1787,7 +1810,11 @@ QVariant QTreeWidgetItem::data(int column, int role) const bool QTreeWidgetItem::operator<(const QTreeWidgetItem &other) const { int column = view ? view->sortColumn() : 0; - return text(column) < other.text(column); + const QVariant v1 = data(column, Qt::DisplayRole); + const QVariant v2 = other.data(column, Qt::DisplayRole); + if (QTreeModel::canConvertToDouble(v1) && QTreeModel::canConvertToDouble(v2)) + return v1.toDouble() < v2.toDouble(); + return v1.toString() < v2.toString(); } #ifndef QT_NO_DATASTREAM @@ -2074,7 +2101,7 @@ void QTreeWidgetItemPrivate::sortChildren(int column, Qt::SortOrder order, bool if (climb) { QList::iterator it = q->children.begin(); for (; it != q->children.end(); ++it) { - //here we call the private object's method to avoid emitting + //here we call the private object's method to avoid emitting //the layoutAboutToBeChanged and layoutChanged signals (*it)->d->sortChildren(column, order, climb); } diff --git a/src/gui/itemviews/qtreewidget_p.h b/src/gui/itemviews/qtreewidget_p.h index a089cf5..96f734d 100644 --- a/src/gui/itemviews/qtreewidget_p.h +++ b/src/gui/itemviews/qtreewidget_p.h @@ -116,6 +116,7 @@ public: const QPair &right); static bool itemGreaterThan(const QPair &left, const QPair &right); + static bool canConvertToDouble(const QVariant &value); static QList::iterator sortedInsertionIterator( const QList::iterator &begin, const QList::iterator &end, diff --git a/tests/auto/qtreewidget/tst_qtreewidget.cpp b/tests/auto/qtreewidget/tst_qtreewidget.cpp index 906332c..32a2c40 100644 --- a/tests/auto/qtreewidget/tst_qtreewidget.cpp +++ b/tests/auto/qtreewidget/tst_qtreewidget.cpp @@ -2434,6 +2434,10 @@ void tst_QTreeWidget::itemOperatorLessThan() item1.setText(0, "b"); item2.setText(0, "a"); QCOMPARE(item1 < item2, true); + tw.sortItems(0, Qt::AscendingOrder); + item1.setData(0, Qt::DisplayRole, 11); + item2.setData(0, Qt::DisplayRole, 2); + QCOMPARE(item1 < item2, false); } } -- cgit v0.12 From fded22680a728ecba93feb87733785537c234b02 Mon Sep 17 00:00:00 2001 From: mae Date: Mon, 8 Jun 2009 12:35:20 +0200 Subject: Extend auto test to cover the emission order of the contentChange() and cursorPositionChanged() singals of QTextDocument. The contentChange() signal is used for the syntax highlighter. --- tests/auto/qtextdocument/tst_qtextdocument.cpp | 32 ++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/tests/auto/qtextdocument/tst_qtextdocument.cpp b/tests/auto/qtextdocument/tst_qtextdocument.cpp index 63a172b..27be372 100644 --- a/tests/auto/qtextdocument/tst_qtextdocument.cpp +++ b/tests/auto/qtextdocument/tst_qtextdocument.cpp @@ -163,6 +163,8 @@ private slots: void testUndoBlocks(); + void receiveCursorPositionChangedAfterContentsChange(); + private: void backgroundImage_checkExpectedHtml(const QTextDocument &doc); @@ -2453,5 +2455,35 @@ void tst_QTextDocument::testUndoBlocks() QCOMPARE(doc->toPlainText(), QString("")); } +class Receiver : public QObject +{ + Q_OBJECT + public: + QString first; + public slots: + void cursorPositionChanged() { + if (first.isEmpty()) + first = QLatin1String("cursorPositionChanged"); + } + + void contentsChange() { + if (first.isEmpty()) + first = QLatin1String("contentsChanged"); + } +}; + +void tst_QTextDocument::receiveCursorPositionChangedAfterContentsChange() +{ + QVERIFY(doc); + doc->setDocumentLayout(new MyAbstractTextDocumentLayout(doc)); + Receiver rec; + connect(doc, SIGNAL(cursorPositionChanged(QTextCursor)), + &rec, SLOT(cursorPositionChanged())); + connect(doc, SIGNAL(contentsChange(int,int,int)), + &rec, SLOT(contentsChange())); + cursor.insertText("Hello World"); + QCOMPARE(rec.first, QString("contentsChanged")); +} + QTEST_MAIN(tst_QTextDocument) #include "tst_qtextdocument.moc" -- cgit v0.12 From 11303c676166cda3aae33e7e97939e9d2942271f Mon Sep 17 00:00:00 2001 From: mae Date: Mon, 8 Jun 2009 12:43:13 +0200 Subject: Revert signal emission order in QTextDocument to 4.5 behaviour This is covered by the autotest tst_QTextDocument::receiveCursorPositionChangedAfterContentsChange() Reviewed-by: con --- src/gui/text/qtextdocument_p.cpp | 8 +++++++- src/gui/text/qtextdocument_p.h | 6 ++++-- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/gui/text/qtextdocument_p.cpp b/src/gui/text/qtextdocument_p.cpp index e1da4be..7700c14 100644 --- a/src/gui/text/qtextdocument_p.cpp +++ b/src/gui/text/qtextdocument_p.cpp @@ -193,6 +193,8 @@ QTextDocumentPrivate::QTextDocumentPrivate() undoEnabled = true; inContentsChange = false; + inEdit = false; + defaultTextOption.setTabStop(80); // same as in qtextengine.cpp defaultTextOption.setWrapMode(QTextOption::WrapAtWordBoundaryOrAnywhere); @@ -439,6 +441,7 @@ void QTextDocumentPrivate::insert(int pos, int strPos, int strLength, int format Q_ASSERT(pos >= 0 && pos < fragments.length()); Q_ASSERT(formats.format(format).isCharFormat()); + beginEdit(); insert_string(pos, strPos, strLength, format, QTextUndoCommand::MoveCursor); if (undoEnabled) { int b = blocks.findNode(pos); @@ -564,6 +567,7 @@ void QTextDocumentPrivate::move(int pos, int to, int length, QTextUndoCommand::O if (pos == to) return; + beginEdit(); const bool needsInsert = to != -1; #if !defined(QT_NO_DEBUG) @@ -1106,6 +1110,8 @@ void QTextDocumentPrivate::finishEdit() if (editBlock) return; + inEdit = false; + if (framesDirty) scan_frames(docChangeFrom, docChangeOldLength, docChangeLength); @@ -1175,7 +1181,7 @@ void QTextDocumentPrivate::adjustDocumentChangesAndCursors(int from, int addedOr for (int i = 0; i < cursors.size(); ++i) { QTextCursorPrivate *curs = cursors.at(i); if (curs->adjustPosition(from, addedOrRemoved, op) == QTextCursorPrivate::CursorMoved) { - if (editBlock) { + if (editBlock || inEdit) { if (!changedCursors.contains(curs)) changedCursors.append(curs); } else { diff --git a/src/gui/text/qtextdocument_p.h b/src/gui/text/qtextdocument_p.h index d754ff0..e10e7ae 100644 --- a/src/gui/text/qtextdocument_p.h +++ b/src/gui/text/qtextdocument_p.h @@ -202,6 +202,7 @@ public: inline void beginEditBlock() { editBlock++; } void joinPreviousEditBlock(); void endEditBlock(); + inline void beginEdit() { inEdit = true; } void finishEdit(); inline bool isInEditBlock() const { return editBlock; } void enableUndoRedo(bool enable); @@ -335,8 +336,9 @@ public: QCss::StyleSheet parsedDefaultStyleSheet; #endif int maximumBlockCount; - bool needsEnsureMaximumBlockCount; - bool inContentsChange; + uint needsEnsureMaximumBlockCount : 1; + uint inContentsChange : 1; + uint inEdit : 1; // between beginEdit() and finishEdit() QSizeF pageSize; QString title; QString url; -- cgit v0.12 From f38c81bfbae39c6f58d87b874d0abdee0d3ac8af Mon Sep 17 00:00:00 2001 From: Bruno Abinader Date: Mon, 8 Jun 2009 13:06:21 +0200 Subject: Reflected the state machine framework API changes on documentation. Signed-off-by: Bruno Abinader Merge-request: 602 Reviewed-by: David Boddie --- doc/src/animation.qdoc | 33 +++++++++++++++++---------------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/doc/src/animation.qdoc b/doc/src/animation.qdoc index b4e603c..c16d6a2 100644 --- a/doc/src/animation.qdoc +++ b/doc/src/animation.qdoc @@ -327,14 +327,14 @@ \section1 Animations and States When using a \l{The State Machine Framework}{state machine}, we - have a special state, QAnimationState, that will play one or more - animations. - - The QState::addAnimatedTransition() convenience function lets you - associate an animation to a state transition. The function will - create the QAnimationState for you, and insert it into the state - machine. We also have the possibility to associate properties with - the states rather than setting the start and end values ourselves. + can associate an animation to a transition between states using a + QSignalTransition or QEventTransition class. These classes are both + derived from QAbstractClass, which defines the convenience function + addAnimation() that enables the appending of one or more animations + triggered when the transition occurs. + + We also have the possibility to associate properties with the + states rather than setting the start and end values ourselves. Below is a complete code example that animates the geometry of a QPushButton. @@ -345,18 +345,19 @@ QStateMachine *machine = new QStateMachine; QState *state1 = new QState(machine->rootState()); - state1->setPropertyOnEntry(button, "geometry", - QRect(0, 0, 100, 30)); + state1->assignProperty(button, "geometry", QRect(0, 0, 100, 30)); machine->setInitialState(state1); QState *state2 = new QState(machine->rootState()); - state2->setPropertyOnEntry(button, "geometry", - QRect(250, 250, 100, 30)); + state2->assignProperty(button, "geometry", QRect(250, 250, 100, 30)); - state1->addAnimatedTransition(button, SIGNAL(clicked()), state2, - new QPropertyAnimation(button, "geometry")); - state2->addAnimatedTransition(button, SIGNAL(clicked()), state1, - new QPropertyAnimation(button, "geometry")); + QSignalTransition *transition1 = state1->addTransition(button, + SIGNAL(clicked()), state2); + transition1->addAnimation(new QPropertyAnimation(button, "geometry")); + + QSignalTransition *transition2 = state2->addTransition(button, + SIGNAL(clicked()), state1); + transition2->addAnimation(new QPropertyAnimation(button, "geometry")); machine->start(); \endcode -- cgit v0.12 From fd6b00fcbc049ba3d7f8f0e6b9913b376130d88f Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 8 Jun 2009 13:25:19 +0200 Subject: qdoc: Updated the code to create references to documents and files. Task-number: 251995 Reviewed-by: Martin Smith --- tools/qdoc3/tree.cpp | 80 +++++++++++++++++++++++++++++++--------------------- 1 file changed, 48 insertions(+), 32 deletions(-) diff --git a/tools/qdoc3/tree.cpp b/tools/qdoc3/tree.cpp index 0fbd438..370bd5a 100644 --- a/tools/qdoc3/tree.cpp +++ b/tools/qdoc3/tree.cpp @@ -1884,23 +1884,25 @@ QString Tree::fullDocumentLocation(const Node *node) const if (!node->url().isEmpty()) return node->url(); + QString parentName; + QString anchorRef; + if (node->type() == Node::Namespace) { // The root namespace has no name - check for this before creating // an attribute containing the location of any documentation. if (!node->fileBase().isEmpty()) - return node->fileBase() + ".html"; + parentName = node->fileBase() + ".html"; else return ""; } else if (node->type() == Node::Fake) { - return node->fileBase() + ".html"; + parentName = node->fileBase() + ".html"; } else if (node->fileBase().isEmpty()) return ""; - QString parentName; Node *parentNode = 0; if ((parentNode = node->relates())) @@ -1912,10 +1914,11 @@ QString Tree::fullDocumentLocation(const Node *node) const case Node::Class: case Node::Namespace: if (parentNode && !parentNode->name().isEmpty()) - return parentName.replace(".html", "") + "-" - + node->fileBase().toLower() + ".html"; + parentName = parentName.replace(".html", "") + "-" + + node->fileBase().toLower() + ".html"; else - return node->fileBase() + ".html"; + parentName = node->fileBase() + ".html"; + break; case Node::Function: { /* @@ -1925,29 +1928,17 @@ QString Tree::fullDocumentLocation(const Node *node) const const FunctionNode *functionNode = static_cast(node); - // Functions can be compatibility functions or be obsolete. - switch (node->status()) { - case Node::Compat: - parentName.replace(".html", "-qt3.html"); - break; - case Node::Obsolete: - parentName.replace(".html", "-obsolete.html"); - break; - default: - ; - } - if (functionNode->metaness() == FunctionNode::Dtor) - return parentName + "#dtor." + functionNode->name().mid(1); + anchorRef = "#dtor." + functionNode->name().mid(1); - if (functionNode->associatedProperty()) + else if (functionNode->associatedProperty()) return fullDocumentLocation(functionNode->associatedProperty()); - if (functionNode->overloadNumber() > 1) - return parentName + "#" + functionNode->name() - + "-" + QString::number(functionNode->overloadNumber()); + else if (functionNode->overloadNumber() > 1) + anchorRef = "#" + functionNode->name() + + "-" + QString::number(functionNode->overloadNumber()); else - return parentName + "#" + functionNode->name(); + anchorRef = "#" + functionNode->name(); } /* @@ -1955,27 +1946,52 @@ QString Tree::fullDocumentLocation(const Node *node) const the latter returns the name in lower-case. For HTML anchors, we need to preserve the case. */ + break; case Node::Enum: - return parentName + "#" + node->name() + "-enum"; + anchorRef = "#" + node->name() + "-enum"; + break; case Node::Typedef: - return parentName + "#" + node->name() + "-typedef"; + anchorRef = "#" + node->name() + "-typedef"; + break; case Node::Property: - return parentName + "#" + node->name() + "-prop"; + anchorRef = "#" + node->name() + "-prop"; + break; case Node::Variable: - return parentName + "#" + node->name() + "-var"; + anchorRef = "#" + node->name() + "-var"; + break; case Node::Target: - return parentName + "#" + Doc::canonicalTitle(node->name()); + anchorRef = "#" + Doc::canonicalTitle(node->name()); + break; case Node::Fake: { - QString pageName = node->name(); - return pageName.replace("/", "-").replace(".", "-") + ".html"; + /* + Use node->fileBase() for fake nodes because they are represented + by pages whose file names are lower-case. + */ + parentName = node->fileBase(); + parentName.replace("/", "-").replace(".", "-"); + parentName += ".html"; } break; default: break; } - return ""; + // Various objects can be compat (deprecated) or obsolete. + if (node->type() != Node::Class && node->type() != Node::Namespace) { + switch (node->status()) { + case Node::Compat: + parentName.replace(".html", "-qt3.html"); + break; + case Node::Obsolete: + parentName.replace(".html", "-obsolete.html"); + break; + default: + ; + } + } + + return parentName.toLower() + anchorRef; } /*! -- cgit v0.12 From 2dbd8c48c11deb7732920d88f8b6c20bf162bd6b Mon Sep 17 00:00:00 2001 From: David Boddie Date: Mon, 8 Jun 2009 13:29:00 +0200 Subject: Doc: Added information about the Fontconfig and FreeType dependencies. Task-number: 250349 Reviewed-by: Trust Me --- doc/src/diagrams/dependencies.lout | 59 +- doc/src/diagrams/x11_dependencies.sk | 1542 +++++++++++++++++++--------------- doc/src/images/x11_dependencies.png | Bin 93480 -> 68043 bytes 3 files changed, 908 insertions(+), 693 deletions(-) diff --git a/doc/src/diagrams/dependencies.lout b/doc/src/diagrams/dependencies.lout index d20f4f1..256f7de 100644 --- a/doc/src/diagrams/dependencies.lout +++ b/doc/src/diagrams/dependencies.lout @@ -1,7 +1,13 @@ +# This file is used to create x11_dependencies.sk, which is then converted to a PNG image. +# +# lout -EPS -o dependencies.eps dependencies.lout +# pstoedit -f sk dependencies.eps x11_dependencies.sk +# makeimage.py x11_dependencies.sk x11_dependencies.png 0.25 --anti-alias + @SysInclude { picture } @SysInclude { tbl } @SysInclude { diag } -# lout -EPS dependencies.lout > dependencies.eps + macro @TTGreenColour { {cmyk 0.40 0.00 1.00 0.01} } macro @TTPurpleColour { {cmyk 0.39 0.39 0.00 0.00} } macro @DefaultColour { rgb { 0.961 0.961 0.863 } } @@ -41,31 +47,33 @@ macro @GlibColour { rgb { 0.7 0.7 0.7 } } div { top } # fmarginbelow { 0c } - aformat { @Cell A | @Cell B | @Cell marginbelow { 0c } font { +2p } C | @Cell D | @Cell E } - bformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell F } - cformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell marginleft { 1.5c } E | @Cell F } - dformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell F } - eformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell F } - fformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell F } - gformat { @Cell A | @Cell B | @Cell C | @Cell D | @StartHSpan @Cell E | @HSpan } + aformat { @Cell A | @Cell B | @StartHSpan @Cell marginbelow { 0c } font { +2p } C | @HSpan | @HSpan | @Cell F | @Cell G} + bformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell F | @Cell G } + cformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell marginleft { 1.5c } F | @Cell G } + dformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell F | @Cell G } + eformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell F | @Cell G } + fformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @Cell F | @Cell G } + gformat { @Cell A | @Cell B | @Cell C | @Cell D | @Cell E | @StartHSpan @Cell F | @HSpan } { @Rowa C { Qt"/"X11 library dependencies } - @Rowb C { QTGUI:: @Node paint { @TTGreenColour } QtGui } - @Rowc B { XCURSOR:: @Node paint { @OptionalColour } Xcursor } - C { XRANDR:: @Node paint { @OptionalColour } Xrandr } - D { XINERAMA:: @Node paint { @OptionalColour } Xinerama } - E { Xi:: @Node paint { @OptionalColour } Xi } - @Rowd C { XRENDER:: @Node paint { @OptionalColour } XRender } - F { Xt:: @Node paint { @DefaultColour } Xt* } - @Rowe A { QTCORE:: @Node paint { @TTPurpleColour } QtCore } - C { XFIXES:: @Node paint { @OptionalColour } Xfixes } - D { XEXT:: @Node paint { @DefaultColour } Xext } - F { SM:: @Node paint { @SMColour } SM } - @Rowf A { PTHREAD:: @Node paint { @PthreadColour } pthread } - B { GLIB:: @Node paint { @GlibColour } Glib } - D { X:: @Node paint { @DefaultColour } X11 } - F { ICE:: @Node paint { @SMColour } ICE } - @Rowg E { + @Rowb D { QTGUI:: @Node paint { @TTGreenColour } QtGui } + @Rowc C { XCURSOR:: @Node paint { @OptionalColour } Xcursor } + D { XRANDR:: @Node paint { @OptionalColour } Xrandr } + E { XINERAMA:: @Node paint { @OptionalColour } Xinerama } + F { Xi:: @Node paint { @OptionalColour } Xi } + @Rowd A { FONTCONFIG:: @Node paint { @OptionalColour } Fontconfig } + D { XRENDER:: @Node paint { @OptionalColour } XRender } + G { Xt:: @Node paint { @DefaultColour } Xt* } + @Rowe A { FREETYPE:: @Node paint { @OptionalColour } FreeType } + B { QTCORE:: @Node paint { @TTPurpleColour } QtCore } + D { XFIXES:: @Node paint { @OptionalColour } Xfixes } + E { XEXT:: @Node paint { @DefaultColour } Xext } + G { SM:: @Node paint { @SMColour } SM } + @Rowf B { PTHREAD:: @Node paint { @PthreadColour } pthread } + C { GLIB:: @Node paint { @GlibColour } Glib } + E { X:: @Node paint { @DefaultColour } X11 } + G { ICE:: @Node paint { @SMColour } ICE } + @Rowg F { @Tbl font { -2p } margin { 0.15f } @@ -101,6 +109,9 @@ macro @GlibColour { rgb { 0.7 0.7 0.7 } } @Arrow from { XEXT } to { X } @VHCurveArrow from { XCURSOR } to { XFIXES } @VHVCurveArrow from { XFIXES } to { X } +@HVCurveArrow from { QTGUI } to { FONTCONFIG } pathstyle { dotted } +@Arrow from { FONTCONFIG } to { FREETYPE } pathstyle { dotted } +@VHVCurveArrow from { FREETYPE } to { PTHREAD } @Link from { C@W } to { D@E } pathstyle { dotted } } } diff --git a/doc/src/diagrams/x11_dependencies.sk b/doc/src/diagrams/x11_dependencies.sk index 5f6b304..a9eb3e3 100644 --- a/doc/src/diagrams/x11_dependencies.sk +++ b/doc/src/diagrams/x11_dependencies.sk @@ -2,1415 +2,1619 @@ document() layout('A4',0) layer('Layer 1',1,1,0,0,(0,0,0)) -G() +fp((0,0,0)) +Fn('Helvetica') +Fs(16) +txt('Qt/X11',(254.1,398.35)) +fp((0,0,0)) +Fn('Helvetica') +Fs(16) +txt('libr',(304.9,398.35)) +fp((0,0,0)) +Fn('Helvetica') +Fs(16) +txt('ar',(326.07,398.35)) +fp((0,0,0)) +Fn('Helvetica') +Fs(16) +txt('y',(340.739,398.35)) +fp((0,0,0)) +Fn('Helvetica') +Fs(16) +txt('dependencies',(352.85,398.35)) fp((0,0,0)) le() b() -bs(268.8,339.25,0) -bs(268.8,337.15,0) -bs(352.8,337.15,0) -bs(352.8,362.2,0) -bs(350.7,362.2,0) -bs(350.7,339.25,0) -bs(268.8,339.25,0) +bs(312.898,344.199,0) +bs(312.898,342.102,0) +bs(396.898,342.102,0) +bs(396.898,367.148,0) +bs(394.801,367.148,0) +bs(394.801,344.199,0) +bs(312.898,344.199,0) bC() -fp((0.59,0.99,0)) +fp((0.594,0.99,0)) le() b() -bs(266.7,339.25,0) -bs(350.7,339.25,0) -bs(350.7,364.3,0) -bs(266.7,364.3,0) -bs(266.7,339.25,0) +bs(310.801,344.199,0) +bs(394.801,344.199,0) +bs(394.801,369.25,0) +bs(310.801,369.25,0) +bs(310.801,344.199,0) lw(1.12) lc(2) b() -bs(266.7,339.25,0) -bs(350.7,339.25,0) +bs(310.801,344.199,0) +bs(394.801,344.199,0) lw(1.12) lc(2) b() -bs(350.7,339.25,0) -bs(350.7,364.3,0) +bs(394.801,344.199,0) +bs(394.801,369.25,0) lw(1.12) lc(2) b() -bs(350.7,364.3,0) -bs(266.7,364.3,0) +bs(394.801,369.25,0) +bs(310.801,369.25,0) lw(1.12) lc(2) b() -bs(266.7,364.3,0) -bs(266.7,339.25,0) +bs(310.801,369.25,0) +bs(310.801,344.199,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('QtGui',(290.95,347)) +txt('QtGui',(335.05,351.95)) fp((0,0,0)) le() b() -bs(111.3,280.05,0) -bs(111.3,277.95,0) -bs(195.3,277.95,0) -bs(195.3,302.15,0) -bs(193.2,302.15,0) -bs(193.2,280.05,0) -bs(111.3,280.05,0) +bs(212.102,285,0) +bs(212.102,282.898,0) +bs(296.102,282.898,0) +bs(296.102,307.102,0) +bs(294,307.102,0) +bs(294,285,0) +bs(212.102,285,0) bC() fp((0.792,0.882,1)) le() b() -bs(109.2,280.05,0) -bs(193.2,280.05,0) -bs(193.2,304.25,0) -bs(109.2,304.25,0) -bs(109.2,280.05,0) +bs(210,285,0) +bs(294,285,0) +bs(294,309.199,0) +bs(210,309.199,0) +bs(210,285,0) lw(1.12) lc(2) b() -bs(109.2,280.05,0) -bs(193.2,280.05,0) +bs(210,285,0) +bs(294,285,0) lw(1.12) lc(2) b() -bs(193.2,280.05,0) -bs(193.2,304.25,0) +bs(294,285,0) +bs(294,309.199,0) lw(1.12) lc(2) b() -bs(193.2,304.25,0) -bs(109.2,304.25,0) +bs(294,309.199,0) +bs(210,309.199,0) lw(1.12) lc(2) b() -bs(109.2,304.25,0) -bs(109.2,280.05,0) +bs(210,309.199,0) +bs(210,285,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('Xcursor',(127.15,287.25)) +txt('Xcursor',(227.95,292.2)) fp((0,0,0)) le() b() -bs(268.8,280.05,0) -bs(268.8,277.95,0) -bs(352.8,277.95,0) -bs(352.8,302.15,0) -bs(350.7,302.15,0) -bs(350.7,280.05,0) -bs(268.8,280.05,0) +bs(312.898,285,0) +bs(312.898,282.898,0) +bs(396.898,282.898,0) +bs(396.898,307.102,0) +bs(394.801,307.102,0) +bs(394.801,285,0) +bs(312.898,285,0) bC() fp((0.792,0.882,1)) le() b() -bs(266.7,280.05,0) -bs(350.7,280.05,0) -bs(350.7,304.25,0) -bs(266.7,304.25,0) -bs(266.7,280.05,0) +bs(310.801,285,0) +bs(394.801,285,0) +bs(394.801,309.199,0) +bs(310.801,309.199,0) +bs(310.801,285,0) lw(1.12) lc(2) b() -bs(266.7,280.05,0) -bs(350.7,280.05,0) +bs(310.801,285,0) +bs(394.801,285,0) lw(1.12) lc(2) b() -bs(350.7,280.05,0) -bs(350.7,304.25,0) +bs(394.801,285,0) +bs(394.801,309.199,0) lw(1.12) lc(2) b() -bs(350.7,304.25,0) -bs(266.7,304.25,0) +bs(394.801,309.199,0) +bs(310.801,309.199,0) lw(1.12) lc(2) b() -bs(266.7,304.25,0) -bs(266.7,280.05,0) +bs(310.801,309.199,0) +bs(310.801,285,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('Xr',(287.8,287.25)) +txt('Xr',(331.9,292.2)) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('andr',(301.7,287.25)) +txt('andr',(345.796,292.2)) fp((0,0,0)) le() b() -bs(426.3,280.05,0) -bs(426.3,277.95,0) -bs(510.3,277.95,0) -bs(510.3,302.15,0) -bs(508.2,302.15,0) -bs(508.2,280.05,0) -bs(426.3,280.05,0) +bs(413.699,285,0) +bs(413.699,282.898,0) +bs(497.699,282.898,0) +bs(497.699,307.102,0) +bs(495.602,307.102,0) +bs(495.602,285,0) +bs(413.699,285,0) bC() fp((0.792,0.882,1)) le() b() -bs(424.2,280.05,0) -bs(508.2,280.05,0) -bs(508.2,304.25,0) -bs(424.2,304.25,0) -bs(424.2,280.05,0) +bs(411.602,285,0) +bs(495.602,285,0) +bs(495.602,309.199,0) +bs(411.602,309.199,0) +bs(411.602,285,0) lw(1.12) lc(2) b() -bs(424.2,280.05,0) -bs(508.2,280.05,0) +bs(411.602,285,0) +bs(495.602,285,0) lw(1.12) lc(2) b() -bs(508.2,280.05,0) -bs(508.2,304.25,0) +bs(495.602,285,0) +bs(495.602,309.199,0) lw(1.12) lc(2) b() -bs(508.2,304.25,0) -bs(424.2,304.25,0) +bs(495.602,309.199,0) +bs(411.602,309.199,0) lw(1.12) lc(2) b() -bs(424.2,304.25,0) -bs(424.2,280.05,0) +bs(411.602,309.199,0) +bs(411.602,285,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('Xiner',(436.55,287.25)) +txt('Xiner',(423.95,292.2)) +fp((0,0,0)) +Fn('Helvetica') +Fs(14) +txt('ama',(456.514,292.2)) +fp((0,0,0)) +le() +b() +bs(548.602,285.102,0) +bs(548.602,283,0) +bs(632.602,283,0) +bs(632.602,307,0) +bs(630.5,307,0) +bs(630.5,285.102,0) +bs(548.602,285.102,0) +bC() +fp((0.792,0.882,1)) +le() +b() +bs(546.5,285.102,0) +bs(630.5,285.102,0) +bs(630.5,309.102,0) +bs(546.5,309.102,0) +bs(546.5,285.102,0) +lw(1.12) +lc(2) +b() +bs(546.5,285.102,0) +bs(630.5,285.102,0) +lw(1.12) +lc(2) +b() +bs(630.5,285.102,0) +bs(630.5,309.102,0) +lw(1.12) +lc(2) +b() +bs(630.5,309.102,0) +bs(546.5,309.102,0) +lw(1.12) +lc(2) +b() +bs(546.5,309.102,0) +bs(546.5,285.102,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('ama',(469.125,287.25)) +txt('Xi',(582.75,292.1)) fp((0,0,0)) le() b() -bs(561.2,280.15,0) -bs(561.2,278.05,0) -bs(645.2,278.05,0) -bs(645.2,302.05,0) -bs(643.1,302.05,0) -bs(643.1,280.15,0) -bs(561.2,280.15,0) +bs(10.5,222.801,0) +bs(10.5,220.699,0) +bs(94.5,220.699,0) +bs(94.5,247.898,0) +bs(92.3984,247.898,0) +bs(92.3984,222.801,0) +bs(10.5,222.801,0) bC() fp((0.792,0.882,1)) le() b() -bs(559.1,280.15,0) -bs(643.1,280.15,0) -bs(643.1,304.15,0) -bs(559.1,304.15,0) -bs(559.1,280.15,0) +bs(8.39844,222.801,0) +bs(92.3984,222.801,0) +bs(92.3984,250,0) +bs(8.39844,250,0) +bs(8.39844,222.801,0) lw(1.12) lc(2) b() -bs(559.1,280.15,0) -bs(643.1,280.15,0) +bs(8.39844,222.801,0) +bs(92.3984,222.801,0) lw(1.12) lc(2) b() -bs(643.1,280.15,0) -bs(643.1,304.15,0) +bs(92.3984,222.801,0) +bs(92.3984,250,0) lw(1.12) lc(2) b() -bs(643.1,304.15,0) -bs(559.1,304.15,0) +bs(92.3984,250,0) +bs(8.39844,250,0) lw(1.12) lc(2) b() -bs(559.1,304.15,0) -bs(559.1,280.15,0) +bs(8.39844,250,0) +bs(8.39844,222.801,0) +fp((0,0,0)) +Fn('Helvetica') +Fs(14) +txt('F',(18.4,232.85)) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('Xi',(595.35,287.15)) +txt('ontconfig',(26.5508,232.85)) fp((0,0,0)) le() b() -bs(268.8,220.85,0) -bs(268.8,218.75,0) -bs(352.8,218.75,0) -bs(352.8,242.95,0) -bs(350.7,242.95,0) -bs(350.7,220.85,0) -bs(268.8,220.85,0) +bs(312.898,225.801,0) +bs(312.898,223.699,0) +bs(396.898,223.699,0) +bs(396.898,247.898,0) +bs(394.801,247.898,0) +bs(394.801,225.801,0) +bs(312.898,225.801,0) bC() fp((0.792,0.882,1)) le() b() -bs(266.7,220.85,0) -bs(350.7,220.85,0) -bs(350.7,245.05,0) -bs(266.7,245.05,0) -bs(266.7,220.85,0) +bs(310.801,225.801,0) +bs(394.801,225.801,0) +bs(394.801,250,0) +bs(310.801,250,0) +bs(310.801,225.801,0) lw(1.12) lc(2) b() -bs(266.7,220.85,0) -bs(350.7,220.85,0) +bs(310.801,225.801,0) +bs(394.801,225.801,0) lw(1.12) lc(2) b() -bs(350.7,220.85,0) -bs(350.7,245.05,0) +bs(394.801,225.801,0) +bs(394.801,250,0) lw(1.12) lc(2) b() -bs(350.7,245.05,0) -bs(266.7,245.05,0) +bs(394.801,250,0) +bs(310.801,250,0) lw(1.12) lc(2) b() -bs(266.7,245.05,0) -bs(266.7,220.85,0) +bs(310.801,250,0) +bs(310.801,225.801,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('XRender',(281.15,228.05)) +txt('XRender',(325.25,233)) fp((0,0,0)) le() b() -bs(662,220.95,0) -bs(662,218.85,0) -bs(746,218.85,0) -bs(746,242.95,0) -bs(743.9,242.95,0) -bs(743.9,220.95,0) -bs(662,220.95,0) +bs(649.398,225.898,0) +bs(649.398,223.801,0) +bs(733.398,223.801,0) +bs(733.398,247.898,0) +bs(731.301,247.898,0) +bs(731.301,225.898,0) +bs(649.398,225.898,0) bC() fp((0.961,0.961,0.863)) le() b() -bs(659.9,220.95,0) -bs(743.9,220.95,0) -bs(743.9,245.05,0) -bs(659.9,245.05,0) -bs(659.9,220.95,0) +bs(647.301,225.898,0) +bs(731.301,225.898,0) +bs(731.301,250,0) +bs(647.301,250,0) +bs(647.301,225.898,0) lw(1.12) lc(2) b() -bs(659.9,220.95,0) -bs(743.9,220.95,0) +bs(647.301,225.898,0) +bs(731.301,225.898,0) lw(1.12) lc(2) b() -bs(743.9,220.95,0) -bs(743.9,245.05,0) +bs(731.301,225.898,0) +bs(731.301,250,0) lw(1.12) lc(2) b() -bs(743.9,245.05,0) -bs(659.9,245.05,0) +bs(731.301,250,0) +bs(647.301,250,0) lw(1.12) lc(2) b() -bs(659.9,245.05,0) -bs(659.9,220.95,0) +bs(647.301,250,0) +bs(647.301,225.898,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('Xt*',(692.9,228.05)) +txt('Xt*',(680.3,233)) fp((0,0,0)) le() b() -bs(10.4998,160.8,0) -bs(10.4998,158.7,0) -bs(94.4998,158.7,0) -bs(94.4998,183.75,0) -bs(92.3999,183.75,0) -bs(92.3999,160.8,0) -bs(10.4998,160.8,0) +bs(10.5,160.801,0) +bs(10.5,158.699,0) +bs(94.5,158.699,0) +bs(94.5,185.699,0) +bs(92.3984,185.699,0) +bs(92.3984,160.801,0) +bs(10.5,160.801,0) +bC() +fp((0.792,0.882,1)) +le() +b() +bs(8.39844,160.801,0) +bs(92.3984,160.801,0) +bs(92.3984,187.801,0) +bs(8.39844,187.801,0) +bs(8.39844,160.801,0) +lw(1.12) +lc(2) +b() +bs(8.39844,160.801,0) +bs(92.3984,160.801,0) +lw(1.12) +lc(2) +b() +bs(92.3984,160.801,0) +bs(92.3984,187.801,0) +lw(1.12) +lc(2) +b() +bs(92.3984,187.801,0) +bs(8.39844,187.801,0) +lw(1.12) +lc(2) +b() +bs(8.39844,187.801,0) +bs(8.39844,160.801,0) +fp((0,0,0)) +Fn('Helvetica') +Fs(14) +txt('F',(21.9,170.8)) +fp((0,0,0)) +Fn('Helvetica') +Fs(14) +txt('reeT',(29.8508,170.8)) +fp((0,0,0)) +Fn('Helvetica') +Fs(14) +txt('ype',(56.9742,170.8)) +fp((0,0,0)) +le() +b() +bs(111.301,161.801,0) +bs(111.301,159.699,0) +bs(195.301,159.699,0) +bs(195.301,184.75,0) +bs(193.199,184.75,0) +bs(193.199,161.801,0) +bs(111.301,161.801,0) bC() fp((0.61,0.61,1)) le() b() -bs(8.3999,160.8,0) -bs(92.3999,160.8,0) -bs(92.3999,185.85,0) -bs(8.3999,185.85,0) -bs(8.3999,160.8,0) +bs(109.199,161.801,0) +bs(193.199,161.801,0) +bs(193.199,186.852,0) +bs(109.199,186.852,0) +bs(109.199,161.801,0) lw(1.12) lc(2) b() -bs(8.3999,160.8,0) -bs(92.3999,160.8,0) +bs(109.199,161.801,0) +bs(193.199,161.801,0) lw(1.12) lc(2) b() -bs(92.3999,160.8,0) -bs(92.3999,185.85,0) +bs(193.199,161.801,0) +bs(193.199,186.852,0) lw(1.12) lc(2) b() -bs(92.3999,185.85,0) -bs(8.3999,185.85,0) +bs(193.199,186.852,0) +bs(109.199,186.852,0) lw(1.12) lc(2) b() -bs(8.3999,185.85,0) -bs(8.3999,160.8,0) +bs(109.199,186.852,0) +bs(109.199,161.801,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('QtCore',(28.1997,168.55)) +txt('QtCore',(129,169.55)) fp((0,0,0)) le() b() -bs(268.8,161.15,0) -bs(268.8,159.05,0) -bs(352.8,159.05,0) -bs(352.8,183.4,0) -bs(350.7,183.4,0) -bs(350.7,161.15,0) -bs(268.8,161.15,0) +bs(312.898,162.148,0) +bs(312.898,160.051,0) +bs(396.898,160.051,0) +bs(396.898,184.398,0) +bs(394.801,184.398,0) +bs(394.801,162.148,0) +bs(312.898,162.148,0) bC() fp((0.792,0.882,1)) le() b() -bs(266.7,161.15,0) -bs(350.7,161.15,0) -bs(350.7,185.5,0) -bs(266.7,185.5,0) -bs(266.7,161.15,0) +bs(310.801,162.148,0) +bs(394.801,162.148,0) +bs(394.801,186.5,0) +bs(310.801,186.5,0) +bs(310.801,162.148,0) lw(1.12) lc(2) b() -bs(266.7,161.15,0) -bs(350.7,161.15,0) +bs(310.801,162.148,0) +bs(394.801,162.148,0) lw(1.12) lc(2) b() -bs(350.7,161.15,0) -bs(350.7,185.5,0) +bs(394.801,162.148,0) +bs(394.801,186.5,0) lw(1.12) lc(2) b() -bs(350.7,185.5,0) -bs(266.7,185.5,0) +bs(394.801,186.5,0) +bs(310.801,186.5,0) lw(1.12) lc(2) b() -bs(266.7,185.5,0) -bs(266.7,161.15,0) +bs(310.801,186.5,0) +bs(310.801,162.148,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('Xfix',(290.1,168.35)) +txt('Xfix',(334.2,169.35)) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('es',(313.038,168.35)) +txt('es',(357.136,169.35)) fp((0,0,0)) le() b() -bs(426.3,161.25,0) -bs(426.3,159.15,0) -bs(510.3,159.15,0) -bs(510.3,183.35,0) -bs(508.2,183.35,0) -bs(508.2,161.25,0) -bs(426.3,161.25,0) +bs(413.699,162.199,0) +bs(413.699,160.102,0) +bs(497.699,160.102,0) +bs(497.699,184.301,0) +bs(495.602,184.301,0) +bs(495.602,162.199,0) +bs(413.699,162.199,0) bC() fp((0.961,0.961,0.863)) le() b() -bs(424.2,161.25,0) -bs(508.2,161.25,0) -bs(508.2,185.45,0) -bs(424.2,185.45,0) -bs(424.2,161.25,0) +bs(411.602,162.199,0) +bs(495.602,162.199,0) +bs(495.602,186.398,0) +bs(411.602,186.398,0) +bs(411.602,162.199,0) lw(1.12) lc(2) b() -bs(424.2,161.25,0) -bs(508.2,161.25,0) +bs(411.602,162.199,0) +bs(495.602,162.199,0) lw(1.12) lc(2) b() -bs(508.2,161.25,0) -bs(508.2,185.45,0) +bs(495.602,162.199,0) +bs(495.602,186.398,0) lw(1.12) lc(2) b() -bs(508.2,185.45,0) -bs(424.2,185.45,0) +bs(495.602,186.398,0) +bs(411.602,186.398,0) lw(1.12) lc(2) b() -bs(424.2,185.45,0) -bs(424.2,161.25,0) +bs(411.602,186.398,0) +bs(411.602,162.199,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('Xe',(452.55,168.45)) +txt('Xe',(439.95,169.4)) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('xt',(469.272,168.45)) +txt('xt',(456.667,169.4)) fp((0,0,0)) le() b() -bs(662,161.05,0) -bs(662,158.95,0) -bs(746,158.95,0) -bs(746,183.5,0) -bs(743.9,183.5,0) -bs(743.9,161.05,0) -bs(662,161.05,0) +bs(649.398,162.051,0) +bs(649.398,159.949,0) +bs(733.398,159.949,0) +bs(733.398,184.5,0) +bs(731.301,184.5,0) +bs(731.301,162.051,0) +bs(649.398,162.051,0) bC() fp((0.761,0.98,0.98)) le() b() -bs(659.9,161.05,0) -bs(743.9,161.05,0) -bs(743.9,185.6,0) -bs(659.9,185.6,0) -bs(659.9,161.05,0) +bs(647.301,162.051,0) +bs(731.301,162.051,0) +bs(731.301,186.602,0) +bs(647.301,186.602,0) +bs(647.301,162.051,0) lw(1.12) lc(2) b() -bs(659.9,161.05,0) -bs(743.9,161.05,0) +bs(647.301,162.051,0) +bs(731.301,162.051,0) lw(1.12) lc(2) b() -bs(743.9,161.05,0) -bs(743.9,185.6,0) +bs(731.301,162.051,0) +bs(731.301,186.602,0) lw(1.12) lc(2) b() -bs(743.9,185.6,0) -bs(659.9,185.6,0) +bs(731.301,186.602,0) +bs(647.301,186.602,0) lw(1.12) lc(2) b() -bs(659.9,185.6,0) -bs(659.9,161.05,0) +bs(647.301,186.602,0) +bs(647.301,162.051,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('SM',(691.9,168.3)) +txt('SM',(679.3,169.3)) fp((0,0,0)) le() b() -bs(10.4998,98.9001,0) -bs(10.4998,96.8003,0) -bs(94.4998,96.8003,0) -bs(94.4998,123.7,0) -bs(92.3999,123.7,0) -bs(92.3999,98.9001,0) -bs(10.4998,98.9001,0) +bs(111.301,98.8984,0) +bs(111.301,96.8008,0) +bs(195.301,96.8008,0) +bs(195.301,123.699,0) +bs(193.199,123.699,0) +bs(193.199,98.8984,0) +bs(111.301,98.8984,0) bC() fp((0.741,0.718,0.42)) le() b() -bs(8.3999,98.9001,0) -bs(92.3999,98.9001,0) -bs(92.3999,125.8,0) -bs(8.3999,125.8,0) -bs(8.3999,98.9001,0) +bs(109.199,98.8984,0) +bs(193.199,98.8984,0) +bs(193.199,125.801,0) +bs(109.199,125.801,0) +bs(109.199,98.8984,0) lw(1.12) lc(2) b() -bs(8.3999,98.9001,0) -bs(92.3999,98.9001,0) +bs(109.199,98.8984,0) +bs(193.199,98.8984,0) lw(1.12) lc(2) b() -bs(92.3999,98.9001,0) -bs(92.3999,125.8,0) +bs(193.199,98.8984,0) +bs(193.199,125.801,0) lw(1.12) lc(2) b() -bs(92.3999,125.8,0) -bs(8.3999,125.8,0) +bs(193.199,125.801,0) +bs(109.199,125.801,0) lw(1.12) lc(2) b() -bs(8.3999,125.8,0) -bs(8.3999,98.9001,0) +bs(109.199,125.801,0) +bs(109.199,98.8984,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('pthread',(27.1499,108.8)) +txt('pthread',(127.95,108.8)) fp((0,0,0)) le() b() -bs(111.3,100.1,0) -bs(111.3,98.0002,0) -bs(195.3,98.0002,0) -bs(195.3,122.55,0) -bs(193.2,122.55,0) -bs(193.2,100.1,0) -bs(111.3,100.1,0) +bs(212.102,100.102,0) +bs(212.102,98,0) +bs(296.102,98,0) +bs(296.102,122.551,0) +bs(294,122.551,0) +bs(294,100.102,0) +bs(212.102,100.102,0) bC() fp((0.7,0.7,0.7)) le() b() -bs(109.2,100.1,0) -bs(193.2,100.1,0) -bs(193.2,124.65,0) -bs(109.2,124.65,0) -bs(109.2,100.1,0) +bs(210,100.102,0) +bs(294,100.102,0) +bs(294,124.648,0) +bs(210,124.648,0) +bs(210,100.102,0) lw(1.12) lc(2) b() -bs(109.2,100.1,0) -bs(193.2,100.1,0) +bs(210,100.102,0) +bs(294,100.102,0) lw(1.12) lc(2) b() -bs(193.2,100.1,0) -bs(193.2,124.65,0) +bs(294,100.102,0) +bs(294,124.648,0) lw(1.12) lc(2) b() -bs(193.2,124.65,0) -bs(109.2,124.65,0) +bs(294,124.648,0) +bs(210,124.648,0) lw(1.12) lc(2) b() -bs(109.2,124.65,0) -bs(109.2,100.1,0) +bs(210,124.648,0) +bs(210,100.102,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('Glib',(139.05,107.35)) +txt('Glib',(239.85,107.35)) fp((0,0,0)) le() b() -bs(426.3,100.35,0) -bs(426.3,98.2502,0) -bs(510.3,98.2502,0) -bs(510.3,122.25,0) -bs(508.2,122.25,0) -bs(508.2,100.35,0) -bs(426.3,100.35,0) +bs(413.699,100.352,0) +bs(413.699,98.25,0) +bs(497.699,98.25,0) +bs(497.699,122.25,0) +bs(495.602,122.25,0) +bs(495.602,100.352,0) +bs(413.699,100.352,0) bC() fp((0.961,0.961,0.863)) le() b() -bs(424.2,100.35,0) -bs(508.2,100.35,0) -bs(508.2,124.35,0) -bs(424.2,124.35,0) -bs(424.2,100.35,0) +bs(411.602,100.352,0) +bs(495.602,100.352,0) +bs(495.602,124.352,0) +bs(411.602,124.352,0) +bs(411.602,100.352,0) lw(1.12) lc(2) b() -bs(424.2,100.35,0) -bs(508.2,100.35,0) +bs(411.602,100.352,0) +bs(495.602,100.352,0) lw(1.12) lc(2) b() -bs(508.2,100.35,0) -bs(508.2,124.35,0) +bs(495.602,100.352,0) +bs(495.602,124.352,0) lw(1.12) lc(2) b() -bs(508.2,124.35,0) -bs(424.2,124.35,0) +bs(495.602,124.352,0) +bs(411.602,124.352,0) lw(1.12) lc(2) b() -bs(424.2,124.35,0) -bs(424.2,100.35,0) +bs(411.602,124.352,0) +bs(411.602,100.352,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('X11',(455.15,107.35)) +txt('X11',(442.55,107.35)) fp((0,0,0)) le() b() -bs(662,100.1,0) -bs(662,98.0002,0) -bs(746,98.0002,0) -bs(746,122.55,0) -bs(743.9,122.55,0) -bs(743.9,100.1,0) -bs(662,100.1,0) +bs(649.398,100.102,0) +bs(649.398,98,0) +bs(733.398,98,0) +bs(733.398,122.551,0) +bs(731.301,122.551,0) +bs(731.301,100.102,0) +bs(649.398,100.102,0) bC() fp((0.761,0.98,0.98)) le() b() -bs(659.9,100.1,0) -bs(743.9,100.1,0) -bs(743.9,124.65,0) -bs(659.9,124.65,0) -bs(659.9,100.1,0) +bs(647.301,100.102,0) +bs(731.301,100.102,0) +bs(731.301,124.648,0) +bs(647.301,124.648,0) +bs(647.301,100.102,0) lw(1.12) lc(2) b() -bs(659.9,100.1,0) -bs(743.9,100.1,0) +bs(647.301,100.102,0) +bs(731.301,100.102,0) lw(1.12) lc(2) b() -bs(743.9,100.1,0) -bs(743.9,124.65,0) +bs(731.301,100.102,0) +bs(731.301,124.648,0) lw(1.12) lc(2) b() -bs(743.9,124.65,0) -bs(659.9,124.65,0) +bs(731.301,124.648,0) +bs(647.301,124.648,0) lw(1.12) lc(2) b() -bs(659.9,124.65,0) -bs(659.9,100.1,0) +bs(647.301,124.648,0) +bs(647.301,100.102,0) fp((0,0,0)) Fn('Helvetica') Fs(14) -txt('ICE',(690.6,107.35)) +txt('ICE',(678,107.35)) fp((0,0,0)) Fn('Helvetica') -txt('some',(585.05,38.7002)) +txt('some',(572.45,38.7)) fp((0,0,0)) Fn('Helvetica') -txt('configur',(617.15,38.7002)) +txt('configur',(604.55,38.7)) fp((0,0,0)) Fn('Helvetica') -txt('ations',(659.733,38.7002)) +txt('ations',(647.13,38.7)) fp((0,0,0)) Fn('Helvetica') -txt('only',(694.4,38.7002)) +txt('only',(681.8,38.7)) fp((0,0,0)) Fn('Helvetica') -txt('*',(568.85,22.5002)) +txt('*',(556.25,22.5)) fp((0,0,0)) Fn('Helvetica') -txt('Xt',(585.05,22.5002)) +txt('Xt',(572.45,22.5)) fp((0,0,0)) Fn('Helvetica') -txt('intr',(599.4,22.5002)) +txt('intr',(586.8,22.5)) fp((0,0,0)) Fn('Helvetica') -txt('insics',(616.217,22.5002)) +txt('insics',(603.61,22.5)) fp((0,0,0)) Fn('Helvetica') -txt('only',(648.95,22.5002)) +txt('only',(636.35,22.5)) lw(1.12) lc(2) -ld((0, 2.4999899999999999)) +ld((0, 2.5)) b() -bs(308.7,339.25,0) -bs(308.7,328.05,0) +bs(352.801,344.199,0) +bs(352.801,333,0) lw(1.12) lc(2) -ld((0, 2.0312000000000001)) +ld((0, 2.03125)) b() -bs(308.7,328.05,0) -bs(308.7,332.6,0) +bs(352.801,333,0) +bs(352.801,337.551,0) lw(1.12) lc(2) ld((0, 2.45438)) b() -bs(308.7,332.6,0) -bs(308.7,332.6,0) -bc(308.7,330.744,309.438,328.963,310.75,327.651,0) +bs(352.801,337.551,0) +bs(352.801,337.551,0) +bc(352.801,335.695,353.539,333.914,354.852,332.602,0) lw(1.12) lc(2) -ld((0, 2.4543599999999999)) +ld((0, 2.45438)) b() -bs(310.75,327.65,0) -bs(310.75,327.651,0) -bc(312.063,326.338,313.844,325.6,315.7,325.6,0) +bs(354.852,332.602,0) +bs(354.852,332.602,0) +bc(356.164,331.289,357.945,330.551,359.801,330.551,0) lw(1.12) lc(2) -ld((0, 2.4639500000000001)) +ld((0, 2.4218799999999998)) b() -bs(315.7,325.6,0) -bs(387.45,325.6,0) +bs(359.801,330.551,0) +bs(403.199,330.551,0) lw(1.12) lc(2) -ld((0, 2.4639500000000001)) +ld((0, 2.4218799999999998)) b() -bs(387.45,325.6,0) -bs(459.2,325.6,0) +bs(403.199,330.551,0) +bs(446.602,330.551,0) lw(1.12) lc(2) ld((0, 2.45438)) b() -bs(459.2,325.6,0) -bs(459.2,325.6,0) -bc(461.056,325.6,462.837,324.863,464.15,323.55,0) +bs(446.602,330.551,0) +bs(446.602,330.551,0) +bc(448.457,330.551,450.238,329.812,451.551,328.5,0) lw(1.12) lc(2) ld((0, 2.45438)) b() -bs(464.15,323.55,0) -bs(464.15,323.55,0) -bc(465.462,322.237,466.2,320.457,466.2,318.6,0) +bs(451.551,328.5,0) +bs(451.551,328.5,0) +bc(452.863,327.188,453.602,325.406,453.602,323.551,0) lw(1.12) lc(2) -ld((0, 2.3437899999999998)) +ld((0, 2.3437399999999999)) b() -bs(466.2,318.6,0) -bs(466.2,313.35,0) +bs(453.602,323.551,0) +bs(453.602,318.301,0) lw(1.12) lc(2) ld((0, 2.5)) b() -bs(466.2,313.35,0) -bs(466.2,311.95,0) +bs(453.602,318.301,0) +bs(453.602,316.898,0) fp((0,0,0)) le() b() -bs(462.35,311.95,0) -bs(466.199,304.25,0) -bs(470.05,311.95,0) +bs(449.75,316.898,0) +bs(453.602,309.199,0) +bs(457.449,316.898,0) lw(1.12) lc(2) -ld((0, 2.4999899999999999)) +ld((0, 2.5)) b() -bs(308.7,339.25,0) -bs(308.7,328.05,0) +bs(352.801,344.199,0) +bs(352.801,333,0) lw(1.12) lc(2) -ld((0, 2.0088900000000001)) +ld((0, 2.0089299999999999)) b() -bs(308.7,328.05,0) -bs(308.7,332.55,0) +bs(352.801,333,0) +bs(352.801,337.5,0) +lw(1.12) +lc(2) +ld((0, 2.4543599999999999)) +b() +bs(352.801,337.5,0) +bs(352.801,337.5,0) +bc(352.801,335.645,353.539,333.863,354.852,332.551,0) lw(1.12) lc(2) ld((0, 2.45438)) b() -bs(308.7,332.55,0) -bs(308.7,332.55,0) -bc(308.7,330.694,309.438,328.913,310.75,327.601,0) +bs(354.852,332.551,0) +bs(354.852,332.551,0) +bc(356.164,331.238,357.945,330.5,359.801,330.5,0) lw(1.12) lc(2) -ld((0, 2.4543599999999999)) +ld((0, 2.4743300000000001)) b() -bs(310.75,327.6,0) -bs(310.75,327.601,0) -bc(312.063,326.288,313.844,325.55,315.7,325.55,0) +bs(359.801,330.5,0) +bs(470.648,330.5,0) lw(1.12) lc(2) -ld((0, 2.4857100000000001)) +ld((0, 2.4743300000000001)) b() -bs(459.2,325.6,0) -bs(594.1,325.55,0) +bs(470.648,330.5,0) +bs(581.5,330.5,0) lw(1.12) lc(2) -ld((0, 2.4543900000000001)) +ld((0, 2.45438)) b() -bs(594.1,325.55,0) -bs(594.1,325.55,0) -bc(595.956,325.55,597.737,324.813,599.05,323.5,0) +bs(581.5,330.5,0) +bs(581.5,330.5,0) +bc(583.355,330.5,585.137,329.762,586.449,328.449,0) lw(1.12) lc(2) -ld((0, 2.4544100000000002)) +ld((0, 2.45438)) b() -bs(599.05,323.5,0) -bs(599.05,323.5,0) -bc(600.362,322.187,601.1,320.407,601.1,318.55,0) +bs(586.449,328.449,0) +bs(586.449,328.449,0) +bc(587.762,327.137,588.5,325.355,588.5,323.5,0) lw(1.12) lc(2) -ld((0, 2.3660899999999998)) +ld((0, 2.36605)) b() -bs(601.1,318.55,0) -bs(601.1,313.25,0) +bs(588.5,323.5,0) +bs(588.5,318.199,0) lw(1.12) lc(2) ld((0, 2.5)) b() -bs(601.1,313.25,0) -bs(601.1,311.85,0) +bs(588.5,318.199,0) +bs(588.5,316.801,0) fp((0,0,0)) le() b() -bs(597.25,311.85,0) -bs(601.099,304.15,0) -bs(604.949,311.85,0) +bs(584.648,316.801,0) +bs(588.5,309.102,0) +bs(592.352,316.801,0) lw(1.12) lc(2) b() -bs(266.7,351.775,0) -bs(255.5,351.775,0) +bs(310.801,356.727,0) +bs(299.602,356.727,0) lw(1.12) lc(2) b() -bs(255.5,351.775,0) -bs(57.3999,351.775,0) +bs(299.602,356.727,0) +bs(158.199,356.727,0) lw(1.12) lc(2) b() -bs(57.3999,351.775,0) -bs(57.3999,351.775,0) -bc(53.5339,351.775,50.3999,348.641,50.3999,344.775,0) +bs(158.199,356.727,0) +bs(158.199,356.727,0) +bc(154.336,356.727,151.199,353.59,151.199,349.727,0) lw(1.12) lc(2) b() -bs(50.3999,344.775,0) -bs(50.3999,194.95,0) +bs(151.199,349.727,0) +bs(151.199,195.949,0) lw(1.12) lc(2) b() -bs(50.3999,194.95,0) -bs(50.3999,193.55,0) +bs(151.199,195.949,0) +bs(151.199,194.551,0) fp((0,0,0)) le() b() -bs(46.5496,193.55,0) -bs(50.3994,185.85,0) -bs(54.2495,193.55,0) +bs(147.352,194.551,0) +bs(151.199,186.852,0) +bs(155.051,194.551,0) lw(1.12) lc(2) b() -bs(50.3999,160.8,0) -bs(50.3999,133.5,0) +bs(151.199,161.801,0) +bs(151.199,133.5,0) fp((0,0,0)) le() b() -bs(46.5496,133.5,0) -bs(50.3994,125.8,0) -bs(54.2495,133.5,0) +bs(147.352,133.5,0) +bs(151.199,125.801,0) +bs(155.051,133.5,0) lw(1.12) lc(2) ld((0, 2)) b() -bs(50.3999,160.8,0) -bs(50.3999,149.6,0) +bs(151.199,161.801,0) +bs(151.199,150.602,0) lw(1.12) lc(2) -ld((0, 1.7745500000000001)) +ld((0, 1.5513600000000001)) b() -bs(50.3999,149.6,0) -bs(50.3999,153.575,0) +bs(151.199,150.602,0) +bs(151.199,154.074,0) lw(1.12) lc(2) -ld((0, 2.4543599999999999)) +ld((0, 2.4543400000000002)) b() -bs(50.3999,153.575,0) -bs(50.3999,153.575,0) -bc(50.3999,151.719,51.1375,149.938,52.4502,148.625,0) +bs(151.199,154.074,0) +bs(151.199,154.074,0) +bc(151.199,152.219,151.938,150.438,153.25,149.125,0) lw(1.12) lc(2) ld((0, 2.4543699999999999)) b() -bs(52.45,148.625,0) -bs(52.4502,148.625,0) -bc(53.7629,147.313,55.5435,146.575,57.3999,146.575,0) +bs(153.25,149.125,0) +bs(153.25,149.125,0) +bc(154.562,147.812,156.344,147.074,158.199,147.074,0) lw(1.12) lc(2) ld((0, 2.4218799999999998)) b() -bs(57.3999,146.575,0) -bs(100.8,146.575,0) +bs(158.199,147.074,0) +bs(201.602,147.074,0) lw(1.12) lc(2) ld((0, 2.4218799999999998)) b() -bs(100.8,146.575,0) -bs(144.2,146.575,0) +bs(201.602,147.074,0) +bs(245,147.074,0) lw(1.12) lc(2) ld((0, 2.45438)) b() -bs(144.2,146.575,0) -bs(144.2,146.575,0) -bc(146.056,146.575,147.837,145.838,149.15,144.525,0) +bs(245,147.074,0) +bs(245,147.074,0) +bc(246.855,147.074,248.637,146.336,249.949,145.023,0) lw(1.12) lc(2) -ld((0, 2.4543699999999999)) +ld((0, 2.4543900000000001)) b() -bs(149.15,144.525,0) -bs(149.15,144.525,0) -bc(150.462,143.212,151.2,141.432,151.2,139.575,0) +bs(249.949,145.023,0) +bs(249.949,145.023,0) +bc(251.262,143.711,252,141.93,252,140.074,0) lw(1.12) lc(2) -ld((0, 1.73363)) +ld((0, 1.88243)) b() -bs(151.2,139.575,0) -bs(151.2,133.75,0) +bs(252,140.074,0) +bs(252,133.75,0) lw(1.12) lc(2) ld((0, 2.5)) b() -bs(151.2,133.75,0) -bs(151.2,132.35,0) +bs(252,133.75,0) +bs(252,132.352,0) fp((0,0,0)) le() b() -bs(147.35,132.35,0) -bs(151.199,124.65,0) -bs(155.05,132.35,0) +bs(248.148,132.352,0) +bs(252,124.648,0) +bs(255.852,132.352,0) lw(1.12) lc(2) b() -bs(350.7,351.775,0) -bs(361.9,351.775,0) +bs(394.801,356.727,0) +bs(406,356.727,0) lw(1.12) lc(2) b() -bs(361.9,351.775,0) -bs(694.9,351.775,0) +bs(406,356.727,0) +bs(682.301,356.727,0) lw(1.12) lc(2) b() -bs(694.9,351.775,0) -bs(694.9,351.775,0) -bc(698.766,351.775,701.9,348.641,701.9,344.775,0) +bs(682.301,356.727,0) +bs(682.301,356.727,0) +bc(686.164,356.727,689.301,353.59,689.301,349.727,0) lw(1.12) lc(2) b() -bs(701.9,344.775,0) -bs(701.9,254.15,0) +bs(689.301,349.727,0) +bs(689.301,259.102,0) lw(1.12) lc(2) b() -bs(701.9,254.15,0) -bs(701.9,252.75,0) +bs(689.301,259.102,0) +bs(689.301,257.699,0) fp((0,0,0)) le() b() -bs(698.05,252.75,0) -bs(701.899,245.05,0) -bs(705.75,252.75,0) +bs(685.449,257.699,0) +bs(689.301,250,0) +bs(693.148,257.699,0) lw(1.12) lc(2) -ld((0, 2.4375200000000001)) +ld((0, 2.4375)) b() -bs(308.7,339.25,0) -bs(308.7,311.95,0) +bs(352.801,344.199,0) +bs(352.801,316.898,0) fp((0,0,0)) le() b() -bs(304.85,311.95,0) -bs(308.699,304.25,0) -bs(312.55,311.95,0) +bs(348.949,316.898,0) +bs(352.801,309.199,0) +bs(356.648,316.898,0) lw(1.12) lc(2) -ld((0, 2.4999899999999999)) +ld((0, 2.5)) b() -bs(308.7,339.25,0) -bs(308.7,328.05,0) +bs(352.801,344.199,0) +bs(352.801,333,0) lw(1.12) lc(2) -ld((0, 2.0312000000000001)) +ld((0, 2.03125)) b() -bs(308.7,328.05,0) -bs(308.7,332.6,0) +bs(352.801,333,0) +bs(352.801,337.551,0) lw(1.12) lc(2) ld((0, 2.45438)) b() -bs(308.7,332.6,0) -bs(308.7,332.6,0) -bc(308.7,330.744,307.962,328.963,306.65,327.651,0) +bs(352.801,337.551,0) +bs(352.801,337.551,0) +bc(352.801,335.695,352.062,333.914,350.75,332.602,0) lw(1.12) lc(2) ld((0, 2.45438)) b() -bs(306.65,327.65,0) -bs(306.65,327.651,0) -bc(305.337,326.338,303.556,325.601,301.7,325.601,0) +bs(350.75,332.602,0) +bs(350.75,332.602,0) +bc(349.438,331.289,347.656,330.551,345.801,330.551,0) lw(1.12) lc(2) -ld((0, 2.4639500000000001)) +ld((0, 2.4218799999999998)) b() -bs(301.7,325.6,0) -bs(229.95,325.6,0) +bs(345.801,330.551,0) +bs(302.398,330.551,0) lw(1.12) lc(2) -ld((0, 2.4639500000000001)) +ld((0, 2.4218799999999998)) b() -bs(229.95,325.6,0) -bs(158.2,325.6,0) +bs(302.398,330.551,0) +bs(259,330.551,0) lw(1.12) lc(2) -ld((0, 2.4543699999999999)) +ld((0, 2.45438)) b() -bs(158.2,325.6,0) -bs(158.2,325.6,0) -bc(156.344,325.6,154.563,324.863,153.25,323.55,0) +bs(259,330.551,0) +bs(259,330.551,0) +bc(257.145,330.551,255.363,329.812,254.051,328.5,0) lw(1.12) lc(2) ld((0, 2.45438)) b() -bs(153.25,323.55,0) -bs(153.25,323.55,0) -bc(151.938,322.237,151.2,320.457,151.2,318.6,0) +bs(254.051,328.5,0) +bs(254.051,328.5,0) +bc(252.738,327.188,252,325.406,252,323.551,0) lw(1.12) lc(2) -ld((0, 2.3437899999999998)) +ld((0, 2.3437399999999999)) b() -bs(151.2,318.6,0) -bs(151.2,313.35,0) +bs(252,323.551,0) +bs(252,318.301,0) lw(1.12) lc(2) ld((0, 2.5)) b() -bs(151.2,313.35,0) -bs(151.2,311.95,0) +bs(252,318.301,0) +bs(252,316.898,0) fp((0,0,0)) le() b() -bs(147.35,311.95,0) -bs(151.199,304.25,0) -bs(155.05,311.95,0) +bs(248.148,316.898,0) +bs(252,309.199,0) +bs(255.852,316.898,0) lw(1.12) lc(2) b() -bs(308.7,280.05,0) -bs(308.7,252.75,0) +bs(352.801,285,0) +bs(352.801,257.699,0) fp((0,0,0)) le() b() -bs(304.85,252.75,0) -bs(308.699,245.05,0) -bs(312.55,252.75,0) +bs(348.949,257.699,0) +bs(352.801,250,0) +bs(356.648,257.699,0) lw(1.12) lc(2) b() -bs(466.2,280.05,0) -bs(466.2,193.15,0) +bs(453.602,285,0) +bs(453.602,194.102,0) fp((0,0,0)) le() b() -bs(462.35,193.15,0) -bs(466.199,185.45,0) -bs(470.05,193.15,0) +bs(449.75,194.102,0) +bs(453.602,186.398,0) +bs(457.449,194.102,0) lw(1.12) lc(2) b() -bs(151.2,280.05,0) -bs(151.2,268.85,0) +bs(252,285,0) +bs(252,273.801,0) lw(1.12) lc(2) b() -bs(151.2,268.85,0) -bs(151.2,239.95,0) +bs(252,273.801,0) +bs(252,244.898,0) lw(1.12) lc(2) b() -bs(151.2,239.95,0) -bs(151.2,239.95,0) -bc(151.2,236.084,154.334,232.95,158.2,232.95,0) +bs(252,244.898,0) +bs(252,244.898,0) +bc(252,241.035,255.137,237.898,259,237.898,0) lw(1.12) lc(2) b() -bs(158.2,232.95,0) -bs(257.6,232.95,0) +bs(259,237.898,0) +bs(301.699,237.898,0) lw(1.12) lc(2) b() -bs(257.6,232.95,0) -bs(259,232.95,0) +bs(301.699,237.898,0) +bs(303.102,237.898,0) fp((0,0,0)) le() b() -bs(259,229.1,0) -bs(266.699,232.95,0) -bs(259,236.8,0) +bs(303.102,234.051,0) +bs(310.801,237.898,0) +bs(303.102,241.75,0) lw(1.12) lc(2) b() -bs(350.7,232.95,0) -bs(361.9,232.95,0) +bs(394.801,237.898,0) +bs(406,237.898,0) lw(1.12) lc(2) b() -bs(361.9,232.95,0) -bs(459.2,232.95,0) +bs(406,237.898,0) +bs(446.602,237.898,0) lw(1.12) lc(2) b() -bs(459.2,232.95,0) -bs(459.2,232.95,0) -bc(463.066,232.95,466.2,229.816,466.2,225.95,0) +bs(446.602,237.898,0) +bs(446.602,237.898,0) +bc(450.465,237.898,453.602,234.762,453.602,230.898,0) lw(1.12) lc(2) b() -bs(466.2,225.95,0) -bs(466.2,194.55,0) +bs(453.602,230.898,0) +bs(453.602,195.5,0) lw(1.12) lc(2) b() -bs(466.2,194.55,0) -bs(466.2,193.15,0) +bs(453.602,195.5,0) +bs(453.602,194.102,0) fp((0,0,0)) le() b() -bs(462.35,193.15,0) -bs(466.199,185.45,0) -bs(470.05,193.15,0) +bs(449.75,194.102,0) +bs(453.602,186.398,0) +bs(457.449,194.102,0) lw(1.12) lc(2) b() -bs(559.1,292.15,0) -bs(547.9,292.15,0) +bs(546.5,297.102,0) +bs(535.301,297.102,0) lw(1.12) lc(2) b() -bs(547.9,292.15,0) -bs(544.5,292.15,0) +bs(535.301,297.102,0) +bs(531.898,297.102,0) lw(1.12) lc(2) b() -bs(544.5,292.15,0) -bs(544.5,292.15,0) -bc(542.643,292.15,540.863,291.413,539.55,290.1,0) +bs(531.898,297.102,0) +bs(531.898,297.102,0) +bc(530.043,297.102,528.262,296.363,526.949,295.051,0) lw(1.12) lc(2) b() -bs(539.55,290.1,0) -bs(539.55,290.1,0) -bc(538.238,288.787,537.5,287.007,537.5,285.15,0) +bs(526.949,295.051,0) +bs(526.949,295.051,0) +bc(525.637,293.738,524.898,291.957,524.898,290.102,0) lw(1.12) lc(2) b() -bs(537.5,285.15,0) -bs(537.5,232.75,0) +bs(524.898,290.102,0) +bs(524.898,235.699,0) lw(1.12) lc(2) b() -bs(537.5,232.75,0) -bs(537.5,180.35,0) +bs(524.898,235.699,0) +bs(524.898,181.301,0) lw(1.12) lc(2) b() -bs(537.5,180.35,0) -bs(537.5,180.35,0) -bc(537.5,178.494,536.762,176.713,535.449,175.401,0) +bs(524.898,181.301,0) +bs(524.898,181.301,0) +bc(524.898,179.445,524.16,177.664,522.852,176.352,0) lw(1.12) lc(2) b() -bs(535.449,175.4,0) -bs(535.449,175.401,0) -bc(534.137,174.088,532.356,173.35,530.5,173.35,0) +bs(522.852,176.352,0) +bs(522.852,176.352,0) +bc(521.539,175.039,519.754,174.301,517.898,174.301,0) lw(1.12) lc(2) b() -bs(530.5,173.35,0) -bs(517.3,173.35,0) +bs(517.898,174.301,0) +bs(504.699,174.301,0) lw(1.12) lc(2) b() -bs(517.3,173.35,0) -bs(515.9,173.35,0) +bs(504.699,174.301,0) +bs(503.301,174.301,0) fp((0,0,0)) le() b() -bs(515.9,177.2,0) -bs(508.2,173.351,0) -bs(515.9,169.5,0) +bs(503.301,178.148,0) +bs(495.602,174.301,0) +bs(503.301,170.449,0) lw(1.12) lc(2) b() -bs(701.9,220.95,0) -bs(701.9,193.3,0) +bs(689.301,225.898,0) +bs(689.301,194.301,0) fp((0,0,0)) le() b() -bs(698.05,193.3,0) -bs(701.899,185.6,0) -bs(705.75,193.3,0) +bs(685.449,194.301,0) +bs(689.301,186.602,0) +bs(693.148,194.301,0) lw(1.12) lc(2) b() -bs(659.9,233,0) -bs(648.7,233,0) +bs(647.301,237.949,0) +bs(636.102,237.949,0) lw(1.12) lc(2) b() -bs(648.7,233,0) -bs(594.9,233,0) +bs(636.102,237.949,0) +bs(582.301,237.949,0) lw(1.12) lc(2) b() -bs(594.9,233,0) -bs(594.9,233,0) -bc(593.043,233,591.263,232.263,589.95,230.95,0) +bs(582.301,237.949,0) +bs(582.301,237.949,0) +bc(580.445,237.949,578.664,237.211,577.352,235.898,0) lw(1.12) lc(2) b() -bs(589.95,230.95,0) -bs(589.95,230.95,0) -bc(588.638,229.637,587.9,227.857,587.9,226,0) +bs(577.352,235.898,0) +bs(577.352,235.898,0) +bc(576.039,234.586,575.301,232.805,575.301,230.949,0) lw(1.12) lc(2) b() -bs(587.9,226,0) -bs(587.9,172.675,0) +bs(575.301,230.949,0) +bs(575.301,175.148,0) lw(1.12) lc(2) b() -bs(587.9,172.675,0) -bs(587.9,119.35,0) +bs(575.301,175.148,0) +bs(575.301,119.352,0) lw(1.12) lc(2) b() -bs(587.9,119.35,0) -bs(587.9,119.35,0) -bc(587.9,117.494,587.162,115.713,585.85,114.401,0) +bs(575.301,119.352,0) +bs(575.301,119.352,0) +bc(575.301,117.496,574.562,115.711,573.25,114.398,0) lw(1.12) lc(2) b() -bs(585.85,114.4,0) -bs(585.85,114.401,0) -bc(584.537,113.088,582.756,112.35,580.9,112.35,0) +bs(573.25,114.398,0) +bs(573.25,114.398,0) +bc(571.938,113.09,570.156,112.352,568.301,112.352,0) lw(1.12) lc(2) b() -bs(580.9,112.35,0) -bs(517.3,112.35,0) +bs(568.301,112.352,0) +bs(504.699,112.352,0) lw(1.12) lc(2) b() -bs(517.3,112.35,0) -bs(515.9,112.35,0) +bs(504.699,112.352,0) +bs(503.301,112.352,0) fp((0,0,0)) le() b() -bs(515.9,116.2,0) -bs(508.2,112.35,0) -bs(515.9,108.5,0) +bs(503.301,116.199,0) +bs(495.602,112.352,0) +bs(503.301,108.5,0) lw(1.12) lc(2) b() -bs(701.9,161.05,0) -bs(701.9,132.35,0) +bs(689.301,162.051,0) +bs(689.301,132.352,0) fp((0,0,0)) le() b() -bs(698.05,132.35,0) -bs(701.899,124.65,0) -bs(705.75,132.35,0) +bs(685.449,132.352,0) +bs(689.301,124.648,0) +bs(693.148,132.352,0) lw(1.12) lc(2) b() -bs(466.2,161.25,0) -bs(466.2,132.05,0) +bs(453.602,162.199,0) +bs(453.602,132.051,0) fp((0,0,0)) le() b() -bs(462.35,132.05,0) -bs(466.199,124.35,0) -bs(470.05,132.05,0) +bs(449.75,132.051,0) +bs(453.602,124.352,0) +bs(457.449,132.051,0) lw(1.12) lc(2) b() -bs(151.2,280.05,0) -bs(151.2,268.85,0) +bs(252,285,0) +bs(252,273.801,0) lw(1.12) lc(2) b() -bs(151.2,268.85,0) -bs(151.2,180.325,0) +bs(252,273.801,0) +bs(252,181.324,0) lw(1.12) lc(2) b() -bs(151.2,180.325,0) -bs(151.2,180.325,0) -bc(151.2,176.459,154.334,173.325,158.2,173.325,0) +bs(252,181.324,0) +bs(252,181.324,0) +bc(252,177.461,255.137,174.324,259,174.324,0) lw(1.12) lc(2) b() -bs(158.2,173.325,0) -bs(257.6,173.325,0) +bs(259,174.324,0) +bs(301.699,174.324,0) lw(1.12) lc(2) b() -bs(257.6,173.325,0) -bs(259,173.325,0) +bs(301.699,174.324,0) +bs(303.102,174.324,0) fp((0,0,0)) le() b() -bs(259,169.475,0) -bs(266.699,173.325,0) -bs(259,177.175,0) +bs(303.102,170.477,0) +bs(310.801,174.324,0) +bs(303.102,178.176,0) lw(1.12) lc(2) b() -bs(308.7,161.15,0) -bs(308.7,149.95,0) +bs(352.801,162.148,0) +bs(352.801,150.949,0) lw(1.12) lc(2) b() -bs(308.7,149.95,0) -bs(308.7,153.6,0) +bs(352.801,150.949,0) +bs(352.801,154.102,0) lw(1.12) lc(2) b() -bs(308.7,153.6,0) -bs(308.7,153.6,0) -bc(308.7,151.744,309.438,149.963,310.75,148.651,0) +bs(352.801,154.102,0) +bs(352.801,154.102,0) +bc(352.801,152.246,353.539,150.461,354.852,149.148,0) lw(1.12) lc(2) b() -bs(310.75,148.65,0) -bs(310.75,148.651,0) -bc(312.063,147.338,313.844,146.6,315.7,146.6,0) +bs(354.852,149.148,0) +bs(354.852,149.148,0) +bc(356.164,147.84,357.945,147.102,359.801,147.102,0) lw(1.12) lc(2) b() -bs(315.7,146.6,0) -bs(387.45,146.6,0) +bs(359.801,147.102,0) +bs(403.199,147.102,0) lw(1.12) lc(2) b() -bs(387.45,146.6,0) -bs(459.2,146.6,0) +bs(403.199,147.102,0) +bs(446.602,147.102,0) lw(1.12) lc(2) b() -bs(459.2,146.6,0) -bs(459.2,146.6,0) -bc(461.056,146.6,462.837,145.863,464.15,144.55,0) +bs(446.602,147.102,0) +bs(446.602,147.102,0) +bc(448.457,147.102,450.238,146.363,451.551,145.051,0) lw(1.12) lc(2) b() -bs(464.15,144.55,0) -bs(464.15,144.55,0) -bc(465.462,143.237,466.2,141.457,466.2,139.6,0) +bs(451.551,145.051,0) +bs(451.551,145.051,0) +bc(452.863,143.738,453.602,141.957,453.602,140.102,0) lw(1.12) lc(2) b() -bs(466.2,139.6,0) -bs(466.2,133.45,0) +bs(453.602,140.102,0) +bs(453.602,133.449,0) lw(1.12) lc(2) b() -bs(466.2,133.45,0) -bs(466.2,132.05,0) +bs(453.602,133.449,0) +bs(453.602,132.051,0) fp((0,0,0)) le() b() -bs(462.35,132.05,0) -bs(466.199,124.35,0) -bs(470.05,132.05,0) +bs(449.75,132.051,0) +bs(453.602,124.352,0) +bs(457.449,132.051,0) lw(1.12) lc(2) -ld((0, 2.2889599999999999)) +ld((0, 2.5)) b() -bs(552.65,41.8,0) -bs(580.85,41.8,0) -G_() -G() -fp((0,0,0)) -Fn('Helvetica') -Fs(16) -txt('libr',(341.317,393.4)) -fp((0,0,0)) -Fn('Helvetica') -Fs(16) -txt('ar',(362.494,393.4)) +bs(310.801,356.727,0) +bs(299.602,356.727,0) +lw(1.12) +lc(2) +ld((0, 2.48563)) +b() +bs(299.602,356.727,0) +bs(57.3984,356.727,0) +lw(1.12) +lc(2) +ld((0, 2.4543699999999999)) +b() +bs(57.3984,356.727,0) +bs(57.3984,356.727,0) +bc(53.5352,356.727,50.3984,353.59,50.3984,349.727,0) +lw(1.12) +lc(2) +ld((0, 2.4519700000000002)) +b() +bs(50.3984,349.727,0) +bs(50.3984,259.102,0) +lw(1.12) +lc(2) +ld((0, 2.5)) +b() +bs(50.3984,259.102,0) +bs(50.3984,257.699,0) fp((0,0,0)) -Fn('Helvetica') -Fs(16) -txt('y',(377.168,393.4)) +le() +b() +bs(46.5508,257.699,0) +bs(50.3984,250,0) +bs(54.25,257.699,0) +lw(1.12) +lc(2) +ld((0, 2.4375100000000001)) +b() +bs(50.3984,222.801,0) +bs(50.3984,195.5,0) fp((0,0,0)) -Fn('Helvetica') -Fs(16) -txt('dependencies',(389.267,393.4)) +le() +b() +bs(46.5508,195.5,0) +bs(50.3984,187.801,0) +bs(54.25,195.5,0) +lw(1.12) +lc(2) +b() +bs(50.3984,160.801,0) +bs(50.3984,154.148,0) +lw(1.12) +lc(2) +b() +bs(50.3984,154.148,0) +bs(50.3984,154.148,0) +bc(50.3984,152.293,51.1367,150.512,52.4492,149.199,0) +lw(1.12) +lc(2) +b() +bs(52.4492,149.199,0) +bs(52.4492,149.199,0) +bc(53.7617,147.887,55.543,147.148,57.3984,147.148,0) +lw(1.12) +lc(2) +b() +bs(57.3984,147.148,0) +bs(100.801,147.148,0) +lw(1.12) +lc(2) +b() +bs(100.801,147.148,0) +bs(144.199,147.148,0) +lw(1.12) +lc(2) +b() +bs(144.199,147.148,0) +bs(144.199,147.148,0) +bc(146.055,147.148,147.836,146.41,149.148,145.102,0) +lw(1.12) +lc(2) +b() +bs(149.148,145.102,0) +bs(149.148,145.102,0) +bc(150.461,143.789,151.199,142.004,151.199,140.148,0) +lw(1.12) +lc(2) +b() +bs(151.199,140.148,0) +bs(151.199,134.898,0) +lw(1.12) +lc(2) +b() +bs(151.199,134.898,0) +bs(151.199,133.5,0) fp((0,0,0)) -Fn('Helvetica') -Fs(16) -txt('Qt for X11',(265.517,393.4)) -G_() +le() +b() +bs(147.352,133.5,0) +bs(151.199,125.801,0) +bs(155.051,133.5,0) +lw(1.12) +lc(2) +ld((0, 2.2889599999999999)) +b() +bs(540.051,41.8008,0) +bs(568.25,41.8008,0) guidelayer('Guide Lines',1,0,0,1,(0,0,1)) grid((0,0,5,5),1,(0,0,1),'Grid') diff --git a/doc/src/images/x11_dependencies.png b/doc/src/images/x11_dependencies.png index 02bce1a..6ad952e 100644 Binary files a/doc/src/images/x11_dependencies.png and b/doc/src/images/x11_dependencies.png differ -- cgit v0.12 From 1034e372f1b9ec972d9f0586321c8f299c3955f0 Mon Sep 17 00:00:00 2001 From: Prasanth Ullattil Date: Mon, 8 Jun 2009 13:31:40 +0200 Subject: Fix GDI object leak. In case the SetWindowRgn() fails, the region object has to be deleted. Task-number: 251293 Reviewed-by: Denis Dzyubenko --- src/gui/kernel/qwidget_win.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/gui/kernel/qwidget_win.cpp b/src/gui/kernel/qwidget_win.cpp index 0f341fd..ea79329 100644 --- a/src/gui/kernel/qwidget_win.cpp +++ b/src/gui/kernel/qwidget_win.cpp @@ -1845,7 +1845,8 @@ void QWidgetPrivate::setMask_sys(const QRegion ®ion) OffsetRgn(wr, offset.x(), offset.y()); Q_ASSERT(q->testAttribute(Qt::WA_WState_Created)); - SetWindowRgn(data.winid, wr, true); + if (!SetWindowRgn(data.winid, wr, true)) + DeleteObject(wr); } void QWidgetPrivate::updateFrameStrut() -- cgit v0.12 From cbb9af732fee50010bb540d0a3dc39e67f2e4e7e Mon Sep 17 00:00:00 2001 From: Roberto Raggi Date: Mon, 8 Jun 2009 14:01:26 +0200 Subject: Compile with gcc 4.0.x --- tools/qdoc3/qdoc3.pro | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/qdoc3/qdoc3.pro b/tools/qdoc3/qdoc3.pro index 5438e5f..ed27669 100644 --- a/tools/qdoc3/qdoc3.pro +++ b/tools/qdoc3/qdoc3.pro @@ -1,8 +1,8 @@ DEFINES += QDOC2_COMPAT DEFINES += QT_NO_CAST_TO_ASCII #DEFINES += QT_NO_CAST_FROM_ASCII -DEFINES += QT_USE_FAST_OPERATOR_PLUS -DEFINES += QT_USE_FAST_CONCATENATION +#DEFINES += QT_USE_FAST_OPERATOR_PLUS +#DEFINES += QT_USE_FAST_CONCATENATION QT = core xml CONFIG += console -- cgit v0.12 From e0405b6b42ddf794935af27a0265ca259c73ce4c Mon Sep 17 00:00:00 2001 From: Ariya Hidayat Date: Mon, 8 Jun 2009 14:00:42 +0200 Subject: Make the easing curve icons more beautiful. Draw the curve with anti-aliasing. Do not use absolute black, but rather a dark black color for the lines. Draw the red and blue dots, indicating the start and end points. Reviewed-by: Jan-Arve --- examples/animation/easing/window.cpp | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/examples/animation/easing/window.cpp b/examples/animation/easing/window.cpp index cf4be15..f575483 100644 --- a/examples/animation/easing/window.cpp +++ b/examples/animation/easing/window.cpp @@ -94,11 +94,24 @@ void Window::createCurveIcons() qreal yAxis = m_iconSize.width()/3; painter.drawLine(0, xAxis, m_iconSize.width(), xAxis); painter.drawLine(yAxis, 0, yAxis, m_iconSize.height()); - painter.setPen(Qt::black); qreal curveScale = m_iconSize.height()/2; - QPoint currentPos(yAxis, xAxis); - + + painter.setPen(Qt::NoPen); + + // start point + painter.setBrush(Qt::red); + QPoint start(yAxis, xAxis - curveScale * curve.valueForProgress(0)); + painter.drawRect(start.x() - 1, start.y() - 1, 3, 3); + + // end point + painter.setBrush(Qt::blue); + QPoint end(yAxis + curveScale, xAxis - curveScale * curve.valueForProgress(1)); + painter.drawRect(end.x() - 1, end.y() - 1, 3, 3); + + painter.setPen(QColor(32, 32, 32)); + painter.setRenderHint(QPainter::Antialiasing, true); + QPoint currentPos(start); for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { QPoint to; to.setX(yAxis + curveScale * t); @@ -106,6 +119,7 @@ void Window::createCurveIcons() painter.drawLine(currentPos, to); currentPos = to; } + painter.setRenderHint(QPainter::Antialiasing, false); QListWidgetItem *item = new QListWidgetItem; item->setIcon(QIcon(pix)); item->setText(metaEnum.key(i)); -- cgit v0.12 From f75ff5e473c2a8fea0092d12c289698e90bff297 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Arve=20S=C3=A6ther?= Date: Mon, 8 Jun 2009 14:24:52 +0200 Subject: Remove trailing whitespace. --- examples/animation/easing/window.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/examples/animation/easing/window.cpp b/examples/animation/easing/window.cpp index f575483..5a1f764 100644 --- a/examples/animation/easing/window.cpp +++ b/examples/animation/easing/window.cpp @@ -41,28 +41,28 @@ #include "window.h" -Window::Window(QWidget *parent) +Window::Window(QWidget *parent) : QWidget(parent), m_iconSize(64, 64) { m_ui.setupUi(this); QButtonGroup *buttonGroup = qFindChild(this); // ### workaround for uic in 4.4 - m_ui.easingCurvePicker->setIconSize(m_iconSize); + m_ui.easingCurvePicker->setIconSize(m_iconSize); m_ui.easingCurvePicker->setMinimumHeight(m_iconSize.height() + 50); buttonGroup->setId(m_ui.lineRadio, 0); buttonGroup->setId(m_ui.circleRadio, 1); - + QEasingCurve dummy; m_ui.periodSpinBox->setValue(dummy.period()); m_ui.amplitudeSpinBox->setValue(dummy.amplitude()); m_ui.overshootSpinBox->setValue(dummy.overshoot()); - + connect(m_ui.easingCurvePicker, SIGNAL(currentRowChanged(int)), this, SLOT(curveChanged(int))); connect(buttonGroup, SIGNAL(buttonClicked(int)), this, SLOT(pathChanged(int))); connect(m_ui.periodSpinBox, SIGNAL(valueChanged(double)), this, SLOT(periodChanged(double))); connect(m_ui.amplitudeSpinBox, SIGNAL(valueChanged(double)), this, SLOT(amplitudeChanged(double))); connect(m_ui.overshootSpinBox, SIGNAL(valueChanged(double)), this, SLOT(overshootChanged(double))); createCurveIcons(); - + QPixmap pix(QLatin1String(":/images/qt-logo.png")); m_item = new PixmapItem(pix); m_scene.addItem(m_item); @@ -94,7 +94,7 @@ void Window::createCurveIcons() qreal yAxis = m_iconSize.width()/3; painter.drawLine(0, xAxis, m_iconSize.width(), xAxis); painter.drawLine(yAxis, 0, yAxis, m_iconSize.height()); - + qreal curveScale = m_iconSize.height()/2; painter.setPen(Qt::NoPen); @@ -141,7 +141,7 @@ void Window::curveChanged(int row) QEasingCurve::Type curveType = (QEasingCurve::Type)row; m_anim->setEasingCurve(curveType); m_anim->setCurrentTime(0); - + bool isElastic = curveType >= QEasingCurve::InElastic && curveType <= QEasingCurve::OutInElastic; bool isBounce = curveType >= QEasingCurve::InBounce && curveType <= QEasingCurve::OutInBounce; m_ui.periodSpinBox->setEnabled(isElastic); -- cgit v0.12 From 4003ec67b479ae9bb14d65464403fcdad6e9f394 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Arve=20S=C3=A6ther?= Date: Mon, 8 Jun 2009 14:27:51 +0200 Subject: Use a QPainterPath instead to draw the graph. This enables the antialiazing to be done on the graph as a whole, and not on every tiny line segment. The result is that the curve is painter prettier. --- examples/animation/easing/window.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/examples/animation/easing/window.cpp b/examples/animation/easing/window.cpp index 5a1f764..8a6d850 100644 --- a/examples/animation/easing/window.cpp +++ b/examples/animation/easing/window.cpp @@ -109,16 +109,16 @@ void Window::createCurveIcons() QPoint end(yAxis + curveScale, xAxis - curveScale * curve.valueForProgress(1)); painter.drawRect(end.x() - 1, end.y() - 1, 3, 3); - painter.setPen(QColor(32, 32, 32)); - painter.setRenderHint(QPainter::Antialiasing, true); - QPoint currentPos(start); + QPainterPath curvePath; + curvePath.moveTo(start); for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { QPoint to; to.setX(yAxis + curveScale * t); to.setY(xAxis - curveScale * curve.valueForProgress(t)); - painter.drawLine(currentPos, to); - currentPos = to; + curvePath.lineTo(to); } + painter.setRenderHint(QPainter::Antialiasing, true); + painter.strokePath(curvePath, QColor(32, 32, 32)); painter.setRenderHint(QPainter::Antialiasing, false); QListWidgetItem *item = new QListWidgetItem; item->setIcon(QIcon(pix)); -- cgit v0.12 From 4662f3984a89b7a702a7d24c02cb30b0a5e76ef1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jan-Arve=20S=C3=A6ther?= Date: Mon, 8 Jun 2009 14:29:55 +0200 Subject: Make sure we draw the complete curve. --- examples/animation/easing/window.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/animation/easing/window.cpp b/examples/animation/easing/window.cpp index 8a6d850..3e44873 100644 --- a/examples/animation/easing/window.cpp +++ b/examples/animation/easing/window.cpp @@ -111,7 +111,7 @@ void Window::createCurveIcons() QPainterPath curvePath; curvePath.moveTo(start); - for (qreal t = 0; t < 1.0; t+=1.0/curveScale) { + for (qreal t = 0; t <= 1.0; t+=1.0/curveScale) { QPoint to; to.setX(yAxis + curveScale * t); to.setY(xAxis - curveScale * curve.valueForProgress(t)); -- cgit v0.12 From b6542eb2b1e44aea5d82ad89b8506c567aef18ad Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 8 Jun 2009 14:46:53 +0200 Subject: Small fix to exported symbol --- src/corelib/tools/qunicodetables_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/tools/qunicodetables_p.h b/src/corelib/tools/qunicodetables_p.h index e588313..5f696dd 100644 --- a/src/corelib/tools/qunicodetables_p.h +++ b/src/corelib/tools/qunicodetables_p.h @@ -178,7 +178,7 @@ namespace QUnicodeTables { } Q_CORE_EXPORT int QT_FASTCALL script(uint ucs4); - Q_CORE_EXPORT_INLINE int QT_FASTCALL script(const QChar &ch) { + inline int script(const QChar &ch) { return script(ch.unicode()); } -- cgit v0.12 From eda070eb1f0e65366eaece43e5d86baf9fb8cd89 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 8 Jun 2009 14:47:13 +0200 Subject: small code cleanup --- src/gui/itemviews/qlistview.cpp | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/src/gui/itemviews/qlistview.cpp b/src/gui/itemviews/qlistview.cpp index 8b50d0e..03ba641 100644 --- a/src/gui/itemviews/qlistview.cpp +++ b/src/gui/itemviews/qlistview.cpp @@ -1100,14 +1100,8 @@ void QListView::paintEvent(QPaintEvent *e) QPainter painter(d->viewport); QRect area = e->rect(); - QVector toBeRendered; -// QVector rects = e->region().rects(); -// for (int i = 0; i < rects.size(); ++i) { -// d->intersectingSet(rects.at(i).translated(horizontalOffset(), verticalOffset())); -// toBeRendered += d->intersectVector; -// } d->intersectingSet(e->rect().translated(horizontalOffset(), verticalOffset()), false); - toBeRendered = d->intersectVector; + const QVector toBeRendered = d->intersectVector; const QModelIndex current = currentIndex(); const QModelIndex hover = d->hover; -- cgit v0.12 From 9281ea186212591e636437d30747e7efd6138af6 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 8 Jun 2009 14:47:33 +0200 Subject: Fixed ListView so that it is able to move items in negative space and still paint them. The autotest is included. Task-number: 254449 Reviewed-by: ogoffart --- src/gui/itemviews/qlistview_p.h | 2 +- tests/auto/qlistview/tst_qlistview.cpp | 51 ++++++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/src/gui/itemviews/qlistview_p.h b/src/gui/itemviews/qlistview_p.h index 4568d8c..6514496 100644 --- a/src/gui/itemviews/qlistview_p.h +++ b/src/gui/itemviews/qlistview_p.h @@ -84,7 +84,7 @@ public: inline bool operator!=(const QListViewItem &other) const { return !(*this == other); } inline bool isValid() const - { return (x > -1) && (y > -1) && (w > 0) && (h > 0) && (indexHint > -1); } + { return rect().isValid() && (indexHint > -1); } inline void invalidate() { x = -1; y = -1; w = 0; h = 0; } inline void resize(const QSize &size) diff --git a/tests/auto/qlistview/tst_qlistview.cpp b/tests/auto/qlistview/tst_qlistview.cpp index f70db14..8338ffa 100644 --- a/tests/auto/qlistview/tst_qlistview.cpp +++ b/tests/auto/qlistview/tst_qlistview.cpp @@ -52,6 +52,7 @@ #include #include #include +#include #if defined(Q_OS_WIN) || defined(Q_OS_WINCE) #include #endif @@ -107,6 +108,7 @@ private slots: void task248430_crashWith0SizedItem(); void task250446_scrollChanged(); void task196118_visualRegionForSelection(); + void task254449_draggingItemToNegativeCoordinates(); void keyboardSearch(); }; @@ -1580,6 +1582,55 @@ void tst_QListView::task196118_visualRegionForSelection() QVERIFY(view.visualRegionForSelection().isEmpty()); } +void tst_QListView::task254449_draggingItemToNegativeCoordinates() +{ + //we'll check that the items are painted correctly + class MyListView : public QListView + { + public: + void setPositionForIndex(const QPoint &position, const QModelIndex &index) + { QListView::setPositionForIndex(position, index); } + + } list; + + QStandardItemModel model(1,1); + QModelIndex index = model.index(0,0); + model.setData(index, QLatin1String("foo")); + list.setModel(&model); + list.setViewMode(QListView::IconMode); + list.show(); + QTest::qWait(200); //makes sure the layout is done + + const QPoint topLeft(-6, 0); + + + list.setPositionForIndex(topLeft, index); + + class MyItemDelegate : public QStyledItemDelegate + { + public: + MyItemDelegate() : numPaints(0) { } + void paint(QPainter *painter, + const QStyleOptionViewItem &option, const QModelIndex &index) const + { + numPaints++; + QStyledItemDelegate::paint(painter, option, index); + } + + mutable int numPaints; + } delegate; + + list.setItemDelegate(&delegate); + + //we'll make sure the item is repainted + delegate.numPaints = 0; + list.viewport()->repaint(); + + QCOMPARE(list.visualRect(index).topLeft(), topLeft); + QCOMPARE(delegate.numPaints, 1); +} + + void tst_QListView::keyboardSearch() { QStringList items; -- cgit v0.12 From a825991ad68f4b999b3063db05e3cdb73fbee834 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Mon, 8 Jun 2009 14:55:56 +0200 Subject: qdoc: Changed to mountain fresh blue. I didn't test this, because I can't build qdoc3 due to changes in QStringBuilder. --- tools/qdoc3/test/classic.css | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index fa0167b..3e2370d 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -14,12 +14,11 @@ H3 { h3.fn,span.fn { - background-color: #d5e1d5; + background-color: #e0eff6; border-width: 1px; border-style: solid; - border-color: #66bc29; + border-color: #3388be #e0eff6 #e9f8ff #e0eff6; font-weight: bold; - -moz-border-radius: 8px 8px 8px 8px; padding: 6px 0px 6px 10px; } -- cgit v0.12 From c7296d97ae0dc92b2383dfd47e1f85aa570d5d0c Mon Sep 17 00:00:00 2001 From: Benjamin Poulain Date: Mon, 8 Jun 2009 16:22:09 +0200 Subject: Sync the French tutorial with the English version Reviewed-by: Pierre --- examples/tutorials/addressbook-fr/part3/addressbook.cpp | 4 +--- examples/tutorials/addressbook-fr/part4/addressbook.cpp | 3 --- examples/tutorials/addressbook-fr/part5/addressbook.cpp | 3 --- examples/tutorials/addressbook-fr/part6/addressbook.cpp | 3 --- examples/tutorials/addressbook-fr/part7/addressbook.cpp | 3 --- 5 files changed, 1 insertion(+), 15 deletions(-) diff --git a/examples/tutorials/addressbook-fr/part3/addressbook.cpp b/examples/tutorials/addressbook-fr/part3/addressbook.cpp index 49c5206..332e808 100644 --- a/examples/tutorials/addressbook-fr/part3/addressbook.cpp +++ b/examples/tutorials/addressbook-fr/part3/addressbook.cpp @@ -125,8 +125,7 @@ void AddressBook::submitContact() if (name == "" || address == "") { QMessageBox::information(this, tr("Empty Field"), - tr("Please enter a name and adderss.")); - return; + tr("Please enter a name and address.")); } if (!contacts.contains(name)) { @@ -136,7 +135,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Add Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } if (contacts.isEmpty()) { diff --git a/examples/tutorials/addressbook-fr/part4/addressbook.cpp b/examples/tutorials/addressbook-fr/part4/addressbook.cpp index 95def9c..06f8a09 100644 --- a/examples/tutorials/addressbook-fr/part4/addressbook.cpp +++ b/examples/tutorials/addressbook-fr/part4/addressbook.cpp @@ -135,7 +135,6 @@ void AddressBook::submitContact() if (name == "" || address == "") { QMessageBox::information(this, tr("Empty Field"), tr("Please enter a name and address.")); - return; } //! [submitContact() function part1] if (currentMode == AddingMode) { @@ -147,7 +146,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Add Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } //! [submitContact() function part1] //! [submitContact() function part2] @@ -162,7 +160,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Edit Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } } else if (oldAddress != address) { QMessageBox::information(this, tr("Edit Successful"), diff --git a/examples/tutorials/addressbook-fr/part5/addressbook.cpp b/examples/tutorials/addressbook-fr/part5/addressbook.cpp index 5afb6b8..af3c2d0 100644 --- a/examples/tutorials/addressbook-fr/part5/addressbook.cpp +++ b/examples/tutorials/addressbook-fr/part5/addressbook.cpp @@ -142,7 +142,6 @@ void AddressBook::submitContact() if (name == "" || address == "") { QMessageBox::information(this, tr("Empty Field"), tr("Please enter a name and address.")); - return; } if (currentMode == AddingMode) { @@ -154,7 +153,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Add Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } } else if (currentMode == EditingMode) { @@ -167,7 +165,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Edit Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } } else if (oldAddress != address) { QMessageBox::information(this, tr("Edit Successful"), diff --git a/examples/tutorials/addressbook-fr/part6/addressbook.cpp b/examples/tutorials/addressbook-fr/part6/addressbook.cpp index b7cd446..5f31c99 100644 --- a/examples/tutorials/addressbook-fr/part6/addressbook.cpp +++ b/examples/tutorials/addressbook-fr/part6/addressbook.cpp @@ -148,7 +148,6 @@ void AddressBook::submitContact() if (name == "" || address == "") { QMessageBox::information(this, tr("Empty Field"), tr("Please enter a name and address.")); - return; } if (currentMode == AddingMode) { @@ -160,7 +159,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Add Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } } else if (currentMode == EditingMode) { @@ -173,7 +171,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Edit Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } } else if (oldAddress != address) { QMessageBox::information(this, tr("Edit Successful"), diff --git a/examples/tutorials/addressbook-fr/part7/addressbook.cpp b/examples/tutorials/addressbook-fr/part7/addressbook.cpp index 2f81d2b..8be4d2b 100644 --- a/examples/tutorials/addressbook-fr/part7/addressbook.cpp +++ b/examples/tutorials/addressbook-fr/part7/addressbook.cpp @@ -150,7 +150,6 @@ void AddressBook::submitContact() if (name == "" || address == "") { QMessageBox::information(this, tr("Empty Field"), tr("Please enter a name and address.")); - return; } if (currentMode == AddingMode) { @@ -162,7 +161,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Add Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } } else if (currentMode == EditingMode) { @@ -175,7 +173,6 @@ void AddressBook::submitContact() } else { QMessageBox::information(this, tr("Edit Unsuccessful"), tr("Sorry, \"%1\" is already in your address book.").arg(name)); - return; } } else if (oldAddress != address) { QMessageBox::information(this, tr("Edit Successful"), -- cgit v0.12 From 168f75927390d4ab726870946d60604abf994654 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 8 Jun 2009 14:55:54 +0200 Subject: Small simplification on code --- src/corelib/io/qnoncontiguousbytedevice_p.h | 5 --- src/corelib/kernel/qobject.cpp | 4 +-- src/corelib/plugin/qplugin.h | 2 +- src/corelib/thread/qthread.cpp | 6 ---- src/corelib/thread/qthread_p.h | 54 +++++++++++++++-------------- src/gui/itemviews/qtablewidget.cpp | 10 +++--- 6 files changed, 35 insertions(+), 46 deletions(-) diff --git a/src/corelib/io/qnoncontiguousbytedevice_p.h b/src/corelib/io/qnoncontiguousbytedevice_p.h index acfc6eb..562b759 100644 --- a/src/corelib/io/qnoncontiguousbytedevice_p.h +++ b/src/corelib/io/qnoncontiguousbytedevice_p.h @@ -96,7 +96,6 @@ public: class QNonContiguousByteDeviceByteArrayImpl : public QNonContiguousByteDevice { - Q_OBJECT public: QNonContiguousByteDeviceByteArrayImpl(QByteArray *ba); ~QNonContiguousByteDeviceByteArrayImpl(); @@ -112,7 +111,6 @@ protected: class QNonContiguousByteDeviceRingBufferImpl : public QNonContiguousByteDevice { - Q_OBJECT public: QNonContiguousByteDeviceRingBufferImpl(QRingBuffer *rb); ~QNonContiguousByteDeviceRingBufferImpl(); @@ -129,7 +127,6 @@ protected: class QNonContiguousByteDeviceIoDeviceImpl : public QNonContiguousByteDevice { - Q_OBJECT public: QNonContiguousByteDeviceIoDeviceImpl(QIODevice *d); ~QNonContiguousByteDeviceIoDeviceImpl(); @@ -151,7 +148,6 @@ protected: class QNonContiguousByteDeviceBufferImpl : public QNonContiguousByteDevice { - Q_OBJECT public: QNonContiguousByteDeviceBufferImpl(QBuffer *b); ~QNonContiguousByteDeviceBufferImpl(); @@ -169,7 +165,6 @@ protected: // ... and the reverse thing class QByteDeviceWrappingIoDevice : public QIODevice { - Q_OBJECT public: QByteDeviceWrappingIoDevice (QNonContiguousByteDevice *bd); ~QByteDeviceWrappingIoDevice (); diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index 1501351..5e33a71 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -2228,11 +2228,11 @@ static void err_method_notfound(const QObject *object, if (strchr(method,')') == 0) // common typing mistake qWarning("Object::%s: Parentheses expected, %s %s::%s%s%s", func, type, object->metaObject()->className(), method+1, - loc ? " in ":"\0", loc ? loc : "\0"); + loc ? " in ": "", loc ? loc : ""); else qWarning("Object::%s: No such %s %s::%s%s%s", func, type, object->metaObject()->className(), method+1, - loc ? " in ":"\0", loc ? loc : "\0"); + loc ? " in ": "", loc ? loc : ""); } diff --git a/src/corelib/plugin/qplugin.h b/src/corelib/plugin/qplugin.h index 121a875..e3b9d32 100644 --- a/src/corelib/plugin/qplugin.h +++ b/src/corelib/plugin/qplugin.h @@ -131,7 +131,7 @@ struct qt_plugin_instance_deleter "pattern=""QT_PLUGIN_VERIFICATION_DATA""\n" \ "version="QT_VERSION_STR"\n" \ "debug="QPLUGIN_DEBUG_STR"\n" \ - "buildkey="QT_BUILD_KEY"\0"; + "buildkey="QT_BUILD_KEY; # if defined (Q_OS_WIN32) && defined(Q_CC_BOR) # define Q_STANDARD_CALL __stdcall diff --git a/src/corelib/thread/qthread.cpp b/src/corelib/thread/qthread.cpp index 2fb6335..8fba574 100644 --- a/src/corelib/thread/qthread.cpp +++ b/src/corelib/thread/qthread.cpp @@ -113,12 +113,6 @@ QThreadData::~QThreadData() // fprintf(stderr, "QThreadData %p destroyed\n", this); } -QThreadData *QThreadData::get2(QThread *thread) -{ - Q_ASSERT_X(thread != 0, "QThread", "internal error"); - return thread->d_func()->data; -} - void QThreadData::ref() { #ifndef QT_NO_THREAD diff --git a/src/corelib/thread/qthread_p.h b/src/corelib/thread/qthread_p.h index 75293ce..eb290db 100644 --- a/src/corelib/thread/qthread_p.h +++ b/src/corelib/thread/qthread_p.h @@ -107,32 +107,6 @@ public: { } }; -class Q_CORE_EXPORT QThreadData -{ - QAtomicInt _ref; - -public: - QThreadData(int initialRefCount = 1); - ~QThreadData(); - - static QThreadData *current(); - static QThreadData *get2(QThread *thread); - - void ref(); - void deref(); - - QThread *thread; - bool quitNow; - int loopLevel; - QAbstractEventDispatcher *eventDispatcher; - QStack eventLoops; - QPostEventList postEventList; - bool canWait; - QMap tls; - - QMutex mutex; -}; - #ifndef QT_NO_THREAD class QThreadPrivate : public QObjectPrivate { @@ -210,6 +184,34 @@ public: #endif // QT_NO_THREAD +class QThreadData +{ + QAtomicInt _ref; + +public: + QThreadData(int initialRefCount = 1); + ~QThreadData(); + + static QThreadData *current(); + static QThreadData *get2(QThread *thread) + { Q_ASSERT_X(thread != 0, "QThread", "internal error"); return thread->d_func()->data; } + + + void ref(); + void deref(); + + QThread *thread; + bool quitNow; + int loopLevel; + QAbstractEventDispatcher *eventDispatcher; + QStack eventLoops; + QPostEventList postEventList; + bool canWait; + QMap tls; + + QMutex mutex; +}; + QT_END_NAMESPACE #endif // QTHREAD_P_H diff --git a/src/gui/itemviews/qtablewidget.cpp b/src/gui/itemviews/qtablewidget.cpp index e88301e..8cb2e55 100644 --- a/src/gui/itemviews/qtablewidget.cpp +++ b/src/gui/itemviews/qtablewidget.cpp @@ -1662,10 +1662,9 @@ void QTableWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex ¤t, void QTableWidgetPrivate::_q_sort() { - Q_Q(QTableWidget); if (sortingEnabled) { - int column = q->horizontalHeader()->sortIndicatorSection(); - Qt::SortOrder order = q->horizontalHeader()->sortIndicatorOrder(); + int column = horizontalHeader->sortIndicatorSection(); + Qt::SortOrder order = horizontalHeader->sortIndicatorOrder(); model()->sort(column, order); } } @@ -1673,11 +1672,10 @@ void QTableWidgetPrivate::_q_sort() void QTableWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { - Q_Q(QTableWidget); if (sortingEnabled && topLeft.isValid() && bottomRight.isValid()) { - int column = q->horizontalHeader()->sortIndicatorSection(); + int column = horizontalHeader->sortIndicatorSection(); if (column >= topLeft.column() && column <= bottomRight.column()) { - Qt::SortOrder order = q->horizontalHeader()->sortIndicatorOrder(); + Qt::SortOrder order = horizontalHeader->sortIndicatorOrder(); model()->ensureSorted(column, order, topLeft.row(), bottomRight.row()); } } -- cgit v0.12 From 4336436b8113d6a80428d70beda40a89713d04db Mon Sep 17 00:00:00 2001 From: Alex Cucos Date: Mon, 8 Jun 2009 16:29:18 +0200 Subject: Clip region to screen coordinates before setting its component rectangles dirty. When using Qt/E with VNC screen driver on top of the Linux framebuffer (export QWS_DISPLAY="VNC:LinuxFb") the region to be exposed needs be clipped to the real screen to avoid possible negative coordinates which in turn cause access to invalid memory locations when comparing the content of the VNC buffer with the Linux framebuffer. Merge-request: 603 Reviewed-by: Tom Cooksey --- src/gui/embedded/qscreenproxy_qws.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gui/embedded/qscreenproxy_qws.cpp b/src/gui/embedded/qscreenproxy_qws.cpp index 5b8f6f0..7652bd9 100644 --- a/src/gui/embedded/qscreenproxy_qws.cpp +++ b/src/gui/embedded/qscreenproxy_qws.cpp @@ -279,6 +279,7 @@ void QProxyScreen::exposeRegion(QRegion r, int changing) } realScreen->exposeRegion(r, changing); + r &= realScreen->region(); const QVector rects = r.rects(); for (int i = 0; i < rects.size(); ++i) -- cgit v0.12 From 9736f27a0a6c3dde4d1493e5129557e05160e546 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Mon, 8 Jun 2009 16:37:48 +0200 Subject: Make sure that indexes in the autogenerated locale info do not exceed 16bit range. Reviewed-By: TrustMe --- util/local_database/qlocalexml2cpp.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/util/local_database/qlocalexml2cpp.py b/util/local_database/qlocalexml2cpp.py index a9abe22..af6da33 100755 --- a/util/local_database/qlocalexml2cpp.py +++ b/util/local_database/qlocalexml2cpp.py @@ -237,7 +237,17 @@ class StringData: return self.hash[s] lst = map(lambda x: hex(ord(x)), s) - token = StringDataToken(len(self.data), len(lst)) + index = len(self.data) + if index >= 65535: + print "\n\n\n#error Data index is too big!" + sys.stderr.write ("\n\n\nERROR: index exceeds the uint16 range! index = %d\n" % index) + sys.exit(1) + size = len(lst) + if size >= 65535: + print "\n\n\n#error Data is too big!" + sys.stderr.write ("\n\n\nERROR: data size exceeds the uint16 range! size = %d\n" % size) + sys.exit(1) + token = StringDataToken(index, size) self.hash[s] = token self.data += lst return token -- cgit v0.12 From 3fdc5e9ca07c8058aef29d1a1e434b3ebf7815ae Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 8 Jun 2009 16:55:14 +0200 Subject: Reduce the members in QLocale to 16bit integer instea of 32 bits. That reduces memory usage. Reviewed-by: denis --- src/corelib/tools/qlocale_p.h | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/src/corelib/tools/qlocale_p.h b/src/corelib/tools/qlocale_p.h index b07b948..ed7fc10 100644 --- a/src/corelib/tools/qlocale_p.h +++ b/src/corelib/tools/qlocale_p.h @@ -140,29 +140,29 @@ public: QString dateTimeToString(const QString &format, const QDate *date, const QTime *time, const QLocale *q) const; - quint32 m_language_id, m_country_id; + quint16 m_language_id, m_country_id; quint16 m_decimal, m_group, m_list, m_percent, m_zero, m_minus, m_plus, m_exponential; - quint32 m_short_date_format_idx, m_short_date_format_size; - quint32 m_long_date_format_idx, m_long_date_format_size; - quint32 m_short_time_format_idx, m_short_time_format_size; - quint32 m_long_time_format_idx, m_long_time_format_size; - quint32 m_standalone_short_month_names_idx, m_standalone_short_month_names_size; - quint32 m_standalone_long_month_names_idx, m_standalone_long_month_names_size; - quint32 m_standalone_narrow_month_names_idx, m_standalone_narrow_month_names_size; - quint32 m_short_month_names_idx, m_short_month_names_size; - quint32 m_long_month_names_idx, m_long_month_names_size; - quint32 m_narrow_month_names_idx, m_narrow_month_names_size; - quint32 m_standalone_short_day_names_idx, m_standalone_short_day_names_size; - quint32 m_standalone_long_day_names_idx, m_standalone_long_day_names_size; - quint32 m_standalone_narrow_day_names_idx, m_standalone_narrow_day_names_size; - quint32 m_short_day_names_idx, m_short_day_names_size; - quint32 m_long_day_names_idx, m_long_day_names_size; - quint32 m_narrow_day_names_idx, m_narrow_day_names_size; - quint32 m_am_idx, m_am_size; - quint32 m_pm_idx, m_pm_size; + quint16 m_short_date_format_idx, m_short_date_format_size; + quint16 m_long_date_format_idx, m_long_date_format_size; + quint16 m_short_time_format_idx, m_short_time_format_size; + quint16 m_long_time_format_idx, m_long_time_format_size; + quint16 m_standalone_short_month_names_idx, m_standalone_short_month_names_size; + quint16 m_standalone_long_month_names_idx, m_standalone_long_month_names_size; + quint16 m_standalone_narrow_month_names_idx, m_standalone_narrow_month_names_size; + quint16 m_short_month_names_idx, m_short_month_names_size; + quint16 m_long_month_names_idx, m_long_month_names_size; + quint16 m_narrow_month_names_idx, m_narrow_month_names_size; + quint16 m_standalone_short_day_names_idx, m_standalone_short_day_names_size; + quint16 m_standalone_long_day_names_idx, m_standalone_long_day_names_size; + quint16 m_standalone_narrow_day_names_idx, m_standalone_narrow_day_names_size; + quint16 m_short_day_names_idx, m_short_day_names_size; + quint16 m_long_day_names_idx, m_long_day_names_size; + quint16 m_narrow_day_names_idx, m_narrow_day_names_size; + quint16 m_am_idx, m_am_size; + quint16 m_pm_idx, m_pm_size; }; inline char QLocalePrivate::digitToCLocale(const QChar &in) const -- cgit v0.12 From 917d812013b3c34bfe71e2edfd8caa7ebd958e55 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 8 Jun 2009 17:21:00 +0200 Subject: Reduce binary size by using 16bits integers in static data over 32 bits. Reviewed-by: ogoffart --- src/corelib/xml/qxmlstream_p.h | 41 ++++++++++++++++++----------------------- 1 file changed, 18 insertions(+), 23 deletions(-) diff --git a/src/corelib/xml/qxmlstream_p.h b/src/corelib/xml/qxmlstream_p.h index cf1d228..26509ff 100644 --- a/src/corelib/xml/qxmlstream_p.h +++ b/src/corelib/xml/qxmlstream_p.h @@ -127,27 +127,22 @@ public: GOTO_CHECK_OFFSET = 1017 }; - static const char *const spell []; - static const int lhs []; - static const int rhs []; - static const int goto_default []; - static const int action_default []; - static const int action_index []; - static const int action_info []; - static const int action_check []; + static const char *const spell []; + static const qint16 lhs []; + static const qint16 rhs []; + static const qint16 goto_default []; + static const qint16 action_default []; + static const qint16 action_index []; + static const qint16 action_info []; + static const qint16 action_check []; static inline int nt_action (int state, int nt) { - const int *const goto_index = &action_index [GOTO_INDEX_OFFSET]; - const int *const goto_check = &action_check [GOTO_CHECK_OFFSET]; - - const int yyn = goto_index [state] + nt; - - if (yyn < 0 || goto_check [yyn] != nt) + const int yyn = action_index [GOTO_INDEX_OFFSET + state] + nt; + if (yyn < 0 || action_check [GOTO_CHECK_OFFSET + yyn] != nt) return goto_default [nt]; - const int *const goto_info = &action_info [GOTO_INFO_OFFSET]; - return goto_info [yyn]; + return action_info [GOTO_INFO_OFFSET + yyn]; } static inline int t_action (int state, int token) @@ -170,7 +165,7 @@ const char *const QXmlStreamReader_Table::spell [] = { "EMPTY", "ANY", "PCDATA", 0, 0, 0, 0, "CDATA", "ID", "IDREF", "IDREFS", "ENTITIES", "NMTOKEN", "NMTOKENS", " Date: Mon, 8 Jun 2009 18:38:51 +0200 Subject: openUrl("mailto:") fails to open Thunderbird on windows. Thunderbird sets only the user level shell association for mailto. This is now being read before the default mail application registry. The registry crawling could have been avoided by using the ShellExecute() but it supports only around 2KBytes of data as parameter, so we will continue using CreateProcess(). Task-number: 251554 Reviewed-by: Jens Bache-Wiig --- src/gui/util/qdesktopservices_win.cpp | 64 +++++++++++++++-------------------- 1 file changed, 28 insertions(+), 36 deletions(-) diff --git a/src/gui/util/qdesktopservices_win.cpp b/src/gui/util/qdesktopservices_win.cpp index 0449cba..8d2701c 100644 --- a/src/gui/util/qdesktopservices_win.cpp +++ b/src/gui/util/qdesktopservices_win.cpp @@ -98,32 +98,35 @@ static bool launchWebBrowser(const QUrl &url) { if (url.scheme() == QLatin1String("mailto")) { //Retrieve the commandline for the default mail client - //the key used below is the command line for the mailto: shell command + //the default key used below is the command line for the mailto: shell command DWORD bufferSize = 2 * MAX_PATH; long returnValue = -1; QString command; HKEY handle; LONG res; - QT_WA ({ - res = RegOpenKeyExW(HKEY_CLASSES_ROOT, L"mailto\\Shell\\Open\\Command", 0, KEY_READ, &handle); - if (res != ERROR_SUCCESS) - return false; - - wchar_t keyValue[2 * MAX_PATH] = {0}; - returnValue = RegQueryValueExW(handle, L"", 0, 0, reinterpret_cast(keyValue), &bufferSize); - if (!returnValue) - command = QString::fromRawData((QChar*)keyValue, bufferSize); - }, { - res = RegOpenKeyExA(HKEY_CLASSES_ROOT, "mailto\\Shell\\Open\\Command", 0, KEY_READ, &handle); - if (res != ERROR_SUCCESS) - return false; - - char keyValue[2 * MAX_PATH] = {0}; - returnValue = RegQueryValueExA(handle, "", 0, 0, reinterpret_cast(keyValue), &bufferSize); + wchar_t keyValue[2 * MAX_PATH] = {0}; + QString keyName(QLatin1String("mailto")); + + //Check if user has set preference, otherwise use default. + res = RegOpenKeyExW(HKEY_CURRENT_USER, + L"Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\mailto\\UserChoice", + 0, KEY_READ, &handle); + if (res == ERROR_SUCCESS) { + returnValue = RegQueryValueEx(handle, L"Progid", 0, 0, reinterpret_cast(keyValue), &bufferSize); if (!returnValue) - command = QString::fromLocal8Bit(keyValue); - }); + keyName = QString::fromUtf16(keyValue); + RegCloseKey(handle); + } + keyName += QLatin1String("\\Shell\\Open\\Command"); + res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyName.utf16(), 0, KEY_READ, &handle); + if (res != ERROR_SUCCESS) + return false; + + bufferSize = 2 * MAX_PATH; + returnValue = RegQueryValueExW(handle, L"", 0, 0, reinterpret_cast(keyValue), &bufferSize); + if (!returnValue) + command = QString::fromRawData((QChar*)keyValue, bufferSize); RegCloseKey(handle); if(returnValue) @@ -145,19 +148,11 @@ static bool launchWebBrowser(const QUrl &url) //start the process PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); - QT_WA ({ - STARTUPINFO si; - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); - - returnValue = CreateProcess(NULL, (TCHAR*)command.utf16(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); - }, { - STARTUPINFOA si; - ZeroMemory(&si, sizeof(si)); - si.cb = sizeof(si); + STARTUPINFO si; + ZeroMemory(&si, sizeof(si)); + si.cb = sizeof(si); - returnValue = CreateProcessA(NULL, command.toLocal8Bit().data(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); - }); + returnValue = CreateProcess(NULL, (TCHAR*)command.utf16(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); if (!returnValue) return false; @@ -171,11 +166,8 @@ static bool launchWebBrowser(const QUrl &url) return false; quintptr returnValue; - QT_WA ({ - returnValue = (quintptr)ShellExecute(0, 0, (TCHAR *) QString::fromUtf8(url.toEncoded().constData()).utf16(), 0, 0, SW_SHOWNORMAL); - } , { - returnValue = (quintptr)ShellExecuteA(0, 0, url.toEncoded().constData(), 0, 0, SW_SHOWNORMAL); - }); + returnValue = (quintptr)ShellExecute(0, 0, (TCHAR *) QString::fromUtf8(url.toEncoded().constData()).utf16(), + 0, 0, SW_SHOWNORMAL); return (returnValue > 32); } -- cgit v0.12 From f64ef46fdb49c609a434ad92ce01ee40116d6545 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 9 Jun 2009 08:53:44 +1000 Subject: Compile fix for WinCE. --- src/declarative/fx/qfxreflectionfilter.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/declarative/fx/qfxreflectionfilter.cpp b/src/declarative/fx/qfxreflectionfilter.cpp index 2e57aa7..c66deb7 100644 --- a/src/declarative/fx/qfxreflectionfilter.cpp +++ b/src/declarative/fx/qfxreflectionfilter.cpp @@ -239,7 +239,7 @@ void QFxReflectionFilter::setScale(qreal s) update(); } -static inline float min(float a, float b) +static inline float floatmin(float a, float b) { return (a < b)?a:b; } @@ -257,7 +257,7 @@ void QFxReflectionFilter::filterGL(QSimpleCanvasItem::GLPainter &p) float refHeight = height; if (d->height > 0) - refHeight = min(height, d->height); + refHeight = floatmin(height, d->height); QSimpleCanvas::Matrix simpMat; QSimpleCanvasItem *simpItem = 0; -- cgit v0.12 From 9410eb0630e0f3b80ffd335002efbd7ce532e826 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 9 Jun 2009 09:24:14 +1000 Subject: Revert "Naively fix handling of qreal properties for ARM." This reverts commit 2575eac4c26ad92dde95959a82f576edc3e76e1d. Conflicts: src/declarative/qml/qmlvme.cpp --- src/declarative/qml/qmlvme.cpp | 3 +-- src/tools/moc/generator.cpp | 6 ------ 2 files changed, 1 insertion(+), 8 deletions(-) diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index c85524f..3c13b38 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -343,8 +343,7 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QFxCompilerTimer cc; #endif QObject *target = stack.top(); - //### moc treats qreal properties as having type double - double r = static_cast(instr.storeReal.value); + qreal r = instr.storeReal.value; void *a[1]; a[0] = &r; QMetaObject::metacall(target, QMetaObject::WriteProperty, diff --git a/src/tools/moc/generator.cpp b/src/tools/moc/generator.cpp index b6bd1ad..ca1311b 100644 --- a/src/tools/moc/generator.cpp +++ b/src/tools/moc/generator.cpp @@ -758,9 +758,6 @@ void Generator::generateMetacall() else if (cdef->enumDeclarations.value(p.type, false)) fprintf(out, " case %d: *reinterpret_cast(_v) = QFlag(%s()); break;\n", propindex, p.read.constData()); - else if (p.type == "qreal") - fprintf(out, " case %d: *reinterpret_cast< double*>(_v) = %s(); break;\n", - propindex, p.read.constData()); else fprintf(out, " case %d: *reinterpret_cast< %s*>(_v) = %s(); break;\n", propindex, p.type.constData(), p.read.constData()); @@ -785,9 +782,6 @@ void Generator::generateMetacall() if (cdef->enumDeclarations.value(p.type, false)) { fprintf(out, " case %d: %s(QFlag(*reinterpret_cast(_v))); break;\n", propindex, p.write.constData()); - } else if(p.type == "qreal") { - fprintf(out, " case %d: %s(*reinterpret_cast< double*>(_v)); break;\n", - propindex, p.write.constData()); } else { fprintf(out, " case %d: %s(*reinterpret_cast< %s*>(_v)); break;\n", propindex, p.write.constData(), p.type.constData()); -- cgit v0.12 From ef4378dd282ed51098d1366792e46e9cfbde727a Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 9 Jun 2009 10:35:57 +1000 Subject: Compile fix for WinCE. --- src/declarative/extra/qfxintegermodel.cpp | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/declarative/extra/qfxintegermodel.cpp b/src/declarative/extra/qfxintegermodel.cpp index 2a85ee1..53814cd 100644 --- a/src/declarative/extra/qfxintegermodel.cpp +++ b/src/declarative/extra/qfxintegermodel.cpp @@ -48,9 +48,9 @@ QML_DEFINE_TYPE(QFxIntegerModel, IntegerModel) class QFxIntegerModelPrivate { public: - QFxIntegerModelPrivate() : min(0), max(0) {} - int min; - int max; + QFxIntegerModelPrivate() : minimum(0), maximum(0) {} + int minimum; + int maximum; }; QFxIntegerModel::QFxIntegerModel(QObject *parent) @@ -66,27 +66,27 @@ QFxIntegerModel::~QFxIntegerModel() int QFxIntegerModel::minimum() const { - return d->min; + return d->minimum; } -void QFxIntegerModel::setMinimum(int min) +void QFxIntegerModel::setMinimum(int minimum) { - d->min = min; + d->minimum = minimum; } int QFxIntegerModel::maximum() const { - return d->max; + return d->maximum; } -void QFxIntegerModel::setMaximum(int max) +void QFxIntegerModel::setMaximum(int maximum) { - d->max = max; + d->maximum = maximum; } int QFxIntegerModel::count() const { - return qMax(0, d->max - d->min + 1); + return qMax(0, d->maximum - d->minimum + 1); } QHash QFxIntegerModel::data(int index, const QList &roles) const @@ -98,7 +98,7 @@ QHash QFxIntegerModel::data(int index, const QList &roles) co QVariant info; switch(role) { case Qt::DisplayRole: - info = QVariant(QString::number(d->min+index)); + info = QVariant(QString::number(d->minimum+index)); break; default: break; -- cgit v0.12 From 3ac9b6bdeb9f7522fa857fbc25a9da48e6d82186 Mon Sep 17 00:00:00 2001 From: Rohan McGovern Date: Tue, 9 Jun 2009 10:50:10 +1000 Subject: Fixed compile with MinGW 3.4. This compiler doesn't seem to follow the same rule as others for implicit conversions to/from wchar_t. Add the necessary casts, keeping in mind that sizeof(wchar_t) == 2 on Windows. --- src/gui/util/qdesktopservices_win.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/util/qdesktopservices_win.cpp b/src/gui/util/qdesktopservices_win.cpp index 8d2701c..9f8efb4 100644 --- a/src/gui/util/qdesktopservices_win.cpp +++ b/src/gui/util/qdesktopservices_win.cpp @@ -115,11 +115,11 @@ static bool launchWebBrowser(const QUrl &url) if (res == ERROR_SUCCESS) { returnValue = RegQueryValueEx(handle, L"Progid", 0, 0, reinterpret_cast(keyValue), &bufferSize); if (!returnValue) - keyName = QString::fromUtf16(keyValue); + keyName = QString::fromUtf16((const ushort*)keyValue); RegCloseKey(handle); } keyName += QLatin1String("\\Shell\\Open\\Command"); - res = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyName.utf16(), 0, KEY_READ, &handle); + res = RegOpenKeyExW(HKEY_CLASSES_ROOT, (const wchar_t*)keyName.utf16(), 0, KEY_READ, &handle); if (res != ERROR_SUCCESS) return false; -- cgit v0.12 From a359abb4ccf5a2dc3bd1fac9836231677b3dc14f Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 9 Jun 2009 10:53:25 +1000 Subject: Protect EGL property names that only exist in some versions with #ifdefs Reviewed-by: trustme --- src/opengl/qegl.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/opengl/qegl.cpp b/src/opengl/qegl.cpp index f1ae4ed..290f77c 100644 --- a/src/opengl/qegl.cpp +++ b/src/opengl/qegl.cpp @@ -413,12 +413,18 @@ int QEglProperties::value(int name) const case EGL_RED_SIZE: return 0; case EGL_GREEN_SIZE: return 0; case EGL_BLUE_SIZE: return 0; - case EGL_LUMINANCE_SIZE: return 0; case EGL_ALPHA_SIZE: return 0; +#if defined(EGL_LUMINANCE_SIZE) + case EGL_LUMINANCE_SIZE: return 0; +#endif +#if defined(EGL_ALPHA_MASK_SIZE) case EGL_ALPHA_MASK_SIZE: return 0; +#endif case EGL_BIND_TO_TEXTURE_RGB: return EGL_DONT_CARE; case EGL_BIND_TO_TEXTURE_RGBA: return EGL_DONT_CARE; +#if defined(EGL_COLOR_BUFFER_TYPE) case EGL_COLOR_BUFFER_TYPE: return EGL_RGB_BUFFER; +#endif case EGL_CONFIG_CAVEAT: return EGL_DONT_CARE; case EGL_CONFIG_ID: return EGL_DONT_CARE; case EGL_DEPTH_SIZE: return 0; @@ -427,7 +433,9 @@ int QEglProperties::value(int name) const case EGL_NATIVE_VISUAL_TYPE: return EGL_DONT_CARE; case EGL_MAX_SWAP_INTERVAL: return EGL_DONT_CARE; case EGL_MIN_SWAP_INTERVAL: return EGL_DONT_CARE; +#if defined(EGL_RENDERABLE_TYPE) case EGL_RENDERABLE_TYPE: return EGL_OPENGL_ES_BIT; +#endif case EGL_SAMPLE_BUFFERS: return 0; case EGL_SAMPLES: return 0; case EGL_STENCIL_SIZE: return 0; -- cgit v0.12 From 1bbe23c5814dfda4cc6154c49e5bbf7c6ead7eba Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 9 Jun 2009 10:54:37 +1000 Subject: Make OpenGL/ES 1.1 work again for Qt/Embedded Reviewed-by: trustme --- src/opengl/qgl.cpp | 15 +++++++++++++++ src/opengl/qgl_p.h | 3 +-- src/opengl/qglframebufferobject.cpp | 2 ++ src/opengl/qglpixelbuffer.cpp | 5 +++-- 4 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 2e72851..37a9916 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -65,12 +65,19 @@ #include "qimage.h" #include "qgl_p.h" +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) #include "gl2paintengineex/qpaintengineex_opengl2_p.h" +#endif #ifndef QT_OPENGL_ES_2 #include #endif +#ifdef Q_WS_QWS +#include +#include +#endif + #include #include @@ -4428,7 +4435,11 @@ void QGLDrawable::swapBuffers() void QGLDrawable::makeCurrent() { previous_fbo = 0; +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) if (!pixmapData && !fbo) { +#else +#endif + if (!fbo) { QGLContext *ctx = context(); previous_fbo = ctx->d_ptr->current_fbo; ctx->d_ptr->current_fbo = 0; @@ -4561,8 +4572,10 @@ QColor QGLDrawable::backgroundColor() const { if (widget) return widget->palette().brush(widget->backgroundRole()).color(); +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) else if (pixmapData) return pixmapData->fillColor(); +#endif return QApplication::palette().brush(QPalette::Background).color(); } @@ -4590,8 +4603,10 @@ bool QGLDrawable::autoFillBackground() const { if (widget) return widget->autoFillBackground(); +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) else if (pixmapData) return pixmapData->needsFill(); +#endif else return false; } diff --git a/src/opengl/qgl_p.h b/src/opengl/qgl_p.h index b3523d4..4af8598 100644 --- a/src/opengl/qgl_p.h +++ b/src/opengl/qgl_p.h @@ -428,8 +428,7 @@ private: extern Q_OPENGL_EXPORT QGLShareRegister* qgl_share_reg(); #ifdef Q_WS_QWS -class QOpenGLPaintEngine; -extern QOpenGLPaintEngine* qt_qgl_paint_engine(); +extern QPaintEngine* qt_qgl_paint_engine(); extern EGLDisplay qt_qgl_egl_display(); #endif diff --git a/src/opengl/qglframebufferobject.cpp b/src/opengl/qglframebufferobject.cpp index 3e7ca0a..fb16107 100644 --- a/src/opengl/qglframebufferobject.cpp +++ b/src/opengl/qglframebufferobject.cpp @@ -43,7 +43,9 @@ #include #include +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) #include +#endif #ifndef QT_OPENGL_ES_2 #include diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp index 483856a..0af97e3 100644 --- a/src/opengl/qglpixelbuffer.cpp +++ b/src/opengl/qglpixelbuffer.cpp @@ -76,12 +76,13 @@ \sa {opengl/pbuffers}{Pbuffers Example} */ -#include - #include #include #include +#if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) +#include +#endif #ifndef QT_OPENGL_ES_2 #include #endif -- cgit v0.12 From 991b41aa407b5a8740e6899a3efdc724276dcb95 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 9 Jun 2009 11:16:41 +1000 Subject: Fix handling of qreal properties. This is to bring us in line with the fix made to moc's handling of qreal properties. --- src/declarative/qml/qmlbasicscript.cpp | 14 +++++++------- src/declarative/qml/qmlcompiler.cpp | 24 +++++++++++++++++------- src/declarative/qml/qmlinstruction.cpp | 7 +++++-- src/declarative/qml/qmlinstruction_p.h | 14 ++++++++++---- src/declarative/qml/qmlvme.cpp | 26 ++++++++++++++++++++------ 5 files changed, 59 insertions(+), 26 deletions(-) diff --git a/src/declarative/qml/qmlbasicscript.cpp b/src/declarative/qml/qmlbasicscript.cpp index 3d74b37..7bd898c 100644 --- a/src/declarative/qml/qmlbasicscript.cpp +++ b/src/declarative/qml/qmlbasicscript.cpp @@ -117,25 +117,25 @@ void QmlBasicScriptNodeCache::clear() static QVariant toObjectOrVariant(const QVariant &v) { - switch(v.type()) { + switch(v.userType()) { case QVariant::String: case QVariant::UInt: case QVariant::Int: - case 135: + case QMetaType::Float: case QVariant::Double: case QVariant::Color: case QVariant::Bool: default: - return v; - case QVariant::UserType: - { + { + if (v.type() == QVariant::UserType) { QObject *o = QmlMetaType::toQObject(v); if (o) return qVariantFromValue(o); else return v; } - break; + return v; + } } } @@ -166,7 +166,7 @@ static QVariant fetch_value(QObject *o, int idx, int type) return QVariant(val); } break; - case 135: + case QMetaType::Float: { float val; void *args[] = { &val, 0 }; diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 46695b7..b28d7dd 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -262,7 +262,7 @@ bool QmlCompiler::compileStoreInstruction(QmlInstruction &instr, instr.storeInteger.value = value; return true; } - int type = prop.type(); + int type = prop.userType(); switch(type) { case -1: { @@ -300,16 +300,26 @@ bool QmlCompiler::compileStoreInstruction(QmlInstruction &instr, instr.storeInteger.value = value; } break; - case 135: - case QVariant::Double: + case QMetaType::Float: { - instr.type = QmlInstruction::StoreReal; - instr.storeReal.propertyIndex = prop.propertyIndex(); + instr.type = QmlInstruction::StoreFloat; + instr.storeFloat.propertyIndex = prop.propertyIndex(); bool ok; float value = string.toFloat(&ok); if (!ok) - COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to real number"); - instr.storeReal.value = value; + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to float number"); + instr.storeFloat.value = value; + } + break; + case QVariant::Double: + { + instr.type = QmlInstruction::StoreDouble; + instr.storeDouble.propertyIndex = prop.propertyIndex(); + bool ok; + double value = string.toDouble(&ok); + if (!ok) + COMPILE_EXCEPTION2(v, "Cannot convert value" << string << "to double number"); + instr.storeDouble.value = value; } break; case QVariant::Color: diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index 0aa860d..af1489a 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -70,8 +70,11 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) case QmlInstruction::StoreMetaObject: qWarning() << idx << "\t" << line << "\t" << "STORE_META\t\t" << instr->storeMeta.data << "\t" << instr->storeMeta.slotData; break; - case QmlInstruction::StoreReal: - qWarning() << idx << "\t" << line << "\t" << "STORE_REAL\t\t" << instr->storeReal.propertyIndex << "\t" << instr->storeReal.value; + case QmlInstruction::StoreFloat: + qWarning() << idx << "\t" << line << "\t" << "STORE_FLOAT\t\t" << instr->storeFloat.propertyIndex << "\t" << instr->storeFloat.value; + break; + case QmlInstruction::StoreDouble: + qWarning() << idx << "\t" << line << "\t" << "STORE_DOUBLE\t\t" << instr->storeDouble.propertyIndex << "\t" << instr->storeDouble.value; break; case QmlInstruction::StoreInteger: qWarning() << idx << "\t" << line << "\t" << "STORE_INTEGER\t\t" << instr->storeInteger.propertyIndex << "\t" << instr->storeInteger.value; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index 5c6fa5a..5a1729f 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -71,7 +71,8 @@ public: // // Precomputed single assignment // - // StoreReal - Store a qreal in a core property + // StoreFloat - Store a float in a core property + // StoreDouble - Store a double in a core property // StoreInteger - Store a int or uint in a core property // StoreBool - Store a bool in a core property // StoreString - Store a QString in a core property @@ -82,14 +83,15 @@ public: // StoreVariant - Store a QVariant in a core property // StoreObject - Pop the object on the top of the object stack and // store it in a core property - StoreReal, /* storeReal */ + StoreFloat, /* storeFloat */ + StoreDouble, /* storeDouble */ StoreInteger, /* storeInteger */ StoreBool, /* storeBool */ StoreString, /* storeString */ StoreColor, /* storeColor */ StoreDate, /* storeDate */ StoreTime, /* storeTime */ - StoreDateTime, /* storeDateTime */ + StoreDateTime, /* storeDateTime */ StorePoint, /* storeRealPair */ StorePointF, /* storeRealPair */ StoreSize, /* storeRealPair */ @@ -196,7 +198,11 @@ public: struct { int propertyIndex; float value; - } storeReal; + } storeFloat; + struct { + int propertyIndex; + double value; + } storeDouble; struct { int propertyIndex; int value; diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 3c13b38..f00d282 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -337,17 +337,31 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; - case QmlInstruction::StoreReal: + case QmlInstruction::StoreFloat: { #ifdef Q_ENABLE_PERFORMANCE_LOG QFxCompilerTimer cc; #endif QObject *target = stack.top(); - qreal r = instr.storeReal.value; + float f = instr.storeFloat.value; void *a[1]; - a[0] = &r; - QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeReal.propertyIndex, a); + a[0] = &f; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeFloat.propertyIndex, a); + } + break; + +case QmlInstruction::StoreDouble: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + double d = instr.storeDouble.value; + void *a[1]; + a[0] = &d; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeDouble.propertyIndex, a); } break; @@ -373,7 +387,7 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in void *a[1]; a[0] = (void *)&instr.storeInteger.value; QMetaObject::metacall(target, QMetaObject::WriteProperty, - instr.storeReal.propertyIndex, a); + instr.storeInteger.propertyIndex, a); } break; -- cgit v0.12 From db4addcf3408140bb34fa8884c7192c1d9667be8 Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Tue, 9 Jun 2009 12:46:10 +1000 Subject: Add dynamic object creation from Script. Can now create, inside script, objects from qml snippets and files. These objects can then be manipulated from script. Deleting these items is still being looked into. --- src/declarative/qml/qmlcomponent.cpp | 18 ++++++ src/declarative/qml/qmlcomponent.h | 11 ++-- src/declarative/qml/qmlengine.cpp | 122 +++++++++++++++++++++++++++++++++++ src/declarative/qml/qmlengine.h | 9 +++ 4 files changed, 156 insertions(+), 4 deletions(-) diff --git a/src/declarative/qml/qmlcomponent.cpp b/src/declarative/qml/qmlcomponent.cpp index 78137e8..267fba8 100644 --- a/src/declarative/qml/qmlcomponent.cpp +++ b/src/declarative/qml/qmlcomponent.cpp @@ -387,6 +387,24 @@ QmlComponent::QmlComponent(QmlComponentPrivate &dd, QObject *parent) } /*! + Create a script object instance from this component. Returns a null + script object if creation failed. It will create the instance in the + engine's \l {QmlEngine::rootContext()}{root context}. + + Similar to QmlComponent::create(), but creates an object suitable + for usage within scripts. +*/ +QScriptValue QmlComponent::createObject() +{ + Q_D(QmlComponent); + QObject* ret = create(); + if(ret) + return QmlEngine::qmlScriptObject(ret, d->engine); + else + return d->engine->scriptEngine()->nullValue(); +} + +/*! Create an object instance from this component. Returns 0 if creation failed. \a context specifies the context within which to create the object instance. diff --git a/src/declarative/qml/qmlcomponent.h b/src/declarative/qml/qmlcomponent.h index e7386d9..bb76c8b 100644 --- a/src/declarative/qml/qmlcomponent.h +++ b/src/declarative/qml/qmlcomponent.h @@ -44,6 +44,7 @@ #include #include +#include #include #include #include @@ -70,18 +71,20 @@ public: const QUrl &baseUrl=QUrl(), QObject *parent=0); virtual ~QmlComponent(); + Q_ENUMS( Status ); enum Status { Null, Ready, Loading, Error }; Status status() const; - bool isNull() const; - bool isReady() const; - bool isError() const; - bool isLoading() const; + Q_INVOKABLE bool isNull() const; + Q_INVOKABLE bool isReady() const; + Q_INVOKABLE bool isError() const; + Q_INVOKABLE bool isLoading() const; QList errors() const; QUrl url() const; + Q_INVOKABLE QScriptValue createObject(); virtual QObject *create(QmlContext *context = 0); virtual QObject *beginCreate(QmlContext *); virtual void completeCreate(); diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index 18f28ed..d8ca809 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -203,6 +203,13 @@ void QmlEnginePrivate::init() debugger->attachTo(&scriptEngine); } #endif + //###needed for the other funcs, but should it be exposed? + scriptEngine.globalObject().setProperty(QLatin1String("qmlEngine"), + scriptEngine.newQObject(q)); + scriptEngine.globalObject().setProperty(QLatin1String("evalQml"), + scriptEngine.newFunction(QmlEngine::createQMLObject, 1)); + scriptEngine.globalObject().setProperty(QLatin1String("createComponent"), + scriptEngine.newFunction(QmlEngine::createComponent, 1)); } QmlContext *QmlEnginePrivate::setCurrentBindContext(QmlContext *c) @@ -808,7 +815,122 @@ QmlEngine *QmlEngine::activeEngine() return engines->top(); } +/*! + Creates a QScriptValue allowing you to use \a object in QML script. + \a engine is the QmlEngine it is to be created in. + + The QScriptValue returned is a QtScript Object, not a QtScript QObject, due + to the special needs of QML requiring more functionality than a standard + QtScript QObject. + + You'll want to use this function if you are writing C++ code which + dynamically creates and returns objects when called from QtScript, + and these objects are visual items in the QML tree. + + \sa QmlEngine::newQObject() +*/ +QScriptValue QmlEngine::qmlScriptObject(QObject* object, QmlEngine* engine) +{ + return engine->scriptEngine()->newObject(new QmlObjectScriptClass(engine), + engine->scriptEngine()->newQObject(object)); +} + +/*! + This function is intended for use inside QML only. In C++ just create a + component object as usual. + + This function takes the URL of a QML file as its only argument. It returns + a component object which can be used to create and load that QML file. + + Example JavaScript: + \code + component = createComponent("Sprite.qml"); + if(component.isReady()){ + sprite = component.create(); + if(sprite == 0){ + // Error Handling + }else{ + sprite.parent = page; + sprite.x = 200; + //... + } + }else{ + // The finishCreation function does the same thing as the above + // if(component.isReady()) branch + component.statusChanged.connect(finishCreation); + } + \endcode + + Remember that QML files that might be loaded over the network cannot be + expected to be ready immediately. +*/ +QScriptValue QmlEngine::createComponent(QScriptContext *ctxt, QScriptEngine *engine) +{ + QmlComponent* c; + QmlEngine* activeEngine = qobject_cast( + engine->globalObject().property(QLatin1String("qmlEngine")).toQObject()); + if(ctxt->argumentCount() != 1 || !activeEngine){ + c = new QmlComponent(activeEngine); + }else{ + c = new QmlComponent(activeEngine, QUrl(ctxt->argument(0).toString()), + activeEngine); + } + return engine->newQObject(c); +} +/*! + Creates a new object from the specified string of qml. If a second argument + is provided, this is treated as the filepath that the qml came from. + + This function is intended for use inside QML only. It is intended to behave + similarly to eval, but for creating QML elements. Thus, it is called as + evalQml() in QtScript. + + Returns the created object, or null if there is an error. In the case of an + error, details of the error are output using qWarning(). +*/ +QScriptValue QmlEngine::createQMLObject(QScriptContext *ctxt, QScriptEngine *engine) +{ + QmlEngine* activeEngine = qobject_cast( + engine->globalObject().property(QLatin1String("qmlEngine")).toQObject()); + if(ctxt->argumentCount() < 1 || !activeEngine){ + if(ctxt->argumentCount() < 1){ + qWarning() << "createQMLObject requires a string argument."; + }else{ + qWarning() << "createQMLObject failed inexplicably."; + } + return engine->nullValue(); + } + + QString qml = ctxt->argument(0).toString(); + QUrl url; + if(ctxt->argumentCount() > 1) + url = QUrl(ctxt->argument(1).toString()); + QmlComponent component(activeEngine, qml.toUtf8(), url); + if(component.isError()) { + QList errors = component.errors(); + foreach (const QmlError &error, errors) { + qWarning() << error; + } + + return engine->nullValue(); + } + + QObject *obj = component.create(); + if(component.isError()) { + QList errors = component.errors(); + foreach (const QmlError &error, errors) { + qWarning() << error; + } + + return engine->nullValue(); + } + + if(obj){ + return qmlScriptObject(obj, activeEngine); + } + return engine->nullValue(); +} QmlExpressionPrivate::QmlExpressionPrivate(QmlExpression *b) : q(b), ctxt(0), sseData(0), proxy(0), me(0), trackChange(false), line(-1), id(0), log(0) diff --git a/src/declarative/qml/qmlengine.h b/src/declarative/qml/qmlengine.h index 9382389..ca66097 100644 --- a/src/declarative/qml/qmlengine.h +++ b/src/declarative/qml/qmlengine.h @@ -44,6 +44,7 @@ #include #include +#include QT_BEGIN_HEADER @@ -57,6 +58,7 @@ class QmlExpression; class QmlContext; class QUrl; class QScriptEngine; +class QScriptContext; class QNetworkAccessManager; class Q_DECLARATIVE_EXPORT QmlEngine : public QObject { @@ -85,6 +87,13 @@ public: static QmlContext *contextForObject(const QObject *); static void setContextForObject(QObject *, QmlContext *); + + static QScriptValue qmlScriptObject(QObject*, QmlEngine*); + + // Below two functions provide a way to dynamically create objects from JS + static QScriptValue createComponent(QScriptContext*, QScriptEngine*); + static QScriptValue createQMLObject(QScriptContext*, QScriptEngine*); + private: // LK: move to the private class QScriptEngine *scriptEngine(); -- cgit v0.12 From 6d4fe549e7a258913b19f52e29bcfb84cc8a97ad Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 9 Jun 2009 12:58:10 +1000 Subject: Fix build breakage from 1bbe23c5 - endif in the wrong place Reviewed-by: trustme --- src/opengl/qgl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/opengl/qgl.cpp b/src/opengl/qgl.cpp index 37a9916..146d088 100644 --- a/src/opengl/qgl.cpp +++ b/src/opengl/qgl.cpp @@ -4438,8 +4438,8 @@ void QGLDrawable::makeCurrent() #if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) if (!pixmapData && !fbo) { #else -#endif if (!fbo) { +#endif QGLContext *ctx = context(); previous_fbo = ctx->d_ptr->current_fbo; ctx->d_ptr->current_fbo = 0; -- cgit v0.12 From cea87b08520888feff2f10d1bbf71bc8c2f1d780 Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 9 Jun 2009 13:20:51 +1000 Subject: Another breakage in 1bbe23c5 - move qpaintengineex_opengl2_p.h include up Moving qpaintengineex_opengl2_p.h down caused it to come after an include of , which causes problems on some platforms. Move it back up again. Reviewed-by: trustme --- src/opengl/qglpixelbuffer.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/opengl/qglpixelbuffer.cpp b/src/opengl/qglpixelbuffer.cpp index 0af97e3..9b7a506 100644 --- a/src/opengl/qglpixelbuffer.cpp +++ b/src/opengl/qglpixelbuffer.cpp @@ -76,13 +76,16 @@ \sa {opengl/pbuffers}{Pbuffers Example} */ -#include -#include -#include +#include #if !defined(QT_OPENGL_ES_1) && !defined(QT_OPENGL_ES_1_CL) #include #endif + +#include +#include +#include + #ifndef QT_OPENGL_ES_2 #include #endif -- cgit v0.12 From 60e291e39040fa4d59a646427dcea8ddf108bf5c Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Tue, 9 Jun 2009 13:50:51 +1000 Subject: Warn when trying to anchor to non-sibling/non-parent. --- src/declarative/fx/qfxanchors.cpp | 14 ++++++++++++-- tests/auto/declarative/anchors/tst_anchors.cpp | 19 ++++++------------- 2 files changed, 18 insertions(+), 15 deletions(-) diff --git a/src/declarative/fx/qfxanchors.cpp b/src/declarative/fx/qfxanchors.cpp index bd5520a..09d6178 100644 --- a/src/declarative/fx/qfxanchors.cpp +++ b/src/declarative/fx/qfxanchors.cpp @@ -325,6 +325,10 @@ QFxItem *QFxAnchors::fill() const void QFxAnchors::setFill(QFxItem *f) { Q_D(QFxAnchors); + if (f != d->item->itemParent() && f->itemParent() != d->item->itemParent()){ + qmlInfo(d->item) << "Can't anchor to an item that isn't a parent or sibling."; + return; + } d->remDepend(d->fill); d->fill = f; d->addDepend(d->fill); @@ -847,7 +851,10 @@ bool QFxAnchorsPrivate::checkHAnchorValid(QFxAnchorLine anchor) const if (anchor.anchorLine & QFxAnchorLine::Vertical_Mask) { qmlInfo(item) << "Can't anchor a horizontal edge to a vertical edge."; return false; - }else if (anchor.item == item){ + } else if (anchor.item != item->itemParent() && anchor.item->itemParent() != item->itemParent()){ + qmlInfo(item) << "Can't anchor to an item that isn't a parent or sibling."; + return false; + } else if (anchor.item == item){ qmlInfo(item) << "Can't anchor item to self."; return false; } @@ -878,7 +885,10 @@ bool QFxAnchorsPrivate::checkVAnchorValid(QFxAnchorLine anchor) const if (anchor.anchorLine & QFxAnchorLine::Horizontal_Mask) { qmlInfo(item) << "Can't anchor a vertical edge to a horizontal edge."; return false; - }else if (anchor.item == item){ + } else if (anchor.item != item->itemParent() && anchor.item->itemParent() != item->itemParent()){ + qmlInfo(item) << "Can't anchor to an item that isn't a parent or sibling."; + return false; + } else if (anchor.item == item){ qmlInfo(item) << "Can't anchor item to self."; return false; } diff --git a/tests/auto/declarative/anchors/tst_anchors.cpp b/tests/auto/declarative/anchors/tst_anchors.cpp index 587b4ab..abe6d96 100644 --- a/tests/auto/declarative/anchors/tst_anchors.cpp +++ b/tests/auto/declarative/anchors/tst_anchors.cpp @@ -95,9 +95,7 @@ void tst_anchors::loops() view->setUrl(QUrl("file://" SRCDIR "/data/loop1.qml")); - //### ignoreMessage doesn't seem to work - //QTest::ignoreMessage(QtWarningMsg, "QML QFxText (unknown location): Anchor loop detected on horizontal anchor."); - //QTest::ignoreMessage(QtWarningMsg, "QML QFxText (unknown location): Anchor loop detected on horizontal anchor."); + QTest::ignoreMessage(QtWarningMsg, "QML QFxText (unknown location): Possible anchor loop detected on horizontal anchor. "); //x5 view->execute(); qApp->processEvents(); @@ -109,9 +107,7 @@ void tst_anchors::loops() view->setUrl(QUrl("file://" SRCDIR "/data/loop2.qml")); - //### ignoreMessage doesn't seem to work here - //QTest::ignoreMessage(QtWarningMsg, "QML QFxImage (unknown location): Anchor loop detected on horizontal anchor."); - //QTest::ignoreMessage(QtWarningMsg, "QML QFxImage (unknown location): Anchor loop detected on horizontal anchor."); + QTest::ignoreMessage(QtWarningMsg, "QML QFxImage (unknown location): Possible anchor loop detected on horizontal anchor. "); //x3 view->execute(); qApp->processEvents(); @@ -126,8 +122,7 @@ void tst_anchors::illegalSets() view->setUrl(QUrl("file://" SRCDIR "/data/illegal1.qml")); - //### ignoreMessage doesn't seem to work - //QTest::ignoreMessage(QtWarningMsg, "QML QFxRect (unknown location): Can't specify left, right, and hcenter anchors."); + QTest::ignoreMessage(QtWarningMsg, "QML QFxRect (unknown location): Can't specify left, right, and hcenter anchors. "); view->execute(); qApp->processEvents(); @@ -139,8 +134,7 @@ void tst_anchors::illegalSets() view->setUrl(QUrl("file://" SRCDIR "/data/illegal2.qml")); - //### ignoreMessage doesn't seem to work here - //QTest::ignoreMessage(QtWarningMsg, "QML QFxText (unknown location): Baseline anchor can't be used in conjunction with top, bottom, or vcenter anchors."); + QTest::ignoreMessage(QtWarningMsg, "QML QFxText (unknown location): Baseline anchor can't be used in conjunction with top, bottom, or vcenter anchors. "); view->execute(); //qApp->processEvents(); @@ -152,10 +146,9 @@ void tst_anchors::illegalSets() view->setUrl(QUrl("file://" SRCDIR "/data/illegal3.qml")); - //### ignoreMessage doesn't seem to work here - //QTest::ignoreMessage(QtWarningMsg, "Can't anchor to an item that isn't a parent or sibling."); + QTest::ignoreMessage(QtWarningMsg, "QML QFxRect (unknown location): Can't anchor to an item that isn't a parent or sibling. "); view->execute(); - qApp->processEvents(); + //qApp->processEvents(); delete view; } -- cgit v0.12 From edd535defde42cf4b57c6144b6ba8a0607363d5e Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 9 Jun 2009 14:59:16 +1000 Subject: Fix OpenGL texture access issues --- src/declarative/fx/qfximage.cpp | 100 ++++++++++++++++++++--------------- src/declarative/fx/qfxtext.cpp | 19 ++++--- src/declarative/opengl/gltexture.cpp | 8 +++ src/declarative/opengl/gltexture.h | 1 + 4 files changed, 78 insertions(+), 50 deletions(-) diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 03a674d..c5e7e89 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -500,6 +500,12 @@ void QFxImage::paintGLContents(GLPainter &p) float glWidth = d->tex->glWidth(); float glHeight = d->tex->glHeight(); + float deltaX = 0.5 / qreal(d->tex->glSize().width()); + float deltaY = 0.5 / qreal(d->tex->glSize().height()); + glWidth -= deltaX; + glHeight -= deltaY; + + float vert[] = { 0, heightV, widthV, heightV, @@ -510,12 +516,12 @@ void QFxImage::paintGLContents(GLPainter &p) widthV, 0 }; float tex[] = { - 0, 0, - glWidth, 0, - 0, glHeight, + deltaX, deltaY, + glWidth, deltaY, + deltaX, glHeight, - glWidth, 0, - 0, glHeight, + glWidth, deltaY, + deltaX, glHeight, glWidth, glHeight }; @@ -551,11 +557,17 @@ void QFxImage::paintGLContents(GLPainter &p) float widthV = width(); float heightV = height(); - - float texleft = 0; - float texright = d->tex->glWidth(); - float textop = d->tex->glHeight(); - float texbottom = 0; + float glWidth = d->tex->glWidth(); + float glHeight = d->tex->glHeight(); + float deltaX = 0.5 / qreal(d->tex->glSize().width()); + float deltaY = 0.5 / qreal(d->tex->glSize().height()); + glHeight -= deltaY; + glWidth -= deltaX; + + float texleft = deltaX; + float texright = glWidth; + float textop = glHeight; + float texbottom = deltaY; float imgleft = 0; float imgright = widthV; float imgtop = 0; @@ -567,19 +579,19 @@ void QFxImage::paintGLContents(GLPainter &p) const int sgb = d->scaleGrid->bottom(); if (sgl) { - texleft = d->tex->glWidth() * float(sgl) / imgWidth; + texleft = deltaX + d->tex->glWidth() * float(sgl) / imgWidth; imgleft = sgl; } if (sgr) { - texright = d->tex->glWidth() - float(sgr) / imgWidth; + texright = d->tex->glWidth() - float(sgr) / imgWidth - deltaX; imgright = widthV - sgr; } if (sgt) { - textop = d->tex->glHeight() - float(sgb) / imgHeight; + textop = d->tex->glHeight() - float(sgb) / imgHeight - deltaY; imgtop = sgt; } if (sgb) { - texbottom = d->tex->glHeight() * float(sgt) / imgHeight; + texbottom = deltaY + d->tex->glHeight() * float(sgt) / imgHeight; imgbottom = heightV - sgb; } @@ -655,35 +667,35 @@ void QFxImage::paintGLContents(GLPainter &p) widthV, imgbottom, widthV, heightV }; - float tex1[] = { 0, 1, - 0, textop, - texleft, 1, + float tex1[] = { deltaX, glHeight, + deltaX, textop, + texleft, glHeight, - 0, textop, - texleft, 1, + deltaX, textop, + texleft, glHeight, texleft, textop, - texleft, 1, + texleft, glHeight, texleft, textop, - texright, 1, + texright, glHeight, texleft, textop, - texright, 1, + texright, glHeight, texright, textop, - texright, 1, + texright, glHeight, texright, textop, - 1, 1, + glWidth, glHeight, texright, textop, - 1, 1, - 1, textop, + glWidth, glHeight, + glWidth, textop, - 0, textop, - 0, texbottom, + deltaX, textop, + deltaX, texbottom, texleft, textop, - 0, texbottom, + deltaX, texbottom, texleft, textop, texleft, texbottom, @@ -697,35 +709,35 @@ void QFxImage::paintGLContents(GLPainter &p) texright, textop, texright, texbottom, - 1, textop, + glWidth, textop, texright, texbottom, - 1, textop, - 1, texbottom, + glWidth, textop, + glWidth, texbottom, - 0, texbottom, - 0, 0, + deltaX, texbottom, + deltaX, deltaY, texleft, texbottom, - 0, 0, + deltaX, deltaY, texleft, texbottom, - texleft, 0, + texleft, deltaY, texleft, texbottom, - texleft, 0, + texleft, deltaY, texright, texbottom, - texleft, 0, + texleft, deltaY, texright, texbottom, - texright, 0, + texright, deltaY, texright, texbottom, - texright, 0, - 1, texbottom, + texright, deltaY, + glWidth, texbottom, - texright, 0, - 1, texbottom, - 1, 0 }; + texright, deltaY, + glWidth, texbottom, + glWidth, deltaY }; glBindTexture(GL_TEXTURE_2D, d->tex->texture()); diff --git a/src/declarative/fx/qfxtext.cpp b/src/declarative/fx/qfxtext.cpp index 7a2dd8d..031c0f8 100644 --- a/src/declarative/fx/qfxtext.cpp +++ b/src/declarative/fx/qfxtext.cpp @@ -793,9 +793,16 @@ void QFxText::paintGLContents(GLPainter &p) float widthV = d->imgCache.width(); float heightV = d->imgCache.height(); + float glWidth = d->tex.glWidth(); + float glHeight = d->tex.glHeight(); QGLShaderProgram *shader = p.useTextureShader(); + float deltaX = 0.5 / qreal(d->tex.glSize().width()); + float deltaY = 0.5 / qreal(d->tex.glSize().height()); + glWidth -= deltaX; + glHeight -= deltaY; + GLfloat vertices[] = { x, y + heightV, x + widthV, y + heightV, x, y, @@ -804,13 +811,13 @@ void QFxText::paintGLContents(GLPainter &p) x, y, x + widthV, y }; - GLfloat texVertices[] = { 0, 0, - d->tex.glWidth(), 0, - 0, d->tex.glHeight(), + GLfloat texVertices[] = { deltaX, deltaY, + glWidth, deltaY, + deltaX, glHeight, - d->tex.glWidth(), 0, - 0, d->tex.glHeight(), - d->tex.glWidth(), d->tex.glHeight() }; + glWidth, deltaY, + deltaX, glHeight, + glWidth, glHeight }; shader->setAttributeArray(SingleTextureShader::Vertices, vertices, 2); shader->setAttributeArray(SingleTextureShader::TextureCoords, texVertices, 2); diff --git a/src/declarative/opengl/gltexture.cpp b/src/declarative/opengl/gltexture.cpp index cd9c406..c2a02df 100644 --- a/src/declarative/opengl/gltexture.cpp +++ b/src/declarative/opengl/gltexture.cpp @@ -95,6 +95,7 @@ public: qreal glWidth; qreal glHeight; + QSize glSize; void genTexture(); }; @@ -199,6 +200,7 @@ void GLTexture::setImage(const QImage &img, ImageMode mode) } d->glWidth = 1.; d->glHeight = 1.; + d->glSize = img.size(); } else { // mode == PowerOfTwo @@ -233,6 +235,7 @@ void GLTexture::setImage(const QImage &img, ImageMode mode) d->glWidth = qreal(img.width()) / qreal(max); d->glHeight = qreal(img.height()) / qreal(max); + d->glSize = QSize(max, max); } d->width = img.width(); @@ -273,6 +276,11 @@ qreal GLTexture::glHeight() const return d->glHeight; } +QSize GLTexture::glSize() const +{ + return d->glSize; +} + /*! Sets the \a size of the texture. This will destroy the current contents of the texture. If an image has been assigned, it will need to be reassigned diff --git a/src/declarative/opengl/gltexture.h b/src/declarative/opengl/gltexture.h index d301d8a..c08d68f 100644 --- a/src/declarative/opengl/gltexture.h +++ b/src/declarative/opengl/gltexture.h @@ -77,6 +77,7 @@ public: int height() const; qreal glWidth() const; qreal glHeight() const; + QSize glSize() const; QSize size() const; void setSize(const QSize &); -- cgit v0.12 From 45ad5f8e643f8a1bd52143ad628e5418f5ae8fa3 Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Tue, 9 Jun 2009 15:16:16 +1000 Subject: Can now dynamically delete objects as well. The QtScript object wrapper now has a destroy function. This should work for all QML objects. This commit also has some clean up in the dynamic creation code, which still has a bug regarding path resolution. --- src/declarative/qml/qmlcomponent.cpp | 1 + src/declarative/qml/qmlcomponent.h | 1 + src/declarative/qml/qmlengine.cpp | 74 +++++++++++++++++++++++++++--------- src/declarative/qml/qmlengine.h | 1 - src/declarative/qml/qmlengine_p.h | 3 ++ 5 files changed, 62 insertions(+), 18 deletions(-) diff --git a/src/declarative/qml/qmlcomponent.cpp b/src/declarative/qml/qmlcomponent.cpp index 267fba8..f90af4a 100644 --- a/src/declarative/qml/qmlcomponent.cpp +++ b/src/declarative/qml/qmlcomponent.cpp @@ -59,6 +59,7 @@ QT_BEGIN_NAMESPACE class QByteArray; +int statusId = qRegisterMetaType("QmlComponent::Status"); /*! \class QmlComponent diff --git a/src/declarative/qml/qmlcomponent.h b/src/declarative/qml/qmlcomponent.h index bb76c8b..fe0c422 100644 --- a/src/declarative/qml/qmlcomponent.h +++ b/src/declarative/qml/qmlcomponent.h @@ -104,6 +104,7 @@ private: friend class QmlVME; friend struct QmlCompositeTypeData; }; +Q_DECLARE_METATYPE(QmlComponent::Status); QML_DECLARE_TYPE(QmlComponent) QT_END_NAMESPACE diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index d8ca809..73b9245 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -842,27 +842,48 @@ QScriptValue QmlEngine::qmlScriptObject(QObject* object, QmlEngine* engine) This function takes the URL of a QML file as its only argument. It returns a component object which can be used to create and load that QML file. - Example JavaScript: + Example JavaScript is below, remember that QML files that might be loaded + over the network cannot be expected to be ready immediately. \code - component = createComponent("Sprite.qml"); - if(component.isReady()){ - sprite = component.create(); - if(sprite == 0){ + var component; + var sprite; + function finishCreation(){ + if(component.isReady()){ + sprite = component.createObject(); + if(sprite == 0){ + // Error Handling + }else{ + sprite.parent = page; + sprite.x = 200; + //... + } + }else if(component.isError()){ // Error Handling - }else{ - sprite.parent = page; - sprite.x = 200; - //... } + } + + component = createComponent("Sprite.qml"); + if(component.isReady()){ + finishCreation(); }else{ - // The finishCreation function does the same thing as the above - // if(component.isReady()) branch component.statusChanged.connect(finishCreation); } \endcode - Remember that QML files that might be loaded over the network cannot be - expected to be ready immediately. + If you are certain the files will be local, you could simplify to + + \code + component = createComponent("Sprite.qml"); + sprite = component.createObject(); + if(sprite == 0){ + // Error Handling + }else{ + sprite.parent = page; + sprite.x = 200; + //... + } + \endcode + */ QScriptValue QmlEngine::createComponent(QScriptContext *ctxt, QScriptEngine *engine) { @@ -872,8 +893,8 @@ QScriptValue QmlEngine::createComponent(QScriptContext *ctxt, QScriptEngine *eng if(ctxt->argumentCount() != 1 || !activeEngine){ c = new QmlComponent(activeEngine); }else{ - c = new QmlComponent(activeEngine, QUrl(ctxt->argument(0).toString()), - activeEngine); + QUrl url = QUrl(ctxt->argument(0).toString()); + c = new QmlComponent(activeEngine, url, activeEngine); } return engine->newQObject(c); } @@ -897,7 +918,7 @@ QScriptValue QmlEngine::createQMLObject(QScriptContext *ctxt, QScriptEngine *eng if(ctxt->argumentCount() < 1){ qWarning() << "createQMLObject requires a string argument."; }else{ - qWarning() << "createQMLObject failed inexplicably."; + qWarning() << "createQMLObject cannot find engine."; } return engine->nullValue(); } @@ -1518,18 +1539,37 @@ void QmlContextScriptClass::setProperty(QScriptValue &object, ///////////////////////////////////////////////////////////// /* The QmlObjectScriptClass handles property access for QObjects - via QtScript. + via QtScript. It is also used to provide a more useful API in + QtScript for QML. */ + +QScriptValue QmlObjectDestroy(QScriptContext *context, QScriptEngine *engine) +{ + QObject* obj = context->thisObject().data().toQObject(); + if(obj) + delete obj; + context->thisObject().setData(QScriptValue(engine, 0)); + return engine->nullValue(); +} + QmlObjectScriptClass::QmlObjectScriptClass(QmlEngine *bindEngine) : QmlScriptClass(bindEngine) { engine = bindEngine; + prototypeObject = engine->scriptEngine()->newObject(); + prototypeObject.setProperty("destroy", + engine->scriptEngine()->newFunction(QmlObjectDestroy)); } QmlObjectScriptClass::~QmlObjectScriptClass() { } +QScriptValue QmlObjectScriptClass::prototype() const +{ + return prototypeObject; +} + QScriptClass::QueryFlags QmlObjectScriptClass::queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id) diff --git a/src/declarative/qml/qmlengine.h b/src/declarative/qml/qmlengine.h index ca66097..f114379 100644 --- a/src/declarative/qml/qmlengine.h +++ b/src/declarative/qml/qmlengine.h @@ -90,7 +90,6 @@ public: static QScriptValue qmlScriptObject(QObject*, QmlEngine*); - // Below two functions provide a way to dynamically create objects from JS static QScriptValue createComponent(QScriptContext*, QScriptEngine*); static QScriptValue createQMLObject(QScriptContext*, QScriptEngine*); diff --git a/src/declarative/qml/qmlengine_p.h b/src/declarative/qml/qmlengine_p.h index 89b0a4a..d7249e4 100644 --- a/src/declarative/qml/qmlengine_p.h +++ b/src/declarative/qml/qmlengine_p.h @@ -221,6 +221,9 @@ public: QmlObjectScriptClass(QmlEngine *); ~QmlObjectScriptClass(); + virtual QScriptValue prototype () const; + QScriptValue prototypeObject; + virtual QueryFlags queryProperty(const QScriptValue &object, const QScriptString &name, QueryFlags flags, uint *id); -- cgit v0.12 From ebcf875d90d940103e409de9127bb592d7336afe Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 9 Jun 2009 09:10:53 +0200 Subject: qdoc: Inserted
      between summary sections. Also added the left and right borders to the function headers in the detail sections. --- tools/qdoc3/htmlgenerator.cpp | 3 ++- tools/qdoc3/test/classic.css | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index 90d3b04..0c21534 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -1073,6 +1073,7 @@ void HtmlGenerator::generateClassLikeNode(const InnerNode *inner, if (!s->inherited.isEmpty()) needOtherSection = true; } else { + out() << "
      \n"; out() << "\n"; @@ -2335,7 +2336,7 @@ void HtmlGenerator::generateSynopsis(const Node *node, QString HtmlGenerator::highlightedCode(const QString& markedCode, CodeMarker *marker, const Node *relative, - CodeMarker::SynopsisStyle style, + CodeMarker::SynopsisStyle , bool nameAlignment) { QString src = markedCode; diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index 3e2370d..85bb348 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -17,7 +17,7 @@ h3.fn,span.fn background-color: #e0eff6; border-width: 1px; border-style: solid; - border-color: #3388be #e0eff6 #e9f8ff #e0eff6; + border-color: #3388be #3388be #e9f8ff #3388be; font-weight: bold; padding: 6px 0px 6px 10px; } -- cgit v0.12 From b5c401b9aa3481886ad9e2d7816680c97839004e Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 25 May 2009 11:59:10 +0200 Subject: Add recursive drawing method to QGraphicsScene. For now it's opt-in, but the important thing is by effectively implementing Simple Canvas' approach to drawing, we're in theory (and in practise measured on the desktop) as fast as Simple Canvas when rendering. --- src/gui/graphicsview/qgraphicsscene.cpp | 82 +++++++++++++++++++++++++++++++++ src/gui/graphicsview/qgraphicsscene_p.h | 3 ++ src/gui/graphicsview/qgraphicsview.cpp | 34 ++++++++------ src/gui/graphicsview/qgraphicsview.h | 3 +- 4 files changed, 107 insertions(+), 15 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 49c2329..362d66d 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -1870,6 +1870,11 @@ inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item return z1 != z2 ? z1 > z2 : d1->siblingIndex > d2->siblingIndex; } +static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2) +{ + return qt_closestLeaf(item2, item1); +} + /*! \internal @@ -5013,6 +5018,83 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } } +void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, + const QRegion &exposedRegion, QWidget *widget) +{ + if (item && (!item->isVisible() || qFuzzyIsNull(item->opacity()))) + return; + + painter->save(); + + // Set transform + if (item) { + if (item->d_ptr->itemIsUntransformable()) { + painter->setWorldTransform(item->deviceTransform(viewTransform), false); + } else { + const QPointF &pos = item->d_ptr->pos; + bool posNull = pos.isNull(); + if (!posNull || item->d_ptr->hasTransform) { + if (item->d_ptr->hasTransform) { + QTransform x = item->transform(); + if (!posNull) + x *= QTransform::fromTranslate(pos.x(), pos.y()); + painter->setWorldTransform(x, true); + } else { + painter->setWorldTransform(QTransform::fromTranslate(pos.x(), pos.y()), true); + } + } + } + } + + // Setup recursive clipping. + if (item && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) + painter->setClipPath(item->shape(), Qt::IntersectClip); + +#if 0 + const QList &children = item ? item->d_ptr->children : topLevelItems; +#else + // ### if we ensure all children are sorted by Z by default, we don't have + // to sort this list for each paint. + QList children = item ? item->d_ptr->children : topLevelItems; + qSort(children.begin(), children.end(), qt_notclosestLeaf); +#endif + + // Draw children behind + int i; + for (i = 0; i < children.size(); ++i) { + QGraphicsItem *child = children.at(i); + if (!(child->flags() & QGraphicsItem::ItemStacksBehindParent)) + break; + drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget); + } + + // Draw item + if (item) { + QRect itemViewRect = painter->worldTransform().mapRect(item->boundingRect()).toRect().adjusted(-1, -1, 1, 1); + if (itemViewRect.intersects(exposedRegion.boundingRect())) { + QStyleOptionGraphicsItem option; + item->d_ptr->initStyleOption(&option, painter->worldTransform(), exposedRegion); + + bool clipsToShape = (item->flags() & QGraphicsItem::ItemClipsToShape); + if (clipsToShape) { + painter->save(); + painter->setClipPath(item->shape(), Qt::IntersectClip); + } + + drawItemHelper(item, painter, &option, widget, false); + + if (clipsToShape) + painter->restore(); + } + } + + // Draw children in front + for (; i < children.size(); ++i) + drawSubtreeRecursive(children.at(i), painter, viewTransform, exposedRegion, widget); + + painter->restore(); +} + /*! Paints the given \a items using the provided \a painter, after the background has been drawn, and before the foreground has been diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 9ace725..369b0ef 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -253,6 +253,9 @@ public: const QStyleOptionGraphicsItem *option, QWidget *widget, bool painterStateProtection); + void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, + const QRegion &exposedRegion, QWidget *widget); + QStyle *style; QFont font; void setFont_helper(const QFont &font); diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 10b837a..2459c49 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3387,10 +3387,6 @@ void QGraphicsView::paintEvent(QPaintEvent *event) bool allItems = false; QList itemList = d->findItems(exposedRegion, &allItems); -#ifdef QGRAPHICSVIEW_DEBUG - int exposedTime = stopWatch.elapsed(); -#endif - if ((d->cacheMode & CacheBackground) #ifdef Q_WS_X11 && X11->use_xrender @@ -3436,16 +3432,26 @@ void QGraphicsView::paintEvent(QPaintEvent *event) int backgroundTime = stopWatch.elapsed() - exposedTime; #endif - if (!itemList.isEmpty()) { - // Generate the style options. - const int numItems = itemList.size(); - QGraphicsItem **itemArray = &itemList[0]; // Relies on QList internals, but is perfectly valid. - QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems); - for (int i = 0; i < numItems; ++i) - itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], viewTransform, exposedRegion, allItems); - // Draw the items. - drawItems(&painter, numItems, itemArray, styleOptionArray); - d->freeStyleOptionsArray(styleOptionArray); + const char *directEnv = getenv("QGRAPHICSVIEW_DIRECT"); + bool overrideDirectPaint = directEnv && atoi(directEnv) != 0; + if (overrideDirectPaint || (d->optimizationFlags & BypassDrawItems)) { + d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, exposedRegion, viewport()); + } else { + // Find all exposed items + bool allItems = false; + QList itemList = d->findItems(exposedRegion, &allItems); + + if (!itemList.isEmpty()) { + // Generate the style options. + const int numItems = itemList.size(); + QGraphicsItem **itemArray = &itemList[0]; // Relies on QList internals, but is perfectly valid. + QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems); + for (int i = 0; i < numItems; ++i) + itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], viewTransform, exposedRegion, allItems); + // Draw the items. + drawItems(&painter, numItems, itemArray, styleOptionArray); + d->freeStyleOptionsArray(styleOptionArray); + } } #ifdef QGRAPHICSVIEW_DEBUG diff --git a/src/gui/graphicsview/qgraphicsview.h b/src/gui/graphicsview/qgraphicsview.h index c3ea6e5..7692e16 100644 --- a/src/gui/graphicsview/qgraphicsview.h +++ b/src/gui/graphicsview/qgraphicsview.h @@ -112,7 +112,8 @@ public: enum OptimizationFlag { DontClipPainter = 0x1, // obsolete DontSavePainterState = 0x2, - DontAdjustForAntialiasing = 0x4 + DontAdjustForAntialiasing = 0x4, + BypassDrawItems = 0x8 }; Q_DECLARE_FLAGS(OptimizationFlags, OptimizationFlag) -- cgit v0.12 From 82cff1af638de427aa3d6f8bd147f4451662ee65 Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Tue, 9 Jun 2009 17:22:25 +1000 Subject: Add dynamic object creation example --- examples/declarative/dynamic/dynamic.js | 52 +++++++++++++++++++++++++++++++ examples/declarative/dynamic/dynamic.qml | 16 ++++++++++ examples/declarative/dynamic/star.png | Bin 0 -> 262 bytes 3 files changed, 68 insertions(+) create mode 100644 examples/declarative/dynamic/dynamic.js create mode 100644 examples/declarative/dynamic/dynamic.qml create mode 100644 examples/declarative/dynamic/star.png diff --git a/examples/declarative/dynamic/dynamic.js b/examples/declarative/dynamic/dynamic.js new file mode 100644 index 0000000..66ec292 --- /dev/null +++ b/examples/declarative/dynamic/dynamic.js @@ -0,0 +1,52 @@ +var sprite = null; +var component; +var started = false; +function make(p) { + return evalQml('Rect { color: "lightsteelblue"; width: 100;' + + 'height: 100; id: newRect}','DynPart.qml'); +} + +function death() { + if(!(sprite==null)){ + sprite.destroy(); + sprite = null; + } +} + +function spawn() {//Like create, but assumes instant readyness + if(sprite!=null)//Already made + return null; + component = createComponent("dynamic.qml"); + sprite = component.createObject(); + if(sprite == null){ + print("err"); + }else{ + sprite.parent = targetItem; + return sprite; + } + return null; +} + +function finishCreation(){ + if(component.isReady()){ + sprite = component.createObject(); + sprite.parent = targetItem; + }else if(component.isError()){ + sprite = null; + } +} + +function create(){ + if(started!=false){ + finishCreation();//Remakes if destroyed + return sprite; + } + started = true; + component = createComponent("dynamic.qml"); + finishCreation(); + if(sprite != null){ + return sprite; + } + component.statusChanged.connect(finishCreation); + return null; +} diff --git a/examples/declarative/dynamic/dynamic.qml b/examples/declarative/dynamic/dynamic.qml new file mode 100644 index 0000000..ee81ff6 --- /dev/null +++ b/examples/declarative/dynamic/dynamic.qml @@ -0,0 +1,16 @@ +Rect { id: page; width: 800; height: 800; color:"black" + Script { source: "dynamic.js" } + property bool fourthBox: false; + Item { id: targetItem; x: 100; y: 100; } + Item { id: targetItem2; x: 0; y: 300; } + Rect { width: 100; height: 100; color: "green"; id: rect + MouseRegion { anchors.fill:parent; onClicked: {a = create();}} + } + Rect { width: 100; height: 100; color: "red"; id: rect2; y:100; + MouseRegion { anchors.fill:parent; onClicked: {death();}} + } + Rect { width: 100; height: 100; color: "blue"; id: rect3; y:200; + MouseRegion { anchors.fill:parent; onClicked: {a = make(); if(a!=null){a.parent = targetItem2; fourthBox = true;}}} + } + Particles { x:0; y:0; count:20; lifeSpan:500; width:100; height: if(fourthBox){400;}else{300;} source:"star.png"} +} diff --git a/examples/declarative/dynamic/star.png b/examples/declarative/dynamic/star.png new file mode 100644 index 0000000..defbde5 Binary files /dev/null and b/examples/declarative/dynamic/star.png differ -- cgit v0.12 From 1873203f3a3c64a2eb59bbc555eb8edf6b30315a Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 25 May 2009 16:41:31 +0200 Subject: Fix optimization flags and opacity. --- src/gui/graphicsview/qgraphicsscene.cpp | 44 +++++++++++++++++++++++---------- src/gui/graphicsview/qgraphicsscene_p.h | 3 ++- src/gui/graphicsview/qgraphicsview.cpp | 3 ++- 3 files changed, 35 insertions(+), 15 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 362d66d..e360a07 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5019,12 +5019,22 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, - const QRegion &exposedRegion, QWidget *widget) + const QRegion &exposedRegion, QWidget *widget, + QGraphicsView::OptimizationFlags optimizationFlags) { - if (item && (!item->isVisible() || qFuzzyIsNull(item->opacity()))) + if (item && (!item->isVisible())) return; - painter->save(); + bool hasOpacity = item && item->d_ptr->hasEffectiveOpacity; + bool childClip = (item && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)); + bool savePainter = !(optimizationFlags & QGraphicsView::DontSavePainterState); + + QTransform restoreTransform; + if (childClip || hasOpacity) { + painter->save(); + } else { + restoreTransform = painter->worldTransform(); + } // Set transform if (item) { @@ -5047,8 +5057,10 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } // Setup recursive clipping. - if (item && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) + if (childClip) painter->setClipPath(item->shape(), Qt::IntersectClip); + if (hasOpacity) + painter->setOpacity(item->effectiveOpacity()); #if 0 const QList &children = item ? item->d_ptr->children : topLevelItems; @@ -5065,34 +5077,40 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * QGraphicsItem *child = children.at(i); if (!(child->flags() & QGraphicsItem::ItemStacksBehindParent)) break; - drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget); + drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, optimizationFlags); } // Draw item - if (item) { - QRect itemViewRect = painter->worldTransform().mapRect(item->boundingRect()).toRect().adjusted(-1, -1, 1, 1); + if (item && !item->d_ptr->isFullyTransparent()) { + QRectF brect = item->boundingRect(); + _q_adjustRect(&brect); + QRect itemViewRect = painter->worldTransform().mapRect(brect).toRect().adjusted(-1, -1, 1, 1); if (itemViewRect.intersects(exposedRegion.boundingRect())) { QStyleOptionGraphicsItem option; item->d_ptr->initStyleOption(&option, painter->worldTransform(), exposedRegion); bool clipsToShape = (item->flags() & QGraphicsItem::ItemClipsToShape); - if (clipsToShape) { + if (savePainter || clipsToShape) painter->save(); + if (clipsToShape) painter->setClipPath(item->shape(), Qt::IntersectClip); - } drawItemHelper(item, painter, &option, widget, false); - - if (clipsToShape) + + if (savePainter || clipsToShape) painter->restore(); } } // Draw children in front for (; i < children.size(); ++i) - drawSubtreeRecursive(children.at(i), painter, viewTransform, exposedRegion, widget); + drawSubtreeRecursive(children.at(i), painter, viewTransform, exposedRegion, widget, optimizationFlags); - painter->restore(); + if (childClip || hasOpacity) { + painter->restore(); + } else { + painter->setWorldTransform(restoreTransform, /* combine = */ false); + } } /*! diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 369b0ef..0ac1765 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -57,6 +57,7 @@ #if !defined(QT_NO_GRAPHICSVIEW) || (QT_EDITION & QT_MODULE_GRAPHICSVIEW) != QT_MODULE_GRAPHICSVIEW +#include "qgraphicsview.h" #include "qgraphicsscene_bsp_p.h" #include "qgraphicsitem_p.h" @@ -254,7 +255,7 @@ public: bool painterStateProtection); void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, - const QRegion &exposedRegion, QWidget *widget); + const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags); QStyle *style; QFont font; diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 2459c49..40c84db 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3435,7 +3435,8 @@ void QGraphicsView::paintEvent(QPaintEvent *event) const char *directEnv = getenv("QGRAPHICSVIEW_DIRECT"); bool overrideDirectPaint = directEnv && atoi(directEnv) != 0; if (overrideDirectPaint || (d->optimizationFlags & BypassDrawItems)) { - d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, exposedRegion, viewport()); + d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, exposedRegion, + viewport(), d->optimizationFlags); } else { // Find all exposed items bool allItems = false; -- cgit v0.12 From 6cbc582c9699498e7f1762121bb2cff04d2596ce Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 25 May 2009 17:15:03 +0200 Subject: Minor optimizations. --- src/gui/graphicsview/qgraphicsscene.cpp | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index e360a07..45108ca 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5022,15 +5022,14 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags) { - if (item && (!item->isVisible())) + if (item && !item->d_ptr->visible) return; - bool hasOpacity = item && item->d_ptr->hasEffectiveOpacity; - bool childClip = (item && (item->flags() & QGraphicsItem::ItemClipsChildrenToShape)); + bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); bool savePainter = !(optimizationFlags & QGraphicsView::DontSavePainterState); QTransform restoreTransform; - if (childClip || hasOpacity) { + if (childClip) { painter->save(); } else { restoreTransform = painter->worldTransform(); @@ -5059,7 +5058,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Setup recursive clipping. if (childClip) painter->setClipPath(item->shape(), Qt::IntersectClip); - if (hasOpacity) + if (item) painter->setOpacity(item->effectiveOpacity()); #if 0 @@ -5075,7 +5074,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * int i; for (i = 0; i < children.size(); ++i) { QGraphicsItem *child = children.at(i); - if (!(child->flags() & QGraphicsItem::ItemStacksBehindParent)) + if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) break; drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, optimizationFlags); } @@ -5089,7 +5088,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * QStyleOptionGraphicsItem option; item->d_ptr->initStyleOption(&option, painter->worldTransform(), exposedRegion); - bool clipsToShape = (item->flags() & QGraphicsItem::ItemClipsToShape); + bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); if (savePainter || clipsToShape) painter->save(); if (clipsToShape) @@ -5106,7 +5105,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * for (; i < children.size(); ++i) drawSubtreeRecursive(children.at(i), painter, viewTransform, exposedRegion, widget, optimizationFlags); - if (childClip || hasOpacity) { + if (childClip) { painter->restore(); } else { painter->setWorldTransform(restoreTransform, /* combine = */ false); -- cgit v0.12 From 6f1cca3661b794f170ed00fdc84e8ad31789aa9f Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 26 May 2009 09:07:44 +0200 Subject: Further optimizations, from the simple canvas rendering logics. --- src/gui/graphicsview/qgraphicsscene.cpp | 115 +++++++++++++++++--------------- src/gui/graphicsview/qgraphicsscene_p.h | 3 +- src/gui/graphicsview/qgraphicsview.cpp | 2 +- 3 files changed, 63 insertions(+), 57 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 45108ca..7eb49e9 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5018,27 +5018,20 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } } -void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, +void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, + const QTransform &viewTransform, const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags) { - if (item && !item->d_ptr->visible) + if (item && item->d_ptr->isInvisible()) return; - bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); - bool savePainter = !(optimizationFlags & QGraphicsView::DontSavePainterState); - - QTransform restoreTransform; - if (childClip) { - painter->save(); - } else { - restoreTransform = painter->worldTransform(); - } - - // Set transform + // Calculate the full transform for this item. + QTransform transform; + QRect viewBoundingRect; if (item) { if (item->d_ptr->itemIsUntransformable()) { - painter->setWorldTransform(item->deviceTransform(viewTransform), false); + transform = item->deviceTransform(viewTransform); } else { const QPointF &pos = item->d_ptr->pos; bool posNull = pos.isNull(); @@ -5047,69 +5040,81 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * QTransform x = item->transform(); if (!posNull) x *= QTransform::fromTranslate(pos.x(), pos.y()); - painter->setWorldTransform(x, true); + transform = x * parentTransform; } else { - painter->setWorldTransform(QTransform::fromTranslate(pos.x(), pos.y()), true); + transform = QTransform::fromTranslate(pos.x(), pos.y()) * parentTransform; } + } else { + transform = parentTransform; } } + QRectF brect = item->boundingRect(); + _q_adjustRect(&brect); + viewBoundingRect = transform.mapRect(brect).toRect().adjusted(-1, -1, 1, 1) & exposedRegion.boundingRect(); + } else { + transform = parentTransform; } - // Setup recursive clipping. - if (childClip) - painter->setClipPath(item->shape(), Qt::IntersectClip); - if (item) - painter->setOpacity(item->effectiveOpacity()); - -#if 0 - const QList &children = item ? item->d_ptr->children : topLevelItems; -#else - // ### if we ensure all children are sorted by Z by default, we don't have - // to sort this list for each paint. + // Find and sort children. QList children = item ? item->d_ptr->children : topLevelItems; qSort(children.begin(), children.end(), qt_notclosestLeaf); -#endif + + bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); + bool dontDrawItem = !item || viewBoundingRect.isEmpty(); + bool dontDrawChildren = item && dontDrawItem && childClip; + childClip &= !dontDrawChildren & !children.isEmpty(); + + // Clip children. + if (childClip) { + painter->save(); + painter->setWorldTransform(transform); + painter->setClipPath(item->shape(), Qt::IntersectClip); + } // Draw children behind int i; - for (i = 0; i < children.size(); ++i) { - QGraphicsItem *child = children.at(i); - if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) - break; - drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, optimizationFlags); + if (!dontDrawChildren) { + for (i = 0; i < children.size(); ++i) { + QGraphicsItem *child = children.at(i); + if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) + break; + drawSubtreeRecursive(child, painter, transform, viewTransform, + exposedRegion, widget, optimizationFlags); + } } // Draw item - if (item && !item->d_ptr->isFullyTransparent()) { - QRectF brect = item->boundingRect(); - _q_adjustRect(&brect); - QRect itemViewRect = painter->worldTransform().mapRect(brect).toRect().adjusted(-1, -1, 1, 1); - if (itemViewRect.intersects(exposedRegion.boundingRect())) { - QStyleOptionGraphicsItem option; - item->d_ptr->initStyleOption(&option, painter->worldTransform(), exposedRegion); + if (!dontDrawItem) { + QStyleOptionGraphicsItem option; + item->d_ptr->initStyleOption(&option, transform, exposedRegion); - bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); - if (savePainter || clipsToShape) - painter->save(); - if (clipsToShape) - painter->setClipPath(item->shape(), Qt::IntersectClip); + bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); + bool savePainter = clipsToShape || !(optimizationFlags & QGraphicsView::DontSavePainterState); + if (savePainter) + painter->save(); + if (!childClip) + painter->setWorldTransform(transform); + if (clipsToShape) + painter->setClipPath(item->shape(), Qt::IntersectClip); + painter->setOpacity(item->effectiveOpacity()); - drawItemHelper(item, painter, &option, widget, false); + drawItemHelper(item, painter, &option, widget, false); - if (savePainter || clipsToShape) - painter->restore(); - } + if (savePainter) + painter->restore(); } // Draw children in front - for (; i < children.size(); ++i) - drawSubtreeRecursive(children.at(i), painter, viewTransform, exposedRegion, widget, optimizationFlags); + if (!dontDrawChildren) { + for (; i < children.size(); ++i) { + drawSubtreeRecursive(children.at(i), painter, transform, viewTransform, + exposedRegion, widget, optimizationFlags); + } + } - if (childClip) { + // Restore child clip + if (childClip) painter->restore(); - } else { - painter->setWorldTransform(restoreTransform, /* combine = */ false); - } } /*! diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 0ac1765..bb99908 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -254,7 +254,8 @@ public: const QStyleOptionGraphicsItem *option, QWidget *widget, bool painterStateProtection); - void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, + void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, + const QTransform &viewTransform, const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags); QStyle *style; diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 40c84db..1994675 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3435,7 +3435,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) const char *directEnv = getenv("QGRAPHICSVIEW_DIRECT"); bool overrideDirectPaint = directEnv && atoi(directEnv) != 0; if (overrideDirectPaint || (d->optimizationFlags & BypassDrawItems)) { - d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, exposedRegion, + d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, viewTransform, exposedRegion, viewport(), d->optimizationFlags); } else { // Find all exposed items -- cgit v0.12 From e7c7e4f57530d7b3571bf11dbe555c52f6dc3f34 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Tue, 26 May 2009 20:23:54 +0200 Subject: Cache QGraphicsItem::childrenBoundingRect. We'll need this later when making a smarter update mechanism. --- src/gui/graphicsview/qgraphicsitem.cpp | 15 +++++++++++++++ src/gui/graphicsview/qgraphicsitem_p.h | 5 ++++- 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index b9e462b..e09d3f0 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -925,6 +925,11 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de */ void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rect) { + if (!dirtyChildrenBoundingRect) { + *rect |= x->mapRect(childrenBoundingRect); + return; + } + for (int i = 0; i < children.size(); ++i) { QGraphicsItem *child = children.at(i); QGraphicsItemPrivate *childd = child->d_ptr; @@ -948,6 +953,9 @@ void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rec childd->childrenBoundingRectHelper(x, rect); } } + + childrenBoundingRect = *rect; + dirtyChildrenBoundingRect = 0; } void QGraphicsItemPrivate::initStyleOption(QStyleOptionGraphicsItem *option, const QTransform &worldTransform, @@ -3567,6 +3575,9 @@ void QGraphicsItem::setZValue(qreal z) */ QRectF QGraphicsItem::childrenBoundingRect() const { + if (!d_ptr->dirtyChildrenBoundingRect) + return d_ptr->childrenBoundingRect; + QRectF childRect; QTransform x; d_ptr->childrenBoundingRectHelper(&x, &childRect); @@ -6400,6 +6411,10 @@ void QGraphicsItem::prepareGeometryChange() scenePrivate->removeFromIndex(this); } + QGraphicsItem *parent = this; + while (parent = parent->d_ptr->parent) + parent->d_ptr->dirtyChildrenBoundingRect = 1; + if (d_ptr->inSetPosHelper) return; diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index bd81fe5..200d177 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -160,6 +160,7 @@ public: hasDecomposedTransform(0), dirtyTransform(0), dirtyTransformComponents(0), + dirtyChildrenBoundingRect(1), globalStackingOrder(-1), sceneTransformIndex(-1), q_ptr(0) @@ -308,6 +309,7 @@ public: } QPainterPath cachedClipPath; + QRectF childrenBoundingRect; QPointF pos; qreal z; QGraphicsScene *scene; @@ -350,7 +352,8 @@ public: quint32 hasDecomposedTransform : 1; quint32 dirtyTransform : 1; quint32 dirtyTransformComponents : 1; - quint32 padding : 18; // feel free to use + quint32 dirtyChildrenBoundingRect : 1; + quint32 padding : 17; // feel free to use // Optional stacking order int globalStackingOrder; -- cgit v0.12 From 63a3c0ad549b57d0896f267383cf671d6212a70e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Wed, 27 May 2009 21:31:44 +0200 Subject: Massive re-factoring of Graphics View's update mechanism. This is work-in-progress, so don't expect everything to work perfectly. Most of the auto-test pass and examples and demos seem to run fine. Unfortunately I'm too tired to write about the actual update mehanism now, but it's faster than the old approach (if that helps:)). There's more to optimize, but I'll come back to that later. I need some sleep now :) To be continued. --- src/gui/graphicsview/qgraphicsitem.cpp | 156 ++++++----------- src/gui/graphicsview/qgraphicsitem_p.h | 22 ++- src/gui/graphicsview/qgraphicsscene.cpp | 212 ++++++++++++----------- src/gui/graphicsview/qgraphicsscene.h | 4 +- src/gui/graphicsview/qgraphicsscene_p.h | 30 +++- src/gui/graphicsview/qgraphicsview.cpp | 194 ++++----------------- src/gui/graphicsview/qgraphicsview.h | 1 - src/gui/graphicsview/qgraphicsview_p.h | 9 +- tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp | 5 +- 9 files changed, 253 insertions(+), 380 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index e09d3f0..ec6b35b 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -863,8 +863,11 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de parent->d_ptr->addChild(q); parent->itemChange(QGraphicsItem::ItemChildAddedChange, thisPointerVariant); - if (!implicitUpdate) - updateHelper(QRectF(), false, true); + if (!implicitUpdate && scene) { + scene->d_func()->markDirty(q_ptr, QRect(), + /*invalidateChildren=*/false, + /*maybeDirtyClipPath=*/true); + } // Inherit ancestor flags from the new parent. updateAncestorFlag(QGraphicsItem::GraphicsItemFlag(-1)); @@ -895,7 +898,11 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de setEnabledHelper(true, /* explicit = */ false); // If the item is being deleted, the whole scene will be updated. - updateHelper(QRectF(), false, true); + if (scene) { + scene->d_func()->markDirty(q_ptr, QRect(), + /*invalidateChildren=*/false, + /*maybeDirtyClipPath=*/true); + } } } @@ -1358,7 +1365,7 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) const quint32 geomChangeFlagsMask = (ItemClipsChildrenToShape | ItemClipsToShape | ItemIgnoresTransformations); bool fullUpdate = (quint32(flags) & geomChangeFlagsMask) != (d_ptr->flags & geomChangeFlagsMask); if (fullUpdate) - d_ptr->fullUpdateHelper(false, true); + d_ptr->paintedViewBoundingRectsNeedRepaint = 1; // Keep the old flags to compare the diff. GraphicsItemFlags oldFlags = this->flags(); @@ -1398,8 +1405,11 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) d_ptr->updateAncestorFlag(ItemIgnoresTransformations); } - // ### Why updateHelper? - d_ptr->updateHelper(QRectF(), false, true); + if (d_ptr->scene) { + d_ptr->scene->d_func()->markDirty(this, QRectF(), + /*invalidateChildren=*/true, + /*maybeDirtyClipPath*/true); + } // Notify change. itemChange(ItemFlagsHaveChanged, quint32(flags)); @@ -1665,7 +1675,12 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo QGraphicsItemCache *c = (QGraphicsItemCache *)qVariantValue(extra(ExtraCacheData)); if (c) c->purge(); - updateHelper(QRectF(), /* force = */ true); + if (scene) { + scene->d_func()->markDirty(q_ptr, QRectF(), + /*invalidateChildren=*/false, + /*maybeDirtyClipPath=*/false, + /*force=*/true); + } } // Certain properties are dropped as an item becomes invisible. @@ -1828,8 +1843,8 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo enabled = newEnabledVariant.toBool(); // Schedule redraw. - if (update) - updateHelper(); + if (update && scene) + scene->d_func()->markDirty(q_ptr); foreach (QGraphicsItem *child, children) { if (!newEnabled || !child->d_ptr->explicitlyDisabled) @@ -1930,9 +1945,8 @@ void QGraphicsItem::setSelected(bool selected) return; d_ptr->selected = newSelected; - d_ptr->updateHelper(); - if (d_ptr->scene) { + d_ptr->scene->d_func()->markDirty(this); QGraphicsScenePrivate *sceneD = d_ptr->scene->d_func(); if (selected) { sceneD->selectedItems << this; @@ -2051,7 +2065,12 @@ void QGraphicsItem::setOpacity(qreal opacity) itemChange(ItemOpacityHasChanged, newOpacity); // Update. - d_ptr->fullUpdateHelper(/*childrenOnly=*/false, /*maybeDirtyClipPath=*/false, /*ignoreOpacity=*/true); + if (d_ptr->scene) + d_ptr->scene->d_func()->markDirty(this, QRectF(), + /*invalidateChildren=*/true, + /*maybeDirtyClipPath=*/false, + /*force=*/false, + /*ignoreOpacity=*/true); } /*! @@ -2501,10 +2520,8 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) // Update and repositition. inSetPosHelper = 1; updateCachedClipPathFromSetPosHelper(newPos); - if (scene) { - fullUpdateHelper(true); + if (scene) q->prepareGeometryChange(); - } this->pos = newPos; invalidateSceneTransformCache(); @@ -3305,7 +3322,6 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) return; // Update and set the new transformation. - d_ptr->fullUpdateHelper(true, true); prepareGeometryChange(); d_ptr->hasTransform = !newTransform.isIdentity(); d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); @@ -3358,7 +3374,6 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) return; // Update and set the new transformation. - d_ptr->fullUpdateHelper(true, true); prepareGeometryChange(); d_ptr->hasTransform = !newTransform.isIdentity(); d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); @@ -3545,9 +3560,9 @@ void QGraphicsItem::setZValue(qreal z) if (newZ == d_ptr->z) return; d_ptr->z = newZ; - d_ptr->fullUpdateHelper(); if (d_ptr->scene) { + d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true); // Invalidate any sort caching; arrival of a new item means we need to // resort. d_ptr->scene->d_func()->invalidateSortCache(); @@ -4208,84 +4223,13 @@ bool QGraphicsItemPrivate::discardUpdateRequest(bool ignoreClipping, bool ignore // No scene, or if the scene is updating everything, means we have nothing // to do. The only exception is if the scene tracks the growing scene rect. return (!visible && !ignoreVisibleBit) - || (dirty && !ignoreDirtyBit) + || (!ignoreDirtyBit && (dirty || hasDirtyAncestor())) || !scene || (scene->d_func()->updateAll && scene->d_func()->hasSceneRect) || (!ignoreClipping && (childrenClippedToShape() && isClippedAway())) || (!ignoreOpacity && childrenCombineOpacity() && isFullyTransparent()); } -/*! - \internal - - Asks the scene to mark this item's scene rect as dirty, requesting a - redraw. This does not invalidate any cache. - - The \a force argument is for the update call in setVisible(), which is the - only case where the item's background should be marked as dirty even when - the item isn't visible. -*/ -void QGraphicsItemPrivate::updateHelper(const QRectF &rect, bool force, bool maybeDirtyClipPath) -{ - // No scene, or if the scene is updating everything, means we have nothing - // to do. The only exception is if the scene tracks the growing scene rect. - if (discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath, /*ignoreVisibleBit=*/force)) - return; - - if (rect.isNull()) - dirty = 1; - scene->itemUpdated(q_ptr, rect); -} - -/*! - \internal - - Propagates updates to \a item and all its children. -*/ -void QGraphicsItemPrivate::fullUpdateHelper(bool childrenOnly, bool maybeDirtyClipPath, bool ignoreOpacity) -{ - if (discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath, /*ignoreVisibleBit=*/false, - /*ignoreDirtyBit=*/true, ignoreOpacity)) { - return; - } - - if (!childrenOnly && !dirty) { - // Effectively the same as updateHelper(QRectF(), false, maybeDirtyClipPath). - dirty = 1; - scene->itemUpdated(q_ptr, QRectF()); - } - - if (dirtyChildren || childrenClippedToShape()) { - // Unnecessary to update children as well. - return; - } - - if (ancestorFlags & AncestorClipsChildren) { - Q_Q(QGraphicsItem); - // Check if we can avoid updating all children. - QGraphicsItem *p = parent; - QRectF br = q->boundingRect(); - while (p) { - if (p->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape) { - bool ok; - QTransform x = q->itemTransform(p, &ok); - if (!ok) - break; - if (x.mapRect(br).contains(p->boundingRect())) - return; - } - p = p->d_ptr->parent; - if (!p || !(p->d_ptr->ancestorFlags & AncestorClipsChildren)) - break; - // ### check one level only - break; - } - } - foreach (QGraphicsItem *child, children) - child->d_ptr->fullUpdateHelper(false, maybeDirtyClipPath); - dirtyChildren = 1; -} - static inline bool allChildrenCombineOpacityHelper(QGraphicsItem *parent) { Q_ASSERT(parent); @@ -4590,14 +4534,10 @@ void QGraphicsItem::update(const QRectF &rect) // Only invalidate cache; item is already dirty. if (d_ptr->dirty) return; - } else if (d_ptr->discardUpdateRequest()) { - return; } - // Effectively the same as updateHelper(rect); - if (rect.isNull()) - d_ptr->dirty = 1; - d_ptr->scene->itemUpdated(this, rect); + if (d_ptr->scene) + d_ptr->scene->d_func()->markDirty(this); } /*! @@ -4695,7 +4635,7 @@ void QGraphicsItem::scroll(qreal dx, qreal dy, const QRectF &rect) exposed -= r.translated(dx, dy); foreach (QRect rect, exposed.rects()) update(rect); - d_ptr->updateHelper(); + d->scene->d_func()->markDirty(this); } else { update(rect); } @@ -5911,7 +5851,8 @@ void QGraphicsItem::focusOutEvent(QFocusEvent *event) void QGraphicsItem::hoverEnterEvent(QGraphicsSceneHoverEvent *event) { Q_UNUSED(event); - d_ptr->updateHelper(); + if (d_ptr->scene) + d_ptr->scene->d_func()->markDirty(this); } /*! @@ -5939,7 +5880,8 @@ void QGraphicsItem::hoverMoveEvent(QGraphicsSceneHoverEvent *event) void QGraphicsItem::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) { Q_UNUSED(event); - d_ptr->updateHelper(); + if (d_ptr->scene) + d_ptr->scene->d_func()->markDirty(this); } /*! @@ -6367,9 +6309,10 @@ void QGraphicsItem::addToIndex() // ### add to child index only if applicable return; } - if (d_ptr->scene) + if (d_ptr->scene) { d_ptr->scene->d_func()->addToIndex(this); - d_ptr->updateHelper(); + d_ptr->scene->d_func()->markDirty(this); + } } /*! @@ -6385,9 +6328,10 @@ void QGraphicsItem::removeFromIndex() // ### remove from child index only if applicable return; } - d_ptr->updateHelper(); - if (d_ptr->scene) + if (d_ptr->scene) { + d_ptr->scene->d_func()->markDirty(this); d_ptr->scene->d_func()->removeFromIndex(this); + } } /*! @@ -6406,7 +6350,10 @@ void QGraphicsItem::removeFromIndex() void QGraphicsItem::prepareGeometryChange() { if (d_ptr->scene) { - d_ptr->updateHelper(QRectF(), false, /*maybeDirtyClipPath=*/!d_ptr->inSetPosHelper); + d_ptr->paintedViewBoundingRectsNeedRepaint = 1; + d_ptr->scene->d_func()->markDirty(this, QRectF(), + /*invalidateChildren=*/true, + /*maybeDirtyClipPath=*/!d_ptr->inSetPosHelper); QGraphicsScenePrivate *scenePrivate = d_ptr->scene->d_func(); scenePrivate->removeFromIndex(this); } @@ -8075,7 +8022,6 @@ void QGraphicsPixmapItem::setTransformationMode(Qt::TransformationMode mode) { Q_D(QGraphicsPixmapItem); if (mode != d->transformationMode) { - d_ptr->updateHelper(); d->transformationMode = mode; update(); } diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 200d177..1d4b37a 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -161,6 +161,8 @@ public: dirtyTransform(0), dirtyTransformComponents(0), dirtyChildrenBoundingRect(1), + inDirtyList(0), + paintedViewBoundingRectsNeedRepaint(0), globalStackingOrder(-1), sceneTransformIndex(-1), q_ptr(0) @@ -186,8 +188,6 @@ public: void setEnabledHelper(bool newEnabled, bool explicitly, bool update = true); bool discardUpdateRequest(bool ignoreClipping = false, bool ignoreVisibleBit = false, bool ignoreDirtyBit = false, bool ignoreOpacity = false) const; - void updateHelper(const QRectF &rect = QRectF(), bool force = false, bool maybeDirtyClipPath = false); - void fullUpdateHelper(bool childrenOnly = false, bool maybeDirtyClipPath = false, bool ignoreOpacity = false); void updateEffectiveOpacity(); void resolveEffectiveOpacity(qreal effectiveParentOpacity); void resolveDepth(int parentDepth); @@ -308,8 +308,22 @@ public: || (childrenCombineOpacity() && isFullyTransparent()); } + inline bool hasDirtyAncestor() const + { + QGraphicsItem *p = parent; + while (p) { + if (p->d_ptr->dirtyChildren || (p->d_ptr->dirty && p->d_ptr->childrenClippedToShape())) + return true; + p = p->d_ptr->parent; + } + return false; + } + + QPainterPath cachedClipPath; QRectF childrenBoundingRect; + QRectF needsRepaint; + QMap paintedViewBoundingRects; QPointF pos; qreal z; QGraphicsScene *scene; @@ -353,7 +367,9 @@ public: quint32 dirtyTransform : 1; quint32 dirtyTransformComponents : 1; quint32 dirtyChildrenBoundingRect : 1; - quint32 padding : 17; // feel free to use + quint32 inDirtyList : 1; + quint32 paintedViewBoundingRectsNeedRepaint : 1; + quint32 padding : 15; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 7eb49e9..d004ed2 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -334,7 +334,6 @@ QGraphicsScenePrivate::QGraphicsScenePrivate() updateAll(false), calledEmitUpdated(false), selectionChanging(0), - dirtyItemResetPending(false), regenerateIndex(true), purgePending(false), indexTimerId(0), @@ -678,31 +677,81 @@ void QGraphicsScenePrivate::_q_polishItems() unpolishedItems.clear(); } -/*! - \internal -*/ -void QGraphicsScenePrivate::_q_resetDirtyItems() +void QGraphicsScenePrivate::_q_processDirtyItems() { + Q_Q(QGraphicsScene); + if (dirtyItems.isEmpty()) + return; + + if (updateAll) { + for (int i = 0; i < dirtyItems.size(); ++i) + resetDirtyItem(dirtyItems.at(i)); + dirtyItems.clear(); + return; + } + + const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask); for (int i = 0; i < dirtyItems.size(); ++i) { QGraphicsItem *item = dirtyItems.at(i); - item->d_ptr->dirty = 0; - item->d_ptr->dirtyChildren = 0; + if (useCompatUpdate && !item->d_ptr->itemIsUntransformable() + && qFuzzyIsNull(item->boundingRegionGranularity())) { + // This block of code is kept for compatibility. Since 4.5, by default + // QGraphicsView does not connect the signal and we use the below + // method of delivering updates. + q->update(item->sceneBoundingRect()); + resetDirtyItem(item); + continue; + } + + QRectF dirtyRect; + bool uninitializedDirtyRect = true; + + for (int j = 0; j < views.size(); ++j) { + QGraphicsView *view = views.at(j); + QGraphicsViewPrivate *viewPrivate = view->d_func(); + if (viewPrivate->fullUpdatePending) + continue; + switch (viewPrivate->viewportUpdateMode) { + case QGraphicsView::NoViewportUpdate: + continue; + case QGraphicsView::FullViewportUpdate: + view->viewport()->update(); + viewPrivate->fullUpdatePending = 1; + continue; + default: + break; + } + + if (uninitializedDirtyRect) { + dirtyRect = adjustedItemBoundingRect(item); + if (!item->d_ptr->dirty) { + _q_adjustRect(&item->d_ptr->needsRepaint); + dirtyRect &= item->d_ptr->needsRepaint; + } + + if (item->d_ptr->dirtyChildren && !item->d_ptr->children.isEmpty() + && !item->d_ptr->childrenClippedToShape()) { + QRectF childrenBounds = item->childrenBoundingRect(); + _q_adjustRect(&childrenBounds); + dirtyRect |= childrenBounds; + } + uninitializedDirtyRect = false; + } + + if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) + viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + + if (!item->d_ptr->hasBoundingRegionGranularity) + viewPrivate->updateRect(viewPrivate->mapToViewRect(item, dirtyRect)); + else + viewPrivate->updateRegion(viewPrivate->mapToViewRegion(item, dirtyRect)); + } + resetDirtyItem(item); } - dirtyItems.clear(); - dirtyItemResetPending = false; -} -/*! - \internal -*/ -void QGraphicsScenePrivate::resetDirtyItemsLater() -{ - Q_Q(QGraphicsScene); - if (dirtyItemResetPending) - return; - // dirtyItems.reserve(indexedItems.size() + unindexedItems.size()); - dirtyItemResetPending = true; - QMetaObject::invokeMethod(q, "_q_resetDirtyItems", Qt::QueuedConnection); + dirtyItems.clear(); + for (int i = 0; i < views.size(); ++i) + views.at(i)->d_func()->processPendingUpdates(); } /*! @@ -761,10 +810,9 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) // Update selected & hovered item bookkeeping selectedItems.remove(item); hoverItems.removeAll(item); - pendingUpdateItems.removeAll(item); cachedItemsUnderMouse.removeAll(item); unpolishedItems.removeAll(item); - dirtyItems.removeAll(item); + removeFromDirtyItems(item); //We remove all references of item from the sceneEventFilter arrays QMultiMap::iterator iterator = sceneEventFilters.begin(); @@ -3319,7 +3367,7 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) d->pendingUpdateItems.removeAll(item); d->cachedItemsUnderMouse.removeAll(item); d->unpolishedItems.removeAll(item); - d->dirtyItems.removeAll(item); + d->removeFromDirtyItems(item); //We remove all references of item from the sceneEventFilter arrays QMultiMap::iterator iterator = d->sceneEventFilters.begin(); @@ -3330,11 +3378,6 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) ++iterator; } - - //Ensure dirty flag have the correct default value so the next time it will be added it will receive updates - item->d_func()->dirty = 0; - item->d_func()->dirtyChildren = 0; - // Remove all children recursively foreach (QGraphicsItem *child, item->children()) removeItem(child); @@ -5050,7 +5093,9 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } QRectF brect = item->boundingRect(); _q_adjustRect(&brect); - viewBoundingRect = transform.mapRect(brect).toRect().adjusted(-1, -1, 1, 1) & exposedRegion.boundingRect(); + const QRect paintedViewBoundingRect = transform.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); + item->d_ptr->paintedViewBoundingRects.insert(widget, paintedViewBoundingRect); + viewBoundingRect = paintedViewBoundingRect & exposedRegion.boundingRect(); } else { transform = parentTransform; } @@ -5117,6 +5162,44 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * painter->restore(); } +void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, bool invalidateChildren, + bool maybeDirtyClipPath, bool force, bool ignoreOpacity) +{ + Q_ASSERT(item); + if (updateAll) + return; + + if (item->d_ptr->discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath, + /*ignoreVisibleBit=*/force, + /*ignoreDirtyBit=*/false, ignoreOpacity)) { + return; + } + + const bool fullItemUpdate = rect.isNull(); + if (!fullItemUpdate && rect.isEmpty()) + return; + + if (dirtyItems.isEmpty()) + QMetaObject::invokeMethod(q_ptr, "_q_processDirtyItems", Qt::QueuedConnection); + + if (item->d_ptr->inDirtyList) { + if (fullItemUpdate) + item->d_ptr->dirty = 1; + else if (!item->d_ptr->dirty) + item->d_ptr->needsRepaint |= rect; + } else { + dirtyItems.append(item); + item->d_ptr->inDirtyList = 1; + if (fullItemUpdate) + item->d_ptr->dirty = 1; + else if (!item->d_ptr->dirty) + item->d_ptr->needsRepaint = rect; + } + + if (invalidateChildren) + item->d_ptr->dirtyChildren = 1; +} + /*! Paints the given \a items using the provided \a painter, after the background has been drawn, and before the foreground has been @@ -5238,6 +5321,8 @@ void QGraphicsScene::drawItems(QPainter *painter, // Draw the item d->drawItemHelper(item, painter, &options[i], widget, d->painterStateProtection); + const QRect paintedViewBoundingRect = painter->worldTransform().mapRect(options[i].rect).adjusted(-1, -1, 1, 1); + item->d_ptr->paintedViewBoundingRects.insert(widget, paintedViewBoundingRect); if (saveState) painter->restore(); @@ -5364,73 +5449,6 @@ bool QGraphicsScene::focusNextPrevChild(bool next) */ /*! - \internal - - This private function is called by QGraphicsItem, which is a friend of - QGraphicsScene. It is used by QGraphicsScene to record the rectangles that - need updating. It also launches a single-shot timer to ensure that - updated() will be emitted later. - - The \a item parameter is the item that changed, and \a rect is the - area of the item that changed given in item coordinates. -*/ -void QGraphicsScene::itemUpdated(QGraphicsItem *item, const QRectF &rect) -{ - Q_D(QGraphicsScene); - // Deliver the actual update. - if (!d->updateAll) { - if (d->views.isEmpty() || ((d->connectedSignals & d->changedSignalMask) && !item->d_ptr->itemIsUntransformable() - && qFuzzyIsNull(item->boundingRegionGranularity()))) { - // This block of code is kept for compatibility. Since 4.5, by default - // QGraphicsView does not connect the signal and we use the below - // method of delivering updates. - update(item->sceneBoundingRect()); - } else { - // ### Remove _q_adjustedRects(). - QRectF boundingRect(adjustedItemBoundingRect(item)); - if (!rect.isNull()) { - QRectF adjustedRect(rect); - _q_adjustRect(&adjustedRect); - boundingRect &= adjustedRect; - } - - // Update each view directly. - for (int i = 0; i < d->views.size(); ++i) - d->views.at(i)->d_func()->itemUpdated(item, boundingRect); - } - } - if (item->d_ptr->dirty) { - d->dirtyItems << item; - d->resetDirtyItemsLater(); - } - - if (!item->isVisible()) - return; // Hiding an item won't effect the largestUntransformableItem/sceneRect. - - // Update d->largestUntransformableItem by mapping this item's bounding - // rect back to the topmost untransformable item's untransformed - // coordinate system (which sort of equals the 1:1 coordinate system of an - // untransformed view). - if (item->d_ptr->itemIsUntransformable()) { - QGraphicsItem *parent = item; - while (parent && (parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations)) - parent = parent->parentItem(); - d->largestUntransformableItem |= item->mapToItem(parent, item->boundingRect()).boundingRect(); - } - - // Only track the automatically growing scene rect if the scene has no - // defined scene rect. - if (!d->hasSceneRect) { - QRectF oldGrowingItemsBoundingRect = d->growingItemsBoundingRect; - QRectF adjustedItemSceneBoundingRect(item->sceneBoundingRect()); - _q_adjustRect(&adjustedItemSceneBoundingRect); - d->growingItemsBoundingRect |= adjustedItemSceneBoundingRect; - if (d->growingItemsBoundingRect != oldGrowingItemsBoundingRect) - emit sceneRectChanged(d->growingItemsBoundingRect); - } -} - -/*! \since 4.4 Returns the scene's style, or the same as QApplication::style() if the diff --git a/src/gui/graphicsview/qgraphicsscene.h b/src/gui/graphicsview/qgraphicsscene.h index 9802f87..4c0f2ec 100644 --- a/src/gui/graphicsview/qgraphicsscene.h +++ b/src/gui/graphicsview/qgraphicsscene.h @@ -271,8 +271,6 @@ Q_SIGNALS: void selectionChanged(); private: - void itemUpdated(QGraphicsItem *item, const QRectF &rect); - Q_DECLARE_PRIVATE(QGraphicsScene) Q_DISABLE_COPY(QGraphicsScene) Q_PRIVATE_SLOT(d_func(), void _q_updateIndex()) @@ -281,7 +279,7 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_updateLater()) Q_PRIVATE_SLOT(d_func(), void _q_polishItems()) Q_PRIVATE_SLOT(d_func(), void _q_updateSortCache()) - Q_PRIVATE_SLOT(d_func(), void _q_resetDirtyItems()) + Q_PRIVATE_SLOT(d_func(), void _q_processDirtyItems()) friend class QGraphicsItem; friend class QGraphicsItemPrivate; friend class QGraphicsView; diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index bb99908..f2226bf 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -111,7 +111,7 @@ public: QSet selectedItems; QList unindexedItems; QList indexedItems; - QList dirtyItems; + QVector dirtyItems; QList pendingUpdateItems; QList unpolishedItems; QList topLevelItems; @@ -121,9 +121,7 @@ public: void _q_updateLater(); void _q_polishItems(); - void _q_resetDirtyItems(); - void resetDirtyItemsLater(); - bool dirtyItemResetPending; + void _q_processDirtyItems(); QList freeItemIndexes; bool regenerateIndex; @@ -257,6 +255,30 @@ public: void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, const QTransform &viewTransform, const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags); + void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, + bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); + + inline void resetDirtyItem(QGraphicsItem *item) + { + Q_ASSERT(item); + item->d_ptr->dirty = 0; + item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0; + item->d_ptr->dirtyChildren = 0; + item->d_ptr->inDirtyList = 0; + item->d_ptr->needsRepaint = QRectF(); + } + + inline void removeFromDirtyItems(QGraphicsItem *item) + { + int i = 0; + while (i < dirtyItems.size()) { + if (dirtyItems.at(i) == item) + dirtyItems.remove(i); + else + ++i; + } + resetDirtyItem(item); + } QStyle *style; QFont font; diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 1994675..acf26e1 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -329,8 +329,6 @@ QGraphicsViewPrivate::QGraphicsViewPrivate() #endif lastDragDropEvent(0), fullUpdatePending(true), - dirtyRectCount(0), - updatingLater(false), updateSceneSlotReimplementedChecked(false) { styleOptions.reserve(QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS); @@ -804,125 +802,28 @@ static inline QRectF adjustedItemBoundingRect(const QGraphicsItem *item) return boundingRect; } -/*! - \internal -*/ -void QGraphicsViewPrivate::itemUpdated(QGraphicsItem *item, const QRectF &rect) +void QGraphicsViewPrivate::processPendingUpdates() { - if (fullUpdatePending || viewportUpdateMode == QGraphicsView::NoViewportUpdate) - return; - if (item->d_ptr->dirty) - updateLater(); - - QRectF updateRect = rect; - if ((item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape) || item->d_ptr->children.isEmpty()) { - updateRect &= adjustedItemBoundingRect(item); - if (updateRect.isEmpty()) - return; - } - - QGraphicsItem *clipItem = item; - if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) { - // Minimize unnecessary redraw. - QGraphicsItem *parent = item; - while ((parent = parent->d_ptr->parent)) { - if (parent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape) { - // Map update rect to the current parent and itersect with its bounding rect. - updateRect = clipItem->itemTransform(parent).mapRect(updateRect) - & adjustedItemBoundingRect(parent); - if (updateRect.isEmpty()) - return; - clipItem = parent; - } - - if (!(parent->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) - break; - } - } - - // Map update rect from clipItem coordinates to view coordinates. - Q_ASSERT(clipItem); - if (!item->d_ptr->hasBoundingRegionGranularity) - this->updateRect(mapToViewRect(clipItem, updateRect) & viewport->rect()); - else - updateRegion(mapToViewRegion(clipItem, updateRect) & viewport->rect()); -} - -void QGraphicsViewPrivate::updateLater() -{ - Q_Q(QGraphicsView); - if (updatingLater) - return; - updatingLater = true; - QMetaObject::invokeMethod(q, "_q_updateLaterSlot", Qt::QueuedConnection); -} - -void QGraphicsViewPrivate::_q_updateLaterSlot() -{ - Q_Q(QGraphicsView); if (!scene) return; - QRect vr = viewport->rect(); - QTransform viewTransform = q->viewportTransform(); - const QList &dirtyItems = scene->d_func()->dirtyItems; - for (int i = 0; i < dirtyItems.size(); ++i) { - const QGraphicsItem *item = dirtyItems.at(i); - if (item->d_ptr->discardUpdateRequest(/*ignoreClipping=*/false, - /*ignoreVisibleBit=*/false, - /*ignoreDirtyBit=*/true)) { - continue; - } - QTransform x = item->sceneTransform() * viewTransform; - updateRect(x.mapRect(item->boundingRect()).toAlignedRect() & vr); + if (fullUpdatePending) { // We have already called viewport->update() + dirtyBoundingRect = QRect(); + dirtyRegion = QRegion(); + return; } - dirtyRectCount += dirtyRects.size(); - - bool noUpdate = !fullUpdatePending && viewportUpdateMode == QGraphicsView::FullViewportUpdate; - if ((dirtyRectCount > 0 || !dirtyBoundingRect.isEmpty()) && !fullUpdatePending && !noUpdate) { - if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate - || (viewportUpdateMode == QGraphicsView::SmartViewportUpdate - && dirtyRectCount >= QGRAPHICSVIEW_REGION_RECT_THRESHOLD)) { - if (!(optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)) { - viewport->update(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); - } else { - viewport->update(dirtyBoundingRect); - } - } else { - // ### Improve this block, which is very slow for complex regions. We - // need to strike the balance between having an accurate update - // region, and running fast. The below approach is the simplest way to - // create a region from a bunch of rects, but we might want to use - // other approaches; e.g., a grid of a fixed size representing - // quadrants of the viewport, which we mark as dirty depending on the - // rectangles in the list. Perhaps this should go into a - // QRegion::fromRects(rects, how) function. - QRegion region; - if (!(optimizationFlags & QGraphicsView::DontAdjustForAntialiasing)) { - for (int i = 0; i < dirtyRegions.size(); ++i) { - QVector rects = dirtyRegions.at(i).rects(); - for (int j = 0; j < rects.size(); ++j) - region += rects.at(j).adjusted(-2, -2, 2, 2); - } - for (int i = 0; i < dirtyRects.size(); ++i) - region += dirtyRects.at(i).adjusted(-2, -2, 2, 2); - } else { - for (int i = 0; i < dirtyRegions.size(); ++i) - region += dirtyRegions.at(i); - for (int i = 0; i < dirtyRects.size(); ++i) - region += dirtyRects.at(i); - } - - viewport->update(region); - } + if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) { + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) + viewport->update(dirtyBoundingRect); + else + viewport->update(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); + } else { + viewport->update(dirtyRegion); // Already adjusted in updateRect/Region. } - dirtyRegions.clear(); - dirtyRects.clear(); - dirtyRectCount = 0; dirtyBoundingRect = QRect(); - updatingLater = false; + dirtyRegion = QRegion(); } void QGraphicsViewPrivate::updateAll() @@ -930,14 +831,13 @@ void QGraphicsViewPrivate::updateAll() Q_Q(QGraphicsView); q->viewport()->update(); fullUpdatePending = true; - dirtyRectCount = 0; dirtyBoundingRect = QRect(); - updatingLater = false; + dirtyRegion = QRegion(); } void QGraphicsViewPrivate::updateRegion(const QRegion &r) { - if (r.isEmpty()) + if (r.isEmpty() || fullUpdatePending) return; Q_Q(QGraphicsView); @@ -950,45 +850,30 @@ void QGraphicsViewPrivate::updateRegion(const QRegion &r) break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r.boundingRect(); - if (dirtyBoundingRect == q->viewport()->rect()) { + if (dirtyBoundingRect.contains(q->viewport()->rect())) { fullUpdatePending = true; q->viewport()->update(); - } else { - updateLater(); } break; - case QGraphicsView::SmartViewportUpdate: - dirtyBoundingRect |= r.boundingRect(); - if ((dirtyRectCount + r.numRects()) < QGRAPHICSVIEW_REGION_RECT_THRESHOLD) - dirtyRegions << r; - dirtyRectCount += r.numRects(); - updateLater(); - break; + case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE case QGraphicsView::MinimalViewportUpdate: - dirtyRegions << r; - dirtyRectCount += r.numRects(); - updateLater(); + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) { + dirtyRegion += r; + } else { + const QVector &rects = r.rects(); + for (int i = 0; i < rects.size(); ++i) + dirtyRegion += rects.at(i).adjusted(-2, -2, 2, 2); + } break; case QGraphicsView::NoViewportUpdate: // Unreachable break; } - - // Compress the regions... - if (dirtyRectCount > QGRAPHICSVIEW_REGION_RECT_THRESHOLD && dirtyRegions.size() > 1) { - QRegion masterRegion; - for (int i=0; iviewport()->rect()) { + if (dirtyBoundingRect.contains(q->viewport()->rect())) { fullUpdatePending = true; q->viewport()->update(); - } else { - updateLater(); } break; - case QGraphicsView::SmartViewportUpdate: - dirtyBoundingRect |= r; - if ((dirtyRectCount + dirtyRects.size()) < QGRAPHICSVIEW_REGION_RECT_THRESHOLD) - dirtyRects << r; - updateLater(); - break; + case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE case QGraphicsView::MinimalViewportUpdate: - dirtyRects << r; - updateLater(); + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) + dirtyRegion += r; + else + dirtyRegion += r.adjusted(-2, -2, 2, 2); break; case QGraphicsView::NoViewportUpdate: // Unreachable @@ -2613,9 +2493,10 @@ void QGraphicsView::updateScene(const QList &rects) // Extract and reset dirty scene rect info. QVector dirtyViewportRects; - for (int i = 0; i < d->dirtyRegions.size(); ++i) - dirtyViewportRects += d->dirtyRegions.at(i).rects(); - d->dirtyRegions.clear(); + const QVector &dirtyRects = d->dirtyRegion.rects(); + for (int i = 0; i < dirtyRects.size(); ++i) + dirtyViewportRects += dirtyRects.at(i); + d->dirtyRegion = QRegion(); bool fullUpdate = !d->accelerateScrolling || d->viewportUpdateMode == QGraphicsView::FullViewportUpdate; bool boundingRectUpdate = (d->viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) @@ -3544,10 +3425,7 @@ void QGraphicsView::scrollContentsBy(int dx, int dy) if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate) { if (d->viewportUpdateMode != QGraphicsView::FullViewportUpdate) { - for (int i = 0; i < d->dirtyRects.size(); ++i) - d->dirtyRects[i].translate(dx, dy); - for (int i = 0; i < d->dirtyRegions.size(); ++i) - d->dirtyRegions[i].translate(dx, dy); + d->dirtyRegion.translate(dx, dy); if (d->accelerateScrolling) { #ifndef QT_NO_RUBBERBAND // Update new and old rubberband regions diff --git a/src/gui/graphicsview/qgraphicsview.h b/src/gui/graphicsview/qgraphicsview.h index 7692e16..deed1d0 100644 --- a/src/gui/graphicsview/qgraphicsview.h +++ b/src/gui/graphicsview/qgraphicsview.h @@ -274,7 +274,6 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_setViewportCursor(const QCursor &)) Q_PRIVATE_SLOT(d_func(), void _q_unsetViewportCursor()) #endif - Q_PRIVATE_SLOT(d_func(), void _q_updateLaterSlot()) friend class QGraphicsSceneWidget; friend class QGraphicsScene; friend class QGraphicsScenePrivate; diff --git a/src/gui/graphicsview/qgraphicsview_p.h b/src/gui/graphicsview/qgraphicsview_p.h index c18f85d..637687b 100644 --- a/src/gui/graphicsview/qgraphicsview_p.h +++ b/src/gui/graphicsview/qgraphicsview_p.h @@ -159,15 +159,10 @@ public: QRect mapToViewRect(const QGraphicsItem *item, const QRectF &rect) const; QRegion mapToViewRegion(const QGraphicsItem *item, const QRectF &rect) const; - void itemUpdated(QGraphicsItem *item, const QRectF &rect); bool fullUpdatePending; - QList dirtyRects; - QList dirtyRegions; - int dirtyRectCount; + QRegion dirtyRegion; QRect dirtyBoundingRect; - void updateLater(); - bool updatingLater; - void _q_updateLaterSlot(); + void processPendingUpdates(); void updateAll(); void updateRect(const QRect &rect); void updateRegion(const QRegion ®ion); diff --git a/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp b/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp index 0c5ebf6..23d7a94 100644 --- a/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp +++ b/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp @@ -1317,8 +1317,9 @@ void tst_QGraphicsScene::removeItem() scene.removeItem(hoverItem); hoverItem->setAcceptsHoverEvents(false); scene.addItem(hoverItem); - qApp->processEvents(); // update - qApp->processEvents(); // draw + qApp->processEvents(); // <- delayed update is called + qApp->processEvents(); // <- scene schedules pending update + qApp->processEvents(); // <- pending update is sent to view QVERIFY(!hoverItem->isHovered); } -- cgit v0.12 From 8afef542ead463b6937ec907c0b35a7977ed4a83 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 10:13:12 +0200 Subject: simplify and cleanup handling of transformations in QGraphicsItem Removed some experimental code to handle scaling and rotating around different axis. It cuased setTransform and transform not to behave symmetrically and caused some performance regressions. Additionally moved the QTransform out of the (relatively slow) extra list and made it a pointer in QGraphicsItemPrivate. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 429 ++------------------------------- src/gui/graphicsview/qgraphicsitem.h | 37 +-- src/gui/graphicsview/qgraphicsitem_p.h | 12 +- src/gui/graphicsview/qgraphicswidget.h | 9 +- 4 files changed, 23 insertions(+), 464 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index ec6b35b..14658cf 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1102,6 +1102,9 @@ QGraphicsItem::~QGraphicsItem() if (d_ptr->scene) d_ptr->scene->d_func()->_q_removeItemLater(this); + if (d_ptr->transform) + delete d_ptr->transform; + delete d_ptr; qt_dataStore()->data.remove(this); @@ -2627,403 +2630,9 @@ QMatrix QGraphicsItem::matrix() const */ QTransform QGraphicsItem::transform() const { - if (!d_ptr->hasTransform) + if (!d_ptr->hasTransform || !d_ptr->transform) return QTransform(); - if (d_ptr->hasDecomposedTransform && d_ptr->dirtyTransform) { - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - QTransform x; - decomposed->generateTransform(&x); - QVariant v(x); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, v); - d_ptr->dirtyTransform = 0; - const_cast(this)->itemChange(ItemTransformHasChanged, v); - return x; - } - return qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform)); -} - -/*! - \since 4.6 - - Returns the rotation around the X axis. - - The default is 0 - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - - \sa setXRotation(), {Transformations} -*/ -qreal QGraphicsItem::xRotation() const -{ - return d_ptr->decomposedTransform()->xRotation; -} - -/*! - \since 4.6 - - Sets the rotation around the X axis to \a angle degrees. - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. - - \sa xRotation(), {Transformations} -*/ -void QGraphicsItem::setXRotation(qreal angle) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->xRotation = angle; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; -} - -/*! - \since 4.6 - - Returns the rotation around the Y axis. - - The default is 0 - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - - \sa setYRotation(), {Transformations} -*/ -qreal QGraphicsItem::yRotation() const -{ - return d_ptr->decomposedTransform()->yRotation; -} - -/*! - \since 4.6 - - Sets the rotation around the Y axis to \a angle degrees. - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. - - \sa yRotation(), {Transformations} -*/ -void QGraphicsItem::setYRotation(qreal angle) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->yRotation = angle; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; -} - -/*! - \since 4.6 - - Returns the rotation around the Z axis. - - The default is 0 - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - - \sa setZRotation(), {Transformations} -*/ -qreal QGraphicsItem::zRotation() const -{ - return d_ptr->decomposedTransform()->zRotation; -} - -/*! - \since 4.6 - - Sets the rotation around the Z axis to \a angle degrees. - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. - - \sa zRotation(), {Transformations} -*/ -void QGraphicsItem::setZRotation(qreal angle) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->zRotation = angle; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; -} - -/*! - \since 4.6 - - This convenience function set the rotation angles around the 3 axes - to \a x, \a y and \a z. - - \sa setXRotation(), setYRotation(), setZRotation() -*/ -void QGraphicsItem::setRotation(qreal x, qreal y, qreal z) -{ - setXRotation(x); - setYRotation(y); - setZRotation(z); -} - -/*! - \since 4.6 - - Returns the scale factor on the X axis. - - The default is 1 - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - - \sa setXScale(), {Transformations} -*/ -qreal QGraphicsItem::xScale() const -{ - return d_ptr->decomposedTransform()->xScale; -} - -/*! - \since 4.6 - - Sets the scale factor on the X axis to \a factor. - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. - - \sa xScale(), {Transformations} -*/ -void QGraphicsItem::setXScale(qreal factor) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->xScale = factor; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; -} - -/*! - \since 4.6 - - Returns the scale factor on the Y axis. - - The default is 1 - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - - \sa setYScale(), {Transformations} -*/ -qreal QGraphicsItem::yScale() const -{ - return d_ptr->decomposedTransform()->yScale; -} - -/*! - \since 4.6 - - Sets the scale factor on the Y axis to \a factor. - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. - - \sa yScale(), {Transformations} -*/ -void QGraphicsItem::setYScale(qreal factor) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->yScale = factor; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; -} - -/*! - \since 4.6 - - This convenience function set the scaling factors on X and Y axis to \a sx and \a sy. - - \sa setXScale(), setYScale() -*/ -void QGraphicsItem::setScale(qreal sx, qreal sy) -{ - setXScale(sx); - setYScale(sy); -} - -/*! - \since 4.6 - - Returns the horizontal shear. - - The default is 0 - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - - \sa setHorizontalShear(), {Transformations} -*/ -qreal QGraphicsItem::horizontalShear() const -{ - return d_ptr->decomposedTransform()->horizontalShear; -} - -/*! - \since 4.6 - - Sets the horizontal shear to \a shear. - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. - - \sa horizontalShear(), {Transformations} -*/ -void QGraphicsItem::setHorizontalShear(qreal shear) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->horizontalShear = shear; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; -} - -/*! - \since 4.6 - - Returns the vertical shear. - - The default is 0 - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - - \sa setHorizontalShear(), {Transformations} -*/ -qreal QGraphicsItem::verticalShear() const -{ - return d_ptr->decomposedTransform()->verticalShear; -} - -/*! - \since 4.6 - - Sets the vertical shear to \a shear. - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. - - \sa verticalShear(), {Transformations} -*/ -void QGraphicsItem::setVerticalShear(qreal shear) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->verticalShear = shear; - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; -} - -/*! - \since 4.6 - - This convenience function sets the horizontal shear to \a sh and the vertical shear to \a sv. - - \sa setHorizontalShear(), setVerticalShear() -*/ -void QGraphicsItem::setShear(qreal sh, qreal sv) -{ - setHorizontalShear(sh); - setVerticalShear(sv); -} - -/*! - \since 4.6 - - Returns the transformation origin for the transformation properties. - - The default is QPointF(0,0). - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, this function return the default value. - - \sa setTransformOrigin(), {Transformations} -*/ -QPointF QGraphicsItem::transformOrigin() const -{ - const QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - return QPointF(decomposed->xOrigin, decomposed->yOrigin); -} - -/*! - \fn inline void setTransformOrigin(qreal x, qreal y) - - \since 4.6 - - This is an overloaded member function, provided for convenience. - Sets the transformation origin for the transformation - properties to the point(\a x, \a y). - - \sa setTransformOrigin(), {Transformations} -*/ - -/*! - \since 4.6 - - Sets the transformation origin for the transformation properties to \a origin. - This does not apply to the transformation set by setTransform. - - \warning setting this property is conflicting with calling setTransform. - If a transform has been set, it will be overwritten. - - \sa transformOrigin(), {Transformations} -*/ -void QGraphicsItem::setTransformOrigin(const QPointF &origin) -{ - if (!d_ptr->dirtyTransform) { - d_ptr->fullUpdateHelper(true); - prepareGeometryChange(); - } - QGraphicsItemPrivate::DecomposedTransform *decomposed = d_ptr->decomposedTransform(); - decomposed->xOrigin = origin.x(); - decomposed->yOrigin = origin.y(); - if (!d_ptr->dirtyTransform) - d_ptr->invalidateSceneTransformCache(); - d_ptr->dirtyTransform = 1; - d_ptr->hasTransform = 1; + return *d_ptr->transform; } /*! @@ -3306,11 +2915,7 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) { QTransform oldTransform = this->transform(); - QTransform newTransform; - if (!combine) - newTransform = QTransform(matrix); - else - newTransform = QTransform(matrix) * oldTransform; + QTransform newTransform(combine ? QTransform(matrix) * oldTransform : QTransform(matrix)); if (oldTransform == newTransform) return; @@ -3324,9 +2929,10 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); d_ptr->hasTransform = !newTransform.isIdentity(); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); - d_ptr->dirtyTransformComponents = 1; - d_ptr->dirtyTransform = 0; + if(!d_ptr->transform) + d_ptr->transform = new QTransform(newTransform); + else + *d_ptr->transform = newTransform; d_ptr->invalidateSceneTransformCache(); // Send post-notification. @@ -3358,11 +2964,7 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) { QTransform oldTransform = this->transform(); - QTransform newTransform; - if (!combine) - newTransform = matrix; - else - newTransform = matrix * oldTransform; + QTransform newTransform(combine ? matrix * oldTransform : matrix); if (oldTransform == newTransform) return; @@ -3376,9 +2978,10 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); d_ptr->hasTransform = !newTransform.isIdentity(); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, newTransform); - d_ptr->dirtyTransformComponents = 1; - d_ptr->dirtyTransform = 0; + if(!d_ptr->transform) + d_ptr->transform = new QTransform(newTransform); + else + *d_ptr->transform = newTransform; d_ptr->invalidateSceneTransformCache(); // Send post-notification. @@ -6359,7 +5962,7 @@ void QGraphicsItem::prepareGeometryChange() } QGraphicsItem *parent = this; - while (parent = parent->d_ptr->parent) + while ((parent = parent->d_ptr->parent)) parent->d_ptr->dirtyChildrenBoundingRect = 1; if (d_ptr->inSetPosHelper) diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index f6ee197..def773e 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -242,39 +242,10 @@ public: void setTransform(const QTransform &matrix, bool combine = false); void resetTransform(); - void rotate(qreal angle); // ### obsolete - void scale(qreal sx, qreal sy); // ### obsolete - void shear(qreal sh, qreal sv); // ### obsolete - void translate(qreal dx, qreal dy); // ### obsolete - - qreal xRotation() const; - void setXRotation(qreal angle); - - qreal yRotation() const; - void setYRotation(qreal angle); - - qreal zRotation() const; - void setZRotation(qreal angle); - void setRotation(qreal x, qreal y, qreal z); - - qreal xScale() const; - void setXScale(qreal factor); - - qreal yScale() const; - void setYScale(qreal factor); - void setScale(qreal sx, qreal sy); - - qreal horizontalShear() const; - void setHorizontalShear(qreal shear); - - qreal verticalShear() const; - void setVerticalShear(qreal shear); - void setShear(qreal sh, qreal sv); - - QPointF transformOrigin() const; - void setTransformOrigin(const QPointF &origin); - inline void setTransformOrigin(qreal x, qreal y) - { setTransformOrigin(QPointF(x,y)); } + void rotate(qreal angle); + void scale(qreal sx, qreal sy); + void shear(qreal sh, qreal sv); + void translate(qreal dx, qreal dy); virtual void advance(int phase); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 1d4b37a..5c7e67c 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -95,17 +95,7 @@ class Q_AUTOTEST_EXPORT QGraphicsItemPrivate { Q_DECLARE_PUBLIC(QGraphicsItem) public: - struct TransformData - { - TransformData() : rotationX(0),rotationY(0),rotationZ(0),scaleX(1),scaleY(1), dirty(true) {} - QTransform baseTransform; - QTransform transform; - QPointF transformCenter; - qreal rotationX,rotationY,rotationZ,scaleX,scaleY; - bool dirty; - }; enum Extra { - ExtraTransform, ExtraToolTip, ExtraCursor, ExtraCacheData, @@ -127,6 +117,7 @@ public: : z(0), scene(0), parent(0), + transform(0), siblingIndex(-1), index(-1), depth(0), @@ -329,6 +320,7 @@ public: QGraphicsScene *scene; QGraphicsItem *parent; QList children; + QTransform *transform; int siblingIndex; int index; int depth; diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h index a5c9068..34f1c5f 100644 --- a/src/gui/graphicsview/qgraphicswidget.h +++ b/src/gui/graphicsview/qgraphicswidget.h @@ -81,14 +81,7 @@ class Q_GUI_EXPORT QGraphicsWidget : public QObject, public QGraphicsItem, publi Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity) Q_PROPERTY(QPointF pos READ pos WRITE setPos) Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry) - Q_PROPERTY(QPointF transformOrigin READ transformOrigin WRITE setTransformOrigin) - Q_PROPERTY(qreal xRotation READ xRotation WRITE setXRotation) - Q_PROPERTY(qreal yRotation READ yRotation WRITE setYRotation) - Q_PROPERTY(qreal zRotation READ zRotation WRITE setZRotation) - Q_PROPERTY(qreal xScale READ xScale WRITE setXScale) - Q_PROPERTY(qreal yScale READ yScale WRITE setYScale) - Q_PROPERTY(qreal horizontalShear READ horizontalShear WRITE setHorizontalShear) - Q_PROPERTY(qreal verticalShear READ verticalShear WRITE setVerticalShear) + public: QGraphicsWidget(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); ~QGraphicsWidget(); -- cgit v0.12 From 5ea28946b53b001a6fcbc1c382f80f798ac6ab4b Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 28 May 2009 11:31:24 +0200 Subject: Remove scene transform cache from QGraphicsItem. Now that we have a recursive painting algorithm these types of optimizations are no longer necessary. In fact they only cause more problems and clutter up the code unnecessarily. Removing this also removes extra overhead from moving and transforming items. Reviewed-by: Lars --- src/gui/graphicsview/qgraphicsitem.cpp | 64 +++++---------------------------- src/gui/graphicsview/qgraphicsitem_p.h | 3 -- src/gui/graphicsview/qgraphicsscene.cpp | 17 ++------- src/gui/graphicsview/qgraphicsscene_p.h | 4 --- 4 files changed, 10 insertions(+), 78 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 14658cf..c1848e0 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -918,9 +918,6 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de // Resolve depth. resolveDepth(parent ? parent->d_ptr->depth : -1); - // Invalidate transform cache. - invalidateSceneTransformCache(); - // Deliver post-change notification q->itemChange(QGraphicsItem::ItemParentHasChanged, newParentVariant); } @@ -2526,7 +2523,6 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) if (scene) q->prepareGeometryChange(); this->pos = newPos; - invalidateSceneTransformCache(); // Send post-notification. q->itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); @@ -2667,44 +2663,15 @@ QMatrix QGraphicsItem::sceneMatrix() const */ QTransform QGraphicsItem::sceneTransform() const { - // Check if there's any entry in the transform cache. - QGraphicsScenePrivate *sd = d_ptr->scene ? d_ptr->scene->d_func() : 0; - int index = d_ptr->sceneTransformIndex; - if (sd && index != -1 && sd->validTransforms.testBit(index)) - return sd->sceneTransformCache[index]; - - // Calculate local transform. QTransform m; - if (d_ptr->hasTransform) { - m = transform(); - if (!d_ptr->pos.isNull()) - m *= QTransform::fromTranslate(d_ptr->pos.x(), d_ptr->pos.y()); - } else if (!d_ptr->pos.isNull()) { - m = QTransform::fromTranslate(d_ptr->pos.x(), d_ptr->pos.y()); - } - - // Combine with parent and add to cache. - if (d_ptr->parent) { - m *= d_ptr->parent->sceneTransform(); - // Don't cache toplevels - if (sd) { - if (index == -1) { - if (!sd->freeSceneTransformSlots.isEmpty()) { - index = sd->freeSceneTransformSlots.last(); - sd->freeSceneTransformSlots.pop_back(); - } else { - index = sd->sceneTransformCache.size(); - } - d_ptr->sceneTransformIndex = index; - if (index >= sd->validTransforms.size()) { - sd->validTransforms.resize(index + 1); - sd->sceneTransformCache.resize(index + 1); - } - } - sd->validTransforms.setBit(index, 1); - sd->sceneTransformCache[index] = m; - } - } + const QGraphicsItem *p = this; + do { + if (p->d_ptr->hasTransform) + m *= p->transform(); + const QPointF &pos = p->d_ptr->pos; + if (!pos.isNull()) + m *= QTransform::fromTranslate(pos.x(), pos.y()); + } while ((p = p->d_ptr->parent)); return m; } @@ -2933,7 +2900,6 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) d_ptr->transform = new QTransform(newTransform); else *d_ptr->transform = newTransform; - d_ptr->invalidateSceneTransformCache(); // Send post-notification. // NB! We have to change the value from QMatrix to QTransform. @@ -2982,7 +2948,6 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) d_ptr->transform = new QTransform(newTransform); else *d_ptr->transform = newTransform; - d_ptr->invalidateSceneTransformCache(); // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -3912,19 +3877,6 @@ void QGraphicsItemPrivate::resolveDepth(int parentDepth) /*! \internal */ -void QGraphicsItemPrivate::invalidateSceneTransformCache() -{ - if (!scene || (parent && sceneTransformIndex == -1)) - return; - if (sceneTransformIndex != -1) - scene->d_func()->validTransforms.setBit(sceneTransformIndex, 0); - for (int i = 0; i < children.size(); ++i) - children.at(i)->d_ptr->invalidateSceneTransformCache(); -} - -/*! - \internal -*/ void QGraphicsItemPrivate::addChild(QGraphicsItem *child) { child->d_ptr->siblingIndex = children.size(); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 5c7e67c..5a6401a 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -155,7 +155,6 @@ public: inDirtyList(0), paintedViewBoundingRectsNeedRepaint(0), globalStackingOrder(-1), - sceneTransformIndex(-1), q_ptr(0) { } @@ -182,7 +181,6 @@ public: void updateEffectiveOpacity(); void resolveEffectiveOpacity(qreal effectiveParentOpacity); void resolveDepth(int parentDepth); - void invalidateSceneTransformCache(); void addChild(QGraphicsItem *child); void removeChild(QGraphicsItem *child); void setParentItemHelper(QGraphicsItem *parent, bool deleting); @@ -365,7 +363,6 @@ public: // Optional stacking order int globalStackingOrder; - int sceneTransformIndex; struct DecomposedTransform; DecomposedTransform *decomposedTransform() const diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index d004ed2..86e7cdb 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -823,13 +823,6 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) ++iterator; } - // Remove from scene transform cache - int transformIndex = item->d_func()->sceneTransformIndex; - if (transformIndex != -1) { - validTransforms.setBit(transformIndex, 0); - freeSceneTransformSlots.append(transformIndex); - } - // Reset the mouse grabber if (mouseGrabberItems.contains(item)) ungrabMouse(item, /* item is dying */ true); @@ -3340,14 +3333,6 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) d->unindexedItems.removeAll(item); } - // Remove from scene transform cache - int transformIndex = item->d_func()->sceneTransformIndex; - if (transformIndex != -1) { - d->validTransforms.setBit(transformIndex, 0); - d->freeSceneTransformSlots.append(transformIndex); - item->d_func()->sceneTransformIndex = -1; - } - if (item == d->focusItem) d->focusItem = 0; if (item == d->lastFocusItem) @@ -3817,6 +3802,8 @@ bool QGraphicsScene::event(QEvent *event) // items from inside event handlers, this list can quickly end up // having stale pointers in it. We need to clear it before dispatching // events that use it. + // ### this should only be cleared if we received a new mouse move event, + // which relies on us fixing the replay mechanism in QGraphicsView. d->cachedItemsUnderMouse.clear(); default: break; diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index f2226bf..bf7ac0a 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -289,10 +289,6 @@ public: void setPalette_helper(const QPalette &palette); void resolvePalette(); void updatePalette(const QPalette &palette); - - mutable QVector sceneTransformCache; - mutable QBitArray validTransforms; - mutable QVector freeSceneTransformSlots; }; QT_END_NAMESPACE -- cgit v0.12 From f233dafed58b6429d693ae0248f596a0377cd547 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 12:25:21 +0200 Subject: get rid of the hasTransform flag in QGraphicsItem Since the transform is now a pointer in QGraphicsItemPrivate, we can use this pointer directly and there's no need for a separate bitflag anymore. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 81 ++++++++++++++++----------------- src/gui/graphicsview/qgraphicsitem_p.h | 3 +- src/gui/graphicsview/qgraphicsscene.cpp | 16 +++---- src/gui/graphicsview/qgraphicsview.cpp | 2 +- 4 files changed, 48 insertions(+), 54 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index c1848e0..26da858 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -937,12 +937,11 @@ void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rec for (int i = 0; i < children.size(); ++i) { QGraphicsItem *child = children.at(i); QGraphicsItemPrivate *childd = child->d_ptr; - bool hasX = childd->hasTransform; bool hasPos = !childd->pos.isNull(); - if (hasPos || hasX) { + if (hasPos || childd->transform) { QTransform matrix; - if (hasX) - matrix = child->transform(); + if (childd->transform) + matrix = *childd->transform; if (hasPos) { const QPointF &p = childd->pos; matrix *= QTransform::fromTranslate(p.x(), p.y()); @@ -2626,7 +2625,7 @@ QMatrix QGraphicsItem::matrix() const */ QTransform QGraphicsItem::transform() const { - if (!d_ptr->hasTransform || !d_ptr->transform) + if (!d_ptr->transform) return QTransform(); return *d_ptr->transform; } @@ -2666,8 +2665,8 @@ QTransform QGraphicsItem::sceneTransform() const QTransform m; const QGraphicsItem *p = this; do { - if (p->d_ptr->hasTransform) - m *= p->transform(); + if (p->d_ptr->transform) + m *= *p->d_ptr->transform; const QPointF &pos = p->d_ptr->pos; if (!pos.isNull()) m *= QTransform::fromTranslate(pos.x(), pos.y()); @@ -2777,17 +2776,17 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co *ok = true; const QPointF &itemPos = d_ptr->pos; if (itemPos.isNull()) - return d_ptr->hasTransform ? transform() : QTransform(); - if (d_ptr->hasTransform) - return transform() * QTransform::fromTranslate(itemPos.x(), itemPos.y()); + return d_ptr->transform ? *d_ptr->transform : QTransform(); + if (d_ptr->transform) + return *d_ptr->transform * QTransform::fromTranslate(itemPos.x(), itemPos.y()); return QTransform::fromTranslate(itemPos.x(), itemPos.y()); } // This is other's parent if (otherParent == this) { const QPointF &otherPos = other->d_ptr->pos; - if (other->d_ptr->hasTransform) { - QTransform otherToParent = other->transform(); + if (other->d_ptr->transform) { + QTransform otherToParent = *other->d_ptr->transform; if (!otherPos.isNull()) otherToParent *= QTransform::fromTranslate(otherPos.x(), otherPos.y()); return otherToParent.inverted(ok); @@ -2800,12 +2799,10 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co // Siblings if (parent == otherParent) { - bool hasTr = d_ptr->hasTransform; - bool otherHasTr = other->d_ptr->hasTransform; const QPointF &itemPos = d_ptr->pos; const QPointF &otherPos = other->d_ptr->pos; - if (!hasTr && !otherHasTr) { + if (!d_ptr->transform && !other->d_ptr->transform) { QPointF delta = itemPos - otherPos; if (ok) *ok = true; @@ -2813,12 +2810,12 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co } QTransform itemToParent = QTransform::fromTranslate(itemPos.x(), itemPos.y()); - if (hasTr) - itemToParent = itemPos.isNull() ? transform() : transform() * itemToParent; + if (d_ptr->transform) + itemToParent = itemPos.isNull() ? *d_ptr->transform : *d_ptr->transform * itemToParent; QTransform otherToParent = QTransform::fromTranslate(otherPos.x(), otherPos.y()); - if (otherHasTr) - otherToParent = otherPos.isNull() ? other->transform() : other->transform() * otherToParent; + if (other->d_ptr->transform) + otherToParent = otherPos.isNull() ? *other->d_ptr->transform : *other->d_ptr->transform * otherToParent; return itemToParent * otherToParent.inverted(ok); } @@ -2856,8 +2853,8 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co const QGraphicsItem *p = child; do { const QGraphicsItemPrivate *pd = p->d_ptr; - if (pd->hasTransform) - x *= p->transform(); + if (pd->transform) + x *= *pd->transform; if (!pd->pos.isNull()) x *= QTransform::fromTranslate(pd->pos.x(), pd->pos.y()); } while ((p = p->d_ptr->parent) && p != root); @@ -2895,7 +2892,6 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); - d_ptr->hasTransform = !newTransform.isIdentity(); if(!d_ptr->transform) d_ptr->transform = new QTransform(newTransform); else @@ -2943,7 +2939,6 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); - d_ptr->hasTransform = !newTransform.isIdentity(); if(!d_ptr->transform) d_ptr->transform = new QTransform(newTransform); else @@ -3214,7 +3209,7 @@ QRectF QGraphicsItem::sceneBoundingRect() const const QGraphicsItemPrivate *itemd; do { itemd = parentItem->d_ptr; - if (itemd->hasTransform) + if (itemd->transform) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); @@ -3984,13 +3979,13 @@ void QGraphicsItemPrivate::updateCachedClipPathFromSetPosHelper(const QPointF &n // Find closest clip ancestor and transform. Q_Q(QGraphicsItem); - QTransform thisToParentTransform = hasTransform - ? q->transform() * QTransform::fromTranslate(newPos.x(), newPos.y()) + QTransform thisToParentTransform = transform + ? *transform * QTransform::fromTranslate(newPos.x(), newPos.y()) : QTransform::fromTranslate(newPos.x(), newPos.y()); QGraphicsItem *clipParent = parent; while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)) { - if (clipParent->d_ptr->hasTransform) - thisToParentTransform *= clipParent->transform(); + if (clipParent->d_ptr->transform) + thisToParentTransform *= *clipParent->d_ptr->transform; if (!clipParent->d_ptr->pos.isNull()) { thisToParentTransform *= QTransform::fromTranslate(clipParent->d_ptr->pos.x(), clipParent->d_ptr->pos.y()); @@ -4357,9 +4352,9 @@ QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPointF &point */ QPointF QGraphicsItem::mapToParent(const QPointF &point) const { - if (!d_ptr->hasTransform) + if (!d_ptr->transform) return point + d_ptr->pos; - return transform().map(point) + d_ptr->pos; + return d_ptr->transform->map(point) + d_ptr->pos; } /*! @@ -4424,9 +4419,9 @@ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QRectF &rect */ QPolygonF QGraphicsItem::mapToParent(const QRectF &rect) const { - if (!d_ptr->hasTransform) + if (!d_ptr->transform) return rect.translated(d_ptr->pos); - return transform().map(rect).translated(d_ptr->pos); + return d_ptr->transform->map(rect).translated(d_ptr->pos); } /*! @@ -4493,7 +4488,7 @@ QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, const QRectF &rec */ QRectF QGraphicsItem::mapRectToParent(const QRectF &rect) const { - QRectF r = !d_ptr->hasTransform ? rect : transform().mapRect(rect); + QRectF r = !d_ptr->transform ? rect : d_ptr->transform->mapRect(rect); return r.translated(d_ptr->pos); } @@ -4566,7 +4561,7 @@ QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, const QRectF &r QRectF QGraphicsItem::mapRectFromParent(const QRectF &rect) const { QRectF r = rect.translated(-d_ptr->pos); - return d_ptr->hasTransform ? transform().inverted().mapRect(r) : r; + return d_ptr->transform ? d_ptr->transform->inverted().mapRect(r) : r; } /*! @@ -4625,9 +4620,9 @@ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPolygonF &p */ QPolygonF QGraphicsItem::mapToParent(const QPolygonF &polygon) const { - if (!d_ptr->hasTransform) + if (!d_ptr->transform) return polygon.translated(d_ptr->pos); - return transform().map(polygon).translated(d_ptr->pos); + return d_ptr->transform->map(polygon).translated(d_ptr->pos); } /*! @@ -4669,9 +4664,9 @@ QPainterPath QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPainterP */ QPainterPath QGraphicsItem::mapToParent(const QPainterPath &path) const { - if (!d_ptr->hasTransform) + if (!d_ptr->transform) return path.translated(d_ptr->pos); - return transform().map(path).translated(d_ptr->pos); + return d_ptr->transform->map(path).translated(d_ptr->pos); } /*! @@ -4720,8 +4715,8 @@ QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPointF &poi */ QPointF QGraphicsItem::mapFromParent(const QPointF &point) const { - if (d_ptr->hasTransform) - return transform().inverted().map(point - d_ptr->pos); + if (d_ptr->transform) + return d_ptr->transform->inverted().map(point - d_ptr->pos); return point - d_ptr->pos; } @@ -4789,7 +4784,7 @@ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QRectF &re QPolygonF QGraphicsItem::mapFromParent(const QRectF &rect) const { QRectF r = rect.translated(-d_ptr->pos); - return d_ptr->hasTransform ? transform().inverted().map(r) : r; + return d_ptr->transform ? d_ptr->transform->inverted().map(r) : r; } /*! @@ -4846,7 +4841,7 @@ QPolygonF QGraphicsItem::mapFromParent(const QPolygonF &polygon) const { QPolygonF p = polygon; p.translate(-d_ptr->pos); - return d_ptr->hasTransform ? transform().inverted().map(p) : p; + return d_ptr->transform ? d_ptr->transform->inverted().map(p) : p; } /*! @@ -4888,7 +4883,7 @@ QPainterPath QGraphicsItem::mapFromParent(const QPainterPath &path) const { QPainterPath p(path); p.translate(-d_ptr->pos); - return d_ptr->hasTransform ? transform().inverted().map(p) : p; + return d_ptr->transform ? d_ptr->transform->inverted().map(p) : p; } /*! diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 5a6401a..35305b4 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -132,7 +132,6 @@ public: isMemberOfGroup(0), handlesChildEvents(0), itemDiscovered(0), - hasTransform(0), hasCursor(0), ancestorFlags(0), cacheMode(0), @@ -335,7 +334,6 @@ public: quint32 isMemberOfGroup : 1; quint32 handlesChildEvents : 1; quint32 itemDiscovered : 1; - quint32 hasTransform : 1; quint32 hasCursor : 1; quint32 ancestorFlags : 3; quint32 cacheMode : 2; @@ -349,6 +347,7 @@ public: quint32 dirtyClipPath : 1; quint32 emptyClipPath : 1; quint32 inSetPosHelper : 1; + quint32 unused : 1; // New 32 bits quint32 flags : 10; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 86e7cdb..b105c9c 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -1679,7 +1679,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, QList &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->hasTransform && !item->transform().isInvertible()) + if (item->d_ptr->transform && !item->d_ptr->transform->isInvertible()) continue; // Skip invisible items and all their children. @@ -1719,7 +1719,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, QList &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->hasTransform && !item->transform().isInvertible()) + if (item->d_ptr->transform && !item->d_ptr->transform->isInvertible()) continue; // Skip invisible items and all their children. @@ -1755,7 +1755,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) { // Recurse into children. - if (!item->d_ptr->hasTransform || item->transform().type() <= QTransform::TxScale) { + if (!item->d_ptr->transform || item->d_ptr->transform->type() <= QTransform::TxScale) { // Rect childItems_helper(items, item, item->mapRectFromParent(rect), mode); } else { @@ -1785,7 +1785,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, QList &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->hasTransform && !item->transform().isInvertible()) + if (item->d_ptr->transform && !item->d_ptr->transform->isInvertible()) continue; // Skip invisible items. @@ -1844,7 +1844,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, QList &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->hasTransform && !item->transform().isInvertible()) + if (item->d_ptr->transform && !item->d_ptr->transform->isInvertible()) continue; // Skip invisible items. @@ -5065,9 +5065,9 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } else { const QPointF &pos = item->d_ptr->pos; bool posNull = pos.isNull(); - if (!posNull || item->d_ptr->hasTransform) { - if (item->d_ptr->hasTransform) { - QTransform x = item->transform(); + if (!posNull || item->d_ptr->transform) { + if (item->d_ptr->transform) { + QTransform x = *item->d_ptr->transform; if (!posNull) x *= QTransform::fromTranslate(pos.x(), pos.y()); transform = x * parentTransform; diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index acf26e1..68c0e39 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -753,7 +753,7 @@ QRect QGraphicsViewPrivate::mapToViewRect(const QGraphicsItem *item, const QRect const QGraphicsItemPrivate *itemd; do { itemd = parentItem->d_ptr; - if (itemd->hasTransform) + if (itemd->transform) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); -- cgit v0.12 From 7c164da956c3b55b6b38df1c9e13dcd821b5062f Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 15:31:46 +0200 Subject: simplify opacity handling in QGraphicsItem Greatly simplify how we handle opacity and store it as a member in QGraphicsItemPrivate. Remove the caching of effectiveOpacity. It's faster to calculate it on the fly, and the recursive painting algorithm will make even that need go away. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 114 +++++---------------------------- src/gui/graphicsview/qgraphicsitem_p.h | 28 ++++---- 2 files changed, 31 insertions(+), 111 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 26da858..3f6b83c 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -912,9 +912,6 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de scene->d_func()->invalidateSortCache(); } - // Resolve opacity. - updateEffectiveOpacity(); - // Resolve depth. resolveDepth(parent ? parent->d_ptr->depth : -1); @@ -1372,11 +1369,6 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) // Update flags. d_ptr->flags = flags; - // Reresolve effective opacity if the opacity flags change. - static const quint32 opacityFlagsMask = ItemIgnoresParentOpacity | ItemDoesntPropagateOpacityToChildren; - if ((flags & opacityFlagsMask) != (oldFlags & opacityFlagsMask)) - d_ptr->updateEffectiveOpacity(); - if (!(d_ptr->flags & ItemIsFocusable) && hasFocus()) { // Clear focus on the item if it has focus when the focusable flag // is unset. @@ -1981,12 +1973,7 @@ void QGraphicsItem::setSelected(bool selected) */ qreal QGraphicsItem::opacity() const { - if (d_ptr->hasOpacity) { - QVariant o = d_ptr->extra(QGraphicsItemPrivate::ExtraOpacity); - if (!o.isNull()) - return o.toDouble(); - } - return qreal(1.0); + return d_ptr->opacity; } /*! @@ -2002,11 +1989,20 @@ qreal QGraphicsItem::opacity() const */ qreal QGraphicsItem::effectiveOpacity() const { - if (!d_ptr->hasEffectiveOpacity) - return qreal(1.0); + if (!d_ptr->parent) + return d_ptr->opacity; + + QGraphicsItem::GraphicsItemFlags myFlags = flags(); + QGraphicsItem::GraphicsItemFlags parentFlags = d_ptr->parent ? d_ptr->parent->flags() : QGraphicsItem::GraphicsItemFlags(0); + + // If I have a parent, and I don't ignore my parent's opacity, and my + // parent propagates to me, then combine my local opacity with my parent's + // effective opacity into my effective opacity. + if (!(myFlags & QGraphicsItem::ItemIgnoresParentOpacity) + && !(parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) + return d_ptr->opacity * d_ptr->parent->effectiveOpacity(); - QVariant effectiveOpacity = d_ptr->extra(QGraphicsItemPrivate::ExtraEffectiveOpacity); - return effectiveOpacity.isNull() ? qreal(1.0) : qreal(effectiveOpacity.toDouble()); + return d_ptr->opacity; } /*! @@ -2041,24 +2037,10 @@ void QGraphicsItem::setOpacity(qreal opacity) newOpacity = qBound(0.0, newOpacity, 1.0); // No change? Done. - if (qFuzzyIsNull(newOpacity - this->opacity())) + if (newOpacity == d_ptr->opacity) return; - // Assign local opacity. - if (qFuzzyIsNull(newOpacity - 1)) { - // Opaque, unset opacity. - d_ptr->hasOpacity = 0; - d_ptr->unsetExtra(QGraphicsItemPrivate::ExtraOpacity); - } else { - d_ptr->hasOpacity = 1; - d_ptr->setExtra(QGraphicsItemPrivate::ExtraOpacity, double(newOpacity)); - } - - // Resolve effective opacity. - if (QGraphicsItem *p = d_ptr->parent) - d_ptr->resolveEffectiveOpacity(p->effectiveOpacity()); - else - d_ptr->resolveEffectiveOpacity(1.0); + d_ptr->opacity = newOpacity; // Notify change. itemChange(ItemOpacityHasChanged, newOpacity); @@ -3793,70 +3775,6 @@ bool QGraphicsItemPrivate::discardUpdateRequest(bool ignoreClipping, bool ignore || (!ignoreOpacity && childrenCombineOpacity() && isFullyTransparent()); } -static inline bool allChildrenCombineOpacityHelper(QGraphicsItem *parent) -{ - Q_ASSERT(parent); - if (parent->flags() & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) - return false; - - const QList children(parent->childItems()); - for (int i = 0; i < children.size(); ++i) { - if (children.at(i)->flags() & QGraphicsItem::ItemIgnoresParentOpacity) - return false; - } - return true; -} - -void QGraphicsItemPrivate::updateEffectiveOpacity() -{ - Q_Q(QGraphicsItem); - if (parent) { - resolveEffectiveOpacity(parent->effectiveOpacity()); - parent->d_ptr->allChildrenCombineOpacity = allChildrenCombineOpacityHelper(parent); - } else { - resolveEffectiveOpacity(1.0); - } - allChildrenCombineOpacity = allChildrenCombineOpacityHelper(q); -} - -/*! - \internal - - Resolves and propagates this item's effective opacity to its children. -*/ -void QGraphicsItemPrivate::resolveEffectiveOpacity(qreal parentEffectiveOpacity) -{ - Q_Q(QGraphicsItem); - QGraphicsItem::GraphicsItemFlags myFlags = q->flags(); - QGraphicsItem::GraphicsItemFlags parentFlags = parent ? parent->flags() : QGraphicsItem::GraphicsItemFlags(0); - - // My local opacity is always part of my effective opacity. - qreal myEffectiveOpacity = q->opacity(); - - // If I have a parent, and I don't ignore my parent's opacity, and my - // parent propagates to me, then combine my local opacity with my parent's - // effective opacity into my effective opacity. - if (parent - && !(myFlags & QGraphicsItem::ItemIgnoresParentOpacity) - && !(parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) { - myEffectiveOpacity *= parentEffectiveOpacity; - } - - // Set this item's resolved opacity. - if (qFuzzyIsNull(myEffectiveOpacity - 1)) { - // Opaque, unset effective opacity. - hasEffectiveOpacity = 0; - unsetExtra(ExtraEffectiveOpacity); - } else { - hasEffectiveOpacity = 1; - setExtra(ExtraEffectiveOpacity, myEffectiveOpacity); - } - - // Resolve children always. - for (int i = 0; i < children.size(); ++i) - children.at(i)->d_ptr->resolveEffectiveOpacity(myEffectiveOpacity); -} - /*! \internal diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 35305b4..c999378 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -100,10 +100,7 @@ public: ExtraCursor, ExtraCacheData, ExtraMaxDeviceCoordCacheSize, - ExtraBoundingRegionGranularity, - ExtraOpacity, - ExtraEffectiveOpacity, - ExtraDecomposedTransform + ExtraBoundingRegionGranularity }; enum AncestorFlag { @@ -115,6 +112,7 @@ public: inline QGraphicsItemPrivate() : z(0), + opacity(1.), scene(0), parent(0), transform(0), @@ -136,8 +134,6 @@ public: ancestorFlags(0), cacheMode(0), hasBoundingRegionGranularity(0), - hasOpacity(0), - hasEffectiveOpacity(0), isWidget(0), dirty(0), dirtyChildren(0), @@ -177,8 +173,6 @@ public: void setEnabledHelper(bool newEnabled, bool explicitly, bool update = true); bool discardUpdateRequest(bool ignoreClipping = false, bool ignoreVisibleBit = false, bool ignoreDirtyBit = false, bool ignoreOpacity = false) const; - void updateEffectiveOpacity(); - void resolveEffectiveOpacity(qreal effectiveParentOpacity); void resolveDepth(int parentDepth); void addChild(QGraphicsItem *child); void removeChild(QGraphicsItem *child); @@ -278,10 +272,19 @@ public: void updateCachedClipPathFromSetPosHelper(const QPointF &newPos); inline bool isFullyTransparent() const - { return hasEffectiveOpacity && qFuzzyIsNull(q_func()->effectiveOpacity()); } + { return q_func()->effectiveOpacity() < .001; } inline bool childrenCombineOpacity() const - { return allChildrenCombineOpacity || children.isEmpty(); } + { + if (!children.size() || flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) + return false; + + for (int i = 0; i < children.size(); ++i) { + if (children.at(i)->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity) + return false; + } + return true; + } inline bool isClippedAway() const { return !dirtyClipPath && q_func()->isClipped() && (emptyClipPath || cachedClipPath.isEmpty()); } @@ -314,6 +317,7 @@ public: QMap paintedViewBoundingRects; QPointF pos; qreal z; + qreal opacity; QGraphicsScene *scene; QGraphicsItem *parent; QList children; @@ -338,8 +342,6 @@ public: quint32 ancestorFlags : 3; quint32 cacheMode : 2; quint32 hasBoundingRegionGranularity : 1; - quint32 hasOpacity : 1; - quint32 hasEffectiveOpacity : 1; quint32 isWidget : 1; quint32 dirty : 1; quint32 dirtyChildren : 1; @@ -347,7 +349,7 @@ public: quint32 dirtyClipPath : 1; quint32 emptyClipPath : 1; quint32 inSetPosHelper : 1; - quint32 unused : 1; + quint32 unused : 3; // New 32 bits quint32 flags : 10; -- cgit v0.12 From ce5b4c468d98bb4ec64429fa362554b9b3614496 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 16:08:25 +0200 Subject: smaller optimisation in setTransform --- src/gui/graphicsview/qgraphicsitem.cpp | 40 +++++++++++++++------------------- 1 file changed, 18 insertions(+), 22 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 3f6b83c..486e0b5 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -2860,28 +2860,25 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co */ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) { - QTransform oldTransform = this->transform(); - QTransform newTransform(combine ? QTransform(matrix) * oldTransform : QTransform(matrix)); - if (oldTransform == newTransform) + if(!d_ptr->transform) + d_ptr->transform = new QTransform; + + QTransform newTransform(combine ? QTransform(matrix) * *d_ptr->transform : QTransform(matrix)); + if(*d_ptr->transform == newTransform) return; - // Notify the item that the matrix is changing. - QVariant newTransformVariant(itemChange(ItemMatrixChange, - qVariantFromValue(newTransform.toAffine()))); - newTransform = QTransform(qVariantValue(newTransformVariant)); - if (oldTransform == newTransform) + // Notify the item that the transformation matrix is changing. + const QVariant newTransformVariant(itemChange(ItemTransformChange, + qVariantFromValue(newTransform))); + newTransform = qVariantValue(newTransformVariant); + if (*d_ptr->transform == newTransform) return; // Update and set the new transformation. prepareGeometryChange(); - if(!d_ptr->transform) - d_ptr->transform = new QTransform(newTransform); - else - *d_ptr->transform = newTransform; + *d_ptr->transform = newTransform; // Send post-notification. - // NB! We have to change the value from QMatrix to QTransform. - qVariantSetValue(newTransformVariant, newTransform); itemChange(ItemTransformHasChanged, newTransformVariant); } @@ -2907,24 +2904,23 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) */ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) { - QTransform oldTransform = this->transform(); - QTransform newTransform(combine ? matrix * oldTransform : matrix); - if (oldTransform == newTransform) + if(!d_ptr->transform) + d_ptr->transform = new QTransform; + + QTransform newTransform(combine ? matrix * *d_ptr->transform : matrix); + if(*d_ptr->transform == newTransform) return; // Notify the item that the transformation matrix is changing. const QVariant newTransformVariant(itemChange(ItemTransformChange, qVariantFromValue(newTransform))); newTransform = qVariantValue(newTransformVariant); - if (oldTransform == newTransform) + if (*d_ptr->transform == newTransform) return; // Update and set the new transformation. prepareGeometryChange(); - if(!d_ptr->transform) - d_ptr->transform = new QTransform(newTransform); - else - *d_ptr->transform = newTransform; + *d_ptr->transform = newTransform; // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); -- cgit v0.12 From fa256ad3758e0d8794136975f0e93ddfa91216f5 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 16:09:38 +0200 Subject: remove now unused flag --- src/gui/graphicsview/qgraphicsitem_p.h | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index c999378..95a7733 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -142,10 +142,6 @@ public: emptyClipPath(0), inSetPosHelper(0), flags(0), - allChildrenCombineOpacity(1), - hasDecomposedTransform(0), - dirtyTransform(0), - dirtyTransformComponents(0), dirtyChildrenBoundingRect(1), inDirtyList(0), paintedViewBoundingRectsNeedRepaint(0), @@ -353,14 +349,10 @@ public: // New 32 bits quint32 flags : 10; - quint32 allChildrenCombineOpacity : 1; - quint32 hasDecomposedTransform : 1; - quint32 dirtyTransform : 1; - quint32 dirtyTransformComponents : 1; quint32 dirtyChildrenBoundingRect : 1; quint32 inDirtyList : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; - quint32 padding : 15; // feel free to use + quint32 padding : 19; // feel free to use // Optional stacking order int globalStackingOrder; -- cgit v0.12 From 72e083c98c3adb07bb1578fb7f28f121fc3f34ac Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 16:47:29 +0200 Subject: greatly speed up QTransform::mapRect() for projective transforms The code so far was converting the rect to a painterpath, mapping that one and then taking the bounding rect. It is actually sufficient to simply map the four corners of the rectangle and take the bounding rect of these four points even in the projective case. Reviewed-by: Andreas --- src/gui/painting/qtransform.cpp | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/src/gui/painting/qtransform.cpp b/src/gui/painting/qtransform.cpp index c00012a..86e594c 100644 --- a/src/gui/painting/qtransform.cpp +++ b/src/gui/painting/qtransform.cpp @@ -1788,7 +1788,7 @@ QRect QTransform::mapRect(const QRect &rect) const y -= h; } return QRect(x, y, w, h); - } else if (t < TxProject) { + } else { // see mapToPolygon for explanations of the algorithm. qreal x = 0, y = 0; MAP(rect.left(), rect.top(), x, y); @@ -1812,10 +1812,6 @@ QRect QTransform::mapRect(const QRect &rect) const xmax = qMax(xmax, x); ymax = qMax(ymax, y); return QRect(qRound(xmin), qRound(ymin), qRound(xmax)-qRound(xmin), qRound(ymax)-qRound(ymin)); - } else { - QPainterPath path; - path.addRect(rect); - return map(path).boundingRect().toRect(); } } @@ -1858,7 +1854,7 @@ QRectF QTransform::mapRect(const QRectF &rect) const y -= h; } return QRectF(x, y, w, h); - } else if (t < TxProject) { + } else { qreal x = 0, y = 0; MAP(rect.x(), rect.y(), x, y); qreal xmin = x; @@ -1881,10 +1877,6 @@ QRectF QTransform::mapRect(const QRectF &rect) const xmax = qMax(xmax, x); ymax = qMax(ymax, y); return QRectF(xmin, ymin, xmax-xmin, ymax - ymin); - } else { - QPainterPath path; - path.addRect(rect); - return map(path).boundingRect(); } } -- cgit v0.12 From bea8a19742ed1decbd63464e36e57980fbde7016 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 22:55:49 +0200 Subject: fix a small logic bug in childrenCombineOpacity Regression introduced during refactoring earlier today. --- src/gui/graphicsview/qgraphicsitem_p.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 95a7733..acd2fcc 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -272,7 +272,9 @@ public: inline bool childrenCombineOpacity() const { - if (!children.size() || flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) + if (!children.size()) + return true; + if (flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) return false; for (int i = 0; i < children.size(); ++i) { -- cgit v0.12 From c563cff78b9606bf5869707fcbe6183198508d60 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 08:54:31 +0200 Subject: Introduce QGraphicsItem::ItemHasNoContents. This flag helps optimize the case where an item is used only as a transformation node in a scene graph, and where the item itself doesn't paint anything. This is the default for FxItem (the subclasses that do paint enable the HasContents flag). This lets Graphics View know whether there's any point in setting up the world transform, opacity and other things. Reviewed-by: Lars --- src/gui/graphicsview/qgraphicsitem.cpp | 8 ++++++++ src/gui/graphicsview/qgraphicsitem.h | 3 ++- src/gui/graphicsview/qgraphicsitem_p.h | 4 ++-- src/gui/graphicsview/qgraphicsscene.cpp | 30 ++++++++++++++++++++---------- 4 files changed, 32 insertions(+), 13 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 486e0b5..12aaba5 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -309,6 +309,11 @@ and is always initialized to 1. Use QStyleOptionGraphicsItem::levelOfDetailFromTransform for a more fine-grained value. + + \value ItemHasNoContents The item does not paint anything (i.e., calling + paint() on the item has no effect). You should set this flag on items that + do not need to be painted to ensure that Graphics View avoids unnecessary + painting preparations. */ /*! @@ -9108,6 +9113,9 @@ QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag) case QGraphicsItem::ItemUsesExtendedStyleOption: str = "ItemUsesExtendedStyleOption"; break; + case QGraphicsItem::ItemHasNoContents: + str = "ItemHasNoContents"; + break; } debug << str; return debug; diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index def773e..737ea80 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -95,7 +95,8 @@ public: ItemIgnoresParentOpacity = 0x40, ItemDoesntPropagateOpacityToChildren = 0x80, ItemStacksBehindParent = 0x100, - ItemUsesExtendedStyleOption = 0x200 + ItemUsesExtendedStyleOption = 0x200, + ItemHasNoContents = 0x400 // NB! Don't forget to increase the d_ptr->flags bit field by 1 when adding a new flag. }; Q_DECLARE_FLAGS(GraphicsItemFlags, GraphicsItemFlag) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index acd2fcc..9d5b58a 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -350,11 +350,11 @@ public: quint32 unused : 3; // New 32 bits - quint32 flags : 10; + quint32 flags : 11; quint32 dirtyChildrenBoundingRect : 1; quint32 inDirtyList : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; - quint32 padding : 19; // feel free to use + quint32 padding : 18; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index b105c9c..eaebd1a 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -295,9 +295,13 @@ static inline bool QRectF_intersects(const QRectF &s, const QRectF &r) static inline void _q_adjustRect(QRectF *rect) { Q_ASSERT(rect); - if (!rect->width()) + bool nullWidth = !rect->width(); + bool nullHeight = !rect->height(); + if (nullWidth && nullHeight) + return; + if (nullWidth) rect->adjust(-0.00001, 0, 0.00001, 0); - if (!rect->height()) + else if (nullHeight) rect->adjust(0, -0.00001, 0, 0.00001); } @@ -5079,22 +5083,23 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } } QRectF brect = item->boundingRect(); - _q_adjustRect(&brect); - const QRect paintedViewBoundingRect = transform.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); - item->d_ptr->paintedViewBoundingRects.insert(widget, paintedViewBoundingRect); - viewBoundingRect = paintedViewBoundingRect & exposedRegion.boundingRect(); + if (!brect.size().isNull()) { + // ### This does not take the clip into account. + _q_adjustRect(&brect); + const QRect paintedViewBoundingRect = transform.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); + item->d_ptr->paintedViewBoundingRects.insert(widget, paintedViewBoundingRect); + viewBoundingRect = paintedViewBoundingRect & exposedRegion.boundingRect(); + } } else { transform = parentTransform; } - // Find and sort children. - QList children = item ? item->d_ptr->children : topLevelItems; - qSort(children.begin(), children.end(), qt_notclosestLeaf); - bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); bool dontDrawItem = !item || viewBoundingRect.isEmpty(); bool dontDrawChildren = item && dontDrawItem && childClip; childClip &= !dontDrawChildren & !children.isEmpty(); + if (item && item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) + dontDrawItem = true; // Clip children. if (childClip) { @@ -5103,6 +5108,11 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * painter->setClipPath(item->shape(), Qt::IntersectClip); } + // Find and sort children. + QList children = item ? item->d_ptr->children : topLevelItems; + if (!dontDrawChildren) + qSort(children.begin(), children.end(), qt_notclosestLeaf); + // Draw children behind int i; if (!dontDrawChildren) { -- cgit v0.12 From 33c1496689c090561657c698321442ae655ccec3 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 28 May 2009 11:31:24 +0200 Subject: Remove scene transform cache from QGraphicsItem. Now that we have a recursive painting algorithm these types of optimizations are no longer necessary. In fact they only cause more problems and clutter up the code unnecessarily. Removing this also removes extra overhead from moving and transforming items. Reviewed-by: Lars --- src/gui/graphicsview/qgraphicsitem.cpp | 232 +++++++++++++++++++++++++++++++++ 1 file changed, 232 insertions(+) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 12aaba5..0990e16 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -2652,8 +2652,13 @@ QTransform QGraphicsItem::sceneTransform() const QTransform m; const QGraphicsItem *p = this; do { +<<<<<<< HEAD:src/gui/graphicsview/qgraphicsitem.cpp if (p->d_ptr->transform) m *= *p->d_ptr->transform; +======= + if (p->d_ptr->hasTransform) + m *= p->transform(); +>>>>>>> Remove scene transform cache from QGraphicsItem.:src/gui/graphicsview/qgraphicsitem.cpp const QPointF &pos = p->d_ptr->pos; if (!pos.isNull()) m *= QTransform::fromTranslate(pos.x(), pos.y()); @@ -2881,7 +2886,13 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); +<<<<<<< HEAD:src/gui/graphicsview/qgraphicsitem.cpp *d_ptr->transform = newTransform; +======= + transformData->baseTransform = newTransform; + transformData->dirty = true; + d_ptr->hasTransform = true; +>>>>>>> Remove scene transform cache from QGraphicsItem.:src/gui/graphicsview/qgraphicsitem.cpp // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -2925,7 +2936,14 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); +<<<<<<< HEAD:src/gui/graphicsview/qgraphicsitem.cpp *d_ptr->transform = newTransform; +======= + transformData->baseTransform = newTransform; + transformData->dirty = true; + d_ptr->hasTransform = true; + transform(); // ### update transform, bad! +>>>>>>> Remove scene transform cache from QGraphicsItem.:src/gui/graphicsview/qgraphicsitem.cpp // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -3036,6 +3054,220 @@ void QGraphicsItem::translate(qreal dx, qreal dy) } /*! +<<<<<<< HEAD:src/gui/graphicsview/qgraphicsitem.cpp +======= + Returns the origin point used for all transformations. + */ +QPointF QGraphicsItem::transformOrigin() const +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) + return QPointF(); + + return transformData->transformCenter; +} + +/*! + Set a \a center for all transformations. +*/ +void QGraphicsItem::setTransformOrigin(const QPointF ¢er) +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) { + if (center.isNull()) + return; + transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); + } + if (transformData->transformCenter == center) + return; + + prepareGeometryChange(); + + transformData->transformCenter = center; + + transformData->dirty = true; + d_ptr->hasTransform = true; +} + +/*! + Returns the x scale factor. + */ +qreal QGraphicsItem::xScale() const +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) + return 1; + + return transformData->scaleX; +} + +/*! + Sets the x scale factor to \a factor. + */ +void QGraphicsItem::setXScale(qreal factor) +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) { + if (factor == 1) + return; + transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); + } + if (transformData->scaleX == factor) + return; + + prepareGeometryChange(); + + transformData->scaleX = factor; + transformData->dirty = true; + d_ptr->hasTransform = true; +} + +/*! + Returns the y scale factor. + */ +qreal QGraphicsItem::yScale() const +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) + return 1; + + return transformData->scaleY; +} + +/*! + Sets the y scale factor to \a factor. + */ +void QGraphicsItem::setYScale(qreal factor) +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) { + if (factor == 1) + return; + transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); + } + if (transformData->scaleY == factor) + return; + + prepareGeometryChange(); + + transformData->scaleY = factor; + transformData->dirty = true; + d_ptr->hasTransform = true; +} + +/*! + Returns the x rotation angle. + */ +qreal QGraphicsItem::xRotation() const +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) + return 0; + return transformData->rotationX; +} + +/*! + Sets the x rotation angle to \a angle. + */ +void QGraphicsItem::setXRotation(qreal angle) +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) { + if (qFuzzyCompare(angle + 1, 1)) + return; + transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); + } + + prepareGeometryChange(); + + transformData->rotationX = angle; + + transformData->dirty = true; + d_ptr->hasTransform = true; +} + +/*! + Returns the y rotation angle. + */ +qreal QGraphicsItem::yRotation() const +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) + return 0; + return transformData->rotationY; +} + +/*! + Sets the y rotation angle to \a angle. + */ +void QGraphicsItem::setYRotation(qreal angle) +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) { + if (qFuzzyCompare(angle + 1, 1)) + return; + transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); + } + + prepareGeometryChange(); + + transformData->rotationY = angle; + + transformData->dirty = true; + d_ptr->hasTransform = true; +} + +/*! + Returns the z rotation angle. + */ +qreal QGraphicsItem::zRotation() const +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) + return 0; + return transformData->rotationZ; +} + +/*! + Sets the z rotation angle to \a angle. + */ +void QGraphicsItem::setZRotation(qreal angle) +{ + QGraphicsItemPrivate::TransformData *transformData = static_cast( + qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); + if (!transformData) { + if (qFuzzyCompare(angle + 1, 1)) + return; + transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); + } + + prepareGeometryChange(); + + transformData->rotationZ = angle; + + transformData->dirty = true; + d_ptr->hasTransform = true; +} + +/*! +>>>>>>> Remove scene transform cache from QGraphicsItem.:src/gui/graphicsview/qgraphicsitem.cpp This virtual function is called twice for all items by the QGraphicsScene::advance() slot. In the first phase, all items are called with \a phase == 0, indicating that items on the scene are about to -- cgit v0.12 From e506c0816dadd336e8151a0af504bd8b814bbaf3 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 12:25:21 +0200 Subject: get rid of the hasTransform flag in QGraphicsItem Since the transform is now a pointer in QGraphicsItemPrivate, we can use this pointer directly and there's no need for a separate bitflag anymore. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 242 ++------------------------------- src/gui/graphicsview/qgraphicsitem_p.h | 2 +- 2 files changed, 9 insertions(+), 235 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 0990e16..3008997 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -2652,13 +2652,8 @@ QTransform QGraphicsItem::sceneTransform() const QTransform m; const QGraphicsItem *p = this; do { -<<<<<<< HEAD:src/gui/graphicsview/qgraphicsitem.cpp if (p->d_ptr->transform) m *= *p->d_ptr->transform; -======= - if (p->d_ptr->hasTransform) - m *= p->transform(); ->>>>>>> Remove scene transform cache from QGraphicsItem.:src/gui/graphicsview/qgraphicsitem.cpp const QPointF &pos = p->d_ptr->pos; if (!pos.isNull()) m *= QTransform::fromTranslate(pos.x(), pos.y()); @@ -2886,13 +2881,10 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); -<<<<<<< HEAD:src/gui/graphicsview/qgraphicsitem.cpp - *d_ptr->transform = newTransform; -======= - transformData->baseTransform = newTransform; - transformData->dirty = true; - d_ptr->hasTransform = true; ->>>>>>> Remove scene transform cache from QGraphicsItem.:src/gui/graphicsview/qgraphicsitem.cpp + if(!d_ptr->transform) + d_ptr->transform = new QTransform(newTransform); + else + *d_ptr->transform = newTransform; // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -2936,14 +2928,10 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); -<<<<<<< HEAD:src/gui/graphicsview/qgraphicsitem.cpp - *d_ptr->transform = newTransform; -======= - transformData->baseTransform = newTransform; - transformData->dirty = true; - d_ptr->hasTransform = true; - transform(); // ### update transform, bad! ->>>>>>> Remove scene transform cache from QGraphicsItem.:src/gui/graphicsview/qgraphicsitem.cpp + if(!d_ptr->transform) + d_ptr->transform = new QTransform(newTransform); + else + *d_ptr->transform = newTransform; // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -3054,220 +3042,6 @@ void QGraphicsItem::translate(qreal dx, qreal dy) } /*! -<<<<<<< HEAD:src/gui/graphicsview/qgraphicsitem.cpp -======= - Returns the origin point used for all transformations. - */ -QPointF QGraphicsItem::transformOrigin() const -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) - return QPointF(); - - return transformData->transformCenter; -} - -/*! - Set a \a center for all transformations. -*/ -void QGraphicsItem::setTransformOrigin(const QPointF ¢er) -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) { - if (center.isNull()) - return; - transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); - } - if (transformData->transformCenter == center) - return; - - prepareGeometryChange(); - - transformData->transformCenter = center; - - transformData->dirty = true; - d_ptr->hasTransform = true; -} - -/*! - Returns the x scale factor. - */ -qreal QGraphicsItem::xScale() const -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) - return 1; - - return transformData->scaleX; -} - -/*! - Sets the x scale factor to \a factor. - */ -void QGraphicsItem::setXScale(qreal factor) -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) { - if (factor == 1) - return; - transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); - } - if (transformData->scaleX == factor) - return; - - prepareGeometryChange(); - - transformData->scaleX = factor; - transformData->dirty = true; - d_ptr->hasTransform = true; -} - -/*! - Returns the y scale factor. - */ -qreal QGraphicsItem::yScale() const -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) - return 1; - - return transformData->scaleY; -} - -/*! - Sets the y scale factor to \a factor. - */ -void QGraphicsItem::setYScale(qreal factor) -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) { - if (factor == 1) - return; - transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); - } - if (transformData->scaleY == factor) - return; - - prepareGeometryChange(); - - transformData->scaleY = factor; - transformData->dirty = true; - d_ptr->hasTransform = true; -} - -/*! - Returns the x rotation angle. - */ -qreal QGraphicsItem::xRotation() const -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) - return 0; - return transformData->rotationX; -} - -/*! - Sets the x rotation angle to \a angle. - */ -void QGraphicsItem::setXRotation(qreal angle) -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) { - if (qFuzzyCompare(angle + 1, 1)) - return; - transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); - } - - prepareGeometryChange(); - - transformData->rotationX = angle; - - transformData->dirty = true; - d_ptr->hasTransform = true; -} - -/*! - Returns the y rotation angle. - */ -qreal QGraphicsItem::yRotation() const -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) - return 0; - return transformData->rotationY; -} - -/*! - Sets the y rotation angle to \a angle. - */ -void QGraphicsItem::setYRotation(qreal angle) -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) { - if (qFuzzyCompare(angle + 1, 1)) - return; - transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); - } - - prepareGeometryChange(); - - transformData->rotationY = angle; - - transformData->dirty = true; - d_ptr->hasTransform = true; -} - -/*! - Returns the z rotation angle. - */ -qreal QGraphicsItem::zRotation() const -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) - return 0; - return transformData->rotationZ; -} - -/*! - Sets the z rotation angle to \a angle. - */ -void QGraphicsItem::setZRotation(qreal angle) -{ - QGraphicsItemPrivate::TransformData *transformData = static_cast( - qVariantValue(d_ptr->extra(QGraphicsItemPrivate::ExtraTransform))); - if (!transformData) { - if (qFuzzyCompare(angle + 1, 1)) - return; - transformData = new QGraphicsItemPrivate::TransformData; - d_ptr->setExtra(QGraphicsItemPrivate::ExtraTransform, qVariantFromValue(transformData)); - } - - prepareGeometryChange(); - - transformData->rotationZ = angle; - - transformData->dirty = true; - d_ptr->hasTransform = true; -} - -/*! ->>>>>>> Remove scene transform cache from QGraphicsItem.:src/gui/graphicsview/qgraphicsitem.cpp This virtual function is called twice for all items by the QGraphicsScene::advance() slot. In the first phase, all items are called with \a phase == 0, indicating that items on the scene are about to diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 9d5b58a..4deb6e5 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -347,7 +347,7 @@ public: quint32 dirtyClipPath : 1; quint32 emptyClipPath : 1; quint32 inSetPosHelper : 1; - quint32 unused : 3; + quint32 unused : 1; // New 32 bits quint32 flags : 11; -- cgit v0.12 From 0e650ed3a8e7e4bdf4c9d3eefd667d4abb318c5a Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 15:31:46 +0200 Subject: simplify opacity handling in QGraphicsItem Greatly simplify how we handle opacity and store it as a member in QGraphicsItemPrivate. Remove the caching of effectiveOpacity. It's faster to calculate it on the fly, and the recursive painting algorithm will make even that need go away. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem_p.h | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 4deb6e5..aac1795 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -272,9 +272,7 @@ public: inline bool childrenCombineOpacity() const { - if (!children.size()) - return true; - if (flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) + if (!children.size() || flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) return false; for (int i = 0; i < children.size(); ++i) { @@ -347,7 +345,7 @@ public: quint32 dirtyClipPath : 1; quint32 emptyClipPath : 1; quint32 inSetPosHelper : 1; - quint32 unused : 1; + quint32 unused : 3; // New 32 bits quint32 flags : 11; -- cgit v0.12 From 910e3d807226027a48a3b02906ff8e15b662ad00 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 16:08:25 +0200 Subject: smaller optimisation in setTransform --- src/gui/graphicsview/qgraphicsitem.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 3008997..12aaba5 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -2881,10 +2881,7 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); - if(!d_ptr->transform) - d_ptr->transform = new QTransform(newTransform); - else - *d_ptr->transform = newTransform; + *d_ptr->transform = newTransform; // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -2928,10 +2925,7 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); - if(!d_ptr->transform) - d_ptr->transform = new QTransform(newTransform); - else - *d_ptr->transform = newTransform; + *d_ptr->transform = newTransform; // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); -- cgit v0.12 From f8f185b99a12e14374ce29501b8d13c5e3d125fd Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 16:09:38 +0200 Subject: remove now unused flag --- src/gui/graphicsview/qgraphicsitem_p.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index aac1795..95a7733 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -348,11 +348,11 @@ public: quint32 unused : 3; // New 32 bits - quint32 flags : 11; + quint32 flags : 10; quint32 dirtyChildrenBoundingRect : 1; quint32 inDirtyList : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; - quint32 padding : 18; // feel free to use + quint32 padding : 19; // feel free to use // Optional stacking order int globalStackingOrder; -- cgit v0.12 From 6e92cbd42ce7e68112de8bce8a0468532843a947 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 28 May 2009 22:55:49 +0200 Subject: fix a small logic bug in childrenCombineOpacity Regression introduced during refactoring earlier today. --- src/gui/graphicsview/qgraphicsitem_p.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 95a7733..acd2fcc 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -272,7 +272,9 @@ public: inline bool childrenCombineOpacity() const { - if (!children.size() || flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) + if (!children.size()) + return true; + if (flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren) return false; for (int i = 0; i < children.size(); ++i) { -- cgit v0.12 From aba52a08d8868682e576d1b53d423cedb0a9134e Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 08:54:31 +0200 Subject: Introduce QGraphicsItem::ItemHasNoContents. This flag helps optimize the case where an item is used only as a transformation node in a scene graph, and where the item itself doesn't paint anything. This is the default for FxItem (the subclasses that do paint enable the HasContents flag). This lets Graphics View know whether there's any point in setting up the world transform, opacity and other things. Reviewed-by: Lars --- src/gui/graphicsview/qgraphicsitem_p.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index acd2fcc..9d5b58a 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -350,11 +350,11 @@ public: quint32 unused : 3; // New 32 bits - quint32 flags : 10; + quint32 flags : 11; quint32 dirtyChildrenBoundingRect : 1; quint32 inDirtyList : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; - quint32 padding : 19; // feel free to use + quint32 padding : 18; // feel free to use // Optional stacking order int globalStackingOrder; -- cgit v0.12 From 32c09e7a36ecd41e8beb2a1f947944502793fd84 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 28 May 2009 20:16:20 +0200 Subject: More re-factoring of Graphics View's update mechanism. This time with a recursive approach of processing dirty items. I've kept the previous approach using a dirty list, but the recursive one is now the default. Use QT_GV_USE_DIRTY_LIST=1 to swap. I've also cached the item's device transform in both cases so that we can re-use it later when drawing the item. --- src/gui/graphicsview/qgraphicsitem.cpp | 2 +- src/gui/graphicsview/qgraphicsitem_p.h | 21 ++- src/gui/graphicsview/qgraphicsscene.cpp | 241 +++++++++++++++++++++++--------- src/gui/graphicsview/qgraphicsscene_p.h | 4 + 4 files changed, 185 insertions(+), 83 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 12aaba5..c3744b2 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -3769,7 +3769,7 @@ bool QGraphicsItemPrivate::discardUpdateRequest(bool ignoreClipping, bool ignore // No scene, or if the scene is updating everything, means we have nothing // to do. The only exception is if the scene tracks the growing scene rect. return (!visible && !ignoreVisibleBit) - || (!ignoreDirtyBit && (dirty || hasDirtyAncestor())) + || (!ignoreDirtyBit && dirty) || !scene || (scene->d_func()->updateAll && scene->d_func()->hasSceneRect) || (!ignoreClipping && (childrenClippedToShape() && isClippedAway())) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 9d5b58a..deaf30f 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -145,6 +145,9 @@ public: dirtyChildrenBoundingRect(1), inDirtyList(0), paintedViewBoundingRectsNeedRepaint(0), + allChildrenDirty(0), + fullUpdatePending(0), + hasValidDeviceTransform(0), globalStackingOrder(-1), q_ptr(0) { @@ -297,18 +300,6 @@ public: || (childrenCombineOpacity() && isFullyTransparent()); } - inline bool hasDirtyAncestor() const - { - QGraphicsItem *p = parent; - while (p) { - if (p->d_ptr->dirtyChildren || (p->d_ptr->dirty && p->d_ptr->childrenClippedToShape())) - return true; - p = p->d_ptr->parent; - } - return false; - } - - QPainterPath cachedClipPath; QRectF childrenBoundingRect; QRectF needsRepaint; @@ -320,6 +311,7 @@ public: QGraphicsItem *parent; QList children; QTransform *transform; + QTransform deviceTransform; int siblingIndex; int index; int depth; @@ -354,7 +346,10 @@ public: quint32 dirtyChildrenBoundingRect : 1; quint32 inDirtyList : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; - quint32 padding : 18; // feel free to use + quint32 allChildrenDirty : 1; + quint32 fullUpdatePending : 1; + quint32 hasValidDeviceTransform : 1; + quint32 padding : 15; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index eaebd1a..a5ac9d9 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -337,6 +337,7 @@ QGraphicsScenePrivate::QGraphicsScenePrivate() hasSceneRect(false), updateAll(false), calledEmitUpdated(false), + processDirtyItemsEmitted(false), selectionChanging(0), regenerateIndex(true), purgePending(false), @@ -683,73 +684,70 @@ void QGraphicsScenePrivate::_q_polishItems() void QGraphicsScenePrivate::_q_processDirtyItems() { - Q_Q(QGraphicsScene); - if (dirtyItems.isEmpty()) - return; + static int useDirtyListEnv = qgetenv("QT_GV_USE_DIRTY_LIST").toInt(); + processDirtyItemsEmitted = false; if (updateAll) { - for (int i = 0; i < dirtyItems.size(); ++i) - resetDirtyItem(dirtyItems.at(i)); - dirtyItems.clear(); + if (useDirtyListEnv) { + for (int i = 0; i < dirtyItems.size(); ++i) + resetDirtyItem(dirtyItems.at(i)); + dirtyItems.clear(); + } + return; + } + + if (!useDirtyListEnv) { + processDirtyItemsRecursive(0, views.at(0)->viewportTransform()); + for (int i = 0; i < views.size(); ++i) + views.at(i)->d_func()->processPendingUpdates(); return; } - const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask); for (int i = 0; i < dirtyItems.size(); ++i) { QGraphicsItem *item = dirtyItems.at(i); - if (useCompatUpdate && !item->d_ptr->itemIsUntransformable() - && qFuzzyIsNull(item->boundingRegionGranularity())) { - // This block of code is kept for compatibility. Since 4.5, by default - // QGraphicsView does not connect the signal and we use the below - // method of delivering updates. - q->update(item->sceneBoundingRect()); - resetDirtyItem(item); - continue; + QGraphicsView *view = views.at(0); + QGraphicsViewPrivate *viewPrivate = view->d_func(); + const QTransform deviceTransform = item->deviceTransform(view->viewportTransform()); + + QRectF dirtyRect = adjustedItemBoundingRect(item); + if (!item->d_ptr->fullUpdatePending) { + _q_adjustRect(&item->d_ptr->needsRepaint); + dirtyRect &= item->d_ptr->needsRepaint; } - QRectF dirtyRect; - bool uninitializedDirtyRect = true; - - for (int j = 0; j < views.size(); ++j) { - QGraphicsView *view = views.at(j); - QGraphicsViewPrivate *viewPrivate = view->d_func(); - if (viewPrivate->fullUpdatePending) - continue; - switch (viewPrivate->viewportUpdateMode) { - case QGraphicsView::NoViewportUpdate: - continue; - case QGraphicsView::FullViewportUpdate: - view->viewport()->update(); - viewPrivate->fullUpdatePending = 1; - continue; - default: - break; - } - - if (uninitializedDirtyRect) { - dirtyRect = adjustedItemBoundingRect(item); - if (!item->d_ptr->dirty) { - _q_adjustRect(&item->d_ptr->needsRepaint); - dirtyRect &= item->d_ptr->needsRepaint; - } - - if (item->d_ptr->dirtyChildren && !item->d_ptr->children.isEmpty() - && !item->d_ptr->childrenClippedToShape()) { - QRectF childrenBounds = item->childrenBoundingRect(); - _q_adjustRect(&childrenBounds); - dirtyRect |= childrenBounds; - } - uninitializedDirtyRect = false; - } + if (item->d_ptr->allChildrenDirty && !item->d_ptr->children.isEmpty() + && !item->d_ptr->childrenClippedToShape()) { + QRectF childrenBounds = item->childrenBoundingRect(); + _q_adjustRect(&childrenBounds); + dirtyRect |= childrenBounds; + } - if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) - viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) + viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); - if (!item->d_ptr->hasBoundingRegionGranularity) - viewPrivate->updateRect(viewPrivate->mapToViewRect(item, dirtyRect)); + bool dirtyRectOutsideViewport = false; + if (item->d_ptr->hasBoundingRegionGranularity) { + const QRegion dirtyViewRegion = deviceTransform.map(QRegion(dirtyRect.toRect())) + & viewPrivate->viewport->rect(); + if (!dirtyViewRegion.isEmpty()) + viewPrivate->updateRegion(dirtyViewRegion); else - viewPrivate->updateRegion(viewPrivate->mapToViewRegion(item, dirtyRect)); + dirtyRectOutsideViewport = true; + } else { + const QRect dirtyViewRect = deviceTransform.mapRect(dirtyRect).toRect() + & viewPrivate->viewport->rect(); + if (!dirtyViewRect.isEmpty()) + viewPrivate->updateRect(dirtyViewRect); + else + dirtyRectOutsideViewport = true; + } + if (!dirtyRectOutsideViewport) { + // We know for sure this item will be process in the paint event, hence + // store its device transform and re-use it when drawing. + item->d_ptr->hasValidDeviceTransform = 1; + item->d_ptr->deviceTransform = deviceTransform; } + resetDirtyItem(item); } @@ -5064,6 +5062,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * QTransform transform; QRect viewBoundingRect; if (item) { + if (!item->d_ptr->hasValidDeviceTransform) { if (item->d_ptr->itemIsUntransformable()) { transform = item->deviceTransform(viewTransform); } else { @@ -5082,6 +5081,10 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * transform = parentTransform; } } + } else { + transform = item->d_ptr->deviceTransform; + item->d_ptr->hasValidDeviceTransform = 0; + } QRectF brect = item->boundingRect(); if (!brect.size().isNull()) { // ### This does not take the clip into account. @@ -5176,25 +5179,120 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b if (!fullItemUpdate && rect.isEmpty()) return; - if (dirtyItems.isEmpty()) + if (!processDirtyItemsEmitted) { QMetaObject::invokeMethod(q_ptr, "_q_processDirtyItems", Qt::QueuedConnection); + processDirtyItemsEmitted = true; + } + + item->d_ptr->dirty = 1; + if (fullItemUpdate) + item->d_ptr->fullUpdatePending = 1; + else if (!item->d_ptr->fullUpdatePending) + item->d_ptr->needsRepaint |= rect; - if (item->d_ptr->inDirtyList) { - if (fullItemUpdate) - item->d_ptr->dirty = 1; - else if (!item->d_ptr->dirty) - item->d_ptr->needsRepaint |= rect; + if (invalidateChildren) { + item->d_ptr->allChildrenDirty = 1; + item->d_ptr->dirtyChildren = 1; + } + + static int useDirtyListEnv = qgetenv("QT_GV_USE_DIRTY_LIST").toInt(); + if (useDirtyListEnv) { + if (!item->d_ptr->inDirtyList) { + dirtyItems.append(item); + item->d_ptr->inDirtyList = 1; + } } else { - dirtyItems.append(item); - item->d_ptr->inDirtyList = 1; - if (fullItemUpdate) - item->d_ptr->dirty = 1; - else if (!item->d_ptr->dirty) - item->d_ptr->needsRepaint = rect; + QGraphicsItem *p = item->d_ptr->parent; + while (p && !p->d_ptr->dirtyChildren) { + p->d_ptr->dirtyChildren = 1; + p = p->d_ptr->parent; + } } +} - if (invalidateChildren) - item->d_ptr->dirtyChildren = 1; +void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, const QTransform &parentTransform) +{ + Q_ASSERT(!item || item->d_ptr->dirty || item->d_ptr->dirtyChildren); + + // Calculate the full transform for this item. + QTransform transform; + if (item) { + if (item->d_ptr->itemIsUntransformable()) { + transform = item->deviceTransform(views.at(0)->viewportTransform()); + } else { + const QPointF &pos = item->d_ptr->pos; + bool posNull = pos.isNull(); + if (!posNull || item->d_ptr->transform) { + if (item->d_ptr->transform) { + transform = *item->d_ptr->transform; + if (!posNull) + transform *= QTransform::fromTranslate(pos.x(), pos.y()); + transform *= parentTransform; + } else { + transform = QTransform::fromTranslate(pos.x(), pos.y()) * parentTransform; + } + } else { + transform = parentTransform; + } + } + } else { + transform = parentTransform; + } + + // Process item. + if (item && item->d_ptr->dirty) { + QRectF dirtyRect = adjustedItemBoundingRect(item); + if (!item->d_ptr->fullUpdatePending) { + _q_adjustRect(&item->d_ptr->needsRepaint); + dirtyRect &= item->d_ptr->needsRepaint; + } + + QGraphicsViewPrivate *viewPrivate = views.at(0)->d_func(); + if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) + viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + + bool dirtyRectOutsideViewport = false; + if (item->d_ptr->hasBoundingRegionGranularity) { + const QRegion dirtyViewRegion = transform.map(QRegion(dirtyRect.toRect())) + & viewPrivate->viewport->rect(); + if (!dirtyViewRegion.isEmpty()) + viewPrivate->updateRegion(dirtyViewRegion); + else + dirtyRectOutsideViewport = true; + } else { + const QRect dirtyViewRect = transform.mapRect(dirtyRect).toRect() + & viewPrivate->viewport->rect(); + if (!dirtyViewRect.isEmpty()) + viewPrivate->updateRect(dirtyViewRect); + else + dirtyRectOutsideViewport = true; + } + if (!dirtyRectOutsideViewport) { + // We know for sure this item will be process in the paint event, hence + // store its device transform and re-use it when drawing. + item->d_ptr->hasValidDeviceTransform = 1; + item->d_ptr->deviceTransform = transform; + } + } + + // Process root items / children. + if (!item || item->d_ptr->dirtyChildren) { + QList *children = item ? &item->d_ptr->children : &topLevelItems; + const bool allChildrenDirty = item && item->d_ptr->allChildrenDirty; + for (int i = 0; i < children->size(); ++i) { + QGraphicsItem *child = children->at(i); + if (allChildrenDirty) { + child->d_ptr->dirty = 1; + } else if (!child->d_ptr->dirty && !child->d_ptr->dirtyChildren) { + resetDirtyItem(child); + continue; + } + processDirtyItemsRecursive(child, transform); + } + } + + if (item) + resetDirtyItem(item); } /*! @@ -5302,7 +5400,12 @@ void QGraphicsScene::drawItems(QPainter *painter, } // Set up the painter transform - painter->setWorldTransform(item->deviceTransform(viewTransform), false); + if (item->d_ptr->hasValidDeviceTransform) { + painter->setWorldTransform(item->d_ptr->deviceTransform); + item->d_ptr->hasValidDeviceTransform = 0; + } else { + painter->setWorldTransform(item->deviceTransform(viewTransform), false); + } // Save painter bool saveState = (d->painterStateProtection || (item->flags() & QGraphicsItem::ItemClipsToShape)); diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index bf7ac0a..50c716c 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -105,6 +105,7 @@ public: QList updatedRects; bool updateAll; bool calledEmitUpdated; + bool processDirtyItemsEmitted; QPainterPath selectionArea; int selectionChanging; @@ -257,6 +258,7 @@ public: const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags); void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); + void processDirtyItemsRecursive(QGraphicsItem *item, const QTransform &); inline void resetDirtyItem(QGraphicsItem *item) { @@ -266,6 +268,8 @@ public: item->d_ptr->dirtyChildren = 0; item->d_ptr->inDirtyList = 0; item->d_ptr->needsRepaint = QRectF(); + item->d_ptr->allChildrenDirty = 0; + item->d_ptr->fullUpdatePending = 0; } inline void removeFromDirtyItems(QGraphicsItem *item) -- cgit v0.12 From f582ed67c29e2406adeb0a52c7a68a51e0c2e8ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Fri, 29 May 2009 13:20:42 +0200 Subject: Only call qgetenv("QGRAPHICSVIEW_DIRECT") once. --- src/gui/graphicsview/qgraphicsview.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 68c0e39..369301e 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3313,9 +3313,8 @@ void QGraphicsView::paintEvent(QPaintEvent *event) int backgroundTime = stopWatch.elapsed() - exposedTime; #endif - const char *directEnv = getenv("QGRAPHICSVIEW_DIRECT"); - bool overrideDirectPaint = directEnv && atoi(directEnv) != 0; - if (overrideDirectPaint || (d->optimizationFlags & BypassDrawItems)) { + static int directEnv = getenv("QGRAPHICSVIEW_DIRECT").toInt(); + if (directEnv || (d->optimizationFlags & BypassDrawItems)) { d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, viewTransform, exposedRegion, viewport(), d->optimizationFlags); } else { -- cgit v0.12 From 669679d389ff0585bad30d41b085a4189d0e7a91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Fri, 29 May 2009 13:24:02 +0200 Subject: Ooops. Compile :) --- src/gui/graphicsview/qgraphicsview.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 369301e..354feae 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3313,7 +3313,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) int backgroundTime = stopWatch.elapsed() - exposedTime; #endif - static int directEnv = getenv("QGRAPHICSVIEW_DIRECT").toInt(); + static int directEnv = qgetenv("QGRAPHICSVIEW_DIRECT").toInt(); if (directEnv || (d->optimizationFlags & BypassDrawItems)) { d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, viewTransform, exposedRegion, viewport(), d->optimizationFlags); -- cgit v0.12 From a10e4b983e228284202df536846e6b6d4a8cf40e Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 14:40:32 +0200 Subject: Simplify the QTransform calculations. --- src/gui/graphicsview/qgraphicsscene.cpp | 46 ++++++++------------------------- 1 file changed, 11 insertions(+), 35 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index a5ac9d9..434cc8e 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5059,28 +5059,18 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * return; // Calculate the full transform for this item. - QTransform transform; + QTransform transform = parentTransform; QRect viewBoundingRect; if (item) { if (!item->d_ptr->hasValidDeviceTransform) { - if (item->d_ptr->itemIsUntransformable()) { - transform = item->deviceTransform(viewTransform); - } else { - const QPointF &pos = item->d_ptr->pos; - bool posNull = pos.isNull(); - if (!posNull || item->d_ptr->transform) { - if (item->d_ptr->transform) { - QTransform x = *item->d_ptr->transform; - if (!posNull) - x *= QTransform::fromTranslate(pos.x(), pos.y()); - transform = x * parentTransform; - } else { - transform = QTransform::fromTranslate(pos.x(), pos.y()) * parentTransform; - } + if (item->d_ptr->itemIsUntransformable()) { + transform = item->deviceTransform(viewTransform); } else { - transform = parentTransform; + const QPointF &pos = item->d_ptr->pos; + transform.translate(pos.x(), pos.y()); + if (item->d_ptr->transform) + transform = *item->d_ptr->transform * transform; } - } } else { transform = item->d_ptr->deviceTransform; item->d_ptr->hasValidDeviceTransform = 0; @@ -5093,8 +5083,6 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * item->d_ptr->paintedViewBoundingRects.insert(widget, paintedViewBoundingRect); viewBoundingRect = paintedViewBoundingRect & exposedRegion.boundingRect(); } - } else { - transform = parentTransform; } bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); @@ -5215,28 +5203,16 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, cons Q_ASSERT(!item || item->d_ptr->dirty || item->d_ptr->dirtyChildren); // Calculate the full transform for this item. - QTransform transform; + QTransform transform = parentTransform; if (item) { if (item->d_ptr->itemIsUntransformable()) { transform = item->deviceTransform(views.at(0)->viewportTransform()); } else { const QPointF &pos = item->d_ptr->pos; - bool posNull = pos.isNull(); - if (!posNull || item->d_ptr->transform) { - if (item->d_ptr->transform) { - transform = *item->d_ptr->transform; - if (!posNull) - transform *= QTransform::fromTranslate(pos.x(), pos.y()); - transform *= parentTransform; - } else { - transform = QTransform::fromTranslate(pos.x(), pos.y()) * parentTransform; - } - } else { - transform = parentTransform; - } + transform.translate(pos.x(), pos.y()); + if (item->d_ptr->transform) + transform = *item->d_ptr->transform * transform; } - } else { - transform = parentTransform; } // Process item. -- cgit v0.12 From 2581606e0f86280546c498fec130d2625376dda7 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 15:10:44 +0200 Subject: Remove siblingIndex and use stable sorting instead. To avoid sorting siblings in real-time, ensure we lazily sort the list in place when needed. Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsitem.cpp | 18 ++++++------------ src/gui/graphicsview/qgraphicsitem_p.h | 6 +++--- src/gui/graphicsview/qgraphicsscene.cpp | 27 ++++++++++++++------------- src/gui/graphicsview/qgraphicsscene_p.h | 1 + 4 files changed, 24 insertions(+), 28 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index c3744b2..9159381 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1997,15 +1997,16 @@ qreal QGraphicsItem::effectiveOpacity() const if (!d_ptr->parent) return d_ptr->opacity; - QGraphicsItem::GraphicsItemFlags myFlags = flags(); - QGraphicsItem::GraphicsItemFlags parentFlags = d_ptr->parent ? d_ptr->parent->flags() : QGraphicsItem::GraphicsItemFlags(0); + int myFlags = d_ptr->flags; + int parentFlags = d_ptr->parent ? d_ptr->parent->d_ptr->flags : 0; // If I have a parent, and I don't ignore my parent's opacity, and my // parent propagates to me, then combine my local opacity with my parent's // effective opacity into my effective opacity. if (!(myFlags & QGraphicsItem::ItemIgnoresParentOpacity) - && !(parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) + && !(parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) { return d_ptr->opacity * d_ptr->parent->effectiveOpacity(); + } return d_ptr->opacity; } @@ -3793,7 +3794,7 @@ void QGraphicsItemPrivate::resolveDepth(int parentDepth) */ void QGraphicsItemPrivate::addChild(QGraphicsItem *child) { - child->d_ptr->siblingIndex = children.size(); + needSortChildren = 1; children.append(child); } @@ -3802,14 +3803,7 @@ void QGraphicsItemPrivate::addChild(QGraphicsItem *child) */ void QGraphicsItemPrivate::removeChild(QGraphicsItem *child) { - int idx = child->d_ptr->siblingIndex; - int size = children.size(); - for (int i = idx; i < size - 1; ++i) { - QGraphicsItem *p = children[i + 1]; - children[i] = p; - p->d_ptr->siblingIndex = i; - } - children.removeLast(); + children.removeOne(child); } /*! diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index deaf30f..80b1fb4 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -116,7 +116,6 @@ public: scene(0), parent(0), transform(0), - siblingIndex(-1), index(-1), depth(0), acceptedMouseButtons(0x1f), @@ -141,6 +140,7 @@ public: dirtyClipPath(1), emptyClipPath(0), inSetPosHelper(0), + needSortChildren(1), flags(0), dirtyChildrenBoundingRect(1), inDirtyList(0), @@ -312,7 +312,6 @@ public: QList children; QTransform *transform; QTransform deviceTransform; - int siblingIndex; int index; int depth; @@ -339,7 +338,8 @@ public: quint32 dirtyClipPath : 1; quint32 emptyClipPath : 1; quint32 inSetPosHelper : 1; - quint32 unused : 3; + quint32 needSortChildren : 1; + quint32 unused : 2; // New 32 bits quint32 flags : 11; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 434cc8e..52dc152 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -339,6 +339,7 @@ QGraphicsScenePrivate::QGraphicsScenePrivate() calledEmitUpdated(false), processDirtyItemsEmitted(false), selectionChanging(0), + needSortTopLevelItems(true), regenerateIndex(true), purgePending(false), indexTimerId(0), @@ -631,7 +632,7 @@ void QGraphicsScenePrivate::_q_emitUpdated() */ void QGraphicsScenePrivate::registerTopLevelItem(QGraphicsItem *item) { - item->d_ptr->siblingIndex = topLevelItems.size(); + needSortTopLevelItems = true; topLevelItems.append(item); } @@ -640,14 +641,7 @@ void QGraphicsScenePrivate::registerTopLevelItem(QGraphicsItem *item) */ void QGraphicsScenePrivate::unregisterTopLevelItem(QGraphicsItem *item) { - int idx = item->d_ptr->siblingIndex; - int size = topLevelItems.size(); - for (int i = idx; i < size - 1; ++i) { - QGraphicsItem *p = topLevelItems[i + 1]; - topLevelItems[i] = p; - p->d_ptr->siblingIndex = i; - } - topLevelItems.removeLast(); + topLevelItems.removeOne(item); } /*! @@ -1910,7 +1904,7 @@ inline bool qt_closestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item if (f1 != f2) return f2; qreal z1 = d1->z; qreal z2 = d2->z; - return z1 != z2 ? z1 > z2 : d1->siblingIndex > d2->siblingIndex; + return z1 > z2; } static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2) @@ -5100,9 +5094,16 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } // Find and sort children. - QList children = item ? item->d_ptr->children : topLevelItems; - if (!dontDrawChildren) - qSort(children.begin(), children.end(), qt_notclosestLeaf); + QList &children = item ? item->d_ptr->children : topLevelItems; + if (!dontDrawChildren) { + if (item && item->d_ptr->needSortChildren) { + item->d_ptr->needSortChildren = 0; + qStableSort(children.begin(), children.end(), qt_notclosestLeaf); + } else if (!item && needSortTopLevelItems) { + needSortTopLevelItems = false; + qStableSort(children.begin(), children.end(), qt_notclosestLeaf); + } + } // Draw children behind int i; diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 50c716c..e7e96f5 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -116,6 +116,7 @@ public: QList pendingUpdateItems; QList unpolishedItems; QList topLevelItems; + bool needSortTopLevelItems; QMap movingItemsInitialPositions; void registerTopLevelItem(QGraphicsItem *item); void unregisterTopLevelItem(QGraphicsItem *item); -- cgit v0.12 From 5d54c09085979431831297f0e63f39c73f884d20 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 15:32:38 +0200 Subject: Avoid calling QGraphicsItem::effectiveOpacity() when rendering - instead just calculate it top-down. Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsscene.cpp | 30 ++++++++++++++++++++++++------ src/gui/graphicsview/qgraphicsscene_p.h | 3 ++- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 52dc152..1d33361 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5047,10 +5047,27 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, const QTransform &viewTransform, const QRegion &exposedRegion, QWidget *widget, - QGraphicsView::OptimizationFlags optimizationFlags) + QGraphicsView::OptimizationFlags optimizationFlags, + qreal parentOpacity) { - if (item && item->d_ptr->isInvisible()) - return; + // Calculate opacity. + qreal opacity; + if (item) { + if (!item->d_ptr->visible) + return; + QGraphicsItem *p = item->d_ptr->parent; + bool itemIgnoresParentOpacity = item->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity; + bool parentDoesntPropagateOpacity = (p && (p->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)); + if (!itemIgnoresParentOpacity && !parentDoesntPropagateOpacity) { + opacity = parentOpacity * item->opacity(); + } else { + opacity = item->d_ptr->opacity; + } + if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) + return; + } else { + opacity = parentOpacity; + } // Calculate the full transform for this item. QTransform transform = parentTransform; @@ -5113,7 +5130,8 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) break; drawSubtreeRecursive(child, painter, transform, viewTransform, - exposedRegion, widget, optimizationFlags); + exposedRegion, widget, optimizationFlags, + opacity); } } @@ -5130,7 +5148,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * painter->setWorldTransform(transform); if (clipsToShape) painter->setClipPath(item->shape(), Qt::IntersectClip); - painter->setOpacity(item->effectiveOpacity()); + painter->setOpacity(opacity); drawItemHelper(item, painter, &option, widget, false); @@ -5142,7 +5160,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (!dontDrawChildren) { for (; i < children.size(); ++i) { drawSubtreeRecursive(children.at(i), painter, transform, viewTransform, - exposedRegion, widget, optimizationFlags); + exposedRegion, widget, optimizationFlags, opacity); } } diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index e7e96f5..4facec3 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -256,7 +256,8 @@ public: void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, const QTransform &viewTransform, - const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags); + const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, + qreal parentOpacity = qreal(1.0)); void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); void processDirtyItemsRecursive(QGraphicsItem *item, const QTransform &); -- cgit v0.12 From e5ffaeb4bc9b76a96fdddb31460d4acdc564ae3c Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 16:04:59 +0200 Subject: Experimental change - disable itemChange notifications for move and transform. This change is only to test how much of an impact the itemChange mechanism has on performance. It's easy to revert later on. --- src/gui/graphicsview/qgraphicsitem.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 9159381..0b06613 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -39,6 +39,8 @@ ** ****************************************************************************/ +#define QGRAPHICSITEM_NO_ITEMCHANGE + /*! \class QGraphicsItem \brief The QGraphicsItem class is the base class for all graphical @@ -2036,8 +2038,12 @@ qreal QGraphicsItem::effectiveOpacity() const void QGraphicsItem::setOpacity(qreal opacity) { // Notify change. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE const QVariant newOpacityVariant(itemChange(ItemOpacityChange, double(opacity))); qreal newOpacity = newOpacityVariant.toDouble(); +#else + qreal newOpacity = opacity; +#endif // Normalize. newOpacity = qBound(0.0, newOpacity, 1.0); @@ -2049,7 +2055,9 @@ void QGraphicsItem::setOpacity(qreal opacity) d_ptr->opacity = newOpacity; // Notify change. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE itemChange(ItemOpacityHasChanged, newOpacity); +#endif // Update. if (d_ptr->scene) @@ -2499,10 +2507,14 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) return; // Notify the item that the position is changing. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE const QVariant newPosVariant(q->itemChange(QGraphicsItem::ItemPositionChange, pos)); QPointF newPos = newPosVariant.toPointF(); if (newPos == this->pos) return; +#else + QPointF newPos = pos; +#endif // Update and repositition. inSetPosHelper = 1; @@ -2512,7 +2524,9 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) this->pos = newPos; // Send post-notification. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE q->itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); +#endif inSetPosHelper = 0; } @@ -2874,18 +2888,22 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) return; // Notify the item that the transformation matrix is changing. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE const QVariant newTransformVariant(itemChange(ItemTransformChange, qVariantFromValue(newTransform))); newTransform = qVariantValue(newTransformVariant); if (*d_ptr->transform == newTransform) return; +#endif // Update and set the new transformation. prepareGeometryChange(); *d_ptr->transform = newTransform; // Send post-notification. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE itemChange(ItemTransformHasChanged, newTransformVariant); +#endif } /*! -- cgit v0.12 From d705abe962e309318ecad45064cbf61a2ffc79e2 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 16:05:55 +0200 Subject: Experimental change: replace all updates with repaints. This seems to be the only way to get a high frame rate, regardless of the performance of painting and all. --- src/gui/graphicsview/qgraphicsview.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 354feae..e205985 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -815,11 +815,11 @@ void QGraphicsViewPrivate::processPendingUpdates() if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) { if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) - viewport->update(dirtyBoundingRect); + viewport->repaint(dirtyBoundingRect); else - viewport->update(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); + viewport->repaint(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); } else { - viewport->update(dirtyRegion); // Already adjusted in updateRect/Region. + viewport->repaint(dirtyRegion); // Already adjusted in updateRect/Region. } dirtyBoundingRect = QRect(); @@ -829,7 +829,7 @@ void QGraphicsViewPrivate::processPendingUpdates() void QGraphicsViewPrivate::updateAll() { Q_Q(QGraphicsView); - q->viewport()->update(); + q->viewport()->repaint(); fullUpdatePending = true; dirtyBoundingRect = QRect(); dirtyRegion = QRegion(); @@ -846,13 +846,13 @@ void QGraphicsViewPrivate::updateRegion(const QRegion &r) switch (viewportUpdateMode) { case QGraphicsView::FullViewportUpdate: fullUpdatePending = true; - q->viewport()->update(); + q->viewport()->repaint(); break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r.boundingRect(); if (dirtyBoundingRect.contains(q->viewport()->rect())) { fullUpdatePending = true; - q->viewport()->update(); + q->viewport()->repaint(); } break; case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE @@ -882,13 +882,13 @@ void QGraphicsViewPrivate::updateRect(const QRect &r) switch (viewportUpdateMode) { case QGraphicsView::FullViewportUpdate: fullUpdatePending = true; - q->viewport()->update(); + q->viewport()->repaint(); break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r; if (dirtyBoundingRect.contains(q->viewport()->rect())) { fullUpdatePending = true; - q->viewport()->update(); + q->viewport()->repaint(); } break; case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE -- cgit v0.12 From c714b0e5527377bf3189b15a3bea0063f8aecebf Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 16:47:08 +0200 Subject: Avoid recursive repaint by calling update() when there's a full scene update. --- src/gui/graphicsview/qgraphicsview.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index e205985..7f6fd5e 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -829,7 +829,7 @@ void QGraphicsViewPrivate::processPendingUpdates() void QGraphicsViewPrivate::updateAll() { Q_Q(QGraphicsView); - q->viewport()->repaint(); + q->viewport()->update(); fullUpdatePending = true; dirtyBoundingRect = QRect(); dirtyRegion = QRegion(); -- cgit v0.12 From 80321b092fa35eb398f3aaf6a549f20fc4a94624 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 2 Jun 2009 09:23:04 +0200 Subject: Only repaint in QGraphicsViewPrivate::processPendingUpdates() Convert some repaint() calls back to updates(). This ensures that any updates triggered before this call are processed normally, while still keeping the synchronous repaint() call intact. Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsview.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 7f6fd5e..2515069 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -846,13 +846,13 @@ void QGraphicsViewPrivate::updateRegion(const QRegion &r) switch (viewportUpdateMode) { case QGraphicsView::FullViewportUpdate: fullUpdatePending = true; - q->viewport()->repaint(); + q->viewport()->update(); break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r.boundingRect(); if (dirtyBoundingRect.contains(q->viewport()->rect())) { fullUpdatePending = true; - q->viewport()->repaint(); + q->viewport()->update(); } break; case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE @@ -882,13 +882,13 @@ void QGraphicsViewPrivate::updateRect(const QRect &r) switch (viewportUpdateMode) { case QGraphicsView::FullViewportUpdate: fullUpdatePending = true; - q->viewport()->repaint(); + q->viewport()->update(); break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r; if (dirtyBoundingRect.contains(q->viewport()->rect())) { fullUpdatePending = true; - q->viewport()->repaint(); + q->viewport()->update(); } break; case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE -- cgit v0.12 From bc3804458f29c8f13426ef53fcbacbf0877fc896 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 2 Jun 2009 10:14:26 +0200 Subject: Fix QGraphicsScene::drawItems() to use the recursive path as well. This change also changes the direct painting path to be opt-in as a temporary testing measure to see what's broken when using the old code path. --- src/gui/graphicsview/qgraphicsscene.cpp | 130 +++++--------------------------- src/gui/graphicsview/qgraphicsscene_p.h | 2 +- src/gui/graphicsview/qgraphicsview.cpp | 56 +++----------- src/gui/graphicsview/qgraphicsview.h | 2 +- src/gui/graphicsview/qgraphicsview_p.h | 1 + 5 files changed, 34 insertions(+), 157 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 1d33361..30c7f97 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5048,6 +5048,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * const QTransform &viewTransform, const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, + QList *topLevelItems, qreal parentOpacity) { // Calculate opacity. @@ -5111,7 +5112,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } // Find and sort children. - QList &children = item ? item->d_ptr->children : topLevelItems; + QList &children = item ? item->d_ptr->children : (topLevelItems ? *topLevelItems : this->topLevelItems); if (!dontDrawChildren) { if (item && item->d_ptr->needSortChildren) { item->d_ptr->needSortChildren = 0; @@ -5123,7 +5124,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } // Draw children behind - int i; + int i = 0; if (!dontDrawChildren) { for (i = 0; i < children.size(); ++i) { QGraphicsItem *child = children.at(i); @@ -5131,7 +5132,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * break; drawSubtreeRecursive(child, painter, transform, viewTransform, exposedRegion, widget, optimizationFlags, - opacity); + 0, opacity); } } @@ -5160,7 +5161,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (!dontDrawChildren) { for (; i < children.size(); ++i) { drawSubtreeRecursive(children.at(i), painter, transform, viewTransform, - exposedRegion, widget, optimizationFlags, opacity); + exposedRegion, widget, optimizationFlags, 0, opacity); } } @@ -5321,118 +5322,27 @@ void QGraphicsScene::drawItems(QPainter *painter, const QStyleOptionGraphicsItem options[], QWidget *widget) { Q_D(QGraphicsScene); - - // Detect if painter state protection is disabled. QTransform viewTransform = painter->worldTransform(); - QVarLengthArray childClippers; + Q_UNUSED(options); + // Draw each toplevel recursively. + QGraphicsView *view = widget ? qobject_cast(widget->parentWidget()) : 0; + QList topLevelItems; for (int i = 0; i < numItems; ++i) { - QGraphicsItem *item = items[i]; - if (!(item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)) { - if (!childClippers.isEmpty()) { - // Item is not clipped to any ancestor: pop all current clippers. - for (int i = 0; i < childClippers.size(); ++i) - painter->restore(); - childClippers.clear(); - } - } else { - // Item is clipped to an ancestor, which may or may not be in our - // child clipper list. Let's start by finding the item's closest - // clipping ancestor. - QGraphicsItem *clipParent = item->parentItem(); - while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)) - clipParent = clipParent->parentItem(); - - // Pop any in-between clippers. If the clipper is unknown, pop - // them all. ### QVarLengthArray::lastIndexOf(). - int index = -1; - for (int n = childClippers.size() - 1; n >= 0; --n) { - if (childClippers[n] == clipParent) { - index = n; - break; - } - } - if (index != -1) { - int toPop = childClippers.size() - index - 1; - if (toPop > 0) { - for (int i = 0; i < toPop; ++i) - painter->restore(); - childClippers.resize(index + 1); - } - } - - // Sanity check - if (!childClippers.isEmpty()) - Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent); - - // If the clipper list is empty at this point, but we're still - // clipped to an ancestor, then we need to build the clip chain - // ourselves. There is only one case that can produce this issue: - // This item is stacked behind an ancestor: - // ItemStacksBehindParent. - if (childClippers.isEmpty()) { - Q_ASSERT(clipParent != 0); - // Build a stack of clippers. - QVarLengthArray clippers; - QGraphicsItem *p = clipParent; - do { - if (p->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape) - clippers.append(p); - } while ((p = p->parentItem()) && (p->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren)); - - // ### This code path can also use the itemTransform - // optimization, but it's hit very rarely. - for (int i = clippers.size() - 1; i >= 0; --i) { - QGraphicsItem *clipper = clippers[i]; - painter->setWorldTransform(clipper->deviceTransform(viewTransform), false); - - childClippers.append(clipper); - painter->save(); - painter->setClipPath(clipper->shape(), Qt::IntersectClip); - } - Q_ASSERT(childClippers[childClippers.size() - 1] == clipParent); - } - } - - // Set up the painter transform - if (item->d_ptr->hasValidDeviceTransform) { - painter->setWorldTransform(item->d_ptr->deviceTransform); - item->d_ptr->hasValidDeviceTransform = 0; - } else { - painter->setWorldTransform(item->deviceTransform(viewTransform), false); - } - - // Save painter - bool saveState = (d->painterStateProtection || (item->flags() & QGraphicsItem::ItemClipsToShape)); - if (saveState) - painter->save(); - - // Set local clip - if (item->flags() & QGraphicsItem::ItemClipsToShape) - painter->setClipPath(item->shape(), Qt::IntersectClip); - - // Setup opacity - painter->setOpacity(item->effectiveOpacity()); - - // Draw the item - d->drawItemHelper(item, painter, &options[i], widget, d->painterStateProtection); - const QRect paintedViewBoundingRect = painter->worldTransform().mapRect(options[i].rect).adjusted(-1, -1, 1, 1); - item->d_ptr->paintedViewBoundingRects.insert(widget, paintedViewBoundingRect); - - if (saveState) - painter->restore(); - - if (item->flags() & QGraphicsItem::ItemClipsChildrenToShape) { - // Clip descendents to this item's shape, and keep the painter - // saved. - childClippers.append(item); - painter->save(); - painter->setClipPath(item->shape(), Qt::IntersectClip); + QGraphicsItem *item = items[i]->topLevelItem(); + topLevelItems << item; + + if (!item->d_ptr->itemDiscovered) { + item->d_ptr->itemDiscovered = 1; + d->drawSubtreeRecursive(item, painter, viewTransform, viewTransform, + view->d_func()->exposedRegion, widget, + view->optimizationFlags()); } } - for (int i = 0; i < childClippers.size(); ++i) - painter->restore(); + // Reset discovery bits. + for (int i = 0; i < topLevelItems.size(); ++i) + topLevelItems.at(i)->d_ptr->itemDiscovered = 0; painter->setWorldTransform(viewTransform); } diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 4facec3..2a036e3 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -257,7 +257,7 @@ public: void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, const QTransform &viewTransform, const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, - qreal parentOpacity = qreal(1.0)); + QList *topLevelItems = 0, qreal parentOpacity = qreal(1.0)); void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); void processDirtyItemsRecursive(QGraphicsItem *item, const QTransform &); diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 2515069..8bafe50 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -39,8 +39,6 @@ ** ****************************************************************************/ -//#define QGRAPHICSVIEW_DEBUG - static const int QGRAPHICSVIEW_REGION_RECT_THRESHOLD = 50; static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < 2^9 @@ -3236,12 +3234,12 @@ void QGraphicsView::paintEvent(QPaintEvent *event) d->scene->d_func()->painterStateProtection = !(d->optimizationFlags & DontSavePainterState); // Determine the exposed region - QRegion exposedRegion = event->region(); + d->exposedRegion = event->region(); if (!d->accelerateScrolling) - exposedRegion = viewport()->rect(); + d->exposedRegion = viewport()->rect(); else if (d->viewportUpdateMode == BoundingRectViewportUpdate) - exposedRegion = event->rect(); - QRectF exposedSceneRect = mapToScene(exposedRegion.boundingRect()).boundingRect(); + d->exposedRegion = event->rect(); + QRectF exposedSceneRect = mapToScene(d->exposedRegion.boundingRect()).boundingRect(); // Set up the painter QPainter painter(viewport()); @@ -3258,16 +3256,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) const QTransform viewTransform = viewportTransform(); painter.setTransform(viewTransform, true); -#ifdef QGRAPHICSVIEW_DEBUG - QTime stopWatch; - stopWatch.start(); - qDebug() << "QGraphicsView::paintEvent(" << exposedRegion << ')'; -#endif - - // Find all exposed items - bool allItems = false; - QList itemList = d->findItems(exposedRegion, &allItems); - + // Draw background if ((d->cacheMode & CacheBackground) #ifdef Q_WS_X11 && X11->use_xrender @@ -3309,18 +3298,14 @@ void QGraphicsView::paintEvent(QPaintEvent *event) painter.restore(); } -#ifdef QGRAPHICSVIEW_DEBUG - int backgroundTime = stopWatch.elapsed() - exposedTime; -#endif - - static int directEnv = qgetenv("QGRAPHICSVIEW_DIRECT").toInt(); - if (directEnv || (d->optimizationFlags & BypassDrawItems)) { - d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, viewTransform, exposedRegion, - viewport(), d->optimizationFlags); + // Items + if ((d->optimizationFlags & IndirectPainting)) { + d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, viewTransform, d->exposedRegion, + viewport(), d->optimizationFlags, 0); } else { // Find all exposed items bool allItems = false; - QList itemList = d->findItems(exposedRegion, &allItems); + QList itemList = d->findItems(d->exposedRegion, &allItems); if (!itemList.isEmpty()) { // Generate the style options. @@ -3328,24 +3313,16 @@ void QGraphicsView::paintEvent(QPaintEvent *event) QGraphicsItem **itemArray = &itemList[0]; // Relies on QList internals, but is perfectly valid. QStyleOptionGraphicsItem *styleOptionArray = d->allocStyleOptionsArray(numItems); for (int i = 0; i < numItems; ++i) - itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], viewTransform, exposedRegion, allItems); + itemArray[i]->d_ptr->initStyleOption(&styleOptionArray[i], viewTransform, d->exposedRegion, allItems); // Draw the items. drawItems(&painter, numItems, itemArray, styleOptionArray); d->freeStyleOptionsArray(styleOptionArray); } } -#ifdef QGRAPHICSVIEW_DEBUG - int itemsTime = stopWatch.elapsed() - exposedTime - backgroundTime; -#endif - // Foreground drawForeground(&painter, exposedSceneRect); -#ifdef QGRAPHICSVIEW_DEBUG - int foregroundTime = stopWatch.elapsed() - exposedTime - backgroundTime - itemsTime; -#endif - #ifndef QT_NO_RUBBERBAND // Rubberband if (d->rubberBanding && !d->rubberBandRect.isEmpty()) { @@ -3367,17 +3344,6 @@ void QGraphicsView::paintEvent(QPaintEvent *event) painter.end(); -#ifdef QGRAPHICSVIEW_DEBUG - qDebug() << "\tItem discovery....... " << exposedTime << "msecs (" << itemList.size() << "items," - << (exposedTime > 0 ? (itemList.size() * 1000.0 / exposedTime) : -1) << "/ sec )"; - qDebug() << "\tDrawing background... " << backgroundTime << "msecs (" << exposedRegion.numRects() << "segments )"; - qDebug() << "\tDrawing items........ " << itemsTime << "msecs (" - << (itemsTime > 0 ? (itemList.size() * 1000.0 / itemsTime) : -1) << "/ sec )"; - qDebug() << "\tDrawing foreground... " << foregroundTime << "msecs (" << exposedRegion.numRects() << "segments )"; - qDebug() << "\tTotal rendering time: " << stopWatch.elapsed() << "msecs (" - << (stopWatch.elapsed() > 0 ? (1000.0 / stopWatch.elapsed()) : -1.0) << "fps )"; -#endif - // Restore painter state protection. d->scene->d_func()->painterStateProtection = true; } diff --git a/src/gui/graphicsview/qgraphicsview.h b/src/gui/graphicsview/qgraphicsview.h index deed1d0..b7a9906 100644 --- a/src/gui/graphicsview/qgraphicsview.h +++ b/src/gui/graphicsview/qgraphicsview.h @@ -113,7 +113,7 @@ public: DontClipPainter = 0x1, // obsolete DontSavePainterState = 0x2, DontAdjustForAntialiasing = 0x4, - BypassDrawItems = 0x8 + IndirectPainting = 0x8 }; Q_DECLARE_FLAGS(OptimizationFlags, OptimizationFlag) diff --git a/src/gui/graphicsview/qgraphicsview_p.h b/src/gui/graphicsview/qgraphicsview_p.h index 637687b..814e476 100644 --- a/src/gui/graphicsview/qgraphicsview_p.h +++ b/src/gui/graphicsview/qgraphicsview_p.h @@ -167,6 +167,7 @@ public: void updateRect(const QRect &rect); void updateRegion(const QRegion ®ion); bool updateSceneSlotReimplementedChecked; + QRegion exposedRegion; QList findItems(const QRegion &exposedRegion, bool *allItems) const; }; -- cgit v0.12 From 1fc2406f35594706a9aafa9374694cf0a65cee30 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 2 Jun 2009 11:26:30 +0200 Subject: Refactor QTransform combining code, and mark all code that combines. This change introduces two helper functions in QGraphicsItemPrivate, that combine the item's transform into the current transform, effectively merging the code that calculates any item's combined to-parent transform. This makes the code more readable, and also makes it easier for us to reintroduce the componentized transform API in QGraphicsItem (which was previously reverted). --- src/gui/graphicsview/qgraphicsitem.cpp | 131 +++++++++++++++++++------------- src/gui/graphicsview/qgraphicsitem_p.h | 3 + src/gui/graphicsview/qgraphicsscene.cpp | 30 ++++---- src/gui/graphicsview/qgraphicsview.cpp | 3 +- 4 files changed, 98 insertions(+), 69 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 0b06613..e1389b5 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -787,6 +787,49 @@ bool QGraphicsItemPrivate::itemIsUntransformable() const || (ancestorFlags & AncestorIgnoresTransformations); } + +/*! + \internal + + Combines this item's position and transform onto \a transform. + + If you need to change this function (e.g., adding more transformation + modes / options), make sure to change all places marked with COMBINE. +*/ +void QGraphicsItemPrivate::combineTransformToParent(QTransform *x, const QTransform *viewTransform) const +{ + // COMBINE + if (viewTransform && itemIsUntransformable()) { + *x = q_ptr->deviceTransform(*viewTransform); + } else { + if (transform) + *x *= *transform; + if (!pos.isNull()) + *x *= QTransform::fromTranslate(pos.x(), pos.y()); + } +} + +/*! + \internal + + Combines this item's position and transform onto \a transform. + + If you need to change this function (e.g., adding more transformation + modes / options), make sure to change QGraphicsItem::deviceTransform() as + well. +*/ +void QGraphicsItemPrivate::combineTransformFromParent(QTransform *x, const QTransform *viewTransform) const +{ + // COMBINE + if (viewTransform && itemIsUntransformable()) { + *x = q_ptr->deviceTransform(*viewTransform); + } else { + x->translate(pos.x(), pos.y()); + if (transform) + *x = *transform * *x; + } +} + /*! \internal @@ -943,6 +986,7 @@ void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rec QGraphicsItemPrivate *childd = child->d_ptr; bool hasPos = !childd->pos.isNull(); if (hasPos || childd->transform) { + // COMBINE QTransform matrix; if (childd->transform) matrix = *childd->transform; @@ -2667,11 +2711,7 @@ QTransform QGraphicsItem::sceneTransform() const QTransform m; const QGraphicsItem *p = this; do { - if (p->d_ptr->transform) - m *= *p->d_ptr->transform; - const QPointF &pos = p->d_ptr->pos; - if (!pos.isNull()) - m *= QTransform::fromTranslate(pos.x(), pos.y()); + p->d_ptr->combineTransformToParent(&m); } while ((p = p->d_ptr->parent)); return m; } @@ -2723,6 +2763,8 @@ QTransform QGraphicsItem::deviceTransform(const QTransform &viewportTransform) c // First translate the base untransformable item. QPointF mappedPoint = (untransformedAncestor->sceneTransform() * viewportTransform).map(QPointF(0, 0)); + + // COMBINE QTransform matrix; matrix.translate(mappedPoint.x(), mappedPoint.y()); matrix = untransformedAncestor->transform() * matrix; @@ -2730,10 +2772,7 @@ QTransform QGraphicsItem::deviceTransform(const QTransform &viewportTransform) c // Then transform and translate all children. for (int i = 0; i < parents.size(); ++i) { const QGraphicsItem *parent = parents.at(i); - QPointF pos = parent->pos(); - QTransform moveMatrix; - moveMatrix.translate(pos.x(), pos.y()); - matrix = (parent->transform() * moveMatrix) * matrix; + parent->d_ptr->combineTransformFromParent(&matrix); } return matrix; @@ -2776,34 +2815,29 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co if (parent == other) { if (ok) *ok = true; - const QPointF &itemPos = d_ptr->pos; - if (itemPos.isNull()) - return d_ptr->transform ? *d_ptr->transform : QTransform(); - if (d_ptr->transform) - return *d_ptr->transform * QTransform::fromTranslate(itemPos.x(), itemPos.y()); - return QTransform::fromTranslate(itemPos.x(), itemPos.y()); + QTransform x; + d_ptr->combineTransformFromParent(&x); + return x; } // This is other's parent if (otherParent == this) { const QPointF &otherPos = other->d_ptr->pos; if (other->d_ptr->transform) { - QTransform otherToParent = *other->d_ptr->transform; - if (!otherPos.isNull()) - otherToParent *= QTransform::fromTranslate(otherPos.x(), otherPos.y()); + QTransform otherToParent; + other->d_ptr->combineTransformFromParent(&otherToParent); return otherToParent.inverted(ok); - } else { - if (ok) - *ok = true; - return QTransform::fromTranslate(-otherPos.x(), -otherPos.y()); } + if (ok) + *ok = true; + return QTransform::fromTranslate(-otherPos.x(), -otherPos.y()); } // Siblings if (parent == otherParent) { + // COMBINE const QPointF &itemPos = d_ptr->pos; const QPointF &otherPos = other->d_ptr->pos; - if (!d_ptr->transform && !other->d_ptr->transform) { QPointF delta = itemPos - otherPos; if (ok) @@ -2811,14 +2845,10 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co return QTransform::fromTranslate(delta.x(), delta.y()); } - QTransform itemToParent = QTransform::fromTranslate(itemPos.x(), itemPos.y()); - if (d_ptr->transform) - itemToParent = itemPos.isNull() ? *d_ptr->transform : *d_ptr->transform * itemToParent; - - QTransform otherToParent = QTransform::fromTranslate(otherPos.x(), otherPos.y()); - if (other->d_ptr->transform) - otherToParent = otherPos.isNull() ? *other->d_ptr->transform : *other->d_ptr->transform * otherToParent; - + QTransform itemToParent; + d_ptr->combineTransformFromParent(&itemToParent); + QTransform otherToParent; + other->d_ptr->combineTransformFromParent(&otherToParent); return itemToParent * otherToParent.inverted(ok); } @@ -2854,11 +2884,7 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co QTransform x; const QGraphicsItem *p = child; do { - const QGraphicsItemPrivate *pd = p->d_ptr; - if (pd->transform) - x *= *pd->transform; - if (!pd->pos.isNull()) - x *= QTransform::fromTranslate(pd->pos.x(), pd->pos.y()); + p->d_ptr->combineTransformToParent(&x); } while ((p = p->d_ptr->parent) && p != root); if (parentOfOther) return x.inverted(ok); @@ -3206,6 +3232,7 @@ QRectF QGraphicsItem::childrenBoundingRect() const QRectF QGraphicsItem::sceneBoundingRect() const { // Find translate-only offset + // COMBINE QPointF offset; const QGraphicsItem *parentItem = this; const QGraphicsItemPrivate *itemd; @@ -3910,11 +3937,13 @@ void QGraphicsItemPrivate::updateCachedClipPathFromSetPosHelper(const QPointF &n // Find closest clip ancestor and transform. Q_Q(QGraphicsItem); + // COMBINE QTransform thisToParentTransform = transform ? *transform * QTransform::fromTranslate(newPos.x(), newPos.y()) : QTransform::fromTranslate(newPos.x(), newPos.y()); QGraphicsItem *clipParent = parent; while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)) { + // COMBINE if (clipParent->d_ptr->transform) thisToParentTransform *= *clipParent->d_ptr->transform; if (!clipParent->d_ptr->pos.isNull()) { @@ -4145,13 +4174,7 @@ void QGraphicsItem::scroll(qreal dx, qreal dy, const QRectF &rect) static const QLineF left(0, 0, -1, 0); static const QLineF right(0, 0, 1, 0); - QTransform deviceTr; - if (d->itemIsUntransformable()) { - deviceTr = deviceTransform(view->viewportTransform()); - } else { - deviceTr = sceneTransform() * view->viewportTransform(); - } - + QTransform deviceTr = deviceTransform(view->viewportTransform()); QRect deviceScrollRect = deviceTr.mapRect(scrollRect).toRect(); QLineF v1 = deviceTr.map(right); QLineF v2 = deviceTr.map(down); @@ -4283,6 +4306,7 @@ QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPointF &point */ QPointF QGraphicsItem::mapToParent(const QPointF &point) const { + // COMBINE if (!d_ptr->transform) return point + d_ptr->pos; return d_ptr->transform->map(point) + d_ptr->pos; @@ -4350,6 +4374,7 @@ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QRectF &rect */ QPolygonF QGraphicsItem::mapToParent(const QRectF &rect) const { + // COMBINE if (!d_ptr->transform) return rect.translated(d_ptr->pos); return d_ptr->transform->map(rect).translated(d_ptr->pos); @@ -4419,6 +4444,7 @@ QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, const QRectF &rec */ QRectF QGraphicsItem::mapRectToParent(const QRectF &rect) const { + // COMBINE QRectF r = !d_ptr->transform ? rect : d_ptr->transform->mapRect(rect); return r.translated(d_ptr->pos); } @@ -4491,6 +4517,7 @@ QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, const QRectF &r */ QRectF QGraphicsItem::mapRectFromParent(const QRectF &rect) const { + // COMBINE QRectF r = rect.translated(-d_ptr->pos); return d_ptr->transform ? d_ptr->transform->inverted().mapRect(r) : r; } @@ -4551,6 +4578,7 @@ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPolygonF &p */ QPolygonF QGraphicsItem::mapToParent(const QPolygonF &polygon) const { + // COMBINE if (!d_ptr->transform) return polygon.translated(d_ptr->pos); return d_ptr->transform->map(polygon).translated(d_ptr->pos); @@ -4595,6 +4623,7 @@ QPainterPath QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPainterP */ QPainterPath QGraphicsItem::mapToParent(const QPainterPath &path) const { + // COMBINE if (!d_ptr->transform) return path.translated(d_ptr->pos); return d_ptr->transform->map(path).translated(d_ptr->pos); @@ -4646,6 +4675,7 @@ QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPointF &poi */ QPointF QGraphicsItem::mapFromParent(const QPointF &point) const { + // COMBINE if (d_ptr->transform) return d_ptr->transform->inverted().map(point - d_ptr->pos); return point - d_ptr->pos; @@ -4714,6 +4744,7 @@ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QRectF &re */ QPolygonF QGraphicsItem::mapFromParent(const QRectF &rect) const { + // COMBINE QRectF r = rect.translated(-d_ptr->pos); return d_ptr->transform ? d_ptr->transform->inverted().map(r) : r; } @@ -4770,6 +4801,7 @@ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPolygonF */ QPolygonF QGraphicsItem::mapFromParent(const QPolygonF &polygon) const { + // COMBINE QPolygonF p = polygon; p.translate(-d_ptr->pos); return d_ptr->transform ? d_ptr->transform->inverted().map(p) : p; @@ -4812,6 +4844,7 @@ QPainterPath QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPainte */ QPainterPath QGraphicsItem::mapFromParent(const QPainterPath &path) const { + // COMBINE QPainterPath p(path); p.translate(-d_ptr->pos); return d_ptr->transform ? d_ptr->transform->inverted().map(p) : p; @@ -5540,21 +5573,13 @@ void QGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) if ((item->flags() & ItemIsMovable) && !QGraphicsItemPrivate::movableAncestorIsSelected(item)) { QPointF currentParentPos; QPointF buttonDownParentPos; - if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations) { + if (item->d_ptr->itemIsUntransformable()) { // Items whose ancestors ignore transformations need to // map screen coordinates to local coordinates, then map // those to the parent. QTransform viewToItemTransform = (item->deviceTransform(view->viewportTransform())).inverted(); currentParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->screenPos())))); buttonDownParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton))))); - } else if (item->flags() & ItemIgnoresTransformations) { - // Root items that ignore transformations need to - // calculate their diff by mapping viewport coordinates - // directly to parent coordinates. - QTransform viewToParentTransform = (item->transform().translate(item->d_ptr->pos.x(), item->d_ptr->pos.y())) - * (item->sceneTransform() * view->viewportTransform()).inverted(); - currentParentPos = viewToParentTransform.map(QPointF(view->mapFromGlobal(event->screenPos()))); - buttonDownParentPos = viewToParentTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton)))); } else { // All other items simply map from the scene. currentParentPos = item->mapToParent(item->mapFromScene(event->scenePos())); @@ -8884,6 +8909,8 @@ void QGraphicsItemGroup::addToGroup(QGraphicsItem *item) return; } + // COMBINE + // ### Use itemTransform() instead. QTransform oldSceneMatrix = item->sceneTransform(); item->setPos(mapFromItem(item, 0, 0)); item->setParentItem(this); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 80b1fb4..7fe7d95 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -163,6 +163,9 @@ public: QPointF genericMapFromScene(const QPointF &pos, const QWidget *viewport) const; bool itemIsUntransformable() const; + void combineTransformToParent(QTransform *x, const QTransform *viewTransform = 0) const; + void combineTransformFromParent(QTransform *x, const QTransform *viewTransform = 0) const; + // ### Qt 5: Remove. Workaround for reimplementation added after Qt 4.4. virtual QVariant inputMethodQueryHelper(Qt::InputMethodQuery query) const; static bool movableAncestorIsSelected(const QGraphicsItem *item); diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 30c7f97..b1d1742 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5075,14 +5075,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * QRect viewBoundingRect; if (item) { if (!item->d_ptr->hasValidDeviceTransform) { - if (item->d_ptr->itemIsUntransformable()) { - transform = item->deviceTransform(viewTransform); - } else { - const QPointF &pos = item->d_ptr->pos; - transform.translate(pos.x(), pos.y()); - if (item->d_ptr->transform) - transform = *item->d_ptr->transform * transform; - } + item->d_ptr->combineTransformFromParent(&transform, &viewTransform); } else { transform = item->d_ptr->deviceTransform; item->d_ptr->hasValidDeviceTransform = 0; @@ -5226,12 +5219,10 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, cons QTransform transform = parentTransform; if (item) { if (item->d_ptr->itemIsUntransformable()) { - transform = item->deviceTransform(views.at(0)->viewportTransform()); + QTransform x = views.at(0)->viewportTransform(); + item->d_ptr->combineTransformFromParent(&transform, &x); } else { - const QPointF &pos = item->d_ptr->pos; - transform.translate(pos.x(), pos.y()); - if (item->d_ptr->transform) - transform = *item->d_ptr->transform * transform; + item->d_ptr->combineTransformFromParent(&transform); } } @@ -5325,8 +5316,16 @@ void QGraphicsScene::drawItems(QPainter *painter, QTransform viewTransform = painter->worldTransform(); Q_UNUSED(options); - // Draw each toplevel recursively. + // Determine view, expose and flags. QGraphicsView *view = widget ? qobject_cast(widget->parentWidget()) : 0; + QRegion expose; + QGraphicsView::OptimizationFlags flags; + if (view) { + expose = view->d_func()->exposedRegion; + flags = view->optimizationFlags(); + } + + // Draw each toplevel recursively. QList topLevelItems; for (int i = 0; i < numItems; ++i) { QGraphicsItem *item = items[i]->topLevelItem(); @@ -5335,8 +5334,7 @@ void QGraphicsScene::drawItems(QPainter *painter, if (!item->d_ptr->itemDiscovered) { item->d_ptr->itemDiscovered = 1; d->drawSubtreeRecursive(item, painter, viewTransform, viewTransform, - view->d_func()->exposedRegion, widget, - view->optimizationFlags()); + expose, widget, flags); } } diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 8bafe50..d410a53 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -746,6 +746,7 @@ QRect QGraphicsViewPrivate::mapToViewRect(const QGraphicsItem *item, const QRect } // Translate-only + // COMBINE QPointF offset; const QGraphicsItem *parentItem = item; const QGraphicsItemPrivate *itemd; @@ -783,7 +784,7 @@ QRegion QGraphicsViewPrivate::mapToViewRegion(const QGraphicsItem *item, const Q const_cast(this)->updateScroll(); // Accurate bounding region - QTransform itv = item->sceneTransform() * q->viewportTransform(); + QTransform itv = item->deviceTransform(q->viewportTransform()); return item->boundingRegion(itv) & itv.mapRect(rect).toAlignedRect(); } -- cgit v0.12 From 99318bd50bf044c8202f670b667dc990ce90cfe1 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 2 Jun 2009 12:39:02 +0200 Subject: Fix sorting bug and ensure render functions work. Make direct default. Mark the children list for sorting when the Z value for items changes. Change the signature of the recursive draw function slightly so that the expose region is optional, and ensure we don't intersect with this region if it's not available. This change also flips the direct painting so that the default is to use the recursive approach. --- src/gui/graphicsview/qgraphicsitem.cpp | 1 + src/gui/graphicsview/qgraphicsscene.cpp | 24 +++++++++++------------- src/gui/graphicsview/qgraphicsscene_p.h | 2 +- src/gui/graphicsview/qgraphicsview.cpp | 4 ++-- 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index e1389b5..17cab45 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -3151,6 +3151,7 @@ void QGraphicsItem::setZValue(qreal z) if (newZ == d_ptr->z) return; d_ptr->z = newZ; + d_ptr->needSortChildren = 1; if (d_ptr->scene) { d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true); diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index b1d1742..fcb6352 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -2522,7 +2522,6 @@ QList QGraphicsScene::items(const QPointF &pos) const return d->items_helper(pos); } - /*! \fn QList QGraphicsScene::items(const QRectF &rectangle, Qt::ItemSelectionMode mode) const @@ -5046,7 +5045,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, const QTransform &viewTransform, - const QRegion &exposedRegion, QWidget *widget, + QRegion *exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, QList *topLevelItems, qreal parentOpacity) @@ -5084,10 +5083,11 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (!brect.size().isNull()) { // ### This does not take the clip into account. _q_adjustRect(&brect); - const QRect paintedViewBoundingRect = transform.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); - item->d_ptr->paintedViewBoundingRects.insert(widget, paintedViewBoundingRect); - viewBoundingRect = paintedViewBoundingRect & exposedRegion.boundingRect(); - } + viewBoundingRect = transform.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); + item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect); + if (exposedRegion) + viewBoundingRect &= exposedRegion->boundingRect(); + } } bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); @@ -5132,7 +5132,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Draw item if (!dontDrawItem) { QStyleOptionGraphicsItem option; - item->d_ptr->initStyleOption(&option, transform, exposedRegion); + item->d_ptr->initStyleOption(&option, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); bool savePainter = clipsToShape || !(optimizationFlags & QGraphicsView::DontSavePainterState); @@ -5143,7 +5143,6 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (clipsToShape) painter->setClipPath(item->shape(), Qt::IntersectClip); painter->setOpacity(opacity); - drawItemHelper(item, painter, &option, widget, false); if (savePainter) @@ -5318,20 +5317,19 @@ void QGraphicsScene::drawItems(QPainter *painter, // Determine view, expose and flags. QGraphicsView *view = widget ? qobject_cast(widget->parentWidget()) : 0; - QRegion expose; + QRegion *expose = 0; QGraphicsView::OptimizationFlags flags; if (view) { - expose = view->d_func()->exposedRegion; + expose = &view->d_func()->exposedRegion; flags = view->optimizationFlags(); } - // Draw each toplevel recursively. + // Find all toplevels, they are already sorted. QList topLevelItems; for (int i = 0; i < numItems; ++i) { QGraphicsItem *item = items[i]->topLevelItem(); - topLevelItems << item; - if (!item->d_ptr->itemDiscovered) { + topLevelItems << item; item->d_ptr->itemDiscovered = 1; d->drawSubtreeRecursive(item, painter, viewTransform, viewTransform, expose, widget, flags); diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 2a036e3..2e82a4a 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -256,7 +256,7 @@ public: void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, const QTransform &viewTransform, - const QRegion &exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, + QRegion *exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, QList *topLevelItems = 0, qreal parentOpacity = qreal(1.0)); void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index d410a53..caa3ffc 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3300,8 +3300,8 @@ void QGraphicsView::paintEvent(QPaintEvent *event) } // Items - if ((d->optimizationFlags & IndirectPainting)) { - d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, viewTransform, d->exposedRegion, + if (!(d->optimizationFlags & IndirectPainting)) { + d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, viewTransform, &d->exposedRegion, viewport(), d->optimizationFlags, 0); } else { // Find all exposed items -- cgit v0.12 From 1b78999dcd5512ce46e2fac20811ad63f3e93ec0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Tue, 2 Jun 2009 12:46:32 +0200 Subject: Graphics View cleanup: Remove iterative processing of dirty items. The recursive approach is faster and fits better into the new scene transform cache we'll do later. --- src/gui/graphicsview/qgraphicsitem_p.h | 13 ++--- src/gui/graphicsview/qgraphicsscene.cpp | 89 +++------------------------------ src/gui/graphicsview/qgraphicsscene_p.h | 14 ------ 3 files changed, 11 insertions(+), 105 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 7fe7d95..d962ad0 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -141,12 +141,11 @@ public: emptyClipPath(0), inSetPosHelper(0), needSortChildren(1), + allChildrenDirty(0), + fullUpdatePending(0), flags(0), dirtyChildrenBoundingRect(1), - inDirtyList(0), paintedViewBoundingRectsNeedRepaint(0), - allChildrenDirty(0), - fullUpdatePending(0), hasValidDeviceTransform(0), globalStackingOrder(-1), q_ptr(0) @@ -342,17 +341,15 @@ public: quint32 emptyClipPath : 1; quint32 inSetPosHelper : 1; quint32 needSortChildren : 1; - quint32 unused : 2; + quint32 allChildrenDirty : 1; + quint32 fullUpdatePending : 1; // New 32 bits quint32 flags : 11; quint32 dirtyChildrenBoundingRect : 1; - quint32 inDirtyList : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; - quint32 allChildrenDirty : 1; - quint32 fullUpdatePending : 1; quint32 hasValidDeviceTransform : 1; - quint32 padding : 15; // feel free to use + quint32 padding : 18; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index fcb6352..eac057e 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -614,11 +614,6 @@ void QGraphicsScenePrivate::_q_emitUpdated() } } - // Ensure all dirty items's current positions are recorded in the list of - // updated rects. - for (int i = 0; i < dirtyItems.size(); ++i) - updatedRects += dirtyItems.at(i)->sceneBoundingRect(); - // Notify the changes to anybody interested. QList oldUpdatedRects; oldUpdatedRects = updateAll ? (QList() << q->sceneRect()) : updatedRects; @@ -678,74 +673,12 @@ void QGraphicsScenePrivate::_q_polishItems() void QGraphicsScenePrivate::_q_processDirtyItems() { - static int useDirtyListEnv = qgetenv("QT_GV_USE_DIRTY_LIST").toInt(); processDirtyItemsEmitted = false; - if (updateAll) { - if (useDirtyListEnv) { - for (int i = 0; i < dirtyItems.size(); ++i) - resetDirtyItem(dirtyItems.at(i)); - dirtyItems.clear(); - } - return; - } - - if (!useDirtyListEnv) { - processDirtyItemsRecursive(0, views.at(0)->viewportTransform()); - for (int i = 0; i < views.size(); ++i) - views.at(i)->d_func()->processPendingUpdates(); + if (updateAll) return; - } - - for (int i = 0; i < dirtyItems.size(); ++i) { - QGraphicsItem *item = dirtyItems.at(i); - QGraphicsView *view = views.at(0); - QGraphicsViewPrivate *viewPrivate = view->d_func(); - const QTransform deviceTransform = item->deviceTransform(view->viewportTransform()); - QRectF dirtyRect = adjustedItemBoundingRect(item); - if (!item->d_ptr->fullUpdatePending) { - _q_adjustRect(&item->d_ptr->needsRepaint); - dirtyRect &= item->d_ptr->needsRepaint; - } - - if (item->d_ptr->allChildrenDirty && !item->d_ptr->children.isEmpty() - && !item->d_ptr->childrenClippedToShape()) { - QRectF childrenBounds = item->childrenBoundingRect(); - _q_adjustRect(&childrenBounds); - dirtyRect |= childrenBounds; - } - - if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) - viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); - - bool dirtyRectOutsideViewport = false; - if (item->d_ptr->hasBoundingRegionGranularity) { - const QRegion dirtyViewRegion = deviceTransform.map(QRegion(dirtyRect.toRect())) - & viewPrivate->viewport->rect(); - if (!dirtyViewRegion.isEmpty()) - viewPrivate->updateRegion(dirtyViewRegion); - else - dirtyRectOutsideViewport = true; - } else { - const QRect dirtyViewRect = deviceTransform.mapRect(dirtyRect).toRect() - & viewPrivate->viewport->rect(); - if (!dirtyViewRect.isEmpty()) - viewPrivate->updateRect(dirtyViewRect); - else - dirtyRectOutsideViewport = true; - } - if (!dirtyRectOutsideViewport) { - // We know for sure this item will be process in the paint event, hence - // store its device transform and re-use it when drawing. - item->d_ptr->hasValidDeviceTransform = 1; - item->d_ptr->deviceTransform = deviceTransform; - } - - resetDirtyItem(item); - } - - dirtyItems.clear(); + processDirtyItemsRecursive(0, views.at(0)->viewportTransform()); for (int i = 0; i < views.size(); ++i) views.at(i)->d_func()->processPendingUpdates(); } @@ -808,7 +741,6 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) hoverItems.removeAll(item); cachedItemsUnderMouse.removeAll(item); unpolishedItems.removeAll(item); - removeFromDirtyItems(item); //We remove all references of item from the sceneEventFilter arrays QMultiMap::iterator iterator = sceneEventFilters.begin(); @@ -3347,7 +3279,6 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) d->pendingUpdateItems.removeAll(item); d->cachedItemsUnderMouse.removeAll(item); d->unpolishedItems.removeAll(item); - d->removeFromDirtyItems(item); //We remove all references of item from the sceneEventFilter arrays QMultiMap::iterator iterator = d->sceneEventFilters.begin(); @@ -5195,18 +5126,10 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b item->d_ptr->dirtyChildren = 1; } - static int useDirtyListEnv = qgetenv("QT_GV_USE_DIRTY_LIST").toInt(); - if (useDirtyListEnv) { - if (!item->d_ptr->inDirtyList) { - dirtyItems.append(item); - item->d_ptr->inDirtyList = 1; - } - } else { - QGraphicsItem *p = item->d_ptr->parent; - while (p && !p->d_ptr->dirtyChildren) { - p->d_ptr->dirtyChildren = 1; - p = p->d_ptr->parent; - } + QGraphicsItem *p = item->d_ptr->parent; + while (p && !p->d_ptr->dirtyChildren) { + p->d_ptr->dirtyChildren = 1; + p = p->d_ptr->parent; } } diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 2e82a4a..9e9ef6b 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -112,7 +112,6 @@ public: QSet selectedItems; QList unindexedItems; QList indexedItems; - QVector dirtyItems; QList pendingUpdateItems; QList unpolishedItems; QList topLevelItems; @@ -268,24 +267,11 @@ public: item->d_ptr->dirty = 0; item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0; item->d_ptr->dirtyChildren = 0; - item->d_ptr->inDirtyList = 0; item->d_ptr->needsRepaint = QRectF(); item->d_ptr->allChildrenDirty = 0; item->d_ptr->fullUpdatePending = 0; } - inline void removeFromDirtyItems(QGraphicsItem *item) - { - int i = 0; - while (i < dirtyItems.size()) { - if (dirtyItems.at(i) == item) - dirtyItems.remove(i); - else - ++i; - } - resetDirtyItem(item); - } - QStyle *style; QFont font; void setFont_helper(const QFont &font); -- cgit v0.12 From d44332954b2a8e66ba4129c230e8ccc65fd972ea Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 2 Jun 2009 13:50:28 +0200 Subject: Don't construct new style option objects in a tight loop. The QStyleOption constructor is expensive, as it allocates a QFont, a QPalette and a QFontMetrics. By simply reusing a temporary style option object instead we carve away wasted cycles. Reviewed-by: Ariya --- src/gui/graphicsview/qgraphicsscene.cpp | 17 ++++++++--------- src/gui/graphicsview/qgraphicsscene_p.h | 3 +++ 2 files changed, 11 insertions(+), 9 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index eac057e..0c679de 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -4763,7 +4763,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte // Generate the item's exposedRect and map its list of expose // rects to device coordinates. - QStyleOptionGraphicsItem cacheOption = *option; + styleOptionTmp = *option; QRegion pixmapExposed; QRectF exposedRect; if (!itemCache->allExposed) { @@ -4775,11 +4775,11 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } else { exposedRect = brect; } - cacheOption.exposedRect = exposedRect; + styleOptionTmp.exposedRect = exposedRect; // Render. _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(), - &cacheOption, painterStateProtection); + &styleOptionTmp, painterStateProtection); // insert this pixmap into the cache. itemCache->key = QPixmapCache::insert(pix); @@ -4940,12 +4940,12 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte foreach (QRect r, scrollExposure.rects()) br |= pixmapToItem.mapRect(r); } - QStyleOptionGraphicsItem cacheOption = *option; - cacheOption.exposedRect = br.adjusted(-1, -1, 1, 1); + styleOptionTmp = *option; + styleOptionTmp.exposedRect = br.adjusted(-1, -1, 1, 1); // Render the exposed areas. _q_paintIntoCache(&pix, item, pixmapExposed, itemToPixmap, painter->renderHints(), - &cacheOption, painterStateProtection); + &styleOptionTmp, painterStateProtection); // Reset expose data. pixModified = true; @@ -5062,8 +5062,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Draw item if (!dontDrawItem) { - QStyleOptionGraphicsItem option; - item->d_ptr->initStyleOption(&option, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); + item->d_ptr->initStyleOption(&styleOptionTmp, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); bool savePainter = clipsToShape || !(optimizationFlags & QGraphicsView::DontSavePainterState); @@ -5074,7 +5073,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (clipsToShape) painter->setClipPath(item->shape(), Qt::IntersectClip); painter->setOpacity(opacity); - drawItemHelper(item, painter, &option, widget, false); + drawItemHelper(item, painter, &styleOptionTmp, widget, false); if (savePainter) painter->restore(); diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 9e9ef6b..d74591c 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -69,6 +69,7 @@ #include #include #include +#include QT_BEGIN_NAMESPACE @@ -281,6 +282,8 @@ public: void setPalette_helper(const QPalette &palette); void resolvePalette(); void updatePalette(const QPalette &palette); + + QStyleOptionGraphicsItem styleOptionTmp; }; QT_END_NAMESPACE -- cgit v0.12 From 6f218ce216021ff2e8ecf828b2f29b1b9d82b401 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 2 Jun 2009 14:00:03 +0200 Subject: Microoptimize: make this function inline. Also change the order of comparisons, as the transformable flags are most likely to fail first. --- src/gui/graphicsview/qgraphicsitem.cpp | 16 ++-------------- src/gui/graphicsview/qgraphicsitem_p.h | 6 +++++- 2 files changed, 7 insertions(+), 15 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 17cab45..ca39713 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -779,18 +779,6 @@ QPointF QGraphicsItemPrivate::genericMapFromScene(const QPointF &pos, /*! \internal - Returns true if this item or any of its ancestors are untransformable. -*/ -bool QGraphicsItemPrivate::itemIsUntransformable() const -{ - return (flags & QGraphicsItem::ItemIgnoresTransformations) - || (ancestorFlags & AncestorIgnoresTransformations); -} - - -/*! - \internal - Combines this item's position and transform onto \a transform. If you need to change this function (e.g., adding more transformation @@ -799,7 +787,7 @@ bool QGraphicsItemPrivate::itemIsUntransformable() const void QGraphicsItemPrivate::combineTransformToParent(QTransform *x, const QTransform *viewTransform) const { // COMBINE - if (viewTransform && itemIsUntransformable()) { + if (itemIsUntransformable() && viewTransform) { *x = q_ptr->deviceTransform(*viewTransform); } else { if (transform) @@ -821,7 +809,7 @@ void QGraphicsItemPrivate::combineTransformToParent(QTransform *x, const QTransf void QGraphicsItemPrivate::combineTransformFromParent(QTransform *x, const QTransform *viewTransform) const { // COMBINE - if (viewTransform && itemIsUntransformable()) { + if (itemIsUntransformable() && viewTransform) { *x = q_ptr->deviceTransform(*viewTransform); } else { x->translate(pos.x(), pos.y()); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index d962ad0..61f6496 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -160,7 +160,11 @@ public: void setIsMemberOfGroup(bool enabled); void remapItemPos(QEvent *event, QGraphicsItem *item); QPointF genericMapFromScene(const QPointF &pos, const QWidget *viewport) const; - bool itemIsUntransformable() const; + inline bool itemIsUntransformable() const + { + return (flags & QGraphicsItem::ItemIgnoresTransformations) + || (ancestorFlags & AncestorIgnoresTransformations); + } void combineTransformToParent(QTransform *x, const QTransform *viewTransform = 0) const; void combineTransformFromParent(QTransform *x, const QTransform *viewTransform = 0) const; -- cgit v0.12 From fe640c1245075cabdafa88a16bdd33f9b49452c0 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 2 Jun 2009 16:07:51 +0200 Subject: A faster item discovery function for rectangles (recursive). This function works much faster than the last one, but still it can be much faster. The main expense right now it seems is the transform calculations, and the item->collidesWithPath call. There's still much to gain here. This function does not make use of the BSP tree's fast lookup so it makes lookups slower in (e.g.) the chip demo. --- src/gui/graphicsview/qgraphicsscene.cpp | 110 +++++++++++++++++++++++++++++++- src/gui/graphicsview/qgraphicsscene_p.h | 4 ++ 2 files changed, 113 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 0c679de..963c615 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -250,6 +250,8 @@ static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000; QT_BEGIN_NAMESPACE +static inline bool qt_notclosestLeaf(const QGraphicsItem *item1, const QGraphicsItem *item2); + static inline bool QRectF_intersects(const QRectF &s, const QRectF &r) { qreal xp = s.left(); @@ -1372,6 +1374,110 @@ QGraphicsWidget *QGraphicsScenePrivate::windowForItem(const QGraphicsItem *item) return 0; } +void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF rect, + QList *items, + const QTransform &parentTransform, + const QTransform &viewTransform, + Qt::ItemSelectionMode mode, Qt::SortOrder order, + qreal parentOpacity) const +{ + // Calculate opacity. + qreal opacity; + if (item) { + if (!item->d_ptr->visible) + return; + QGraphicsItem *p = item->d_ptr->parent; + bool itemIgnoresParentOpacity = item->d_ptr->flags & QGraphicsItem::ItemIgnoresParentOpacity; + bool parentDoesntPropagateOpacity = (p && (p->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)); + if (!itemIgnoresParentOpacity && !parentDoesntPropagateOpacity) { + opacity = parentOpacity * item->opacity(); + } else { + opacity = item->d_ptr->opacity; + } + if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) + return; + } else { + opacity = parentOpacity; + } + + // Calculate the full transform for this item. + QTransform transform = parentTransform; + bool keep = false; + if (item) { + item->d_ptr->combineTransformFromParent(&transform, &viewTransform); + + QRectF brect = item->boundingRect(); + if (!brect.size().isNull()) { + // ### This does not take the clip into account. + _q_adjustRect(&brect); + + keep = true; + if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) + keep = rect.contains(transform.mapRect(brect)); + else + keep = rect.intersects(transform.mapRect(brect)); + + if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { + QPainterPath rectPath; + rectPath.addRect(rect); + keep = item->collidesWithPath(transform.inverted().map(rectPath)); + } + } + } + + bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); + bool dontProcessItem = !item || !keep; + bool dontProcessChildren = item && dontProcessItem && childClip; + childClip &= !dontProcessChildren & !children.isEmpty(); + + // Clip. + if (childClip) + rect &= transform.map(item->shape()).controlPointRect(); + + // Find and sort children. + QList &children = item ? item->d_ptr->children : const_cast(this)->topLevelItems; + if (!dontProcessChildren) { + if (item && item->d_ptr->needSortChildren) { + item->d_ptr->needSortChildren = 0; + qStableSort(children.begin(), children.end(), qt_notclosestLeaf); + } else if (!item && needSortTopLevelItems) { + const_cast(this)->needSortTopLevelItems = false; + qStableSort(children.begin(), children.end(), qt_notclosestLeaf); + } + } + + // Process children behind + int i = 0; + if (!dontProcessChildren) { + for (i = 0; i < children.size(); ++i) { + QGraphicsItem *child = children.at(i); + if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) + break; + recursive_items_helper(child, rect, items, transform, viewTransform, + mode, order, opacity); + } + } + + // Process item + if (!dontProcessItem) + items->append(item); + + // Process children in front + if (!dontProcessChildren) { + for (; i < children.size(); ++i) + recursive_items_helper(children.at(i), rect, items, transform, viewTransform, + mode, order, opacity); + } + + if (!item && order == Qt::AscendingOrder) { + int n = items->size(); + for (int i = 0; i < n / 2; ++i) { + QGraphicsItem *tmp = (*items)[n - i - 1]; + (*items)[n - i - 1] = (*items)[i]; + (*items)[i] = tmp; + } + } +} QList QGraphicsScenePrivate::items_helper(const QPointF &pos) const { @@ -2470,7 +2576,9 @@ QList QGraphicsScene::items(const QPointF &pos) const QList QGraphicsScene::items(const QRectF &rect, Qt::ItemSelectionMode mode) const { Q_D(const QGraphicsScene); - return d->items_helper(rect, mode, Qt::AscendingOrder); + QList itemList; + d->recursive_items_helper(0, rect, &itemList, QTransform(), QTransform(), mode, Qt::AscendingOrder); + return itemList; } /*! diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index d74591c..6b4476c 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -204,6 +204,10 @@ public: void mousePressEventHandler(QGraphicsSceneMouseEvent *mouseEvent); QGraphicsWidget *windowForItem(const QGraphicsItem *item) const; + void recursive_items_helper(QGraphicsItem *item, QRectF rect, QList *items, + const QTransform &parentTransform, const QTransform &viewTransform, + Qt::ItemSelectionMode mode, Qt::SortOrder order, qreal parentOpacity = 1.0) const; + QList items_helper(const QPointF &pos) const; QList items_helper(const QRectF &rect, Qt::ItemSelectionMode mode, -- cgit v0.12 From de776b777bd9c1884bda4049d8f75020d6092ab7 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 2 Jun 2009 17:27:22 +0200 Subject: Remove crash, remove item from pending updates when deleted. This caused a crash in the contacts demo. --- src/gui/graphicsview/qgraphicsscene.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 963c615..73d6a93 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -743,6 +743,7 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) hoverItems.removeAll(item); cachedItemsUnderMouse.removeAll(item); unpolishedItems.removeAll(item); + pendingUpdateItems.removeAll(item); //We remove all references of item from the sceneEventFilter arrays QMultiMap::iterator iterator = sceneEventFilters.begin(); -- cgit v0.12 From bdb0c0fc98fc1998f6a7ee21be29513534be3713 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Tue, 2 Jun 2009 20:25:49 +0200 Subject: Optimise effectiveOpacity and make it inlineable. This cut's off some cycles in discardUpdateRequest() which is called from most places when something in the items changes. --- src/gui/graphicsview/qgraphicsitem.cpp | 16 +--------------- src/gui/graphicsview/qgraphicsitem_p.h | 26 +++++++++++++++++++++++++- src/gui/graphicsview/qgraphicsscene.cpp | 4 ++-- 3 files changed, 28 insertions(+), 18 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index ca39713..b913d89 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -2028,21 +2028,7 @@ qreal QGraphicsItem::opacity() const */ qreal QGraphicsItem::effectiveOpacity() const { - if (!d_ptr->parent) - return d_ptr->opacity; - - int myFlags = d_ptr->flags; - int parentFlags = d_ptr->parent ? d_ptr->parent->d_ptr->flags : 0; - - // If I have a parent, and I don't ignore my parent's opacity, and my - // parent propagates to me, then combine my local opacity with my parent's - // effective opacity into my effective opacity. - if (!(myFlags & QGraphicsItem::ItemIgnoresParentOpacity) - && !(parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) { - return d_ptr->opacity * d_ptr->parent->effectiveOpacity(); - } - - return d_ptr->opacity; + return d_ptr->effectiveOpacity(); } /*! diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 61f6496..d92d76e 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -277,7 +277,31 @@ public: void updateCachedClipPathFromSetPosHelper(const QPointF &newPos); inline bool isFullyTransparent() const - { return q_func()->effectiveOpacity() < .001; } + { return effectiveOpacity() < .001; } + + inline qreal effectiveOpacity() const { + if (!parent) + return opacity; + + qreal o = opacity; + QGraphicsItem *p = parent; + int myFlags = flags; + while (p) { + int parentFlags = p->d_ptr->flags; + + // If I have a parent, and I don't ignore my parent's opacity, and my + // parent propagates to me, then combine my local opacity with my parent's + // effective opacity into my effective opacity. + if ((myFlags & QGraphicsItem::ItemIgnoresParentOpacity) + || (parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) + break; + + o *= parent->d_ptr->opacity; + p = p->d_ptr->parent; + myFlags = parentFlags; + } + return o; + } inline bool childrenCombineOpacity() const { diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 73d6a93..25ac279 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -419,7 +419,7 @@ QList QGraphicsScenePrivate::estimateItemsInRect(const QRectF & if (QGraphicsItem *item = unindexedItems.at(i)) { if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) continue; - if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0)) + if (item->d_ptr->visible && !item->d_ptr->isFullyTransparent()) itemsInRect << item; } } @@ -427,7 +427,7 @@ QList QGraphicsScenePrivate::estimateItemsInRect(const QRectF & if (QGraphicsItem *item = indexedItems.at(i)) { if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) continue; - if (item->d_ptr->visible && item->effectiveOpacity() > qreal(0.0)) + if (item->d_ptr->visible && item->d_ptr->isFullyTransparent()) itemsInRect << item; } } -- cgit v0.12 From 07dca7a30d4bd1efd8032915700420cca3fd60fa Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Tue, 2 Jun 2009 21:02:42 +0200 Subject: implement equality operator in a more sane way Using qFuzzyCompare for checking whether two transformations are equal doesn't give us too much and is inconsistent with our other matrix classes. Using simple floating point equality is a lot faster as well. --- src/gui/painting/qtransform.cpp | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/gui/painting/qtransform.cpp b/src/gui/painting/qtransform.cpp index 86e594c..bd2ea31 100644 --- a/src/gui/painting/qtransform.cpp +++ b/src/gui/painting/qtransform.cpp @@ -700,11 +700,15 @@ QTransform & QTransform::rotateRadians(qreal a, Qt::Axis axis) */ bool QTransform::operator==(const QTransform &o) const { -#define qFZ qFuzzyCompare - return qFZ(affine._m11, o.affine._m11) && qFZ(affine._m12, o.affine._m12) && qFZ(m_13, o.m_13) - && qFZ(affine._m21, o.affine._m21) && qFZ(affine._m22, o.affine._m22) && qFZ(m_23, o.m_23) - && qFZ(affine._dx, o.affine._dx) && qFZ(affine._dy, o.affine._dy) && qFZ(m_33, o.m_33); -#undef qFZ + return affine._m11 == o.affine._m11 && + affine._m12 == o.affine._m12 && + affine._m21 == o.affine._m21 && + affine._m22 == o.affine._m22 && + affine._dx == o.affine._dx && + affine._dy == o.affine._dy && + m_13 == o.m_13 && + m_23 == o.m_23 && + m_33 == o.m_33; } /*! -- cgit v0.12 From e5b83ec3dc4e2f4c18b67d45a5699da5a3f05f10 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Tue, 2 Jun 2009 22:05:01 +0200 Subject: optimise isFullyTransparent() This cuts down quite some intructions in some use cases, making esp. discardUpdateRequest() a bit cheaper. --- src/gui/graphicsview/qgraphicsitem_p.h | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index d92d76e..d007f03 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -276,13 +276,8 @@ public: void invalidateCachedClipPathRecursively(bool childrenOnly = false, const QRectF &emptyIfOutsideThisRect = QRectF()); void updateCachedClipPathFromSetPosHelper(const QPointF &newPos); - inline bool isFullyTransparent() const - { return effectiveOpacity() < .001; } - - inline qreal effectiveOpacity() const { - if (!parent) - return opacity; - + inline qreal calcEffectiveOpacity() const + { qreal o = opacity; QGraphicsItem *p = parent; int myFlags = flags; @@ -303,6 +298,23 @@ public: return o; } + inline bool isFullyTransparent() const + { + if (opacity < 0.001) + return true; + if (!parent) + return false; + + return calcEffectiveOpacity() < 0.001; + } + + inline qreal effectiveOpacity() const { + if (!parent || !opacity) + return opacity; + + return calcEffectiveOpacity(); + } + inline bool childrenCombineOpacity() const { if (!children.size()) -- cgit v0.12 From 6887a89b0e0ee7a0eaff2adc34ae71ab01e2ba2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Tue, 2 Jun 2009 13:53:01 +0200 Subject: Generalize QGrahicsScenePrivate::processDirtyItemsRecursive. Add back compatibility support and make it independent of the views. Also store the sceneTransform instead of the deviceTransform. This will later be the item's cached scene transform (coming in another commit). --- src/gui/graphicsview/qgraphicsitem_p.h | 6 +- src/gui/graphicsview/qgraphicsscene.cpp | 99 ++++++++++++++++++--------------- 2 files changed, 58 insertions(+), 47 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index d007f03..0e0a121 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -146,7 +146,7 @@ public: flags(0), dirtyChildrenBoundingRect(1), paintedViewBoundingRectsNeedRepaint(0), - hasValidDeviceTransform(0), + hasValidSceneTransform(0), globalStackingOrder(-1), q_ptr(0) { @@ -353,7 +353,7 @@ public: QGraphicsItem *parent; QList children; QTransform *transform; - QTransform deviceTransform; + QTransform sceneTransform; int index; int depth; @@ -388,7 +388,7 @@ public: quint32 flags : 11; quint32 dirtyChildrenBoundingRect : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; - quint32 hasValidDeviceTransform : 1; + quint32 hasValidSceneTransform : 1; quint32 padding : 18; // feel free to use // Optional stacking order diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 25ac279..34c7dc1 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -680,7 +680,7 @@ void QGraphicsScenePrivate::_q_processDirtyItems() if (updateAll) return; - processDirtyItemsRecursive(0, views.at(0)->viewportTransform()); + processDirtyItemsRecursive(0, QTransform()); for (int i = 0; i < views.size(); ++i) views.at(i)->d_func()->processPendingUpdates(); } @@ -5113,12 +5113,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * QTransform transform = parentTransform; QRect viewBoundingRect; if (item) { - if (!item->d_ptr->hasValidDeviceTransform) { - item->d_ptr->combineTransformFromParent(&transform, &viewTransform); - } else { - transform = item->d_ptr->deviceTransform; - item->d_ptr->hasValidDeviceTransform = 0; - } + item->d_ptr->combineTransformFromParent(&transform, &viewTransform); QRectF brect = item->boundingRect(); if (!brect.size().isNull()) { // ### This does not take the clip into account. @@ -5244,51 +5239,67 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, const QTransform &parentTransform) { Q_ASSERT(!item || item->d_ptr->dirty || item->d_ptr->dirtyChildren); + Q_Q(QGraphicsScene); - // Calculate the full transform for this item. + // Calculate the full scene transform for this item. QTransform transform = parentTransform; - if (item) { - if (item->d_ptr->itemIsUntransformable()) { - QTransform x = views.at(0)->viewportTransform(); - item->d_ptr->combineTransformFromParent(&transform, &x); - } else { - item->d_ptr->combineTransformFromParent(&transform); - } + if (item && !item->d_ptr->itemIsUntransformable()) { + item->d_ptr->combineTransformFromParent(&transform); + item->d_ptr->sceneTransform = transform; + item->d_ptr->hasValidSceneTransform = 1; } // Process item. if (item && item->d_ptr->dirty) { - QRectF dirtyRect = adjustedItemBoundingRect(item); - if (!item->d_ptr->fullUpdatePending) { - _q_adjustRect(&item->d_ptr->needsRepaint); - dirtyRect &= item->d_ptr->needsRepaint; - } + const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask); + if (useCompatUpdate && !item->d_ptr->itemIsUntransformable() + && qFuzzyIsNull(item->boundingRegionGranularity())) { + // This block of code is kept for compatibility. Since 4.5, by default + // QGraphicsView does not connect the signal and we use the below + // method of delivering updates. + q->update(item->sceneBoundingRect()); + } else { + QRectF dirtyRect; + bool uninitializedDirtyRect = true; + + for (int j = 0; j < views.size(); ++j) { + QGraphicsView *view = views.at(j); + QGraphicsViewPrivate *viewPrivate = view->d_func(); + if (viewPrivate->fullUpdatePending) + continue; + switch (viewPrivate->viewportUpdateMode) { + case QGraphicsView::NoViewportUpdate: + continue; + case QGraphicsView::FullViewportUpdate: + view->viewport()->update(); + viewPrivate->fullUpdatePending = 1; + continue; + default: + break; + } - QGraphicsViewPrivate *viewPrivate = views.at(0)->d_func(); - if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) - viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + if (uninitializedDirtyRect) { + dirtyRect = adjustedItemBoundingRect(item); + if (!item->d_ptr->fullUpdatePending) { + _q_adjustRect(&item->d_ptr->needsRepaint); + dirtyRect &= item->d_ptr->needsRepaint; + uninitializedDirtyRect = false; + } + } - bool dirtyRectOutsideViewport = false; - if (item->d_ptr->hasBoundingRegionGranularity) { - const QRegion dirtyViewRegion = transform.map(QRegion(dirtyRect.toRect())) - & viewPrivate->viewport->rect(); - if (!dirtyViewRegion.isEmpty()) - viewPrivate->updateRegion(dirtyViewRegion); - else - dirtyRectOutsideViewport = true; - } else { - const QRect dirtyViewRect = transform.mapRect(dirtyRect).toRect() - & viewPrivate->viewport->rect(); - if (!dirtyViewRect.isEmpty()) - viewPrivate->updateRect(dirtyViewRect); - else - dirtyRectOutsideViewport = true; - } - if (!dirtyRectOutsideViewport) { - // We know for sure this item will be process in the paint event, hence - // store its device transform and re-use it when drawing. - item->d_ptr->hasValidDeviceTransform = 1; - item->d_ptr->deviceTransform = transform; + if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) + viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + + if (item->d_ptr->hasBoundingRegionGranularity) { + const QRegion dirtyViewRegion = item->deviceTransform(view->viewportTransform()) + .map(QRegion(dirtyRect.toRect())); + viewPrivate->updateRegion(dirtyViewRegion); + } else { + const QRect dirtyViewRect = item->deviceTransform(view->viewportTransform()) + .mapRect(dirtyRect).toRect(); + viewPrivate->updateRect(dirtyViewRect); + } + } } } -- cgit v0.12 From 95949e7ef88eb14b7b22b06d235603f8581f6aa0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Tue, 2 Jun 2009 18:53:42 +0200 Subject: Cache QGrahicsItem's scene transform. Invalidating the scene transform is just a matter of setting a bit on the item. Then, when we ask for the item's scene transform, we traverse its ancestors recursively and find the top-most dirty item. The algorithm then backtracks to that item and start calculating the scene transform for the item itself and all its children in the call stack. If the item itself and all its ancestors are "clean", nothing is calculated, only traversed. We use this approach when processing dirty items / drawing items as well. That way we ensure the scene transform is only calculated once when absolutely needed. G'night :) --- src/gui/graphicsview/qgraphicsitem.cpp | 50 ++++++++++++++++++--- src/gui/graphicsview/qgraphicsitem_p.h | 11 ++++- src/gui/graphicsview/qgraphicsscene.cpp | 80 ++++++++++++++++++++++----------- src/gui/graphicsview/qgraphicsscene_p.h | 5 +-- src/gui/graphicsview/qgraphicsview.cpp | 2 +- 5 files changed, 109 insertions(+), 39 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index b913d89..57ca2ef 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -952,6 +952,7 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de // Resolve depth. resolveDepth(parent ? parent->d_ptr->depth : -1); + dirtySceneTransform = 1; // Deliver post-change notification q->itemChange(QGraphicsItem::ItemParentHasChanged, newParentVariant); @@ -2540,6 +2541,7 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) if (scene) q->prepareGeometryChange(); this->pos = newPos; + dirtySceneTransform = 1; // Send post-notification. #ifndef QGRAPHICSITEM_NO_ITEMCHANGE @@ -2682,12 +2684,17 @@ QMatrix QGraphicsItem::sceneMatrix() const */ QTransform QGraphicsItem::sceneTransform() const { - QTransform m; - const QGraphicsItem *p = this; - do { - p->d_ptr->combineTransformToParent(&m); - } while ((p = p->d_ptr->parent)); - return m; + if (d_ptr->dirtySceneTransform) { + // This item and all its descendants have dirty scene transforms. + // We're about to validate this item's scene transform, so we have to + // invalidate all the children; otherwise there's no way for the descendants + // to detect that the ancestor has changed. + d_ptr->invalidateChildrenSceneTransform(); + } + + QGraphicsItem *that = const_cast(this); + d_ptr->ensureSceneTransformRecursive(&that); + return d_ptr->sceneTransform; } /*! @@ -2899,6 +2906,7 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); *d_ptr->transform = newTransform; + d_ptr->dirtySceneTransform = 1; // Send post-notification. #ifndef QGRAPHICSITEM_NO_ITEMCHANGE @@ -2945,6 +2953,7 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) // Update and set the new transformation. prepareGeometryChange(); *d_ptr->transform = newTransform; + d_ptr->dirtySceneTransform = 1; // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -3966,6 +3975,35 @@ void QGraphicsItemPrivate::updateCachedClipPathFromSetPosHelper(const QPointF &n } } +// Traverses all the ancestors up to the top-level and updates the pointer to +// always point to the top-most item that has a dirty scene transform. +// It then backtracks to the top-most dirty item and start calculating the +// scene transform by combining the item's transform (+pos) with the parent's +// cached scene transform (which we at this point know for sure is valid). +void QGraphicsItemPrivate::ensureSceneTransformRecursive(QGraphicsItem **topMostDirtyItem) +{ + Q_ASSERT(topMostDirtyItem); + + if (dirtySceneTransform) + *topMostDirtyItem = q_ptr; + + if (parent) + parent->d_ptr->ensureSceneTransformRecursive(topMostDirtyItem); + + if (*topMostDirtyItem == q_ptr) { + if (!dirtySceneTransform) + return; // OK, neither my ancestors nor I have dirty scene transforms. + *topMostDirtyItem = 0; + } else if (*topMostDirtyItem) { + return; // Continue backtrack. + } + + // COMBINE my transform with the parent's scene transform. + sceneTransform = parent ? parent->d_ptr->sceneTransform : QTransform(); + combineTransformFromParent(&sceneTransform); + dirtySceneTransform = 0; +} + /*! \internal diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 0e0a121..f9d63fb 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -146,7 +146,7 @@ public: flags(0), dirtyChildrenBoundingRect(1), paintedViewBoundingRectsNeedRepaint(0), - hasValidSceneTransform(0), + dirtySceneTransform(1), globalStackingOrder(-1), q_ptr(0) { @@ -275,6 +275,13 @@ public: void invalidateCachedClipPathRecursively(bool childrenOnly = false, const QRectF &emptyIfOutsideThisRect = QRectF()); void updateCachedClipPathFromSetPosHelper(const QPointF &newPos); + void ensureSceneTransformRecursive(QGraphicsItem **topMostDirtyItem); + + inline void invalidateChildrenSceneTransform() + { + for (int i = 0; i < children.size(); ++i) + children.at(i)->d_ptr->dirtySceneTransform = 1; + } inline qreal calcEffectiveOpacity() const { @@ -388,7 +395,7 @@ public: quint32 flags : 11; quint32 dirtyChildrenBoundingRect : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; - quint32 hasValidSceneTransform : 1; + quint32 dirtySceneTransform : 1; quint32 padding : 18; // feel free to use // Optional stacking order diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 34c7dc1..2773bdd 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -680,7 +680,7 @@ void QGraphicsScenePrivate::_q_processDirtyItems() if (updateAll) return; - processDirtyItemsRecursive(0, QTransform()); + processDirtyItemsRecursive(0); for (int i = 0; i < views.size(); ++i) views.at(i)->d_func()->processPendingUpdates(); } @@ -5083,7 +5083,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte } } -void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, +void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, QRegion *exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, @@ -5110,10 +5110,24 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } // Calculate the full transform for this item. - QTransform transform = parentTransform; + QTransform transform; QRect viewBoundingRect; + bool wasDirtyParentSceneTransform = false; if (item) { - item->d_ptr->combineTransformFromParent(&transform, &viewTransform); + if (item->d_ptr->itemIsUntransformable()) { + transform = item->deviceTransform(viewTransform); + } else { + if (item->d_ptr->dirtySceneTransform) { + item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform + : transform; + item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform); + item->d_ptr->dirtySceneTransform = 0; + wasDirtyParentSceneTransform = true; + } + transform = item->d_ptr->sceneTransform; + transform *= viewTransform; + } + QRectF brect = item->boundingRect(); if (!brect.size().isNull()) { // ### This does not take the clip into account. @@ -5156,11 +5170,12 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (!dontDrawChildren) { for (i = 0; i < children.size(); ++i) { QGraphicsItem *child = children.at(i); + if (wasDirtyParentSceneTransform) + child->d_ptr->dirtySceneTransform = 1; if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) break; - drawSubtreeRecursive(child, painter, transform, viewTransform, - exposedRegion, widget, optimizationFlags, - 0, opacity); + drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, + optimizationFlags, 0, opacity); } } @@ -5186,9 +5201,14 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Draw children in front if (!dontDrawChildren) { for (; i < children.size(); ++i) { - drawSubtreeRecursive(children.at(i), painter, transform, viewTransform, - exposedRegion, widget, optimizationFlags, 0, opacity); + QGraphicsItem *child = children.at(i); + if (wasDirtyParentSceneTransform) + child->d_ptr->dirtySceneTransform = 1; + drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, + widget, optimizationFlags, 0, opacity); } + } else if (wasDirtyParentSceneTransform) { + item->d_ptr->invalidateChildrenSceneTransform(); } // Restore child clip @@ -5236,17 +5256,19 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b } } -void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, const QTransform &parentTransform) +void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item) { Q_ASSERT(!item || item->d_ptr->dirty || item->d_ptr->dirtyChildren); Q_Q(QGraphicsScene); // Calculate the full scene transform for this item. - QTransform transform = parentTransform; - if (item && !item->d_ptr->itemIsUntransformable()) { - item->d_ptr->combineTransformFromParent(&transform); - item->d_ptr->sceneTransform = transform; - item->d_ptr->hasValidSceneTransform = 1; + bool wasDirtyParentSceneTransform = false; + if (item && item->d_ptr->dirtySceneTransform && !item->d_ptr->itemIsUntransformable()) { + item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform + : QTransform(); + item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform); + item->d_ptr->dirtySceneTransform = 0; + wasDirtyParentSceneTransform = true; } // Process item. @@ -5261,6 +5283,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, cons } else { QRectF dirtyRect; bool uninitializedDirtyRect = true; + const bool untransformableItem = item->d_ptr->itemIsUntransformable(); for (int j = 0; j < views.size(); ++j) { QGraphicsView *view = views.at(j); @@ -5290,15 +5313,15 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, cons if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); - if (item->d_ptr->hasBoundingRegionGranularity) { - const QRegion dirtyViewRegion = item->deviceTransform(view->viewportTransform()) - .map(QRegion(dirtyRect.toRect())); - viewPrivate->updateRegion(dirtyViewRegion); - } else { - const QRect dirtyViewRect = item->deviceTransform(view->viewportTransform()) - .mapRect(dirtyRect).toRect(); - viewPrivate->updateRect(dirtyViewRect); - } + QTransform deviceTransform = item->d_ptr->sceneTransform; + if (!untransformableItem) + deviceTransform *= view->viewportTransform(); + else + deviceTransform = item->deviceTransform(view->viewportTransform()); + if (item->d_ptr->hasBoundingRegionGranularity) + viewPrivate->updateRegion(deviceTransform.map(QRegion(dirtyRect.toRect()))); + else + viewPrivate->updateRect(deviceTransform.mapRect(dirtyRect).toRect()); } } } @@ -5309,14 +5332,18 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, cons const bool allChildrenDirty = item && item->d_ptr->allChildrenDirty; for (int i = 0; i < children->size(); ++i) { QGraphicsItem *child = children->at(i); + if (wasDirtyParentSceneTransform) + child->d_ptr->dirtySceneTransform = 1; if (allChildrenDirty) { child->d_ptr->dirty = 1; } else if (!child->d_ptr->dirty && !child->d_ptr->dirtyChildren) { resetDirtyItem(child); continue; } - processDirtyItemsRecursive(child, transform); + processDirtyItemsRecursive(child); } + } else if (wasDirtyParentSceneTransform) { + item->d_ptr->invalidateChildrenSceneTransform(); } if (item) @@ -5373,8 +5400,7 @@ void QGraphicsScene::drawItems(QPainter *painter, if (!item->d_ptr->itemDiscovered) { topLevelItems << item; item->d_ptr->itemDiscovered = 1; - d->drawSubtreeRecursive(item, painter, viewTransform, viewTransform, - expose, widget, flags); + d->drawSubtreeRecursive(item, painter, viewTransform, expose, widget, flags); } } diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 6b4476c..e0c48a6 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -258,13 +258,12 @@ public: const QStyleOptionGraphicsItem *option, QWidget *widget, bool painterStateProtection); - void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &parentTransform, - const QTransform &viewTransform, + void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, QRegion *exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, QList *topLevelItems = 0, qreal parentOpacity = qreal(1.0)); void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); - void processDirtyItemsRecursive(QGraphicsItem *item, const QTransform &); + void processDirtyItemsRecursive(QGraphicsItem *item); inline void resetDirtyItem(QGraphicsItem *item) { diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index caa3ffc..e9a432e 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3301,7 +3301,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) // Items if (!(d->optimizationFlags & IndirectPainting)) { - d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, viewTransform, &d->exposedRegion, + d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, &d->exposedRegion, viewport(), d->optimizationFlags, 0); } else { // Find all exposed items -- cgit v0.12 From 062b7b1280ef228567d16187951fe43e2ac0f78c Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Wed, 3 Jun 2009 07:06:57 +0200 Subject: Remove leftover code from merge conflict. --- src/gui/graphicsview/qgraphicsitem_p.h | 66 ------------- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 126 ------------------------- 2 files changed, 192 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index f9d63fb..b0b940b 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -401,77 +401,11 @@ public: // Optional stacking order int globalStackingOrder; - struct DecomposedTransform; - DecomposedTransform *decomposedTransform() const - { - QGraphicsItemPrivate *that = const_cast(this); - DecomposedTransform *decomposed; - if (hasDecomposedTransform) { - decomposed = qVariantValue(extra(ExtraDecomposedTransform)); - } else { - decomposed = new DecomposedTransform; - that->setExtra(ExtraDecomposedTransform, qVariantFromValue(decomposed)); - that->hasDecomposedTransform = 1; - if (!dirtyTransformComponents) - decomposed->reset(); - } - if (dirtyTransformComponents) { - decomposed->initFrom(q_ptr->transform()); - that->dirtyTransformComponents = 0; - } - return decomposed; - } - - struct DecomposedTransform { - qreal xScale; - qreal yScale; - qreal xRotation; - qreal yRotation; - qreal zRotation; - qreal horizontalShear; - qreal verticalShear; - qreal xOrigin; - qreal yOrigin; - - inline void reset() - { - xScale = 1.0; - yScale = 1.0; - xRotation = 0.0; - yRotation = 0.0; - zRotation = 0.0; - horizontalShear = 0.0; - verticalShear = 0.0; - xOrigin = 0.0; - yOrigin = 0.0; - } - - inline void initFrom(const QTransform &x) - { - reset(); - // ### decompose transform - Q_UNUSED(x); - } - - inline void generateTransform(QTransform *x) const - { - x->translate(xOrigin, yOrigin); - x->rotate(xRotation, Qt::XAxis); - x->rotate(yRotation, Qt::YAxis); - x->rotate(zRotation, Qt::ZAxis); - x->shear(horizontalShear, verticalShear); - x->scale(xScale, yScale); - x->translate(-xOrigin, -yOrigin); - } - }; - QGraphicsItem *q_ptr; }; QT_END_NAMESPACE -Q_DECLARE_METATYPE(QGraphicsItemPrivate::DecomposedTransform *) - #endif // QT_NO_GRAPHICSVIEW #endif diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 8afdeb4..9cfd897 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -219,8 +219,6 @@ private slots: void updateCachedItemAfterMove(); void deviceTransform_data(); void deviceTransform(); - void setTransformProperties_data(); - void setTransformProperties(); // task specific tests below me void task141694_textItemEnsureVisible(); @@ -6428,129 +6426,5 @@ void tst_QGraphicsItem::deviceTransform() QCOMPARE(rect3->deviceTransform(deviceX).map(QPointF(50, 50)), mapResult3); } -void tst_QGraphicsItem::setTransformProperties_data() -{ - QTest::addColumn("origin"); - QTest::addColumn("rotationX"); - QTest::addColumn("rotationY"); - QTest::addColumn("rotationZ"); - QTest::addColumn("scaleX"); - QTest::addColumn("scaleY"); - QTest::addColumn("shearX"); - QTest::addColumn("shearY"); - - QTest::newRow("nothing") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) - << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); - - QTest::newRow("rotationZ") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(42.2) - << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); - - QTest::newRow("rotationXY") << QPointF() << qreal(12.5) << qreal(53.6) << qreal(0.0) - << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); - - QTest::newRow("rotationXYZ") << QPointF() << qreal(-25) << qreal(12) << qreal(556) - << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); - - QTest::newRow("rotationXYZ dicentred") << QPointF(-53, 25.2) - << qreal(-2578.2) << qreal(4565.2) << qreal(56) - << qreal(1) << qreal(1) << qreal(0.0) << qreal(0.0); - - QTest::newRow("Scale") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) - << qreal(6) << qreal(0.5) << qreal(0.0) << qreal(0.0); - - QTest::newRow("Shear") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) - << qreal(1) << qreal(1) << qreal(2.2) << qreal(0.5); - - QTest::newRow("Scale and Shear") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) - << qreal(5.2) << qreal(2.1) << qreal(5.2) << qreal(5.5); - - QTest::newRow("Everything") << QPointF() << qreal(41) << qreal(-23) << qreal(0.56) - << qreal(8.2) << qreal(-0.2) << qreal(-12) << qreal(-0.8); - - QTest::newRow("Everything dicentred") << QPointF(qreal(22.3), qreal(-56.2)) << qreal(-175) << qreal(196) << qreal(-1260) - << qreal(4) << qreal(2) << qreal(2.56) << qreal(0.8); -} - -void tst_QGraphicsItem::setTransformProperties() -{ - QFETCH(QPointF,origin); - QFETCH(qreal,rotationX); - QFETCH(qreal,rotationY); - QFETCH(qreal,rotationZ); - QFETCH(qreal,scaleX); - QFETCH(qreal,scaleY); - QFETCH(qreal,shearX); - QFETCH(qreal,shearY); - - QTransform result; - result.translate(origin.x(), origin.y()); - result.rotate(rotationX, Qt::XAxis); - result.rotate(rotationY, Qt::YAxis); - result.rotate(rotationZ, Qt::ZAxis); - result.shear(shearX, shearY); - result.scale(scaleX, scaleY); - result.translate(-origin.x(), -origin.y()); - - QGraphicsScene scene; - QGraphicsRectItem *item = new QGraphicsRectItem(QRectF(0, 0, 100, 100)); - scene.addItem(item); - item->setPos(100, 100); - - item->setRotation(rotationX, rotationY, rotationZ); - item->setScale(scaleX, scaleY); - item->setShear(shearX, shearY); - item->setTransformOrigin(origin); - - QCOMPARE(item->xRotation(), rotationX); - QCOMPARE(item->yRotation(), rotationY); - QCOMPARE(item->zRotation(), rotationZ); - QCOMPARE(item->xScale(), scaleX); - QCOMPARE(item->yScale(), scaleY); - QCOMPARE(item->horizontalShear(), shearX); - QCOMPARE(item->verticalShear(), shearY); - QCOMPARE(item->transformOrigin(), origin); - - QCOMPARE(result, item->transform()); - - //----------------------------------------------------------------- - //Change the rotation Z - item->setZRotation(45); - QTransform result2; - result2.translate(origin.x(), origin.y()); - result2.rotate(rotationX, Qt::XAxis); - result2.rotate(rotationY, Qt::YAxis); - result2.rotate(45, Qt::ZAxis); - result2.shear(shearX, shearY); - result2.scale(scaleX, scaleY); - result2.translate(-origin.x(), -origin.y()); - - QCOMPARE(item->xRotation(), rotationX); - QCOMPARE(item->yRotation(), rotationY); - QCOMPARE(item->zRotation(), 45.0); - QCOMPARE(item->xScale(), scaleX); - QCOMPARE(item->yScale(), scaleY); - QCOMPARE(item->horizontalShear(), shearX); - QCOMPARE(item->verticalShear(), shearY); - QCOMPARE(item->transformOrigin(), origin); - - QCOMPARE(result2, item->transform()); - - //----------------------------------------------------------------- - // calling setTransform() should reset the properties to their default - item->setTransform(result); - - QCOMPARE(item->xRotation(), 0.0); - QCOMPARE(item->yRotation(), 0.0); - QCOMPARE(item->zRotation(), 0.0); - QCOMPARE(item->xScale(), 1.0); - QCOMPARE(item->yScale(), 1.0); - QCOMPARE(item->horizontalShear(), 0.0); - QCOMPARE(item->verticalShear(), 0.0); - QCOMPARE(item->transformOrigin(), QPointF(0,0)); - - QCOMPARE(result, item->transform()); -} - - QTEST_MAIN(tst_QGraphicsItem) #include "tst_qgraphicsitem.moc" -- cgit v0.12 From 8af81877bb11d58099189bfab21d21e3021b7b8b Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Wed, 3 Jun 2009 07:35:06 +0200 Subject: Add QGraphicsView::isTransformed(), and use it to avoid view transforms. Ensure that we don't ask for or multiply with the view transform if the view is not transformed. --- src/gui/graphicsview/qgraphicsscene.cpp | 10 ++++++---- src/gui/graphicsview/qgraphicsview.cpp | 12 ++++++++++++ src/gui/graphicsview/qgraphicsview.h | 1 + 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 2773bdd..7bf58c3 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5314,10 +5314,12 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item) viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); QTransform deviceTransform = item->d_ptr->sceneTransform; - if (!untransformableItem) - deviceTransform *= view->viewportTransform(); - else - deviceTransform = item->deviceTransform(view->viewportTransform()); + if (view->isTransformed()) { + if (!untransformableItem) + deviceTransform *= view->viewportTransform(); + else + deviceTransform = item->deviceTransform(view->viewportTransform()); + } if (item->d_ptr->hasBoundingRegionGranularity) viewPrivate->updateRegion(deviceTransform.map(QRegion(dirtyRect.toRect()))); else diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index e9a432e..c91e0d1 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3555,6 +3555,18 @@ QTransform QGraphicsView::viewportTransform() const } /*! + Returns true if the view is transformed (i.e., a non-identity transform + has been assigned, or the scrollbars are adjusted). + + \sa setTransform(), horizontalScrollBar(), verticalScrollBar() +*/ +bool QGraphicsView::isTransformed() const +{ + Q_D(const QGraphicsView); + return !d->identityMatrix || d->horizontalScroll() || d->verticalScroll(); +} + +/*! Sets the view's current transformation matrix to \a matrix. If \a combine is true, then \a matrix is combined with the current matrix; diff --git a/src/gui/graphicsview/qgraphicsview.h b/src/gui/graphicsview/qgraphicsview.h index b7a9906..387fa01 100644 --- a/src/gui/graphicsview/qgraphicsview.h +++ b/src/gui/graphicsview/qgraphicsview.h @@ -170,6 +170,7 @@ public: void resetMatrix(); QTransform transform() const; QTransform viewportTransform() const; + bool isTransformed() const; void setTransform(const QTransform &matrix, bool combine = false); void resetTransform(); void rotate(qreal angle); -- cgit v0.12 From b5d987298b0502dd593dd09d7e4e1233d6e30dd6 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Wed, 3 Jun 2009 07:50:33 +0200 Subject: Avoid constructing empty temporary QTransforms. This is a microoptimization. --- src/gui/graphicsview/qgraphicsscene.cpp | 19 +++++++++---------- src/gui/graphicsview/qgraphicsscene_p.h | 1 + 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 7bf58c3..188165d 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5110,29 +5110,28 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } // Calculate the full transform for this item. - QTransform transform; QRect viewBoundingRect; bool wasDirtyParentSceneTransform = false; if (item) { if (item->d_ptr->itemIsUntransformable()) { - transform = item->deviceTransform(viewTransform); + transformTmp = item->deviceTransform(viewTransform); } else { if (item->d_ptr->dirtySceneTransform) { item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform - : transform; + : QTransform(); item->d_ptr->combineTransformFromParent(&item->d_ptr->sceneTransform); item->d_ptr->dirtySceneTransform = 0; wasDirtyParentSceneTransform = true; } - transform = item->d_ptr->sceneTransform; - transform *= viewTransform; + transformTmp = item->d_ptr->sceneTransform; + transformTmp *= viewTransform; } - + QRectF brect = item->boundingRect(); if (!brect.size().isNull()) { // ### This does not take the clip into account. _q_adjustRect(&brect); - viewBoundingRect = transform.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); + viewBoundingRect = transformTmp.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect); if (exposedRegion) viewBoundingRect &= exposedRegion->boundingRect(); @@ -5149,7 +5148,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Clip children. if (childClip) { painter->save(); - painter->setWorldTransform(transform); + painter->setWorldTransform(transformTmp); painter->setClipPath(item->shape(), Qt::IntersectClip); } @@ -5181,14 +5180,14 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Draw item if (!dontDrawItem) { - item->d_ptr->initStyleOption(&styleOptionTmp, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); + item->d_ptr->initStyleOption(&styleOptionTmp, transformTmp, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); bool savePainter = clipsToShape || !(optimizationFlags & QGraphicsView::DontSavePainterState); if (savePainter) painter->save(); if (!childClip) - painter->setWorldTransform(transform); + painter->setWorldTransform(transformTmp); if (clipsToShape) painter->setClipPath(item->shape(), Qt::IntersectClip); painter->setOpacity(opacity); diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index e0c48a6..8bc25b6 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -287,6 +287,7 @@ public: void updatePalette(const QPalette &palette); QStyleOptionGraphicsItem styleOptionTmp; + QTransform transformTmp; }; QT_END_NAMESPACE -- cgit v0.12 From 31a7de5cbecad8f5cc106c8886c79c63f07c9b5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Wed, 3 Jun 2009 10:43:49 +0200 Subject: Correct minor mistake after re-refactoring. We don't want to re-calculate the dirty rect for each view. --- src/gui/graphicsview/qgraphicsscene.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 188165d..f8b3b0a 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5305,8 +5305,8 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item) if (!item->d_ptr->fullUpdatePending) { _q_adjustRect(&item->d_ptr->needsRepaint); dirtyRect &= item->d_ptr->needsRepaint; - uninitializedDirtyRect = false; } + uninitializedDirtyRect = false; } if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) -- cgit v0.12 From 33473417a73cafa0c0d9283c00b1e716becba0e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Wed, 3 Jun 2009 14:34:54 +0200 Subject: Speed up processing of dirty items when ancestor clips children. This patch also contains a bug fix where a child item didn't update due to a bit not being properly set. No more rendering artifacts :) --- src/gui/graphicsview/qgraphicsscene.cpp | 33 +++++++++++++++++++++++++++------ src/gui/graphicsview/qgraphicsscene_p.h | 2 +- 2 files changed, 28 insertions(+), 7 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index f8b3b0a..ec0e87b 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5255,7 +5255,7 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b } } -void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item) +void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren) { Q_ASSERT(!item || item->d_ptr->dirty || item->d_ptr->dirtyChildren); Q_Q(QGraphicsScene); @@ -5271,7 +5271,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item) } // Process item. - if (item && item->d_ptr->dirty) { + if (item && (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint)) { const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask); if (useCompatUpdate && !item->d_ptr->itemIsUntransformable() && qFuzzyIsNull(item->boundingRegionGranularity())) { @@ -5300,6 +5300,12 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item) break; } + if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) + viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + + if (!item->d_ptr->dirty) + continue; + if (uninitializedDirtyRect) { dirtyRect = adjustedItemBoundingRect(item); if (!item->d_ptr->fullUpdatePending) { @@ -5309,9 +5315,6 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item) uninitializedDirtyRect = false; } - if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) - viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); - QTransform deviceTransform = item->d_ptr->sceneTransform; if (view->isTransformed()) { if (!untransformableItem) @@ -5331,17 +5334,35 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item) if (!item || item->d_ptr->dirtyChildren) { QList *children = item ? &item->d_ptr->children : &topLevelItems; const bool allChildrenDirty = item && item->d_ptr->allChildrenDirty; + if (!dirtyAncestorContainsChildren) { + dirtyAncestorContainsChildren = item && item->d_ptr->fullUpdatePending + && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape); + } for (int i = 0; i < children->size(); ++i) { QGraphicsItem *child = children->at(i); if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; + if (allChildrenDirty) { child->d_ptr->dirty = 1; + child->d_ptr->fullUpdatePending = 1; + child->d_ptr->dirtyChildren = 1; + child->d_ptr->allChildrenDirty = 1; } else if (!child->d_ptr->dirty && !child->d_ptr->dirtyChildren) { resetDirtyItem(child); continue; } - processDirtyItemsRecursive(child); + + if (dirtyAncestorContainsChildren) { + // No need to process this child's dirty rect, hence reset the dirty state. + // However, we have to continue the recursion because it might have a dirty + // view bounding rect that needs repaint. We also have to reset the dirty + // state of its descendants. + child->d_ptr->dirty = 0; + child->d_ptr->fullUpdatePending = 0; + } + + processDirtyItemsRecursive(child, dirtyAncestorContainsChildren); } } else if (wasDirtyParentSceneTransform) { item->d_ptr->invalidateChildrenSceneTransform(); diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 8bc25b6..f4964f2 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -263,7 +263,7 @@ public: QList *topLevelItems = 0, qreal parentOpacity = qreal(1.0)); void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); - void processDirtyItemsRecursive(QGraphicsItem *item); + void processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren = false); inline void resetDirtyItem(QGraphicsItem *item) { -- cgit v0.12 From 1598ef761a8c3f0c9cccf5318e3de30f6c50880f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Wed, 3 Jun 2009 15:18:25 +0200 Subject: Compatibility fix: Updates made on the scene must be processed with a queued connection This connection was queued in the views before, but we don't do that anymore, instead we re-use the _q_emitUpdated slot and process pending updates on the views there. Makes tst_QGraphicsView::viewportUpdateMode happy again. --- src/gui/graphicsview/qgraphicsscene.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index ec0e87b..8641fe2 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -614,6 +614,10 @@ void QGraphicsScenePrivate::_q_emitUpdated() views.at(i), SLOT(updateScene(QList))); } } + } else { + for (int i = 0; i < views.size(); ++i) + views.at(i)->d_func()->processPendingUpdates(); + return; } // Notify the changes to anybody interested. @@ -3721,7 +3725,7 @@ void QGraphicsScene::update(const QRectF &rect) } } - if (!directUpdates && !d->calledEmitUpdated) { + if (!d->calledEmitUpdated) { d->calledEmitUpdated = true; QMetaObject::invokeMethod(this, "_q_emitUpdated", Qt::QueuedConnection); } -- cgit v0.12 From 728179ed60b43187d28c77a2d6930a74a62791d6 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Wed, 3 Jun 2009 16:34:58 +0200 Subject: Add QGraphicsItem::itemChangeEnabled(). This function allows the user to disable notifications for item changes. In QSimpleCanvasItem, all notifications are disabled by default, and you can enable them one at a time. QGraphicsItem's behavior is to by default enable all notifications. A side effect of this change is that I've removed one optimization in favor of another: by not constructing a QVariant at all when there's no notification we get maximum performance, at the expense of constructing it twice if there is a notification. --- src/gui/graphicsview/qgraphicsitem.cpp | 251 ++++++++++++++++++++++---------- src/gui/graphicsview/qgraphicsitem.h | 5 + src/gui/graphicsview/qgraphicsitem_p.h | 4 +- src/gui/graphicsview/qgraphicsscene.cpp | 30 ++-- 4 files changed, 202 insertions(+), 88 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 57ca2ef..2eb5150 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -39,8 +39,6 @@ ** ****************************************************************************/ -#define QGRAPHICSITEM_NO_ITEMCHANGE - /*! \class QGraphicsItem \brief The QGraphicsItem class is the base class for all graphical @@ -851,11 +849,13 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de if (newParent == parent) return; - const QVariant newParentVariant(q->itemChange(QGraphicsItem::ItemParentChange, - qVariantFromValue(newParent))); - newParent = qVariantValue(newParentVariant); - if (newParent == parent) - return; + bool notify = q->itemChangeEnabled(QGraphicsItem::ItemParentChange); + if (notify) { + newParent = qVariantValue(q->itemChange(QGraphicsItem::ItemParentChange, + qVariantFromValue(newParent))); + if (newParent == parent) + return; + } if (QGraphicsWidget *w = isWidget ? static_cast(q) : q->parentWidget()) { // Update the child focus chain; when reparenting a widget that has a @@ -955,7 +955,8 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de dirtySceneTransform = 1; // Deliver post-change notification - q->itemChange(QGraphicsItem::ItemParentHasChanged, newParentVariant); + if (notify) + q->itemChange(QGraphicsItem::ItemParentHasChanged, qVariantFromValue(newParent)); } /*! @@ -1393,9 +1394,14 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) // Notify change and check for adjustment. if (quint32(d_ptr->flags) == quint32(flags)) return; - flags = GraphicsItemFlags(itemChange(ItemFlagsChange, quint32(flags)).toUInt()); - if (quint32(d_ptr->flags) == quint32(flags)) - return; + + // Notify + bool notify = itemChangeEnabled(ItemFlagsChange); + if (notify) { + flags = GraphicsItemFlags(itemChange(ItemFlagsChange, quint32(flags)).toUInt()); + if (quint32(d_ptr->flags) == quint32(flags)) + return; + } // Flags that alter the geometry of the item (or its children). const quint32 geomChangeFlagsMask = (ItemClipsChildrenToShape | ItemClipsToShape | ItemIgnoresTransformations); @@ -1443,7 +1449,78 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) } // Notify change. - itemChange(ItemFlagsHaveChanged, quint32(flags)); + if (notify) + itemChange(ItemFlagsHaveChanged, quint32(flags)); +} + +static const int itemChangeBits[] = { + /* ItemPositionChange */ 1 << 1, + /* ItemMatrixChange */ 1 << 2, + /* ItemVisibleChange */ 1 << 3, + /* ItemEnabledChange */ 1 << 4, + /* ItemSelectedChange */ 1 << 5, + /* ItemParentChange */ 1 << 6, + /* ItemChildAddedChange */ 1 << 7, + /* ItemChildRemovedChange */ 1 << 8, + /* ItemTransformChange */ 1 << 9, + /* ItemPositionHasChanged */ 1 << 1, + /* ItemTransformHasChanged */ 1 << 9, + /* ItemSceneChange */ 1 << 10, + /* ItemVisibleHasChanged */ 1 << 3, + /* ItemEnabledHasChanged */ 1 << 4, + /* ItemSelectedHasChanged */ 1 << 5, + /* ItemParentHasChanged */ 1 << 6, + /* ItemSceneHasChanged */ 1 << 10, + /* ItemCursorChange */ 1 << 11, + /* ItemCursorHasChanged */ 1 << 11, + /* ItemToolTipChange */ 1 << 12, + /* ItemToolTipHasChanged */ 1 << 12, + /* ItemFlagsChange */ 1 << 13, + /* ItemFlagsHaveChanged */ 1 << 13, + /* ItemZValueChange */ 1 << 14, + /* ItemZValueHasChanged */ 1 << 14, + /* ItemOpacityChange */ 1 << 15, + /* ItemOpacityHasChanged */ 1 << 15 +}; + +/*! + Returns true if \a change is enabled (i.e., QGraphicsItem will call + itemChange() whenever the respective change occurs); otherwise returns + false. + + \sa setItemChangeEnabled(), setItemChangesEnabled(), itemChange() +*/ +bool QGraphicsItem::itemChangeEnabled(GraphicsItemChange change) const +{ + return d_ptr->itemChangesEnabled & itemChangeBits[change]; +} + +/*! + If \a enabled is true, notifications for \a change are enabled; otherwise + they are disabled. By default, QGraphicsItem sends notifications for all + changes by calling itemChange(). + + \sa itemChangeEnabled(), setItemChangesEnabled(), itemChange() +*/ +void QGraphicsItem::setItemChangeEnabled(GraphicsItemChange change, bool enabled) +{ + if (enabled) { + d_ptr->itemChangesEnabled |= itemChangeBits[change]; + } else { + d_ptr->itemChangesEnabled &= itemChangeBits[change]; + } +} + +/*! + If \a enabled is true, all item change notifications are enabled; + otherwise, they are disabled. You can toggle individual notifications by + calling setItemChangeEnabled(). + + \sa itemChangeEnabled(), itemChange() +*/ +void QGraphicsItem::setItemChangesEnabled(bool enabled) +{ + d_ptr->itemChangesEnabled = enabled ? 0xffff : 0; } /*! @@ -1532,9 +1609,13 @@ QString QGraphicsItem::toolTip() const */ void QGraphicsItem::setToolTip(const QString &toolTip) { - const QVariant toolTipVariant(itemChange(ItemToolTipChange, toolTip)); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraToolTip, toolTipVariant.toString()); - itemChange(ItemToolTipHasChanged, toolTipVariant); + bool notify = itemChangeEnabled(ItemToolTipChange); + QVariant toolTipVariant = toolTip; + if (notify) + toolTipVariant = itemChange(ItemToolTipChange, toolTipVariant); + d_ptr->setExtra(QGraphicsItemPrivate::ExtraToolTip, toolTipVariant); + if (notify) + itemChange(ItemToolTipHasChanged, toolTipVariant); } #endif // QT_NO_TOOLTIP @@ -1576,8 +1657,11 @@ QCursor QGraphicsItem::cursor() const */ void QGraphicsItem::setCursor(const QCursor &cursor) { - const QVariant cursorVariant(itemChange(ItemCursorChange, qVariantFromValue(cursor))); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraCursor, qVariantValue(cursorVariant)); + bool notify = itemChangeEnabled(ItemCursorChange); + QVariant cursorVariant = qVariantFromValue(cursor); + if (notify) + cursorVariant = itemChange(ItemCursorChange, cursorVariant); + d_ptr->setExtra(QGraphicsItemPrivate::ExtraCursor, cursorVariant); d_ptr->hasCursor = 1; if (d_ptr->scene) { d_ptr->scene->d_func()->allItemsUseDefaultCursor = false; @@ -1596,7 +1680,8 @@ void QGraphicsItem::setCursor(const QCursor &cursor) } } } - itemChange(ItemCursorHasChanged, cursorVariant); + if (notify) + itemChange(ItemCursorHasChanged, cursorVariant); } /*! @@ -1693,10 +1778,12 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo if (parent && newVisible && !parent->d_ptr->visible) return; + // Notify + bool notify = q->itemChangeEnabled(QGraphicsItem::ItemVisibleChange); + if (notify) + newVisible = q_ptr->itemChange(QGraphicsItem::ItemVisibleChange, quint32(newVisible)).toBool(); + // Modify the property. - const QVariant newVisibleVariant(q_ptr->itemChange(QGraphicsItem::ItemVisibleChange, - quint32(newVisible))); - newVisible = newVisibleVariant.toBool(); if (visible == quint32(newVisible)) return; visible = newVisible; @@ -1763,7 +1850,8 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo } // Deliver post-change notification. - q_ptr->itemChange(QGraphicsItem::ItemVisibleHasChanged, newVisibleVariant); + if (notify) + q_ptr->itemChange(QGraphicsItem::ItemVisibleHasChanged, newVisible); } /*! @@ -1869,9 +1957,10 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo } // Modify the property. - const QVariant newEnabledVariant(q_ptr->itemChange(QGraphicsItem::ItemEnabledChange, - quint32(newEnabled))); - enabled = newEnabledVariant.toBool(); + bool notify = q_ptr->itemChangeEnabled(QGraphicsItem::ItemEnabledChange); + if (notify) + newEnabled = q_ptr->itemChange(QGraphicsItem::ItemEnabledChange, quint32(newEnabled)).toBool(); + enabled = newEnabled; // Schedule redraw. if (update && scene) @@ -1883,7 +1972,8 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo } // Deliver post-change notification. - q_ptr->itemChange(QGraphicsItem::ItemEnabledHasChanged, newEnabledVariant); + if (notify) + q_ptr->itemChange(QGraphicsItem::ItemEnabledHasChanged, newEnabled); } /*! @@ -1970,10 +2060,13 @@ void QGraphicsItem::setSelected(bool selected) selected = false; if (d_ptr->selected == selected) return; - const QVariant newSelectedVariant(itemChange(ItemSelectedChange, quint32(selected))); - bool newSelected = newSelectedVariant.toBool(); - if (d_ptr->selected == newSelected) - return; + bool notify = itemChangeEnabled(ItemSelectedChange); + bool newSelected = selected; + if (notify) { + newSelected = itemChange(ItemSelectedChange, quint32(selected)).toBool(); + if (d_ptr->selected == newSelected) + return; + } d_ptr->selected = newSelected; if (d_ptr->scene) { @@ -1990,7 +2083,8 @@ void QGraphicsItem::setSelected(bool selected) } // Deliver post-change notification. - itemChange(QGraphicsItem::ItemSelectedHasChanged, newSelectedVariant); + if (notify) + itemChange(QGraphicsItem::ItemSelectedHasChanged, newSelected); } /*! @@ -2056,13 +2150,12 @@ qreal QGraphicsItem::effectiveOpacity() const */ void QGraphicsItem::setOpacity(qreal opacity) { - // Notify change. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - const QVariant newOpacityVariant(itemChange(ItemOpacityChange, double(opacity))); - qreal newOpacity = newOpacityVariant.toDouble(); -#else qreal newOpacity = opacity; -#endif + + // Notify + bool notify = itemChangeEnabled(ItemOpacityChange); + if (notify) + newOpacity = itemChange(ItemOpacityChange, double(newOpacity)).toDouble(); // Normalize. newOpacity = qBound(0.0, newOpacity, 1.0); @@ -2073,10 +2166,9 @@ void QGraphicsItem::setOpacity(qreal opacity) d_ptr->opacity = newOpacity; - // Notify change. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - itemChange(ItemOpacityHasChanged, newOpacity); -#endif + // Notify + if (notify) + itemChange(ItemOpacityHasChanged, newOpacity); // Update. if (d_ptr->scene) @@ -2525,15 +2617,15 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) if (this->pos == pos) return; - // Notify the item that the position is changing. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - const QVariant newPosVariant(q->itemChange(QGraphicsItem::ItemPositionChange, pos)); - QPointF newPos = newPosVariant.toPointF(); - if (newPos == this->pos) - return; -#else QPointF newPos = pos; -#endif + + // Notify + bool notify = q->itemChangeEnabled(QGraphicsItem::ItemPositionChange); + if (notify) { + newPos = q->itemChange(QGraphicsItem::ItemPositionChange, pos).toPointF(); + if (newPos == this->pos) + return; + } // Update and repositition. inSetPosHelper = 1; @@ -2544,9 +2636,9 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) dirtySceneTransform = 1; // Send post-notification. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - q->itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); -#endif + if (notify) + q->itemChange(QGraphicsItem::ItemPositionHasChanged, newPos); + inSetPosHelper = 0; } @@ -2887,21 +2979,21 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co */ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) { - if(!d_ptr->transform) + if (!d_ptr->transform) d_ptr->transform = new QTransform; QTransform newTransform(combine ? QTransform(matrix) * *d_ptr->transform : QTransform(matrix)); - if(*d_ptr->transform == newTransform) + if (*d_ptr->transform == newTransform) return; // Notify the item that the transformation matrix is changing. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - const QVariant newTransformVariant(itemChange(ItemTransformChange, - qVariantFromValue(newTransform))); - newTransform = qVariantValue(newTransformVariant); - if (*d_ptr->transform == newTransform) - return; -#endif + bool notify = itemChangeEnabled(ItemMatrixChange); + if (notify) { + newTransform = QTransform(qVariantValue(itemChange(ItemMatrixChange, + qVariantFromValue(newTransform.toAffine())))); + if (*d_ptr->transform == newTransform) + return; + } // Update and set the new transformation. prepareGeometryChange(); @@ -2909,9 +3001,8 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) d_ptr->dirtySceneTransform = 1; // Send post-notification. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - itemChange(ItemTransformHasChanged, newTransformVariant); -#endif + if (notify) + itemChange(ItemTransformHasChanged, qVariantFromValue(newTransform)); } /*! @@ -2936,19 +3027,20 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) */ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) { - if(!d_ptr->transform) + if (!d_ptr->transform) d_ptr->transform = new QTransform; QTransform newTransform(combine ? matrix * *d_ptr->transform : matrix); - if(*d_ptr->transform == newTransform) + if (*d_ptr->transform == newTransform) return; // Notify the item that the transformation matrix is changing. - const QVariant newTransformVariant(itemChange(ItemTransformChange, - qVariantFromValue(newTransform))); - newTransform = qVariantValue(newTransformVariant); - if (*d_ptr->transform == newTransform) - return; + bool notify = itemChangeEnabled(ItemTransformChange); + if (notify) { + newTransform = qVariantValue(itemChange(ItemTransformChange, qVariantFromValue(newTransform))); + if (*d_ptr->transform == newTransform) + return; + } // Update and set the new transformation. prepareGeometryChange(); @@ -2956,7 +3048,8 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) d_ptr->dirtySceneTransform = 1; // Send post-notification. - itemChange(ItemTransformHasChanged, newTransformVariant); + if (notify) + itemChange(ItemTransformHasChanged, qVariantFromValue(newTransform)); } /*! @@ -3129,10 +3222,13 @@ qreal QGraphicsItem::zValue() const */ void QGraphicsItem::setZValue(qreal z) { - const QVariant newZVariant(itemChange(ItemZValueChange, double(z))); - qreal newZ = qreal(newZVariant.toDouble()); - if (newZ == d_ptr->z) - return; + bool notify = itemChangeEnabled(ItemZValueChange); + qreal newZ = z; + if (notify) { + newZ = itemChange(ItemZValueChange, double(z)).toDouble(); + if (newZ == d_ptr->z) + return; + } d_ptr->z = newZ; d_ptr->needSortChildren = 1; @@ -3143,7 +3239,8 @@ void QGraphicsItem::setZValue(qreal z) d_ptr->scene->d_func()->invalidateSortCache(); } - itemChange(ItemZValueHasChanged, newZVariant); + if (notify) + itemChange(ItemZValueHasChanged, newZ); } /*! diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index 737ea80..7c87176 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -129,6 +129,7 @@ public: ItemZValueHasChanged, ItemOpacityChange, ItemOpacityHasChanged + // NB! Don't forget to increase d_ptr->itemChangesEnabled when adding a new entry. }; enum CacheMode { @@ -165,6 +166,10 @@ public: void setFlag(GraphicsItemFlag flag, bool enabled = true); void setFlags(GraphicsItemFlags flags); + bool itemChangeEnabled(GraphicsItemChange change) const; + void setItemChangeEnabled(GraphicsItemChange change, bool enabled); + void setItemChangesEnabled(bool enabled); + CacheMode cacheMode() const; void setCacheMode(CacheMode mode, const QSize &cacheSize = QSize()); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index b0b940b..2752056 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -147,6 +147,7 @@ public: dirtyChildrenBoundingRect(1), paintedViewBoundingRectsNeedRepaint(0), dirtySceneTransform(1), + itemChangesEnabled(0xffff), globalStackingOrder(-1), q_ptr(0) { @@ -396,7 +397,8 @@ public: quint32 dirtyChildrenBoundingRect : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; quint32 dirtySceneTransform : 1; - quint32 padding : 18; // feel free to use + quint32 itemChangesEnabled : 16; + quint32 padding : 3; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 8641fe2..96800a3 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -666,8 +666,10 @@ void QGraphicsScenePrivate::_q_polishItems() const QVariant booleanTrueVariant(true); foreach (QGraphicsItem *item, unpolishedItems) { if (!item->d_ptr->explicitlyHidden) { - item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant); - item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant); + if (item->itemChangeEnabled(QGraphicsItem::ItemVisibleChange)) { + item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant); + item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant); + } } if (item->isWidget()) { QEvent event(QEvent::Polish); @@ -2950,9 +2952,12 @@ void QGraphicsScene::addItem(QGraphicsItem *item) // Notify the item that its scene is changing, and allow the item to // react. - const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange, - qVariantFromValue(this))); - QGraphicsScene *targetScene = qVariantValue(newSceneVariant); + QGraphicsScene *targetScene = this; + bool notify = item->itemChangeEnabled(QGraphicsItem::ItemSceneChange); + if (notify) { + targetScene = qVariantValue(item->itemChange(QGraphicsItem::ItemSceneChange, + qVariantFromValue(this))); + } if (targetScene != this) { if (targetScene && item->scene() != targetScene) targetScene->addItem(item); @@ -3063,7 +3068,8 @@ void QGraphicsScene::addItem(QGraphicsItem *item) emit selectionChanged(); // Deliver post-change notification - item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); + if (notify) + item->itemChange(QGraphicsItem::ItemSceneHasChanged, qVariantFromValue(targetScene)); } /*! @@ -3327,9 +3333,12 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) // Notify the item that it's scene is changing to 0, allowing the item to // react. - const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange, - qVariantFromValue(0))); - QGraphicsScene *targetScene = qVariantValue(newSceneVariant); + QGraphicsScene *targetScene = 0; + bool notify = item->itemChangeEnabled(QGraphicsItem::ItemSceneChange); + if (notify) { + targetScene = qVariantValue(item->itemChange(QGraphicsItem::ItemSceneChange, + qVariantFromValue(0))); + } if (targetScene != 0 && targetScene != this) { targetScene->addItem(item); return; @@ -3425,7 +3434,8 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) emit selectionChanged(); // Deliver post-change notification - item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); + if (notify) + item->itemChange(QGraphicsItem::ItemSceneHasChanged, qVariantFromValue(targetScene)); } /*! -- cgit v0.12 From b6b0469e2d3aba2a163fab8c4b2fda4ab775b7f7 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Wed, 3 Jun 2009 17:06:24 +0200 Subject: Add BSP tree support to the recursive drawing algorithm. The code looks ugly and needs to be refactored, but at least this reintroduces the BSP so the chip demo works fine again. --- src/gui/graphicsview/qgraphicsscene.cpp | 41 +++++++++++++++++++++++++++------ 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 96800a3..7a6c21c 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5167,22 +5167,49 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } // Find and sort children. - QList &children = item ? item->d_ptr->children : (topLevelItems ? *topLevelItems : this->topLevelItems); + QList tmp; + QList *children = 0; + if (item) { + children = &item->d_ptr->children; + } else if (topLevelItems) { + children = topLevelItems; + } else if (indexMethod == QGraphicsScene::NoIndex || !exposedRegion) { + children = &this->topLevelItems; + } else { + tmp = estimateItemsInRect(viewTransform.inverted().mapRect(exposedRegion->boundingRect())); + + QList tli; + for (int i = 0; i < tmp.size(); ++i) { + QGraphicsItem *it = tmp.at(i)->topLevelItem(); + if (!it->d_ptr->itemDiscovered) { + tli << it; + it->d_ptr->itemDiscovered = 1; + } + } + for (int i = 0; i < tli.size(); ++i) + tli.at(i)->d_ptr->itemDiscovered = 0; + + tmp = tli; + children = &tmp; + } + if (!dontDrawChildren) { if (item && item->d_ptr->needSortChildren) { item->d_ptr->needSortChildren = 0; - qStableSort(children.begin(), children.end(), qt_notclosestLeaf); + qStableSort(children->begin(), children->end(), qt_notclosestLeaf); } else if (!item && needSortTopLevelItems) { needSortTopLevelItems = false; - qStableSort(children.begin(), children.end(), qt_notclosestLeaf); + qStableSort(children->begin(), children->end(), qt_notclosestLeaf); + } else if (!item && children == &tmp) { + qStableSort(children->begin(), children->end(), qt_notclosestLeaf); } } // Draw children behind int i = 0; if (!dontDrawChildren) { - for (i = 0; i < children.size(); ++i) { - QGraphicsItem *child = children.at(i); + for (i = 0; i < children->size(); ++i) { + QGraphicsItem *child = children->at(i); if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) @@ -5213,8 +5240,8 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Draw children in front if (!dontDrawChildren) { - for (; i < children.size(); ++i) { - QGraphicsItem *child = children.at(i); + for (; i < children->size(); ++i) { + QGraphicsItem *child = children->at(i); if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, -- cgit v0.12 From 5127105efd8f76721d7d9acf9681fd18e73760d8 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 4 Jun 2009 15:16:40 +0200 Subject: Fix clipping bug, move code to avoid unintentional shadowing. The children variable tested for clipping was the wrong variable. This broke when the code was moved down as part of a previous cleanup change. Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsscene.cpp | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 7a6c21c..a137b06 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5152,20 +5152,6 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } } - bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); - bool dontDrawItem = !item || viewBoundingRect.isEmpty(); - bool dontDrawChildren = item && dontDrawItem && childClip; - childClip &= !dontDrawChildren & !children.isEmpty(); - if (item && item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) - dontDrawItem = true; - - // Clip children. - if (childClip) { - painter->save(); - painter->setWorldTransform(transformTmp); - painter->setClipPath(item->shape(), Qt::IntersectClip); - } - // Find and sort children. QList tmp; QList *children = 0; @@ -5192,6 +5178,20 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * tmp = tli; children = &tmp; } + + bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); + bool dontDrawItem = !item || viewBoundingRect.isEmpty(); + bool dontDrawChildren = item && dontDrawItem && childClip; + childClip &= !dontDrawChildren & !children->isEmpty(); + if (item && item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) + dontDrawItem = true; + + // Clip children. + if (childClip) { + painter->save(); + painter->setWorldTransform(transformTmp); + painter->setClipPath(item->shape(), Qt::IntersectClip); + } if (!dontDrawChildren) { if (item && item->d_ptr->needSortChildren) { -- cgit v0.12 From 2e8a236108f5b78c4d61a254f4097ccf271f90cb Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 4 Jun 2009 15:35:53 +0200 Subject: Ensure we can find and draw items whose size is (0x0). This removes a microoptimization we did to avoid processing items whose size was (0x0). Turns out an autotest started failing if we did this - we have to find and draw such items because they are commonly used to draw points (e.g., plot graphs). Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsscene.cpp | 61 +++++++++++++++------------------ 1 file changed, 27 insertions(+), 34 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index a137b06..bb26bb6 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -297,13 +297,9 @@ static inline bool QRectF_intersects(const QRectF &s, const QRectF &r) static inline void _q_adjustRect(QRectF *rect) { Q_ASSERT(rect); - bool nullWidth = !rect->width(); - bool nullHeight = !rect->height(); - if (nullWidth && nullHeight) - return; - if (nullWidth) + if (!rect->width()) rect->adjust(-0.00001, 0, 0.00001, 0); - else if (nullHeight) + if (!rect->height()) rect->adjust(0, -0.00001, 0, 0.00001); } @@ -1413,33 +1409,26 @@ void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF r if (item) { item->d_ptr->combineTransformFromParent(&transform, &viewTransform); + // ### This does not take the clip into account. QRectF brect = item->boundingRect(); - if (!brect.size().isNull()) { - // ### This does not take the clip into account. - _q_adjustRect(&brect); - - keep = true; - if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) - keep = rect.contains(transform.mapRect(brect)); - else - keep = rect.intersects(transform.mapRect(brect)); - - if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { - QPainterPath rectPath; - rectPath.addRect(rect); - keep = item->collidesWithPath(transform.inverted().map(rectPath)); - } + _q_adjustRect(&brect); + + keep = true; + if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) + keep = rect.contains(transform.mapRect(brect)); + else + keep = rect.intersects(transform.mapRect(brect)); + + if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { + QPainterPath rectPath; + rectPath.addRect(rect); + keep = item->collidesWithPath(transform.inverted().map(rectPath)); } } bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); bool dontProcessItem = !item || !keep; bool dontProcessChildren = item && dontProcessItem && childClip; - childClip &= !dontProcessChildren & !children.isEmpty(); - - // Clip. - if (childClip) - rect &= transform.map(item->shape()).controlPointRect(); // Find and sort children. QList &children = item ? item->d_ptr->children : const_cast(this)->topLevelItems; @@ -1453,6 +1442,12 @@ void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF r } } + childClip &= !dontProcessChildren & !children.isEmpty(); + + // Clip. + if (childClip) + rect &= transform.map(item->shape()).controlPointRect(); + // Process children behind int i = 0; if (!dontProcessChildren) { @@ -5142,14 +5137,12 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } QRectF brect = item->boundingRect(); - if (!brect.size().isNull()) { - // ### This does not take the clip into account. - _q_adjustRect(&brect); - viewBoundingRect = transformTmp.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); - item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect); - if (exposedRegion) - viewBoundingRect &= exposedRegion->boundingRect(); - } + // ### This does not take the clip into account. + _q_adjustRect(&brect); + viewBoundingRect = transformTmp.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); + item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect); + if (exposedRegion) + viewBoundingRect &= exposedRegion->boundingRect(); } // Find and sort children. -- cgit v0.12 From ba48a3fdf39a3db7a3d13ac15031c810454c6e25 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 4 Jun 2009 15:59:25 +0200 Subject: Fix bug in QGraphicsItem::effectiveOpacity() caused by typo. See change 72842b2d, the patch misplaces 'p' and 'parent'. This fixes the tst_QGraphicsItem::opacity autotests. Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsitem_p.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 2752056..9be9310 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -296,10 +296,11 @@ public: // parent propagates to me, then combine my local opacity with my parent's // effective opacity into my effective opacity. if ((myFlags & QGraphicsItem::ItemIgnoresParentOpacity) - || (parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) + || (parentFlags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) { break; + } - o *= parent->d_ptr->opacity; + o *= p->d_ptr->opacity; p = p->d_ptr->parent; myFlags = parentFlags; } -- cgit v0.12 From 32c00c1d30eb275f44ba9d0bff4d6b6b05e9a5ba Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 4 Jun 2009 16:49:10 +0200 Subject: Fix rendering of items that ignore parent opacity. Test if the children ignore the parent's opacity if the current item's opacity is 0.0. If any of the children do ignore the parent then we must continue. Further optimizations are possible: if the item itself is transparent, then don't visit children that don't ignore parent opacity. Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsscene.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index bb26bb6..c46ed68 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5101,6 +5101,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * { // Calculate opacity. qreal opacity; + bool invisibleButChildIgnoresParentOpacity = false; if (item) { if (!item->d_ptr->visible) return; @@ -5112,8 +5113,11 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } else { opacity = item->d_ptr->opacity; } - if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) - return; + if (opacity == 0.0 && !(item->d_ptr->flags & QGraphicsItem::ItemDoesntPropagateOpacityToChildren)) { + invisibleButChildIgnoresParentOpacity = !item->d_ptr->childrenCombineOpacity(); + if (!invisibleButChildIgnoresParentOpacity) + return; + } } else { opacity = parentOpacity; } @@ -5176,7 +5180,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * bool dontDrawItem = !item || viewBoundingRect.isEmpty(); bool dontDrawChildren = item && dontDrawItem && childClip; childClip &= !dontDrawChildren & !children->isEmpty(); - if (item && item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) + if (item && (item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) || invisibleButChildIgnoresParentOpacity) dontDrawItem = true; // Clip children. @@ -5201,6 +5205,8 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Draw children behind int i = 0; if (!dontDrawChildren) { + // ### Don't visit children that don't ignore parent opacity if this + // item is invisible. for (i = 0; i < children->size(); ++i) { QGraphicsItem *child = children->at(i); if (wasDirtyParentSceneTransform) @@ -5233,6 +5239,8 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Draw children in front if (!dontDrawChildren) { + // ### Don't visit children that don't ignore parent opacity if this + // item is invisible. for (; i < children->size(); ++i) { QGraphicsItem *child = children->at(i); if (wasDirtyParentSceneTransform) -- cgit v0.12 From 9eb253eed0ae75d1d32b5e738ead89434fc69837 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 4 Jun 2009 17:07:58 +0200 Subject: Fix stacking order bug, ensure the dirty sort bits are set correctly. The code marked the item's own stacking order as dirty when changing its own Z value, the right thing is however to set the _parent's_ bit. Also added missing code for when the ItemStacksBehindParent flag was toggled. Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsitem.cpp | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 2eb5150..47a9ae2 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1442,6 +1442,14 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) d_ptr->updateAncestorFlag(ItemIgnoresTransformations); } + if ((flags & ItemStacksBehindParent) != (oldFlags & ItemStacksBehindParent)) { + // Ensure child item sorting is up to date when toggling this flag. + if (d_ptr->parent) + d_ptr->parent->d_ptr->needSortChildren = 1; + else if (d_ptr->scene) + d_ptr->scene->d_func()->needSortTopLevelItems = 1; + } + if (d_ptr->scene) { d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true, @@ -3230,7 +3238,10 @@ void QGraphicsItem::setZValue(qreal z) return; } d_ptr->z = newZ; - d_ptr->needSortChildren = 1; + if (d_ptr->parent) + d_ptr->parent->d_ptr->needSortChildren = 1; + else if (d_ptr->scene) + d_ptr->scene->d_func()->needSortTopLevelItems = 1; if (d_ptr->scene) { d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true); -- cgit v0.12 From a47b632971068001d56471a9cb78ad983c4a9fee Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 4 Jun 2009 17:12:42 +0200 Subject: Ensure this test goes via QGraphicsScene::drawItems(). Enable QGraphicsView::IndirectPainting to make sure it detects which items are drawn. --- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 9cfd897..427ecf3 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -5874,6 +5874,7 @@ void tst_QGraphicsItem::nestedClipping() l3->setData(0, "l3"); QGraphicsView view(&scene); + view.setOptimizationFlag(QGraphicsView::IndirectPainting); view.show(); #ifdef Q_WS_X11 qt_x11_wait_for_window_manager(&view); -- cgit v0.12 From 4f3a8e82fd6b328a06990517648f0d46c50ff41e Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Thu, 4 Jun 2009 17:26:57 +0200 Subject: Ensure we pass the intersect mode when checking item collisions. This fixes one of two failures in tst_QGraphicsScene::items_QRectF_2. The other seems unrelated. --- src/gui/graphicsview/qgraphicsscene.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index c46ed68..6a79dde 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -1422,7 +1422,7 @@ void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF r if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath rectPath; rectPath.addRect(rect); - keep = item->collidesWithPath(transform.inverted().map(rectPath)); + keep = item->collidesWithPath(transform.inverted().map(rectPath), mode); } } -- cgit v0.12 From 98f197d1a11c3dd13959967534b1dba7eea479ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 4 Jun 2009 11:56:40 +0200 Subject: Avoid falling in the else case when there are no views. Partially fixes tst_QGraphicsScene::update failure. --- src/gui/graphicsview/qgraphicsscene.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 6a79dde..df3153f 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -601,7 +601,7 @@ void QGraphicsScenePrivate::_q_emitUpdated() // the optimization that items send updates directly to the views, but it // needs to happen in order to keep compatibility with the behavior from // Qt 4.4 and backward. - if (!views.isEmpty() && (connectedSignals & changedSignalMask)) { + if (connectedSignals & changedSignalMask) { for (int i = 0; i < views.size(); ++i) { QGraphicsView *view = views.at(i); if (!view->d_func()->connectedToScene) { -- cgit v0.12 From ad92e095ea34dda9d099fae30340a8fbb4c5380a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 4 Jun 2009 17:31:47 +0200 Subject: Compatibility fix for QGraphicsScene::sceneRectChanged()/sceneRect(). We have to keep the growingItemsBoundingRect up-to-date if there's no scene rect. The only difference now is that sceneRectChanged will not be emitted before entering the event-loop, but the documentation only states it'll be emitted when the scene rect changes, so we consider it harmless. Makes tst_QGraphicsView::sceneRect_growing and tst_QGrahicsScene::sceneRect happy. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 1 + src/gui/graphicsview/qgraphicsitem_p.h | 4 ++- src/gui/graphicsview/qgraphicsscene.cpp | 33 +++++++++++++++++------- src/gui/graphicsview/qgraphicsscene_p.h | 5 +++- tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp | 2 ++ 5 files changed, 34 insertions(+), 11 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 47a9ae2..807ee06 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -5977,6 +5977,7 @@ void QGraphicsItem::removeFromIndex() void QGraphicsItem::prepareGeometryChange() { if (d_ptr->scene) { + d_ptr->geometryChanged = 1; d_ptr->paintedViewBoundingRectsNeedRepaint = 1; d_ptr->scene->d_func()->markDirty(this, QRectF(), /*invalidateChildren=*/true, diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 9be9310..d884b16 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -148,6 +148,7 @@ public: paintedViewBoundingRectsNeedRepaint(0), dirtySceneTransform(1), itemChangesEnabled(0xffff), + geometryChanged(0), globalStackingOrder(-1), q_ptr(0) { @@ -399,7 +400,8 @@ public: quint32 paintedViewBoundingRectsNeedRepaint : 1; quint32 dirtySceneTransform : 1; quint32 itemChangesEnabled : 16; - quint32 padding : 3; // feel free to use + quint32 geometryChanged : 1; + quint32 padding : 2; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index df3153f..c738f80 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -39,7 +39,6 @@ ** ****************************************************************************/ -static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000; /*! \class QGraphicsScene @@ -682,7 +681,11 @@ void QGraphicsScenePrivate::_q_processDirtyItems() if (updateAll) return; + const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect; processDirtyItemsRecursive(0); + if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect) + emit q_func()->sceneRectChanged(growingItemsBoundingRect); + for (int i = 0; i < views.size(); ++i) views.at(i)->d_func()->processPendingUpdates(); } @@ -808,13 +811,13 @@ void QGraphicsScenePrivate::purgeRemovedItems() Starts or restarts the timer used for reindexing unindexed items. */ -void QGraphicsScenePrivate::startIndexTimer() +void QGraphicsScenePrivate::startIndexTimer(int interval) { Q_Q(QGraphicsScene); if (indexTimerId) { restartIndexTimer = true; } else { - indexTimerId = q->startTimer(QGRAPHICSSCENE_INDEXTIMER_TIMEOUT); + indexTimerId = q->startTimer(interval); } } @@ -2982,7 +2985,7 @@ void QGraphicsScene::addItem(QGraphicsItem *item) // a temporary list and schedule an indexing for later. d->unindexedItems << item; item->d_func()->index = -1; - d->startIndexTimer(); + d->startIndexTimer(0); // Add to list of toplevels if this item is a toplevel. if (!item->d_ptr->parent) @@ -5315,16 +5318,27 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool // Process item. if (item && (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint)) { const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask); - if (useCompatUpdate && !item->d_ptr->itemIsUntransformable() - && qFuzzyIsNull(item->boundingRegionGranularity())) { + const bool untransformableItem = item->d_ptr->itemIsUntransformable(); + const QRectF itemBoundingRect = item->boundingRect(); + + if (item->d_ptr->geometryChanged) { + // Update growingItemsBoundingRect. + if (!hasSceneRect) { + QRectF itemSceneBoundingRect = item->d_ptr->sceneTransform.mapRect(itemBoundingRect); + _q_adjustRect(&itemSceneBoundingRect); + growingItemsBoundingRect |= itemSceneBoundingRect; + } + item->d_ptr->geometryChanged = 0; + } + + if (useCompatUpdate && !untransformableItem && qFuzzyIsNull(item->boundingRegionGranularity())) { // This block of code is kept for compatibility. Since 4.5, by default // QGraphicsView does not connect the signal and we use the below // method of delivering updates. - q->update(item->sceneBoundingRect()); + q->update(item->d_ptr->sceneTransform.mapRect(itemBoundingRect)); } else { QRectF dirtyRect; bool uninitializedDirtyRect = true; - const bool untransformableItem = item->d_ptr->itemIsUntransformable(); for (int j = 0; j < views.size(); ++j) { QGraphicsView *view = views.at(j); @@ -5349,7 +5363,8 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool continue; if (uninitializedDirtyRect) { - dirtyRect = adjustedItemBoundingRect(item); + dirtyRect = itemBoundingRect; + _q_adjustRect(&dirtyRect); if (!item->d_ptr->fullUpdatePending) { _q_adjustRect(&item->d_ptr->needsRepaint); dirtyRect &= item->d_ptr->needsRepaint; diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index f4964f2..fd7decf 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -71,6 +71,8 @@ #include #include +static const int QGRAPHICSSCENE_INDEXTIMER_TIMEOUT = 2000; + QT_BEGIN_NAMESPACE class QGraphicsView; @@ -138,7 +140,7 @@ public: int indexTimerId; bool restartIndexTimer; - void startIndexTimer(); + void startIndexTimer(int interval = QGRAPHICSSCENE_INDEXTIMER_TIMEOUT); bool stickyFocus; bool hasFocus; @@ -270,6 +272,7 @@ public: Q_ASSERT(item); item->d_ptr->dirty = 0; item->d_ptr->paintedViewBoundingRectsNeedRepaint = 0; + item->d_ptr->geometryChanged = 0; item->d_ptr->dirtyChildren = 0; item->d_ptr->needsRepaint = QRectF(); item->d_ptr->allChildrenDirty = 0; diff --git a/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp b/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp index 23d7a94..9f93ae0 100644 --- a/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp +++ b/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp @@ -274,7 +274,9 @@ void tst_QGraphicsScene::sceneRect() QCOMPARE(scene.sceneRect(), QRectF()); QGraphicsItem *item = scene.addRect(QRectF(0, 0, 10, 10)); + qApp->processEvents(); item->setPos(-5, -5); + qApp->processEvents(); QCOMPARE(scene.itemAt(0, 0), item); QCOMPARE(scene.itemAt(10, 10), (QGraphicsItem *)0); -- cgit v0.12 From ed0b10aff5d0afb7e8165dbf9b14f30cfd73e3ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 4 Jun 2009 18:06:24 +0200 Subject: Make sure we reset the updateAll variable correctly. Makes tst_QGraphicsScene::update happy. --- src/gui/graphicsview/qgraphicsscene.cpp | 1 + tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp | 1 + 2 files changed, 2 insertions(+) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index c738f80..4578bd4 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -610,6 +610,7 @@ void QGraphicsScenePrivate::_q_emitUpdated() } } } else { + updateAll = false; for (int i = 0; i < views.size(); ++i) views.at(i)->d_func()->processPendingUpdates(); return; diff --git a/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp b/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp index 9f93ae0..8bb9122 100644 --- a/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp +++ b/tests/auto/qgraphicsscene/tst_qgraphicsscene.cpp @@ -2715,6 +2715,7 @@ void tst_QGraphicsScene::update() QGraphicsRectItem *rect = new QGraphicsRectItem(0, 0, 100, 100); scene.addItem(rect); + qApp->processEvents(); rect->setPos(-100, -100); // This function forces indexing -- cgit v0.12 From 9def469f9f83087fab9cb65c0200f2e6059519ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 4 Jun 2009 19:32:19 +0200 Subject: Compatibility fix for QGraphicsScene::changed signal. Makes tst_QGraphicsScene::changedSignal and tst_QGraphicsItem::setMatrix happy. --- src/gui/graphicsview/qgraphicsitem.cpp | 17 ++++++++++++++--- src/gui/graphicsview/qgraphicsscene.cpp | 8 ++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 807ee06..a2d885b 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -5979,10 +5979,21 @@ void QGraphicsItem::prepareGeometryChange() if (d_ptr->scene) { d_ptr->geometryChanged = 1; d_ptr->paintedViewBoundingRectsNeedRepaint = 1; - d_ptr->scene->d_func()->markDirty(this, QRectF(), - /*invalidateChildren=*/true, - /*maybeDirtyClipPath=*/!d_ptr->inSetPosHelper); + QGraphicsScenePrivate *scenePrivate = d_ptr->scene->d_func(); + scenePrivate->markDirty(this, QRectF(), + /*invalidateChildren=*/true, + /*maybeDirtyClipPath=*/!d_ptr->inSetPosHelper); + + // For compatibility reasons, we have to update the item's old geometry + // if someone is connected to the changed signal or the scene has no views. + // Note that this has to be done *after* markDirty to ensure that + // _q_processDirtyItems is called before _q_emitUpdated. + if ((scenePrivate->connectedSignals & scenePrivate->changedSignalMask) + || scenePrivate->views.isEmpty()) { + d_ptr->scene->update(sceneTransform().mapRect(boundingRect())); + } + scenePrivate->removeFromIndex(this); } diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 4578bd4..c7a41d6 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -682,6 +682,7 @@ void QGraphicsScenePrivate::_q_processDirtyItems() if (updateAll) return; + const bool wasPendingSceneUpdate = calledEmitUpdated; const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect; processDirtyItemsRecursive(0); if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect) @@ -689,6 +690,13 @@ void QGraphicsScenePrivate::_q_processDirtyItems() for (int i = 0; i < views.size(); ++i) views.at(i)->d_func()->processPendingUpdates(); + + if (!wasPendingSceneUpdate && calledEmitUpdated) { + // We did a compatibility QGraphicsScene::update in processDirtyItemsRecursive + // and we cannot wait for the control to reach the eventloop before the + // changed signal is emitted, so we emit it now. + _q_emitUpdated(); + } } /*! -- cgit v0.12 From f1ada923f7bbe8724d9a9d6a6b391a92c514c440 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 4 Jun 2009 19:51:41 +0200 Subject: Discard updates outside the bounding rect. Makes tst_QGraphicsItem::cacheMode happy. --- src/gui/graphicsview/qgraphicsitem.cpp | 2 +- src/gui/graphicsview/qgraphicsscene.cpp | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index a2d885b..80ad19d 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -4168,7 +4168,7 @@ void QGraphicsItem::update(const QRectF &rect) } if (d_ptr->scene) - d_ptr->scene->d_func()->markDirty(this); + d_ptr->scene->d_func()->markDirty(this, rect); } /*! diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index c7a41d6..e5c65d1 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5381,6 +5381,9 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool uninitializedDirtyRect = false; } + if (dirtyRect.isEmpty()) + continue; // Discard updates outside the bounding rect. + QTransform deviceTransform = item->d_ptr->sceneTransform; if (view->isTransformed()) { if (!untransformableItem) -- cgit v0.12 From 4af92dcf716ee3c2fc4673aadd07fde19b7bffed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 4 Jun 2009 19:57:04 +0200 Subject: Make sure the dirty state of an item is reset when removed from the scene. Makes tst_QGraphicsItem::paint happy. --- src/gui/graphicsview/qgraphicsscene.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index e5c65d1..eaf00a0 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -758,6 +758,7 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) cachedItemsUnderMouse.removeAll(item); unpolishedItems.removeAll(item); pendingUpdateItems.removeAll(item); + resetDirtyItem(item); //We remove all references of item from the sceneEventFilter arrays QMultiMap::iterator iterator = sceneEventFilters.begin(); @@ -3408,6 +3409,7 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) d->pendingUpdateItems.removeAll(item); d->cachedItemsUnderMouse.removeAll(item); d->unpolishedItems.removeAll(item); + d->resetDirtyItem(item); //We remove all references of item from the sceneEventFilter arrays QMultiMap::iterator iterator = d->sceneEventFilters.begin(); -- cgit v0.12 From 9aa44bff88f377f056eafe5d9f24c88d81f477e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 4 Jun 2009 20:58:34 +0200 Subject: Removes odd artifact in the chip demo. Calling repaint() instead of update() is bad when having multiple views (which GV perfectly supports). The result is that e.g. when moving a chip in the chip demo, there's a visible lag between each view. It can also be a performance killer on QWS, where the surface is locked for each repaint(). Instead of calling repaint() we call update() as before, but we also make sure the updates are processed immediately. --- src/gui/graphicsview/qgraphicsscene.cpp | 9 +++++++++ src/gui/graphicsview/qgraphicsview.cpp | 6 +++--- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index eaf00a0..4b54c08 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -697,6 +697,15 @@ void QGraphicsScenePrivate::_q_processDirtyItems() // changed signal is emitted, so we emit it now. _q_emitUpdated(); } + + // Immediately dispatch all pending update requests on the views. + for (int i = 0; i < views.size(); ++i) { + QWidget *viewport = views.at(i)->d_func()->viewport; + if (qt_widget_private(viewport)->paintOnScreen()) + QCoreApplication::sendPostedEvents(viewport, QEvent::UpdateRequest); + else + QCoreApplication::sendPostedEvents(viewport->window(), QEvent::UpdateRequest); + } } /*! diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index c91e0d1..87b5e3f 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -814,11 +814,11 @@ void QGraphicsViewPrivate::processPendingUpdates() if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) { if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) - viewport->repaint(dirtyBoundingRect); + viewport->update(dirtyBoundingRect); else - viewport->repaint(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); + viewport->update(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); } else { - viewport->repaint(dirtyRegion); // Already adjusted in updateRect/Region. + viewport->update(dirtyRegion); // Already adjusted in updateRect/Region. } dirtyBoundingRect = QRect(); -- cgit v0.12 From 5ab06593a1ed4c050d19f734737a50078b0fbb52 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 5 Jun 2009 09:00:21 +0200 Subject: Fix tst_QGraphicsView::acceptMousePressEvent (by entering event loop). This is necessary after we made the sceneRect grow lazily when it's not assigned. --- tests/auto/qgraphicsview/tst_qgraphicsview.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/auto/qgraphicsview/tst_qgraphicsview.cpp b/tests/auto/qgraphicsview/tst_qgraphicsview.cpp index 8e490ad..718c8d6 100644 --- a/tests/auto/qgraphicsview/tst_qgraphicsview.cpp +++ b/tests/auto/qgraphicsview/tst_qgraphicsview.cpp @@ -2525,6 +2525,8 @@ void tst_QGraphicsView::acceptMousePressEvent() scene.addRect(0, 0, 2000, 2000)->setFlag(QGraphicsItem::ItemIsMovable); + qApp->processEvents(); // ensure scene rect is updated + QApplication::sendEvent(view.viewport(), &event); QVERIFY(view.accepted); } -- cgit v0.12 From 1c0599289a3da43b0a7cdb38eebe05d45f69ad9c Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 5 Jun 2009 10:11:05 +0200 Subject: Fix tst_QGraphicsView::cursor2() - sorting bug when using BSP tree. Make sure we don't claim that we have sorted all toplevel items when we are using the BSP tree, as when painting we have only actually sorted a subset of the elements. --- src/gui/graphicsview/qgraphicsscene.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 4b54c08..6c78ca9 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5217,11 +5217,11 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (item && item->d_ptr->needSortChildren) { item->d_ptr->needSortChildren = 0; qStableSort(children->begin(), children->end(), qt_notclosestLeaf); + } else if (!item && children == &tmp) { + qStableSort(children->begin(), children->end(), qt_notclosestLeaf); } else if (!item && needSortTopLevelItems) { needSortTopLevelItems = false; qStableSort(children->begin(), children->end(), qt_notclosestLeaf); - } else if (!item && children == &tmp) { - qStableSort(children->begin(), children->end(), qt_notclosestLeaf); } } -- cgit v0.12 From a10f1c955f9cbf54909ce2264279efa9d0423ecd Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 5 Jun 2009 10:23:37 +0200 Subject: Fix tst_QGraphicsScene::itemIndexMethod(), typo in estimateItemsInRect() Don't skip all indexed items that aren't transparent ;-). --- src/gui/graphicsview/qgraphicsscene.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 6c78ca9..49ffb32 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -422,7 +422,7 @@ QList QGraphicsScenePrivate::estimateItemsInRect(const QRectF & if (QGraphicsItem *item = indexedItems.at(i)) { if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorClipsChildren) continue; - if (item->d_ptr->visible && item->d_ptr->isFullyTransparent()) + if (item->d_ptr->visible && !item->d_ptr->isFullyTransparent()) itemsInRect << item; } } -- cgit v0.12 From b7b0f7250dcf07a4da5d80ccc48accb156f25092 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 5 Jun 2009 10:41:22 +0200 Subject: Fix tst_QGraphicsScene::items_QRectF_2(), an intersection bug. The recursive items function didn't contain the special case check for when the source and target rectangle are identical. --- src/gui/graphicsview/qgraphicsscene.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 49ffb32..8958e1b 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -1437,7 +1437,7 @@ void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF r keep = true; if (mode == Qt::ContainsItemShape || mode == Qt::ContainsItemBoundingRect) - keep = rect.contains(transform.mapRect(brect)); + keep = rect.contains(transform.mapRect(brect)) && rect != brect; else keep = rect.intersects(transform.mapRect(brect)); -- cgit v0.12 From f31b4a7163cee11c306e9f4fcaab094d9c38cb68 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 5 Jun 2009 11:02:46 +0200 Subject: Fix interaction with QGraphicsWidgets that are a window. Use itemCollidesWithPath, the helper function. --- src/gui/graphicsview/qgraphicsscene.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 8958e1b..de9d865 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -1444,7 +1444,7 @@ void QGraphicsScenePrivate::recursive_items_helper(QGraphicsItem *item, QRectF r if (keep && (mode == Qt::ContainsItemShape || mode == Qt::IntersectsItemShape)) { QPainterPath rectPath; rectPath.addRect(rect); - keep = item->collidesWithPath(transform.inverted().map(rectPath), mode); + keep = itemCollidesWithPath(item, transform.inverted().map(rectPath), mode); } } -- cgit v0.12 From e83cc0aca3bab0d37c4d0679319017f4cfeacfe0 Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Fri, 5 Jun 2009 12:54:04 +0200 Subject: Fix warning. --- src/gui/graphicsview/qgraphicsscene.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index de9d865..7bfc032 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5202,8 +5202,8 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); bool dontDrawItem = !item || viewBoundingRect.isEmpty(); bool dontDrawChildren = item && dontDrawItem && childClip; - childClip &= !dontDrawChildren & !children->isEmpty(); - if (item && (item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) || invisibleButChildIgnoresParentOpacity) + childClip &= !dontDrawChildren && !children->isEmpty(); + if (item && ((item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) || invisibleButChildIgnoresParentOpacity)) dontDrawItem = true; // Clip children. -- cgit v0.12 From 9cafd6bcf6f91c027904c998a0dd536feac8d4e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Mon, 8 Jun 2009 10:55:48 +0200 Subject: Child items leave traces when moving an ancestor item. The problem was that we only marked the painted view bounding rect of the moved item as dirty. We also have to mark its children. --- src/gui/graphicsview/qgraphicsscene.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 7bfc032..caf9309 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5336,6 +5336,7 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool } // Process item. + bool wasDirtyParentViewBoundingRects = false; if (item && (item->d_ptr->dirty || item->d_ptr->paintedViewBoundingRectsNeedRepaint)) { const bool useCompatUpdate = views.isEmpty() || (connectedSignals & changedSignalMask); const bool untransformableItem = item->d_ptr->itemIsUntransformable(); @@ -5376,8 +5377,10 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool break; } - if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) + if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) { + wasDirtyParentViewBoundingRects = true; viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + } if (!item->d_ptr->dirty) continue; @@ -5422,6 +5425,8 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool QGraphicsItem *child = children->at(i); if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; + if (wasDirtyParentViewBoundingRects) + child->d_ptr->paintedViewBoundingRectsNeedRepaint = 1; if (allChildrenDirty) { child->d_ptr->dirty = 1; -- cgit v0.12 From 0095e40b2efc0c43c0d908bb5b9828619bc087e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Mon, 8 Jun 2009 13:09:14 +0200 Subject: QGraphicsItem discard updates when it shouldn't. Once a _q_processDirtyItems call is queued, it means we at least have one item that is marked as dirty and we must reset it when the _q_processDirtyItems slot is called. The problem however, was that we didn't reset the item's dirty state if a full scene update occurred in between, i.e. item->update(); scene.update(); We don't have to calculate the item's dirty rect if a full scene update occurs in between, but we still have to reset its state. Auto-test included. --- src/gui/graphicsview/qgraphicsscene.cpp | 13 ++++++------ src/gui/graphicsview/qgraphicsview.cpp | 1 + tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 28 ++++++++++++++++++++++++++ 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index caf9309..ad392b0 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -679,19 +679,19 @@ void QGraphicsScenePrivate::_q_processDirtyItems() { processDirtyItemsEmitted = false; - if (updateAll) - return; - const bool wasPendingSceneUpdate = calledEmitUpdated; const QRectF oldGrowingItemsBoundingRect = growingItemsBoundingRect; processDirtyItemsRecursive(0); if (!hasSceneRect && oldGrowingItemsBoundingRect != growingItemsBoundingRect) emit q_func()->sceneRectChanged(growingItemsBoundingRect); + if (wasPendingSceneUpdate) + return; + for (int i = 0; i < views.size(); ++i) views.at(i)->d_func()->processPendingUpdates(); - if (!wasPendingSceneUpdate && calledEmitUpdated) { + if (calledEmitUpdated) { // We did a compatibility QGraphicsScene::update in processDirtyItemsRecursive // and we cannot wait for the control to reach the eventloop before the // changed signal is emitted, so we emit it now. @@ -5322,7 +5322,6 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren) { - Q_ASSERT(!item || item->d_ptr->dirty || item->d_ptr->dirtyChildren); Q_Q(QGraphicsScene); // Calculate the full scene transform for this item. @@ -5438,13 +5437,15 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool continue; } - if (dirtyAncestorContainsChildren) { + if (dirtyAncestorContainsChildren || updateAll) { // No need to process this child's dirty rect, hence reset the dirty state. // However, we have to continue the recursion because it might have a dirty // view bounding rect that needs repaint. We also have to reset the dirty // state of its descendants. child->d_ptr->dirty = 0; child->d_ptr->fullUpdatePending = 0; + if (updateAll) + child->d_ptr->paintedViewBoundingRectsNeedRepaint = 0; } processDirtyItemsRecursive(child, dirtyAncestorContainsChildren); diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 87b5e3f..a9fc563 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -2496,6 +2496,7 @@ void QGraphicsView::updateScene(const QList &rects) for (int i = 0; i < dirtyRects.size(); ++i) dirtyViewportRects += dirtyRects.at(i); d->dirtyRegion = QRegion(); + d->dirtyBoundingRect = QRect(); bool fullUpdate = !d->accelerateScrolling || d->viewportUpdateMode == QGraphicsView::FullViewportUpdate; bool boundingRectUpdate = (d->viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 427ecf3..5b297f6 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -219,6 +219,7 @@ private slots: void updateCachedItemAfterMove(); void deviceTransform_data(); void deviceTransform(); + void update(); // task specific tests below me void task141694_textItemEnsureVisible(); @@ -6427,5 +6428,32 @@ void tst_QGraphicsItem::deviceTransform() QCOMPARE(rect3->deviceTransform(deviceX).map(QPointF(50, 50)), mapResult3); } +void tst_QGraphicsItem::update() +{ + QGraphicsScene scene; + QGraphicsView view(&scene); + view.show(); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&view); +#endif + QTest::qWait(100); + + EventTester *item = new EventTester; + scene.addItem(item); + QTest::qWait(100); // Make sure all pending updates are processed. + item->repaints = 0; + + item->update(); // Item marked as dirty + scene.update(); // Entire scene marked as dirty + qApp->processEvents(); + QCOMPARE(item->repaints, 1); + + // Make sure the dirty state from the previous update is reset so that + // the item don't think it is already dirty and discards this update. + item->update(); + qApp->processEvents(); + QCOMPARE(item->repaints, 2); +} + QTEST_MAIN(tst_QGraphicsItem) #include "tst_qgraphicsitem.moc" -- cgit v0.12 From 9ed567ca68d51552f89887aa5a300a5f6a6d8ac3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Mon, 8 Jun 2009 13:55:16 +0200 Subject: A partial QGraphicsItem update causes a full update to be discarded. E.g. item->update(QRectF(0, 0, 5, 5)); item->update(); The problem was that we discarded all update requests whenever the item was already marked as dirty. The dirty bit only means it has pending updates (which might be a full update). However, we have a separate bit for full updates (fullUpdatePending) so we have to check against that bit instead. Makes tst_QGraphicsProxyWidget::paintEvent happy. Another auto-test included. --- src/gui/graphicsview/qgraphicsitem.cpp | 4 ++-- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 31 +++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 80ad19d..2a062ab 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -3907,7 +3907,7 @@ bool QGraphicsItemPrivate::discardUpdateRequest(bool ignoreClipping, bool ignore // No scene, or if the scene is updating everything, means we have nothing // to do. The only exception is if the scene tracks the growing scene rect. return (!visible && !ignoreVisibleBit) - || (!ignoreDirtyBit && dirty) + || (!ignoreDirtyBit && fullUpdatePending) || !scene || (scene->d_func()->updateAll && scene->d_func()->hasSceneRect) || (!ignoreClipping && (childrenClippedToShape() && isClippedAway())) @@ -4163,7 +4163,7 @@ void QGraphicsItem::update(const QRectF &rect) } } // Only invalidate cache; item is already dirty. - if (d_ptr->dirty) + if (d_ptr->fullUpdatePending) return; } diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 5b297f6..41593b5 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -6428,10 +6428,25 @@ void tst_QGraphicsItem::deviceTransform() QCOMPARE(rect3->deviceTransform(deviceX).map(QPointF(50, 50)), mapResult3); } +class MyGraphicsView : public QGraphicsView +{ +public: + int repaints; + QRegion paintedRegion; + MyGraphicsView(QGraphicsScene *scene) : QGraphicsView(scene), repaints(0) {} + void paintEvent(QPaintEvent *e) + { + paintedRegion += e->region(); + ++repaints; + QGraphicsView::paintEvent(e); + } + void reset() { repaints = 0; paintedRegion = QRegion(); } +}; + void tst_QGraphicsItem::update() { QGraphicsScene scene; - QGraphicsView view(&scene); + MyGraphicsView view(&scene); view.show(); #ifdef Q_WS_X11 qt_x11_wait_for_window_manager(&view); @@ -6453,6 +6468,20 @@ void tst_QGraphicsItem::update() item->update(); qApp->processEvents(); QCOMPARE(item->repaints, 2); + + // Make sure a partial update doesn't cause a full update to be discarded. + view.reset(); + item->repaints = 0; + item->update(QRectF(0, 0, 5, 5)); + item->update(); + qApp->processEvents(); + QCOMPARE(item->repaints, 1); + QCOMPARE(view.repaints, 1); + const QRect itemDeviceBoundingRect = item->deviceTransform(view.viewportTransform()) + .mapRect(item->boundingRect()).toRect(); + const QRegion expectedRegion = itemDeviceBoundingRect.adjusted(-2, -2, 2, 2); + // The entire item's bounding rect (adjusted for antialiasing) should have been painted. + QCOMPARE(view.paintedRegion, expectedRegion); } QTEST_MAIN(tst_QGraphicsItem) -- cgit v0.12 From 56f23d4ccfc27f737d30e92ae5b3ecde6e8b0bbf Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 20 May 2009 16:38:47 +0200 Subject: Add (back) properties to QGraphicsItem to change the transformations component This reapply commit 8ad5020940f10d4ecc5c5e8b3b9656531cb84ef3 and its dependent change that has been reverted while rebasing the recursivepaint branch. With the new properties it is possible to easily animate transformations Reviewed-by: Andreas Documentation still need to be reviewed. --- src/gui/graphicsview/qgraphicsitem.cpp | 512 ++++++++++++++++++++----- src/gui/graphicsview/qgraphicsitem.h | 37 +- src/gui/graphicsview/qgraphicsitem_p.h | 56 ++- src/gui/graphicsview/qgraphicsscene.cpp | 10 +- src/gui/graphicsview/qgraphicsview.cpp | 2 +- src/gui/graphicsview/qgraphicswidget.h | 9 +- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 199 ++++++++++ 7 files changed, 716 insertions(+), 109 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 2a062ab..d962554 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -133,12 +133,8 @@ \section1 Transformation QGraphicsItem supports affine transformations in addition to its base - position, pos(). To change the item's transformation, you can either pass - a transformation matrix to setTransform(), or set the different transformation - properties (transformOrigin, x/y/zRotation, x/yScale, horizontal/verticalShear). - Note that setting the transformation matrix conflicts with using the properties. - Setting the properties will overwrite the transformation set with setTransform, - and using setTransform will reset the properties. + position, pos(). To change the item's transformation, you can pass + a transformation matrix to setTransform() Item transformations accumulate from parent to child, so if both a parent and child item are rotated 90 degrees, the child's total transformation will be 180 degrees. @@ -152,19 +148,18 @@ and scenePos(), which returns its position in scene coordinates. To reset an item's matrix, call resetTransform(). + Another way to apply transformation to an item is to use the , or set the + different transformation properties (transformOrigin, x/y/zRotation, x/yScale, + horizontal/verticalShear). Those properties come in addition to the base transformation + The order you set the transformation properties does not affect the resulting transformation The resulting transformation is always computed in the following order \code - [Origin] [RotateX] [RotateY] [RotateZ] [Shear] [Scale] [-Origin] + [Origin] [Base] [RotateX] [RotateY] [RotateZ] [Shear] [Scale] [-Origin] \endcode - So the transformation is equivalent to the following code - - \code - QTransform().translate(xOrigin, yOrigin).rotate(xRotation, Qt::XAxis).rotate(yRotation, Qt::YAxis).rotate(zRotation, Qt::ZAxis) - .shear(horizontalShear, verticalShear).scale(xScale, yScale).translate(-xOrigin, -yOrigin); - \endcode + Where [Base] is the stransformation set by setTransform \section1 Painting @@ -788,8 +783,8 @@ void QGraphicsItemPrivate::combineTransformToParent(QTransform *x, const QTransf if (itemIsUntransformable() && viewTransform) { *x = q_ptr->deviceTransform(*viewTransform); } else { - if (transform) - *x *= *transform; + if (transformData) + *x *= transformData->computedFullTransform(); if (!pos.isNull()) *x *= QTransform::fromTranslate(pos.x(), pos.y()); } @@ -811,8 +806,8 @@ void QGraphicsItemPrivate::combineTransformFromParent(QTransform *x, const QTran *x = q_ptr->deviceTransform(*viewTransform); } else { x->translate(pos.x(), pos.y()); - if (transform) - *x = *transform * *x; + if (transformData) + *x = transformData->computedFullTransform() * *x; } } @@ -975,16 +970,9 @@ void QGraphicsItemPrivate::childrenBoundingRectHelper(QTransform *x, QRectF *rec QGraphicsItem *child = children.at(i); QGraphicsItemPrivate *childd = child->d_ptr; bool hasPos = !childd->pos.isNull(); - if (hasPos || childd->transform) { + if (hasPos || childd->transformData) { // COMBINE - QTransform matrix; - if (childd->transform) - matrix = *childd->transform; - if (hasPos) { - const QPointF &p = childd->pos; - matrix *= QTransform::fromTranslate(p.x(), p.y()); - } - matrix *= *x; + QTransform matrix = childd->transformToParent() * *x; *rect |= matrix.mapRect(child->boundingRect()); if (!childd->children.isEmpty()) childd->childrenBoundingRectHelper(&matrix, rect); @@ -1136,8 +1124,7 @@ QGraphicsItem::~QGraphicsItem() if (d_ptr->scene) d_ptr->scene->d_func()->_q_removeItemLater(this); - if (d_ptr->transform) - delete d_ptr->transform; + delete d_ptr->transformData; delete d_ptr; @@ -2747,12 +2734,364 @@ QMatrix QGraphicsItem::matrix() const */ QTransform QGraphicsItem::transform() const { - if (!d_ptr->transform) + if (!d_ptr->transformData) return QTransform(); - return *d_ptr->transform; + return d_ptr->transformData->transform; +} + +/*! + \since 4.6 + + Returns the rotation around the X axis. + + The default is 0 + + \warning The value doesn't take in account any rotation set with the setTransform() method. + + \sa setXRotation(), {Transformations} +*/ +qreal QGraphicsItem::xRotation() const +{ + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->xRotation; } /*! + \since 4.6 + + Sets the rotation around the X axis to \a angle degrees. + + \warning The value doesn't take in account any rotation set with the setTransform() method. + + \sa xRotation(), setTransformOrigin(), {Transformations} +*/ +void QGraphicsItem::setXRotation(qreal angle) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xRotation = angle; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + Returns the rotation around the Y axis. + + The default is 0 + + \warning The value doesn't take in account any rotation set with the setTransform() method. + + \sa setYRotation(), {Transformations} +*/ +qreal QGraphicsItem::yRotation() const +{ + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->yRotation; +} + +/*! + \since 4.6 + + Sets the rotation around the Y axis to \a angle degrees. + + \warning The value doesn't take in account any rotation set with the setTransform() method. + + \sa yRotation(), setTransformOrigin() {Transformations} +*/ +void QGraphicsItem::setYRotation(qreal angle) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->yRotation = angle; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + Returns the rotation around the Z axis. + + The default is 0 + + \warning The value doesn't take in account any rotation set with the setTransform() method. + + \sa setZRotation(), {Transformations} +*/ +qreal QGraphicsItem::zRotation() const +{ + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->zRotation; +} + +/*! + \since 4.6 + + Sets the rotation around the Z axis to \a angle degrees. + + \warning The value doesn't take in account any rotation set with the setTransform() method. + + \sa zRotation(), setTransformOrigin(), {Transformations} +*/ +void QGraphicsItem::setZRotation(qreal angle) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->zRotation = angle; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + This convenience function set the rotation angles around the 3 axes + to \a x, \a y and \a z. + + \sa setXRotation(), setYRotation(), setZRotation(), {Transformations} +*/ +void QGraphicsItem::setRotation(qreal x, qreal y, qreal z) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xRotation = x; + d_ptr->transformData->yRotation = y; + d_ptr->transformData->zRotation = z; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + Returns the scale factor on the X axis. + + The default is 1 + + \warning The value doesn't take in account any scaling set with the setTransform() method. + + \sa setXScale(), {Transformations} +*/ +qreal QGraphicsItem::xScale() const +{ + if (!d_ptr->transformData) + return 1; + return d_ptr->transformData->xScale; +} + +/*! + \since 4.6 + + Sets the scale factor on the X axis to \a factor. + + \warning The value doesn't take in account any scaling set with the setTransform() method. + + \sa xScale(), setTransformOrigin(), {Transformations} +*/ +void QGraphicsItem::setXScale(qreal factor) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xScale = factor; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + Returns the scale factor on the Y axis. + + The default is 1 + + \warning The value doesn't take in account any scaling set with the setTransform() method. + + \sa setYScale(), {Transformations} +*/ +qreal QGraphicsItem::yScale() const +{ + if (!d_ptr->transformData) + return 1; + return d_ptr->transformData->yScale; +} + +/*! + \since 4.6 + + Sets the scale factor on the Y axis to \a factor. + + \warning The value doesn't take in account any scaling set with the setTransform() method. + + \sa yScale(), setTransformOrigin(), {Transformations} +*/ +void QGraphicsItem::setYScale(qreal factor) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->yScale = factor; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + This convenience function set the scaling factors on X and Y axis to \a sx and \a sy. + + \warning The value doesn't take in account any scaling set with the setTransform() method. + + \sa setXScale(), setYScale(), {Transformations} +*/ +void QGraphicsItem::setScale(qreal sx, qreal sy) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xScale = sx; + d_ptr->transformData->yScale = sy; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + Returns the horizontal shear. + + The default is 0 + + \warning The value doesn't take in account any shearing set with the setTransform() method. + + \sa setHorizontalShear(), {Transformations} +*/ +qreal QGraphicsItem::horizontalShear() const +{ + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->horizontalShear; +} + +/*! + \since 4.6 + + Sets the horizontal shear to \a shear. + + \warning The value doesn't take in account any shearing set with the setTransform() method. + + \sa horizontalShear(), {Transformations} +*/ +void QGraphicsItem::setHorizontalShear(qreal shear) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->horizontalShear = shear; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + Returns the vertical shear. + + The default is 0 + + \warning The value doesn't take in account any shearing set with the setTransform() method. + + \sa setHorizontalShear(), {Transformations} +*/ +qreal QGraphicsItem::verticalShear() const +{ + if (!d_ptr->transformData) + return 0; + return d_ptr->transformData->verticalShear; +} + +/*! + \since 4.6 + + Sets the vertical shear to \a shear. + + \warning The value doesn't take in account any shearing set with the setTransform() method. + + \sa verticalShear(), {Transformations} +*/ +void QGraphicsItem::setVerticalShear(qreal shear) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->verticalShear = shear; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + This convenience function sets the horizontal shear to \a sh and the vertical shear to \a sv. + + \warning The value doesn't take in account any shearing set with the setTransform() method. + + \sa setHorizontalShear(), setVerticalShear() +*/ +void QGraphicsItem::setShear(qreal sh, qreal sv) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->horizontalShear = sh; + d_ptr->transformData->verticalShear = sv; + d_ptr->dirtySceneTransform = 1; +} + +/*! + \since 4.6 + + Returns the origin point using for transformation in item coordinate. + + The default is QPointF(0,0). + + \sa setTransformOrigin(), {Transformations} +*/ +QPointF QGraphicsItem::transformOrigin() const +{ + if (!d_ptr->transformData) + return QPointF(0,0); + return QPointF(d_ptr->transformData->xOrigin, d_ptr->transformData->yOrigin); +} + +/*! + \since 4.6 + + Sets the origin for transformation in item coordinate + + \sa transformOrigin(), {Transformations} +*/ +void QGraphicsItem::setTransformOrigin(const QPointF &origin) +{ + prepareGeometryChange(); + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; + d_ptr->transformData->xOrigin = origin.x(); + d_ptr->transformData->yOrigin = origin.y(); + d_ptr->dirtySceneTransform = 1; +} + +/*! + \fn inline void setTransformOrigin(qreal x, qreal y) + + \since 4.6 + \overload + + \sa setTransformOrigin(), {Transformations} +*/ + + +/*! \obsolete Use sceneTransform() instead. @@ -2778,9 +3117,9 @@ QMatrix QGraphicsItem::sceneMatrix() const \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 4 Unlike transform(), which returns only an item's local transformation, this - function includes the item's (and any parents') position. + function includes the item's (and any parents') position, and all the transfomation properties. - \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System} + \sa transform(), setTransform(), scenePos(), {The Graphics View Coordinate System}, {Transformations} */ QTransform QGraphicsItem::sceneTransform() const { @@ -2848,7 +3187,8 @@ QTransform QGraphicsItem::deviceTransform(const QTransform &viewportTransform) c // COMBINE QTransform matrix; matrix.translate(mappedPoint.x(), mappedPoint.y()); - matrix = untransformedAncestor->transform() * matrix; + if (untransformedAncestor->d_ptr->transformData) + matrix = untransformedAncestor->d_ptr->transformData->computedFullTransform() * matrix; // Then transform and translate all children. for (int i = 0; i < parents.size(); ++i) { @@ -2904,7 +3244,7 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co // This is other's parent if (otherParent == this) { const QPointF &otherPos = other->d_ptr->pos; - if (other->d_ptr->transform) { + if (other->d_ptr->transformData) { QTransform otherToParent; other->d_ptr->combineTransformFromParent(&otherToParent); return otherToParent.inverted(ok); @@ -2919,7 +3259,7 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co // COMBINE const QPointF &itemPos = d_ptr->pos; const QPointF &otherPos = other->d_ptr->pos; - if (!d_ptr->transform && !other->d_ptr->transform) { + if (!d_ptr->transformData && !other->d_ptr->transformData) { QPointF delta = itemPos - otherPos; if (ok) *ok = true; @@ -2987,11 +3327,11 @@ QTransform QGraphicsItem::itemTransform(const QGraphicsItem *other, bool *ok) co */ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) { - if (!d_ptr->transform) - d_ptr->transform = new QTransform; + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - QTransform newTransform(combine ? QTransform(matrix) * *d_ptr->transform : QTransform(matrix)); - if (*d_ptr->transform == newTransform) + QTransform newTransform(combine ? QTransform(matrix) * d_ptr->transformData->transform : QTransform(matrix)); + if (d_ptr->transformData->transform == newTransform) return; // Notify the item that the transformation matrix is changing. @@ -2999,13 +3339,13 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) if (notify) { newTransform = QTransform(qVariantValue(itemChange(ItemMatrixChange, qVariantFromValue(newTransform.toAffine())))); - if (*d_ptr->transform == newTransform) + if (d_ptr->transformData->transform == newTransform) return; } // Update and set the new transformation. prepareGeometryChange(); - *d_ptr->transform = newTransform; + d_ptr->transformData->transform = newTransform; d_ptr->dirtySceneTransform = 1; // Send post-notification. @@ -3028,31 +3368,30 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) to map an item coordiate to a scene coordinate, or mapFromScene() to map from scene coordinates to item coordinates. - \warning using this function conflicts with using the transformation properties. - If you set a transformation, getting the properties will return default values. + \warning using this function doesnt affect the value of the transformation properties - \sa transform(), setRotation(), setScale(), setShear(), setTransformOrigin() {The Graphics View Coordinate System} + \sa transform(), setRotation(), setScale(), setShear(), setTransformOrigin(), {The Graphics View Coordinate System}, {Transformations} */ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) { - if (!d_ptr->transform) - d_ptr->transform = new QTransform; + if (!d_ptr->transformData) + d_ptr->transformData = new QGraphicsItemPrivate::TransformData; - QTransform newTransform(combine ? matrix * *d_ptr->transform : matrix); - if (*d_ptr->transform == newTransform) + QTransform newTransform(combine ? matrix * d_ptr->transformData->transform : matrix); + if (d_ptr->transformData->transform == newTransform) return; // Notify the item that the transformation matrix is changing. bool notify = itemChangeEnabled(ItemTransformChange); if (notify) { newTransform = qVariantValue(itemChange(ItemTransformChange, qVariantFromValue(newTransform))); - if (*d_ptr->transform == newTransform) + if (d_ptr->transformData->transform == newTransform) return; } // Update and set the new transformation. prepareGeometryChange(); - *d_ptr->transform = newTransform; + d_ptr->transformData->transform = newTransform; d_ptr->dirtySceneTransform = 1; // Send post-notification. @@ -3096,8 +3435,7 @@ void QGraphicsItem::resetTransform() \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 6 - \warning using this function conflicts with using the transformation properties. - Getting those properties after using this function will return default values. + \warning using this functionhas no effect on the zRotation value \sa setTransform(), transform(), scale(), shear(), translate() */ @@ -3118,8 +3456,7 @@ void QGraphicsItem::rotate(qreal angle) \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 7 - \warning using this function conflicts with using the transformation properties. - Getting those properties after using this function will return default values. + \warning using this function has no effect on the xScale or yScale value \sa setTransform(), transform() */ @@ -3134,8 +3471,7 @@ void QGraphicsItem::scale(qreal sx, qreal sy) Shears the current item transformation by (\a sh, \a sv). - \warning using this function conflicts with using the transformation properties. - Getting those properties after using this function will return default values. + \warning using this function has no effect on the horizontalShear or verticalShear value \sa setTransform(), transform() */ @@ -3154,9 +3490,6 @@ void QGraphicsItem::shear(qreal sh, qreal sv) setPos() instead; this function changes the item's translation, which is conceptually separate from its position. - \warning using this function conflicts with using the transformation properties. - Getting those properties after using this function will return default values. - \sa setTransform(), transform() */ void QGraphicsItem::translate(qreal dx, qreal dy) @@ -3330,7 +3663,7 @@ QRectF QGraphicsItem::sceneBoundingRect() const const QGraphicsItemPrivate *itemd; do { itemd = parentItem->d_ptr; - if (itemd->transform) + if (itemd->transformData) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); @@ -4030,18 +4363,10 @@ void QGraphicsItemPrivate::updateCachedClipPathFromSetPosHelper(const QPointF &n // Find closest clip ancestor and transform. Q_Q(QGraphicsItem); // COMBINE - QTransform thisToParentTransform = transform - ? *transform * QTransform::fromTranslate(newPos.x(), newPos.y()) - : QTransform::fromTranslate(newPos.x(), newPos.y()); + QTransform thisToParentTransform = transformToParent(); QGraphicsItem *clipParent = parent; while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)) { - // COMBINE - if (clipParent->d_ptr->transform) - thisToParentTransform *= *clipParent->d_ptr->transform; - if (!clipParent->d_ptr->pos.isNull()) { - thisToParentTransform *= QTransform::fromTranslate(clipParent->d_ptr->pos.x(), - clipParent->d_ptr->pos.y()); - } + thisToParentTransform *= clipParent->d_ptr->transformToParent(); clipParent = clipParent->d_ptr->parent; } @@ -4428,9 +4753,9 @@ QPointF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPointF &point QPointF QGraphicsItem::mapToParent(const QPointF &point) const { // COMBINE - if (!d_ptr->transform) + if (!d_ptr->transformData) return point + d_ptr->pos; - return d_ptr->transform->map(point) + d_ptr->pos; + return d_ptr->transformToParent().map(point); } /*! @@ -4496,9 +4821,9 @@ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QRectF &rect QPolygonF QGraphicsItem::mapToParent(const QRectF &rect) const { // COMBINE - if (!d_ptr->transform) + if (!d_ptr->transformData) return rect.translated(d_ptr->pos); - return d_ptr->transform->map(rect).translated(d_ptr->pos); + return d_ptr->transformToParent().map(rect); } /*! @@ -4566,8 +4891,9 @@ QRectF QGraphicsItem::mapRectToItem(const QGraphicsItem *item, const QRectF &rec QRectF QGraphicsItem::mapRectToParent(const QRectF &rect) const { // COMBINE - QRectF r = !d_ptr->transform ? rect : d_ptr->transform->mapRect(rect); - return r.translated(d_ptr->pos); + if (!d_ptr->transformData) + return rect.translated(d_ptr->pos); + return d_ptr->transformToParent().mapRect(rect); } /*! @@ -4639,8 +4965,9 @@ QRectF QGraphicsItem::mapRectFromItem(const QGraphicsItem *item, const QRectF &r QRectF QGraphicsItem::mapRectFromParent(const QRectF &rect) const { // COMBINE - QRectF r = rect.translated(-d_ptr->pos); - return d_ptr->transform ? d_ptr->transform->inverted().mapRect(r) : r; + if (!d_ptr->transformData) + return rect.translated(-d_ptr->pos); + return d_ptr->transformToParent().inverted().mapRect(rect); } /*! @@ -4700,9 +5027,9 @@ QPolygonF QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPolygonF &p QPolygonF QGraphicsItem::mapToParent(const QPolygonF &polygon) const { // COMBINE - if (!d_ptr->transform) + if (!d_ptr->transformData) return polygon.translated(d_ptr->pos); - return d_ptr->transform->map(polygon).translated(d_ptr->pos); + return d_ptr->transformToParent().map(polygon); } /*! @@ -4745,9 +5072,9 @@ QPainterPath QGraphicsItem::mapToItem(const QGraphicsItem *item, const QPainterP QPainterPath QGraphicsItem::mapToParent(const QPainterPath &path) const { // COMBINE - if (!d_ptr->transform) + if (!d_ptr->transformData) return path.translated(d_ptr->pos); - return d_ptr->transform->map(path).translated(d_ptr->pos); + return d_ptr->transformToParent().map(path); } /*! @@ -4797,8 +5124,8 @@ QPointF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPointF &poi QPointF QGraphicsItem::mapFromParent(const QPointF &point) const { // COMBINE - if (d_ptr->transform) - return d_ptr->transform->inverted().map(point - d_ptr->pos); + if (d_ptr->transformData) + return d_ptr->transformToParent().inverted().map(point); return point - d_ptr->pos; } @@ -4866,8 +5193,9 @@ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QRectF &re QPolygonF QGraphicsItem::mapFromParent(const QRectF &rect) const { // COMBINE - QRectF r = rect.translated(-d_ptr->pos); - return d_ptr->transform ? d_ptr->transform->inverted().map(r) : r; + if (!d_ptr->transformData) + return rect.translated(-d_ptr->pos); + return d_ptr->transformToParent().inverted().map(rect); } /*! @@ -4923,9 +5251,9 @@ QPolygonF QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPolygonF QPolygonF QGraphicsItem::mapFromParent(const QPolygonF &polygon) const { // COMBINE - QPolygonF p = polygon; - p.translate(-d_ptr->pos); - return d_ptr->transform ? d_ptr->transform->inverted().map(p) : p; + if (!d_ptr->transformData) + return polygon.translated(-d_ptr->pos); + return d_ptr->transformToParent().inverted().map(polygon); } /*! @@ -4966,9 +5294,9 @@ QPainterPath QGraphicsItem::mapFromItem(const QGraphicsItem *item, const QPainte QPainterPath QGraphicsItem::mapFromParent(const QPainterPath &path) const { // COMBINE - QPainterPath p(path); - p.translate(-d_ptr->pos); - return d_ptr->transform ? d_ptr->transform->inverted().map(p) : p; + if (!d_ptr->transformData) + return path.translated(-d_ptr->pos); + return d_ptr->transformToParent().inverted().map(path); } /*! diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index 7c87176..67b57e0 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -248,10 +248,39 @@ public: void setTransform(const QTransform &matrix, bool combine = false); void resetTransform(); - void rotate(qreal angle); - void scale(qreal sx, qreal sy); - void shear(qreal sh, qreal sv); - void translate(qreal dx, qreal dy); + void rotate(qreal angle); // ### obsolete + void scale(qreal sx, qreal sy); // ### obsolete + void shear(qreal sh, qreal sv); // ### obsolete + void translate(qreal dx, qreal dy); // ### obsolete + + qreal xRotation() const; + void setXRotation(qreal angle); + + qreal yRotation() const; + void setYRotation(qreal angle); + + qreal zRotation() const; + void setZRotation(qreal angle); + void setRotation(qreal x, qreal y, qreal z); + + qreal xScale() const; + void setXScale(qreal factor); + + qreal yScale() const; + void setYScale(qreal factor); + void setScale(qreal sx, qreal sy); + + qreal horizontalShear() const; + void setHorizontalShear(qreal shear); + + qreal verticalShear() const; + void setVerticalShear(qreal shear); + void setShear(qreal sh, qreal sv); + + QPointF transformOrigin() const; + void setTransformOrigin(const QPointF &origin); + inline void setTransformOrigin(qreal x, qreal y) + { setTransformOrigin(QPointF(x,y)); } virtual void advance(int phase); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index d884b16..62ef36a 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -115,7 +115,7 @@ public: opacity(1.), scene(0), parent(0), - transform(0), + transformData(0), index(-1), depth(0), acceptedMouseButtons(0x1f), @@ -147,8 +147,8 @@ public: dirtyChildrenBoundingRect(1), paintedViewBoundingRectsNeedRepaint(0), dirtySceneTransform(1), - itemChangesEnabled(0xffff), geometryChanged(0), + itemChangesEnabled(0xffff), globalStackingOrder(-1), q_ptr(0) { @@ -352,6 +352,8 @@ public: || (childrenCombineOpacity() && isFullyTransparent()); } + inline QTransform transformToParent() const; + QPainterPath cachedClipPath; QRectF childrenBoundingRect; QRectF needsRepaint; @@ -362,7 +364,8 @@ public: QGraphicsScene *scene; QGraphicsItem *parent; QList children; - QTransform *transform; + class TransformData; + TransformData *transformData; QTransform sceneTransform; int index; int depth; @@ -399,16 +402,57 @@ public: quint32 dirtyChildrenBoundingRect : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; quint32 dirtySceneTransform : 1; - quint32 itemChangesEnabled : 16; quint32 geometryChanged : 1; - quint32 padding : 2; // feel free to use + quint32 unused : 2; // feel free to use + quint32 itemChangesEnabled : 16; // Optional stacking order int globalStackingOrder; - QGraphicsItem *q_ptr; }; +struct QGraphicsItemPrivate::TransformData { + QTransform transform; + qreal xScale; + qreal yScale; + qreal xRotation; + qreal yRotation; + qreal zRotation; + qreal horizontalShear; + qreal verticalShear; + qreal xOrigin; + qreal yOrigin; + + TransformData() : + xScale(1.0), yScale(1.0), xRotation(0.0), yRotation(0.0), zRotation(0.0), + horizontalShear(0.0), verticalShear(0.0), xOrigin(0.0), yOrigin(0.0) + {} + + QTransform computedFullTransform() const + { + QTransform x; + x.translate(xOrigin, yOrigin); + x = transform * x; + x.rotate(xRotation, Qt::XAxis); + x.rotate(yRotation, Qt::YAxis); + x.rotate(zRotation, Qt::ZAxis); + x.shear(horizontalShear, verticalShear); + x.scale(xScale, yScale); + x.translate(-xOrigin, -yOrigin); + return x; + } +}; + +/* + return the full transform of the item to the parent. This include the position and all the transform data +*/ +inline QTransform QGraphicsItemPrivate::transformToParent() const +{ + QTransform matrix; + combineTransformToParent(&matrix); + return matrix; +} + QT_END_NAMESPACE #endif // QT_NO_GRAPHICSVIEW diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index ad392b0..1014550 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -1737,7 +1737,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, QList &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->transform && !item->d_ptr->transform->isInvertible()) + if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible()) continue; // Skip invisible items and all their children. @@ -1777,7 +1777,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, QList &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->transform && !item->d_ptr->transform->isInvertible()) + if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible()) continue; // Skip invisible items and all their children. @@ -1813,7 +1813,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, if ((keep || !(item->flags() & QGraphicsItem::ItemClipsChildrenToShape)) && !item->d_ptr->children.isEmpty()) { // Recurse into children. - if (!item->d_ptr->transform || item->d_ptr->transform->type() <= QTransform::TxScale) { + if (!item->d_ptr->transformData || item->d_ptr->transformData->computedFullTransform().type() <= QTransform::TxScale) { // Rect childItems_helper(items, item, item->mapRectFromParent(rect), mode); } else { @@ -1843,7 +1843,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, QList &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->transform && !item->d_ptr->transform->isInvertible()) + if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible()) continue; // Skip invisible items. @@ -1902,7 +1902,7 @@ void QGraphicsScenePrivate::childItems_helper(QList *items, QList &children = parent->d_ptr->children; for (int i = 0; i < children.size(); ++i) { QGraphicsItem *item = children.at(i); - if (item->d_ptr->transform && !item->d_ptr->transform->isInvertible()) + if (item->d_ptr->transformData && !item->d_ptr->transformData->computedFullTransform().isInvertible()) continue; // Skip invisible items. diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index a9fc563..166bcb9 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -752,7 +752,7 @@ QRect QGraphicsViewPrivate::mapToViewRect(const QGraphicsItem *item, const QRect const QGraphicsItemPrivate *itemd; do { itemd = parentItem->d_ptr; - if (itemd->transform) + if (itemd->transformData) break; offset += itemd->pos; } while ((parentItem = itemd->parent)); diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h index 34f1c5f..a5c9068 100644 --- a/src/gui/graphicsview/qgraphicswidget.h +++ b/src/gui/graphicsview/qgraphicswidget.h @@ -81,7 +81,14 @@ class Q_GUI_EXPORT QGraphicsWidget : public QObject, public QGraphicsItem, publi Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity) Q_PROPERTY(QPointF pos READ pos WRITE setPos) Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry) - + Q_PROPERTY(QPointF transformOrigin READ transformOrigin WRITE setTransformOrigin) + Q_PROPERTY(qreal xRotation READ xRotation WRITE setXRotation) + Q_PROPERTY(qreal yRotation READ yRotation WRITE setYRotation) + Q_PROPERTY(qreal zRotation READ zRotation WRITE setZRotation) + Q_PROPERTY(qreal xScale READ xScale WRITE setXScale) + Q_PROPERTY(qreal yScale READ yScale WRITE setYScale) + Q_PROPERTY(qreal horizontalShear READ horizontalShear WRITE setHorizontalShear) + Q_PROPERTY(qreal verticalShear READ verticalShear WRITE setVerticalShear) public: QGraphicsWidget(QGraphicsItem *parent = 0, Qt::WindowFlags wFlags = 0); ~QGraphicsWidget(); diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 41593b5..82c173b 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -220,6 +220,8 @@ private slots: void deviceTransform_data(); void deviceTransform(); void update(); + void setTransformProperties_data(); + void setTransformProperties(); // task specific tests below me void task141694_textItemEnsureVisible(); @@ -6484,5 +6486,202 @@ void tst_QGraphicsItem::update() QCOMPARE(view.paintedRegion, expectedRegion); } +void tst_QGraphicsItem::setTransformProperties_data() +{ + QTest::addColumn("origin"); + QTest::addColumn("rotationX"); + QTest::addColumn("rotationY"); + QTest::addColumn("rotationZ"); + QTest::addColumn("scaleX"); + QTest::addColumn("scaleY"); + QTest::addColumn("shearX"); + QTest::addColumn("shearY"); + + QTest::newRow("nothing") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) + << qreal(1.0) << qreal(1.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("rotationZ") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(42.2) + << qreal(1.0) << qreal(1.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("rotationXY") << QPointF() << qreal(12.5) << qreal(53.6) << qreal(0.0) + << qreal(1.0) << qreal(1.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("rotationXYZ") << QPointF() << qreal(-25) << qreal(12) << qreal(556) + << qreal(1.0) << qreal(1.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("rotationXYZ dicentred") << QPointF(-53, 25.2) + << qreal(-2578.2) << qreal(4565.2) << qreal(56) + << qreal(1.0) << qreal(1.0) << qreal(0.0) << qreal(0.0); + + QTest::newRow("Scale") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) + << qreal(6) << qreal(0.5) << qreal(0.0) << qreal(0.0); + + QTest::newRow("Shear") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) + << qreal(1.0) << qreal(1.0) << qreal(2.2) << qreal(0.5); + + QTest::newRow("Scale and Shear") << QPointF() << qreal(0.0) << qreal(0.0) << qreal(0.0) + << qreal(5.2) << qreal(2.1) << qreal(5.2) << qreal(5.5); + + QTest::newRow("Everything") << QPointF() << qreal(41) << qreal(-23) << qreal(0.56) + << qreal(8.2) << qreal(-0.2) << qreal(-12) << qreal(-0.8); + + QTest::newRow("Everything dicentred") << QPointF(qreal(22.3), qreal(-56.2)) << qreal(-175) << qreal(196) << qreal(-1260) + << qreal(4) << qreal(2) << qreal(2.56) << qreal(0.8); +} + +/** + * the normal QCOMPARE doesn't work because it doesn't use qFuzzyCompare + */ +#define QCOMPARE_TRANSFORM(X1, X2) QVERIFY(((X1)*(X2).inverted()).isIdentity()) + +void tst_QGraphicsItem::setTransformProperties() +{ + QFETCH(QPointF,origin); + QFETCH(qreal,rotationX); + QFETCH(qreal,rotationY); + QFETCH(qreal,rotationZ); + QFETCH(qreal,scaleX); + QFETCH(qreal,scaleY); + QFETCH(qreal,shearX); + QFETCH(qreal,shearY); + + QTransform result; + result.translate(origin.x(), origin.y()); + result.rotate(rotationX, Qt::XAxis); + result.rotate(rotationY, Qt::YAxis); + result.rotate(rotationZ, Qt::ZAxis); + result.shear(shearX, shearY); + result.scale(scaleX, scaleY); + result.translate(-origin.x(), -origin.y()); + + QGraphicsScene scene; + QGraphicsRectItem *item = new QGraphicsRectItem(QRectF(0, 0, 100, 100)); + scene.addItem(item); + + item->setRotation(rotationX, rotationY, rotationZ); + item->setScale(scaleX, scaleY); + item->setShear(shearX, shearY); + item->setTransformOrigin(origin); + + QCOMPARE(item->xRotation(), rotationX); + QCOMPARE(item->yRotation(), rotationY); + QCOMPARE(item->zRotation(), rotationZ); + QCOMPARE(item->xScale(), scaleX); + QCOMPARE(item->yScale(), scaleY); + QCOMPARE(item->horizontalShear(), shearX); + QCOMPARE(item->verticalShear(), shearY); + QCOMPARE(item->transformOrigin(), origin); + + QCOMPARE(QTransform(), item->transform()); + QCOMPARE(result, item->sceneTransform()); + + //----------------------------------------------------------------- + //Change the rotation Z + item->setZRotation(45); + QTransform result2; + result2.translate(origin.x(), origin.y()); + result2.rotate(rotationX, Qt::XAxis); + result2.rotate(rotationY, Qt::YAxis); + result2.rotate(45, Qt::ZAxis); + result2.shear(shearX, shearY); + result2.scale(scaleX, scaleY); + result2.translate(-origin.x(), -origin.y()); + + QCOMPARE(item->xRotation(), rotationX); + QCOMPARE(item->yRotation(), rotationY); + QCOMPARE(item->zRotation(), 45.0); + QCOMPARE(item->xScale(), scaleX); + QCOMPARE(item->yScale(), scaleY); + QCOMPARE(item->horizontalShear(), shearX); + QCOMPARE(item->verticalShear(), shearY); + QCOMPARE(item->transformOrigin(), origin); + + QCOMPARE(QTransform(), item->transform()); + QCOMPARE(result2, item->sceneTransform()); + + //----------------------------------------------------------------- + // calling setTransform() and setPos shoukld change the sceneTransform + item->setTransform(result); + item->setPos(100, -150.5); + + QCOMPARE(item->xRotation(), rotationX); + QCOMPARE(item->yRotation(), rotationY); + QCOMPARE(item->zRotation(), 45.0); + QCOMPARE(item->xScale(), scaleX); + QCOMPARE(item->yScale(), scaleY); + QCOMPARE(item->horizontalShear(), shearX); + QCOMPARE(item->verticalShear(), shearY); + QCOMPARE(item->transformOrigin(), origin); + QCOMPARE(result, item->transform()); + + QTransform result3; + + result3.translate(origin.x(), origin.y()); + result3 = result * result3; + result3.rotate(rotationX, Qt::XAxis); + result3.rotate(rotationY, Qt::YAxis); + result3.rotate(45, Qt::ZAxis); + result3.shear(shearX, shearY); + result3.scale(scaleX, scaleY); + result3.translate(-origin.x(), -origin.y()); + + result3 *= QTransform::fromTranslate(100, -150.5); //the pos; + + QCOMPARE(result3, item->sceneTransform()); + + //----------------------------------------------------- + // setting the propertiees should be the same as setting a transform + {//with center origin on the matrix + QGraphicsRectItem *item1 = new QGraphicsRectItem(QRectF(50.2, -150, 230.5, 119)); + scene.addItem(item1); + QGraphicsRectItem *item2 = new QGraphicsRectItem(QRectF(50.2, -150, 230.5, 119)); + scene.addItem(item2); + + item1->setPos(12.3, -5); + item2->setPos(12.3, -5); + item1->setRotation(rotationX, rotationY, rotationZ); + item1->setScale(scaleX, scaleY); + item1->setShear(shearX, shearY); + item1->setTransformOrigin(origin); + + item2->setTransform(result); + + QCOMPARE_TRANSFORM(item1->sceneTransform(), item2->sceneTransform()); + + QCOMPARE_TRANSFORM(item1->itemTransform(item2), QTransform()); + QCOMPARE_TRANSFORM(item2->itemTransform(item1), QTransform()); + } + + {//with center origin on the item + QGraphicsRectItem *item1 = new QGraphicsRectItem(QRectF(50.2, -150, 230.5, 119)); + scene.addItem(item1); + QGraphicsRectItem *item2 = new QGraphicsRectItem(QRectF(50.2, -150, 230.5, 119)); + scene.addItem(item2); + + item1->setPos(12.3, -5); + item2->setPos(12.3, -5); + item1->setTransformOrigin(origin); + item2->setTransformOrigin(origin); + + item1->setRotation(rotationX, rotationY, rotationZ); + item1->setScale(scaleX, scaleY); + item1->setShear(shearX, shearY); + + QTransform tr; + tr.rotate(rotationX, Qt::XAxis); + tr.rotate(rotationY, Qt::YAxis); + tr.rotate(rotationZ, Qt::ZAxis); + tr.shear(shearX, shearY); + tr.scale(scaleX, scaleY); + + item2->setTransform(tr); + + QCOMPARE_TRANSFORM(item1->sceneTransform(), item2->sceneTransform()); + + QCOMPARE_TRANSFORM(item1->itemTransform(item2), QTransform()); + QCOMPARE_TRANSFORM(item2->itemTransform(item1), QTransform()); + } +} + QTEST_MAIN(tst_QGraphicsItem) #include "tst_qgraphicsitem.moc" -- cgit v0.12 From 9ba5a561b017ec028d675627df2eda5b13e3a6fc Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Mon, 8 Jun 2009 14:49:44 +0200 Subject: Fix two regressions in Plasma. The painter state proctection was not properly pass to drawItemHelper. The second is a double conversion to deviceTransform in createStyleOption of QGraphicsItem. Since the recursive drawing already give a transform in device mode we don't need to convert it two times. Reviewed-by:andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 6 +-- src/gui/graphicsview/qgraphicsscene.cpp | 2 +- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 53 ++++++++++++++++++++++ tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp | 36 +++++++++++++++ 4 files changed, 92 insertions(+), 5 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index d962554..7f22c80 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1016,14 +1016,12 @@ void QGraphicsItemPrivate::initStyleOption(QStyleOptionGraphicsItem *option, con return; // Initialize QStyleOptionGraphicsItem specific values (matrix, exposedRect). - - const QTransform itemToViewportTransform = q->deviceTransform(worldTransform); - option->matrix = itemToViewportTransform.toAffine(); //### discards perspective + option->matrix = worldTransform.toAffine(); //### discards perspective if (!allItems) { // Determine the item's exposed area option->exposedRect = QRectF(); - const QTransform reverseMap = itemToViewportTransform.inverted(); + const QTransform reverseMap = worldTransform.inverted(); const QVector exposedRects(exposedRegion.rects()); for (int i = 0; i < exposedRects.size(); ++i) { option->exposedRect |= reverseMap.mapRect(exposedRects.at(i)); diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 1014550..28d65da 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5254,7 +5254,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (clipsToShape) painter->setClipPath(item->shape(), Qt::IntersectClip); painter->setOpacity(opacity); - drawItemHelper(item, painter, &styleOptionTmp, widget, false); + drawItemHelper(item, painter, &styleOptionTmp, widget, painterStateProtection); if (savePainter) painter->restore(); diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 82c173b..7a789c5 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -44,6 +44,7 @@ #include #include +#include #include #include #include @@ -222,6 +223,7 @@ private slots: void update(); void setTransformProperties_data(); void setTransformProperties(); + void itemUsesExtendedStyleOption(); // task specific tests below me void task141694_textItemEnsureVisible(); @@ -6449,6 +6451,7 @@ void tst_QGraphicsItem::update() { QGraphicsScene scene; MyGraphicsView view(&scene); + view.show(); #ifdef Q_WS_X11 qt_x11_wait_for_window_manager(&view); @@ -6683,5 +6686,55 @@ void tst_QGraphicsItem::setTransformProperties() } } +class MyStyleOptionTester : public QGraphicsRectItem +{ +public: + MyStyleOptionTester(const QRectF &rect) + : QGraphicsRectItem(rect), startTrack(false) + {} + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0) + { + if (startTrack) { + //Doesn't use the extended style option so the exposed rect is the boundingRect + if (!(flags() & QGraphicsItem::ItemUsesExtendedStyleOption)) { + QCOMPARE(option->exposedRect, boundingRect()); + } else { + QVERIFY(option->exposedRect != QRect()); + QVERIFY(option->exposedRect != boundingRect()); + } + } + QGraphicsRectItem::paint(painter, option, widget); + } + bool startTrack; +}; + +void tst_QGraphicsItem::itemUsesExtendedStyleOption() +{ + QGraphicsScene scene(0, 0, 300, 300); + QGraphicsPixmapItem item; + item.setFlag(QGraphicsItem::ItemUsesExtendedStyleOption, true); + QCOMPARE(item.flags(), QGraphicsItem::GraphicsItemFlags(QGraphicsItem::ItemUsesExtendedStyleOption)); + item.setFlag(QGraphicsItem::ItemUsesExtendedStyleOption, false); + QCOMPARE(item.flags(), 0); + + //We now test the content of the style option + MyStyleOptionTester *rect = new MyStyleOptionTester(QRect(0, 0, 100, 100)); + scene.addItem(rect); + rect->setPos(200, 200); + QGraphicsView view(&scene); + QTest::qWait(500); + rect->startTrack = true; + rect->update(10, 10, 10, 10); + QTest::qWait(125); + rect->startTrack = false; + rect->setFlag(QGraphicsItem::ItemUsesExtendedStyleOption, true); + QVERIFY((rect->flags() & QGraphicsItem::ItemUsesExtendedStyleOption)); + QTest::qWait(125); + rect->startTrack = true; + rect->update(10, 10, 10, 10); + QTest::qWait(125); +} + QTEST_MAIN(tst_QGraphicsItem) #include "tst_qgraphicsitem.moc" diff --git a/tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp b/tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp index 56d42c3..00f3155 100644 --- a/tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp +++ b/tests/auto/qgraphicswidget/tst_qgraphicswidget.cpp @@ -155,6 +155,7 @@ private slots: void windowFlags_data(); void windowFlags(); void shortcutsDeletion(); + void painterStateProtectionOnWindowFrame(); // Task fixes void task236127_bspTreeIndexFails(); @@ -2282,6 +2283,41 @@ void tst_QGraphicsWidget::shortcutsDeletion() delete widget; } +class MessUpPainterWidget : public QGraphicsWidget +{ +public: + MessUpPainterWidget(QGraphicsItem * parent = 0, Qt::WindowFlags wFlags = 0) + : QGraphicsWidget(parent, wFlags) + {} + + void paintWindowFrame(QPainter * painter, const QStyleOptionGraphicsItem *option, QWidget *widget) + { + QCOMPARE(painter->opacity(), 1.0); + painter->setOpacity(0.0); + QGraphicsWidget::paintWindowFrame(painter, option, widget); + } + void paint(QPainter * painter, const QStyleOptionGraphicsItem *option, QWidget *widget) + { + QCOMPARE(painter->opacity(), 1.0); + painter->drawRect(0, 0, 100, 100); + QGraphicsWidget::paint(painter, option, widget); + } + +}; + +void tst_QGraphicsWidget::painterStateProtectionOnWindowFrame() +{ + MessUpPainterWidget *widget = new MessUpPainterWidget(0, Qt::Window); + QGraphicsScene scene(0, 0, 300, 300); + QGraphicsView view(&scene); + scene.addItem(widget); + view.show(); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&view); +#endif + QTest::qWait(500); +} + class ProxyStyle : public QCommonStyle { public: -- cgit v0.12 From e8e1cdaea063dc3613b38315ca401ef55340fcbb Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 8 Jun 2009 17:14:10 +0200 Subject: Revert "Add QGraphicsItem::itemChangeEnabled()." This reverts commit 0fc58ca3220083b9e10f88aab2e39824c2764db3. Conflicts: src/gui/graphicsview/qgraphicsitem.cpp src/gui/graphicsview/qgraphicsitem_p.h --- src/gui/graphicsview/qgraphicsitem.cpp | 240 ++++++++++---------------------- src/gui/graphicsview/qgraphicsitem.h | 5 - src/gui/graphicsview/qgraphicsitem_p.h | 4 +- src/gui/graphicsview/qgraphicsscene.cpp | 30 ++-- 4 files changed, 81 insertions(+), 198 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 7f22c80..6679bd5 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -39,6 +39,8 @@ ** ****************************************************************************/ +#define QGRAPHICSITEM_NO_ITEMCHANGE + /*! \class QGraphicsItem \brief The QGraphicsItem class is the base class for all graphical @@ -844,13 +846,11 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de if (newParent == parent) return; - bool notify = q->itemChangeEnabled(QGraphicsItem::ItemParentChange); - if (notify) { - newParent = qVariantValue(q->itemChange(QGraphicsItem::ItemParentChange, - qVariantFromValue(newParent))); - if (newParent == parent) - return; - } + const QVariant newParentVariant(q->itemChange(QGraphicsItem::ItemParentChange, + qVariantFromValue(newParent))); + newParent = qVariantValue(newParentVariant); + if (newParent == parent) + return; if (QGraphicsWidget *w = isWidget ? static_cast(q) : q->parentWidget()) { // Update the child focus chain; when reparenting a widget that has a @@ -950,8 +950,7 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de dirtySceneTransform = 1; // Deliver post-change notification - if (notify) - q->itemChange(QGraphicsItem::ItemParentHasChanged, qVariantFromValue(newParent)); + q->itemChange(QGraphicsItem::ItemParentHasChanged, newParentVariant); } /*! @@ -1379,14 +1378,9 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) // Notify change and check for adjustment. if (quint32(d_ptr->flags) == quint32(flags)) return; - - // Notify - bool notify = itemChangeEnabled(ItemFlagsChange); - if (notify) { - flags = GraphicsItemFlags(itemChange(ItemFlagsChange, quint32(flags)).toUInt()); - if (quint32(d_ptr->flags) == quint32(flags)) - return; - } + flags = GraphicsItemFlags(itemChange(ItemFlagsChange, quint32(flags)).toUInt()); + if (quint32(d_ptr->flags) == quint32(flags)) + return; // Flags that alter the geometry of the item (or its children). const quint32 geomChangeFlagsMask = (ItemClipsChildrenToShape | ItemClipsToShape | ItemIgnoresTransformations); @@ -1442,78 +1436,7 @@ void QGraphicsItem::setFlags(GraphicsItemFlags flags) } // Notify change. - if (notify) - itemChange(ItemFlagsHaveChanged, quint32(flags)); -} - -static const int itemChangeBits[] = { - /* ItemPositionChange */ 1 << 1, - /* ItemMatrixChange */ 1 << 2, - /* ItemVisibleChange */ 1 << 3, - /* ItemEnabledChange */ 1 << 4, - /* ItemSelectedChange */ 1 << 5, - /* ItemParentChange */ 1 << 6, - /* ItemChildAddedChange */ 1 << 7, - /* ItemChildRemovedChange */ 1 << 8, - /* ItemTransformChange */ 1 << 9, - /* ItemPositionHasChanged */ 1 << 1, - /* ItemTransformHasChanged */ 1 << 9, - /* ItemSceneChange */ 1 << 10, - /* ItemVisibleHasChanged */ 1 << 3, - /* ItemEnabledHasChanged */ 1 << 4, - /* ItemSelectedHasChanged */ 1 << 5, - /* ItemParentHasChanged */ 1 << 6, - /* ItemSceneHasChanged */ 1 << 10, - /* ItemCursorChange */ 1 << 11, - /* ItemCursorHasChanged */ 1 << 11, - /* ItemToolTipChange */ 1 << 12, - /* ItemToolTipHasChanged */ 1 << 12, - /* ItemFlagsChange */ 1 << 13, - /* ItemFlagsHaveChanged */ 1 << 13, - /* ItemZValueChange */ 1 << 14, - /* ItemZValueHasChanged */ 1 << 14, - /* ItemOpacityChange */ 1 << 15, - /* ItemOpacityHasChanged */ 1 << 15 -}; - -/*! - Returns true if \a change is enabled (i.e., QGraphicsItem will call - itemChange() whenever the respective change occurs); otherwise returns - false. - - \sa setItemChangeEnabled(), setItemChangesEnabled(), itemChange() -*/ -bool QGraphicsItem::itemChangeEnabled(GraphicsItemChange change) const -{ - return d_ptr->itemChangesEnabled & itemChangeBits[change]; -} - -/*! - If \a enabled is true, notifications for \a change are enabled; otherwise - they are disabled. By default, QGraphicsItem sends notifications for all - changes by calling itemChange(). - - \sa itemChangeEnabled(), setItemChangesEnabled(), itemChange() -*/ -void QGraphicsItem::setItemChangeEnabled(GraphicsItemChange change, bool enabled) -{ - if (enabled) { - d_ptr->itemChangesEnabled |= itemChangeBits[change]; - } else { - d_ptr->itemChangesEnabled &= itemChangeBits[change]; - } -} - -/*! - If \a enabled is true, all item change notifications are enabled; - otherwise, they are disabled. You can toggle individual notifications by - calling setItemChangeEnabled(). - - \sa itemChangeEnabled(), itemChange() -*/ -void QGraphicsItem::setItemChangesEnabled(bool enabled) -{ - d_ptr->itemChangesEnabled = enabled ? 0xffff : 0; + itemChange(ItemFlagsHaveChanged, quint32(flags)); } /*! @@ -1602,13 +1525,9 @@ QString QGraphicsItem::toolTip() const */ void QGraphicsItem::setToolTip(const QString &toolTip) { - bool notify = itemChangeEnabled(ItemToolTipChange); - QVariant toolTipVariant = toolTip; - if (notify) - toolTipVariant = itemChange(ItemToolTipChange, toolTipVariant); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraToolTip, toolTipVariant); - if (notify) - itemChange(ItemToolTipHasChanged, toolTipVariant); + const QVariant toolTipVariant(itemChange(ItemToolTipChange, toolTip)); + d_ptr->setExtra(QGraphicsItemPrivate::ExtraToolTip, toolTipVariant.toString()); + itemChange(ItemToolTipHasChanged, toolTipVariant); } #endif // QT_NO_TOOLTIP @@ -1650,11 +1569,8 @@ QCursor QGraphicsItem::cursor() const */ void QGraphicsItem::setCursor(const QCursor &cursor) { - bool notify = itemChangeEnabled(ItemCursorChange); - QVariant cursorVariant = qVariantFromValue(cursor); - if (notify) - cursorVariant = itemChange(ItemCursorChange, cursorVariant); - d_ptr->setExtra(QGraphicsItemPrivate::ExtraCursor, cursorVariant); + const QVariant cursorVariant(itemChange(ItemCursorChange, qVariantFromValue(cursor))); + d_ptr->setExtra(QGraphicsItemPrivate::ExtraCursor, qVariantValue(cursorVariant)); d_ptr->hasCursor = 1; if (d_ptr->scene) { d_ptr->scene->d_func()->allItemsUseDefaultCursor = false; @@ -1673,8 +1589,7 @@ void QGraphicsItem::setCursor(const QCursor &cursor) } } } - if (notify) - itemChange(ItemCursorHasChanged, cursorVariant); + itemChange(ItemCursorHasChanged, cursorVariant); } /*! @@ -1771,12 +1686,10 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo if (parent && newVisible && !parent->d_ptr->visible) return; - // Notify - bool notify = q->itemChangeEnabled(QGraphicsItem::ItemVisibleChange); - if (notify) - newVisible = q_ptr->itemChange(QGraphicsItem::ItemVisibleChange, quint32(newVisible)).toBool(); - // Modify the property. + const QVariant newVisibleVariant(q_ptr->itemChange(QGraphicsItem::ItemVisibleChange, + quint32(newVisible))); + newVisible = newVisibleVariant.toBool(); if (visible == quint32(newVisible)) return; visible = newVisible; @@ -1843,8 +1756,7 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo } // Deliver post-change notification. - if (notify) - q_ptr->itemChange(QGraphicsItem::ItemVisibleHasChanged, newVisible); + q_ptr->itemChange(QGraphicsItem::ItemVisibleHasChanged, newVisibleVariant); } /*! @@ -1950,10 +1862,9 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo } // Modify the property. - bool notify = q_ptr->itemChangeEnabled(QGraphicsItem::ItemEnabledChange); - if (notify) - newEnabled = q_ptr->itemChange(QGraphicsItem::ItemEnabledChange, quint32(newEnabled)).toBool(); - enabled = newEnabled; + const QVariant newEnabledVariant(q_ptr->itemChange(QGraphicsItem::ItemEnabledChange, + quint32(newEnabled))); + enabled = newEnabledVariant.toBool(); // Schedule redraw. if (update && scene) @@ -1965,8 +1876,7 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo } // Deliver post-change notification. - if (notify) - q_ptr->itemChange(QGraphicsItem::ItemEnabledHasChanged, newEnabled); + q_ptr->itemChange(QGraphicsItem::ItemEnabledHasChanged, newEnabledVariant); } /*! @@ -2053,13 +1963,10 @@ void QGraphicsItem::setSelected(bool selected) selected = false; if (d_ptr->selected == selected) return; - bool notify = itemChangeEnabled(ItemSelectedChange); - bool newSelected = selected; - if (notify) { - newSelected = itemChange(ItemSelectedChange, quint32(selected)).toBool(); - if (d_ptr->selected == newSelected) - return; - } + const QVariant newSelectedVariant(itemChange(ItemSelectedChange, quint32(selected))); + bool newSelected = newSelectedVariant.toBool(); + if (d_ptr->selected == newSelected) + return; d_ptr->selected = newSelected; if (d_ptr->scene) { @@ -2076,8 +1983,7 @@ void QGraphicsItem::setSelected(bool selected) } // Deliver post-change notification. - if (notify) - itemChange(QGraphicsItem::ItemSelectedHasChanged, newSelected); + itemChange(QGraphicsItem::ItemSelectedHasChanged, newSelectedVariant); } /*! @@ -2143,12 +2049,13 @@ qreal QGraphicsItem::effectiveOpacity() const */ void QGraphicsItem::setOpacity(qreal opacity) { + // Notify change. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE + const QVariant newOpacityVariant(itemChange(ItemOpacityChange, double(opacity))); + qreal newOpacity = newOpacityVariant.toDouble(); +#else qreal newOpacity = opacity; - - // Notify - bool notify = itemChangeEnabled(ItemOpacityChange); - if (notify) - newOpacity = itemChange(ItemOpacityChange, double(newOpacity)).toDouble(); +#endif // Normalize. newOpacity = qBound(0.0, newOpacity, 1.0); @@ -2159,9 +2066,10 @@ void QGraphicsItem::setOpacity(qreal opacity) d_ptr->opacity = newOpacity; - // Notify - if (notify) - itemChange(ItemOpacityHasChanged, newOpacity); + // Notify change. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE + itemChange(ItemOpacityHasChanged, newOpacity); +#endif // Update. if (d_ptr->scene) @@ -2610,15 +2518,15 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) if (this->pos == pos) return; + // Notify the item that the position is changing. +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE + const QVariant newPosVariant(q->itemChange(QGraphicsItem::ItemPositionChange, pos)); + QPointF newPos = newPosVariant.toPointF(); + if (newPos == this->pos) + return; +#else QPointF newPos = pos; - - // Notify - bool notify = q->itemChangeEnabled(QGraphicsItem::ItemPositionChange); - if (notify) { - newPos = q->itemChange(QGraphicsItem::ItemPositionChange, pos).toPointF(); - if (newPos == this->pos) - return; - } +#endif // Update and repositition. inSetPosHelper = 1; @@ -2629,9 +2537,9 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) dirtySceneTransform = 1; // Send post-notification. - if (notify) - q->itemChange(QGraphicsItem::ItemPositionHasChanged, newPos); - +#ifndef QGRAPHICSITEM_NO_ITEMCHANGE + q->itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); +#endif inSetPosHelper = 0; } @@ -3333,13 +3241,11 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) return; // Notify the item that the transformation matrix is changing. - bool notify = itemChangeEnabled(ItemMatrixChange); - if (notify) { - newTransform = QTransform(qVariantValue(itemChange(ItemMatrixChange, - qVariantFromValue(newTransform.toAffine())))); - if (d_ptr->transformData->transform == newTransform) - return; - } + const QVariant newTransformVariant(itemChange(ItemTransformChange, + qVariantFromValue(newTransform))); + newTransform = qVariantValue(newTransformVariant); + if (d_ptr->transformData->transform == newTransform) + return; // Update and set the new transformation. prepareGeometryChange(); @@ -3347,8 +3253,7 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) d_ptr->dirtySceneTransform = 1; // Send post-notification. - if (notify) - itemChange(ItemTransformHasChanged, qVariantFromValue(newTransform)); + itemChange(ItemTransformHasChanged, newTransformVariant); } /*! @@ -3380,12 +3285,12 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) return; // Notify the item that the transformation matrix is changing. - bool notify = itemChangeEnabled(ItemTransformChange); - if (notify) { - newTransform = qVariantValue(itemChange(ItemTransformChange, qVariantFromValue(newTransform))); - if (d_ptr->transformData->transform == newTransform) - return; - } + // Notify the item that the transformation matrix is changing. + const QVariant newTransformVariant(itemChange(ItemTransformChange, + qVariantFromValue(newTransform))); + newTransform = qVariantValue(newTransformVariant); + if (d_ptr->transformData->transform == newTransform) + return; // Update and set the new transformation. prepareGeometryChange(); @@ -3393,8 +3298,7 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) d_ptr->dirtySceneTransform = 1; // Send post-notification. - if (notify) - itemChange(ItemTransformHasChanged, qVariantFromValue(newTransform)); + itemChange(ItemTransformHasChanged, newTransformVariant); } /*! @@ -3561,13 +3465,10 @@ qreal QGraphicsItem::zValue() const */ void QGraphicsItem::setZValue(qreal z) { - bool notify = itemChangeEnabled(ItemZValueChange); - qreal newZ = z; - if (notify) { - newZ = itemChange(ItemZValueChange, double(z)).toDouble(); - if (newZ == d_ptr->z) - return; - } + const QVariant newZVariant(itemChange(ItemZValueChange, double(z))); + qreal newZ = qreal(newZVariant.toDouble()); + if (newZ == d_ptr->z) + return; d_ptr->z = newZ; if (d_ptr->parent) d_ptr->parent->d_ptr->needSortChildren = 1; @@ -3581,8 +3482,7 @@ void QGraphicsItem::setZValue(qreal z) d_ptr->scene->d_func()->invalidateSortCache(); } - if (notify) - itemChange(ItemZValueHasChanged, newZ); + itemChange(ItemZValueHasChanged, newZVariant); } /*! diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index 67b57e0..7e33c83 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -129,7 +129,6 @@ public: ItemZValueHasChanged, ItemOpacityChange, ItemOpacityHasChanged - // NB! Don't forget to increase d_ptr->itemChangesEnabled when adding a new entry. }; enum CacheMode { @@ -166,10 +165,6 @@ public: void setFlag(GraphicsItemFlag flag, bool enabled = true); void setFlags(GraphicsItemFlags flags); - bool itemChangeEnabled(GraphicsItemChange change) const; - void setItemChangeEnabled(GraphicsItemChange change, bool enabled); - void setItemChangesEnabled(bool enabled); - CacheMode cacheMode() const; void setCacheMode(CacheMode mode, const QSize &cacheSize = QSize()); diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 62ef36a..13fee8f 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -148,7 +148,6 @@ public: paintedViewBoundingRectsNeedRepaint(0), dirtySceneTransform(1), geometryChanged(0), - itemChangesEnabled(0xffff), globalStackingOrder(-1), q_ptr(0) { @@ -403,8 +402,7 @@ public: quint32 paintedViewBoundingRectsNeedRepaint : 1; quint32 dirtySceneTransform : 1; quint32 geometryChanged : 1; - quint32 unused : 2; // feel free to use - quint32 itemChangesEnabled : 16; + quint32 unused : 17; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 28d65da..54fead1 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -662,10 +662,8 @@ void QGraphicsScenePrivate::_q_polishItems() const QVariant booleanTrueVariant(true); foreach (QGraphicsItem *item, unpolishedItems) { if (!item->d_ptr->explicitlyHidden) { - if (item->itemChangeEnabled(QGraphicsItem::ItemVisibleChange)) { - item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant); - item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant); - } + item->itemChange(QGraphicsItem::ItemVisibleChange, booleanTrueVariant); + item->itemChange(QGraphicsItem::ItemVisibleHasChanged, booleanTrueVariant); } if (item->isWidget()) { QEvent event(QEvent::Polish); @@ -2969,12 +2967,9 @@ void QGraphicsScene::addItem(QGraphicsItem *item) // Notify the item that its scene is changing, and allow the item to // react. - QGraphicsScene *targetScene = this; - bool notify = item->itemChangeEnabled(QGraphicsItem::ItemSceneChange); - if (notify) { - targetScene = qVariantValue(item->itemChange(QGraphicsItem::ItemSceneChange, - qVariantFromValue(this))); - } + const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange, + qVariantFromValue(this))); + QGraphicsScene *targetScene = qVariantValue(newSceneVariant); if (targetScene != this) { if (targetScene && item->scene() != targetScene) targetScene->addItem(item); @@ -3085,8 +3080,7 @@ void QGraphicsScene::addItem(QGraphicsItem *item) emit selectionChanged(); // Deliver post-change notification - if (notify) - item->itemChange(QGraphicsItem::ItemSceneHasChanged, qVariantFromValue(targetScene)); + item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); } /*! @@ -3350,12 +3344,9 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) // Notify the item that it's scene is changing to 0, allowing the item to // react. - QGraphicsScene *targetScene = 0; - bool notify = item->itemChangeEnabled(QGraphicsItem::ItemSceneChange); - if (notify) { - targetScene = qVariantValue(item->itemChange(QGraphicsItem::ItemSceneChange, - qVariantFromValue(0))); - } + const QVariant newSceneVariant(item->itemChange(QGraphicsItem::ItemSceneChange, + qVariantFromValue(0))); + QGraphicsScene *targetScene = qVariantValue(newSceneVariant); if (targetScene != 0 && targetScene != this) { targetScene->addItem(item); return; @@ -3452,8 +3443,7 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) emit selectionChanged(); // Deliver post-change notification - if (notify) - item->itemChange(QGraphicsItem::ItemSceneHasChanged, qVariantFromValue(targetScene)); + item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); } /*! -- cgit v0.12 From c07239ac97dfce35a6b277c82ec5445e01eb2249 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Mon, 8 Jun 2009 14:15:22 +0200 Subject: Add another auto-test ensuring updates outside the brect are discared. --- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 7a789c5..35a7bb9 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -6487,6 +6487,14 @@ void tst_QGraphicsItem::update() const QRegion expectedRegion = itemDeviceBoundingRect.adjusted(-2, -2, 2, 2); // The entire item's bounding rect (adjusted for antialiasing) should have been painted. QCOMPARE(view.paintedRegion, expectedRegion); + + // Make sure update requests outside the bounding rect are discarded. + view.reset(); + item->repaints = 0; + item->update(-15, -15, 5, 5); // Item's brect: (-10, -10, 20, 20) + qApp->processEvents(); + QCOMPARE(item->repaints, 0); + QCOMPARE(view.repaints, 0); } void tst_QGraphicsItem::setTransformProperties_data() -- cgit v0.12 From 8a5a52e95a8ec81ce4bc3bb0599cfab510c8400a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Mon, 8 Jun 2009 17:33:11 +0200 Subject: Auto-test to ensure moved items don't leave traces. See also: 1c9032f29d4500b33622d7510b6361c99d9af296 --- src/gui/graphicsview/qgraphicsscene.cpp | 3 +- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 78 ++++++++++++++++++++++++++ 2 files changed, 80 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 54fead1..7038c3d 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5156,8 +5156,9 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * QRectF brect = item->boundingRect(); // ### This does not take the clip into account. _q_adjustRect(&brect); - viewBoundingRect = transformTmp.mapRect(brect).toRect().adjusted(-1, -1, 1, 1); + viewBoundingRect = transformTmp.mapRect(brect).toRect(); item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect); + viewBoundingRect.adjust(-1, -1, 1, 1); if (exposedRegion) viewBoundingRect &= exposedRegion->boundingRect(); } diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 35a7bb9..c6f9824 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -224,6 +224,7 @@ private slots: void setTransformProperties_data(); void setTransformProperties(); void itemUsesExtendedStyleOption(); + void moveItem(); // task specific tests below me void task141694_textItemEnsureVisible(); @@ -6744,5 +6745,82 @@ void tst_QGraphicsItem::itemUsesExtendedStyleOption() QTest::qWait(125); } +// Make sure we update moved items correctly. +void tst_QGraphicsItem::moveItem() +{ + QGraphicsScene scene; + scene.setSceneRect(-50, -50, 200, 200); + + MyGraphicsView view(&scene); + view.show(); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&view); +#endif + QTest::qWait(100); + + EventTester *parent = new EventTester; + EventTester *child = new EventTester(parent); + EventTester *grandChild = new EventTester(child); + +#define RESET_COUNTERS \ + parent->repaints = 0; \ + child->repaints = 0; \ + grandChild->repaints = 0; \ + view.reset(); + + scene.addItem(parent); + QTest::qWait(100); + + RESET_COUNTERS + + // Item's boundingRect: (-10, -10, 20, 20). + QRect parentDeviceBoundingRect = parent->deviceTransform(view.viewportTransform()) + .mapRect(parent->boundingRect()).toRect() + .adjusted(-2, -2, 2, 2); // Adjusted for antialiasing. + + parent->setPos(20, 20); + qApp->processEvents(); + QCOMPARE(parent->repaints, 1); + QCOMPARE(view.repaints, 1); + QRegion expectedParentRegion = parentDeviceBoundingRect; // old position + parentDeviceBoundingRect.translate(20, 20); + expectedParentRegion += parentDeviceBoundingRect; // new position + QCOMPARE(view.paintedRegion, expectedParentRegion); + + RESET_COUNTERS + + child->setPos(20, 20); + qApp->processEvents(); + QCOMPARE(parent->repaints, 1); + QCOMPARE(child->repaints, 1); + QCOMPARE(view.repaints, 1); + const QRegion expectedChildRegion = expectedParentRegion.translated(20, 20); + QCOMPARE(view.paintedRegion, expectedChildRegion); + + RESET_COUNTERS + + grandChild->setPos(20, 20); + qApp->processEvents(); + QCOMPARE(parent->repaints, 1); + QCOMPARE(child->repaints, 1); + QCOMPARE(grandChild->repaints, 1); + QCOMPARE(view.repaints, 1); + const QRegion expectedGrandChildRegion = expectedParentRegion.translated(40, 40); + QCOMPARE(view.paintedRegion, expectedGrandChildRegion); + + RESET_COUNTERS + + parent->translate(20, 20); + qApp->processEvents(); + QCOMPARE(parent->repaints, 1); + QCOMPARE(child->repaints, 1); + QCOMPARE(grandChild->repaints, 1); + QCOMPARE(view.repaints, 1); + expectedParentRegion.translate(20, 20); + expectedParentRegion += expectedChildRegion.translated(20, 20); + expectedParentRegion += expectedGrandChildRegion.translated(20, 20); + QCOMPARE(view.paintedRegion, expectedParentRegion); +} + QTEST_MAIN(tst_QGraphicsItem) #include "tst_qgraphicsitem.moc" -- cgit v0.12 From 50ddb3451007a94d87c064216603a3e3e6e8b9c6 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 8 Jun 2009 18:58:57 +0200 Subject: Add ItemSendsGeometryChanges, replacing itemChangeEnabled(). This flag toggles whether we should send notifications for setPos, setMatrix, and setTransform. It's off by default. Docs have been updated. All autotests pass. This change also cleans up a bit so that we both have readable code, and keeping the optimized path for when we need to send the notifications. By enabling this flag by default we are going to trigger regressions in end-user code. Reviewed-by: bnilsen --- examples/graphicsview/elasticnodes/node.cpp | 1 + src/gui/graphicsview/qgraphicsitem.cpp | 161 ++++++++++++++----------- src/gui/graphicsview/qgraphicsitem.h | 3 +- src/gui/graphicsview/qgraphicsitem_p.h | 5 +- src/gui/graphicsview/qgraphicswidget.cpp | 3 + src/gui/graphicsview/qgraphicswidget_p.cpp | 2 + tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 58 ++++++++- 7 files changed, 158 insertions(+), 75 deletions(-) diff --git a/examples/graphicsview/elasticnodes/node.cpp b/examples/graphicsview/elasticnodes/node.cpp index 6942fa0..53fe994 100644 --- a/examples/graphicsview/elasticnodes/node.cpp +++ b/examples/graphicsview/elasticnodes/node.cpp @@ -52,6 +52,7 @@ Node::Node(GraphWidget *graphWidget) : graph(graphWidget) { setFlag(ItemIsMovable); + setFlag(ItemSendsGeometryChanges); setCacheMode(DeviceCoordinateCache); setZValue(1); } diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 6679bd5..3138faa 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -39,8 +39,6 @@ ** ****************************************************************************/ -#define QGRAPHICSITEM_NO_ITEMCHANGE - /*! \class QGraphicsItem \brief The QGraphicsItem class is the base class for all graphical @@ -310,7 +308,14 @@ \value ItemHasNoContents The item does not paint anything (i.e., calling paint() on the item has no effect). You should set this flag on items that do not need to be painted to ensure that Graphics View avoids unnecessary - painting preparations. + painting preparations. This flag was introduced in Qt 4.6. + + \value ItemSendsGeometryChanges The item enables itemChange() + notifications for ItemPositionChange, ItemPositionHasChanged, + ItemMatrixChange, ItemTransformChange, and ItemTransformHasChanged. For + performance reasons, these notifications are disabled by default. You must + enable this flag to receive notifications for position and transform + changes. This flag was introduced in Qt 4.6. */ /*! @@ -349,33 +354,36 @@ changing. This value is obsolete; you can use ItemTransformChange instead. \value ItemPositionChange The item's position changes. This notification - is only sent when the item's local position changes, relative to its - parent, has changed (i.e., as a result of calling setPos() or - moveBy()). The value argument is the new position (i.e., a QPointF). You - can call pos() to get the original position. Do not call setPos() or - moveBy() in itemChange() as this notification is delivered; instead, you - can return the new, adjusted position from itemChange(). After this - notification, QGraphicsItem immediately sends the ItemPositionHasChanged - notification if the position changed. + is sent if the ItemSendsGeometryChanges flag is enabled, and when the + item's local position changes, relative to its parent (i.e., as a result + of calling setPos() or moveBy()). The value argument is the new position + (i.e., a QPointF). You can call pos() to get the original position. Do + not call setPos() or moveBy() in itemChange() as this notification is + delivered; instead, you can return the new, adjusted position from + itemChange(). After this notification, QGraphicsItem immediately sends the + ItemPositionHasChanged notification if the position changed. \value ItemPositionHasChanged The item's position has changed. This - notification is only sent after the item's local position, relative to its - parent, has changed. The value argument is the new position (the same as - pos()), and QGraphicsItem ignores the return value for this notification - (i.e., a read-only notification). + notification is sent if the ItemSendsGeometryChanges flag is enabled, and + after the item's local position, relative to its parent, has changed. The + value argument is the new position (the same as pos()), and QGraphicsItem + ignores the return value for this notification (i.e., a read-only + notification). \value ItemTransformChange The item's transformation matrix changes. This - notification is only sent when the item's local transformation matrix - changes (i.e., as a result of calling setTransform(). The value - argument is the new matrix (i.e., a QTransform); to get the old matrix, - call transform(). Do not call setTransform() or set any of the transformation - properties in itemChange() as this notification is delivered; - instead, you can return the new matrix from itemChange(). - This notification is not sent if you change the transformation properties. + notification is send if the ItemSendsGeometryChanges flag is enabled, and + when the item's local transformation matrix changes (i.e., as a result of + calling setTransform(). The value argument is the new matrix (i.e., a + QTransform); to get the old matrix, call transform(). Do not call + setTransform() or set any of the transformation properties in itemChange() + as this notification is delivered; instead, you can return the new matrix + from itemChange(). This notification is not sent if you change the + transformation properties. \value ItemTransformHasChanged The item's transformation matrix has - changed either because setTransform is called, or one of the transformation - properties is changed. This notification is only sent after the item's local + changed either because setTransform is called, or one of the + transformation properties is changed. This notification is sent if the + ItemSendsGeometryChanges flag is enabled, and after the item's local transformation matrix has changed. The value argument is the new matrix (same as transform()), and QGraphicsItem ignores the return value for this notification (i.e., a read-only notification). @@ -1369,7 +1377,9 @@ static void _q_qgraphicsItemSetFlag(QGraphicsItem *item, QGraphicsItem::Graphics item was selected, and \a flags does not enabled ItemIsSelectable, the item is automatically unselected. - By default, no flags are enabled. + By default, no flags are enabled. (QGraphicsWidget enables the + ItemSendsGeometryChanges flag by default in order to track position + changes.) \sa flags(), setFlag() */ @@ -2050,12 +2060,8 @@ qreal QGraphicsItem::effectiveOpacity() const void QGraphicsItem::setOpacity(qreal opacity) { // Notify change. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE const QVariant newOpacityVariant(itemChange(ItemOpacityChange, double(opacity))); qreal newOpacity = newOpacityVariant.toDouble(); -#else - qreal newOpacity = opacity; -#endif // Normalize. newOpacity = qBound(0.0, newOpacity, 1.0); @@ -2067,9 +2073,7 @@ void QGraphicsItem::setOpacity(qreal opacity) d_ptr->opacity = newOpacity; // Notify change. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - itemChange(ItemOpacityHasChanged, newOpacity); -#endif + itemChange(ItemOpacityHasChanged, newOpacityVariant); // Update. if (d_ptr->scene) @@ -2508,42 +2512,33 @@ QPointF QGraphicsItem::scenePos() const /*! \internal - Sets the position \a pos and notifies the change. If \a update is true, - the item is also updated; otherwise it is not updated before and after the - change. + Sets the position \a pos. */ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) { Q_Q(QGraphicsItem); - if (this->pos == pos) - return; - - // Notify the item that the position is changing. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - const QVariant newPosVariant(q->itemChange(QGraphicsItem::ItemPositionChange, pos)); - QPointF newPos = newPosVariant.toPointF(); - if (newPos == this->pos) - return; -#else - QPointF newPos = pos; -#endif - - // Update and repositition. inSetPosHelper = 1; - updateCachedClipPathFromSetPosHelper(newPos); + updateCachedClipPathFromSetPosHelper(pos); if (scene) q->prepareGeometryChange(); - this->pos = newPos; + this->pos = pos; dirtySceneTransform = 1; - - // Send post-notification. -#ifndef QGRAPHICSITEM_NO_ITEMCHANGE - q->itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); -#endif inSetPosHelper = 0; } /*! + \internal + + Sets the transform \a transform. +*/ +void QGraphicsItemPrivate::setTransformHelper(const QTransform &transform) +{ + q_ptr->prepareGeometryChange(); + transformData->transform = transform; + dirtySceneTransform = 1; +} + +/*! Sets the position of the item to \a pos, which is in parent coordinates. For items with no parent, \a pos is in scene coordinates. @@ -2555,7 +2550,26 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) */ void QGraphicsItem::setPos(const QPointF &pos) { - d_ptr->setPosHelper(pos); + if (d_ptr->pos == pos) + return; + + // Update and repositition. + if (!(d_ptr->flags & ItemSendsGeometryChanges)) { + d_ptr->setPosHelper(pos); + return; + } + + // Notify the item that the position is changing. + const QVariant newPosVariant(itemChange(ItemPositionChange, qVariantFromValue(pos))); + QPointF newPos = newPosVariant.toPointF(); + if (newPos == d_ptr->pos) + return; + + // Update and repositition. + d_ptr->setPosHelper(newPos); + + // Send post-notification. + itemChange(QGraphicsItem::ItemPositionHasChanged, newPosVariant); } /*! @@ -3240,20 +3254,23 @@ void QGraphicsItem::setMatrix(const QMatrix &matrix, bool combine) if (d_ptr->transformData->transform == newTransform) return; + // Update and set the new transformation. + if (!(d_ptr->flags & ItemSendsGeometryChanges)) { + d_ptr->setTransformHelper(newTransform); + return; + } + // Notify the item that the transformation matrix is changing. - const QVariant newTransformVariant(itemChange(ItemTransformChange, - qVariantFromValue(newTransform))); - newTransform = qVariantValue(newTransformVariant); + const QVariant newMatrixVariant = qVariantFromValue(newTransform.toAffine()); + newTransform = QTransform(qVariantValue(itemChange(ItemMatrixChange, newMatrixVariant))); if (d_ptr->transformData->transform == newTransform) return; // Update and set the new transformation. - prepareGeometryChange(); - d_ptr->transformData->transform = newTransform; - d_ptr->dirtySceneTransform = 1; - + d_ptr->setTransformHelper(newTransform); + // Send post-notification. - itemChange(ItemTransformHasChanged, newTransformVariant); + itemChange(ItemTransformHasChanged, qVariantFromValue(newTransform)); } /*! @@ -3284,7 +3301,12 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) if (d_ptr->transformData->transform == newTransform) return; - // Notify the item that the transformation matrix is changing. + // Update and set the new transformation. + if (!(d_ptr->flags & ItemSendsGeometryChanges)) { + d_ptr->setTransformHelper(newTransform); + return; + } + // Notify the item that the transformation matrix is changing. const QVariant newTransformVariant(itemChange(ItemTransformChange, qVariantFromValue(newTransform))); @@ -3293,9 +3315,7 @@ void QGraphicsItem::setTransform(const QTransform &matrix, bool combine) return; // Update and set the new transformation. - prepareGeometryChange(); - d_ptr->transformData->transform = newTransform; - d_ptr->dirtySceneTransform = 1; + d_ptr->setTransformHelper(newTransform); // Send post-notification. itemChange(ItemTransformHasChanged, newTransformVariant); @@ -9514,6 +9534,9 @@ QDebug operator<<(QDebug debug, QGraphicsItem::GraphicsItemFlag flag) case QGraphicsItem::ItemHasNoContents: str = "ItemHasNoContents"; break; + case QGraphicsItem::ItemSendsGeometryChanges: + str = "ItemSendsGeometryChanges"; + break; } debug << str; return debug; diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index 7e33c83..cff4f1f 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -96,7 +96,8 @@ public: ItemDoesntPropagateOpacityToChildren = 0x80, ItemStacksBehindParent = 0x100, ItemUsesExtendedStyleOption = 0x200, - ItemHasNoContents = 0x400 + ItemHasNoContents = 0x400, + ItemSendsGeometryChanges = 0x800 // NB! Don't forget to increase the d_ptr->flags bit field by 1 when adding a new flag. }; Q_DECLARE_FLAGS(GraphicsItemFlags, GraphicsItemFlag) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 13fee8f..e2a37a1 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -175,6 +175,7 @@ public: static bool movableAncestorIsSelected(const QGraphicsItem *item); void setPosHelper(const QPointF &pos); + void setTransformHelper(const QTransform &transform); void setVisibleHelper(bool newVisible, bool explicitly, bool update = true); void setEnabledHelper(bool newEnabled, bool explicitly, bool update = true); bool discardUpdateRequest(bool ignoreClipping = false, bool ignoreVisibleBit = false, @@ -397,12 +398,12 @@ public: quint32 fullUpdatePending : 1; // New 32 bits - quint32 flags : 11; + quint32 flags : 12; quint32 dirtyChildrenBoundingRect : 1; quint32 paintedViewBoundingRectsNeedRepaint : 1; quint32 dirtySceneTransform : 1; quint32 geometryChanged : 1; - quint32 unused : 17; // feel free to use + quint32 unused : 16; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 3296aee..7314167 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -1057,6 +1057,9 @@ void QGraphicsWidget::updateGeometry() ItemParentChange both to deliver \l ParentChange events, and for managing the focus chain. + QGraphicsWidget enables the ItemSendsGeometryChanges flag by default in + order to track position changes. + \sa propertyChange() */ QVariant QGraphicsWidget::itemChange(GraphicsItemChange change, const QVariant &value) diff --git a/src/gui/graphicsview/qgraphicswidget_p.cpp b/src/gui/graphicsview/qgraphicswidget_p.cpp index a435758..557b883 100644 --- a/src/gui/graphicsview/qgraphicswidget_p.cpp +++ b/src/gui/graphicsview/qgraphicswidget_p.cpp @@ -77,7 +77,9 @@ void QGraphicsWidgetPrivate::init(QGraphicsItem *parentItem, Qt::WindowFlags wFl resolveLayoutDirection(); q->unsetWindowFrameMargins(); q->setFlag(QGraphicsItem::ItemUsesExtendedStyleOption); + q->setFlag(QGraphicsItem::ItemSendsGeometryChanges); } + qreal QGraphicsWidgetPrivate::titleBarHeight(const QStyleOptionTitleBar &options) const { Q_Q(const QGraphicsWidget); diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index c6f9824..d6ecbba 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -224,6 +224,7 @@ private slots: void setTransformProperties_data(); void setTransformProperties(); void itemUsesExtendedStyleOption(); + void itemSendsGeometryChanges(); void moveItem(); // task specific tests below me @@ -3730,8 +3731,20 @@ void tst_QGraphicsItem::defaultItemTest_QGraphicsEllipseItem() class ItemChangeTester : public QGraphicsRectItem { public: - ItemChangeTester(){} - ItemChangeTester(QGraphicsItem *parent) : QGraphicsRectItem(parent) {} + ItemChangeTester() + { setFlag(ItemSendsGeometryChanges); clear(); } + ItemChangeTester(QGraphicsItem *parent) : QGraphicsRectItem(parent) + { setFlag(ItemSendsGeometryChanges); clear(); } + + void clear() + { + itemChangeReturnValue = QVariant(); + itemSceneChangeTargetScene = 0; + changes.clear(); + values.clear(); + oldValues.clear(); + } + QVariant itemChangeReturnValue; QGraphicsScene *itemSceneChangeTargetScene; @@ -3932,7 +3945,8 @@ void tst_QGraphicsItem::itemChange() QCOMPARE(tester.changes.size(), changeCount); QCOMPARE(tester.changes.at(tester.changes.size() - 2), QGraphicsItem::ItemFlagsChange); QCOMPARE(tester.changes.at(tester.changes.size() - 1), QGraphicsItem::ItemFlagsHaveChanged); - QCOMPARE(tester.values.at(tester.values.size() - 2), qVariantFromValue(QGraphicsItem::ItemIsSelectable)); + QVariant expectedFlags = qVariantFromValue(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemSendsGeometryChanges); + QCOMPARE(tester.values.at(tester.values.size() - 2), expectedFlags); QCOMPARE(tester.values.at(tester.values.size() - 1), qVariantFromValue(QGraphicsItem::ItemIsSelectable)); } { @@ -6745,6 +6759,44 @@ void tst_QGraphicsItem::itemUsesExtendedStyleOption() QTest::qWait(125); } +void tst_QGraphicsItem::itemSendsGeometryChanges() +{ + ItemChangeTester item; + item.setFlags(0); + item.clear(); + + QTransform x = QTransform().rotate(45); + QPointF pos(10, 10); + qreal o(0.5); + item.setTransform(x); + item.setPos(pos); + QCOMPARE(item.transform(), x); + QCOMPARE(item.pos(), pos); + QCOMPARE(item.changes.size(), 0); + + item.setOpacity(o); + QCOMPARE(item.changes.size(), 2); // opacity + + item.setFlag(QGraphicsItem::ItemSendsGeometryChanges); + QCOMPARE(item.changes.size(), 4); // flags + item.setTransform(QTransform()); + item.setPos(QPointF()); + QCOMPARE(item.changes.size(), 8); // transform + pos + QCOMPARE(item.transform(), QTransform()); + QCOMPARE(item.pos(), QPointF()); + QCOMPARE(item.opacity(), o); + + QCOMPARE(item.changes, QList() + << QGraphicsItem::ItemOpacityChange + << QGraphicsItem::ItemOpacityHasChanged + << QGraphicsItem::ItemFlagsChange + << QGraphicsItem::ItemFlagsHaveChanged + << QGraphicsItem::ItemTransformChange + << QGraphicsItem::ItemTransformHasChanged + << QGraphicsItem::ItemPositionChange + << QGraphicsItem::ItemPositionHasChanged); +} + // Make sure we update moved items correctly. void tst_QGraphicsItem::moveItem() { -- cgit v0.12 From e8be9f499547125490d61fb07b6aa023e38cd410 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 8 Jun 2009 19:06:40 +0200 Subject: Update change log with behavior changes in Graphics View. --- dist/changes-4.6.0 | 33 +++++++++++++++++++++++---------- 1 file changed, 23 insertions(+), 10 deletions(-) diff --git a/dist/changes-4.6.0 b/dist/changes-4.6.0 index bedf58a..ba58bcf 100644 --- a/dist/changes-4.6.0 +++ b/dist/changes-4.6.0 @@ -40,17 +40,30 @@ information about a particular change. reasons for this is that Qt Software focuses on OpenGL for desktop hardware accelerated rendering. - - QStyleOptionGraphicsItem::exposedRect and QStyleOptionGraphicsItem::matrix - does no longer contain fine-grained values when passed in drawItems()/paint() - unless the QGraphicsItem::ItemUsesExtendedStyleOptions flag is enabled. - By default, exposedRect is initialized to the item's bounding rect - and the matrix is untransformed. - - - QStyleOptionGraphicsItem::levelOfDetails is obsoleted and its value - is always initialized to 1. For a more fine-grained value use - QStyleOptionGraphicsItem::levelOfDetailFromTransform(const QTransform &). - - When mixing OpenGL and QPainter calls you need to first call syncState() on the paint engine, for example "painter->paintEngine()->syncState()". This is to ensure that the engine flushes any pending drawing and sets up the GL modelview/projection matrices properly. + + - Graphics View has undergone heavy optimization work, and as a result of + this work, the following behavior changes were introduced. + + a) QStyleOptionGraphicsItem::exposedRect now contains the item's bounding + rectangle, and QStyleOptionGraphicsItem::matrix is uninitialized by + default. You can enable an exact exposed rectangle and a correct matrix + by enabling the flag QGraphicsItem::ItemUsesExtendedStyleOptions. + + b) QStyleOptionGraphicsItem::levelOfDetails is obsoleted and its value is + always initialized to 1. Instead you can call + QStyleOptionGraphicsItem::levelOfDetailFromTransform(const QTransform &) + to determine the level of detail. + + c) QGraphicsView no longer calls QGraphicsView::drawItems(), and in turn + QGraphicsScene::drawItems(), by default. You can get the old behavior + back by enabling QGraphicsView::IndirectPainting. + + d) QGraphicsItem no longer calls itemChange() for position and + transformation changes. If you want to receive notifications for changes + to the item's position and transformation, you can set the flag + QGraphicsItem::ItemSendsGeometryChanges (which is enabled by default by + QGraphicsWidget and QGraphicsProxyWidget). -- cgit v0.12 From e2e039954b2212a9cee0b7f72e383621f8bc6c8f Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 8 Jun 2009 19:26:59 +0200 Subject: Revert 7aee2a7054d1ca280f6dfc9c46b3fe2ce403ccb3, fix render bugs. This change introduced an unexpected interdependency for scenes with items that enable ItemStacksBehindParent, and that contain children that are transformed. There's a manual test for this, called clippingAndTransformations, which shows this problem. The bug has been fixed and this change also includes an autotest that covers exactly this problem. --- src/gui/graphicsview/qgraphicsscene.cpp | 15 +++--- src/gui/graphicsview/qgraphicsscene_p.h | 1 - tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 72 ++++++++++++++++++++++---- 3 files changed, 70 insertions(+), 18 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 7038c3d..7963ea1 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5138,9 +5138,10 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Calculate the full transform for this item. QRect viewBoundingRect; bool wasDirtyParentSceneTransform = false; + QTransform transform; if (item) { if (item->d_ptr->itemIsUntransformable()) { - transformTmp = item->deviceTransform(viewTransform); + transform = item->deviceTransform(viewTransform); } else { if (item->d_ptr->dirtySceneTransform) { item->d_ptr->sceneTransform = item->d_ptr->parent ? item->d_ptr->parent->d_ptr->sceneTransform @@ -5149,14 +5150,14 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * item->d_ptr->dirtySceneTransform = 0; wasDirtyParentSceneTransform = true; } - transformTmp = item->d_ptr->sceneTransform; - transformTmp *= viewTransform; + transform = item->d_ptr->sceneTransform; + transform *= viewTransform; } QRectF brect = item->boundingRect(); // ### This does not take the clip into account. _q_adjustRect(&brect); - viewBoundingRect = transformTmp.mapRect(brect).toRect(); + viewBoundingRect = transform.mapRect(brect).toRect(); item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect); viewBoundingRect.adjust(-1, -1, 1, 1); if (exposedRegion) @@ -5200,7 +5201,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Clip children. if (childClip) { painter->save(); - painter->setWorldTransform(transformTmp); + painter->setWorldTransform(transform); painter->setClipPath(item->shape(), Qt::IntersectClip); } @@ -5234,14 +5235,14 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * // Draw item if (!dontDrawItem) { - item->d_ptr->initStyleOption(&styleOptionTmp, transformTmp, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); + item->d_ptr->initStyleOption(&styleOptionTmp, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); bool savePainter = clipsToShape || !(optimizationFlags & QGraphicsView::DontSavePainterState); if (savePainter) painter->save(); if (!childClip) - painter->setWorldTransform(transformTmp); + painter->setWorldTransform(transform); if (clipsToShape) painter->setClipPath(item->shape(), Qt::IntersectClip); painter->setOpacity(opacity); diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index fd7decf..000e2ba 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -290,7 +290,6 @@ public: void updatePalette(const QPalette &palette); QStyleOptionGraphicsItem styleOptionTmp; - QTransform transformTmp; }; QT_END_NAMESPACE diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index d6ecbba..621f2bf 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -236,6 +236,9 @@ private slots: void task240400_clickOnTextItem(); void task243707_addChildBeforeParent(); void task197802_childrenVisibility(); + +private: + QList paintedItems; }; void tst_QGraphicsItem::init() @@ -5793,19 +5796,36 @@ void tst_QGraphicsItem::opacity2() QCOMPARE(grandChild->repaints, 0); } +class StacksBehindParentHelper : public QGraphicsRectItem +{ +public: + StacksBehindParentHelper(QList *paintedItems, const QRectF &rect, QGraphicsItem *parent = 0) + : QGraphicsRectItem(rect, parent), paintedItems(paintedItems) + { } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) + { + QGraphicsRectItem::paint(painter, option, widget); + paintedItems->append(this); + } + +private: + QList *paintedItems; +}; + void tst_QGraphicsItem::itemStacksBehindParent() { - QGraphicsRectItem *parent1 = new QGraphicsRectItem(QRectF(0, 0, 100, 50)); - QGraphicsRectItem *child11 = new QGraphicsRectItem(QRectF(-10, 10, 50, 50), parent1); - QGraphicsRectItem *grandChild111 = new QGraphicsRectItem(QRectF(-20, 20, 50, 50), child11); - QGraphicsRectItem *child12 = new QGraphicsRectItem(QRectF(60, 10, 50, 50), parent1); - QGraphicsRectItem *grandChild121 = new QGraphicsRectItem(QRectF(70, 20, 50, 50), child12); + StacksBehindParentHelper *parent1 = new StacksBehindParentHelper(&paintedItems, QRectF(0, 0, 100, 50)); + StacksBehindParentHelper *child11 = new StacksBehindParentHelper(&paintedItems, QRectF(-10, 10, 50, 50), parent1); + StacksBehindParentHelper *grandChild111 = new StacksBehindParentHelper(&paintedItems, QRectF(-20, 20, 50, 50), child11); + StacksBehindParentHelper *child12 = new StacksBehindParentHelper(&paintedItems, QRectF(60, 10, 50, 50), parent1); + StacksBehindParentHelper *grandChild121 = new StacksBehindParentHelper(&paintedItems, QRectF(70, 20, 50, 50), child12); - QGraphicsRectItem *parent2 = new QGraphicsRectItem(QRectF(0, 0, 100, 50)); - QGraphicsRectItem *child21 = new QGraphicsRectItem(QRectF(-10, 10, 50, 50), parent2); - QGraphicsRectItem *grandChild211 = new QGraphicsRectItem(QRectF(-20, 20, 50, 50), child21); - QGraphicsRectItem *child22 = new QGraphicsRectItem(QRectF(60, 10, 50, 50), parent2); - QGraphicsRectItem *grandChild221 = new QGraphicsRectItem(QRectF(70, 20, 50, 50), child22); + StacksBehindParentHelper *parent2 = new StacksBehindParentHelper(&paintedItems, QRectF(0, 0, 100, 50)); + StacksBehindParentHelper *child21 = new StacksBehindParentHelper(&paintedItems, QRectF(-10, 10, 50, 50), parent2); + StacksBehindParentHelper *grandChild211 = new StacksBehindParentHelper(&paintedItems, QRectF(-20, 20, 50, 50), child21); + StacksBehindParentHelper *child22 = new StacksBehindParentHelper(&paintedItems, QRectF(60, 10, 50, 50), parent2); + StacksBehindParentHelper *grandChild221 = new StacksBehindParentHelper(&paintedItems, QRectF(70, 20, 50, 50), child22); parent1->setData(0, "parent1"); child11->setData(0, "child11"); @@ -5827,25 +5847,57 @@ void tst_QGraphicsItem::itemStacksBehindParent() scene.addItem(parent1); scene.addItem(parent2); + paintedItems.clear(); + + QGraphicsView view(&scene); + view.show(); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&view); +#endif + QTest::qWait(250); + QCOMPARE(scene.items(0, 0, 100, 100), (QList() << grandChild111 << child11 << grandChild121 << child12 << parent1 << grandChild211 << child21 << grandChild221 << child22 << parent2)); + QCOMPARE(paintedItems, QList() + << parent2 << child22 << grandChild221 + << child21 << grandChild211 + << parent1 << child12 << grandChild121 + << child11 << grandChild111); child11->setFlag(QGraphicsItem::ItemStacksBehindParent); + scene.update(); + paintedItems.clear(); + QTest::qWait(250); + QCOMPARE(scene.items(0, 0, 100, 100), (QList() << grandChild121 << child12 << parent1 << grandChild111 << child11 << grandChild211 << child21 << grandChild221 << child22 << parent2)); + QCOMPARE(paintedItems, QList() + << parent2 << child22 << grandChild221 + << child21 << grandChild211 + << child11 << grandChild111 + << parent1 << child12 << grandChild121); child12->setFlag(QGraphicsItem::ItemStacksBehindParent); + paintedItems.clear(); + scene.update(); + QTest::qWait(250); + QCOMPARE(scene.items(0, 0, 100, 100), (QList() << parent1 << grandChild111 << child11 << grandChild121 << child12 << grandChild211 << child21 << grandChild221 << child22 << parent2)); + QCOMPARE(paintedItems, QList() + << parent2 << child22 << grandChild221 + << child21 << grandChild211 + << child12 << grandChild121 + << child11 << grandChild111 << parent1); } class ClippingAndTransformsScene : public QGraphicsScene -- cgit v0.12 From f84782506770f99e9633649483e4dd067e3abcd5 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 8 Jun 2009 19:50:14 +0200 Subject: Fix QGraphicsView::render() regression, ensure the right device is passed. If we pass the viewport widget as the widget pointer when rendering to an arbitrary painter (e.g., onto a pixmap), we confuse the rendering functions to thinking that it's the viewport's region we should render into. So instead, when drawItems() is passed a painter that's different from the view, we pass 0 for the widget. --- src/gui/graphicsview/qgraphicsview.cpp | 6 ++- tests/auto/qgraphicsview/tst_qgraphicsview.cpp | 57 ++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 166bcb9..e685f9b 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3526,8 +3526,10 @@ void QGraphicsView::drawItems(QPainter *painter, int numItems, const QStyleOptionGraphicsItem options[]) { Q_D(QGraphicsView); - if (d->scene) - d->scene->drawItems(painter, numItems, items, options, viewport()); + if (d->scene) { + QWidget *widget = painter->device() == viewport() ? viewport() : 0; + d->scene->drawItems(painter, numItems, items, options, widget); + } } /*! diff --git a/tests/auto/qgraphicsview/tst_qgraphicsview.cpp b/tests/auto/qgraphicsview/tst_qgraphicsview.cpp index 718c8d6..5167682 100644 --- a/tests/auto/qgraphicsview/tst_qgraphicsview.cpp +++ b/tests/auto/qgraphicsview/tst_qgraphicsview.cpp @@ -191,6 +191,7 @@ private slots: void centerOnDirtyItem(); void mouseTracking(); void mouseTracking2(); + void render(); // task specific tests below me void task172231_untransformableItems(); @@ -3203,6 +3204,62 @@ void tst_QGraphicsView::mouseTracking2() QCOMPARE(spy.count(), 1); } +class RenderTester : public QGraphicsRectItem +{ +public: + RenderTester(const QRectF &rect) + : QGraphicsRectItem(rect), paints(0) + { } + + void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, + QWidget *widget) + { + QGraphicsRectItem::paint(painter, option, widget); + ++paints; + } + + int paints; +}; + +void tst_QGraphicsView::render() +{ + // ### This test can be much more thorough - see QGraphicsScene::render. + QGraphicsScene scene; + RenderTester *r1 = new RenderTester(QRectF(0, 0, 50, 50)); + RenderTester *r2 = new RenderTester(QRectF(50, 50, 50, 50)); + RenderTester *r3 = new RenderTester(QRectF(0, 50, 50, 50)); + RenderTester *r4 = new RenderTester(QRectF(50, 0, 50, 50)); + scene.addItem(r1); + scene.addItem(r2); + scene.addItem(r3); + scene.addItem(r4); + + QGraphicsView view(&scene); + view.setFrameStyle(0); + view.resize(200, 200); + view.show(); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&view); +#endif + QTest::qWait(200); + + QCOMPARE(r1->paints, 1); + QCOMPARE(r2->paints, 1); + QCOMPARE(r3->paints, 1); + QCOMPARE(r4->paints, 1); + + QPixmap pix(200, 200); + pix.fill(Qt::transparent); + QPainter painter(&pix); + view.render(&painter); + painter.end(); + + QCOMPARE(r1->paints, 2); + QCOMPARE(r2->paints, 2); + QCOMPARE(r3->paints, 2); + QCOMPARE(r4->paints, 2); +} + void tst_QGraphicsView::task253415_reconnectUpdateSceneOnSceneChanged() { QGraphicsView view; -- cgit v0.12 From 31fa814955cd2b0983b42543e133f24e9830c67f Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Mon, 8 Jun 2009 19:54:51 +0200 Subject: Fix moving regression for ItemIgnoresTransformations items. Removes a piece of code in 775ec8e96c9219981ff220ca5f3d24f0501d17b5 that was submitted by accident. The code in mouseMoveEvent is now identical to that in master. --- src/gui/graphicsview/qgraphicsitem.cpp | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 3138faa..5ba87ee 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -5940,13 +5940,21 @@ void QGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent *event) if ((item->flags() & ItemIsMovable) && !QGraphicsItemPrivate::movableAncestorIsSelected(item)) { QPointF currentParentPos; QPointF buttonDownParentPos; - if (item->d_ptr->itemIsUntransformable()) { + if (item->d_ptr->ancestorFlags & QGraphicsItemPrivate::AncestorIgnoresTransformations) { // Items whose ancestors ignore transformations need to // map screen coordinates to local coordinates, then map // those to the parent. QTransform viewToItemTransform = (item->deviceTransform(view->viewportTransform())).inverted(); currentParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->screenPos())))); buttonDownParentPos = mapToParent(viewToItemTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton))))); + } else if (item->flags() & ItemIgnoresTransformations) { + // Root items that ignore transformations need to + // calculate their diff by mapping viewport coordinates + // directly to parent coordinates. + QTransform viewToParentTransform = (item->transform().translate(item->d_ptr->pos.x(), item->d_ptr->pos.y())) + * (item->sceneTransform() * view->viewportTransform()).inverted(); + currentParentPos = viewToParentTransform.map(QPointF(view->mapFromGlobal(event->screenPos()))); + buttonDownParentPos = viewToParentTransform.map(QPointF(view->mapFromGlobal(event->buttonDownScreenPos(Qt::LeftButton)))); } else { // All other items simply map from the scene. currentParentPos = item->mapToParent(item->mapFromScene(event->scenePos())); -- cgit v0.12 From e4d6cfb1be4a3ff71013362f1f827e3920524934 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 9 Jun 2009 09:05:17 +0200 Subject: Ensure we use the correct static paintedItems list. Fixes the zValue autotest, which regressed when the member list was added. --- tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index 621f2bf..af34fe5 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -1798,15 +1798,15 @@ void tst_QGraphicsItem::setMatrix() QCOMPARE(rlist.at(2), unrotatedRect); // From post-update (update current state) } -static QList paintedItems; +static QList _paintedItems; class PainterItem : public QGraphicsItem { protected: QRectF boundingRect() const { return QRectF(-10, -10, 20, 20); } - void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) - { paintedItems << this; } + void paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) + { _paintedItems << this; painter->fillRect(boundingRect(), Qt::red); } }; void tst_QGraphicsItem::zValue() @@ -1838,10 +1838,10 @@ void tst_QGraphicsItem::zValue() QApplication::sendPostedEvents(); //glib workaround #endif - QVERIFY(!paintedItems.isEmpty()); - QVERIFY((paintedItems.size() % 4) == 0); + QVERIFY(!_paintedItems.isEmpty()); + QVERIFY((_paintedItems.size() % 4) == 0); for (int i = 0; i < 3; ++i) - QVERIFY(paintedItems.at(i)->zValue() < paintedItems.at(i + 1)->zValue()); + QVERIFY(_paintedItems.at(i)->zValue() < _paintedItems.at(i + 1)->zValue()); } void tst_QGraphicsItem::shape() -- cgit v0.12 From 03428c4d2905cc73866f1d046b5cc1bedf1c38b3 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 9 Jun 2009 09:05:57 +0200 Subject: Remove one unnecessary argument from the recursive draw function. We don't have to pass optimization flags; we already have a member variable we can test for painter state protection. --- src/gui/graphicsview/qgraphicsscene.cpp | 14 +++++--------- src/gui/graphicsview/qgraphicsscene_p.h | 2 +- src/gui/graphicsview/qgraphicsview.cpp | 2 +- 3 files changed, 7 insertions(+), 11 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 7963ea1..e43c9cd 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5108,7 +5108,6 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, QRegion *exposedRegion, QWidget *widget, - QGraphicsView::OptimizationFlags optimizationFlags, QList *topLevelItems, qreal parentOpacity) { @@ -5229,7 +5228,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (!(child->d_ptr->flags & QGraphicsItem::ItemStacksBehindParent)) break; drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, widget, - optimizationFlags, 0, opacity); + 0, opacity); } } @@ -5238,7 +5237,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * item->d_ptr->initStyleOption(&styleOptionTmp, transform, exposedRegion ? *exposedRegion : QRegion(), exposedRegion == 0); bool clipsToShape = (item->d_ptr->flags & QGraphicsItem::ItemClipsToShape); - bool savePainter = clipsToShape || !(optimizationFlags & QGraphicsView::DontSavePainterState); + bool savePainter = clipsToShape || painterStateProtection; if (savePainter) painter->save(); if (!childClip) @@ -5261,7 +5260,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (wasDirtyParentSceneTransform) child->d_ptr->dirtySceneTransform = 1; drawSubtreeRecursive(child, painter, viewTransform, exposedRegion, - widget, optimizationFlags, 0, opacity); + widget, 0, opacity); } } else if (wasDirtyParentSceneTransform) { item->d_ptr->invalidateChildrenSceneTransform(); @@ -5487,11 +5486,8 @@ void QGraphicsScene::drawItems(QPainter *painter, // Determine view, expose and flags. QGraphicsView *view = widget ? qobject_cast(widget->parentWidget()) : 0; QRegion *expose = 0; - QGraphicsView::OptimizationFlags flags; - if (view) { + if (view) expose = &view->d_func()->exposedRegion; - flags = view->optimizationFlags(); - } // Find all toplevels, they are already sorted. QList topLevelItems; @@ -5500,7 +5496,7 @@ void QGraphicsScene::drawItems(QPainter *painter, if (!item->d_ptr->itemDiscovered) { topLevelItems << item; item->d_ptr->itemDiscovered = 1; - d->drawSubtreeRecursive(item, painter, viewTransform, expose, widget, flags); + d->drawSubtreeRecursive(item, painter, viewTransform, expose, widget); } } diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 000e2ba..42c4d8c 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -261,7 +261,7 @@ public: bool painterStateProtection); void drawSubtreeRecursive(QGraphicsItem *item, QPainter *painter, const QTransform &viewTransform, - QRegion *exposedRegion, QWidget *widget, QGraphicsView::OptimizationFlags optimizationFlags, + QRegion *exposedRegion, QWidget *widget, QList *topLevelItems = 0, qreal parentOpacity = qreal(1.0)); void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index e685f9b..4891e81 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3303,7 +3303,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) // Items if (!(d->optimizationFlags & IndirectPainting)) { d->scene->d_func()->drawSubtreeRecursive(0, &painter, viewTransform, &d->exposedRegion, - viewport(), d->optimizationFlags, 0); + viewport(), 0); } else { // Find all exposed items bool allItems = false; -- cgit v0.12 From 662d1db6ee1a78c298acc11e7528e73c0415fc75 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 9 Jun 2009 10:32:20 +0200 Subject: doc: Corrected the rich text page wrt smallcaps. Task-number: 254912 --- doc/src/richtext.qdoc | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/doc/src/richtext.qdoc b/doc/src/richtext.qdoc index fbd8adb..6ea82f8 100644 --- a/doc/src/richtext.qdoc +++ b/doc/src/richtext.qdoc @@ -1058,8 +1058,11 @@ Ideas for other sections: \o Specifies where an image or a text will be placed in another element. Note that the \c float property is only supported for tables and images. \row \o \c text-transform - \o [ uppercase | lowercase | smallcaps ] + \o [ uppercase | lowercase ] \o Select the transformation that will be performed on the text prior to displaying it. + \row \o \c font-variant + \o small-caps + \o Perform the smallcaps transformation on the text prior to displaying it. \row \o \c word-spacing \o px \o Specifies an alternate spacing between each word. -- cgit v0.12 From 29496148abe8506fbf50c99e9a210095c5115a14 Mon Sep 17 00:00:00 2001 From: Thomas Hartmann Date: Tue, 9 Jun 2009 10:42:46 +0200 Subject: Compile fix for !QFX_RENDER_OPENGL Some QFX_RENDER_OPENGL guards were missing and getPen had to be replaced with d->pen in some places Reviewed-by: Kai Koehne --- src/declarative/canvas/qsimplecanvasitem.h | 2 ++ src/declarative/fx/qfximage.cpp | 2 ++ src/declarative/fx/qfxrect.cpp | 6 +++--- src/declarative/fx/qfxrect_p.h | 7 +++++-- 4 files changed, 12 insertions(+), 5 deletions(-) diff --git a/src/declarative/canvas/qsimplecanvasitem.h b/src/declarative/canvas/qsimplecanvasitem.h index e62c56d..dce3007 100644 --- a/src/declarative/canvas/qsimplecanvasitem.h +++ b/src/declarative/canvas/qsimplecanvasitem.h @@ -45,7 +45,9 @@ #include #include #include +#if defined(QFX_RENDER_OPENGL) #include +#endif #include #include diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index c5e7e89..224c25e 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -127,10 +127,12 @@ QFxImage::~QFxImage() Q_D(QFxImage); if (d->sciReply) d->sciReply->deleteLater(); +#if defined(QFX_RENDER_OPENGL) if (d->tex) { d->tex->release(); d->tex = 0; } +#endif } /*! diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index eacc85e..f55357f 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -497,7 +497,7 @@ void QFxRect::generateRoundedRect() QPainter p(&(d->rectImage)); p.setRenderHint(QPainter::Antialiasing); if (d->pen && d->pen->isValid()) { - QPen pn(QColor(getPen()->color()), getPen()->width()); + QPen pn(QColor(d->pen->color()), d->pen->width()); p.setPen(pn); } else { p.setPen(Qt::NoPen); @@ -517,7 +517,7 @@ void QFxRect::generateBorderedRect() QPainter p(&(d->rectImage)); p.setRenderHint(QPainter::Antialiasing); if (d->pen && d->pen->isValid()) { - QPen pn(QColor(getPen()->color()), getPen()->width()); + QPen pn(QColor(d->pen->color()), d->pen->width()); p.setPen(pn); } else { p.setPen(Qt::NoPen); @@ -604,7 +604,7 @@ void QFxRect::drawRect(QPainter &p) QPainter::RenderHints oldHints = p.renderHints(); p.setRenderHint(QPainter::Antialiasing); if (d->pen && d->pen->isValid()) { - QPen pn(QColor(getPen()->color()), getPen()->width()); + QPen pn(QColor(d->pen->color()), d->pen->width()); p.setPen(pn); } else { p.setPen(Qt::NoPen); diff --git a/src/declarative/fx/qfxrect_p.h b/src/declarative/fx/qfxrect_p.h index d68eb4e..f662fac 100644 --- a/src/declarative/fx/qfxrect_p.h +++ b/src/declarative/fx/qfxrect_p.h @@ -68,8 +68,11 @@ class QFxRectPrivate : public QFxItemPrivate Q_DECLARE_PUBLIC(QFxRect) public: - QFxRectPrivate() - : rectTexture(0), gradient(0), pen(0), radius(0) + QFxRectPrivate() : +#if defined(QFX_RENDER_OPENGL) + rectTexture(0), +#endif //QFX_RENDER_OPENGL + gradient(0), pen(0), radius(0) { } -- cgit v0.12 From 91ceb21d1d5f6447a47853b6625fb51d2f21cf16 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 9 Jun 2009 10:51:26 +0200 Subject: small refactoring to reduce memory usage of static data --- src/corelib/codecs/qisciicodec.cpp | 2 +- src/corelib/tools/qlocale.cpp | 2 +- src/corelib/tools/qlocale_data_p.h | 10 +++++----- src/corelib/xml/qxmlstream.cpp | 7 +++---- util/local_database/qlocalexml2cpp.py | 6 +++--- 5 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/corelib/codecs/qisciicodec.cpp b/src/corelib/codecs/qisciicodec.cpp index dd2bc8d..de1e477 100644 --- a/src/corelib/codecs/qisciicodec.cpp +++ b/src/corelib/codecs/qisciicodec.cpp @@ -55,7 +55,7 @@ QT_BEGIN_NAMESPACE struct Codecs { - const char *name; + const char name[10]; ushort base; }; diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp index 00132d7..4898e10 100644 --- a/src/corelib/tools/qlocale.cpp +++ b/src/corelib/tools/qlocale.cpp @@ -772,7 +772,7 @@ QVariant QSystemLocale::query(QueryType type, QVariant in = QVariant()) const Instead it can return a "Windows code". This maps windows codes to ISO country names. */ struct WindowsToISOListElt { - int windows_code; + ushort windows_code; char iso_name[6]; }; diff --git a/src/corelib/tools/qlocale_data_p.h b/src/corelib/tools/qlocale_data_p.h index 37f59a4..e0eecf3 100644 --- a/src/corelib/tools/qlocale_data_p.h +++ b/src/corelib/tools/qlocale_data_p.h @@ -60,8 +60,8 @@ QT_BEGIN_NAMESPACE */ struct CountryLanguage { - quint32 languageId; - quint32 countryId; + quint16 languageId; + quint16 countryId; }; static const CountryLanguage ImperialMeasurementSystems[] = { { 31, 225 }, @@ -83,7 +83,7 @@ static const int ImperialMeasurementSystemsCount = */ -static const uint locale_index[] = { +static const quint16 locale_index[] = { 0, // unused 0, // C 0, // Abkhazian @@ -2313,7 +2313,7 @@ static const char language_name_list[] = "Chewa\0" ; -static const uint language_name_index[] = { +static const quint16 language_name_index[] = { 0, // Unused 8, // C 10, // Abkhazian @@ -2727,7 +2727,7 @@ static const char country_name_list[] = "SerbiaAndMontenegro\0" ; -static const uint country_name_index[] = { +static const quint16 country_name_index[] = { 0, // AnyCountry 8, // Afghanistan 20, // Albania diff --git a/src/corelib/xml/qxmlstream.cpp b/src/corelib/xml/qxmlstream.cpp index 5e1fec3..fddcecf 100644 --- a/src/corelib/xml/qxmlstream.cpp +++ b/src/corelib/xml/qxmlstream.cpp @@ -629,7 +629,7 @@ while () { $sizes[$i++] = $counter; $counter += length 1 + $_; } -print " \"\\0\";\n\nstatic const int QXmlStreamReader_tokenTypeString_indices[] = {\n "; +print " \"\\0\";\n\nstatic const short QXmlStreamReader_tokenTypeString_indices[] = {\n "; for ($j = 0; $j < $i; ++$j) { printf "$sizes[$j], "; } @@ -660,10 +660,9 @@ static const char QXmlStreamReader_tokenTypeString_string[] = "Comment\0" "DTD\0" "EntityReference\0" - "ProcessingInstruction\0" - "\0"; + "ProcessingInstruction\0"; -static const int QXmlStreamReader_tokenTypeString_indices[] = { +static const short QXmlStreamReader_tokenTypeString_indices[] = { 0, 8, 16, 30, 42, 55, 66, 77, 85, 89, 105, 0 }; diff --git a/util/local_database/qlocalexml2cpp.py b/util/local_database/qlocalexml2cpp.py index af6da33..d625cfd 100755 --- a/util/local_database/qlocalexml2cpp.py +++ b/util/local_database/qlocalexml2cpp.py @@ -318,7 +318,7 @@ def main(): print # Locale index - print "static const uint locale_index[] = {" + print "static const quint16 locale_index[] = {" print " 0, // unused" index = 0 for key in language_map.keys(): @@ -454,7 +454,7 @@ def main(): print # Language name index - print "static const uint language_name_index[] = {" + print "static const quint16 language_name_index[] = {" print " 0, // Unused" index = 8 for key in language_map.keys(): @@ -477,7 +477,7 @@ def main(): print # Country name index - print "static const uint country_name_index[] = {" + print "static const quint16 country_name_index[] = {" print " 0, // AnyCountry" index = 8 for key in country_map.keys(): -- cgit v0.12 From b1658783099b75097f02bef85c4ea2a469826d37 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 4 Jun 2009 19:49:41 +0200 Subject: make bic test works in shadow build --- tests/auto/bic/bic.pro | 6 ++++++ tests/auto/bic/tst_bic.cpp | 33 +++++++++++++++++---------------- 2 files changed, 23 insertions(+), 16 deletions(-) diff --git a/tests/auto/bic/bic.pro b/tests/auto/bic/bic.pro index a168d77..82711c9 100644 --- a/tests/auto/bic/bic.pro +++ b/tests/auto/bic/bic.pro @@ -2,3 +2,9 @@ load(qttest_p4) SOURCES += tst_bic.cpp qbic.cpp QT = core +wince*:{ + DEFINES += SRCDIR=\\\"\\\" +} else { + DEFINES += SRCDIR=\\\"$$PWD/\\\" +} + diff --git a/tests/auto/bic/tst_bic.cpp b/tests/auto/bic/tst_bic.cpp index 181c275..8bc8d4f 100644 --- a/tests/auto/bic/tst_bic.cpp +++ b/tests/auto/bic/tst_bic.cpp @@ -165,30 +165,30 @@ void tst_Bic::sizesAndVTables_data() #if defined Q_OS_LINUX && defined Q_WS_X11 # if defined(__powerpc__) && !defined(__powerpc64__) - archFileName400 = "data/%1.4.0.0.linux-gcc-ppc32.txt"; - archFileName410 = "data/%1.4.1.0.linux-gcc-ppc32.txt"; - archFileName420 = "data/%1.4.2.0.linux-gcc-ppc32.txt"; + archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-ppc32.txt"; + archFileName410 = SRCDIR "data/%1.4.1.0.linux-gcc-ppc32.txt"; + archFileName420 = SRCDIR "data/%1.4.2.0.linux-gcc-ppc32.txt"; # elif defined(__amd64__) - archFileName400 = "data/%1.4.0.0.linux-gcc-amd64.txt"; + archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-amd64.txt"; # elif defined(__i386__) - archFileName400 = "data/%1.4.0.0.linux-gcc-ia32.txt"; - archFileName410 = "data/%1.4.1.0.linux-gcc-ia32.txt"; - archFileName420 = "data/%1.4.2.0.linux-gcc-ia32.txt"; - archFileName430 = "data/%1.4.3.0.linux-gcc-ia32.txt"; + archFileName400 = SRCDIR "data/%1.4.0.0.linux-gcc-ia32.txt"; + archFileName410 = SRCDIR "data/%1.4.1.0.linux-gcc-ia32.txt"; + archFileName420 = SRCDIR "data/%1.4.2.0.linux-gcc-ia32.txt"; + archFileName430 = SRCDIR "data/%1.4.3.0.linux-gcc-ia32.txt"; # endif #elif defined Q_OS_AIX if (sizeof(void*) == 4) - archFileName400 = "data/%1.4.0.0.aix-gcc-power32.txt"; + archFileName400 = SRCDIR "data/%1.4.0.0.aix-gcc-power32.txt"; #elif defined Q_OS_MAC && defined(__powerpc__) - archFileName400 = "data/%1.4.0.0.macx-gcc-ppc32.txt"; - archFileName410 = "data/%1.4.1.0.macx-gcc-ppc32.txt"; - archFileName420 = "data/%1.4.2.0.macx-gcc-ppc32.txt"; + archFileName400 = SRCDIR "data/%1.4.0.0.macx-gcc-ppc32.txt"; + archFileName410 = SRCDIR "data/%1.4.1.0.macx-gcc-ppc32.txt"; + archFileName420 = SRCDIR "data/%1.4.2.0.macx-gcc-ppc32.txt"; #elif defined Q_OS_MAC && defined(__i386__) - archFileName410 = "data/%1.4.1.0.macx-gcc-ia32.txt"; - archFileName420 = "data/%1.4.2.0.macx-gcc-ia32.txt"; + archFileName410 = SRCDIR "data/%1.4.1.0.macx-gcc-ia32.txt"; + archFileName420 = SRCDIR "data/%1.4.2.0.macx-gcc-ia32.txt"; #elif defined Q_OS_WIN && defined Q_CC_GNU - archFileName410 = "data/%1.4.1.0.win32-gcc-ia32.txt"; - archFileName420 = "data/%1.4.2.0.win32-gcc-ia32.txt"; + archFileName410 = SRCDIR "data/%1.4.1.0.win32-gcc-ia32.txt"; + archFileName420 = SRCDIR "data/%1.4.2.0.win32-gcc-ia32.txt"; #endif if (archFileName400.isEmpty() && archFileName410.isEmpty() @@ -293,6 +293,7 @@ void tst_Bic::sizesAndVTables() bool isFailed = false; + qDebug() << oldLib.arg(libName); if (oldLib.isEmpty() || !QFile::exists(oldLib.arg(libName))) QSKIP("No platform spec found for this platform/version.", SkipSingle); -- cgit v0.12 From c5a9996213a535ad6b1e183ed258913082213073 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Tue, 9 Jun 2009 11:10:46 +0200 Subject: Fix focus frame on combobox on non-Windows styles State_KeyboardFocusChange only makes sens on Windows. Follow the logic on the combobox as in PE_FrameFocusRect in the QWindowsStyle Task-number: 255482 Reviewed-by: jbache --- src/gui/styles/qcleanlooksstyle.cpp | 3 ++- src/gui/styles/qgtkstyle.cpp | 2 +- src/gui/styles/qplastiquestyle.cpp | 3 ++- 3 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/gui/styles/qcleanlooksstyle.cpp b/src/gui/styles/qcleanlooksstyle.cpp index b33dfc1..805cd05 100644 --- a/src/gui/styles/qcleanlooksstyle.cpp +++ b/src/gui/styles/qcleanlooksstyle.cpp @@ -3305,7 +3305,8 @@ void QCleanlooksStyle::drawComplexControl(ComplexControl control, const QStyleOp } } // Draw the focus rect - if ((focus && (option->state & State_KeyboardFocusChange)) && !comboBox->editable) { + if (focus && !comboBox->editable + && ((option->state & State_KeyboardFocusChange) || styleHint(SH_UnderlineShortcut, option, widget))) { QStyleOptionFocusRect focus; focus.rect = subControlRect(CC_ComboBox, &comboBoxCopy, SC_ComboBoxEditField, widget) .adjusted(0, 2, option->direction == Qt::RightToLeft ? 1 : -1, -2); diff --git a/src/gui/styles/qgtkstyle.cpp b/src/gui/styles/qgtkstyle.cpp index 1fe4627..ab81d97 100644 --- a/src/gui/styles/qgtkstyle.cpp +++ b/src/gui/styles/qgtkstyle.cpp @@ -1426,7 +1426,7 @@ void QGtkStyle::drawComplexControl(ComplexControl control, const QStyleOptionCom QGtk::gtk_widget_style_get(gtkToggleButton, "interior-focus", &interiorFocus, NULL); int xt = interiorFocus ? gtkToggleButton->style->xthickness : 0; int yt = interiorFocus ? gtkToggleButton->style->ythickness : 0; - if ((focus && (option->state & State_KeyboardFocusChange))) + if (focus && ((option->state & State_KeyboardFocusChange) || styleHint(SH_UnderlineShortcut, option, widget))) gtkCachedPainter.paintFocus(gtkToggleButton, "button", option->rect.adjusted(xt, yt, -xt, -yt), option->state & State_Sunken ? GTK_STATE_ACTIVE : GTK_STATE_NORMAL, diff --git a/src/gui/styles/qplastiquestyle.cpp b/src/gui/styles/qplastiquestyle.cpp index 01c0e44..0a56213 100644 --- a/src/gui/styles/qplastiquestyle.cpp +++ b/src/gui/styles/qplastiquestyle.cpp @@ -4568,7 +4568,8 @@ void QPlastiqueStyle::drawComplexControl(ComplexControl control, const QStyleOpt } // Draw the focus rect - if (((option->state & State_HasFocus) && (option->state & State_KeyboardFocusChange)) && !comboBox->editable) { + if ((option->state & State_HasFocus) && !comboBox->editable + && ((option->state & State_KeyboardFocusChange) || styleHint(SH_UnderlineShortcut, option, widget))) { QStyleOptionFocusRect focus; focus.rect = subControlRect(CC_ComboBox, option, SC_ComboBoxEditField, widget) .adjusted(-2, 0, 2, 0); -- cgit v0.12 From 9b88c6f485016b53d394a88106a048495cf79294 Mon Sep 17 00:00:00 2001 From: Leonardo Sobral Cunha Date: Tue, 9 Jun 2009 11:58:45 +0200 Subject: Fix QImageReader autotest compilation --- tests/auto/qimagereader/qimagereader.qrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/auto/qimagereader/qimagereader.qrc b/tests/auto/qimagereader/qimagereader.qrc index 3c674ad..c6b963b 100644 --- a/tests/auto/qimagereader/qimagereader.qrc +++ b/tests/auto/qimagereader/qimagereader.qrc @@ -30,7 +30,7 @@ images/image.pgm images/image.png images/image.ppm - images/image.tif + images/image_100dpi.tif images/kollada.png images/marble.xpm images/namedcolors.xpm -- cgit v0.12 From d826a08add652314bb22bee44e0d43bbd672f272 Mon Sep 17 00:00:00 2001 From: Leonardo Sobral Cunha Date: Tue, 9 Jun 2009 12:02:59 +0200 Subject: Fix floating point exception in QImageReader::setScaledSize(QSize(0, 0)) Avoid a division by 0 when doing QImageReader::setScaledSize(QSize(0, 0)) for jpeg formats. Reviewed-by: thierry Task-number: 255627 --- src/plugins/imageformats/jpeg/qjpeghandler.cpp | 3 ++- tests/auto/qimagereader/tst_qimagereader.cpp | 26 ++++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/plugins/imageformats/jpeg/qjpeghandler.cpp b/src/plugins/imageformats/jpeg/qjpeghandler.cpp index 6d0bc1f..088ef97 100644 --- a/src/plugins/imageformats/jpeg/qjpeghandler.cpp +++ b/src/plugins/imageformats/jpeg/qjpeghandler.cpp @@ -781,7 +781,8 @@ static bool read_jpeg_image(QIODevice *device, QImage *outImage, #ifndef QT_NO_IMAGE_SMOOTHSCALE // If high quality not required, shrink image during decompression - if (scaledSize.isValid() && quality < HIGH_QUALITY_THRESHOLD && !params.contains(QLatin1String("GetHeaderInformation")) ) { + if (scaledSize.isValid() && !scaledSize.isEmpty() && quality < HIGH_QUALITY_THRESHOLD + && !params.contains(QLatin1String("GetHeaderInformation")) ) { cinfo.scale_denom = qMin(cinfo.image_width / scaledSize.width(), cinfo.image_width / scaledSize.height()); if (cinfo.scale_denom < 2) { diff --git a/tests/auto/qimagereader/tst_qimagereader.cpp b/tests/auto/qimagereader/tst_qimagereader.cpp index f5313eb..0b32f0a 100644 --- a/tests/auto/qimagereader/tst_qimagereader.cpp +++ b/tests/auto/qimagereader/tst_qimagereader.cpp @@ -156,6 +156,9 @@ private slots: void pixelCompareWithBaseline_data(); void pixelCompareWithBaseline(); + + void task255627_setNullScaledSize_data(); + void task255627_setNullScaledSize(); }; static const QLatin1String prefix(SRCDIR "/images/"); @@ -333,6 +336,29 @@ void tst_QImageReader::setScaledSize() QCOMPARE(image.size(), newSize); } +void tst_QImageReader::task255627_setNullScaledSize_data() +{ + setScaledSize_data(); +} + +void tst_QImageReader::task255627_setNullScaledSize() +{ + QFETCH(QString, fileName); + QFETCH(QByteArray, format); + + if (!format.isEmpty() && !QImageReader::supportedImageFormats().contains(format)) + QSKIP("Qt does not support reading the \"" + format + "\" format", SkipSingle); + + QImageReader reader(prefix + fileName); + + // set a null size + reader.setScaledSize(QSize(0, 0)); + reader.setQuality(0); + QImage image = reader.read(); + QVERIFY(image.isNull()); + QCOMPARE(image.size(), QSize(0, 0)); +} + void tst_QImageReader::setClipRect_data() { QTest::addColumn("fileName"); -- cgit v0.12 From 2de2018a33ea45b32963378bb4f7ef24cd181485 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Tue, 9 Jun 2009 12:32:05 +0200 Subject: WinCE doesn't have time() function, use QTime --- examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp index d360de9..2368608 100644 --- a/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp +++ b/examples/statemachine/tankgameplugins/random_ai/random_ai_plugin.cpp @@ -42,13 +42,12 @@ #include "random_ai_plugin.h" #include +#include #include -#include - QState *RandomAiPlugin::create(QState *parentState, QObject *tank) { - qsrand(uint(time(NULL))); + qsrand(QTime(0,0,0).secsTo(QTime::currentTime())); QState *topLevel = new QState(parentState); -- cgit v0.12 From d6f171c9baa61858aea0db36fd8b1bd3219ffd0b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 5 Jun 2009 11:47:32 +0200 Subject: Improved clipping in GL2 paint engine. Use the stencil method to draw clip paths and regions to the Z-buffer instead of using glClear / glScissor. Using different depth values for the various clip parts also makes restore() very cheap when only IntersectClip is used. As an additional bonus this patch gives antialiased clip in the GL 2 paint engine. Task-number: 254658 Reviewed-by: Trond --- src/gui/painting/qpaintengineex.cpp | 80 ++++- src/gui/painting/qpaintengineex_p.h | 32 +- src/gui/painting/qpainter.h | 1 + .../gl2paintengineex/qglengineshadermanager.cpp | 3 +- .../gl2paintengineex/qglengineshadersource_p.h | 14 + .../gl2paintengineex/qpaintengineex_opengl2.cpp | 374 ++++++++++++--------- .../gl2paintengineex/qpaintengineex_opengl2_p.h | 25 +- 7 files changed, 343 insertions(+), 186 deletions(-) diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index 28f9220..3cf5ff9 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -138,6 +138,76 @@ QPaintEngineExPrivate::~QPaintEngineExPrivate() } +void QPaintEngineExPrivate::replayClipOperations() +{ + Q_Q(QPaintEngineEx); + + QPainter *p = q->painter(); + if (!p || !p->d_ptr) + return; + + QPainterPrivate *pp = p->d_ptr; + QList clipInfo = pp->state->clipInfo; + + QTransform transform = q->state()->matrix; + + QTransform redirection; + redirection.translate(-q->state()->redirection_offset.x(), -q->state()->redirection_offset.y()); + + for (int i = 0; i < clipInfo.size(); ++i) { + const QPainterClipInfo &info = clipInfo.at(i); + + QTransform combined = info.matrix * redirection; + + if (combined != q->state()->matrix) { + q->state()->matrix = combined; + q->transformChanged(); + } + + switch (info.clipType) { + case QPainterClipInfo::RegionClip: + q->clip(info.region, info.operation); + break; + case QPainterClipInfo::PathClip: + q->clip(info.path, info.operation); + break; + case QPainterClipInfo::RectClip: + q->clip(info.rect, info.operation); + break; + case QPainterClipInfo::RectFClip: { + qreal right = info.rectf.x() + info.rectf.width(); + qreal bottom = info.rectf.y() + info.rectf.height(); + qreal pts[] = { info.rectf.x(), info.rectf.y(), + right, info.rectf.y(), + right, bottom, + info.rectf.x(), bottom }; + QVectorPath vp(pts, 4, 0, QVectorPath::RectangleHint); + q->clip(vp, info.operation); + break; + } + } + } + + if (transform != q->state()->matrix) { + q->state()->matrix = transform; + q->transformChanged(); + } +} + + +bool QPaintEngineExPrivate::hasClipOperations() const +{ + Q_Q(const QPaintEngineEx); + + QPainter *p = q->painter(); + if (!p || !p->d_ptr) + return false; + + QPainterPrivate *pp = p->d_ptr; + QList clipInfo = pp->state->clipInfo; + + return !clipInfo.isEmpty(); +} /******************************************************************************* * @@ -244,13 +314,18 @@ static void qpaintengineex_cubicTo(qreal c1x, qreal c1y, qreal c2x, qreal c2y, q ((StrokeHandler *) data)->types.add(QPainterPath::CurveToDataElement); } +QPaintEngineEx::QPaintEngineEx() + : QPaintEngine(*new QPaintEngineExPrivate, AllFeatures) +{ + extended = true; +} + QPaintEngineEx::QPaintEngineEx(QPaintEngineExPrivate &data) : QPaintEngine(data, AllFeatures) { extended = true; } - QPainterState *QPaintEngineEx::createState(QPainterState *orig) const { if (!orig) @@ -483,6 +558,9 @@ void QPaintEngineEx::clip(const QRect &r, Qt::ClipOperation op) void QPaintEngineEx::clip(const QRegion ®ion, Qt::ClipOperation op) { + if (region.numRects() == 1) + clip(region.boundingRect(), op); + QVector rects = region.rects(); if (rects.size() <= 32) { qreal pts[2*32*4]; diff --git a/src/gui/painting/qpaintengineex_p.h b/src/gui/painting/qpaintengineex_p.h index 1c55242..3f64260 100644 --- a/src/gui/painting/qpaintengineex_p.h +++ b/src/gui/painting/qpaintengineex_p.h @@ -139,27 +139,13 @@ public: QDebug Q_GUI_EXPORT &operator<<(QDebug &, const QVectorPath &path); #endif -class Q_GUI_EXPORT QPaintEngineExPrivate : public QPaintEnginePrivate -{ -public: - QPaintEngineExPrivate(); - ~QPaintEngineExPrivate(); - - QStroker stroker; - QDashStroker dasher; - StrokeHandler *strokeHandler; - QStrokerOps *activeStroker; - QPen strokerPen; -}; - class QPixmapFilter; class Q_GUI_EXPORT QPaintEngineEx : public QPaintEngine { Q_DECLARE_PRIVATE(QPaintEngineEx) public: - inline QPaintEngineEx() - : QPaintEngine(*new QPaintEngineExPrivate, AllFeatures) { extended = true; } + QPaintEngineEx(); virtual QPainterState *createState(QPainterState *orig) const; @@ -224,6 +210,22 @@ protected: QPaintEngineEx(QPaintEngineExPrivate &data); }; +class Q_GUI_EXPORT QPaintEngineExPrivate : public QPaintEnginePrivate +{ + Q_DECLARE_PUBLIC(QPaintEngineEx) +public: + QPaintEngineExPrivate(); + ~QPaintEngineExPrivate(); + + void replayClipOperations(); + bool hasClipOperations() const; + + QStroker stroker; + QDashStroker dasher; + StrokeHandler *strokeHandler; + QStrokerOps *activeStroker; + QPen strokerPen; +}; inline uint QVectorPath::polygonFlags(QPaintEngine::PolygonDrawMode mode) { switch (mode) { diff --git a/src/gui/painting/qpainter.h b/src/gui/painting/qpainter.h index f3df7a3..78cd713 100644 --- a/src/gui/painting/qpainter.h +++ b/src/gui/painting/qpainter.h @@ -507,6 +507,7 @@ private: friend class QFontEngineXLFD; friend class QWSManager; friend class QPaintEngine; + friend class QPaintEngineExPrivate; friend class QOpenGLPaintEngine; friend class QX11PaintEngine; friend class QX11PaintEnginePrivate; diff --git a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp index ea57fdf..5c541d0 100644 --- a/src/opengl/gl2paintengineex/qglengineshadermanager.cpp +++ b/src/opengl/gl2paintengineex/qglengineshadermanager.cpp @@ -157,6 +157,7 @@ QGLEngineShaderManager::QGLEngineShaderManager(QGLContext* context) simpleShaderProg->addShader(compiledShaders[PositionOnlyVertexShader]); simpleShaderProg->addShader(compiledShaders[MainFragmentShader]); simpleShaderProg->addShader(compiledShaders[ShockingPinkSrcFragmentShader]); + simpleShaderProg->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR); simpleShaderProg->link(); if (!simpleShaderProg->isLinked()) { qCritical() << "Errors linking simple shader:" @@ -444,7 +445,7 @@ bool QGLEngineShaderManager::useCorrectShaderProg() requiredProgram.program->addShader(requiredProgram.compositionFragShader); // We have to bind the vertex attribute names before the program is linked: - requiredProgram.program->bindAttributeLocation("inputVertex", QT_VERTEX_COORDS_ATTR); + requiredProgram.program->bindAttributeLocation("vertexCoordsArray", QT_VERTEX_COORDS_ATTR); if (useTextureCoords) requiredProgram.program->bindAttributeLocation("textureCoordArray", QT_TEXTURE_COORDS_ATTR); diff --git a/src/opengl/gl2paintengineex/qglengineshadersource_p.h b/src/opengl/gl2paintengineex/qglengineshadersource_p.h index 920d0bc..70cc67e 100644 --- a/src/opengl/gl2paintengineex/qglengineshadersource_p.h +++ b/src/opengl/gl2paintengineex/qglengineshadersource_p.h @@ -84,16 +84,20 @@ static const char* const qglslMainWithTexCoordsVertexShader = "\ static const char* const qglslPositionOnlyVertexShader = "\ attribute highp vec4 vertexCoordsArray;\ uniform highp mat4 pmvMatrix;\ + uniform highp float depth;\ void setPosition(void)\ {\ gl_Position = pmvMatrix * vertexCoordsArray;\ + gl_Position.z = depth;\ }"; static const char* const qglslUntransformedPositionVertexShader = "\ attribute highp vec4 vertexCoordsArray;\ + uniform highp float depth;\ void setPosition(void)\ {\ gl_Position = vertexCoordsArray;\ + gl_Position.z = depth;\ }"; // Pattern Brush - This assumes the texture size is 8x8 and thus, the inverted size is 0.125 @@ -104,9 +108,11 @@ static const char* const qglslPositionWithPatternBrushVertexShader = "\ uniform mediump vec2 invertedTextureSize; \ uniform mediump mat3 brushTransform; \ varying mediump vec2 patternTexCoords; \ + uniform highp float depth;\ void setPosition(void) { \ gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ + gl_Position.z = depth;\ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ @@ -136,9 +142,11 @@ static const char* const qglslPositionWithLinearGradientBrushVertexShader = "\ uniform highp vec3 linearData; \ uniform highp mat3 brushTransform; \ varying mediump float index ; \ + uniform highp float depth;\ void setPosition() { \ gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ + gl_Position.z = depth;\ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ @@ -166,10 +174,12 @@ static const char* const qglslPositionWithConicalGradientBrushVertexShader = "\ uniform mediump vec2 halfViewportSize; \ uniform highp mat3 brushTransform; \ varying highp vec2 A; \ + uniform highp float depth;\ void setPosition(void)\ {\ gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ + gl_Position.z = depth; \ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ @@ -205,10 +215,12 @@ static const char* const qglslPositionWithRadialGradientBrushVertexShader = "\ uniform highp vec2 fmp; \ varying highp float b; \ varying highp vec2 A; \ + uniform highp float depth;\ void setPosition(void) \ {\ gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ + gl_Position.z = depth; \ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ @@ -242,9 +254,11 @@ static const char* const qglslPositionWithTextureBrushVertexShader = "\ uniform mediump vec2 invertedTextureSize; \ uniform mediump mat3 brushTransform; \ varying mediump vec2 brushTextureCoords; \ + uniform highp float depth;\ void setPosition(void) { \ gl_Position = pmvMatrix * vertexCoordsArray;\ gl_Position.xy = gl_Position.xy / gl_Position.w; \ + gl_Position.z = depth; \ mediump vec2 viewportCoords = (gl_Position.xy + 1.0) * halfViewportSize; \ mediump vec3 hTexCoords = brushTransform * vec3(viewportCoords, 1); \ mediump float invertedHTexCoordsZ = 1.0 / hTexCoords.z; \ diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index 868adcf..fae3045 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -183,8 +183,8 @@ void QGLTextureGlyphCache::resizeTextureData(int width, int height) pex->transferMode(BrushDrawingMode); - glDisable(GL_SCISSOR_TEST); glDisable(GL_DEPTH_TEST); + glDisable(GL_SCISSOR_TEST); glViewport(0, 0, oldWidth, oldHeight); @@ -217,7 +217,7 @@ void QGLTextureGlyphCache::resizeTextureData(int width, int height) glBindFramebuffer(GL_FRAMEBUFFER_EXT, ctx->d_ptr->current_fbo); glViewport(0, 0, pex->width, pex->height); - pex->updateDepthClip(); + pex->updateDepthScissorTest(); } void QGLTextureGlyphCache::fillTexture(const Coord &c, glyph_t glyph) @@ -297,6 +297,11 @@ void QGL2PaintEngineExPrivate::useSimpleShader() shaderManager->simpleProgram()->setUniformValue("pmvMatrix", pmvMatrix); simpleShaderMatrixUniformDirty = false; } + + if (simpleShaderDepthUniformDirty) { + shaderManager->simpleProgram()->setUniformValue("depth", (GLfloat)q->state()->currentDepth); + simpleShaderDepthUniformDirty = false; + } } @@ -709,6 +714,7 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) if (path.shape() == QVectorPath::RectangleHint) { QGLRect rect(points[0].x(), points[0].y(), points[2].x(), points[2].y()); prepareForDraw(currentBrush->isOpaque()); + composite(rect); } else if (path.shape() == QVectorPath::EllipseHint) { @@ -739,13 +745,13 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(QGL2PEXVertexArray& vertexArray, bool useWindingFill) { // qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()"); - if (stencilBuferDirty) { + if (stencilBufferDirty) { // Clear the stencil buffer to zeros glDisable(GL_STENCIL_TEST); glStencilMask(0xFFFF); // Enable writing to stencil buffer, otherwise glClear wont do anything. glClearStencil(0); // Clear to zero glClear(GL_STENCIL_BUFFER_BIT); - stencilBuferDirty = false; + stencilBufferDirty = false; } glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes @@ -843,6 +849,7 @@ void QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque) // The shader program has changed so mark all uniforms as dirty: brushUniformsDirty = true; shaderMatrixUniformDirty = true; + depthUniformDirty = true; } if (brushUniformsDirty && mode != ImageDrawingMode) @@ -853,6 +860,11 @@ void QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque) shaderMatrixUniformDirty = false; } + if (depthUniformDirty) { + shaderManager->currentProgram()->setUniformValue("depth", (GLfloat)q->state()->currentDepth); + depthUniformDirty = false; + } + if (useGlobalOpacityUniform) shaderManager->currentProgram()->setUniformValue("globalOpacity", (GLfloat)q->state()->opacity); } @@ -1062,7 +1074,6 @@ void QGL2PaintEngineExPrivate::drawCachedGlyphs(const QPointF &p, const QTextIte matrix.translate(p.x(), p.y()); ti.fontEngine->getGlyphPositions(ti.glyphs, matrix, ti.flags, glyphs, positions); - QFontEngineGlyphCache::Type glyphType = ti.fontEngine->glyphFormat >= 0 ? QFontEngineGlyphCache::Type(ti.fontEngine->glyphFormat) : QFontEngineGlyphCache::Raster_A8; @@ -1146,6 +1157,7 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) } d->ctx->d_ptr->active_engine = this; + d->last_created_state = 0; d->drawable.makeCurrent(); QSize sz = d->drawable.size(); @@ -1172,12 +1184,16 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) d->brushUniformsDirty = true; d->matrixDirty = true; d->compositionModeDirty = true; - d->stencilBuferDirty = true; + d->stencilBufferDirty = true; + d->simpleShaderDepthUniformDirty = true; + d->depthUniformDirty = true; d->use_system_clip = !systemClip().isEmpty(); glDisable(GL_DEPTH_TEST); glDisable(GL_SCISSOR_TEST); + glDepthFunc(GL_LEQUAL); + glDepthMask(false); QGLPixmapData *source = d->drawable.copyOnBegin(); if (d->drawable.context()->d_func()->clear_on_painter_begin && d->drawable.autoFillBackground()) { @@ -1201,7 +1217,7 @@ bool QGL2PaintEngineEx::begin(QPaintDevice *pdev) d->drawTexture(QRectF(rect), QRectF(rect), rect.size(), true); } - updateClipRegion(QRegion(), Qt::NoClip); + d->systemStateChanged(); return true; } @@ -1245,260 +1261,296 @@ void QGL2PaintEngineEx::ensureActive() ctx->d_ptr->active_engine = this; glDisable(GL_DEPTH_TEST); - glDisable(GL_SCISSOR_TEST); glViewport(0, 0, d->width, d->height); + setState(state()); - d->updateDepthClip(); } } +void QGL2PaintEngineExPrivate::updateDepthScissorTest() +{ + Q_Q(QGL2PaintEngineEx); + if (q->state()->depthTestEnabled) + glEnable(GL_DEPTH_TEST); + else + glDisable(GL_DEPTH_TEST); -/////////////////////////////////// State/Clipping stolen from QOpenGLPaintEngine ////////////////////////////////////////// + if (q->state()->scissorTestEnabled) + glEnable(GL_SCISSOR_TEST); + else + glDisable(GL_SCISSOR_TEST); +} void QGL2PaintEngineEx::clipEnabledChanged() { Q_D(QGL2PaintEngineEx); - d->updateDepthClip(); + d->simpleShaderDepthUniformDirty = true; + d->depthUniformDirty = true; + + if (painter()->hasClipping()) { + d->regenerateDepthClip(); + } else { + if (d->use_system_clip) { + state()->currentDepth = -0.5f; + } else { + glDisable(GL_DEPTH_TEST); + state()->depthTestEnabled = false; + } + } } -void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op) +void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, float depth) { -// qDebug("QGL2PaintEngineEx::clip()"); - const qreal *points = path.points(); - const QPainterPath::ElementType *types = path.elements(); - if (!types && path.shape() == QVectorPath::RectangleHint) { - QRectF r(points[0], points[1], points[4]-points[0], points[5]-points[1]); - updateClipRegion(QRegion(r.toRect()), op); - return; - } + transferMode(BrushDrawingMode); - QPainterPath p; - if (types) { - int id = 0; - for (int i=0; istate()->needsDepthBufferClear) { + glDepthMask(true); + glClearDepth(0.5); + glClear(GL_DEPTH_BUFFER_BIT); + q->state()->needsDepthBufferClear = false; + glDepthMask(false); } - if (path.hints() & QVectorPath::WindingFill) - p.setFillRule(Qt::WindingFill); - updateClipRegion(QRegion(p.toFillPolygon().toPolygon(), p.fillRule()), op); - return; + if (path.isEmpty()) + return; + + glDisable(GL_BLEND); + glDepthMask(false); + + vertexCoordinateArray.clear(); + vertexCoordinateArray.addPath(path, inverseScale); + + glDepthMask(GL_FALSE); + fillStencilWithVertexArray(vertexCoordinateArray, path.hasWindingFill()); + + // Stencil the clip onto the clip buffer + glColorMask(false, false, false, false); + glDepthMask(true); + + shaderManager->simpleProgram()->setUniformValue("depth", depth); + simpleShaderDepthUniformDirty = true; + + glEnable(GL_DEPTH_TEST); + glDepthFunc(GL_ALWAYS); + + glStencilFunc(GL_NOTEQUAL, 0, 0xFFFF); // Pass if stencil buff value != 0 + + glEnable(GL_STENCIL_TEST); + composite(vertexCoordinateArray.boundingRect()); + glDisable(GL_STENCIL_TEST); + + glColorMask(true, true, true, true); + glDepthMask(false); + + cleanStencilBuffer(vertexCoordinateArray.boundingRect()); } -void QGL2PaintEngineEx::updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op) +void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op) { -// qDebug("QGL2PaintEngineEx::updateClipRegion()"); +// qDebug("QGL2PaintEngineEx::clip()"); Q_D(QGL2PaintEngineEx); - QRegion sysClip = systemClip(); - if (op == Qt::NoClip && !d->use_system_clip) { - state()->hasClipping = false; - state()->clipRegion = QRegion(); - d->updateDepthClip(); - return; - } + if (op == Qt::ReplaceClip && !d->hasClipOperations()) + op = Qt::IntersectClip; - bool isScreenClip = false; - if (!d->use_system_clip) { - QVector untransformedRects = clipRegion.rects(); + if (!path.isEmpty() && op == Qt::IntersectClip && (path.hints() & QVectorPath::RectangleHint)) { + const QPointF* const points = reinterpret_cast(path.points()); + QRectF rect(points[0], points[2]); - if (untransformedRects.size() == 1) { - QPainterPath path; - path.addRect(untransformedRects[0]); - //path = d->matrix.map(path); - path = state()->matrix.map(path); - -// if (path.contains(QRectF(QPointF(), d->drawable.size()))) -// isScreenClip = true; - if (path.contains(QRectF(0.0, 0.0, d->width, d->height))) - isScreenClip = true; + if (state()->matrix.type() <= QTransform::TxScale) { + rect = state()->matrix.mapRect(rect); + + if (d->use_system_clip && rect.contains(d->systemClip.boundingRect()) + || rect.contains(QRect(0, 0, d->width, d->height))) + return; } } -// QRegion region = isScreenClip ? QRegion() : clipRegion * d->matrix; - QRegion region = isScreenClip ? QRegion() : clipRegion * state()->matrix; switch (op) { case Qt::NoClip: - if (!d->use_system_clip) - break; - state()->clipRegion = sysClip; + if (d->use_system_clip) { + glEnable(GL_DEPTH_TEST); + state()->depthTestEnabled = true; + state()->currentDepth = -0.5; + } else { + glDisable(GL_DEPTH_TEST); + state()->depthTestEnabled = false; + } + state()->canRestoreClip = false; break; case Qt::IntersectClip: - if (isScreenClip) - return; - if (state()->hasClipping) { - state()->clipRegion &= region; - break; - } - // fall through + state()->maxDepth = (1.0f + state()->maxDepth) * 0.5; + d->writeClip(path, state()->maxDepth); + state()->currentDepth = 1.5 * state()->maxDepth - 0.5f; + state()->depthTestEnabled = true; + break; case Qt::ReplaceClip: - if (d->use_system_clip && !sysClip.isEmpty()) - state()->clipRegion = region & sysClip; - else - state()->clipRegion = region; + d->systemStateChanged(); + state()->maxDepth = 0.5f; + glDepthFunc(GL_ALWAYS); + d->writeClip(path, state()->maxDepth); + state()->currentDepth = 0.25f; + state()->canRestoreClip = false; + state()->depthTestEnabled = true; break; case Qt::UniteClip: - state()->clipRegion |= region; - if (d->use_system_clip && !sysClip.isEmpty()) - state()->clipRegion &= sysClip; - break; - default: + glDepthFunc(GL_ALWAYS); + d->writeClip(path, state()->maxDepth); + state()->canRestoreClip = false; + state()->depthTestEnabled = true; break; } - if (isScreenClip) { - state()->hasClipping = false; - state()->clipRegion = QRegion(); - } else { - state()->hasClipping = op != Qt::NoClip || d->use_system_clip; + glDepthFunc(GL_LEQUAL); + if (state()->depthTestEnabled) { + glEnable(GL_DEPTH_TEST); + d->simpleShaderDepthUniformDirty = true; + d->depthUniformDirty = true; } - - d->updateDepthClip(); } -void QGL2PaintEngineExPrivate::systemStateChanged() +void QGL2PaintEngineExPrivate::regenerateDepthClip() { - Q_Q(QGL2PaintEngineEx); - use_system_clip = !systemClip.isEmpty(); - - if (q->painter()->hasClipping()) - q->updateClipRegion(q->painter()->clipRegion(), Qt::ReplaceClip); - else - q->updateClipRegion(QRegion(), Qt::NoClip); + systemStateChanged(); + replayClipOperations(); } -void QGL2PaintEngineExPrivate::updateDepthClip() +void QGL2PaintEngineExPrivate::systemStateChanged() { -// qDebug("QGL2PaintEngineExPrivate::updateDepthClip()"); - Q_Q(QGL2PaintEngineEx); + use_system_clip = !systemClip.isEmpty(); - q->ensureActive(); glDisable(GL_DEPTH_TEST); + q->state()->depthTestEnabled = false; + q->state()->scissorTestEnabled = false; + q->state()->needsDepthBufferClear = true; + glDisable(GL_SCISSOR_TEST); - if (!q->state()->hasClipping) - return; + q->state()->currentDepth = -0.5f; + q->state()->maxDepth = 0.5f; - const QVector rects = q->state()->clipEnabled ? q->state()->clipRegion.rects() : q->systemClip().rects(); - if (rects.size() == 1) { - QRect fastClip = rects.at(0); + if (use_system_clip) { + QRect bounds = systemClip.boundingRect(); + if (systemClip.numRects() == 1 + && bounds == QRect(0, 0, width, height)) + { + q->state()->needsDepthBufferClear = true; + } else { + glEnable(GL_SCISSOR_TEST); - glEnable(GL_SCISSOR_TEST); + const int left = bounds.left(); + const int width = bounds.width(); + const int bottom = height - (bounds.top() + bounds.height()); + const int height = bounds.height(); - const int left = fastClip.left(); - const int width = fastClip.width(); - const int bottom = height - (fastClip.bottom() + 1); - const int height = fastClip.height(); + glScissor(left, bottom, width, height); - glScissor(left, bottom, width, height); - return; - } + QTransform transform = q->state()->matrix; + q->state()->matrix = QTransform(); + q->transformChanged(); - glClearDepth(0x0); - glDepthMask(true); - glClear(GL_DEPTH_BUFFER_BIT); - glClearDepth(0x1); + q->state()->needsDepthBufferClear = false; - glEnable(GL_SCISSOR_TEST); - for (int i = 0; i < rects.size(); ++i) { - QRect rect = rects.at(i); + glDepthMask(true); - const int left = rect.left(); - const int width = rect.width(); - const int bottom = height - (rect.bottom() + 1); - const int height = rect.height(); + glClearDepth(0); + glClear(GL_DEPTH_BUFFER_BIT); - glScissor(left, bottom, width, height); + QPainterPath path; + path.addRegion(systemClip); - glClear(GL_DEPTH_BUFFER_BIT); - } - glDisable(GL_SCISSOR_TEST); + glDepthFunc(GL_ALWAYS); + writeClip(qtVectorPathForPath(path), 0.0f); + glDepthFunc(GL_LEQUAL); - glDepthMask(false); - glDepthFunc(GL_LEQUAL); - glEnable(GL_DEPTH_TEST); -} + glEnable(GL_DEPTH_TEST); + q->state()->depthTestEnabled = true; + q->state()->scissorTestEnabled = true; + q->state()->matrix = transform; + q->transformChanged(); + } + q->state()->currentDepth = -0.5f; + simpleShaderDepthUniformDirty = true; + depthUniformDirty = true; + } +} void QGL2PaintEngineEx::setState(QPainterState *new_state) { -// qDebug("QGL2PaintEngineEx::setState()"); + // qDebug("QGL2PaintEngineEx::setState()"); Q_D(QGL2PaintEngineEx); QOpenGL2PaintEngineState *s = static_cast(new_state); - QOpenGL2PaintEngineState *old_state = state(); - const bool needsDepthClipUpdate = !old_state - || s->clipEnabled != old_state->clipEnabled - || (s->clipEnabled && s->clipRegion != old_state->clipRegion); QPaintEngineEx::setState(s); - if (needsDepthClipUpdate) - d->updateDepthClip(); + if (s == d->last_created_state) { + d->last_created_state = 0; + return; + } d->matrixDirty = true; d->compositionModeDirty = true; d->brushTextureDirty = true; d->brushUniformsDirty = true; + d->simpleShaderDepthUniformDirty = true; + d->depthUniformDirty = true; d->simpleShaderMatrixUniformDirty = true; d->shaderMatrixUniformDirty = true; + + if (old_state && old_state != s && old_state->canRestoreClip) { + d->updateDepthScissorTest(); + glDepthMask(false); + glDepthFunc(GL_LEQUAL); + s->maxDepth = old_state->maxDepth; + } else { + d->regenerateDepthClip(); + } } QPainterState *QGL2PaintEngineEx::createState(QPainterState *orig) const { + Q_D(const QGL2PaintEngineEx); + QOpenGL2PaintEngineState *s; if (!orig) s = new QOpenGL2PaintEngineState(); else s = new QOpenGL2PaintEngineState(*static_cast(orig)); + d->last_created_state = s; return s; } QOpenGL2PaintEngineState::QOpenGL2PaintEngineState(QOpenGL2PaintEngineState &other) : QPainterState(other) { - clipRegion = other.clipRegion; - hasClipping = other.hasClipping; + needsDepthBufferClear = other.needsDepthBufferClear; + depthTestEnabled = other.depthTestEnabled; + scissorTestEnabled = other.scissorTestEnabled; + currentDepth = other.currentDepth; + maxDepth = other.maxDepth; + canRestoreClip = other.canRestoreClip; } QOpenGL2PaintEngineState::QOpenGL2PaintEngineState() { - hasClipping = false; + needsDepthBufferClear = true; + depthTestEnabled = false; + scissorTestEnabled = false; + currentDepth = -0.5f; + maxDepth = 0.5f; + canRestoreClip = true; } QOpenGL2PaintEngineState::~QOpenGL2PaintEngineState() diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index 7213474..2cea8d6 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -77,8 +77,15 @@ public: QOpenGL2PaintEngineState(); ~QOpenGL2PaintEngineState(); - QRegion clipRegion; - bool hasClipping; + bool needsDepthBufferClear; + qreal depthBufferClearValue; + + bool depthTestEnabled; + bool scissorTestEnabled; + qreal currentDepth; + qreal maxDepth; + + bool canRestoreClip; }; @@ -116,7 +123,6 @@ public: Type type() const { return OpenGL; } - // State stuff is just for clipping and ripped off from QGLPaintEngine void setState(QPainterState *s); QPainterState *createState(QPainterState *orig) const; inline QOpenGL2PaintEngineState *state() { @@ -125,7 +131,6 @@ public: inline const QOpenGL2PaintEngineState *state() const { return static_cast(QPaintEngineEx::state()); } - void updateClipRegion(const QRegion &clipRegion, Qt::ClipOperation op); virtual void sync(); private: @@ -180,9 +185,10 @@ public: QGLDrawable drawable; int width, height; QGLContext *ctx; - EngineMode mode; + mutable QOpenGL2PaintEngineState *last_created_state; + // Dirty flags bool matrixDirty; // Implies matrix uniforms are also dirty bool compositionModeDirty; @@ -190,7 +196,9 @@ public: bool brushUniformsDirty; bool simpleShaderMatrixUniformDirty; bool shaderMatrixUniformDirty; - bool stencilBuferDirty; + bool stencilBufferDirty; + bool depthUniformDirty; + bool simpleShaderDepthUniformDirty; const QBrush* currentBrush; // May not be the state's brush! @@ -206,8 +214,9 @@ public: QGLEngineShaderManager* shaderManager; - // Clipping & state stuff stolen from QOpenGLPaintEngine: - void updateDepthClip(); + void writeClip(const QVectorPath &path, float depth); + void updateDepthScissorTest(); + void regenerateDepthClip(); void systemStateChanged(); uint use_system_clip : 1; }; -- cgit v0.12 From 73ea2f5766d2c0925af1bee7037610c2c75e89c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 9 Jun 2009 10:54:42 +0200 Subject: Resolved FBO extensions as well when resolving GL 2 extensions. The new GL 2 text drawing requries the FBO function pointers to be resolved. --- src/opengl/qglextensions.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/opengl/qglextensions.cpp b/src/opengl/qglextensions.cpp index 3c198fb..10ca613 100644 --- a/src/opengl/qglextensions.cpp +++ b/src/opengl/qglextensions.cpp @@ -337,6 +337,9 @@ bool qt_resolve_version_2_0_functions(QGLContext *ctx) if (!qt_resolve_version_1_3_functions(ctx)) gl2supported = false; + if (!qt_resolve_framebufferobject_extensions(ctx)) + gl2supported = false; + if (glStencilOpSeparate) return gl2supported; -- cgit v0.12 From 6495eb4953c5fca93d8cfe91c66b50ce82ce24cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 9 Jun 2009 13:02:47 +0200 Subject: Optimized stencil buffer clearing in GL 2 paint engine. Based on Zack's patch, 17e1bca1ce366395f8331e16aa96b7176ca1abac. Instead of manually clearing the stencil buffer after drawing we simply do the clearing and drawing in one go. Reviewed-by: Trond --- .../gl2paintengineex/qpaintengineex_opengl2.cpp | 50 ++++------------------ .../gl2paintengineex/qpaintengineex_opengl2_p.h | 1 - 2 files changed, 9 insertions(+), 42 deletions(-) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp index fae3045..bdea187 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2.cpp @@ -732,12 +732,14 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) // Stencil the brush onto the dest buffer glStencilFunc(GL_NOTEQUAL, 0, 0xFFFF); // Pass if stencil buff value != 0 + glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); + glEnable(GL_STENCIL_TEST); prepareForDraw(currentBrush->isOpaque()); composite(vertexCoordinateArray.boundingRect()); glDisable(GL_STENCIL_TEST); - cleanStencilBuffer(vertexCoordinateArray.boundingRect()); + glStencilMask(0); } } @@ -745,17 +747,17 @@ void QGL2PaintEngineExPrivate::fill(const QVectorPath& path) void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(QGL2PEXVertexArray& vertexArray, bool useWindingFill) { // qDebug("QGL2PaintEngineExPrivate::fillStencilWithVertexArray()"); + glStencilMask(0xFFFF); // Enable stencil writes + if (stencilBufferDirty) { // Clear the stencil buffer to zeros glDisable(GL_STENCIL_TEST); - glStencilMask(0xFFFF); // Enable writing to stencil buffer, otherwise glClear wont do anything. glClearStencil(0); // Clear to zero glClear(GL_STENCIL_BUFFER_BIT); stencilBufferDirty = false; } glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes - glStencilMask(0xFFFF); // Enable stencil writes glStencilFunc(GL_ALWAYS, 0, 0xFFFF); // Always pass the stencil test // Setup the stencil op: @@ -765,7 +767,7 @@ void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(QGL2PEXVertexArray& ve } else glStencilOp(GL_KEEP, GL_KEEP, GL_INVERT); // Simply invert the stencil bit - // No point in using a fancy gradiant shader for writing into the stencil buffer! + // No point in using a fancy gradient shader for writing into the stencil buffer! useSimpleShader(); glEnable(GL_STENCIL_TEST); // For some reason, this has to happen _after_ the simple shader is use()'d @@ -776,41 +778,6 @@ void QGL2PaintEngineExPrivate::fillStencilWithVertexArray(QGL2PEXVertexArray& ve // Enable color writes & disable stencil writes glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - glStencilMask(0); -} - -void QGL2PaintEngineExPrivate::cleanStencilBuffer(const QGLRect& area) -{ -// qDebug("QGL2PaintEngineExPrivate::cleanStencilBuffer()"); - useSimpleShader(); - - GLfloat rectVerts[] = { - area.left, area.top, - area.left, area.bottom, - area.right, area.bottom, - area.right, area.top - }; - - glEnableVertexAttribArray(QT_VERTEX_COORDS_ATTR); - glVertexAttribPointer(QT_VERTEX_COORDS_ATTR, 2, GL_FLOAT, GL_FALSE, 0, rectVerts); - - glEnable(GL_STENCIL_TEST); - glStencilFunc(GL_ALWAYS, 0, 0xFFFF); // Always pass the stencil test - - glColorMask(GL_FALSE, GL_FALSE, GL_FALSE, GL_FALSE); // Disable color writes - glStencilMask(0xFFFF); // Enable writing to stencil buffer - glStencilOp(GL_ZERO, GL_ZERO, GL_ZERO); // Write 0's to stencil buffer - - glDisable(GL_BLEND); - - glDrawArrays(GL_TRIANGLE_FAN, 0, 4); - - glDisableVertexAttribArray(QT_VERTEX_COORDS_ATTR); - - // Enable color writes & disable stencil writes - glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); - glStencilMask(0); - glDisable(GL_STENCIL_TEST); } void QGL2PaintEngineExPrivate::prepareForDraw(bool srcPixelsAreOpaque) @@ -1339,15 +1306,16 @@ void QGL2PaintEngineExPrivate::writeClip(const QVectorPath &path, float depth) glDepthFunc(GL_ALWAYS); glStencilFunc(GL_NOTEQUAL, 0, 0xFFFF); // Pass if stencil buff value != 0 + glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE); glEnable(GL_STENCIL_TEST); composite(vertexCoordinateArray.boundingRect()); glDisable(GL_STENCIL_TEST); + glStencilMask(0); + glColorMask(true, true, true, true); glDepthMask(false); - - cleanStencilBuffer(vertexCoordinateArray.boundingRect()); } void QGL2PaintEngineEx::clip(const QVectorPath &path, Qt::ClipOperation op) diff --git a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h index 2cea8d6..db39ced 100644 --- a/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h +++ b/src/opengl/gl2paintengineex/qpaintengineex_opengl2_p.h @@ -174,7 +174,6 @@ public: // ^ Composites the bounding rect onto dest buffer void fillStencilWithVertexArray(QGL2PEXVertexArray& vertexArray, bool useWindingFill); // ^ Calls drawVertexArrays to render into stencil buffer - void cleanStencilBuffer(const QGLRect& area); void prepareForDraw(bool srcPixelsAreOpaque); -- cgit v0.12 From 923cadc12b993a0b41200750f151d73662856482 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 9 Jun 2009 13:23:08 +0200 Subject: Prevented pixmap FBOs from growing too big. If we're painting to very wide and then very tall pixmaps we don't want the FBO to grow to max_width * max_height, instead we should recreate the FBO if it grows too large compared to what's being painted. Reviewed-by: Trond --- src/opengl/qpixmapdata_gl.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/opengl/qpixmapdata_gl.cpp b/src/opengl/qpixmapdata_gl.cpp index 8d94c8b..98c406b 100644 --- a/src/opengl/qpixmapdata_gl.cpp +++ b/src/opengl/qpixmapdata_gl.cpp @@ -389,6 +389,11 @@ QPaintEngine* QGLPixmapData::paintEngine() const sz.setWidth(qMax(m_width, qRound(sz.width() * 1.5))); if (sz.height() < m_height) sz.setHeight(qMax(m_height, qRound(sz.height() * 1.5))); + + // wasting too much space? + if (sz.width() * sz.height() > m_width * m_height * 2.5) + sz = QSize(m_width, m_height); + delete textureBufferStack.at(currentTextureBuffer).fbo; textureBufferStack[currentTextureBuffer] = createTextureBuffer(sz, textureBufferStack.at(currentTextureBuffer).engine); -- cgit v0.12 From 7cd3e8233090f2937e38aff846a30635bcd14eb6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Tue, 9 Jun 2009 14:05:03 +0200 Subject: Removed background caching in embeddeddialogs demo. No point in caching a background that is already a pixmap. When maximizing the window this pixmap gets huge, and it doesn't help performance either. Reviewed-by: Trond --- demos/embeddeddialogs/main.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/demos/embeddeddialogs/main.cpp b/demos/embeddeddialogs/main.cpp index cfb31c4..c9b6ee1 100644 --- a/demos/embeddeddialogs/main.cpp +++ b/demos/embeddeddialogs/main.cpp @@ -76,7 +76,6 @@ int main(int argc, char *argv[]) view.scale(0.5, 0.5); view.setRenderHints(view.renderHints() | QPainter::Antialiasing | QPainter::SmoothPixmapTransform); view.setBackgroundBrush(QPixmap(":/No-Ones-Laughing-3.jpg")); - view.setCacheMode(QGraphicsView::CacheBackground); view.setViewportUpdateMode(QGraphicsView::BoundingRectViewportUpdate); view.show(); view.setWindowTitle("Embedded Dialogs Demo"); -- cgit v0.12 From 5039d39f3af42d23bba1f1c0ae10365ebcd82b4a Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 9 Jun 2009 12:17:03 +0200 Subject: small change to reduce static data size --- src/corelib/kernel/qvariant.cpp | 2 +- src/gui/text/qtexthtmlparser.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/corelib/kernel/qvariant.cpp b/src/corelib/kernel/qvariant.cpp index 2ff9818..e6f1c48 100644 --- a/src/corelib/kernel/qvariant.cpp +++ b/src/corelib/kernel/qvariant.cpp @@ -1823,7 +1823,7 @@ QVariant::Type QVariant::nameToType(const char *name) #ifndef QT_NO_DATASTREAM enum { MapFromThreeCount = 35 }; -static const uint map_from_three[MapFromThreeCount] = +static const ushort map_from_three[MapFromThreeCount] = { QVariant::Invalid, QVariant::Map, diff --git a/src/gui/text/qtexthtmlparser.cpp b/src/gui/text/qtexthtmlparser.cpp index ee743dc..76c59c3 100644 --- a/src/gui/text/qtexthtmlparser.cpp +++ b/src/gui/text/qtexthtmlparser.cpp @@ -343,7 +343,7 @@ static QChar resolveEntity(const QString &entity) return e->code; } -static const uint windowsLatin1ExtendedCharacters[0xA0 - 0x80] = { +static const ushort windowsLatin1ExtendedCharacters[0xA0 - 0x80] = { 0x20ac, // 0x80 0x0081, // 0x81 direct mapping 0x201a, // 0x82 -- cgit v0.12 From b9f5e151b3c0bca74136720c5b42c9a93c8f25a8 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 9 Jun 2009 14:04:55 +0200 Subject: small improvement/refactor to cssparser --- src/gui/text/qcssparser.cpp | 42 +----------------------------- src/gui/text/qcssparser_p.h | 1 - tests/auto/qcssparser/tst_cssparser.cpp | 45 +++++++++++++++++++++++++++++++-- 3 files changed, 44 insertions(+), 44 deletions(-) diff --git a/src/gui/text/qcssparser.cpp b/src/gui/text/qcssparser.cpp index 0494b72..a05e5a1 100644 --- a/src/gui/text/qcssparser.cpp +++ b/src/gui/text/qcssparser.cpp @@ -57,46 +57,6 @@ QT_BEGIN_NAMESPACE using namespace QCss; -const char *Scanner::tokenName(QCss::TokenType t) -{ - switch (t) { - case NONE: return "NONE"; - case S: return "S"; - case CDO: return "CDO"; - case CDC: return "CDC"; - case INCLUDES: return "INCLUDES"; - case DASHMATCH: return "DASHMATCH"; - case LBRACE: return "LBRACE"; - case PLUS: return "PLUS"; - case GREATER: return "GREATER"; - case COMMA: return "COMMA"; - case STRING: return "STRING"; - case INVALID: return "INVALID"; - case IDENT: return "IDENT"; - case HASH: return "HASH"; - case ATKEYWORD_SYM: return "ATKEYWORD_SYM"; - case EXCLAMATION_SYM: return "EXCLAMATION_SYM"; - case LENGTH: return "LENGTH"; - case PERCENTAGE: return "PERCENTAGE"; - case NUMBER: return "NUMBER"; - case FUNCTION: return "FUNCTION"; - case COLON: return "COLON"; - case SEMICOLON: return "SEMICOLON"; - case RBRACE: return "RBRACE"; - case SLASH: return "SLASH"; - case MINUS: return "MINUS"; - case DOT: return "DOT"; - case STAR: return "STAR"; - case LBRACKET: return "LBRACKET"; - case RBRACKET: return "RBRACKET"; - case EQUAL: return "EQUAL"; - case LPAREN: return "LPAREN"; - case RPAREN: return "RPAREN"; - case OR: return "OR"; - } - return ""; -} - struct QCssKnownValue { const char *name; @@ -279,7 +239,7 @@ static const QCssKnownValue values[NumKnownValues - 1] = { }; //Map id to strings as they appears in the 'values' array above -static const int indexOfId[NumKnownValues] = { 0, 40, 47, 41, 48, 53, 34, 26, 68, 69, 25, 42, 5, 62, 46, +static const short indexOfId[NumKnownValues] = { 0, 40, 47, 41, 48, 53, 34, 26, 68, 69, 25, 42, 5, 62, 46, 29, 57, 58, 27, 50, 60, 6, 10, 38, 55, 19, 13, 17, 18, 20, 21, 49, 24, 45, 65, 36, 3, 2, 39, 61, 16, 11, 56, 14, 32, 63, 54, 64, 33, 67, 8, 28, 37, 12, 35, 59, 7, 9, 4, 66, 52, 22, 23, 30, 31, 1, 15, 0, 51, 44, 43 }; diff --git a/src/gui/text/qcssparser_p.h b/src/gui/text/qcssparser_p.h index 72bd637..81f306d 100644 --- a/src/gui/text/qcssparser_p.h +++ b/src/gui/text/qcssparser_p.h @@ -731,7 +731,6 @@ class Q_AUTOTEST_EXPORT Scanner public: static QString preprocess(const QString &input, bool *hasEscapeSequences = 0); static void scan(const QString &preprocessedInput, QVector *symbols); - static const char *tokenName(TokenType t); }; class Q_GUI_EXPORT Parser diff --git a/tests/auto/qcssparser/tst_cssparser.cpp b/tests/auto/qcssparser/tst_cssparser.cpp index b41a745..27258b7 100644 --- a/tests/auto/qcssparser/tst_cssparser.cpp +++ b/tests/auto/qcssparser/tst_cssparser.cpp @@ -114,11 +114,52 @@ void tst_CssParser::scanner_data() } } + +static char *tokenName(QCss::TokenType t) +{ + switch (t) { + case QCss::NONE: return "NONE"; + case QCss::S: return "S"; + case QCss::CDO: return "CDO"; + case QCss::CDC: return "CDC"; + case QCss::INCLUDES: return "INCLUDES"; + case QCss::DASHMATCH: return "DASHMATCH"; + case QCss::LBRACE: return "LBRACE"; + case QCss::PLUS: return "PLUS"; + case QCss::GREATER: return "GREATER"; + case QCss::COMMA: return "COMMA"; + case QCss::STRING: return "STRING"; + case QCss::INVALID: return "INVALID"; + case QCss::IDENT: return "IDENT"; + case QCss::HASH: return "HASH"; + case QCss::ATKEYWORD_SYM: return "ATKEYWORD_SYM"; + case QCss::EXCLAMATION_SYM: return "EXCLAMATION_SYM"; + case QCss::LENGTH: return "LENGTH"; + case QCss::PERCENTAGE: return "PERCENTAGE"; + case QCss::NUMBER: return "NUMBER"; + case QCss::FUNCTION: return "FUNCTION"; + case QCss::COLON: return "COLON"; + case QCss::SEMICOLON: return "SEMICOLON"; + case QCss::RBRACE: return "RBRACE"; + case QCss::SLASH: return "SLASH"; + case QCss::MINUS: return "MINUS"; + case QCss::DOT: return "DOT"; + case QCss::STAR: return "STAR"; + case QCss::LBRACKET: return "LBRACKET"; + case QCss::RBRACKET: return "RBRACKET"; + case QCss::EQUAL: return "EQUAL"; + case QCss::LPAREN: return "LPAREN"; + case QCss::RPAREN: return "RPAREN"; + case QCss::OR: return "OR"; + } + return ""; +} + static void debug(const QVector &symbols, int index = -1) { qDebug() << "all symbols:"; for (int i = 0; i < symbols.count(); ++i) - qDebug() << "(" << i << "); Token:" << QCss::Scanner::tokenName(symbols.at(i).token) << "; Lexem:" << symbols.at(i).lexem(); + qDebug() << "(" << i << "); Token:" << tokenName(symbols.at(i).token) << "; Lexem:" << symbols.at(i).lexem(); if (index != -1) qDebug() << "failure at index" << index; } @@ -160,7 +201,7 @@ void tst_CssParser::scanner() QCOMPARE(l.count(), 2); const QString expectedToken = l.at(0); const QString expectedLexem = l.at(1); - QString actualToken = QString::fromLatin1(QCss::Scanner::tokenName(symbols.at(i).token)); + QString actualToken = QString::fromLatin1(tokenName(symbols.at(i).token)); if (actualToken != expectedToken) { debug(symbols, i); QCOMPARE(actualToken, expectedToken); -- cgit v0.12 From d367ee08d1a07f1a30665b77ec11acec96e65a65 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Tue, 9 Jun 2009 15:23:59 +0200 Subject: Doc: Fixed QWebPage::forwardUnsupportedContent documentation and added more information about Web plugins. Reviewed-by: Trust Me --- src/3rdparty/webkit/WebKit/qt/Api/qwebpage.cpp | 8 +++++--- src/3rdparty/webkit/WebKit/qt/Api/qwebsettings.cpp | 22 +++++++++++++++------- src/3rdparty/webkit/WebKit/qt/docs/qtwebkit.qdoc | 3 ++- 3 files changed, 22 insertions(+), 11 deletions(-) diff --git a/src/3rdparty/webkit/WebKit/qt/Api/qwebpage.cpp b/src/3rdparty/webkit/WebKit/qt/Api/qwebpage.cpp index 01b68eb..77add54 100644 --- a/src/3rdparty/webkit/WebKit/qt/Api/qwebpage.cpp +++ b/src/3rdparty/webkit/WebKit/qt/Api/qwebpage.cpp @@ -1986,10 +1986,12 @@ bool QWebPage::isContentEditable() const /*! \property QWebPage::forwardUnsupportedContent - \brief whether QWebPage should forward unsupported content through the - unsupportedContent signal + \brief whether QWebPage should forward unsupported content - If disabled the download of such content is aborted immediately. + If enabled, the unsupportedContent() signal is emitted with a network reply that + can be used to read the content. + + If disabled, the download of such content is aborted immediately. By default unsupported content is not forwarded. */ diff --git a/src/3rdparty/webkit/WebKit/qt/Api/qwebsettings.cpp b/src/3rdparty/webkit/WebKit/qt/Api/qwebsettings.cpp index 1ad23f6..b516263 100644 --- a/src/3rdparty/webkit/WebKit/qt/Api/qwebsettings.cpp +++ b/src/3rdparty/webkit/WebKit/qt/Api/qwebsettings.cpp @@ -213,17 +213,25 @@ QWebSettings *QWebSettings::globalSettings() Each QWebPage object has its own QWebSettings object, which configures the settings for that page. If a setting is not configured, then it is looked up in the global settings object, which can be accessed using - QWebSettings::globalSettings(). + globalSettings(). - QWebSettings allows configuring font properties such as font size and font - family, the location of a custom stylesheet, and generic attributes like java - script, plugins, etc. The \l{QWebSettings::WebAttribute}{WebAttribute} - enum further describes this. + QWebSettings allows configuration of browser properties, such as font sizes and + families, the location of a custom style sheet, and generic attributes like + JavaScript and plugins. Individual attributes are set using the setAttribute() + function. The \l{QWebSettings::WebAttribute}{WebAttribute} enum further describes + each attribute. - QWebSettings also configures global properties such as the web page memory - cache and the web page icon database, local database storage and offline + QWebSettings also configures global properties such as the Web page memory + cache and the Web page icon database, local database storage and offline applications storage. + \section1 Enabling Plugins + + Support for browser plugins can enabled by setting the + \l{QWebSettings::PluginsEnabled}{PluginsEnabled} attribute. For many applications, + this attribute is enabled for all pages by setting it on the + \l{globalSettings()}{global settings object}. + \section1 Web Application Support WebKit provides support for features specified in \l{HTML 5} that improve the diff --git a/src/3rdparty/webkit/WebKit/qt/docs/qtwebkit.qdoc b/src/3rdparty/webkit/WebKit/qt/docs/qtwebkit.qdoc index 06305e0..119c126 100644 --- a/src/3rdparty/webkit/WebKit/qt/docs/qtwebkit.qdoc +++ b/src/3rdparty/webkit/WebKit/qt/docs/qtwebkit.qdoc @@ -96,7 +96,8 @@ Since WebKit supports the Netscape Plugin API, Qt applications can display Web pages that embed common plugins, as long as the user has the appropriate - binary files for those plugins installed. + binary files for those plugins installed and the \l{QWebSettings::PluginsEnabled} + attribute is set for the application. The following locations are searched for plugins: -- cgit v0.12 From 4d7a1cbb060a7fe933f674e1a9ebaa9e81fe2896 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Tue, 9 Jun 2009 15:54:19 +0200 Subject: qdoc: The gray version. --- src/corelib/kernel/qtimer.cpp | 2 +- tools/qdoc3/htmlgenerator.cpp | 2 -- tools/qdoc3/test/classic.css | 49 +++++++++++++++++++++++++++++++++++++------ 3 files changed, 44 insertions(+), 9 deletions(-) diff --git a/src/corelib/kernel/qtimer.cpp b/src/corelib/kernel/qtimer.cpp index 8ca53b9..29bdf7e 100644 --- a/src/corelib/kernel/qtimer.cpp +++ b/src/corelib/kernel/qtimer.cpp @@ -251,7 +251,7 @@ void QTimer::stop() /*! - \reimp + \reimp */ void QTimer::timerEvent(QTimerEvent *e) { diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index 0c21534..fb33de4 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -2349,8 +2349,6 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode, // replace all <@link> tags: "(<@link node=\"([^\"]+)\">).*()" static const QString linkTag("link"); - if (src.contains("setAcceptDrops")) - qDebug() << "SRC:" << src; bool done = false; for (int i = 0, n = src.size(); i < n;) { if (src.at(i) == charLangle && src.at(i + 1).unicode() == '@') { diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index 85bb348..9c59c81 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -14,12 +14,49 @@ H3 { h3.fn,span.fn { - background-color: #e0eff6; + background-color: #eee; border-width: 1px; border-style: solid; - border-color: #3388be #3388be #e9f8ff #3388be; + border-color: #ddd #ddd #ddd #ddd ; font-weight: bold; padding: 6px 0px 6px 10px; + margin: 42px 0px 0px 0px; +} + +hr { + border: 0; + color: #9E9E9E; + background-color: #ccc; + height: 1px; + width: 100%; + text-align: left; + margin: 34px 0px 34px 0px; +} + +table { + border-width: 1px 1px 1px 1px; + border-style: solid; + border-color: #dddddd; + border-collapse: collapse; + background-color: #f0f0f0; + margin-left: 1.5%; + width: 97% +} + +table th { + border-width: 1px 1px 1px 2px; + padding: 4px; + border-style: solid; + border-color: #444; + color:white; + background-color:#444; +} + +p { + margin-left: 1.5%; + margin-top: 8px; + width: 97% + margin-bottom: 8px; } a:link @@ -66,7 +103,7 @@ body table td.memItemLeft { width: 200px; - padding: 1px 0px 0px 8px; + padding: 2px 0px 0px 8px; margin: 4px; border-top-width: 1px; border-right-width: 1px; @@ -76,7 +113,7 @@ table td.memItemLeft { border-right-color: #E0E0E0; border-bottom-color: #E0E0E0; border-left-color: #E0E0E0; - border-top-style: solid; + border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; @@ -85,7 +122,7 @@ table td.memItemLeft { white-space: nowrap } table td.memItemRight { - padding: 1px 8px 0px 8px; + padding: 2px 8px 0px 8px; margin: 4px; border-top-width: 1px; border-right-width: 1px; @@ -95,7 +132,7 @@ table td.memItemRight { border-right-color: #E0E0E0; border-bottom-color: #E0E0E0; border-left-color: #E0E0E0; - border-top-style: solid; + border-top-style: none; border-right-style: none; border-bottom-style: none; border-left-style: none; -- cgit v0.12 From 6185ff436816738e933e3c88d44c45faa7f401f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Tue, 9 Jun 2009 16:13:18 +0200 Subject: Remove duplicated code for removing an item from the scene. Before we had almost two identical functions for removing an item from the scene. There was only minor differences depending on whether the item was removed from QGraphicsScene::removeItem or from the item's destructor. Now we have one function that handles both cases just fine. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 36 +++--- src/gui/graphicsview/qgraphicsitem_p.h | 6 +- src/gui/graphicsview/qgraphicsscene.cpp | 193 +++++++++++++------------------- src/gui/graphicsview/qgraphicsscene.h | 1 - src/gui/graphicsview/qgraphicsscene_p.h | 5 +- 5 files changed, 101 insertions(+), 140 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 5ba87ee..db16213 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -840,11 +840,11 @@ QVariant QGraphicsItemPrivate::inputMethodQueryHelper(Qt::InputMethodQuery query /*! \internal - If \a deleting is true, then this item is being deleted, and \a parent is - null. Make sure not to trigger any pure virtual function calls (e.g., - prepareGeometryChange). + Make sure not to trigger any pure virtual function calls (e.g., + prepareGeometryChange) if the item is in its destructor, i.e. + inDestructor is 1. */ -void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool deleting) +void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent) { Q_Q(QGraphicsItem); if (newParent == q) { @@ -871,7 +871,7 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de // We anticipate geometry changes. If the item is deleted, it will be // removed from the index at a later stage, and the whole scene will be // updated. - if (!deleting) + if (!inDestructor) q_ptr->prepareGeometryChange(); const QVariant thisPointerVariant(qVariantFromValue(q)); @@ -883,7 +883,7 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de // Update toplevelitem list. If this item is being deleted, its parent // will be 0 but we don't want to register/unregister it in the TLI list. - if (scene && !deleting) { + if (scene && !inDestructor) { if (parent && !newParent) { scene->d_func()->registerTopLevelItem(q); } else if (!parent && newParent) { @@ -931,7 +931,7 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent, bool de updateAncestorFlag(QGraphicsItem::ItemClipsChildrenToShape); updateAncestorFlag(QGraphicsItem::ItemIgnoresTransformations); - if (!deleting) { + if (!inDestructor) { // Update item visible / enabled. if (!visible && !explicitlyHidden) setVisibleHelper(true, /* explicit = */ false); @@ -1115,22 +1115,22 @@ QGraphicsItem::QGraphicsItem(QGraphicsItemPrivate &dd, QGraphicsItem *parent, */ QGraphicsItem::~QGraphicsItem() { - if (d_ptr->scene && !d_ptr->parent) - d_ptr->scene->d_func()->unregisterTopLevelItem(this); + d_ptr->inDestructor = 1; + d_ptr->removeExtraItemCache(); clearFocus(); + if (!d_ptr->children.isEmpty()) { + QList oldChildren = d_ptr->children; + qDeleteAll(oldChildren); + Q_ASSERT(d_ptr->children.isEmpty()); + } - d_ptr->removeExtraItemCache(); - QList oldChildren = d_ptr->children; - qDeleteAll(oldChildren); - Q_ASSERT(d_ptr->children.isEmpty()); - - d_ptr->setParentItemHelper(0, /* deleting = */ true); if (d_ptr->scene) - d_ptr->scene->d_func()->_q_removeItemLater(this); + d_ptr->scene->d_func()->removeItemHelper(this); + else + d_ptr->setParentItemHelper(0); delete d_ptr->transformData; - delete d_ptr; qt_dataStore()->data.remove(this); @@ -1272,7 +1272,7 @@ QGraphicsWidget *QGraphicsItem::window() const */ void QGraphicsItem::setParentItem(QGraphicsItem *parent) { - d_ptr->setParentItemHelper(parent, /* deleting = */ false); + d_ptr->setParentItemHelper(parent); } /*! diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index e2a37a1..c502655 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -148,6 +148,7 @@ public: paintedViewBoundingRectsNeedRepaint(0), dirtySceneTransform(1), geometryChanged(0), + inDestructor(0), globalStackingOrder(-1), q_ptr(0) { @@ -183,7 +184,7 @@ public: void resolveDepth(int parentDepth); void addChild(QGraphicsItem *child); void removeChild(QGraphicsItem *child); - void setParentItemHelper(QGraphicsItem *parent, bool deleting); + void setParentItemHelper(QGraphicsItem *parent); void childrenBoundingRectHelper(QTransform *x, QRectF *rect); void initStyleOption(QStyleOptionGraphicsItem *option, const QTransform &worldTransform, const QRegion &exposedRegion, bool allItems = false) const; @@ -403,7 +404,8 @@ public: quint32 paintedViewBoundingRectsNeedRepaint : 1; quint32 dirtySceneTransform : 1; quint32 geometryChanged : 1; - quint32 unused : 16; // feel free to use + quint32 inDestructor : 1; + quint32 unused : 15; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index e43c9cd..b63efd6 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -710,39 +710,65 @@ void QGraphicsScenePrivate::_q_processDirtyItems() \internal Schedules an item for removal. This function leaves some stale indexes - around in the BSP tree; these will be cleaned up the next time someone - triggers purgeRemovedItems(). + around in the BSP tree if called from the item's destructor; these will + be cleaned up the next time someone triggers purgeRemovedItems(). - Note: This function is called from QGraphicsItem's destructor. \a item is + Note: This function might get called from QGraphicsItem's destructor. \a item is being destroyed, so we cannot call any pure virtual functions on it (such as boundingRect()). Also, it is unnecessary to update the item's own state in any way. - - ### Refactoring: This function shares much functionality with removeItem() */ -void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) +void QGraphicsScenePrivate::removeItemHelper(QGraphicsItem *item) { Q_Q(QGraphicsScene); - // Clear focus on the item to remove any reference in the focusWidget - // chain. + // Clear focus on the item to remove any reference in the focusWidget chain. item->clearFocus(); - - int index = item->d_func()->index; - if (index != -1) { - // Important: The index is useless until purgeRemovedItems() is - // called. - indexedItems[index] = (QGraphicsItem *)0; - if (!purgePending) { + markDirty(item, QRectF(), false, false, false, false, /*removingItemFromScene=*/true); + + if (!item->d_ptr->inDestructor) { + // Can potentially call item->boundingRect() (virtual function), that's why + // we only can call this function if the item is not in its destructor. + removeFromIndex(item); + } else if (item->d_ptr->index != -1) { + // Important: The index is useless until purgeRemovedItems() is called. + indexedItems[item->d_ptr->index] = (QGraphicsItem *)0; + if (!purgePending) purgePending = true; - q->update(); - } removedItems << item; } else { // Recently added items are purged immediately. unindexedItems() never // contains stale items. unindexedItems.removeAll(item); - q->update(); + } + + if (!item->d_ptr->inDestructor && item == tabFocusFirst) { + QGraphicsWidget *widget = static_cast(item); + widget->d_func()->fixFocusChainBeforeReparenting(0, 0); + } + + item->d_func()->scene = 0; + + // Remove from parent, or unregister from toplevels. + if (QGraphicsItem *parentItem = item->parentItem()) { + if (parentItem->scene()) { + Q_ASSERT_X(parentItem->scene() == q, "QGraphicsScene::removeItem", + "Parent item's scene is different from this item's scene"); + item->d_ptr->setParentItemHelper(0); + } + } else { + unregisterTopLevelItem(item); + } + + if (!item->d_ptr->inDestructor) { + // Remove from our item lists. + int index = item->d_func()->index; + if (index != -1) { + freeItemIndexes << index; + indexedItems[index] = 0; + } else { + unindexedItems.removeAll(item); + } } // Reset the mouse grabber and focus item data. @@ -776,13 +802,19 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) ++iterator; } - // Reset the mouse grabber + if (!item->d_ptr->inDestructor) { + // Remove all children recursively + for (int i = 0; i < item->d_ptr->children.size(); ++i) + q->removeItem(item->d_ptr->children.at(i)); + } + + // Reset the mouse grabber and focus item data. if (mouseGrabberItems.contains(item)) - ungrabMouse(item, /* item is dying */ true); + ungrabMouse(item, /* item is dying */ item->d_ptr->inDestructor); // Reset the keyboard grabber if (keyboardGrabberItems.contains(item)) - ungrabKeyboard(item, /* item is dying */ true); + ungrabKeyboard(item, /* item is dying */ item->d_ptr->inDestructor); // Reset the last mouse grabber item if (item == lastMouseGrabberItem) @@ -801,8 +833,6 @@ void QGraphicsScenePrivate::_q_removeItemLater(QGraphicsItem *item) */ void QGraphicsScenePrivate::purgeRemovedItems() { - Q_Q(QGraphicsScene); - if (!purgePending && removedItems.isEmpty()) return; @@ -818,9 +848,6 @@ void QGraphicsScenePrivate::purgeRemovedItems() freeItemIndexes << i; } purgePending = false; - - // No locality info for the items; update the whole scene. - q->update(); } /*! @@ -3352,95 +3379,7 @@ void QGraphicsScene::removeItem(QGraphicsItem *item) return; } - // If the item has focus, remove it (and any focusWidget reference). - item->clearFocus(); - - // Clear its background - item->update(); - - // Note: This will access item's sceneBoundingRect(), which (as this is - // C++) is why we cannot call removeItem() from QGraphicsItem's - // destructor. - d->removeFromIndex(item); - - if (item == d->tabFocusFirst) { - QGraphicsWidget *widget = static_cast(item); - widget->d_func()->fixFocusChainBeforeReparenting(0, 0); - } - // Set the item's scene ptr to 0. - item->d_func()->scene = 0; - - // Remove from parent, or unregister from toplevels. - if (QGraphicsItem *parentItem = item->parentItem()) { - if (parentItem->scene()) { - Q_ASSERT_X(parentItem->scene() == this, "QGraphicsScene::removeItem", - "Parent item's scene is different from this item's scene"); - item->setParentItem(0); - } - } else { - d->unregisterTopLevelItem(item); - } - - // Remove from our item lists. - int index = item->d_func()->index; - if (index != -1) { - d->freeItemIndexes << index; - d->indexedItems[index] = 0; - } else { - d->unindexedItems.removeAll(item); - } - - if (item == d->focusItem) - d->focusItem = 0; - if (item == d->lastFocusItem) - d->lastFocusItem = 0; - if (item == d->activeWindow) { - // ### deactivate... - d->activeWindow = 0; - } - - // Disable selectionChanged() for individual items - ++d->selectionChanging; - int oldSelectedItemsSize = d->selectedItems.size(); - - // Update selected & hovered item bookkeeping - d->selectedItems.remove(item); - d->hoverItems.removeAll(item); - d->pendingUpdateItems.removeAll(item); - d->cachedItemsUnderMouse.removeAll(item); - d->unpolishedItems.removeAll(item); - d->resetDirtyItem(item); - - //We remove all references of item from the sceneEventFilter arrays - QMultiMap::iterator iterator = d->sceneEventFilters.begin(); - while (iterator != d->sceneEventFilters.end()) { - if (iterator.value() == item || iterator.key() == item) - iterator = d->sceneEventFilters.erase(iterator); - else - ++iterator; - } - - // Remove all children recursively - foreach (QGraphicsItem *child, item->children()) - removeItem(child); - - // Reset the mouse grabber and focus item data. - if (d->mouseGrabberItems.contains(item)) - d->ungrabMouse(item); - - // Reset the keyboard grabber - if (d->keyboardGrabberItems.contains(item)) - item->ungrabKeyboard(); - - // Reset the last mouse grabber item - if (item == d->lastMouseGrabberItem) - d->lastMouseGrabberItem = 0; - - // Reenable selectionChanged() for individual items - --d->selectionChanging; - - if (!d->selectionChanging && d->selectedItems.size() != oldSelectedItemsSize) - emit selectionChanged(); + d->removeItemHelper(item); // Deliver post-change notification item->itemChange(QGraphicsItem::ItemSceneHasChanged, newSceneVariant); @@ -5272,7 +5211,8 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, bool invalidateChildren, - bool maybeDirtyClipPath, bool force, bool ignoreOpacity) + bool maybeDirtyClipPath, bool force, bool ignoreOpacity, + bool removingItemFromScene) { Q_ASSERT(item); if (updateAll) @@ -5280,7 +5220,8 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b if (item->d_ptr->discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath, /*ignoreVisibleBit=*/force, - /*ignoreDirtyBit=*/false, ignoreOpacity)) { + /*ignoreDirtyBit=*/removingItemFromScene, + /*ignoreOpacity=*/ignoreOpacity)) { return; } @@ -5293,6 +5234,24 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b processDirtyItemsEmitted = true; } + if (removingItemFromScene) { + // Note that this function can be called from the item's destructor, so + // do NOT call any virtual functions on it within this block. + if ((connectedSignals & changedSignalMask) || views.isEmpty()) { + // This block of code is kept for compatibility. Since 4.5, by default + // QGraphicsView does not connect the signal and we use the below + // method of delivering updates. + q_func()->update(); + return; + } + + for (int i = 0; i < views.size(); ++i) { + QGraphicsViewPrivate *viewPrivate = views.at(i)->d_func(); + viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + } + return; + } + item->d_ptr->dirty = 1; if (fullItemUpdate) item->d_ptr->fullUpdatePending = 1; diff --git a/src/gui/graphicsview/qgraphicsscene.h b/src/gui/graphicsview/qgraphicsscene.h index 4c0f2ec..c4c9f9c 100644 --- a/src/gui/graphicsview/qgraphicsscene.h +++ b/src/gui/graphicsview/qgraphicsscene.h @@ -275,7 +275,6 @@ private: Q_DISABLE_COPY(QGraphicsScene) Q_PRIVATE_SLOT(d_func(), void _q_updateIndex()) Q_PRIVATE_SLOT(d_func(), void _q_emitUpdated()) - Q_PRIVATE_SLOT(d_func(), void _q_removeItemLater(QGraphicsItem *item)) Q_PRIVATE_SLOT(d_func(), void _q_updateLater()) Q_PRIVATE_SLOT(d_func(), void _q_polishItems()) Q_PRIVATE_SLOT(d_func(), void _q_updateSortCache()) diff --git a/src/gui/graphicsview/qgraphicsscene_p.h b/src/gui/graphicsview/qgraphicsscene_p.h index 42c4d8c..11e9b64 100644 --- a/src/gui/graphicsview/qgraphicsscene_p.h +++ b/src/gui/graphicsview/qgraphicsscene_p.h @@ -131,7 +131,7 @@ public: bool regenerateIndex; bool purgePending; - void _q_removeItemLater(QGraphicsItem *item); + void removeItemHelper(QGraphicsItem *item); QSet removedItems; void purgeRemovedItems(); @@ -264,7 +264,8 @@ public: QRegion *exposedRegion, QWidget *widget, QList *topLevelItems = 0, qreal parentOpacity = qreal(1.0)); void markDirty(QGraphicsItem *item, const QRectF &rect = QRectF(), bool invalidateChildren = false, - bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false); + bool maybeDirtyClipPath = false, bool force = false, bool ignoreOpacity = false, + bool removingItemFromScene = false); void processDirtyItemsRecursive(QGraphicsItem *item, bool dirtyAncestorContainsChildren = false); inline void resetDirtyItem(QGraphicsItem *item) -- cgit v0.12 From a15cce3256e57464720ea7fe7cf663c973f43c7b Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 9 Jun 2009 16:46:18 +0200 Subject: small changes in private headers --- src/gui/image/qpicture_p.h | 2 +- src/gui/painting/qtextureglyphcache_p.h | 2 +- src/gui/text/qfontengine.cpp | 6 ------ src/gui/text/qfontengine_p.h | 1 - src/gui/text/qfontengineglyphcache_p.h | 4 ++-- 5 files changed, 4 insertions(+), 11 deletions(-) diff --git a/src/gui/image/qpicture_p.h b/src/gui/image/qpicture_p.h index a3fd34f..3e8391f 100644 --- a/src/gui/image/qpicture_p.h +++ b/src/gui/image/qpicture_p.h @@ -69,7 +69,7 @@ class QPaintEngine; extern const char *qt_mfhdr_tag; -class Q_GUI_EXPORT QPicturePrivate +class QPicturePrivate { Q_DECLARE_PUBLIC(QPicture) friend class QPicturePaintEngine; diff --git a/src/gui/painting/qtextureglyphcache_p.h b/src/gui/painting/qtextureglyphcache_p.h index cb5be75..689c091 100644 --- a/src/gui/painting/qtextureglyphcache_p.h +++ b/src/gui/painting/qtextureglyphcache_p.h @@ -121,7 +121,7 @@ protected: }; -class Q_GUI_EXPORT QImageTextureGlyphCache : public QTextureGlyphCache +class QImageTextureGlyphCache : public QTextureGlyphCache { public: QImageTextureGlyphCache(QFontEngineGlyphCache::Type type, const QTransform &matrix) diff --git a/src/gui/text/qfontengine.cpp b/src/gui/text/qfontengine.cpp index 6e8adcf..79e341a 100644 --- a/src/gui/text/qfontengine.cpp +++ b/src/gui/text/qfontengine.cpp @@ -70,12 +70,6 @@ static inline bool qtransform_equals_no_translate(const QTransform &a, const QTr } } - - -QFontEngineGlyphCache::~QFontEngineGlyphCache() -{ -} - // Harfbuzz helper functions static HB_Bool hb_stringToGlyphs(HB_Font font, const HB_UChar16 *string, hb_uint32 length, HB_Glyph *glyphs, hb_uint32 *numGlyphs, HB_Bool rightToLeft) diff --git a/src/gui/text/qfontengine_p.h b/src/gui/text/qfontengine_p.h index 0f8d81c..3ef9d5f 100644 --- a/src/gui/text/qfontengine_p.h +++ b/src/gui/text/qfontengine_p.h @@ -93,7 +93,6 @@ struct QGlyphLayout; class Q_GUI_EXPORT QFontEngine : public QObject { - Q_OBJECT public: enum Type { Box, diff --git a/src/gui/text/qfontengineglyphcache_p.h b/src/gui/text/qfontengineglyphcache_p.h index 8589cc6..ca67e3f 100644 --- a/src/gui/text/qfontengineglyphcache_p.h +++ b/src/gui/text/qfontengineglyphcache_p.h @@ -72,7 +72,7 @@ QT_BEGIN_NAMESPACE -class Q_GUI_EXPORT QFontEngineGlyphCache +class QFontEngineGlyphCache { public: QFontEngineGlyphCache(const QTransform &matrix) : m_transform(matrix) { } @@ -83,7 +83,7 @@ public: Raster_Mono }; - virtual ~QFontEngineGlyphCache(); + virtual ~QFontEngineGlyphCache() { } QTransform m_transform; }; -- cgit v0.12 From df7d44d9e826e608d280270125b2d376c33c66ad Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 9 Jun 2009 17:02:32 +0200 Subject: removed foreach usage from animation API --- src/corelib/animation/qparallelanimationgroup.cpp | 33 +++++++++++++---------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/src/corelib/animation/qparallelanimationgroup.cpp b/src/corelib/animation/qparallelanimationgroup.cpp index c148cb5d..6ec4679 100644 --- a/src/corelib/animation/qparallelanimationgroup.cpp +++ b/src/corelib/animation/qparallelanimationgroup.cpp @@ -135,13 +135,14 @@ void QParallelAnimationGroup::updateCurrentTime(int) // simulate completion of the loop int dura = duration(); if (dura > 0) { - foreach (QAbstractAnimation *animation, d->animations) { - animation->setCurrentTime(dura); // will stop + for (int i = 0; i < d->animations.size(); ++i) { + d->animations.at(i)->setCurrentTime(dura); // will stop } } } else if (d->currentLoop < d->lastLoop) { // simulate completion of the loop seeking backwards - foreach (QAbstractAnimation *animation, d->animations) { + for (int i = 0; i < d->animations.size(); ++i) { + QAbstractAnimation *animation = d->animations.at(i); animation->setCurrentTime(0); animation->stop(); } @@ -154,7 +155,8 @@ void QParallelAnimationGroup::updateCurrentTime(int) __LINE__, d->currentTime, d->currentLoop, d->lastLoop, timeFwd, d->lastCurrentTime, state()); #endif // finally move into the actual time of the current loop - foreach (QAbstractAnimation *animation, d->animations) { + for (int i = 0; i < d->animations.size(); ++i) { + QAbstractAnimation *animation = d->animations.at(i); const int dura = animation->totalDuration(); if (dura == -1 && d->isUncontrolledAnimationFinished(animation)) continue; @@ -200,17 +202,18 @@ void QParallelAnimationGroup::updateState(QAbstractAnimation::State oldState, switch (newState) { case Stopped: - foreach (QAbstractAnimation *animation, d->animations) - animation->stop(); + for (int i = 0; i < d->animations.size(); ++i) + d->animations.at(i)->stop(); d->disconnectUncontrolledAnimations(); break; case Paused: - foreach (QAbstractAnimation *animation, d->animations) - animation->pause(); + for (int i = 0; i < d->animations.size(); ++i) + d->animations.at(i)->pause(); break; case Running: d->connectUncontrolledAnimations(); - foreach (QAbstractAnimation *animation, d->animations) { + for (int i = 0; i < d->animations.size(); ++i) { + QAbstractAnimation *animation = d->animations.at(i); animation->stop(); animation->setDirection(d->direction); animation->start(); @@ -243,8 +246,8 @@ void QParallelAnimationGroupPrivate::_q_uncontrolledAnimationFinished() return; int maxDuration = 0; - foreach (QAbstractAnimation *a, animations) - maxDuration = qMax(maxDuration, a->totalDuration()); + for (int i = 0; i < animations.size(); ++i) + maxDuration = qMax(maxDuration, animations.at(i)->totalDuration()); if (currentTime >= maxDuration) q->stop(); @@ -267,7 +270,8 @@ void QParallelAnimationGroupPrivate::connectUncontrolledAnimations() { Q_Q(QParallelAnimationGroup); - foreach (QAbstractAnimation *animation, animations) { + for (int i = 0; i < animations.size(); ++i) { + QAbstractAnimation *animation = animations.at(i); if (animation->duration() == -1 || animation->loopCount() < 0) { uncontrolledFinishTime[animation] = -1; QObject::connect(animation, SIGNAL(finished()), q, SLOT(_q_uncontrolledAnimationFinished())); @@ -288,8 +292,9 @@ void QParallelAnimationGroup::updateDirection(QAbstractAnimation::Direction dire Q_D(QParallelAnimationGroup); //we need to update the direction of the current animation if (state() != Stopped) { - foreach(QAbstractAnimation *anim, d->animations) { - anim->setDirection(direction); + for (int i = 0; i < d->animations.size(); ++i) { + QAbstractAnimation *animation = d->animations.at(i); + animation->setDirection(direction); } } else { if (direction == Forward) { -- cgit v0.12 From 861bf225fedc452ab5b18c12e18e38c4172a5f1a Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Tue, 9 Jun 2009 17:04:33 +0200 Subject: Improves the documentation of QHeaderView::setResizeMode to specify that the section indicated by the parameter logicalIndex should exist Task-number: 255541 --- src/gui/itemviews/qheaderview.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/gui/itemviews/qheaderview.cpp b/src/gui/itemviews/qheaderview.cpp index d28c08a..7ad825a 100644 --- a/src/gui/itemviews/qheaderview.cpp +++ b/src/gui/itemviews/qheaderview.cpp @@ -1153,7 +1153,8 @@ void QHeaderView::setResizeMode(ResizeMode mode) \overload Sets the constraints on how the section specified by \a logicalIndex in - the header can be resized to those described by the given \a mode. + the header can be resized to those described by the given \a mode. The logical + index should exist at the time this function is called. \note This setting will be ignored for the last section if the stretchLastSection property is set to true. This is the default for the horizontal headers provided -- cgit v0.12 From 2312b121131774a84d01854b3e47d3d2a035a6a1 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Thu, 4 Jun 2009 12:10:06 +0200 Subject: Implemented the NET_WM_SYNC protocol on X11. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Done with Thorbjørn Lindeijer Task-number: 220550 Reviewed-by: Thorbjørn Lindeijer Reviewed-by: mae --- src/gui/kernel/qapplication_x11.cpp | 87 ++++++++++++++++++++++++++++++++++++- src/gui/kernel/qt_x11_p.h | 6 +++ src/gui/kernel/qwidget_p.h | 8 ++++ src/gui/kernel/qwidget_x11.cpp | 28 +++++++++++- 4 files changed, 127 insertions(+), 2 deletions(-) diff --git a/src/gui/kernel/qapplication_x11.cpp b/src/gui/kernel/qapplication_x11.cpp index 1473421..8ebea19 100644 --- a/src/gui/kernel/qapplication_x11.cpp +++ b/src/gui/kernel/qapplication_x11.cpp @@ -157,6 +157,8 @@ static const char * x11_atomnames = { "WM_TAKE_FOCUS\0" "_NET_WM_PING\0" "_NET_WM_CONTEXT_HELP\0" + "_NET_WM_SYNC_REQUEST\0" + "_NET_WM_SYNC_REQUEST_COUNTER\0" // ICCCM window state "WM_STATE\0" @@ -508,6 +510,7 @@ static Bool qt_xfixes_scanner(Display*, XEvent *event, XPointer arg) class QETWidget : public QWidget // event translator widget { public: + QWidgetPrivate* d_func() { return QWidget::d_func(); } bool translateMouseEvent(const XEvent *); void translatePaintEvent(const XEvent *); bool translateConfigEvent(const XEvent *); @@ -718,6 +721,44 @@ static int qt_xio_errhandler(Display *) } #endif +#ifndef QT_NO_XSYNC +struct qt_sync_request_event_data +{ + WId window; +}; + +#if defined(Q_C_CALLBACKS) +extern "C" { +#endif + +static Bool qt_sync_request_scanner(Display*, XEvent *event, XPointer arg) +{ + qt_sync_request_event_data *data = + reinterpret_cast(arg); + if (event->type == ClientMessage && + event->xany.window == data->window && + event->xclient.message_type == ATOM(WM_PROTOCOLS) && + (Atom)event->xclient.data.l[0] == ATOM(_NET_WM_SYNC_REQUEST)) { + QWidget *w = QWidget::find(event->xany.window); + if (QTLWExtra *tlw = ((QETWidget*)w)->d_func()->maybeTopData()) { + const ulong timestamp = (const ulong) event->xclient.data.l[1]; + if (timestamp > X11->time) + X11->time = timestamp; + if (timestamp == CurrentTime || timestamp > tlw->syncRequestTimestamp) { + tlw->syncRequestTimestamp = timestamp; + tlw->newCounterValueLo = event->xclient.data.l[2]; + tlw->newCounterValueHi = event->xclient.data.l[3]; + } + } + return true; + } + return false; +} + +#if defined(Q_C_CALLBACKS) +} +#endif +#endif // QT_NO_XSYNC static void qt_x11_create_intern_atoms() { @@ -2090,6 +2131,13 @@ void qt_init(QApplicationPrivate *priv, int, #endif // QT_RUNTIME_XCURSOR #endif // QT_NO_XCURSOR +#ifndef QT_NO_XSYNC + int xsync_evbase, xsync_errbase; + int major, minor; + if (XSyncQueryExtension(X11->display, &xsync_evbase, &xsync_errbase)) + XSyncInitialize(X11->display, &major, &minor); +#endif // QT_NO_XSYNC + #ifndef QT_NO_XINERAMA #ifdef QT_RUNTIME_XINERAMA X11->ptrXineramaQueryExtension = 0; @@ -3116,6 +3164,19 @@ int QApplication::x11ClientMessage(QWidget* w, XEvent* event, bool passive_only) XSendEvent(event->xclient.display, event->xclient.window, False, SubstructureNotifyMask|SubstructureRedirectMask, event); } +#ifndef QT_NO_XSYNC + } else if (a == ATOM(_NET_WM_SYNC_REQUEST)) { + const ulong timestamp = (const ulong) event->xclient.data.l[1]; + if (timestamp > X11->time) + X11->time = timestamp; + if (QTLWExtra *tlw = w->d_func()->maybeTopData()) { + if (timestamp == CurrentTime || timestamp > tlw->syncRequestTimestamp) { + tlw->syncRequestTimestamp = timestamp; + tlw->newCounterValueLo = event->xclient.data.l[2]; + tlw->newCounterValueHi = event->xclient.data.l[3]; + } + } +#endif } } else if (event->xclient.message_type == ATOM(_QT_SCROLL_DONE)) { widget->translateScrollDoneEvent(event); @@ -4144,7 +4205,9 @@ bool QETWidget::translateMouseEvent(const XEvent *event) || ((nextEvent.type == EnterNotify || nextEvent.type == LeaveNotify) && qt_button_down == this) || (nextEvent.type == ClientMessage - && nextEvent.xclient.message_type == ATOM(_QT_SCROLL_DONE))) { + && (nextEvent.xclient.message_type == ATOM(_QT_SCROLL_DONE) || + (nextEvent.xclient.message_type == ATOM(WM_PROTOCOLS) && + (Atom)nextEvent.xclient.data.l[0] == ATOM(_NET_WM_SYNC_REQUEST))))) { qApp->x11ProcessEvent(&nextEvent); continue; } else if (nextEvent.type != MotionNotify || @@ -5200,6 +5263,14 @@ bool QETWidget::translateConfigEvent(const XEvent *event) otherEvent.xconfigure.border_width; } } +#ifndef QT_NO_XSYNC + qt_sync_request_event_data sync_event; + sync_event.window = internalWinId(); + for (XEvent ev;;) { + if (!XCheckIfEvent(X11->display, &ev, &qt_sync_request_scanner, (XPointer)&sync_event)) + break; + } +#endif // QT_NO_XSYNC } QRect cr (geometry()); @@ -5285,6 +5356,20 @@ bool QETWidget::translateConfigEvent(const XEvent *event) if (d->extra && d->extra->topextra) d->extra->topextra->inTopLevelResize = false; } +#ifndef QT_NO_XSYNC + if (QTLWExtra *tlwExtra = d->maybeTopData()) { + if (tlwExtra->newCounterValueLo != 0 || tlwExtra->newCounterValueHi != 0) { + XSyncValue value; + XSyncIntsToValue(&value, + tlwExtra->newCounterValueLo, + tlwExtra->newCounterValueHi); + + XSyncSetCounter(X11->display, tlwExtra->syncUpdateCounter, value); + tlwExtra->newCounterValueHi = 0; + tlwExtra->newCounterValueLo = 0; + } + } +#endif return true; } diff --git a/src/gui/kernel/qt_x11_p.h b/src/gui/kernel/qt_x11_p.h index b9ace9d..21bb550 100644 --- a/src/gui/kernel/qt_x11_p.h +++ b/src/gui/kernel/qt_x11_p.h @@ -154,6 +154,10 @@ extern "C" { # include #endif // QT_NO_XRENDER +#ifndef QT_NO_XSYNC +# include "X11/extensions/sync.h" +#endif + // #define QT_NO_XKB #ifndef QT_NO_XKB # include @@ -514,6 +518,8 @@ struct QX11Data WM_TAKE_FOCUS, _NET_WM_PING, _NET_WM_CONTEXT_HELP, + _NET_WM_SYNC_REQUEST, + _NET_WM_SYNC_REQUEST_COUNTER, // ICCCM window state WM_STATE, diff --git a/src/gui/kernel/qwidget_p.h b/src/gui/kernel/qwidget_p.h index bf4f091..ff194f7 100644 --- a/src/gui/kernel/qwidget_p.h +++ b/src/gui/kernel/qwidget_p.h @@ -131,6 +131,10 @@ struct QTLWExtra { uint embedded : 1; // *************************** Platform specific values (bit fields first) ********** +#ifndef QT_NO_XSYNC + int newCounterValueHi : 32; + uint newCounterValueLo : 32; +#endif #if defined(Q_WS_X11) // <----------------------------------------------------------- X11 uint spont_unmapped: 1; // window was spontaneously unmapped uint dnd : 1; // DND properties installed @@ -156,6 +160,10 @@ struct QTLWExtra { QWSManager *qwsManager; #endif #endif +#ifndef QT_NO_XSYNC + WId syncUpdateCounter; + ulong syncRequestTimestamp; +#endif }; struct QWExtra { diff --git a/src/gui/kernel/qwidget_x11.cpp b/src/gui/kernel/qwidget_x11.cpp index 4e34045..8159f8e 100644 --- a/src/gui/kernel/qwidget_x11.cpp +++ b/src/gui/kernel/qwidget_x11.cpp @@ -754,11 +754,14 @@ void QWidgetPrivate::create_sys(WId window, bool initializeWindow, bool destroyO qBound(1, data.crect.width(), XCOORD_MAX), qBound(1, data.crect.height(), XCOORD_MAX)); XStoreName(dpy, id, appName.data()); - Atom protocols[4]; + Atom protocols[5]; int n = 0; protocols[n++] = ATOM(WM_DELETE_WINDOW); // support del window protocol protocols[n++] = ATOM(WM_TAKE_FOCUS); // support take focus window protocol protocols[n++] = ATOM(_NET_WM_PING); // support _NET_WM_PING protocol +#ifndef QT_NO_XSYNC + protocols[n++] = ATOM(_NET_WM_SYNC_REQUEST); // support _NET_WM_SYNC_REQUEST protocol +#endif // QT_NO_XSYNC if (flags & Qt::WindowContextHelpButtonHint) protocols[n++] = ATOM(_NET_WM_CONTEXT_HELP); XSetWMProtocols(dpy, id, protocols, n); @@ -1877,6 +1880,23 @@ void QWidgetPrivate::show_sys() if (setUserTime) qt_net_update_user_time(q, userTime); +#ifndef QT_NO_XSYNC + if (!topData()->syncUpdateCounter) { + XSyncValue value; + XSyncIntToValue(&value, 0); + topData()->syncUpdateCounter = XSyncCreateCounter(X11->display, value); + + XChangeProperty(X11->display, q->internalWinId(), + ATOM(_NET_WM_SYNC_REQUEST_COUNTER), + XA_CARDINAL, + 32, PropModeReplace, + (uchar *) &topData()->syncUpdateCounter, 1); + + topData()->newCounterValueHi = 0; + topData()->newCounterValueLo = 0; + } +#endif + if (!topData()->embedded && (topData()->validWMState || topData()->waitingForMapNotify) && !q->isMinimized()) { @@ -2687,6 +2707,12 @@ void QWidgetPrivate::createTLSysExtra() extra->topextra->waitingForMapNotify = 0; extra->topextra->parentWinId = 0; extra->topextra->userTimeWindow = 0; +#ifndef QT_NO_XSYNC + extra->topextra->syncUpdateCounter = 0; + extra->topextra->syncRequestTimestamp = 0; + extra->topextra->newCounterValueHi = 0; + extra->topextra->newCounterValueLo = 0; +#endif } void QWidgetPrivate::deleteTLSysExtra() -- cgit v0.12 From 2dc47ad36f235ba053a329179be4ed87d0b4d484 Mon Sep 17 00:00:00 2001 From: Benjamin Poulain Date: Tue, 9 Jun 2009 18:48:16 +0200 Subject: Add support for TIFF formats (Mono and indexed) Add support for reading and writing for Mono, MonoLSB and Indexed images in the tiff format. Previously, the images were always written in RGB32, dismissing the input format. Task-number: 254317 Reviewed-by: Samuel --- src/plugins/imageformats/tiff/qtiffhandler.cpp | 342 +++++++++++++++++++------ tests/auto/qimagewriter/tst_qimagewriter.cpp | 26 ++ 2 files changed, 285 insertions(+), 83 deletions(-) diff --git a/src/plugins/imageformats/tiff/qtiffhandler.cpp b/src/plugins/imageformats/tiff/qtiffhandler.cpp index 77dfeb3..791aeaa 100644 --- a/src/plugins/imageformats/tiff/qtiffhandler.cpp +++ b/src/plugins/imageformats/tiff/qtiffhandler.cpp @@ -131,58 +131,138 @@ bool QTiffHandler::read(QImage *image) if (!canRead()) return false; - TIFF *tiff = TIFFClientOpen("foo", - "r", - this, - qtiffReadProc, - qtiffWriteProc, - qtiffSeekProc, - qtiffCloseProc, - qtiffSizeProc, - qtiffMapProc, - qtiffUnmapProc); - - if (tiff) { - uint32 width = 0; - uint32 height = 0; - TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width); - TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height); - if (image->size() != QSize(width, height) || image->format() != QImage::Format_ARGB32) - *image = QImage(width, height, QImage::Format_ARGB32); + TIFF *const tiff = TIFFClientOpen("foo", + "r", + this, + qtiffReadProc, + qtiffWriteProc, + qtiffSeekProc, + qtiffCloseProc, + qtiffSizeProc, + qtiffMapProc, + qtiffUnmapProc); + + if (!tiff) { + return false; + } + uint32 width; + uint32 height; + uint16 photometric; + if (!TIFFGetField(tiff, TIFFTAG_IMAGEWIDTH, &width) + || !TIFFGetField(tiff, TIFFTAG_IMAGELENGTH, &height) + || !TIFFGetField(tiff, TIFFTAG_PHOTOMETRIC, &photometric)) { + TIFFClose(tiff); + return false; + } + + if (photometric == PHOTOMETRIC_MINISBLACK || photometric == PHOTOMETRIC_MINISWHITE) { + if (image->size() != QSize(width, height) || image->format() != QImage::Format_Mono) + *image = QImage(width, height, QImage::Format_Mono); + QVector colortable(2); + if (photometric == PHOTOMETRIC_MINISBLACK) { + colortable[0] = 0xff000000; + colortable[1] = 0xffffffff; + } else { + colortable[0] = 0xffffffff; + colortable[1] = 0xff000000; + } + image->setColorTable(colortable); + if (!image->isNull()) { - if (TIFFReadRGBAImageOriented(tiff, width, height, reinterpret_cast(image->bits()), ORIENTATION_TOPLEFT, 0)) { - uint16 resUnit = RESUNIT_NONE; - float resX = 0; - float resY = 0; - TIFFGetField(tiff, TIFFTAG_RESOLUTIONUNIT, &resUnit); - TIFFGetField(tiff, TIFFTAG_XRESOLUTION, &resX); - TIFFGetField(tiff, TIFFTAG_YRESOLUTION, &resY); - switch(resUnit) { - case RESUNIT_CENTIMETER: - image->setDotsPerMeterX(qRound(resX * 100)); - image->setDotsPerMeterY(qRound(resY * 100)); - break; - case RESUNIT_INCH: - image->setDotsPerMeterX(qRound(resX * (100 / 2.54))); - image->setDotsPerMeterY(qRound(resY * (100 / 2.54))); - break; - default: - // do nothing as defaults have already - // been set within the QImage class - break; + for (uint32 y=0; yscanLine(y), y, 0) < 0) { + TIFFClose(tiff); + return false; + } + } + } + } else { + uint16 bitPerSample; + if (!TIFFGetField(tiff, TIFFTAG_BITSPERSAMPLE, &bitPerSample)) { + TIFFClose(tiff); + return false; + } + if (photometric == PHOTOMETRIC_PALETTE && bitPerSample == 8) { + if (image->size() != QSize(width, height) || image->format() != QImage::Format_Indexed8) + *image = QImage(width, height, QImage::Format_Indexed8); + if (!image->isNull()) { + // create the color table + const uint16 tableSize = 256; + uint16 *redTable = static_cast(qMalloc(tableSize * sizeof(uint16))); + uint16 *greenTable = static_cast(qMalloc(tableSize * sizeof(uint16))); + uint16 *blueTable = static_cast(qMalloc(tableSize * sizeof(uint16))); + if (!redTable || !greenTable || !blueTable) { + TIFFClose(tiff); + return false; + } + if (!TIFFGetField(tiff, TIFFTAG_COLORMAP, &redTable, &greenTable, &blueTable)) { + TIFFClose(tiff); + return false; + } + + QVector qtColorTable(tableSize); + for (int i = 0; isetColorTable(qtColorTable); + for (uint32 y=0; yscanLine(y), y, 0) < 0) { + TIFFClose(tiff); + return false; + } + } + + // free redTable, greenTable and greenTable done by libtiff + } + } else { + if (image->size() != QSize(width, height) || image->format() != QImage::Format_ARGB32) + *image = QImage(width, height, QImage::Format_ARGB32); + if (!image->isNull()) { + if (TIFFReadRGBAImageOriented(tiff, width, height, reinterpret_cast(image->bits()), ORIENTATION_TOPLEFT, 0)) { + for (uint32 y=0; yscanLine(y), width); + } else { + TIFFClose(tiff); + return false; } - for (uint32 y=0; yscanLine(y), width); - } else { - *image = QImage(); } } - TIFFClose(tiff); } - if (image->isNull()) + if (image->isNull()) { + TIFFClose(tiff); return false; + } + + float resX = 0; + float resY = 0; + uint16 resUnit = RESUNIT_NONE; + if (TIFFGetField(tiff, TIFFTAG_RESOLUTIONUNIT, &resUnit) + && TIFFGetField(tiff, TIFFTAG_XRESOLUTION, &resX) + && TIFFGetField(tiff, TIFFTAG_YRESOLUTION, &resY)) { + + switch(resUnit) { + case RESUNIT_CENTIMETER: + image->setDotsPerMeterX(qRound(resX * 100)); + image->setDotsPerMeterY(qRound(resY * 100)); + break; + case RESUNIT_INCH: + image->setDotsPerMeterX(qRound(resX * (100 / 2.54))); + image->setDotsPerMeterY(qRound(resY * (100 / 2.54))); + break; + default: + // do nothing as defaults have already + // been set within the QImage class + break; + } + } + TIFFClose(tiff); return true; } @@ -191,48 +271,145 @@ bool QTiffHandler::write(const QImage &image) if (!device()->isWritable()) return false; - TIFF *tiff = TIFFClientOpen("foo", - "w", - this, - qtiffReadProc, - qtiffWriteProc, - qtiffSeekProc, - qtiffCloseProc, - qtiffSizeProc, - qtiffMapProc, - qtiffUnmapProc); - - if (tiff) { - int width = image.width(); - int height = image.height(); - int depth = 32; - - if (!TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, width) - || !TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, height) - || !TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB) - || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW) - || !TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, depth/8) - || !TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG) - || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)) { + TIFF *const tiff = TIFFClientOpen("foo", + "w", + this, + qtiffReadProc, + qtiffWriteProc, + qtiffSeekProc, + qtiffCloseProc, + qtiffSizeProc, + qtiffMapProc, + qtiffUnmapProc); + if (!tiff) + return false; + + const int width = image.width(); + const int height = image.height(); + + if (!TIFFSetField(tiff, TIFFTAG_IMAGEWIDTH, width) + || !TIFFSetField(tiff, TIFFTAG_IMAGELENGTH, height) + || !TIFFSetField(tiff, TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG)) { + TIFFClose(tiff); + return false; + } + + // set the resolution + bool resolutionSet = false; + const int dotPerMeterX = image.dotsPerMeterX(); + const int dotPerMeterY = image.dotsPerMeterY(); + if ((dotPerMeterX % 100) == 0 + && (dotPerMeterY % 100) == 0) { + resolutionSet = TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER) + && TIFFSetField(tiff, TIFFTAG_XRESOLUTION, dotPerMeterX/100.0) + && TIFFSetField(tiff, TIFFTAG_YRESOLUTION, dotPerMeterY/100.0); + } else { + resolutionSet = TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH) + && TIFFSetField(tiff, TIFFTAG_XRESOLUTION, static_cast(image.logicalDpiX())) + && TIFFSetField(tiff, TIFFTAG_YRESOLUTION, static_cast(image.logicalDpiY())); + } + if (!resolutionSet) { + TIFFClose(tiff); + return false; + } + + // configure image depth + const QImage::Format format = image.format(); + if (format == QImage::Format_Mono || format == QImage::Format_MonoLSB) { + uint16 photometric = PHOTOMETRIC_MINISBLACK; + if (image.colorTable().at(0) == 0xffffffff) + photometric = PHOTOMETRIC_MINISWHITE; + if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, photometric) + || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_CCITTRLE)) { TIFFClose(tiff); return false; } - // set the resolution - bool resolutionSet = false; - const int dotPerMeterX = image.dotsPerMeterX(); - const int dotPerMeterY = image.dotsPerMeterY(); - if ((dotPerMeterX % 100) == 0 - && (dotPerMeterY % 100) == 0) { - resolutionSet = TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_CENTIMETER) - && TIFFSetField(tiff, TIFFTAG_XRESOLUTION, dotPerMeterX/100.0) - && TIFFSetField(tiff, TIFFTAG_YRESOLUTION, dotPerMeterY/100.0); - } else { - resolutionSet = TIFFSetField(tiff, TIFFTAG_RESOLUTIONUNIT, RESUNIT_INCH) - && TIFFSetField(tiff, TIFFTAG_XRESOLUTION, static_cast(image.logicalDpiX())) - && TIFFSetField(tiff, TIFFTAG_YRESOLUTION, static_cast(image.logicalDpiY())); + // try to do the conversion in chunks no greater than 16 MB + int chunks = (width * height / (1024 * 1024 * 16)) + 1; + int chunkHeight = qMax(height / chunks, 1); + + int y = 0; + while (y < height) { + QImage chunk = image.copy(0, y, width, qMin(chunkHeight, height - y)).convertToFormat(QImage::Format_Mono); + + int chunkStart = y; + int chunkEnd = y + chunk.height(); + while (y < chunkEnd) { + if (TIFFWriteScanline(tiff, reinterpret_cast(chunk.scanLine(y - chunkStart)), y) != 1) { + TIFFClose(tiff); + return false; + } + ++y; + } + } + TIFFClose(tiff); + } else if (format == QImage::Format_Indexed8) { + if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_PALETTE) + || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_PACKBITS) + || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)) { + TIFFClose(tiff); + return false; + } + //// write the color table + // allocate the color tables + uint16 *redTable = static_cast(qMalloc(256 * sizeof(uint16))); + uint16 *greenTable = static_cast(qMalloc(256 * sizeof(uint16))); + uint16 *blueTable = static_cast(qMalloc(256 * sizeof(uint16))); + if (!redTable || !greenTable || !blueTable) { + TIFFClose(tiff); + return false; + } + + // set the color table + const QVector colorTable = image.colorTable(); + + const int tableSize = colorTable.size(); + Q_ASSERT(tableSize <= 256); + for (int i = 0; i(chunk.scanLine(y - chunkStart)), y) != 1) { + TIFFClose(tiff); + return false; + } + ++y; + } } - if (!resolutionSet) { + TIFFClose(tiff); + + } else { + if (!TIFFSetField(tiff, TIFFTAG_PHOTOMETRIC, PHOTOMETRIC_RGB) + || !TIFFSetField(tiff, TIFFTAG_COMPRESSION, compression == NoCompression ? COMPRESSION_NONE : COMPRESSION_LZW) + || !TIFFSetField(tiff, TIFFTAG_SAMPLESPERPIXEL, 4) + || !TIFFSetField(tiff, TIFFTAG_BITSPERSAMPLE, 8)) { TIFFClose(tiff); return false; } @@ -260,9 +437,8 @@ bool QTiffHandler::write(const QImage &image) } } TIFFClose(tiff); - } else { - return false; } + return true; } diff --git a/tests/auto/qimagewriter/tst_qimagewriter.cpp b/tests/auto/qimagewriter/tst_qimagewriter.cpp index 349afa5..3ceb2c2 100644 --- a/tests/auto/qimagewriter/tst_qimagewriter.cpp +++ b/tests/auto/qimagewriter/tst_qimagewriter.cpp @@ -59,6 +59,7 @@ Q_DECLARE_METATYPE(QStringMap) Q_DECLARE_METATYPE(QIntList) Q_DECLARE_METATYPE(QImageWriter::ImageWriterError) Q_DECLARE_METATYPE(QIODevice *) +Q_DECLARE_METATYPE(QImage::Format) //TESTED_FILES= @@ -82,6 +83,9 @@ private slots: void writeImage2(); void supportedFormats(); + void readWriteNonDestructive_data(); + void readWriteNonDestructive(); + #if defined QTEST_HAVE_TIFF void largeTiff(); #endif @@ -376,6 +380,28 @@ void tst_QImageWriter::supportedFormats() QCOMPARE(formatSet.size(), formats.size()); } +void tst_QImageWriter::readWriteNonDestructive_data() +{ + QTest::addColumn("format"); + QTest::addColumn("expectedFormat"); + QTest::newRow("tiff mono") << QImage::Format_Mono << QImage::Format_Mono; + QTest::newRow("tiff indexed") << QImage::Format_Indexed8 << QImage::Format_Indexed8; + QTest::newRow("tiff rgb32") << QImage::Format_ARGB32 << QImage::Format_ARGB32; +} + +void tst_QImageWriter::readWriteNonDestructive() +{ + QFETCH(QImage::Format, format); + QFETCH(QImage::Format, expectedFormat); + QImage image = QImage(prefix + "colorful.bmp").convertToFormat(format); + QVERIFY(image.save(prefix + "gen-readWriteNonDestructive.tiff")); + + QImage image2 = QImage(prefix + "gen-readWriteNonDestructive.tiff"); + QImage::Format readFormat = image2.format(); + QCOMPARE(readFormat, expectedFormat); + QCOMPARE(image, image2); +} + void tst_QImageWriter::setDescription_data() { QTest::addColumn("fileName"); -- cgit v0.12 From 2af18f51f216d5c624ce28b3fa966a17050d882b Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Tue, 9 Jun 2009 17:45:04 +0200 Subject: Fix sorting bug when using BSP tree index + add autotest. We use stable sorting to keep insertion order. This works fine as long as we sort a complete list of siblings in one go, and this list already has items in insertion order. But if we shuffle such a list, the only way to get proper sort order again (with insertion order intact), is if each item has a sibling index. We used to have this, but we don't have it anymore (as it's not needed for NoIndex mode). So until we separate the BSP index into a separate class and add this index there, we add this workaround which uses the toplevelitems list to ensure the items have the correct order. Reviewed-by: bnilsen --- src/gui/graphicsview/qgraphicsitem.cpp | 8 +--- src/gui/graphicsview/qgraphicsscene.cpp | 46 +++++++++++++++------ tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp | 56 ++++++++++++++++++++++++++ 3 files changed, 92 insertions(+), 18 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index db16213..f50d210 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -6190,10 +6190,8 @@ void QGraphicsItem::addToIndex() // ### add to child index only if applicable return; } - if (d_ptr->scene) { + if (d_ptr->scene) d_ptr->scene->d_func()->addToIndex(this); - d_ptr->scene->d_func()->markDirty(this); - } } /*! @@ -6209,10 +6207,8 @@ void QGraphicsItem::removeFromIndex() // ### remove from child index only if applicable return; } - if (d_ptr->scene) { - d_ptr->scene->d_func()->markDirty(this); + if (d_ptr->scene) d_ptr->scene->d_func()->removeFromIndex(this); - } } /*! diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index b63efd6..e6c3503 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5112,18 +5112,42 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } else if (indexMethod == QGraphicsScene::NoIndex || !exposedRegion) { children = &this->topLevelItems; } else { - tmp = estimateItemsInRect(viewTransform.inverted().mapRect(exposedRegion->boundingRect())); + QRectF sceneRect = viewTransform.inverted().mapRect(QRectF(exposedRegion->boundingRect().adjusted(-1, -1, 1, 1))); + if (!largestUntransformableItem.isEmpty()) { + // ### Nuke this when we move the indexing code into a separate + // class. All the largestUntransformableItem code should then go + // away, and the estimate function should return untransformable + // items as well. + QRectF untr = largestUntransformableItem; + QRectF ltri = viewTransform.inverted().mapRect(untr); + ltri.adjust(-untr.width(), -untr.height(), untr.width(), untr.height()); + sceneRect.adjust(-ltri.width(), -ltri.height(), ltri.width(), ltri.height()); + } + tmp = estimateItemsInRect(sceneRect); QList tli; - for (int i = 0; i < tmp.size(); ++i) { - QGraphicsItem *it = tmp.at(i)->topLevelItem(); - if (!it->d_ptr->itemDiscovered) { - tli << it; - it->d_ptr->itemDiscovered = 1; + for (int i = 0; i < tmp.size(); ++i) + tmp.at(i)->topLevelItem()->d_ptr->itemDiscovered = 1; + + // Sort if the toplevel list is unsorted. + if (needSortTopLevelItems) { + needSortTopLevelItems = false; + qStableSort(this->topLevelItems.begin(), + this->topLevelItems.end(), qt_notclosestLeaf); + } + + for (int i = 0; i < this->topLevelItems.size(); ++i) { + // ### Investigate smarter ways. Looping through all top level + // items is not optimal. If the BSP tree is to have maximum + // effect, it should be possible to sort the subset of items + // quickly. We must use this approach for now, as it's the only + // current way to keep the stable sorting order (insertion order). + QGraphicsItem *item = this->topLevelItems.at(i); + if (item->d_ptr->itemDiscovered) { + item->d_ptr->itemDiscovered = 0; + tli << item; } } - for (int i = 0; i < tli.size(); ++i) - tli.at(i)->d_ptr->itemDiscovered = 0; tmp = tli; children = &tmp; @@ -5147,9 +5171,7 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * if (item && item->d_ptr->needSortChildren) { item->d_ptr->needSortChildren = 0; qStableSort(children->begin(), children->end(), qt_notclosestLeaf); - } else if (!item && children == &tmp) { - qStableSort(children->begin(), children->end(), qt_notclosestLeaf); - } else if (!item && needSortTopLevelItems) { + } else if (!item && needSortTopLevelItems && children != &tmp) { needSortTopLevelItems = false; qStableSort(children->begin(), children->end(), qt_notclosestLeaf); } @@ -5220,7 +5242,7 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b if (item->d_ptr->discardUpdateRequest(/*ignoreClipping=*/maybeDirtyClipPath, /*ignoreVisibleBit=*/force, - /*ignoreDirtyBit=*/removingItemFromScene, + /*ignoreDirtyBit=*/removingItemFromScene || invalidateChildren, /*ignoreOpacity=*/ignoreOpacity)) { return; } diff --git a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp index af34fe5..481dc6b 100644 --- a/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp +++ b/tests/auto/qgraphicsitem/tst_qgraphicsitem.cpp @@ -226,6 +226,8 @@ private slots: void itemUsesExtendedStyleOption(); void itemSendsGeometryChanges(); void moveItem(); + void sorting_data(); + void sorting(); // task specific tests below me void task141694_textItemEnsureVisible(); @@ -6926,5 +6928,59 @@ void tst_QGraphicsItem::moveItem() QCOMPARE(view.paintedRegion, expectedParentRegion); } +void tst_QGraphicsItem::sorting_data() +{ + QTest::addColumn("index"); + + QTest::newRow("NoIndex") << int(QGraphicsScene::NoIndex); + QTest::newRow("BspTreeIndex") << int(QGraphicsScene::BspTreeIndex); +} + +void tst_QGraphicsItem::sorting() +{ + _paintedItems.clear(); + + QGraphicsScene scene; + QGraphicsItem *grid[100][100]; + for (int x = 0; x < 100; ++x) { + for (int y = 0; y < 100; ++y) { + PainterItem *item = new PainterItem; + item->setPos(x * 25, y * 25); + item->setData(0, QString("%1x%2").arg(x).arg(y)); + grid[x][y] = item; + scene.addItem(item); + } + } + + PainterItem *item1 = new PainterItem; + PainterItem *item2 = new PainterItem; + item1->setData(0, "item1"); + item2->setData(0, "item2"); + scene.addItem(item1); + scene.addItem(item2); + + QGraphicsView view(&scene); + view.setResizeAnchor(QGraphicsView::NoAnchor); + view.setTransformationAnchor(QGraphicsView::NoAnchor); + view.resize(100, 100); + view.setFrameStyle(0); + view.show(); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&view); +#endif + QTest::qWait(100); + + _paintedItems.clear(); + + view.viewport()->repaint(); + + QCOMPARE(_paintedItems, QList() + << grid[0][0] << grid[0][1] << grid[0][2] << grid[0][3] + << grid[1][0] << grid[1][1] << grid[1][2] << grid[1][3] + << grid[2][0] << grid[2][1] << grid[2][2] << grid[2][3] + << grid[3][0] << grid[3][1] << grid[3][2] << grid[3][3] + << item1 << item2); +} + QTEST_MAIN(tst_QGraphicsItem) #include "tst_qgraphicsitem.moc" -- cgit v0.12 From 5b24c5793607c809b1bac82c7cc3696001ee9217 Mon Sep 17 00:00:00 2001 From: Prasanth Ullattil Date: Tue, 9 Jun 2009 18:49:40 +0200 Subject: Opening links with cyrillic file names does not work in QLabel. QDestopServices was converting the file names to percentage encoding before calling ShellExecute. This will not work with URLs without a scheme. These are now being treated similar to a file. Task-number: 254501 Reviewed-by: Jens Bache-Wiig --- src/gui/util/qdesktopservices_win.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/gui/util/qdesktopservices_win.cpp b/src/gui/util/qdesktopservices_win.cpp index 9f8efb4..a8aa11c 100644 --- a/src/gui/util/qdesktopservices_win.cpp +++ b/src/gui/util/qdesktopservices_win.cpp @@ -165,6 +165,9 @@ static bool launchWebBrowser(const QUrl &url) if (!url.isValid()) return false; + if (url.scheme().isEmpty()) + return openDocument(url); + quintptr returnValue; returnValue = (quintptr)ShellExecute(0, 0, (TCHAR *) QString::fromUtf8(url.toEncoded().constData()).utf16(), 0, 0, SW_SHOWNORMAL); -- cgit v0.12 From b14a89473a51bee7cc2f313b88a8bc1e87a454d8 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 10 Jun 2009 14:16:19 +1000 Subject: Improve bindings startup performance --- src/declarative/qml/qml.pri | 3 +- src/declarative/qml/qmlbasicscript.cpp | 166 ++++++++++++++++++++++++++++----- src/declarative/qml/qmlbasicscript_p.h | 11 ++- src/declarative/qml/qmlcompiler.cpp | 55 ++++++----- src/declarative/qml/qmlcompiler_p.h | 44 ++++++--- src/declarative/qml/qmlengine.cpp | 28 +----- src/declarative/qml/qmlengine_p.h | 12 +-- src/declarative/qml/qmlexpression.h | 2 +- src/declarative/qml/qmlvme.cpp | 4 +- src/declarative/qml/qpodvector_p.h | 124 ++++++++++++++++++++++++ 10 files changed, 356 insertions(+), 93 deletions(-) create mode 100644 src/declarative/qml/qpodvector_p.h diff --git a/src/declarative/qml/qml.pri b/src/declarative/qml/qml.pri index c61200e..efe4d3f 100644 --- a/src/declarative/qml/qml.pri +++ b/src/declarative/qml/qml.pri @@ -63,7 +63,8 @@ HEADERS += qml/qmlparser_p.h \ qml/qmldeclarativedata_p.h \ qml/qmlerror.h \ qml/qmlscriptparser_p.h \ - qml/qmlbasicscript_p.h + qml/qmlbasicscript_p.h \ + qml/qpodvector_p.h # for qtscript debugger QT += scripttools diff --git a/src/declarative/qml/qmlbasicscript.cpp b/src/declarative/qml/qmlbasicscript.cpp index 7bd898c..d8e65bf 100644 --- a/src/declarative/qml/qmlbasicscript.cpp +++ b/src/declarative/qml/qmlbasicscript.cpp @@ -22,11 +22,19 @@ QT_BEGIN_NAMESPACE +using namespace JavaScript; + struct ScriptInstruction { enum { Load, // fetch Fetch, // fetch + LoadIdObject, // fetch + FetchConstant, // constant + FetchD0Constant, // constant + FetchD1Constant, // constant + + Add, // NA Subtract, // NA Multiply, // NA @@ -47,6 +55,11 @@ struct ScriptInstruction { struct { bool value; } boolean; + struct { + short idx; + short notify; + int type; + } constant; }; }; @@ -249,9 +262,14 @@ struct QmlBasicScriptCompiler { QmlBasicScriptCompiler() : script(0), stateSize(0) {} + QmlBasicScript *script; int stateSize; + QmlParser::Object *context; + QmlParser::Object *component; + QHash > ids; + bool compile(JavaScript::AST::Node *); bool compileExpression(JavaScript::AST::Node *); @@ -259,7 +277,7 @@ struct QmlBasicScriptCompiler bool tryConstant(JavaScript::AST::Node *); bool parseConstant(JavaScript::AST::Node *); bool tryName(JavaScript::AST::Node *); - bool parseName(JavaScript::AST::Node *); + bool parseName(JavaScript::AST::Node *, QmlParser::Object ** = 0); bool tryBinaryExpression(JavaScript::AST::Node *); bool compileBinaryExpression(JavaScript::AST::Node *); @@ -437,19 +455,18 @@ bool QmlBasicScript::isValid() const return d != 0; } -/*! - Compile \a v and return true if the compilation is successful, otherwise - returns false. - */ -bool QmlBasicScript::compile(const QmlParser::Variant &v) +bool QmlBasicScript::compile(const Expression &expression) { - if (!v.asAST()) return false; + if (!expression.expression.asAST()) return false; - QByteArray expr = v.asScript().toLatin1(); + QByteArray expr = expression.expression.asScript().toLatin1(); const char *src = expr.constData(); QmlBasicScriptCompiler bsc; bsc.script = this; + bsc.context = expression.context; + bsc.component = expression.component; + bsc.ids = expression.ids; if (d) { if (flags & QmlBasicScriptPrivate::OwnData) @@ -458,7 +475,7 @@ bool QmlBasicScript::compile(const QmlParser::Variant &v) flags = 0; } - if (bsc.compile(v.asAST())) { + if (bsc.compile(expression.expression.asAST())) { int len = ::strlen(src); flags = QmlBasicScriptPrivate::OwnData; int size = sizeof(QmlBasicScriptPrivate) + @@ -483,7 +500,6 @@ bool QmlBasicScriptCompiler::compile(JavaScript::AST::Node *node) return compileExpression(node); } -using namespace JavaScript; bool QmlBasicScriptCompiler::tryConstant(JavaScript::AST::Node *node) { if (node->kind == AST::Node::Kind_TrueLiteral || @@ -524,10 +540,11 @@ bool QmlBasicScriptCompiler::tryName(JavaScript::AST::Node *node) node->kind == AST::Node::Kind_FieldMemberExpression; } -bool QmlBasicScriptCompiler::parseName(AST::Node *node) +bool QmlBasicScriptCompiler::parseName(AST::Node *node, + QmlParser::Object **type) { bool load = false; - + QmlParser::Object *loadedType = 0; QString name; if (node->kind == AST::Node::Kind_IdentifierExpression) { name = static_cast(node)->name->asString(); @@ -535,7 +552,7 @@ bool QmlBasicScriptCompiler::parseName(AST::Node *node) } else if (node->kind == AST::Node::Kind_FieldMemberExpression) { AST::FieldMemberExpression *expr = static_cast(node); - if (!parseName(expr->base)) + if (!parseName(expr->base, &loadedType)) return false; name = expr->name->asString(); @@ -543,18 +560,72 @@ bool QmlBasicScriptCompiler::parseName(AST::Node *node) return false; } - int nref = data.count(); - data.append(name.toUtf8()); - data.append('\0'); ScriptInstruction instr; - if (load) - instr.type = ScriptInstruction::Load; - else - instr.type = ScriptInstruction::Fetch; - instr.fetch.idx = nref; - bytecode.append(instr); - ++stateSize; + if (load) { + if (ids.contains(name)) { + instr.type = ScriptInstruction::LoadIdObject; + instr.fetch.idx = ids.value(name).second; + + if (type) + *type = ids.value(name).first; + + } else { + int d0Idx = context->metaObject()->indexOfProperty(name.toUtf8().constData()); + int d1Idx = -1; + if (d0Idx == -1) + d1Idx = component->metaObject()->indexOfProperty(name.toUtf8().constData()); + if (d0Idx != -1) { + + instr.type = ScriptInstruction::FetchD0Constant; + instr.constant.idx = d0Idx; + QMetaProperty prop = context->metaObject()->property(d0Idx); + instr.constant.notify = prop.notifySignalIndex(); + instr.constant.type = prop.userType(); + + } else if (d1Idx != -1) { + + instr.type = ScriptInstruction::FetchD1Constant; + instr.constant.idx = d1Idx; + QMetaProperty prop = component->metaObject()->property(d1Idx); + instr.constant.notify = prop.notifySignalIndex(); + instr.constant.type = prop.userType(); + + } else { + + int nref = data.count(); + data.append(name.toUtf8()); + data.append('\0'); + instr.type = ScriptInstruction::Load; + instr.fetch.idx = nref; + ++stateSize; + + } + } + + } else { + + int idx = -1; + if (loadedType) + idx = loadedType->metaObject()->indexOfProperty(name.toUtf8().constData()); + if (idx != -1) { + instr.type = ScriptInstruction::FetchConstant; + instr.constant.idx = idx; + QMetaProperty prop = loadedType->metaObject()->property(idx); + instr.constant.notify = prop.notifySignalIndex(); + instr.constant.type = prop.userType(); + } else { + int nref = data.count(); + data.append(name.toUtf8()); + data.append('\0'); + instr.type = ScriptInstruction::Fetch; + instr.fetch.idx = nref; + ++stateSize; + } + + } + + bytecode.append(instr); return true; } @@ -679,12 +750,16 @@ QVariant QmlBasicScript::run(QmlContext *context, void *voidCache, CacheState *c { if (!isValid()) return QVariant(); + + QmlContextPrivate *contextPrivate = context->d_func(); + QmlEnginePrivate *enginePrivate = context->engine()->d_func(); QmlBasicScriptNodeCache *dataCache = reinterpret_cast(voidCache); int dataCacheItem; - QStack stack; + QStack stack; + bool resetting = false; bool hasReset = false; @@ -702,6 +777,49 @@ QVariant QmlBasicScript::run(QmlContext *context, void *voidCache, CacheState *c const ScriptInstruction &instr = d->instructions()[idx]; switch(instr.type) { + case ScriptInstruction::LoadIdObject: + { + stack.push(contextPrivate->propertyValues.at(instr.fetch.idx)); + enginePrivate->capturedProperties << + QmlEnginePrivate::CapturedProperty(context, contextPrivate->notifyIndex + instr.fetch.idx); + state = Reset; + } + break; + + case ScriptInstruction::FetchD0Constant: + { + QObject *obj = contextPrivate->defaultObjects.at(0); + + stack.push(fetch_value(obj, instr.constant.idx, instr.constant.type)); + enginePrivate->capturedProperties << + QmlEnginePrivate::CapturedProperty(obj, instr.constant.notify); + state = Reset; + } + break; + + case ScriptInstruction::FetchD1Constant: + { + QObject *obj = contextPrivate->defaultObjects.at(1); + + stack.push(fetch_value(obj, instr.constant.idx, instr.constant.type)); + enginePrivate->capturedProperties << + QmlEnginePrivate::CapturedProperty(obj, instr.constant.notify); + state = Reset; + } + break; + + case ScriptInstruction::FetchConstant: + { + QVariant o = stack.pop(); + QObject *obj = qvariant_cast(o); + + stack.push(fetch_value(obj, instr.constant.idx, instr.constant.type)); + enginePrivate->capturedProperties << + QmlEnginePrivate::CapturedProperty(obj, instr.constant.notify); + state = Reset; + } + break; + case ScriptInstruction::Load: // either an object or a property case ScriptInstruction::Fetch: // can only be a property { diff --git a/src/declarative/qml/qmlbasicscript_p.h b/src/declarative/qml/qmlbasicscript_p.h index 1117e11..43c0d36 100644 --- a/src/declarative/qml/qmlbasicscript_p.h +++ b/src/declarative/qml/qmlbasicscript_p.h @@ -38,7 +38,16 @@ public: QByteArray expression() const; - bool compile(const QmlParser::Variant &); + struct Expression + { + QmlParser::Object *component; + QmlParser::Object *context; + QmlParser::Property *property; + QmlParser::Variant expression; + QHash > ids; + }; + + bool compile(const Expression &); bool isValid() const; void clear(); diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index b28d7dd..fe3da57 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -533,6 +533,8 @@ bool QmlCompiler::compile(QmlEngine *engine, void QmlCompiler::compileTree(Object *tree) { + compileState.root = tree; + QmlInstruction init; init.type = QmlInstruction::Init; init.line = 0; @@ -557,7 +559,7 @@ void QmlCompiler::compileTree(Object *tree) finalizeComponent(0); } -bool QmlCompiler::compileObject(Object *obj, int ctxt) +bool QmlCompiler::compileObject(Object *obj, const BindingContext &ctxt) { Q_ASSERT (obj->type != -1); obj->metatype = output->types.at(obj->type).metaObject(); @@ -567,7 +569,7 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) return true; } - ctxt = 0; + BindingContext objCtxt(obj); int createInstrIdx = output->bytecode.count(); // Create the object @@ -617,7 +619,7 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) if (isCustomParser) { // Custom parser types don't support signal properties if (testProperty(prop, obj)) { - COMPILE_CHECK(compileProperty(prop, obj, ctxt)); + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } else { customProps << QmlCustomParserNodePrivate::fromProperty(prop); } @@ -625,7 +627,7 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) if (isSignalPropertyName(prop->name)) { COMPILE_CHECK(compileSignal(prop,obj)); } else { - COMPILE_CHECK(compileProperty(prop, obj, ctxt)); + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } } @@ -637,12 +639,12 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) if (isCustomParser) { if (testProperty(prop, obj)) { - COMPILE_CHECK(compileProperty(prop, obj, ctxt)); + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } else { customProps << QmlCustomParserNodePrivate::fromProperty(prop); } } else { - COMPILE_CHECK(compileProperty(prop, obj, ctxt)); + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } } @@ -673,7 +675,7 @@ bool QmlCompiler::compileObject(Object *obj, int ctxt) return true; } -bool QmlCompiler::compileComponent(Object *obj, int ctxt) +bool QmlCompiler::compileComponent(Object *obj, const BindingContext &ctxt) { Property *idProp = 0; if (obj->properties.count() > 1 || @@ -709,6 +711,7 @@ bool QmlCompiler::compileComponent(Object *obj, int ctxt) reference.id = val; reference.object = obj; reference.instructionIdx = output->bytecode.count(); + reference.idx = compileState.ids.count(); compileState.ids.insert(val, reference); int pref = output->indexForString(val); @@ -724,7 +727,7 @@ bool QmlCompiler::compileComponent(Object *obj, int ctxt) return true; } -bool QmlCompiler::compileComponentFromRoot(Object *obj, int ctxt) +bool QmlCompiler::compileComponentFromRoot(Object *obj, const BindingContext &ctxt) { output->bytecode.push_back(QmlInstruction()); QmlInstruction &create = output->bytecode.last(); @@ -743,6 +746,7 @@ bool QmlCompiler::compileComponentFromRoot(Object *obj, int ctxt) ComponentCompileState oldComponentCompileState = compileState; compileState = ComponentCompileState(); + compileState.root = obj; if (obj) COMPILE_CHECK(compileObject(obj, ctxt)); @@ -753,7 +757,7 @@ bool QmlCompiler::compileComponentFromRoot(Object *obj, int ctxt) } -bool QmlCompiler::compileFetchedObject(Object *obj, int ctxt) +bool QmlCompiler::compileFetchedObject(Object *obj, const BindingContext &ctxt) { Q_ASSERT(obj->metatype); @@ -871,7 +875,7 @@ bool QmlCompiler::testProperty(QmlParser::Property *prop, return false; } -bool QmlCompiler::compileProperty(Property *prop, Object *obj, int ctxt) +bool QmlCompiler::compileProperty(Property *prop, Object *obj, const BindingContext &ctxt) { if (prop->values.isEmpty() && !prop->value) COMPILE_EXCEPTION2(prop, "Empty property assignment"); @@ -992,6 +996,7 @@ bool QmlCompiler::compileIdProperty(QmlParser::Property *prop, reference.id = val; reference.object = obj; reference.instructionIdx = output->bytecode.count(); + reference.idx = compileState.ids.count(); compileState.ids.insert(val, reference); QmlInstruction id; @@ -1012,7 +1017,7 @@ bool QmlCompiler::compileIdProperty(QmlParser::Property *prop, // } // GridView is an attached property object. bool QmlCompiler::compileAttachedProperty(QmlParser::Property *prop, - int ctxt) + const BindingContext &ctxt) { Q_ASSERT(prop->value); int id = QmlMetaType::attachedPropertiesFuncId(prop->name); @@ -1024,7 +1029,7 @@ bool QmlCompiler::compileAttachedProperty(QmlParser::Property *prop, fetch.fetchAttached.id = id; output->bytecode << fetch; - COMPILE_CHECK(compileFetchedObject(prop->value, ctxt + 1)); + COMPILE_CHECK(compileFetchedObject(prop->value, ctxt.incr())); QmlInstruction pop; pop.type = QmlInstruction::PopFetchedObject; @@ -1040,7 +1045,7 @@ bool QmlCompiler::compileAttachedProperty(QmlParser::Property *prop, // } // font is a nested property. size is not. bool QmlCompiler::compileNestedProperty(QmlParser::Property *prop, - int ctxt) + const BindingContext &ctxt) { Q_ASSERT(prop->type != 0); Q_ASSERT(prop->index != -1); @@ -1057,7 +1062,7 @@ bool QmlCompiler::compileNestedProperty(QmlParser::Property *prop, fetch.line = prop->location.start.line; output->bytecode << fetch; - COMPILE_CHECK(compileFetchedObject(prop->value, ctxt + 1)); + COMPILE_CHECK(compileFetchedObject(prop->value, ctxt.incr())); QmlInstruction pop; pop.type = QmlInstruction::PopFetchedObject; @@ -1074,7 +1079,7 @@ bool QmlCompiler::compileNestedProperty(QmlParser::Property *prop, // QmlList * types can accept a list of objects bool QmlCompiler::compileListProperty(QmlParser::Property *prop, QmlParser::Object *obj, - int ctxt) + const BindingContext &ctxt) { Q_ASSERT(QmlMetaType::isList(prop->type) || QmlMetaType::isQmlList(prop->type)); @@ -1166,7 +1171,7 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, // We allow assignming multiple values to single value properties bool QmlCompiler::compilePropertyAssignment(QmlParser::Property *prop, QmlParser::Object *obj, - int ctxt) + const BindingContext &ctxt) { for (int ii = 0; ii < prop->values.count(); ++ii) { Value *v = prop->values.at(ii); @@ -1187,7 +1192,7 @@ bool QmlCompiler::compilePropertyAssignment(QmlParser::Property *prop, // Compile assigning a single object instance to a regular property bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, QmlParser::Value *v, - int ctxt) + const BindingContext &ctxt) { Q_ASSERT(prop->index != -1); Q_ASSERT(v->object->type != -1); @@ -1296,7 +1301,7 @@ bool QmlCompiler::compilePropertyObjectAssignment(QmlParser::Property *prop, bool QmlCompiler::compilePropertyLiteralAssignment(QmlParser::Property *prop, QmlParser::Object *obj, QmlParser::Value *v, - int ctxt) + const BindingContext &ctxt) { Q_ASSERT(prop->index != -1); @@ -1409,7 +1414,7 @@ bool QmlCompiler::compileDynamicMeta(QmlParser::Object *obj) bool QmlCompiler::compileBinding(QmlParser::Value *value, QmlParser::Property *prop, - int ctxt) + const BindingContext &ctxt) { Q_ASSERT(prop->index); Q_ASSERT(prop->parent); @@ -1491,7 +1496,15 @@ void QmlCompiler::finalizeComponent(int patch) void QmlCompiler::finalizeBinding(const BindingReference &binding) { QmlBasicScript bs; - bs.compile(binding.expression); + QmlBasicScript::Expression expr; + expr.component = compileState.root; + expr.context = binding.bindingContext.object; + expr.property = binding.property; + expr.expression = binding.expression; + foreach (const IdReference &id, compileState.ids) + expr.ids.insert(id.id, qMakePair(id.object, id.idx)); + + bs.compile(expr); QmlInstruction &instr = output->bytecode[binding.instructionIdx]; instr.line = binding.value->location.start.line; @@ -1553,7 +1566,7 @@ void QmlCompiler::finalizeBinding(const BindingReference &binding) bref = output->indexForString(binding.expression.asScript()); } - instr.assignBinding.context = binding.bindingContext; + instr.assignBinding.context = binding.bindingContext.stack; if (bs.isValid()) instr.type = QmlInstruction::StoreCompiledBinding; diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index 6b6e1e2..6b6d8cb 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -125,41 +125,55 @@ public: private: void reset(QmlCompiledComponent *, bool); + struct BindingContext { + BindingContext() + : stack(0), object(0) {} + BindingContext(QmlParser::Object *o) + : stack(0), object(o) {} + BindingContext incr() const { + BindingContext rv(object); + rv.stack = stack + 1; + return rv; + } + int stack; + QmlParser::Object *object; + }; + void compileTree(QmlParser::Object *tree); - bool compileObject(QmlParser::Object *obj, int); - bool compileComponent(QmlParser::Object *obj, int); - bool compileComponentFromRoot(QmlParser::Object *obj, int); - bool compileFetchedObject(QmlParser::Object *obj, int); + bool compileObject(QmlParser::Object *obj, const BindingContext &); + bool compileComponent(QmlParser::Object *obj, const BindingContext &); + bool compileComponentFromRoot(QmlParser::Object *obj, const BindingContext &); + bool compileFetchedObject(QmlParser::Object *obj, const BindingContext &); bool compileSignal(QmlParser::Property *prop, QmlParser::Object *obj); bool testProperty(QmlParser::Property *prop, QmlParser::Object *obj); int signalByName(const QMetaObject *, const QByteArray &name); - bool compileProperty(QmlParser::Property *prop, QmlParser::Object *obj, int); + bool compileProperty(QmlParser::Property *prop, QmlParser::Object *obj, const BindingContext &); bool compileIdProperty(QmlParser::Property *prop, QmlParser::Object *obj); bool compileAttachedProperty(QmlParser::Property *prop, - int ctxt); + const BindingContext &ctxt); bool compileNestedProperty(QmlParser::Property *prop, - int ctxt); + const BindingContext &ctxt); bool compileListProperty(QmlParser::Property *prop, QmlParser::Object *obj, - int ctxt); + const BindingContext &ctxt); bool compilePropertyAssignment(QmlParser::Property *prop, QmlParser::Object *obj, - int ctxt); + const BindingContext &ctxt); bool compilePropertyObjectAssignment(QmlParser::Property *prop, QmlParser::Value *value, - int ctxt); + const BindingContext &ctxt); bool compilePropertyLiteralAssignment(QmlParser::Property *prop, QmlParser::Object *obj, QmlParser::Value *value, - int ctxt); + const BindingContext &ctxt); bool compileStoreInstruction(QmlInstruction &instr, const QMetaProperty &prop, QmlParser::Value *value); bool compileDynamicMeta(QmlParser::Object *obj); bool compileBinding(QmlParser::Value *, QmlParser::Property *prop, - int ctxt); + const BindingContext &ctxt); void finalizeComponent(int patch); struct BindingReference; @@ -169,6 +183,7 @@ private: QString id; QmlParser::Object *object; int instructionIdx; + int idx; }; struct BindingReference { @@ -176,17 +191,18 @@ private: QmlParser::Property *property; QmlParser::Value *value; int instructionIdx; - int bindingContext; + BindingContext bindingContext; }; struct ComponentCompileState { - ComponentCompileState() : parserStatusCount(0), savedObjects(0), pushedProperties(0) {} + ComponentCompileState() : parserStatusCount(0), savedObjects(0), pushedProperties(0), root(0) {} QHash ids; int parserStatusCount; int savedObjects; int pushedProperties; QList bindings; + QmlParser::Object *root; }; ComponentCompileState compileState; diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index 73b9245..66781ce 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -219,30 +219,11 @@ QmlContext *QmlEnginePrivate::setCurrentBindContext(QmlContext *c) return old; } -QmlEnginePrivate::CapturedProperty::CapturedProperty(QObject *obj, int n) -: object(obj), notifyIndex(n) -{ -} - QmlEnginePrivate::CapturedProperty::CapturedProperty(const QmlMetaProperty &p) -: object(p.object()), name(p.name()), notifyIndex(p.property().notifySignalIndex()) -{ -} - -QmlEnginePrivate::CapturedProperty::CapturedProperty(const CapturedProperty &o) -: object(o.object), name(o.name), notifyIndex(o.notifyIndex) +: object(p.object()), notifyIndex(p.property().notifySignalIndex()) { } -QmlEnginePrivate::CapturedProperty & -QmlEnginePrivate::CapturedProperty::operator=(const CapturedProperty &o) -{ - object = o.object; - name = o.name; - notifyIndex = o.notifyIndex; - return *this; -} - //////////////////////////////////////////////////////////////////// typedef QHash, bool> FunctionCache; Q_GLOBAL_STATIC(FunctionCache, functionCache); @@ -1224,8 +1205,9 @@ QVariant QmlExpression::value() QMetaObject::connect(prop.object, prop.notifyIndex, d->proxy, changedIndex); } else { - QString warn = QLatin1String("Expression depends on property without a NOTIFY signal: [") + QLatin1String(prop.object->metaObject()->className()) + QLatin1String("].") + prop.name; - log.addWarning(warn); + // ### FIXME + //QString warn = QLatin1String("Expression depends on property without a NOTIFY signal: [") + QLatin1String(prop.object->metaObject()->className()) + QLatin1String("].") + prop.name; + //log.addWarning(warn); } } d->addLog(log); @@ -1305,7 +1287,7 @@ void QmlExpression::setTrackChange(bool trackChange) Set the location of this expression to \a line of \a fileName. This information is used by the script engine. */ -void QmlExpression::setSourceLocation(const QString &fileName, int line) +void QmlExpression::setSourceLocation(const QUrl &fileName, int line) { d->fileName = fileName; d->line = line; diff --git a/src/declarative/qml/qmlengine_p.h b/src/declarative/qml/qmlengine_p.h index d7249e4..a1028e6 100644 --- a/src/declarative/qml/qmlengine_p.h +++ b/src/declarative/qml/qmlengine_p.h @@ -52,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -90,16 +91,14 @@ public: QScriptValue propertyObject(const QScriptString &propName, QObject *, uint id = 0); struct CapturedProperty { - CapturedProperty(QObject *, int); + CapturedProperty(QObject *o, int n) + : object(o), notifyIndex(n) {} CapturedProperty(const QmlMetaProperty &); - CapturedProperty(const CapturedProperty &); - CapturedProperty &operator=(const CapturedProperty &); QObject *object; - QString name; int notifyIndex; }; - QList capturedProperties; + QPODVector capturedProperties; QmlContext *rootContext; QmlContext *currentBindContext; @@ -280,7 +279,8 @@ public: BindExpressionProxy *proxy; QObject *me; bool trackChange; - QString fileName; + + QUrl fileName; int line; quint32 id; diff --git a/src/declarative/qml/qmlexpression.h b/src/declarative/qml/qmlexpression.h index 651fd9c..15d026a 100644 --- a/src/declarative/qml/qmlexpression.h +++ b/src/declarative/qml/qmlexpression.h @@ -77,7 +77,7 @@ public: bool trackChange() const; void setTrackChange(bool); - void setSourceLocation(const QString &fileName, int line); + void setSourceLocation(const QUrl &fileName, int line); QObject *scopeObject() const; diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index f00d282..9ed7e95 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -695,7 +695,7 @@ case QmlInstruction::StoreDouble: QFx_setParent_noEvent(bind, target); bind->setTarget(mp); - bind->setSourceLocation(comp->url.toString(), instr.line); + bind->setSourceLocation(comp->url, instr.line); } break; @@ -719,7 +719,7 @@ case QmlInstruction::StoreDouble: QFx_setParent_noEvent(bind, target); bind->setTarget(mp); - bind->setSourceLocation(comp->url.toString(), instr.line); + bind->setSourceLocation(comp->url, instr.line); } break; diff --git a/src/declarative/qml/qpodvector_p.h b/src/declarative/qml/qpodvector_p.h new file mode 100644 index 0000000..55c04e7 --- /dev/null +++ b/src/declarative/qml/qpodvector_p.h @@ -0,0 +1,124 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtDeclarative module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QPODVECTOR_P_H +#define QPODVECTOR_P_H + +#include + +QT_BEGIN_NAMESPACE + +template +class QPODVector +{ +public: + QPODVector() + : m_count(0), m_capacity(0), m_data(0) {} + + const T &at(int idx) { + return m_data[idx]; + } + + T &operator[](int idx) { + return m_data[idx]; + } + + void clear() { + m_count = 0; + } + + void prepend(const T &v) { + insert(0, v); + } + + void append(const T &v) { + insert(m_count, v); + } + + void insert(int idx, const T &v) { + if (m_count == m_capacity) { + m_capacity += 1024; + m_data = (T *)realloc(m_data, m_capacity * sizeof(T)); + } + int moveCount = m_count - idx; + if (moveCount) + ::memmove(m_data + idx + 1, m_data + idx, moveCount * sizeof(T)); + m_count++; + m_data[idx] = v; + } + + void insertBlank(int idx, int count) { + int newSize = m_count + count; + if (newSize >= m_capacity) { + m_capacity = (newSize + 1023) & 0xFFFFFC00; + m_data = (T *)realloc(m_data, m_capacity * sizeof(T)); + } + + int moveCount = m_count - idx; + if (moveCount) + ::memmove(m_data + idx + count, m_data + idx, + moveCount * sizeof(T)); + m_count = newSize; + } + + void remove(int idx, int count = 1) { + int moveCount = m_count - (idx + count); + if (moveCount) + ::memmove(m_data + idx, m_data + idx + count, + moveCount * sizeof(T)); + m_count -= count; + } + + int count() const { + return m_count; + } + + QPODVector &operator<<(const T &v) { append(v); return *this; } +private: + QPODVector(const QPODVector &); + QPODVector &operator=(const QPODVector &); + int m_count; + int m_capacity; + T *m_data; +}; +QT_END_NAMESPACE + +#endif -- cgit v0.12 From 5c24620b91ee57629b4356885f8b5517e3d82e32 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 10 Jun 2009 14:22:04 +1000 Subject: Remove dead code --- src/declarative/qml/qmlcompiler.cpp | 4 ---- src/declarative/qml/qmlinstruction.cpp | 2 +- src/declarative/qml/qmlinstruction_p.h | 6 +----- 3 files changed, 2 insertions(+), 10 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index fe3da57..04a488d 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -1102,8 +1102,6 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, QmlInstruction assign; assign.type = QmlInstruction::AssignObjectList; assign.line = prop->location.start.line; - assign.assignObject.property = output->indexForByteArray(prop->name); - assign.assignObject.castValue = 0; output->bytecode << assign; } else { COMPILE_EXCEPTION("Cannot assign primitives to lists"); @@ -1130,8 +1128,6 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, QmlInstruction assign; assign.type = QmlInstruction::AssignObjectList; assign.line = v->location.start.line; - assign.assignObject.property = output->indexForByteArray(prop->name); - assign.assignObject.castValue = 0; output->bytecode << assign; } else if (v->value.isScript()) { if (assignedBinding) diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index af1489a..bcc1f0d 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -146,7 +146,7 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) qWarning() << idx << "\t" << line << "\t" << "COMPLETE\t\t" << instr->complete.castValue; break; case QmlInstruction::AssignObjectList: - qWarning() << idx << "\t" << line << "\t" << "ASSIGN_OBJECT_LIST\t" << instr->assignObject.property << "\t" << instr->assignObject.castValue << "\t\t" << ((instr->assignObject.property == -1)?QByteArray("default"):datas.at(instr->assignObject.property)); + qWarning() << idx << "\t" << line << "\t" << "ASSIGN_OBJECT_LIST\t"; break; case QmlInstruction::FetchAttached: qWarning() << idx << "\t" << line << "\t" << "FETCH_ATTACHED\t\t" << instr->fetchAttached.id; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index 5a1729f..bdbbaff 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -122,7 +122,7 @@ public: BeginObject, /* begin */ CompleteObject, /* complete */ - AssignObjectList, /* assignObject */ + AssignObjectList, /* NA */ FetchAttached, /* fetchAttached */ FetchQmlList, /* fetchQmlList */ @@ -170,10 +170,6 @@ public: } setId; struct { int property; - int castValue; - } assignObject; - struct { - int property; } assignValueSource; struct { int property; -- cgit v0.12 From 4dc4cfac667389efda4a43df5ff8cfa4ba305a2f Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Wed, 10 Jun 2009 14:57:51 +1000 Subject: Support URLs directly (not just as strings), so they are correctly resolved. URLs expressed as strings (possible relative) are resolved relative to the component in which the string expression is converted to a url value. All items are converted to use QUrl properties, except SqlConnection, where the databasename is only a special-case URL (this may need further consideration). --- doc/src/declarative/basictypes.qdoc | 20 +++++++++++++ src/declarative/extra/qmlxmllistmodel.cpp | 8 ++--- src/declarative/extra/qmlxmllistmodel.h | 6 ++-- src/declarative/fx/qfxanimatedimageitem.cpp | 5 ++-- src/declarative/fx/qfxblendedimage.cpp | 34 +++++++++++----------- src/declarative/fx/qfxblendedimage.h | 14 ++++----- src/declarative/fx/qfxhighlightfilter.cpp | 12 ++++---- src/declarative/fx/qfxhighlightfilter.h | 8 ++--- src/declarative/fx/qfximage.cpp | 15 +++++----- src/declarative/fx/qfximage.h | 8 ++--- src/declarative/fx/qfximage_p.h | 1 - src/declarative/fx/qfxitem.cpp | 21 +++++++------ src/declarative/fx/qfxitem.h | 6 ++-- src/declarative/fx/qfxitem_p.h | 3 +- src/declarative/fx/qfxparticles.cpp | 18 +++++------- src/declarative/fx/qfxparticles.h | 6 ++-- src/declarative/fx/qfxwebview.cpp | 18 +++++------- src/declarative/fx/qfxwebview.h | 6 ++-- src/declarative/qml/qmlbindablevalue.cpp | 4 +++ src/declarative/qml/qmlcompiler.cpp | 11 +++++++ src/declarative/qml/qmlinstruction.cpp | 3 ++ src/declarative/qml/qmlinstruction_p.h | 6 ++++ src/declarative/qml/qmlparser_p.h | 2 +- src/declarative/qml/qmlscriptparser.cpp | 1 + src/declarative/qml/qmlvme.cpp | 16 ++++++++++ src/declarative/qml/qmlvmemetaobject.cpp | 3 ++ src/declarative/util/qfxview.cpp | 6 ---- src/declarative/util/qmlscript.cpp | 17 +++++------ src/declarative/util/qmlscript.h | 6 ++-- .../numberformatter/tst_numberformatter.cpp | 1 + 30 files changed, 166 insertions(+), 119 deletions(-) diff --git a/doc/src/declarative/basictypes.qdoc b/doc/src/declarative/basictypes.qdoc index f7eee50..2ef91e6 100644 --- a/doc/src/declarative/basictypes.qdoc +++ b/doc/src/declarative/basictypes.qdoc @@ -82,6 +82,26 @@ \raw HTML \endraw + \target basicqmlurl + \raw HTML +
      + + +
      url
      + \endraw + + URLs are resource locators, such as file names. They can be either absolute, like "http://qtsoftware.com", + or relative, like "pics/logo.png". Relative URLs are resolved relative to the URL of the component where + the URL is converted from a JavaScript string expression to a url property value. + + Setting a url looks like this: + \code + Image { source: "pics/logo.png" } + \endcode + + \raw HTML + \endraw + \target basicqmlcolor \raw HTML
      diff --git a/src/declarative/extra/qmlxmllistmodel.cpp b/src/declarative/extra/qmlxmllistmodel.cpp index a7f5d72..62ede80 100644 --- a/src/declarative/extra/qmlxmllistmodel.cpp +++ b/src/declarative/extra/qmlxmllistmodel.cpp @@ -270,7 +270,7 @@ public: , queryId(-1), roleObjects(this) {} bool isClassComplete; - QString src; + QUrl src; QString query; QString namespaces; int size; @@ -388,13 +388,13 @@ QString QmlXmlListModel::toString(int role) const return d->roleNames.at(index); } -QString QmlXmlListModel::source() const +QUrl QmlXmlListModel::source() const { Q_D(const QmlXmlListModel); return d->src; } -void QmlXmlListModel::setSource(const QString &src) +void QmlXmlListModel::setSource(const QUrl &src) { Q_D(QmlXmlListModel); if (d->src != src) { @@ -483,7 +483,7 @@ void QmlXmlListModel::reload() emit progressChanged(d->progress); emit statusChanged(d->status); - QNetworkRequest req((QUrl(d->src))); + QNetworkRequest req(d->src); req.setAttribute(QNetworkRequest::CacheLoadControlAttribute, QNetworkRequest::PreferCache); d->reply = qmlContext(this)->engine()->networkAccessManager()->get(req); QObject::connect(d->reply, SIGNAL(finished()), this, SLOT(requestFinished())); diff --git a/src/declarative/extra/qmlxmllistmodel.h b/src/declarative/extra/qmlxmllistmodel.h index 052a0c2..bdbba47 100644 --- a/src/declarative/extra/qmlxmllistmodel.h +++ b/src/declarative/extra/qmlxmllistmodel.h @@ -93,7 +93,7 @@ class Q_DECLARATIVE_EXPORT QmlXmlListModel : public QListModelInterface, public Q_PROPERTY(Status status READ status NOTIFY statusChanged) Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) - Q_PROPERTY(QString source READ source WRITE setSource) + Q_PROPERTY(QUrl source READ source WRITE setSource) Q_PROPERTY(QString query READ query WRITE setQuery) Q_PROPERTY(QString namespaceDeclarations READ namespaceDeclarations WRITE setNamespaceDeclarations) Q_PROPERTY(QmlList *roles READ roleObjects) @@ -109,8 +109,8 @@ public: QmlList *roleObjects(); - QString source() const; - void setSource(const QString&); + QUrl source() const; + void setSource(const QUrl&); QString query() const; void setQuery(const QString&); diff --git a/src/declarative/fx/qfxanimatedimageitem.cpp b/src/declarative/fx/qfxanimatedimageitem.cpp index 029206b..604481c 100644 --- a/src/declarative/fx/qfxanimatedimageitem.cpp +++ b/src/declarative/fx/qfxanimatedimageitem.cpp @@ -155,7 +155,7 @@ int QFxAnimatedImageItem::frameCount() const void QFxAnimatedImageItem::setSource(const QString &url) { Q_D(QFxAnimatedImageItem); - if (url == d->source) + if (url == d->url) return; delete d->_movie; @@ -166,8 +166,7 @@ void QFxAnimatedImageItem::setSource(const QString &url) d->reply = 0; } - d->source = url; - d->url = qmlContext(this)->resolvedUrl(url); + d->url = url; if (url.isEmpty()) { delete d->_movie; diff --git a/src/declarative/fx/qfxblendedimage.cpp b/src/declarative/fx/qfxblendedimage.cpp index 4c6eb58..1f805df 100644 --- a/src/declarative/fx/qfxblendedimage.cpp +++ b/src/declarative/fx/qfxblendedimage.cpp @@ -84,9 +84,9 @@ QFxBlendedImage::QFxBlendedImage(QFxItem *parent) \qmlproperty string BlendedImage::primaryUrl The URL of the first image to be displayed in this item. */ -QString QFxBlendedImage::primaryUrl() const +QUrl QFxBlendedImage::primaryUrl() const { - return primSrc; + return primUrl; } void QFxBlendedImage::primaryLoaded() @@ -96,15 +96,15 @@ void QFxBlendedImage::primaryLoaded() update(); } -void QFxBlendedImage::setPrimaryUrl(const QString &url) +void QFxBlendedImage::setPrimaryUrl(const QUrl &url) { - if (primSrc == url) + if (primUrl == url) return; - if (!primSrc.isEmpty()) + if (!primUrl.isEmpty()) QFxPixmap::cancelGet(primUrl,this); - primSrc = url; - primUrl = qmlContext(this)->resolvedUrl(url); - if (!primSrc.isEmpty()) + Q_ASSERT(!primUrl.isRelative()); + primUrl = url; + if (!primUrl.isEmpty()) QFxPixmap::get(qmlEngine(this), primUrl,this,SLOT(primaryLoaded())); } @@ -112,9 +112,9 @@ void QFxBlendedImage::setPrimaryUrl(const QString &url) \qmlproperty string BlendedImage::secondaryUrl The URL of the second image to be displayed in this item. */ -QString QFxBlendedImage::secondaryUrl() const +QUrl QFxBlendedImage::secondaryUrl() const { - return secSrc; + return secUrl; } void QFxBlendedImage::secondaryLoaded() @@ -124,15 +124,15 @@ void QFxBlendedImage::secondaryLoaded() update(); } -void QFxBlendedImage::setSecondaryUrl(const QString &url) +void QFxBlendedImage::setSecondaryUrl(const QUrl &url) { - if (secSrc == url) + if (secUrl == url) return; - if (!secSrc.isEmpty()) + if (!secUrl.isEmpty()) QFxPixmap::cancelGet(secUrl,this); - secSrc = url; - secUrl = qmlContext(this)->resolvedUrl(url); - if (!secSrc.isEmpty()) + Q_ASSERT(!url.isRelative()); + secUrl = url; + if (!secUrl.isEmpty()) QFxPixmap::get(qmlEngine(this), secUrl,this,SLOT(secondaryLoaded())); } @@ -183,7 +183,7 @@ void QFxBlendedImage::setSmoothTransform(bool s) void QFxBlendedImage::paintContents(QPainter &p) { - if (primSrc.isNull() && secSrc.isNull()) + if (primUrl.isEmpty() && secUrl.isEmpty()) return; if (_smooth) { diff --git a/src/declarative/fx/qfxblendedimage.h b/src/declarative/fx/qfxblendedimage.h index baf4b64..7169b92 100644 --- a/src/declarative/fx/qfxblendedimage.h +++ b/src/declarative/fx/qfxblendedimage.h @@ -57,18 +57,18 @@ class Q_DECLARATIVE_EXPORT QFxBlendedImage : public QFxItem { Q_OBJECT - Q_PROPERTY(QString primaryUrl READ primaryUrl WRITE setPrimaryUrl) - Q_PROPERTY(QString secondaryUrl READ secondaryUrl WRITE setSecondaryUrl) + Q_PROPERTY(QUrl primaryUrl READ primaryUrl WRITE setPrimaryUrl) + Q_PROPERTY(QUrl secondaryUrl READ secondaryUrl WRITE setSecondaryUrl) Q_PROPERTY(qreal blend READ blend WRITE setBlend) Q_PROPERTY(bool smooth READ smoothTransform WRITE setSmoothTransform) public: QFxBlendedImage(QFxItem *parent=0); - QString primaryUrl() const; - void setPrimaryUrl(const QString &); + QUrl primaryUrl() const; + void setPrimaryUrl(const QUrl &); - QString secondaryUrl() const; - void setSecondaryUrl(const QString &); + QUrl secondaryUrl() const; + void setSecondaryUrl(const QUrl &); qreal blend() const; void setBlend(qreal); @@ -87,8 +87,6 @@ private Q_SLOTS: void secondaryLoaded(); private: - QString primSrc; - QString secSrc; QUrl primUrl; QUrl secUrl; diff --git a/src/declarative/fx/qfxhighlightfilter.cpp b/src/declarative/fx/qfxhighlightfilter.cpp index 6bf3148..3d5f413 100644 --- a/src/declarative/fx/qfxhighlightfilter.cpp +++ b/src/declarative/fx/qfxhighlightfilter.cpp @@ -128,7 +128,7 @@ QFxHighlightFilter::~QFxHighlightFilter() \property QFxHighlightFilter::source \brief the URL of the image to be used as the highlight. */ -QString QFxHighlightFilter::source() const +QUrl QFxHighlightFilter::source() const { return d->source; } @@ -144,14 +144,14 @@ void QFxHighlightFilter::imageLoaded() update(); } -void QFxHighlightFilter::setSource(const QString &f) +void QFxHighlightFilter::setSource(const QUrl &f) { - if (d->source == f) + if (d->url == f) return; - if (!d->source.isEmpty()) + if (!d->url.isEmpty()) QFxPixmap::cancelGet(d->url, this); - d->source = f; - d->url = qmlContext(this)->resolvedUrl(f); + Q_ASSERT(!f.isRelative()); + d->url = f; #if defined(QFX_RENDER_OPENGL2) d->tex.clear(); #endif diff --git a/src/declarative/fx/qfxhighlightfilter.h b/src/declarative/fx/qfxhighlightfilter.h index 19e95ac..33f0963 100644 --- a/src/declarative/fx/qfxhighlightfilter.h +++ b/src/declarative/fx/qfxhighlightfilter.h @@ -56,7 +56,7 @@ class Q_DECLARATIVE_EXPORT QFxHighlightFilter : public QSimpleCanvasFilter { Q_OBJECT - Q_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged) + Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged) Q_PROPERTY(bool tiled READ tiled WRITE setTiled NOTIFY tiledChanged) Q_PROPERTY(int xOffset READ xOffset WRITE setXOffset NOTIFY offsetChanged) Q_PROPERTY(int yOffset READ yOffset WRITE setYOffset NOTIFY offsetChanged) @@ -64,8 +64,8 @@ public: QFxHighlightFilter(QObject *parent=0); virtual ~QFxHighlightFilter(); - QString source() const; - void setSource(const QString &); + QUrl source() const; + void setSource(const QUrl &); bool tiled() const; void setTiled(bool); @@ -76,7 +76,7 @@ public: void setYOffset(int); Q_SIGNALS: - void sourceChanged(const QString &); + void sourceChanged(const QUrl &); void offsetChanged(int x, int y); void tiledChanged(bool); diff --git a/src/declarative/fx/qfximage.cpp b/src/declarative/fx/qfximage.cpp index 224c25e..05738e3 100644 --- a/src/declarative/fx/qfximage.cpp +++ b/src/declarative/fx/qfximage.cpp @@ -825,19 +825,19 @@ qreal QFxImage::progress() const The content specified can be of any image type loadable by QImage. Alternatively, you can specify an sci format file, which specifies both an image and it's scale grid. */ -QString QFxImage::source() const +QUrl QFxImage::source() const { Q_D(const QFxImage); - return d->source; + return d->url; } -void QFxImage::setSource(const QString &url) +void QFxImage::setSource(const QUrl &url) { #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer perf; #endif Q_D(QFxImage); - if (url == d->source) + if (url == d->url) return; if (d->sciReply) { @@ -850,8 +850,7 @@ void QFxImage::setSource(const QString &url) if (!d->sciurl.isEmpty()) QFxPixmap::cancelGet(d->sciurl, this); - d->source = url; - d->url = qmlContext(this)->resolvedUrl(url); + d->url = url; d->sciurl = QUrl(); if (d->progress != 0.0) { d->progress = 0.0; @@ -872,7 +871,7 @@ void QFxImage::setSource(const QString &url) } #endif emit statusChanged(d->status); - emit sourceChanged(d->source); + emit sourceChanged(d->url); emit progressChanged(1.0); update(); } else { @@ -936,7 +935,7 @@ void QFxImage::requestFinished() } #endif emit statusChanged(d->status); - emit sourceChanged(d->source); + emit sourceChanged(d->url); emit progressChanged(1.0); update(); } diff --git a/src/declarative/fx/qfximage.h b/src/declarative/fx/qfximage.h index 4d5f134..35b921a 100644 --- a/src/declarative/fx/qfximage.h +++ b/src/declarative/fx/qfximage.h @@ -58,7 +58,7 @@ class Q_DECLARATIVE_EXPORT QFxImage : public QFxItem Q_ENUMS(Status) Q_PROPERTY(Status status READ status NOTIFY statusChanged) - Q_PROPERTY(QString source READ source WRITE setSource NOTIFY sourceChanged) + Q_PROPERTY(QUrl source READ source WRITE setSource NOTIFY sourceChanged) Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) Q_PROPERTY(QFxScaleGrid *scaleGrid READ scaleGrid) @@ -88,8 +88,8 @@ public: Status status() const; qreal progress() const; - QString source() const; - virtual void setSource(const QString &url); + QUrl source() const; + virtual void setSource(const QUrl &url); virtual void dump(int depth); virtual QString propertyInfo() const; @@ -102,7 +102,7 @@ public: #endif Q_SIGNALS: - void sourceChanged(const QString &); + void sourceChanged(const QUrl &); void statusChanged(Status); void progressChanged(qreal progress); diff --git a/src/declarative/fx/qfximage_p.h b/src/declarative/fx/qfximage_p.h index cd07a37..1785abb 100644 --- a/src/declarative/fx/qfximage_p.h +++ b/src/declarative/fx/qfximage_p.h @@ -106,7 +106,6 @@ public: #endif QFxImage::Status status; - QString source; QUrl url; QUrl sciurl; QNetworkReply *sciReply; diff --git a/src/declarative/fx/qfxitem.cpp b/src/declarative/fx/qfxitem.cpp index 7129757..09ec748 100644 --- a/src/declarative/fx/qfxitem.cpp +++ b/src/declarative/fx/qfxitem.cpp @@ -792,12 +792,12 @@ QFxItem *QFxItem::qmlItem() const } /*! - \qmlproperty string Item::qml - This property holds the dynamic QML for the item. + \qmlproperty url Item::qml + This property holds the dynamic URL of the QML for the item. This property is used for dynamically loading QML into the item. Querying for the QML only has meaning if the QML has been - dynamically set; otherwise an empty string is returned. + dynamically set; otherwise an empty URL is returned. */ /*! \fn void QFxItem::qmlChanged() @@ -809,32 +809,31 @@ QFxItem *QFxItem::qmlItem() const /*! \property QFxItem::qml - This property holds the dynamic QML for the item. + This property holds the dynamic URL of the QML for the item. This property is used for dynamically loading QML into the item. Querying for the QML only has meaning if the QML has been - dynamically set; otherwise an empty string is returned. + dynamically set; otherwise an empty URL is returned. */ -QString QFxItem::qml() const +QUrl QFxItem::qml() const { Q_D(const QFxItem); return d->_qml; } -void QFxItem::setQml(const QString &qml) +void QFxItem::setQml(const QUrl &qml) { Q_D(QFxItem); if (d->_qml == qml) return; if (!d->_qml.isEmpty()) { - QmlChildren::Iterator iter = d->_qmlChildren.find(d->_qml); + QmlChildren::Iterator iter = d->_qmlChildren.find(d->_qml.toString()); if (iter != d->_qmlChildren.end()) (*iter)->setOpacity(0.); } d->_qml = qml; - d->_qmlurl = qmlContext(this)->resolvedUri(qml); d->qmlItem = 0; if (d->_qml.isEmpty()) { @@ -842,14 +841,14 @@ void QFxItem::setQml(const QString &qml) return; } - QmlChildren::Iterator iter = d->_qmlChildren.find(d->_qml); + QmlChildren::Iterator iter = d->_qmlChildren.find(d->_qml.toString()); if (iter != d->_qmlChildren.end()) { (*iter)->setOpacity(1.); d->qmlItem = (*iter); emit qmlChanged(); } else { d->_qmlcomp = - new QmlComponent(qmlEngine(this), d->_qmlurl, this); + new QmlComponent(qmlEngine(this), d->_qml, this); if (!d->_qmlcomp->isLoading()) qmlLoaded(); else diff --git a/src/declarative/fx/qfxitem.h b/src/declarative/fx/qfxitem.h index 8ca1f9e..3c872e1 100644 --- a/src/declarative/fx/qfxitem.h +++ b/src/declarative/fx/qfxitem.h @@ -111,7 +111,7 @@ class Q_DECLARATIVE_EXPORT QFxItem : public QSimpleCanvasItem, public QmlParserS Q_PROPERTY(QmlList* states READ states DESIGNABLE false) Q_PROPERTY(QmlList* transitions READ transitions DESIGNABLE false) Q_PROPERTY(QString state READ state WRITE setState NOTIFY stateChanged) - Q_PROPERTY(QString qml READ qml WRITE setQml NOTIFY qmlChanged) + Q_PROPERTY(QUrl qml READ qml WRITE setQml NOTIFY qmlChanged) Q_PROPERTY(QFxItem *qmlItem READ qmlItem NOTIFY qmlChanged) Q_PROPERTY(qreal x READ x WRITE setX NOTIFY leftChanged) Q_PROPERTY(qreal y READ y WRITE setY NOTIFY topChanged) @@ -171,8 +171,8 @@ public: void setState(const QString &); QFxItem *qmlItem() const; - QString qml() const; - void setQml(const QString &); + QUrl qml() const; + void setQml(const QUrl &); bool flipVertically() const; void setFlipVertically(bool); diff --git a/src/declarative/fx/qfxitem_p.h b/src/declarative/fx/qfxitem_p.h index a54f523..b38d877 100644 --- a/src/declarative/fx/qfxitem_p.h +++ b/src/declarative/fx/qfxitem_p.h @@ -133,9 +133,8 @@ public: QFxAnchors *_anchors; QFxContents *_contents; QFxItem *qmlItem; - QUrl _qmlurl; QmlComponent *_qmlcomp; - QString _qml; + QUrl _qml; QList _qmlnewloading; QList _qmlnewcomp; diff --git a/src/declarative/fx/qfxparticles.cpp b/src/declarative/fx/qfxparticles.cpp index 41fb5bc..25e359d 100644 --- a/src/declarative/fx/qfxparticles.cpp +++ b/src/declarative/fx/qfxparticles.cpp @@ -395,7 +395,6 @@ public: void createParticle(int time); void updateOpacity(QFxParticle &p, int age); - QString source; QUrl url; QPixmap image; int count; @@ -642,10 +641,10 @@ QFxParticles::~QFxParticles() \property QFxParticles::source \brief the URL of the particle image. */ -QString QFxParticles::source() const +QUrl QFxParticles::source() const { Q_D(const QFxParticles); - return d->source; + return d->url; } void QFxParticles::imageLoaded() @@ -659,18 +658,17 @@ void QFxParticles::imageLoaded() update(); } -void QFxParticles::setSource(const QString &name) +void QFxParticles::setSource(const QUrl &name) { Q_D(QFxParticles); - if (name == d->source) + if (name == d->url) return; - if (!d->source.isEmpty()) + if (!d->url.isEmpty()) QFxPixmap::cancelGet(d->url, this); if (name.isEmpty()) { - d->source = name; - d->url = QUrl(); + d->url = name; d->image = QPixmap(); #if defined(QFX_RENDER_OPENGL) d->texDirty = true; @@ -678,8 +676,8 @@ void QFxParticles::setSource(const QString &name) #endif update(); } else { - d->source = name; - d->url = qmlContext(this)->resolvedUrl(name); + d->url = name; + Q_ASSERT(!name.isRelative()); QFxPixmap::get(qmlEngine(this), d->url, this, SLOT(imageLoaded())); } } diff --git a/src/declarative/fx/qfxparticles.h b/src/declarative/fx/qfxparticles.h index 6ef2582..b3a569b 100644 --- a/src/declarative/fx/qfxparticles.h +++ b/src/declarative/fx/qfxparticles.h @@ -153,7 +153,7 @@ class Q_DECLARATIVE_EXPORT QFxParticles : public QFxItem { Q_OBJECT - Q_PROPERTY(QString source READ source WRITE setSource) + Q_PROPERTY(QUrl source READ source WRITE setSource) Q_PROPERTY(int count READ count WRITE setCount) Q_PROPERTY(int lifeSpan READ lifeSpan WRITE setLifeSpan) Q_PROPERTY(int lifeSpanDeviation READ lifeSpanDeviation WRITE setLifeSpanDeviation) @@ -172,8 +172,8 @@ public: QFxParticles(QFxItem *parent=0); ~QFxParticles(); - QString source() const; - void setSource(const QString &); + QUrl source() const; + void setSource(const QUrl &); int count() const; void setCount(int cnt); diff --git a/src/declarative/fx/qfxwebview.cpp b/src/declarative/fx/qfxwebview.cpp index bfccd34..d15502b 100644 --- a/src/declarative/fx/qfxwebview.cpp +++ b/src/declarative/fx/qfxwebview.cpp @@ -287,7 +287,7 @@ void QFxWebView::componentComplete() Q_D(QFxWebView); switch (d->pending) { case QFxWebViewPrivate::PendingUrl: - setUrl(d->pending_url.toString()); + setUrl(d->pending_url); break; case QFxWebViewPrivate::PendingHtml: setHtml(d->pending_string, d->pending_url); @@ -339,7 +339,7 @@ void QFxWebView::doLoadFinished(bool ok) } /*! - \qmlproperty string WebView::url + \qmlproperty url WebView::url This property holds the URL to the page displayed in this item. Note that after this property is set, it may take some time @@ -358,24 +358,22 @@ void QFxWebView::doLoadFinished(bool ok) Emitted when loading of the URL successfully starts after setUrl() is called. */ -QString QFxWebView::url() const +QUrl QFxWebView::url() const { - return page()->mainFrame()->url().toString(); + return page()->mainFrame()->url(); } -void QFxWebView::setUrl(const QString &n) +void QFxWebView::setUrl(const QUrl &url) { Q_D(QFxWebView); - if (n == page()->mainFrame()->url().toString()) + if (url == page()->mainFrame()->url()) return; page()->setViewportSize(QSize( d->idealwidth>0 ? d->idealwidth : width(), d->idealheight>0 ? d->idealheight : height())); - QUrl url(n); - if (url.isRelative()) - url = qmlContext(this)->resolvedUrl(n); + Q_ASSERT(!url.isRelative()); if (isComponentComplete()) page()->mainFrame()->load(url); @@ -942,7 +940,7 @@ void QFxWebView::setHtml(const QString &html, const QUrl &baseUrl) d->idealwidth>0 ? d->idealwidth : width(), d->idealheight>0 ? d->idealheight : height())); if (isComponentComplete()) - page()->mainFrame()->setHtml(html, qmlContext(this)->resolvedUrl(baseUrl)); + page()->mainFrame()->setHtml(html, baseUrl); else { d->pending = d->PendingHtml; d->pending_url = baseUrl; diff --git a/src/declarative/fx/qfxwebview.h b/src/declarative/fx/qfxwebview.h index 28ef6c3..f30fd0d 100644 --- a/src/declarative/fx/qfxwebview.h +++ b/src/declarative/fx/qfxwebview.h @@ -90,7 +90,7 @@ class Q_DECLARATIVE_EXPORT QFxWebView : public QFxPaintedItem Q_PROPERTY(int idealWidth READ idealWidth WRITE setIdealWidth NOTIFY idealWidthChanged) Q_PROPERTY(int idealHeight READ idealHeight WRITE setIdealHeight NOTIFY idealHeightChanged) - Q_PROPERTY(QString url READ url WRITE setUrl NOTIFY urlChanged) + Q_PROPERTY(QUrl url READ url WRITE setUrl NOTIFY urlChanged) Q_PROPERTY(qreal progress READ progress NOTIFY progressChanged) Q_PROPERTY(bool interactive READ interactive WRITE setInteractive NOTIFY interactiveChanged) @@ -108,8 +108,8 @@ public: QFxWebView(QFxItem *parent=0); ~QFxWebView(); - QString url() const; - void setUrl(const QString &); + QUrl url() const; + void setUrl(const QUrl &); QString title() const; diff --git a/src/declarative/qml/qmlbindablevalue.cpp b/src/declarative/qml/qmlbindablevalue.cpp index 351e0bd..de01387 100644 --- a/src/declarative/qml/qmlbindablevalue.cpp +++ b/src/declarative/qml/qmlbindablevalue.cpp @@ -220,6 +220,10 @@ void QmlBindableValue::update() } else if (d->property.propertyCategory() == QmlMetaProperty::Normal) { QVariant value = this->value(); + if (d->property.propertyType() == QVariant::Url && value.canConvert(QVariant::String) && !value.isNull()) { + // Must resolve first + value.setValue(context()->resolvedUrl(value.toString())); + } d->property.write(value); } diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index b28d7dd..8b4be2b 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -278,6 +278,14 @@ bool QmlCompiler::compileStoreInstruction(QmlInstruction &instr, instr.storeString.value = output->indexForString(string); } break; + case QVariant::Url: + { + instr.type = QmlInstruction::StoreUrl; + QUrl u = output->url.resolved(string); + instr.storeUrl.propertyIndex = prop.propertyIndex(); + instr.storeUrl.value = output->indexForString(u.toString()); + } + break; case QVariant::UInt: { instr.type = QmlInstruction::StoreInteger; @@ -1355,6 +1363,9 @@ bool QmlCompiler::compileDynamicMeta(QmlParser::Object *obj) case Object::DynamicProperty::String: type = "QString"; break; + case Object::DynamicProperty::Url: + type = "QUrl"; + break; case Object::DynamicProperty::Color: type = "QColor"; break; diff --git a/src/declarative/qml/qmlinstruction.cpp b/src/declarative/qml/qmlinstruction.cpp index af1489a..3fe3a8e 100644 --- a/src/declarative/qml/qmlinstruction.cpp +++ b/src/declarative/qml/qmlinstruction.cpp @@ -85,6 +85,9 @@ void QmlCompiledComponent::dump(QmlInstruction *instr, int idx) case QmlInstruction::StoreString: qWarning() << idx << "\t" << line << "\t" << "STORE_STRING\t\t" << instr->storeString.propertyIndex << "\t" << instr->storeString.value << "\t\t" << primitives.at(instr->storeString.value); break; + case QmlInstruction::StoreUrl: + qWarning() << idx << "\t" << line << "\t" << "STORE_URL\t\t" << instr->storeUrl.propertyIndex << "\t" << instr->storeUrl.value << "\t\t" << primitives.at(instr->storeUrl.value); + break; case QmlInstruction::StoreColor: qWarning() << idx << "\t" << line << "\t" << "STORE_COLOR\t\t" << instr->storeColor.propertyIndex << "\t" << QString::number(instr->storeColor.value, 16); break; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index 5a1729f..7cdc1ed 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -76,6 +76,7 @@ public: // StoreInteger - Store a int or uint in a core property // StoreBool - Store a bool in a core property // StoreString - Store a QString in a core property + // StoreUrl - Store a QUrl in a core property // StoreColor - Store a QColor in a core property // StoreDate - Store a QDate in a core property // StoreTime - Store a QTime in a core property @@ -88,6 +89,7 @@ public: StoreInteger, /* storeInteger */ StoreBool, /* storeBool */ StoreString, /* storeString */ + StoreUrl, /* storeUrl */ StoreColor, /* storeColor */ StoreDate, /* storeDate */ StoreTime, /* storeTime */ @@ -217,6 +219,10 @@ public: } storeString; struct { int propertyIndex; + int value; + } storeUrl; + struct { + int propertyIndex; unsigned int value; } storeColor; struct { diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h index 0fdd26b..7989933 100644 --- a/src/declarative/qml/qmlparser_p.h +++ b/src/declarative/qml/qmlparser_p.h @@ -131,7 +131,7 @@ namespace QmlParser DynamicProperty(); DynamicProperty(const DynamicProperty &); - enum Type { Variant, Int, Bool, Real, String, Color, Date }; + enum Type { Variant, Int, Bool, Real, String, Url, Color, Date }; bool isDefaultProperty; Type type; diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index 5207292..cab7915 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -501,6 +501,7 @@ bool ProcessAST::visit(AST::UiPublicMember *node) { "double", Object::DynamicProperty::Real }, { "real", Object::DynamicProperty::Real }, { "string", Object::DynamicProperty::String }, + { "url", Object::DynamicProperty::Url }, { "color", Object::DynamicProperty::Color }, { "date", Object::DynamicProperty::Date }, { "var", Object::DynamicProperty::Variant }, diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index f00d282..af0b3e0 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -77,6 +77,7 @@ Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { Q_DECLARE_PERFORMANCE_METRIC(InstrStoreInteger); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreBool); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreString); + Q_DECLARE_PERFORMANCE_METRIC(InstrStoreUrl); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreColor); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreDate); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreDateTime); @@ -116,6 +117,7 @@ Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { Q_DEFINE_PERFORMANCE_METRIC(InstrStoreInteger, "StoreInteger"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreBool, "StoreBool"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreString, "StoreString"); + Q_DEFINE_PERFORMANCE_METRIC(InstrStoreUrl, "StoreUrl"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreColor, "StoreColor"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreDate, "StoreDate"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreDateTime, "StoreDateTime"); @@ -337,6 +339,20 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; + case QmlInstruction::StoreUrl: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *target = stack.top(); + void *a[1]; + QUrl u(primitives.at(instr.storeUrl.value)); + a[0] = (void *)&u; + QMetaObject::metacall(target, QMetaObject::WriteProperty, + instr.storeUrl.propertyIndex, a); + } + break; + case QmlInstruction::StoreFloat: { #ifdef Q_ENABLE_PERFORMANCE_LOG diff --git a/src/declarative/qml/qmlvmemetaobject.cpp b/src/declarative/qml/qmlvmemetaobject.cpp index 58708cf..0117448 100644 --- a/src/declarative/qml/qmlvmemetaobject.cpp +++ b/src/declarative/qml/qmlvmemetaobject.cpp @@ -134,6 +134,9 @@ int QmlVMEMetaObject::metaCall(QMetaObject::Call c, int id, void **a) case QVariant::String: *reinterpret_cast(a[0]) = data[propId].toString(); break; + case QVariant::Url: + *reinterpret_cast(a[0]) = data[propId].toUrl(); + break; case QVariant::Color: *reinterpret_cast(a[0]) = data[propId].value(); break; diff --git a/src/declarative/util/qfxview.cpp b/src/declarative/util/qfxview.cpp index 0d5b796..d8d9ba1 100644 --- a/src/declarative/util/qfxview.cpp +++ b/src/declarative/util/qfxview.cpp @@ -84,11 +84,6 @@ static QVariant stringToKeySequence(const QString &str) return QVariant::fromValue(QKeySequence(str)); } -static QVariant stringToUrl(const QString &str) -{ - return QVariant(QUrl(str)); -} - class QFxViewPrivate { public: @@ -166,7 +161,6 @@ void QFxViewPrivate::init() QmlMetaType::registerCustomStringConverter(QVariant::Pixmap, &stringToPixmap); QmlMetaType::registerCustomStringConverter(QVariant::Icon, &stringToIcon); QmlMetaType::registerCustomStringConverter(QVariant::KeySequence, &stringToKeySequence); - QmlMetaType::registerCustomStringConverter(QVariant::Url, &stringToUrl); #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer perf; diff --git a/src/declarative/util/qmlscript.cpp b/src/declarative/util/qmlscript.cpp index 45370e2..e422f37 100644 --- a/src/declarative/util/qmlscript.cpp +++ b/src/declarative/util/qmlscript.cpp @@ -69,7 +69,6 @@ public: void addScriptToEngine(const QString &, const QString &fileName=QString()); QString script; - QString source; QNetworkReply *reply; QUrl url; }; @@ -138,26 +137,26 @@ void QmlScript::setScript(const QString &script) \property QmlScript::source \brief the path to a script file. */ -QString QmlScript::source() const +QUrl QmlScript::source() const { Q_D(const QmlScript); - return d->source; + return d->url; } -void QmlScript::setSource(const QString &source) +void QmlScript::setSource(const QUrl &source) { Q_D(QmlScript); - if (d->source == source) + if (d->url == source) return; - d->source = source; - d->url = qmlContext(this)->resolvedUrl(source); + d->url = source; + Q_ASSERT(!source.isRelative()); #ifndef QT_NO_LOCALFILE_OPTIMIZED_QML if (d->url.scheme() == QLatin1String("file")) { QFile file(d->url.toLocalFile()); file.open(QIODevice::ReadOnly); QByteArray ba = file.readAll(); - d->addScriptToEngine(QString::fromUtf8(ba), d->source); + d->addScriptToEngine(QString::fromUtf8(ba), d->url); } else #endif { @@ -174,7 +173,7 @@ void QmlScript::replyFinished() Q_D(QmlScript); if (!d->reply->error()) { QByteArray ba = d->reply->readAll(); - d->addScriptToEngine(QString::fromUtf8(ba), d->source); + d->addScriptToEngine(QString::fromUtf8(ba), d->url); } d->reply->deleteLater(); d->reply = 0; diff --git a/src/declarative/util/qmlscript.h b/src/declarative/util/qmlscript.h index dc090bc..09ebc2c 100644 --- a/src/declarative/util/qmlscript.h +++ b/src/declarative/util/qmlscript.h @@ -58,7 +58,7 @@ class Q_DECLARATIVE_EXPORT QmlScript : public QObject Q_DECLARE_PRIVATE(QmlScript) Q_PROPERTY(QString script READ script WRITE setScript) - Q_PROPERTY(QString source READ source WRITE setSource) + Q_PROPERTY(QUrl source READ source WRITE setSource) Q_CLASSINFO("DefaultProperty", "script") public: @@ -67,8 +67,8 @@ public: QString script() const; void setScript(const QString &); - QString source() const; - void setSource(const QString &); + QUrl source() const; + void setSource(const QUrl &); private Q_SLOTS: void replyFinished(); diff --git a/tests/auto/declarative/numberformatter/tst_numberformatter.cpp b/tests/auto/declarative/numberformatter/tst_numberformatter.cpp index e70d651..9a2f4f3 100644 --- a/tests/auto/declarative/numberformatter/tst_numberformatter.cpp +++ b/tests/auto/declarative/numberformatter/tst_numberformatter.cpp @@ -1,4 +1,5 @@ #include +#include #include #include #include -- cgit v0.12 From 6b88d7152a72a3a6ba12cb6b4eeeecc1a0c24c51 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 10 Jun 2009 15:03:29 +1000 Subject: Improve list assignment performance --- src/declarative/qml/qmlcompiler.cpp | 68 +++++++++++++++++--- src/declarative/qml/qmlcompiler_p.h | 2 + src/declarative/qml/qmlinstruction_p.h | 4 +- src/declarative/qml/qmlvme.cpp | 110 +++++++++++++++++---------------- 4 files changed, 120 insertions(+), 64 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 04a488d..16e1b13 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -1091,7 +1091,9 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, fetch.line = prop->location.start.line; fetch.type = QmlInstruction::FetchQmlList; fetch.fetchQmlList.property = prop->index; - fetch.fetchQmlList.type = QmlMetaType::qmlListType(t); + int listType = QmlMetaType::qmlListType(t); + bool listTypeIsInterface = QmlMetaType::isInterface(listType); + fetch.fetchQmlList.type = listType; output->bytecode << fetch; for (int ii = 0; ii < prop->values.count(); ++ii) { @@ -1099,10 +1101,23 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, if (v->object) { v->type = Value::CreatedObject; COMPILE_CHECK(compileObject(v->object, ctxt)); - QmlInstruction assign; - assign.type = QmlInstruction::AssignObjectList; - assign.line = prop->location.start.line; - output->bytecode << assign; + + if (!listTypeIsInterface) { + if (canConvert(listType, v->object)) { + QmlInstruction store; + store.type = QmlInstruction::StoreObjectQmlList; + store.line = prop->location.start.line; + output->bytecode << store; + } else { + COMPILE_EXCEPTION("Cannot assign object to list"); + } + + } else { + QmlInstruction assign; + assign.type = QmlInstruction::AssignObjectList; + assign.line = prop->location.start.line; + output->bytecode << assign; + } } else { COMPILE_EXCEPTION("Cannot assign primitives to lists"); } @@ -1116,7 +1131,10 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, QmlInstruction fetch; fetch.type = QmlInstruction::FetchQList; fetch.line = prop->location.start.line; - fetch.fetch.property = prop->index; + fetch.fetchQmlList.property = prop->index; + int listType = QmlMetaType::listType(t); + bool listTypeIsInterface = QmlMetaType::isInterface(listType); + fetch.fetchQmlList.type = listType; output->bytecode << fetch; bool assignedBinding = false; @@ -1125,10 +1143,22 @@ bool QmlCompiler::compileListProperty(QmlParser::Property *prop, if (v->object) { v->type = Value::CreatedObject; COMPILE_CHECK(compileObject(v->object, ctxt)); - QmlInstruction assign; - assign.type = QmlInstruction::AssignObjectList; - assign.line = v->location.start.line; - output->bytecode << assign; + + if (!listTypeIsInterface) { + if (canConvert(listType, v->object)) { + QmlInstruction store; + store.type = QmlInstruction::StoreObjectQList; + store.line = prop->location.start.line; + output->bytecode << store; + } else { + COMPILE_EXCEPTION("Cannot assign object to list"); + } + } else { + QmlInstruction assign; + assign.type = QmlInstruction::AssignObjectList; + assign.line = v->location.start.line; + output->bytecode << assign; + } } else if (v->value.isScript()) { if (assignedBinding) COMPILE_EXCEPTION("Can only assign one binding to lists"); @@ -1575,6 +1605,24 @@ void QmlCompiler::finalizeBinding(const BindingReference &binding) instr.assignBinding.category = QmlMetaProperty::propertyCategory(mp); } +/*! + Returns true if object can be assigned to a (QObject) property of type + convertType. +*/ +bool QmlCompiler::canConvert(int convertType, QmlParser::Object *object) +{ + const QMetaObject *convertTypeMo = + QmlMetaType::rawMetaObjectForType(convertType); + const QMetaObject *objectMo = object->metaObject(); + + while (objectMo) { + if (objectMo == convertTypeMo) + return true; + objectMo = objectMo->superClass(); + } + return false; +} + QmlCompiledData::QmlCompiledData() { } diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index 6b6d8cb..3b1a496 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -179,6 +179,8 @@ private: struct BindingReference; void finalizeBinding(const BindingReference &); + bool canConvert(int, QmlParser::Object *); + struct IdReference { QString id; QmlParser::Object *object; diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index bdbbaff..a1d923d 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -105,8 +105,6 @@ public: StoreSignal, /* storeSignal */ - StoreObjectQmlList, - // XXX need to handle storing objects in variants // @@ -122,6 +120,8 @@ public: BeginObject, /* begin */ CompleteObject, /* complete */ + StoreObjectQmlList, /* NA */ + StoreObjectQList, /* NA */ AssignObjectList, /* NA */ FetchAttached, /* fetchAttached */ diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 9ed7e95..3f7739e 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -87,6 +87,7 @@ Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { Q_DECLARE_PERFORMANCE_METRIC(InstrStoreObject); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreSignal); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreObjectQmlList); + Q_DECLARE_PERFORMANCE_METRIC(InstrStoreObjectQList); Q_DECLARE_PERFORMANCE_METRIC(InstrAssignSignalObject); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreBinding); Q_DECLARE_PERFORMANCE_METRIC(InstrStoreCompiledBinding); @@ -126,6 +127,7 @@ Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { Q_DEFINE_PERFORMANCE_METRIC(InstrStoreObject, "StoreObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreSignal, "StoreSignal"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreObjectQmlList, "StoreObjectQmlList"); + Q_DEFINE_PERFORMANCE_METRIC(InstrStoreObjectQList, "StoreObjectQList"); Q_DEFINE_PERFORMANCE_METRIC(InstrAssignSignalObject, "AssignSignalObject"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreBinding, "StoreBinding"); Q_DEFINE_PERFORMANCE_METRIC(InstrStoreCompiledBinding, "StoreCompiledBinding"); @@ -171,13 +173,18 @@ QmlVME::QmlVME() struct ListInstance { ListInstance() {} + /* ListInstance(const QVariant &l, int t) : list(l), type(t), qmlListInterface(0) {} + */ + ListInstance(QList *q, int t) + : type(t), qListInterface(q) {} ListInstance(QmlPrivate::ListInterface *q, int t) : type(t), qmlListInterface(q) {} - QVariant list; + //QVariant list; int type; + QList *qListInterface; QmlPrivate::ListInterface *qmlListInterface; }; @@ -737,65 +744,56 @@ case QmlInstruction::StoreDouble: } break; + case QmlInstruction::StoreObjectQmlList: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *assign = stack.pop(); + const ListInstance &list = qliststack.top(); + + void *d = (void *)&assign; + list.qmlListInterface->append(d); + } + break; + + case QmlInstruction::StoreObjectQList: + { +#ifdef Q_ENABLE_PERFORMANCE_LOG + QFxCompilerTimer cc; +#endif + QObject *assign = stack.pop(); + + const ListInstance &list = qliststack.top(); + list.qListInterface->append((void *)assign); + } + break; + case QmlInstruction::AssignObjectList: { + // This is only used for assigning interfaces #ifdef Q_ENABLE_PERFORMANCE_LOG QFxCompilerTimer cc; #endif QObject *assign = stack.pop(); const ListInstance &list = qliststack.top(); - if (list.qmlListInterface) { - int type = list.type; - - void *d = 0; - void *ptr = 0; - bool found = false; - - if (QmlMetaType::isInterface(type)) { - const char *iid = QmlMetaType::interfaceIId(type); - if (iid) - ptr = assign->qt_metacast(iid); - if (ptr) { - d = &ptr; - found = true; - } - } else { - const QMetaObject *mo = - QmlMetaType::rawMetaObjectForType(type); - - const QMetaObject *assignMo = assign->metaObject(); - while(!found && assignMo) { - if (assignMo == mo) - found = true; - else - assignMo = assignMo->superClass(); - } - - // NOTE: This assumes a cast to QObject does not alter - // the object pointer - d = (void *)&assign; - } + int type = list.type; - if (!found) - VME_EXCEPTION("Cannot assign object to list"); + void *ptr = 0; - list.qmlListInterface->append(d); + const char *iid = QmlMetaType::interfaceIId(type); + if (iid) + ptr = assign->qt_metacast(iid); + if (!ptr) + VME_EXCEPTION("Cannot assign object to list"); + + if (list.qmlListInterface) { + void *d = (void *)&ptr; + list.qmlListInterface->append(d); } else { - int type = list.type; - - if (QmlMetaType::isInterface(type)) { - void *ptr = 0; - const char *iid = QmlMetaType::interfaceIId(type); - if (iid) - ptr = assign->qt_metacast(iid); - QVariant v(list.type, &ptr); - QmlMetaType::append(list.list, v); - } else { - QVariant v = QmlMetaType::fromObject(assign, list.type); - QmlMetaType::append(list.list, v); - } + list.qListInterface->append(ptr); } } break; @@ -883,10 +881,18 @@ case QmlInstruction::StoreDouble: QFxCompilerTimer cc; #endif QObject *target = stack.top(); - QMetaProperty prop = - target->metaObject()->property(instr.fetch.property); - QVariant v = prop.read(target); - qliststack.push(ListInstance(v, QmlMetaType::listType(prop.userType()))); + + void *a[1]; + // We know that QList* can be converted to + // QList* + QList *list = 0; + a[0] = &list; + QMetaObject::metacall(target, QMetaObject::ReadProperty, + instr.fetchQmlList.property, a); + if (!list) + VME_EXCEPTION("Cannot assign to null list"); + + qliststack.push(ListInstance(list, instr.fetchQmlList.type)); } break; -- cgit v0.12 From 4f40fa9b92f6f31f5a6d584f8890e2331b68f3bc Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 10 Jun 2009 15:07:51 +1000 Subject: Remove perf metrics These numbers were always too small to be measured meaningfully in this way. --- src/declarative/qml/qmlvme.cpp | 209 ----------------------------------------- 1 file changed, 209 deletions(-) diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 3f7739e..28b880c 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -66,91 +66,6 @@ #include QT_BEGIN_NAMESPACE -Q_DECLARE_PERFORMANCE_LOG(QFxCompiler) { - Q_DECLARE_PERFORMANCE_METRIC(InstrCreateObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrCreateCustomObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrSetId); - Q_DECLARE_PERFORMANCE_METRIC(InstrSetDefault); - Q_DECLARE_PERFORMANCE_METRIC(InstrCreateComponent); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreMetaObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreReal); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreInteger); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreBool); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreString); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreColor); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreDate); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreDateTime); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreTime); - Q_DECLARE_PERFORMANCE_METRIC(InstrStorePoint); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreSize); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreVariant); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreSignal); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreObjectQmlList); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreObjectQList); - Q_DECLARE_PERFORMANCE_METRIC(InstrAssignSignalObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreBinding); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreCompiledBinding); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreValueSource); - Q_DECLARE_PERFORMANCE_METRIC(InstrBeginObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrCompleteObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrAssignObjectList); - Q_DECLARE_PERFORMANCE_METRIC(InstrFetchAttached); - Q_DECLARE_PERFORMANCE_METRIC(InstrFetchQmlList); - Q_DECLARE_PERFORMANCE_METRIC(InstrFetchQList); - Q_DECLARE_PERFORMANCE_METRIC(InstrFetchObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrPopFetchedObject); - Q_DECLARE_PERFORMANCE_METRIC(InstrPopQList); - Q_DECLARE_PERFORMANCE_METRIC(InstrPushProperty); - Q_DECLARE_PERFORMANCE_METRIC(InstrStoreStackObject); - Q_DECLARE_PERFORMANCE_METRIC(Dummy); -} - -Q_DEFINE_PERFORMANCE_LOG(QFxCompiler, "QFxCompiler") { - Q_DEFINE_PERFORMANCE_METRIC(InstrCreateObject, "CreateObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrCreateCustomObject, "CreateCustomObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrSetId, "SetId"); - Q_DEFINE_PERFORMANCE_METRIC(InstrSetDefault, "SetDefault"); - Q_DEFINE_PERFORMANCE_METRIC(InstrCreateComponent, "CreateComponent"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreMetaObject, "StoreMetaObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreReal, "StoreReal"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreInteger, "StoreInteger"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreBool, "StoreBool"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreString, "StoreString"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreColor, "StoreColor"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreDate, "StoreDate"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreDateTime, "StoreDateTime"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreTime, "StoreTime"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStorePoint, "StorePoint(F)"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreSize, "StoreSize(F)"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreVariant, "StoreVariant"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreObject, "StoreObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreSignal, "StoreSignal"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreObjectQmlList, "StoreObjectQmlList"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreObjectQList, "StoreObjectQList"); - Q_DEFINE_PERFORMANCE_METRIC(InstrAssignSignalObject, "AssignSignalObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreBinding, "StoreBinding"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreCompiledBinding, "StoreCompiledBinding"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreValueSource, "StoreValueSource"); - Q_DEFINE_PERFORMANCE_METRIC(InstrBeginObject, "BeginObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrCompleteObject, "CompleteObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrAssignObjectList, "AssignObjectList"); - Q_DEFINE_PERFORMANCE_METRIC(InstrFetchAttached, "FetchAttached"); - Q_DEFINE_PERFORMANCE_METRIC(InstrFetchQmlList, "FetchQmlList"); - Q_DEFINE_PERFORMANCE_METRIC(InstrFetchQList, "FetchQList"); - Q_DEFINE_PERFORMANCE_METRIC(InstrFetchObject, "FetchObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrPopFetchedObject, "PopFetchedObject"); - Q_DEFINE_PERFORMANCE_METRIC(InstrPopQList, "PopQList"); - Q_DEFINE_PERFORMANCE_METRIC(InstrPushProperty, "PushProperty"); - Q_DEFINE_PERFORMANCE_METRIC(InstrStoreStackObject, "StoreStackObject"); - Q_DEFINE_PERFORMANCE_METRIC(Dummy, "Dummy"); -} - -static inline int qIndexOfProperty(QObject *o, const char *name) -{ - int idx = o->metaObject()->indexOfProperty(name); - return idx; -} QmlVME::QmlVME() { @@ -207,9 +122,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in const QList &floatData = comp->floatData; -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxPerfTimer cr; -#endif QmlEnginePrivate::SimpleList bindValues; QmlEnginePrivate::SimpleList parserStatus; @@ -245,9 +157,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::CreateObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *o = types.at(instr.create.type).createInstance(QmlContext::activeContext()); if (!o) { if(types.at(instr.create.type).component) @@ -271,9 +180,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::SetId: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QmlContext *ctxt = QmlContext::activeContext(); @@ -287,9 +193,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::SetDefault: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QmlContext::activeContext()->addDefaultObject(target); } @@ -297,9 +200,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::CreateComponent: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *qcomp = new QmlComponent(ctxt->engine(), comp, ii + 1, instr.createComponent.count, stack.isEmpty() ? 0 : stack.top()); stack.push(qcomp); ii += instr.createComponent.count; @@ -308,9 +208,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::StoreMetaObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); new QmlVMEMetaObject(target, synthesizedMetaObjects.at(instr.storeMeta.data), &comp->primitives, instr.storeMeta.slotData, comp); } @@ -318,9 +215,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::StoreVariant: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; // XXX - can be more efficient @@ -333,9 +227,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::StoreString: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; a[0] = (void *)&primitives.at(instr.storeString.value); @@ -346,9 +237,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::StoreFloat: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); float f = instr.storeFloat.value; void *a[1]; @@ -360,9 +248,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in case QmlInstruction::StoreDouble: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); double d = instr.storeDouble.value; void *a[1]; @@ -374,9 +259,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreBool: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; a[0] = (void *)&instr.storeBool.value; @@ -387,9 +269,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreInteger: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; a[0] = (void *)&instr.storeInteger.value; @@ -400,9 +279,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreColor: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QColor c = QColor::fromRgba(instr.storeColor.value); @@ -414,9 +290,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreDate: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QDate d = QDate::fromJulianDay(instr.storeDate.value); @@ -428,9 +301,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreTime: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - //QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QTime t; @@ -446,9 +316,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreDateTime: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - //QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QTime t; @@ -465,9 +332,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StorePoint: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QPoint p = QPointF(floatData.at(instr.storeRealPair.valueIndex), @@ -480,9 +344,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StorePointF: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QPointF p(floatData.at(instr.storeRealPair.valueIndex), @@ -495,9 +356,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreSize: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QSize p = QSizeF(floatData.at(instr.storeRealPair.valueIndex), @@ -510,9 +368,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreSizeF: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QSizeF s(floatData.at(instr.storeRealPair.valueIndex), @@ -525,9 +380,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreRect: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - //QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QRect r = QRectF(floatData.at(instr.storeRect.valueIndex), @@ -542,9 +394,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreRectF: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - //QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; QRectF r(floatData.at(instr.storeRect.valueIndex), @@ -559,9 +408,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *assignObj = stack.pop(); QObject *target = stack.top(); @@ -597,9 +443,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::AssignSignalObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif // XXX optimize QObject *assign = stack.pop(); @@ -629,9 +472,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreSignal: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); // XXX scope QMetaMethod signal = @@ -647,9 +487,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::BeginObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QmlParserStatus *status = reinterpret_cast(reinterpret_cast(target) + instr.begin.castValue); parserStatus.append(status); @@ -661,9 +498,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::CompleteObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QmlParserStatus *status = reinterpret_cast(reinterpret_cast(target) + instr.complete.castValue); status->classComplete(); @@ -672,9 +506,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::PushProperty: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QmlMetaProperty mp(target, instr.pushProperty.property, QmlMetaProperty::Object); @@ -684,9 +515,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreCompiledBinding: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QObject *context = stack.at(stack.count() - 1 - instr.assignBinding.context); @@ -708,9 +536,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreBinding: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QObject *context = stack.at(stack.count() - 1 - instr.assignBinding.context); @@ -732,9 +557,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreValueSource: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *assign = stack.pop(); QmlPropertyValueSource *vs = static_cast(assign); @@ -746,9 +568,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreObjectQmlList: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *assign = stack.pop(); const ListInstance &list = qliststack.top(); @@ -759,9 +578,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::StoreObjectQList: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *assign = stack.pop(); const ListInstance &list = qliststack.top(); @@ -772,9 +588,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::AssignObjectList: { // This is only used for assigning interfaces -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *assign = stack.pop(); const ListInstance &list = qliststack.top(); @@ -840,9 +653,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::FetchAttached: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QObject *qmlObject = qmlAttachedPropertiesObjectById(instr.fetchAttached.id, target); @@ -856,9 +666,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::FetchQmlList: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; @@ -877,9 +684,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::FetchQList: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); void *a[1]; @@ -898,9 +702,6 @@ case QmlInstruction::StoreDouble: case QmlInstruction::FetchObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif QObject *target = stack.top(); QObject *obj = 0; @@ -930,28 +731,18 @@ case QmlInstruction::StoreDouble: case QmlInstruction::PopQList: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif qliststack.pop(); } break; case QmlInstruction::PopFetchedObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif stack.pop(); } break; case QmlInstruction::StoreStackObject: { -#ifdef Q_ENABLE_PERFORMANCE_LOG - QFxCompilerTimer cc; -#endif - const QmlMetaProperty &prop = pushedProperties.at(instr.assignStackObject.property); QObject *obj = savedObjects[instr.assignStackObject.object]; -- cgit v0.12 From 5419a744c830003cb2e93e5de731e684a67930a2 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Wed, 10 Jun 2009 15:59:41 +1000 Subject: Ideas for full module support. --- doc/src/declarative/modules.qdoc | 94 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) diff --git a/doc/src/declarative/modules.qdoc b/doc/src/declarative/modules.qdoc index 5933223..d84ad46 100644 --- a/doc/src/declarative/modules.qdoc +++ b/doc/src/declarative/modules.qdoc @@ -20,3 +20,97 @@ the component issuing the import. The import statement cannot be used by remote content. */ + +/* + +Ideas for full module support.... + + +* Modularity within applications + +This is the currently-supported mechanism. + +By using the "import" statement, a subdirectory of types can be added to the +empty namespace. Alternatively, a type in a subdirectory can be referenced +explicitly: + + ./SubModule1/Type1.qml + ./SubModule2/Type1.qml + import "SubModule1" + Type1 { ... } + SubModule2.Type1 { ... } + + +* System-installed modules (dependencies) + +To use system-installed modules, the dependency must be explicitly stated +using the "require" statement. Types in required modules must still be +explicitly qualified. Dependencies cannot be added to the empty namespace. + + QMLPATH=/opt/Nokia/qml:/usr/share/lib/qml + /opt/Nokia/qml/Module1/Type1.qml + /usr/share/lib/qml/Module1/Type1.qml + require "Module1" + Module1.Type1 { ... } + + +* Grouping of components within application modules + +Sub-sub directories allow further grouping of types. + + ./SubModule1/Group1/*.qml + ./SubModule1/Group2/*.qml + + SubModule1.Group1.Type1 { ... } + SubModule1.Group1.Type2 { ... } + SubModule1.Group2.Type1 { ... } + SubModule1.Group2.Type2 { ... } + + import "SubModule1/Group1" + Type1 { ... } + + import "SubModule1" + Group1.Type1 { ... } + + +* Grouping of components within system-installed modules + +System-installed types may also be grouped into types. The hierarchy is a +global namespace, so such grouping is recommended to reduce clashes. + + /opt/Nokia/qml/Module1/Group1/*.qml + /opt/Nokia/qml/Module1/Group2/*.qml + + require "Module1" + Module1.Group1.Type1 { ... } + Module1.Group1.Type2 { ... } + Module1.Group2.Type1 { ... } + Module1.Group2.Type2 { ... } + + require "Module1/Group1" + Group1.Type1 { ... } + + // Alternative syntax + /opt/qml/com/nokia/qml/Module1/Group1/*.qml + require "com.nokia.qml.Module1.Group1" + Group1.Type1 { ... } + + +* Private sub-components + +Directories begining with _ cannot be referenced except by types in the +directory immediately containing it. + + /opt/Nokia/qml/Module1/_private/Type1.qml + ./SubModule1/_private/Type1.qml + + SubModule1._private.Type1 { ... } // Not allowed + import "SubModule1._private" // Not allowed + require "SubModule1._private" // Not allowed + require "SubModule1" + Module1._private.Type1 { ... } // Not allowed + + import "_private" // allowed + Type1 { ... } + +*/ -- cgit v0.12 From 73fa8dd86f14ab161c84fa9224cd4335f352ba75 Mon Sep 17 00:00:00 2001 From: Jason McDonald Date: Wed, 10 Jun 2009 16:10:21 +1000 Subject: Fix license headers for QStringBuilder. Only release branches are allowed to have the Commercial usage header. All other branches must have the No Commercial Usage header. Reviewed-by: Trust Me --- src/corelib/tools/qstringbuilder.cpp | 12 ++++++------ src/corelib/tools/qstringbuilder.h | 12 ++++++------ 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/corelib/tools/qstringbuilder.cpp b/src/corelib/tools/qstringbuilder.cpp index 03d8160..740deb4 100644 --- a/src/corelib/tools/qstringbuilder.cpp +++ b/src/corelib/tools/qstringbuilder.cpp @@ -3,14 +3,14 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Commercial License Agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Nokia. +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser diff --git a/src/corelib/tools/qstringbuilder.h b/src/corelib/tools/qstringbuilder.h index 2c31476..30a7c67 100644 --- a/src/corelib/tools/qstringbuilder.h +++ b/src/corelib/tools/qstringbuilder.h @@ -3,14 +3,14 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ -** Commercial Usage -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Commercial License Agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Nokia. +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser -- cgit v0.12 From df4763878d756fe1f5bcfe6b7dd8cf91cdd091e1 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Wed, 10 Jun 2009 16:11:05 +1000 Subject: doc --- doc/src/declarative/modules.qdoc | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/doc/src/declarative/modules.qdoc b/doc/src/declarative/modules.qdoc index d84ad46..194be40 100644 --- a/doc/src/declarative/modules.qdoc +++ b/doc/src/declarative/modules.qdoc @@ -32,10 +32,15 @@ This is the currently-supported mechanism. By using the "import" statement, a subdirectory of types can be added to the empty namespace. Alternatively, a type in a subdirectory can be referenced -explicitly: +explicitly. + +So, given these files: ./SubModule1/Type1.qml ./SubModule2/Type1.qml + +This is valid QML: + import "SubModule1" Type1 { ... } SubModule2.Type1 { ... } @@ -50,6 +55,7 @@ explicitly qualified. Dependencies cannot be added to the empty namespace. QMLPATH=/opt/Nokia/qml:/usr/share/lib/qml /opt/Nokia/qml/Module1/Type1.qml /usr/share/lib/qml/Module1/Type1.qml + require "Module1" Module1.Type1 { ... } -- cgit v0.12 From b2edf6ee037decf53c7d2698863ba63742317acc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 10 Jun 2009 10:21:19 +0200 Subject: Fixed clipping bug in raster paint engine causing rendering artifacts. The artifacts were visible in the mainwindow demo when dragging the top toolbar separator left and right. We need to check that rect clipping is actually activated before we compare the new clip rect with the old, otherwise the clip type and clip bound flags won't get updated. --- src/gui/painting/qpaintengine_raster.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 0810bb9..7ed2dfd 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -4311,7 +4311,7 @@ QClipData::QClipData(int height) clipSpanHeight = height; m_clipLines = 0; - allocated = height; + allocated = 0; m_spans = 0; xmin = xmax = ymin = ymax = 0; count = 0; @@ -4479,7 +4479,7 @@ void QClipData::fixup() */ void QClipData::setClipRect(const QRect &rect) { - if (rect == clipRect) + if (hasRectClip && rect == clipRect) return; // qDebug() << "setClipRect" << clipSpanHeight << count << allocated << rect; -- cgit v0.12 From 52ee3d6525e2b271fc50103001f9d71d681b6afe Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 10 Jun 2009 18:29:12 +1000 Subject: Source location isn't needed for compiled bindings --- src/declarative/qml/qmlvme.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index cdc6a66..3a66c69 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -541,7 +541,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QFx_setParent_noEvent(bind, target); bind->setTarget(mp); - bind->setSourceLocation(comp->url, instr.line); } break; -- cgit v0.12 From f0f12f3d1ad2041c57095edaa7683c5d3599a3e6 Mon Sep 17 00:00:00 2001 From: Jason McDonald Date: Wed, 10 Jun 2009 18:47:49 +1000 Subject: Fix some incorrect license headers. The MODULE placeholder shouldn't be used anymore, and neither should the old Trolltech license header. Reviewed-by: Trust Me --- doc/src/diagrams/programs/easingcurve/main.cpp | 36 +++++++++++++++++++++-- src/gui/math3d/qgenericmatrix.cpp | 2 +- src/gui/math3d/qgenericmatrix.h | 2 +- src/gui/math3d/qmatrix4x4.cpp | 2 +- src/gui/math3d/qmatrix4x4.h | 2 +- src/gui/math3d/qquaternion.cpp | 2 +- src/gui/math3d/qquaternion.h | 2 +- src/gui/math3d/qvector2d.cpp | 2 +- src/gui/math3d/qvector2d.h | 2 +- src/gui/math3d/qvector3d.cpp | 2 +- src/gui/math3d/qvector3d.h | 2 +- src/gui/math3d/qvector4d.cpp | 2 +- src/gui/math3d/qvector4d.h | 2 +- tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp | 2 +- tests/auto/math3d/qquaternion/tst_qquaternion.cpp | 2 +- tests/auto/math3d/qvectornd/tst_qvectornd.cpp | 2 +- tests/auto/math3d/shared/math3dincludes.h | 2 +- 17 files changed, 49 insertions(+), 19 deletions(-) diff --git a/doc/src/diagrams/programs/easingcurve/main.cpp b/doc/src/diagrams/programs/easingcurve/main.cpp index 98e9d37..8d399a3 100644 --- a/doc/src/diagrams/programs/easingcurve/main.cpp +++ b/doc/src/diagrams/programs/easingcurve/main.cpp @@ -1,11 +1,41 @@ /**************************************************************************** ** -** Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies). +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the examples of the Qt Toolkit. ** -** $TROLLTECH_DUAL_LICENSE$ +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ ** ****************************************************************************/ diff --git a/src/gui/math3d/qgenericmatrix.cpp b/src/gui/math3d/qgenericmatrix.cpp index 6ecd878..19a0f6e 100644 --- a/src/gui/math3d/qgenericmatrix.cpp +++ b/src/gui/math3d/qgenericmatrix.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qgenericmatrix.h b/src/gui/math3d/qgenericmatrix.h index b4d3707..330ded2 100644 --- a/src/gui/math3d/qgenericmatrix.h +++ b/src/gui/math3d/qgenericmatrix.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qmatrix4x4.cpp b/src/gui/math3d/qmatrix4x4.cpp index 8ef4da3..a69b9df 100644 --- a/src/gui/math3d/qmatrix4x4.cpp +++ b/src/gui/math3d/qmatrix4x4.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qmatrix4x4.h b/src/gui/math3d/qmatrix4x4.h index ba7f67f..da1bcba 100644 --- a/src/gui/math3d/qmatrix4x4.h +++ b/src/gui/math3d/qmatrix4x4.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qquaternion.cpp b/src/gui/math3d/qquaternion.cpp index 96659ea..03f626a 100644 --- a/src/gui/math3d/qquaternion.cpp +++ b/src/gui/math3d/qquaternion.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qquaternion.h b/src/gui/math3d/qquaternion.h index c05c641..b17cf73 100644 --- a/src/gui/math3d/qquaternion.h +++ b/src/gui/math3d/qquaternion.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qvector2d.cpp b/src/gui/math3d/qvector2d.cpp index c3aaa42..df2519d 100644 --- a/src/gui/math3d/qvector2d.cpp +++ b/src/gui/math3d/qvector2d.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qvector2d.h b/src/gui/math3d/qvector2d.h index b027df4..2be0a11 100644 --- a/src/gui/math3d/qvector2d.h +++ b/src/gui/math3d/qvector2d.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qvector3d.cpp b/src/gui/math3d/qvector3d.cpp index c83cd60..a5f5c5b 100644 --- a/src/gui/math3d/qvector3d.cpp +++ b/src/gui/math3d/qvector3d.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qvector3d.h b/src/gui/math3d/qvector3d.h index 02873f2..480667a 100644 --- a/src/gui/math3d/qvector3d.h +++ b/src/gui/math3d/qvector3d.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qvector4d.cpp b/src/gui/math3d/qvector4d.cpp index 010fa53..c5124e2 100644 --- a/src/gui/math3d/qvector4d.cpp +++ b/src/gui/math3d/qvector4d.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/src/gui/math3d/qvector4d.h b/src/gui/math3d/qvector4d.h index 8e673f3..e38f4e5 100644 --- a/src/gui/math3d/qvector4d.h +++ b/src/gui/math3d/qvector4d.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the QtGui module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp b/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp index 4d51e89..dd3e396 100644 --- a/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp +++ b/tests/auto/math3d/qmatrixnxn/tst_qmatrixnxn.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/tests/auto/math3d/qquaternion/tst_qquaternion.cpp b/tests/auto/math3d/qquaternion/tst_qquaternion.cpp index f25f858..5d70e4d 100644 --- a/tests/auto/math3d/qquaternion/tst_qquaternion.cpp +++ b/tests/auto/math3d/qquaternion/tst_qquaternion.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/tests/auto/math3d/qvectornd/tst_qvectornd.cpp b/tests/auto/math3d/qvectornd/tst_qvectornd.cpp index a092fb0..f7d2411 100644 --- a/tests/auto/math3d/qvectornd/tst_qvectornd.cpp +++ b/tests/auto/math3d/qvectornd/tst_qvectornd.cpp @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage diff --git a/tests/auto/math3d/shared/math3dincludes.h b/tests/auto/math3d/shared/math3dincludes.h index 1ac0c08..a77090b 100644 --- a/tests/auto/math3d/shared/math3dincludes.h +++ b/tests/auto/math3d/shared/math3dincludes.h @@ -3,7 +3,7 @@ ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Qt Software Information (qt-info@nokia.com) ** -** This file is part of the $MODULE$ of the Qt Toolkit. +** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage -- cgit v0.12 From d0d89a49a7c1e5f302a8606448fc5defdb327a25 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 10 Jun 2009 18:51:21 +1000 Subject: Minor cleanups --- src/declarative/qml/qmlbindablevalue.cpp | 28 +++--- src/declarative/qml/qmlmetaproperty.cpp | 162 +------------------------------ 2 files changed, 13 insertions(+), 177 deletions(-) diff --git a/src/declarative/qml/qmlbindablevalue.cpp b/src/declarative/qml/qmlbindablevalue.cpp index de01387..d111bbb 100644 --- a/src/declarative/qml/qmlbindablevalue.cpp +++ b/src/declarative/qml/qmlbindablevalue.cpp @@ -179,34 +179,29 @@ void QmlBindableValue::update() } } else if (d->property.propertyCategory() == QmlMetaProperty::Bindable) { - // NOTE: We assume that only core properties can have - // propertyType == Bindable int idx = d->property.coreIndex(); Q_ASSERT(idx != -1); void *a[1]; QmlBindableValue *t = this; a[0] = (void *)&t; - d->property.object()->qt_metacall(QMetaObject::WriteProperty, - idx, a); + QMetaObject::metacall(d->property.object(), + QMetaObject::WriteProperty, + idx, a); } else if (d->property.propertyCategory() == QmlMetaProperty::Object) { QVariant value = this->value(); - if ((int)value.type() != qMetaTypeId()) { - if (scriptWarnings()) { - if (!value.isValid()) { - qWarning() << "QmlBindableValue: Unable to assign invalid value to object property"; - } else { - qWarning() << "QmlBindableValue: Unable to assign non-object to object property"; - } - } + + QObject *obj = QmlMetaType::toQObject(value); + + if (!obj) { + if (scriptWarnings()) + qWarning() << "QmlBindableValue: Unable to assign non-object to object property"; return; } - // NOTE: This assumes a cast to QObject does not alter the - // object pointer - QObject *obj = *(QObject **)value.data(); + // XXX This isn't type safe // NOTE: We assume that only core properties can have // propertyType == Object @@ -220,7 +215,8 @@ void QmlBindableValue::update() } else if (d->property.propertyCategory() == QmlMetaProperty::Normal) { QVariant value = this->value(); - if (d->property.propertyType() == QVariant::Url && value.canConvert(QVariant::String) && !value.isNull()) { + if (d->property.propertyType() == QVariant::Url && + value.canConvert(QVariant::String) && !value.isNull()) { // Must resolve first value.setValue(context()->resolvedUrl(value.toString())); } diff --git a/src/declarative/qml/qmlmetaproperty.cpp b/src/declarative/qml/qmlmetaproperty.cpp index 4f39ebc..5cddf3d 100644 --- a/src/declarative/qml/qmlmetaproperty.cpp +++ b/src/declarative/qml/qmlmetaproperty.cpp @@ -813,168 +813,8 @@ void QmlMetaProperty::write(const QVariant &value) const } else if (prop.name()) { - if (prop.isEnumType()) { - QVariant v = value; - if (value.type() == QVariant::Double) { //enum values come through the script engine as doubles - double integral; - double fractional = modf(value.toDouble(), &integral); - if (qFuzzyCompare(fractional, (double)0.0)) - v.convert(QVariant::Int); - } - prop.write(object(), v); - } else { - if (!value.isValid()) - return; - - int t = propertyType(); - int vt = value.type(); - - if (vt == t || - value.userType() == t) { - - void *a[1]; - a[0] = (void *)value.constData(); - QMetaObject::metacall(object(), QMetaObject::WriteProperty, d->coreIdx, a); - - } else if (qMetaTypeId() == t) { - - prop.write(object(), value); - - } else if (propertyCategory() == Object) { - - QObject *o = QmlMetaType::toQObject(value); - if (o) - prop.write(object(), QmlMetaType::fromObject(o, propertyType())); - - } else if (propertyCategory() == List) { - - int listType = QmlMetaType::listType(t); - if (value.userType() == qMetaTypeId >()) { - const QList &list = - qvariant_cast >(value); - QVariant listVar = prop.read(object()); - QmlMetaType::clear(listVar); - for (int ii = 0; ii < list.count(); ++ii) { - QVariant v = QmlMetaType::fromObject(list.at(ii), listType); - QmlMetaType::append(listVar, v); - } - - } else if (vt == listType || - value.userType() == listType) { - QVariant listVar = prop.read(object()); - if (!QmlMetaType::append(listVar, value)) { - qWarning() << "QmlMetaProperty: Unable to assign object to list"; - } - } - } else if (propertyCategory() == QmlList) { - // XXX - optimize! - QVariant list = prop.read(object()); - QmlPrivate::ListInterface *li = - *(QmlPrivate::ListInterface **)list.constData(); - - int type = li->type(); - - if (QObject *obj = QmlMetaType::toQObject(value)) { - const QMetaObject *mo = - QmlMetaType::rawMetaObjectForType(type); - - const QMetaObject *objMo = obj->metaObject(); - bool found = false; - while(!found && objMo) { - if (objMo == mo) - found = true; - else - objMo = objMo->superClass(); - } - - if (!found) { - qWarning() << "Unable to assign object to list"; - return; - } - - // NOTE: This assumes a cast to QObject does not alter - // the object pointer - void *d = (void *)&obj; - li->append(d); - } - } else if (propertyCategory() == Normal) { - - switch(t) { - case QVariant::Double: - { - double dd; - bool found = true; - if (vt == QVariant::Int) { - dd = value.toInt(); - } else if (vt == QVariant::UInt) { - dd = value.toUInt(); - } else { - found = false; - } - - if (found) { - void *a[1]; - a[0] = ⅆ - QMetaObject::metacall(object(), - QMetaObject::WriteProperty, - d->coreIdx, a); - return; - } - } - break; - - case QVariant::Int: - { - int i; - bool found = true; - if (vt == QVariant::Double) { - i = (int)value.toDouble(); - } else if (vt == QVariant::UInt) { - i = (int)value.toUInt(); - } else { - found = false; - } - - if (found) { - void *a[1]; - a[0] = &i; - QMetaObject::metacall(object(), - QMetaObject::WriteProperty, - d->coreIdx, a); - return; - } - } - break; - - case QVariant::String: - { - QString s; - bool found = true; - if (vt == QVariant::ByteArray) { - s = QLatin1String(value.toByteArray()); - } else { - found = false; - } - - if (found) { - void *a[1]; - a[0] = &s; - QMetaObject::metacall(object(), - QMetaObject::WriteProperty, - d->coreIdx, a); - return; - } - } - break; + d->writeValueProperty(value); - - default: - break; - } - prop.write(object(), value); - } - - } } } -- cgit v0.12 From 8b75843c44df306cf5003980f4563d0759dffe7e Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Wed, 10 Jun 2009 10:54:11 +0200 Subject: Fix tst_QGraphicsProxyWidget::scrollUpdate test, wrong test. It should not be necessary to adjust the expose rectangle by 1 in all directions; the expose has already been adjusted by the scene and view. Reviewed-by: bnilsen --- tests/auto/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/auto/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp b/tests/auto/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp index d856024..fa0e035 100644 --- a/tests/auto/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp +++ b/tests/auto/qgraphicsproxywidget/tst_qgraphicsproxywidget.cpp @@ -1487,7 +1487,7 @@ void tst_QGraphicsProxyWidget::scrollUpdate() QVector() << QRect(0, 0, 200, 12) << QRect(0, 12, 102, 10)); QCOMPARE(widget->npaints, 2); QCOMPARE(widget->paintEventRegion.rects(), - QVector() << QRect(0, 0, 200, 13) << QRect(0, 13, 103, 10)); + QVector() << QRect(0, 0, 200, 12) << QRect(0, 12, 102, 10)); } void tst_QGraphicsProxyWidget::setWidget_simple() -- cgit v0.12 From f6f89890d032317d16cda7726b4d9f97c12d661d Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 10 Jun 2009 19:12:41 +1000 Subject: Simplify QmlBindableValue by using the logic already present in QmlMetaProperty --- src/declarative/qml/qmlbindablevalue.cpp | 84 +--------- src/declarative/qml/qmlmetaproperty.cpp | 274 +++++++++++++++++-------------- 2 files changed, 151 insertions(+), 207 deletions(-) diff --git a/src/declarative/qml/qmlbindablevalue.cpp b/src/declarative/qml/qmlbindablevalue.cpp index d111bbb..293c3a8 100644 --- a/src/declarative/qml/qmlbindablevalue.cpp +++ b/src/declarative/qml/qmlbindablevalue.cpp @@ -125,59 +125,7 @@ void QmlBindableValue::update() if (!d->updating) { d->updating = true; - if (d->property.propertyCategory() == QmlMetaProperty::List) { - QVariant value = this->value(); - int listType = QmlMetaType::listType(d->property.propertyType()); - - if (value.userType() == qMetaTypeId >()) { - const QList &list = - qvariant_cast >(value); - QVariant listVar = d->property.read(); - QmlMetaType::clear(listVar); - for (int ii = 0; ii < list.count(); ++ii) { - QVariant v = QmlMetaType::fromObject(list.at(ii), listType); - QmlMetaType::append(listVar, v); - } - - } else if (value.type() == uint(listType) || - value.userType() == listType) { - QVariant listVar = d->property.read(); - QmlMetaType::clear(listVar); - QmlMetaType::append(listVar, value); - } - } else if (d->property.propertyCategory() == QmlMetaProperty::QmlList) { - // XXX - optimize! - QVariant value = this->value(); - QVariant list = d->property.read(); - QmlPrivate::ListInterface *li = - *(QmlPrivate::ListInterface **)list.constData(); - - int type = li->type(); - - if (QObject *obj = QmlMetaType::toQObject(value)) { - const QMetaObject *mo = - QmlMetaType::rawMetaObjectForType(type); - - const QMetaObject *objMo = obj->metaObject(); - bool found = false; - while(!found && objMo) { - if (objMo == mo) - found = true; - else - objMo = objMo->superClass(); - } - - if (!found) { - qWarning() << "Unable to assign object to list"; - return; - } - - // NOTE: This assumes a cast to QObject does not alter - // the object pointer - void *d = (void *)&obj; - li->append(d); - } - } else if (d->property.propertyCategory() == QmlMetaProperty::Bindable) { + if (d->property.propertyCategory() == QmlMetaProperty::Bindable) { int idx = d->property.coreIndex(); Q_ASSERT(idx != -1); @@ -189,37 +137,13 @@ void QmlBindableValue::update() QMetaObject::WriteProperty, idx, a); - } else if (d->property.propertyCategory() == QmlMetaProperty::Object) { + } else { QVariant value = this->value(); - - QObject *obj = QmlMetaType::toQObject(value); - - if (!obj) { - if (scriptWarnings()) - qWarning() << "QmlBindableValue: Unable to assign non-object to object property"; - return; - } - - // XXX This isn't type safe - - // NOTE: We assume that only core properties can have - // propertyType == Object - int idx = d->property.coreIndex(); - Q_ASSERT(idx != -1); - - void *a[1]; - a[0] = (void *)&obj; - d->property.object()->qt_metacall(QMetaObject::WriteProperty, - idx, a); - - } else if (d->property.propertyCategory() == QmlMetaProperty::Normal) { - QVariant value = this->value(); if (d->property.propertyType() == QVariant::Url && - value.canConvert(QVariant::String) && !value.isNull()) { - // Must resolve first + value.canConvert(QVariant::String) && !value.isNull()) value.setValue(context()->resolvedUrl(value.toString())); - } + d->property.write(value); } diff --git a/src/declarative/qml/qmlmetaproperty.cpp b/src/declarative/qml/qmlmetaproperty.cpp index 5cddf3d..a152807 100644 --- a/src/declarative/qml/qmlmetaproperty.cpp +++ b/src/declarative/qml/qmlmetaproperty.cpp @@ -646,159 +646,179 @@ void QmlMetaPropertyPrivate::writeValueProperty(const QVariant &value) v.convert(QVariant::Int); } prop.write(object, v); - } else { - if (!value.isValid()) + return; + } + + if (!value.isValid()) + return; + + int t = propertyType(); + int vt = value.userType(); + int category = propertyCategory(); + + if (vt == t) { + + void *a[1]; + a[0] = (void *)value.constData(); + QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, a); + + } else if (qMetaTypeId() == t) { + + prop.write(object, value); + + } else if (category == QmlMetaProperty::Object) { + + QObject *o = QmlMetaType::toQObject(value); + + if (!o) return; - int t = propertyType(); - int vt = value.type(); + const QMetaObject *valMo = o->metaObject(); + const QMetaObject *propMo = QmlMetaType::rawMetaObjectForType(t); - if (vt == t || - value.userType() == t) { + while (valMo) { + if (valMo == propMo) + break; + valMo = valMo->superClass(); + } - void *a[1]; - a[0] = (void *)value.constData(); - QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, a); + if (valMo) { - } else if (qMetaTypeId() == t) { + void *args[] = { &o, 0 }; + QMetaObject::metacall(object, QMetaObject::WriteProperty, coreIdx, + args); - prop.write(object, value); + } - } else if (propertyCategory() == QmlMetaProperty::Object) { + } else if (category == QmlMetaProperty::List) { - QObject *o = QmlMetaType::toQObject(value); - if (o) - prop.write(object, QmlMetaType::fromObject(o, propertyType())); + int listType = QmlMetaType::listType(t); - } else if (propertyCategory() == QmlMetaProperty::List) { + if (value.userType() == qMetaTypeId >()) { + const QList &list = + qvariant_cast >(value); + QVariant listVar = prop.read(object); + QmlMetaType::clear(listVar); + for (int ii = 0; ii < list.count(); ++ii) { + QVariant v = QmlMetaType::fromObject(list.at(ii), listType); + QmlMetaType::append(listVar, v); + } - int listType = QmlMetaType::listType(t); - if (value.userType() == qMetaTypeId >()) { - const QList &list = - qvariant_cast >(value); - QVariant listVar = prop.read(object); - QmlMetaType::clear(listVar); - for (int ii = 0; ii < list.count(); ++ii) { - QVariant v = QmlMetaType::fromObject(list.at(ii), listType); - QmlMetaType::append(listVar, v); - } + } else if (vt == listType || + value.userType() == listType) { + QVariant listVar = prop.read(object); + QmlMetaType::clear(listVar); + QmlMetaType::append(listVar, value); + } + } else if (category == QmlMetaProperty::QmlList) { + + // XXX - optimize! + QVariant list = prop.read(object); + QmlPrivate::ListInterface *li = + *(QmlPrivate::ListInterface **)list.constData(); + + int type = li->type(); + + if (QObject *obj = QmlMetaType::toQObject(value)) { + const QMetaObject *mo = + QmlMetaType::rawMetaObjectForType(type); + + const QMetaObject *objMo = obj->metaObject(); + bool found = false; + while(!found && objMo) { + if (objMo == mo) + found = true; + else + objMo = objMo->superClass(); + } - } else if (vt == listType || - value.userType() == listType) { - QVariant listVar = prop.read(object); - if (!QmlMetaType::append(listVar, value)) { - qWarning() << "QmlMetaProperty: Unable to assign object to list"; - } + if (!found) { + qWarning() << "Unable to assign object to list"; + return; } - } else if (propertyCategory() == QmlMetaProperty::QmlList) { - // XXX - optimize! - QVariant list = prop.read(object); - QmlPrivate::ListInterface *li = - *(QmlPrivate::ListInterface **)list.constData(); - - int type = li->type(); - - if (QObject *obj = QmlMetaType::toQObject(value)) { - const QMetaObject *mo = - QmlMetaType::rawMetaObjectForType(type); - - const QMetaObject *objMo = obj->metaObject(); - bool found = false; - while(!found && objMo) { - if (objMo == mo) - found = true; - else - objMo = objMo->superClass(); + + // NOTE: This assumes a cast to QObject does not alter + // the object pointer + void *d = (void *)&obj; + li->append(d); + } + } else if (category == QmlMetaProperty::Normal) { + + switch(t) { + case QVariant::Double: + { + double d; + bool found = true; + if (vt == QVariant::Int) { + d = value.toInt(); + } else if (vt == QVariant::UInt) { + d = value.toUInt(); + } else { + found = false; } - if (!found) { - qWarning() << "Unable to assign object to list"; + if (found) { + void *a[1]; + a[0] = &d; + QMetaObject::metacall(object, + QMetaObject::WriteProperty, + coreIdx, a); return; } - - // NOTE: This assumes a cast to QObject does not alter - // the object pointer - void *d = (void *)&obj; - li->append(d); } - } else if (propertyCategory() == QmlMetaProperty::Normal) { - - switch(t) { - case QVariant::Double: - { - double d; - bool found = true; - if (vt == QVariant::Int) { - d = value.toInt(); - } else if (vt == QVariant::UInt) { - d = value.toUInt(); - } else { - found = false; - } - - if (found) { - void *a[1]; - a[0] = &d; - QMetaObject::metacall(object, - QMetaObject::WriteProperty, - coreIdx, a); - return; - } + break; + + case QVariant::Int: + { + int i; + bool found = true; + if (vt == QVariant::Double) { + i = (int)value.toDouble(); + } else if (vt == QVariant::UInt) { + i = (int)value.toUInt(); + } else { + found = false; } - break; - case QVariant::Int: - { - int i; - bool found = true; - if (vt == QVariant::Double) { - i = (int)value.toDouble(); - } else if (vt == QVariant::UInt) { - i = (int)value.toUInt(); - } else { - found = false; - } - - if (found) { - void *a[1]; - a[0] = &i; - QMetaObject::metacall(object, - QMetaObject::WriteProperty, - coreIdx, a); - return; - } + if (found) { + void *a[1]; + a[0] = &i; + QMetaObject::metacall(object, + QMetaObject::WriteProperty, + coreIdx, a); + return; + } + } + break; + + case QVariant::String: + { + QString s; + bool found = true; + if (vt == QVariant::ByteArray) { + s = QLatin1String(value.toByteArray()); + } else { + found = false; } - break; - case QVariant::String: - { - QString s; - bool found = true; - if (vt == QVariant::ByteArray) { - s = QLatin1String(value.toByteArray()); - } else { - found = false; - } - - if (found) { - void *a[1]; - a[0] = &s; - QMetaObject::metacall(object, - QMetaObject::WriteProperty, - coreIdx, a); - return; - } + if (found) { + void *a[1]; + a[0] = &s; + QMetaObject::metacall(object, + QMetaObject::WriteProperty, + coreIdx, a); + return; } - break; + } + break; - default: - break; - } - prop.write(object, value); + default: + break; } - + prop.write(object, value); } + } /*! -- cgit v0.12 From 0bae9bea91f4fcf087edd6d5b2af5c9e1658fb4a Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 10 Jun 2009 19:16:35 +1000 Subject: Remove dead code --- src/declarative/qml/qmlbindablevalue.cpp | 6 ------ src/declarative/qml/qmlbindablevalue.h | 1 - 2 files changed, 7 deletions(-) diff --git a/src/declarative/qml/qmlbindablevalue.cpp b/src/declarative/qml/qmlbindablevalue.cpp index 293c3a8..e1b6961 100644 --- a/src/declarative/qml/qmlbindablevalue.cpp +++ b/src/declarative/qml/qmlbindablevalue.cpp @@ -58,12 +58,6 @@ QmlBindableValuePrivate::QmlBindableValuePrivate() } QML_DEFINE_NOCREATE_TYPE(QmlBindableValue); -QmlBindableValue::QmlBindableValue(QObject *parent) -: QmlPropertyValueSource(*new QmlBindableValuePrivate, parent) -{ - qFatal("QmlBindableValue: Default constructor not supported"); -} - QmlBindableValue::QmlBindableValue(void *data, QmlRefCount *rc, QObject *obj, QObject *parent) : QmlPropertyValueSource(*new QmlBindableValuePrivate, parent), QmlExpression(QmlContext::activeContext(), data, rc, obj) { diff --git a/src/declarative/qml/qmlbindablevalue.h b/src/declarative/qml/qmlbindablevalue.h index 71a7051..f54481a 100644 --- a/src/declarative/qml/qmlbindablevalue.h +++ b/src/declarative/qml/qmlbindablevalue.h @@ -62,7 +62,6 @@ class Q_DECLARATIVE_EXPORT QmlBindableValue : public QmlPropertyValueSource, { Q_OBJECT public: - QmlBindableValue(QObject *parent); QmlBindableValue(const QString &, QObject *, QObject *parent=0); QmlBindableValue(void *, QmlRefCount *, QObject *, QObject *parent); ~QmlBindableValue(); -- cgit v0.12 From c0bbe44ab6290dee088138c01724779026d2c033 Mon Sep 17 00:00:00 2001 From: Erik Verbruggen Date: Wed, 10 Jun 2009 12:02:29 +0200 Subject: Changed the QML parser and the AST to store the position of comma tokens of QML arrays. Also exposed these positions through the QML DOM. --- src/declarative/qml/parser/javascript.g | 9 +++--- src/declarative/qml/parser/javascriptast.cpp | 12 ++++++- src/declarative/qml/parser/javascriptast_p.h | 37 ++++++++++++++++++++-- src/declarative/qml/parser/javascriptastfwd_p.h | 1 + .../qml/parser/javascriptastvisitor_p.h | 2 ++ src/declarative/qml/parser/javascriptparser.cpp | 9 +++--- src/declarative/qml/parser/javascriptparser_p.h | 1 + src/declarative/qml/qmldom.cpp | 10 ++++++ src/declarative/qml/qmldom.h | 2 ++ src/declarative/qml/qmlparser_p.h | 1 + src/declarative/qml/qmlscriptparser.cpp | 18 ++++++++++- 11 files changed, 90 insertions(+), 12 deletions(-) diff --git a/src/declarative/qml/parser/javascript.g b/src/declarative/qml/parser/javascript.g index 8cabeea..884d814 100644 --- a/src/declarative/qml/parser/javascript.g +++ b/src/declarative/qml/parser/javascript.g @@ -568,15 +568,16 @@ case $rule_number: { UiArrayMemberList: UiObjectDefinition ; /. case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); } break; ./ UiArrayMemberList: UiArrayMemberList T_COMMA UiObjectDefinition ; /. case $rule_number: { - AST::UiObjectMemberList *node = makeAstNode (driver->nodePool(), - sym(1).UiObjectMemberList, sym(3).UiObjectMember); + AST::UiArrayMemberList *node = makeAstNode (driver->nodePool(), + sym(1).UiArrayMemberList, sym(3).UiObjectMember); + node->commaToken = loc(2); sym(1).Node = node; } break; ./ @@ -616,7 +617,7 @@ UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ; /. case $rule_number: { AST::UiArrayBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), - sym(4).UiObjectMemberList->finish()); + sym(4).UiArrayMemberList->finish()); node->colonToken = loc(2); node->lbracketToken = loc(3); node->rbracketToken = loc(5); diff --git a/src/declarative/qml/parser/javascriptast.cpp b/src/declarative/qml/parser/javascriptast.cpp index 130229b..ada19d5 100644 --- a/src/declarative/qml/parser/javascriptast.cpp +++ b/src/declarative/qml/parser/javascriptast.cpp @@ -893,7 +893,7 @@ void UiArrayBinding::accept0(Visitor *visitor) { if (visitor->visit(this)) { acceptChild(qualifiedId, visitor); - for (UiObjectMemberList *it = members; it; it = it->next) + for (UiArrayMemberList *it = members; it; it = it->next) acceptChild(it->member, visitor); } @@ -910,6 +910,16 @@ void UiObjectMemberList::accept0(Visitor *visitor) visitor->endVisit(this); } +void UiArrayMemberList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + for (UiArrayMemberList *it = this; it; it = it->next) + acceptChild(it->member, visitor); + } + + visitor->endVisit(this); +} + void UiQualifiedId::accept0(Visitor *visitor) { if (visitor->visit(this)) { diff --git a/src/declarative/qml/parser/javascriptast_p.h b/src/declarative/qml/parser/javascriptast_p.h index 23d59e5..8c1e2bc 100644 --- a/src/declarative/qml/parser/javascriptast_p.h +++ b/src/declarative/qml/parser/javascriptast_p.h @@ -207,6 +207,7 @@ public: Kind_UiObjectDefinition, Kind_UiObjectInitializer, Kind_UiObjectMemberList, + Kind_UiArrayMemberList, Kind_UiProgram, Kind_UiPublicMember, Kind_UiQualifiedId, @@ -2301,6 +2302,38 @@ public: UiObjectMember *member; }; +class UiArrayMemberList: public Node +{ +public: + JAVASCRIPT_DECLARE_AST_NODE(UiArrayMemberList) + + UiArrayMemberList(UiObjectMember *member) + : next(this), member(member) + { kind = K; } + + UiArrayMemberList(UiArrayMemberList *previous, UiObjectMember *member) + : member(member) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual void accept0(Visitor *visitor); + + UiArrayMemberList *finish() + { + UiArrayMemberList *head = next; + next = 0; + return head; + } + +// attributes + UiArrayMemberList *next; + UiObjectMember *member; + SourceLocation commaToken; +}; + class UiObjectInitializer: public Node { public: @@ -2481,7 +2514,7 @@ public: JAVASCRIPT_DECLARE_AST_NODE(UiArrayBinding) UiArrayBinding(UiQualifiedId *qualifiedId, - UiObjectMemberList *members) + UiArrayMemberList *members) : qualifiedId(qualifiedId), members(members) { kind = K; } @@ -2496,7 +2529,7 @@ public: // attributes UiQualifiedId *qualifiedId; - UiObjectMemberList *members; + UiArrayMemberList *members; SourceLocation colonToken; SourceLocation lbracketToken; SourceLocation rbracketToken; diff --git a/src/declarative/qml/parser/javascriptastfwd_p.h b/src/declarative/qml/parser/javascriptastfwd_p.h index 822a2d7..23270e5 100644 --- a/src/declarative/qml/parser/javascriptastfwd_p.h +++ b/src/declarative/qml/parser/javascriptastfwd_p.h @@ -174,6 +174,7 @@ class UiSourceElement; class UiArrayBinding; class UiObjectMember; class UiObjectMemberList; +class UiArrayMemberList; class UiQualifiedId; } } // namespace AST diff --git a/src/declarative/qml/parser/javascriptastvisitor_p.h b/src/declarative/qml/parser/javascriptastvisitor_p.h index 81df364..7c73e43 100644 --- a/src/declarative/qml/parser/javascriptastvisitor_p.h +++ b/src/declarative/qml/parser/javascriptastvisitor_p.h @@ -80,6 +80,7 @@ public: virtual bool visit(UiScriptBinding *) { return true; } virtual bool visit(UiArrayBinding *) { return true; } virtual bool visit(UiObjectMemberList *) { return true; } + virtual bool visit(UiArrayMemberList *) { return true; } virtual bool visit(UiQualifiedId *) { return true; } virtual void endVisit(UiProgram *) {} @@ -93,6 +94,7 @@ public: virtual void endVisit(UiScriptBinding *) {} virtual void endVisit(UiArrayBinding *) {} virtual void endVisit(UiObjectMemberList *) {} + virtual void endVisit(UiArrayMemberList *) {} virtual void endVisit(UiQualifiedId *) {} // JavaScript diff --git a/src/declarative/qml/parser/javascriptparser.cpp b/src/declarative/qml/parser/javascriptparser.cpp index 34ecd0e..bbffc4f 100644 --- a/src/declarative/qml/parser/javascriptparser.cpp +++ b/src/declarative/qml/parser/javascriptparser.cpp @@ -239,12 +239,13 @@ case 10: { } break; case 11: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); } break; case 12: { - AST::UiObjectMemberList *node = makeAstNode (driver->nodePool(), - sym(1).UiObjectMemberList, sym(3).UiObjectMember); + AST::UiArrayMemberList *node = makeAstNode (driver->nodePool(), + sym(1).UiArrayMemberList, sym(3).UiObjectMember); + node->commaToken = loc(2); sym(1).Node = node; } break; @@ -270,7 +271,7 @@ case 15: { case 17: { AST::UiArrayBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), - sym(4).UiObjectMemberList->finish()); + sym(4).UiArrayMemberList->finish()); node->colonToken = loc(2); node->lbracketToken = loc(3); node->rbracketToken = loc(5); diff --git a/src/declarative/qml/parser/javascriptparser_p.h b/src/declarative/qml/parser/javascriptparser_p.h index 2ae4c34..b6a2432 100644 --- a/src/declarative/qml/parser/javascriptparser_p.h +++ b/src/declarative/qml/parser/javascriptparser_p.h @@ -117,6 +117,7 @@ public: AST::UiArrayBinding *UiArrayBinding; AST::UiObjectMember *UiObjectMember; AST::UiObjectMemberList *UiObjectMemberList; + AST::UiArrayMemberList *UiArrayMemberList; AST::UiQualifiedId *UiQualifiedId; }; diff --git a/src/declarative/qml/qmldom.cpp b/src/declarative/qml/qmldom.cpp index e06afb5..d2608c8 100644 --- a/src/declarative/qml/qmldom.cpp +++ b/src/declarative/qml/qmldom.cpp @@ -1449,6 +1449,16 @@ int QmlDomList::length() const return 0; } +/*! + Returns a list of positions of the commas in the QML file. +*/ +QList QmlDomList:: commaPositions() const +{ + if (d && d->property) + return d->property->listCommaPositions; + else + return QList(); +} /*! \class QmlDomComponent diff --git a/src/declarative/qml/qmldom.h b/src/declarative/qml/qmldom.h index 442a4fc..fde35a8 100644 --- a/src/declarative/qml/qmldom.h +++ b/src/declarative/qml/qmldom.h @@ -268,6 +268,8 @@ public: int position() const; int length() const; + QList commaPositions() const; + private: friend class QmlDomValue; QSharedDataPointer d; diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h index 7989933..1481391 100644 --- a/src/declarative/qml/qmlparser_p.h +++ b/src/declarative/qml/qmlparser_p.h @@ -277,6 +277,7 @@ namespace QmlParser LocationSpan location; LocationRange listValueRange; + QList listCommaPositions; void dump(int = 0) const; }; diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index cab7915..ee2981e 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -649,7 +649,20 @@ bool ProcessAST::visit(AST::ExpressionStatement *node) return true; } -// UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiObjectMemberList T_RBRACKET ; +static QList collectCommas(AST::UiArrayMemberList *members) +{ + QList commas; + + if (members) { + for (AST::UiArrayMemberList *it = members->next; it; it = it->next) { + commas.append(it->commaToken.offset); + } + } + + return commas; +} + +// UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ; bool ProcessAST::visit(AST::UiArrayBinding *node) { int propertyCount = 0; @@ -667,6 +680,9 @@ bool ProcessAST::visit(AST::UiArrayBinding *node) prop->listValueRange.offset = node->lbracketToken.offset; prop->listValueRange.length = node->rbracketToken.offset + node->rbracketToken.length - node->lbracketToken.offset; + // Store the positions of the comma token too, again for the DOM to be able to retreive it. + prop->listCommaPositions = collectCommas(node->members); + while (propertyCount--) _stateStack.pop(); -- cgit v0.12 From f2c4d2fe8a846cfce457512ef1806a7276745590 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Wed, 10 Jun 2009 12:10:33 +0200 Subject: qdoc: Added new class names for different tables. class="valuelist" is for the table used for enum types. class="alignedsummary" is for summary sections aligned on the name. class="propsummary" is for the property summary section. class="toc" is used for tables of contents. class="generic" is used for all other tables. We might need to break this down more. --- tools/qdoc3/htmlgenerator.cpp | 53 +++++++++++++++++++++++++++---------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index fb33de4..44401ed 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -678,13 +678,17 @@ int HtmlGenerator::generateAtom(const Atom *atom, else if (atom->string() == ATOM_LIST_VALUE) { threeColumnEnumValueTable = isThreeColumnEnumValueTable(atom); if (threeColumnEnumValueTable) { - out() << "

      \n" - "" - "\n"; + out() << "

      ConstantValueDescription
      \n" + << "" + << "" + << "\n"; } else { - out() << "

      ConstantValueDescription
      \n" - << "\n"; + out() << "

      ConstantValue
      \n" + << "\n"; } } else { @@ -858,14 +862,17 @@ int HtmlGenerator::generateAtom(const Atom *atom, } if (!atom->string().isEmpty()) { if (atom->string().contains("%")) - out() << "

      ConstantValue
      string() << "\" " + out() << "

      string() << "\" " << "align=\"center\" cellpadding=\"2\" " << "cellspacing=\"1\" border=\"0\">\n"; - else - out() << "

      \n"; + else { + out() << "

      \n"; + } } else { - out() << "

      \n"; + out() << "

      \n"; } numTableRows = 0; break; @@ -1577,7 +1584,8 @@ void HtmlGenerator::generateTableOfContents(const Node *node, QString tdTag; if (numColumns > 1) { tdTag = "
      "; - out() << "

      \n" << tdTag << "\n"; + out() << "

      \n" + << tdTag << "\n"; } // disable nested links in table of contents @@ -1596,7 +1604,8 @@ void HtmlGenerator::generateTableOfContents(const Node *node, out() << "
        "; sectionNumber.append("1"); } while (sectionNumber.size() < nextLevel); - } else { + } + else { while (sectionNumber.size() > nextLevel) { out() << "
      \n"; sectionNumber.removeLast(); @@ -1804,10 +1813,13 @@ void HtmlGenerator::generateClassHierarchy(const Node *relative, } } -void HtmlGenerator::generateAnnotatedList(const Node *relative, CodeMarker *marker, - const QMap &nodeMap) +void +HtmlGenerator::generateAnnotatedList(const Node *relative, + CodeMarker *marker, + const QMap&nodeMap) { - out() << "

      \n"; + out() << "

      \n"; int row = 0; foreach (const QString &name, nodeMap.keys()) { @@ -1960,7 +1972,7 @@ void HtmlGenerator::generateCompactList(const Node *relative, CodeMarker *marker } firstOffset[NumColumns] = classMap.count(); - out() << "

      \n"; + out() << "

      \n"; for (k = 0; k < numRows; k++) { out() << "\n"; for (i = 0; i < NumColumns; i++) { @@ -2213,12 +2225,12 @@ void HtmlGenerator::generateSectionList(const Section& section, name_alignment = false; } if (name_alignment) { - out() << "
      \n"; } else { if (twoColumn) - out() << "

      \n" << "
      "; @@ -2513,12 +2525,13 @@ void HtmlGenerator::generateSectionList(const Section& section, bool twoColumn = false; if (style == CodeMarker::SeparateList) { twoColumn = (section.members.count() >= 16); - } else if (section.members.first()->type() == Node::Property) { + } + else if (section.members.first()->type() == Node::Property) { twoColumn = (section.members.count() >= 5); } if (twoColumn) - out() << "

      \n" + out() << "

      \n" << ""; if (qpgn->isDefault()) { - out() << "
      " + out() << "
      "; out() << "
        \n"; -- cgit v0.12 From 8179a9e2cd52b24c70b194106dd170ed1bb677e4 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 10 Jun 2009 12:54:53 +0200 Subject: small code cleanup that improves some loops it uses les foreach --- src/gui/itemviews/qabstractitemview.cpp | 4 ++-- src/gui/itemviews/qsortfilterproxymodel.cpp | 7 ++++--- src/gui/itemviews/qstandarditemmodel.cpp | 4 ++-- src/gui/itemviews/qtreeview.cpp | 6 ++++-- src/gui/kernel/qaction.cpp | 25 +++++++++++++++++-------- src/gui/kernel/qwidgetaction.cpp | 4 ++-- src/gui/widgets/qdockarealayout.cpp | 8 ++++---- src/gui/widgets/qdockwidget.cpp | 7 ++++--- src/gui/widgets/qmenubar.cpp | 6 ++++-- 9 files changed, 43 insertions(+), 28 deletions(-) diff --git a/src/gui/itemviews/qabstractitemview.cpp b/src/gui/itemviews/qabstractitemview.cpp index c90216b..d353c2d 100644 --- a/src/gui/itemviews/qabstractitemview.cpp +++ b/src/gui/itemviews/qabstractitemview.cpp @@ -2398,8 +2398,8 @@ void QAbstractItemView::updateEditorGeometries() //we release the editor outside of the loop because it might change the focus and try //to change the d->editors list. - foreach(QWidget *editor, editorsToRelease) { - d->releaseEditor(editor); + for (int i = 0; i < editorsToRelease.count(); ++i) { + d->releaseEditor(editorsToRelease.at(i)); } } diff --git a/src/gui/itemviews/qsortfilterproxymodel.cpp b/src/gui/itemviews/qsortfilterproxymodel.cpp index 96eb6f0..4021c83 100644 --- a/src/gui/itemviews/qsortfilterproxymodel.cpp +++ b/src/gui/itemviews/qsortfilterproxymodel.cpp @@ -884,8 +884,8 @@ void QSortFilterProxyModelPrivate::proxy_item_range( { proxy_low = INT_MAX; proxy_high = INT_MIN; - foreach (int source_item, source_items) { - int proxy_item = source_to_proxy.at(source_item); + for (int i = 0; i < source_items.count(); ++i) { + int proxy_item = source_to_proxy.at(source_items.at(i)); Q_ASSERT(proxy_item != -1); if (proxy_item < proxy_low) proxy_low = proxy_item; @@ -985,7 +985,8 @@ QSet QSortFilterProxyModelPrivate::handle_filter_changed( Q_Q(QSortFilterProxyModel); // Figure out which mapped items to remove QVector source_items_remove; - foreach (int source_item, proxy_to_source) { + for (int i = 0; i < proxy_to_source.count(); ++i) { + const int source_item = proxy_to_source.at(i); if ((orient == Qt::Vertical) ? !q->filterAcceptsRow(source_item, source_parent) : !q->filterAcceptsColumn(source_item, source_parent)) { diff --git a/src/gui/itemviews/qstandarditemmodel.cpp b/src/gui/itemviews/qstandarditemmodel.cpp index d8adbd2..9d0f796 100644 --- a/src/gui/itemviews/qstandarditemmodel.cpp +++ b/src/gui/itemviews/qstandarditemmodel.cpp @@ -2907,8 +2907,8 @@ QMimeData *QStandardItemModel::mimeData(const QModelIndexList &indexes) const QStack stack; itemsSet.reserve(indexes.count()); stack.reserve(indexes.count()); - foreach (const QModelIndex &index, indexes) { - QStandardItem *item = itemFromIndex(index); + for (int i = 0; i < indexes.count(); ++i) { + QStandardItem *item = itemFromIndex(indexes.at(i)); itemsSet << item; stack.push(item); } diff --git a/src/gui/itemviews/qtreeview.cpp b/src/gui/itemviews/qtreeview.cpp index 7837700..965a5c7 100644 --- a/src/gui/itemviews/qtreeview.cpp +++ b/src/gui/itemviews/qtreeview.cpp @@ -2072,7 +2072,8 @@ QModelIndex QTreeView::moveCursor(CursorAction cursorAction, Qt::KeyboardModifie const bool useTopIndex = (cursorAction == MoveUp || cursorAction == MovePrevious); int index = useTopIndex ? INT_MAX : INT_MIN; const QItemSelection selection = d->selectionModel->selection(); - foreach (const QItemSelectionRange &range, selection) { + for (int i = 0; i < selection.count(); ++i) { + const QItemSelectionRange &range = selection.at(i); int candidate = d->viewIndex(useTopIndex ? range.topLeft() : range.bottomRight()); if (candidate >= 0) index = useTopIndex ? qMin(index, candidate) : qMax(index, candidate); @@ -3558,7 +3559,8 @@ QList > QTreeViewPrivate::columnRanges(const QModelIndex &topInd QPair current; current.first = -2; // -1 is not enough because -1+1 = 0 current.second = -2; - foreach (int logicalColumn, logicalIndexes) { + for(int i = 0; i < logicalIndexes.count(); ++i) { + const int logicalColumn = logicalIndexes.at(i); if (current.second + 1 != logicalColumn) { if (current.first != -2) { //let's save the current one diff --git a/src/gui/kernel/qaction.cpp b/src/gui/kernel/qaction.cpp index 051b6a6..f44d207 100644 --- a/src/gui/kernel/qaction.cpp +++ b/src/gui/kernel/qaction.cpp @@ -136,25 +136,31 @@ void QActionPrivate::redoGrab(QShortcutMap &map) void QActionPrivate::redoGrabAlternate(QShortcutMap &map) { Q_Q(QAction); - foreach (int id, alternateShortcutIds) - if (id) + for(int i = 0; i < alternateShortcutIds.count(); ++i) { + if (const int id = alternateShortcutIds.at(i)) map.removeShortcut(id, q); + } alternateShortcutIds.clear(); if (alternateShortcuts.isEmpty()) return; - foreach (const QKeySequence& alternate, alternateShortcuts) { + for(int i = 0; i < alternateShortcuts.count(); ++i) { + const QKeySequence& alternate = alternateShortcuts.at(i); if (!alternate.isEmpty()) alternateShortcutIds.append(map.addShortcut(q, alternate, shortcutContext)); else alternateShortcutIds.append(0); } if (!enabled) { - foreach (int id, alternateShortcutIds) + for(int i = 0; i < alternateShortcutIds.count(); ++i) { + const int id = alternateShortcutIds.at(i); map.setShortcutEnabled(false, id, q); + } } if (!autorepeat) { - foreach (int id, alternateShortcutIds) + for(int i = 0; i < alternateShortcutIds.count(); ++i) { + const int id = alternateShortcutIds.at(i); map.setShortcutAutoRepeat(false, id, q); + } } } @@ -163,9 +169,10 @@ void QActionPrivate::setShortcutEnabled(bool enable, QShortcutMap &map) Q_Q(QAction); if (shortcutId) map.setShortcutEnabled(enable, shortcutId, q); - foreach (int id, alternateShortcutIds) - if (id) + for(int i = 0; i < alternateShortcutIds.count(); ++i) { + if (const int id = alternateShortcutIds.at(i)) map.setShortcutEnabled(enable, id, q); + } } #endif // QT_NO_SHORTCUT @@ -615,8 +622,10 @@ QAction::~QAction() #ifndef QT_NO_SHORTCUT if (d->shortcutId && qApp) { qApp->d_func()->shortcutMap.removeShortcut(d->shortcutId, this); - foreach (int id, d->alternateShortcutIds) + for(int i = 0; i < d->alternateShortcutIds.count(); ++i) { + const int id = d->alternateShortcutIds.at(i); qApp->d_func()->shortcutMap.removeShortcut(id, this); + } } #endif } diff --git a/src/gui/kernel/qwidgetaction.cpp b/src/gui/kernel/qwidgetaction.cpp index efdde5e..cd12029 100644 --- a/src/gui/kernel/qwidgetaction.cpp +++ b/src/gui/kernel/qwidgetaction.cpp @@ -228,8 +228,8 @@ bool QWidgetAction::event(QEvent *event) if (event->type() == QEvent::ActionChanged) { if (d->defaultWidget) d->defaultWidget->setEnabled(isEnabled()); - foreach (QWidget *w, d->createdWidgets) - w->setEnabled(isEnabled()); + for (int i = 0; i < d->createdWidgets.count(); ++i) + d->createdWidgets.at(i)->setEnabled(isEnabled()); } return QAction::event(event); } diff --git a/src/gui/widgets/qdockarealayout.cpp b/src/gui/widgets/qdockarealayout.cpp index 4f0ec1e..58e8f9c 100644 --- a/src/gui/widgets/qdockarealayout.cpp +++ b/src/gui/widgets/qdockarealayout.cpp @@ -2202,8 +2202,8 @@ QSet QDockAreaLayoutInfo::usedSeparatorWidgets() const { QSet result; - foreach (QWidget *sepWidget, separatorWidgets) - result << sepWidget; + for (int i = 0; i < separatorWidgets.count(); ++i) + result << separatorWidgets.at(i); for (int i = 0; i < item_list.count(); ++i) { const QDockAreaLayoutItem &item = item_list.at(i); @@ -3244,8 +3244,8 @@ QSet QDockAreaLayout::usedSeparatorWidgets() const { QSet result; - foreach (QWidget *sepWidget, separatorWidgets) - result << sepWidget; + for (int i = 0; i < separatorWidgets.count(); ++i) + result << separatorWidgets.at(i); for (int i = 0; i < QInternal::DockCount; ++i) { const QDockAreaLayoutInfo &dock = docks[i]; result += dock.usedSeparatorWidgets(); diff --git a/src/gui/widgets/qdockwidget.cpp b/src/gui/widgets/qdockwidget.cpp index d573b8b..6a0c879 100644 --- a/src/gui/widgets/qdockwidget.cpp +++ b/src/gui/widgets/qdockwidget.cpp @@ -221,7 +221,8 @@ void QDockWidgetLayout::addItem(QLayoutItem*) QLayoutItem *QDockWidgetLayout::itemAt(int index) const { int cnt = 0; - foreach (QLayoutItem *item, item_list) { + for (int i = 0; i < item_list.count(); ++i) { + QLayoutItem *item = item_list.at(i); if (item == 0) continue; if (index == cnt++) @@ -250,8 +251,8 @@ QLayoutItem *QDockWidgetLayout::takeAt(int index) int QDockWidgetLayout::count() const { int result = 0; - foreach (QLayoutItem *item, item_list) { - if (item != 0) + for (int i = 0; i < item_list.count(); ++i) { + if (item_list.at(i)) ++result; } return result; diff --git a/src/gui/widgets/qmenubar.cpp b/src/gui/widgets/qmenubar.cpp index cffc3d5..fc7e901 100644 --- a/src/gui/widgets/qmenubar.cpp +++ b/src/gui/widgets/qmenubar.cpp @@ -220,7 +220,8 @@ void QMenuBarPrivate::updateGeometries() //we try to see if the actions will fit there bool hasHiddenActions = false; - foreach(QAction *action, actionList) { + for (int i = 0; i < actionList.count(); ++i) { + QAction *action = actionList.at(i); if (!menuRect.contains(actionRect(action))) { hasHiddenActions = true; break; @@ -230,7 +231,8 @@ void QMenuBarPrivate::updateGeometries() //...and if not, determine the ones that fit on the menu with the extension visible if (hasHiddenActions) { menuRect = this->menuRect(true); - foreach(QAction *action, actionList) { + for (int i = 0; i < actionList.count(); ++i) { + QAction *action = actionList.at(i); if (!menuRect.contains(actionRect(action))) { hiddenActions.append(action); } -- cgit v0.12 From 4a6548b83a6f1df42b82664efaca26c7efbc1909 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Wed, 10 Jun 2009 13:21:33 +0200 Subject: qdoc: Fix broken XHTML output. --- tools/qdoc3/htmlgenerator.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index c507f6c..eb8e65c 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -3456,7 +3456,9 @@ void HtmlGenerator::generateDetailedQmlMember(const Node *node, generateQmlItem(qpn, relative, marker, false); out() << "
      " + << "" + << "

      " << "
      " << "" << "
      " -- cgit v0.12 From 53632d45ca64ad4c20d4302e0826c0234877dd69 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Wed, 10 Jun 2009 13:26:23 +0200 Subject: Revert "implement equality operator in a more sane way" This reverts commit 07dca7a30d4bd1efd8032915700420cca3fd60fa. Move the equality operator code back in (qFuzzyCompare) to avoid breaking many autotests. The change should go back in later on, possibly supplemented by a qFuzzyCompare(QTransform) function. But until we can figure out how to not break everything this patch has to wait. Reviewed-by: Lars --- src/gui/painting/qtransform.cpp | 14 +++++--------- 1 file changed, 5 insertions(+), 9 deletions(-) diff --git a/src/gui/painting/qtransform.cpp b/src/gui/painting/qtransform.cpp index bd2ea31..86e594c 100644 --- a/src/gui/painting/qtransform.cpp +++ b/src/gui/painting/qtransform.cpp @@ -700,15 +700,11 @@ QTransform & QTransform::rotateRadians(qreal a, Qt::Axis axis) */ bool QTransform::operator==(const QTransform &o) const { - return affine._m11 == o.affine._m11 && - affine._m12 == o.affine._m12 && - affine._m21 == o.affine._m21 && - affine._m22 == o.affine._m22 && - affine._dx == o.affine._dx && - affine._dy == o.affine._dy && - m_13 == o.m_13 && - m_23 == o.m_23 && - m_33 == o.m_33; +#define qFZ qFuzzyCompare + return qFZ(affine._m11, o.affine._m11) && qFZ(affine._m12, o.affine._m12) && qFZ(m_13, o.m_13) + && qFZ(affine._m21, o.affine._m21) && qFZ(affine._m22, o.affine._m22) && qFZ(m_23, o.m_23) + && qFZ(affine._dx, o.affine._dx) && qFZ(affine._dy, o.affine._dy) && qFZ(m_33, o.m_33); +#undef qFZ } /*! -- cgit v0.12 From 62725a02652cee576efe055d1371765945045026 Mon Sep 17 00:00:00 2001 From: Thomas Zander Date: Wed, 10 Jun 2009 13:31:06 +0200 Subject: add some api docs to clarify what collate does --- src/gui/painting/qprinter.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/gui/painting/qprinter.cpp b/src/gui/painting/qprinter.cpp index ba208fd..ce33893 100644 --- a/src/gui/painting/qprinter.cpp +++ b/src/gui/painting/qprinter.cpp @@ -1308,6 +1308,9 @@ void QPrinter::setNumCopies(int numCopies) Returns true if collation is turned on when multiple copies is selected. Returns false if it is turned off when multiple copies is selected. + When collating is turned off the printing of each individual page will be repeated + the numCopies() amount before the next page is started. With collating turned on + all pages are printed before the next copy of those pages is started. \sa setCollateCopies() */ -- cgit v0.12 From 14f72183fbe1c7fad7c5434b2af032cc51436f5e Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Wed, 10 Jun 2009 14:08:23 +0200 Subject: Revert "greatly speed up QTransform::mapRect() for projective transforms" This reverts commit 72e083c98c3adb07bb1578fb7f28f121fc3f34ac. This test broke the tst_QTransform::projectivePathMapping autotest. Lars is looking into it; for now we take the patch out. Reviewed-by: Lars --- src/gui/painting/qtransform.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/gui/painting/qtransform.cpp b/src/gui/painting/qtransform.cpp index 86e594c..c00012a 100644 --- a/src/gui/painting/qtransform.cpp +++ b/src/gui/painting/qtransform.cpp @@ -1788,7 +1788,7 @@ QRect QTransform::mapRect(const QRect &rect) const y -= h; } return QRect(x, y, w, h); - } else { + } else if (t < TxProject) { // see mapToPolygon for explanations of the algorithm. qreal x = 0, y = 0; MAP(rect.left(), rect.top(), x, y); @@ -1812,6 +1812,10 @@ QRect QTransform::mapRect(const QRect &rect) const xmax = qMax(xmax, x); ymax = qMax(ymax, y); return QRect(qRound(xmin), qRound(ymin), qRound(xmax)-qRound(xmin), qRound(ymax)-qRound(ymin)); + } else { + QPainterPath path; + path.addRect(rect); + return map(path).boundingRect().toRect(); } } @@ -1854,7 +1858,7 @@ QRectF QTransform::mapRect(const QRectF &rect) const y -= h; } return QRectF(x, y, w, h); - } else { + } else if (t < TxProject) { qreal x = 0, y = 0; MAP(rect.x(), rect.y(), x, y); qreal xmin = x; @@ -1877,6 +1881,10 @@ QRectF QTransform::mapRect(const QRectF &rect) const xmax = qMax(xmax, x); ymax = qMax(ymax, y); return QRectF(xmin, ymin, xmax-xmin, ymax - ymin); + } else { + QPainterPath path; + path.addRect(rect); + return map(path).boundingRect(); } } -- cgit v0.12 From 0141b9b410278e064f3455d20cb21a50c926a2c8 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Wed, 10 Jun 2009 14:40:50 +0200 Subject: qdoc: Commented out debug code. Reviewed-by: Trust Me --- tools/qdoc3/htmlgenerator.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index 335cf66..cff8331 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -2498,8 +2498,8 @@ QString HtmlGenerator::highlightedCode(const QString& markedCode, // replace all <@link> tags: "(<@link node=\"([^\"]+)\">).*()" static const QString linkTag("link"); - if (src.contains("setAcceptDrops")) - qDebug() << "SRC:" << src; + //if (src.contains("setAcceptDrops")) + // qDebug() << "SRC:" << src; bool done = false; for (int i = 0, n = src.size(); i < n;) { if (src.at(i) == charLangle && src.at(i + 1).unicode() == '@') { @@ -3843,10 +3843,10 @@ void HtmlGenerator::generateQmlInherits(const QmlClassNode* cn, generateText(text, cn, marker); out() << "

      "; } - else - qDebug() << "generateQmlInherits(): " - << "Inherited element not documented -->" - << linkPair.first; +// else +// qDebug() << "generateQmlInherits(): " +// << "Inherited element not documented -->" +// << linkPair.first; } } } -- cgit v0.12 From 08618c4d4e7b3d99ffa2b56ea03fa4e25de101bd Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 10 Jun 2009 14:41:33 +0200 Subject: Fix some possible double connected signals Task-number: 250147 Reviewed-by: Thierry --- src/gui/itemviews/qtableview.cpp | 6 +++--- src/gui/itemviews/qtreeview.cpp | 9 ++------- src/gui/widgets/qtoolbarlayout.cpp | 2 +- 3 files changed, 6 insertions(+), 11 deletions(-) diff --git a/src/gui/itemviews/qtableview.cpp b/src/gui/itemviews/qtableview.cpp index 0bded54..454b1f5 100644 --- a/src/gui/itemviews/qtableview.cpp +++ b/src/gui/itemviews/qtableview.cpp @@ -1844,14 +1844,14 @@ void QTableView::setSortingEnabled(bool enable) disconnect(horizontalHeader(), SIGNAL(sectionPressed(int)), this, SLOT(selectColumn(int))); connect(horizontalHeader(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), - this, SLOT(sortByColumn(int))); + this, SLOT(sortByColumn(int)), Qt::UniqueConnection); sortByColumn(horizontalHeader()->sortIndicatorSection(), horizontalHeader()->sortIndicatorOrder()); } else { connect(d->horizontalHeader, SIGNAL(sectionEntered(int)), - this, SLOT(_q_selectColumn(int))); + this, SLOT(_q_selectColumn(int)), Qt::UniqueConnection); connect(horizontalHeader(), SIGNAL(sectionPressed(int)), - this, SLOT(selectColumn(int))); + this, SLOT(selectColumn(int)), Qt::UniqueConnection); disconnect(horizontalHeader(), SIGNAL(sortIndicatorChanged(int,Qt::SortOrder)), this, SLOT(sortByColumn(int))); } diff --git a/src/gui/itemviews/qtreeview.cpp b/src/gui/itemviews/qtreeview.cpp index 965a5c7..9910118 100644 --- a/src/gui/itemviews/qtreeview.cpp +++ b/src/gui/itemviews/qtreeview.cpp @@ -238,11 +238,6 @@ void QTreeView::setModel(QAbstractItemModel *model) connect(d->model, SIGNAL(rowsRemoved(QModelIndex,int,int)), this, SLOT(rowsRemoved(QModelIndex,int,int))); - connect(d->model, SIGNAL(columnsAboutToBeRemoved(QModelIndex,int,int)), - this, SLOT(_q_columnsAboutToBeRemoved(QModelIndex,int,int))); - connect(d->model, SIGNAL(columnsRemoved(QModelIndex,int,int)), - this, SLOT(_q_columnsRemoved(QModelIndex,int,int))); - connect(d->model, SIGNAL(modelAboutToBeReset()), SLOT(_q_modelAboutToBeReset())); if (d->sortingEnabled) @@ -3072,16 +3067,16 @@ void QTreeViewPrivate::_q_modelAboutToBeReset() void QTreeViewPrivate::_q_columnsAboutToBeRemoved(const QModelIndex &parent, int start, int end) { - Q_UNUSED(parent); if (start <= 0 && 0 <= end) viewItems.clear(); + QAbstractItemViewPrivate::_q_columnsAboutToBeRemoved(parent, start, end); } void QTreeViewPrivate::_q_columnsRemoved(const QModelIndex &parent, int start, int end) { - Q_UNUSED(parent); if (start <= 0 && 0 <= end) doDelayedItemsLayout(); + QAbstractItemViewPrivate::_q_columnsRemoved(parent, start, end); } void QTreeViewPrivate::layout(int i) diff --git a/src/gui/widgets/qtoolbarlayout.cpp b/src/gui/widgets/qtoolbarlayout.cpp index 0bfa493..0af2b65 100644 --- a/src/gui/widgets/qtoolbarlayout.cpp +++ b/src/gui/widgets/qtoolbarlayout.cpp @@ -128,7 +128,7 @@ void QToolBarLayout::setUsePopupMenu(bool set) invalidate(); if (!set) { QObject::connect(extension, SIGNAL(clicked(bool)), - this, SLOT(setExpanded(bool))); + this, SLOT(setExpanded(bool)), Qt::UniqueConnection); extension->setPopupMode(QToolButton::DelayedPopup); extension->setMenu(0); delete popupMenu; -- cgit v0.12 From 686700203aa9deeafba3bae826c7caec6d6916fd Mon Sep 17 00:00:00 2001 From: Alexis Menard Date: Wed, 10 Jun 2009 14:44:52 +0200 Subject: Move declaration of QFileInfoPrivate in a separate file _p and add an auto-test when we copy file infos. Reviewed-by: ogoffart --- src/corelib/io/io.pri | 1 + src/corelib/io/qfileinfo.cpp | 65 +---------------- src/corelib/io/qfileinfo_p.h | 126 +++++++++++++++++++++++++++++++++ tests/auto/qfileinfo/tst_qfileinfo.cpp | 56 +++++++++++++++ 4 files changed, 184 insertions(+), 64 deletions(-) create mode 100644 src/corelib/io/qfileinfo_p.h diff --git a/src/corelib/io/io.pri b/src/corelib/io/io.pri index 8f37e25..5033b21 100644 --- a/src/corelib/io/io.pri +++ b/src/corelib/io/io.pri @@ -10,6 +10,7 @@ HEADERS += \ io/qdiriterator.h \ io/qfile.h \ io/qfileinfo.h \ + io/qfileinfo_p.h \ io/qiodevice.h \ io/qiodevice_p.h \ io/qnoncontiguousbytedevice_p.h \ diff --git a/src/corelib/io/qfileinfo.cpp b/src/corelib/io/qfileinfo.cpp index 36b1ed8..4f1b943 100644 --- a/src/corelib/io/qfileinfo.cpp +++ b/src/corelib/io/qfileinfo.cpp @@ -48,73 +48,10 @@ #include "qatomic.h" #include "qhash.h" #include "qdir.h" +#include "qfileinfo_p.h" QT_BEGIN_NAMESPACE -class QFileInfoPrivate -{ -public: - QFileInfoPrivate(const QFileInfo *copy=0); - ~QFileInfoPrivate(); - - void initFileEngine(const QString &); - - enum Access { - ReadAccess, - WriteAccess, - ExecuteAccess - }; - bool hasAccess(Access access) const; - - uint getFileFlags(QAbstractFileEngine::FileFlags) const; - QDateTime &getFileTime(QAbstractFileEngine::FileTime) const; - QString getFileName(QAbstractFileEngine::FileName) const; - - enum { CachedFileFlags=0x01, CachedLinkTypeFlag=0x02, CachedBundleTypeFlag=0x04, - CachedMTime=0x10, CachedCTime=0x20, CachedATime=0x40, - CachedSize =0x08 }; - struct Data { - inline Data() - : ref(1), fileEngine(0), cache_enabled(1) - { clear(); } - inline Data(const Data ©) - : ref(1), fileEngine(QAbstractFileEngine::create(copy.fileName)), - fileName(copy.fileName), cache_enabled(copy.cache_enabled) - { clear(); } - inline ~Data() { delete fileEngine; } - inline void clearFlags() { - fileFlags = 0; - cachedFlags = 0; - if (fileEngine) - (void)fileEngine->fileFlags(QFSFileEngine::Refresh); - } - inline void clear() { - fileNames.clear(); - clearFlags(); - } - mutable QAtomicInt ref; - - QAbstractFileEngine *fileEngine; - mutable QString fileName; - mutable QHash fileNames; - - mutable uint cachedFlags : 31; - mutable uint cache_enabled : 1; - mutable uint fileFlags; - mutable qint64 fileSize; - mutable QDateTime fileTimes[3]; - inline bool getCachedFlag(uint c) const - { return cache_enabled ? (cachedFlags & c) : 0; } - inline void setCachedFlag(uint c) - { if (cache_enabled) cachedFlags |= c; } - } *data; - inline void reset() { - detach(); - data->clear(); - } - void detach(); -}; - QFileInfoPrivate::QFileInfoPrivate(const QFileInfo *copy) { if(copy) { diff --git a/src/corelib/io/qfileinfo_p.h b/src/corelib/io/qfileinfo_p.h new file mode 100644 index 0000000..8155bcb --- /dev/null +++ b/src/corelib/io/qfileinfo_p.h @@ -0,0 +1,126 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QFILEINFO_P_H +#define QFILEINFO_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qfileinfo.h" + +QT_BEGIN_NAMESPACE + +class QFileInfoPrivate +{ +public: + QFileInfoPrivate(const QFileInfo *copy=0); + ~QFileInfoPrivate(); + + void initFileEngine(const QString &); + + enum Access { + ReadAccess, + WriteAccess, + ExecuteAccess + }; + bool hasAccess(Access access) const; + + uint getFileFlags(QAbstractFileEngine::FileFlags) const; + QDateTime &getFileTime(QAbstractFileEngine::FileTime) const; + QString getFileName(QAbstractFileEngine::FileName) const; + + enum { CachedFileFlags=0x01, CachedLinkTypeFlag=0x02, CachedBundleTypeFlag=0x04, + CachedMTime=0x10, CachedCTime=0x20, CachedATime=0x40, + CachedSize =0x08 }; + struct Data { + inline Data() + : ref(1), fileEngine(0), cache_enabled(1) + { clear(); } + inline Data(const Data ©) + : ref(1), fileEngine(QAbstractFileEngine::create(copy.fileName)), + fileName(copy.fileName), cache_enabled(copy.cache_enabled) + { clear(); } + inline ~Data() { delete fileEngine; } + inline void clearFlags() { + fileFlags = 0; + cachedFlags = 0; + if (fileEngine) + (void)fileEngine->fileFlags(QFSFileEngine::Refresh); + } + inline void clear() { + fileNames.clear(); + clearFlags(); + } + mutable QAtomicInt ref; + + QAbstractFileEngine *fileEngine; + mutable QString fileName; + mutable QHash fileNames; + + mutable uint cachedFlags : 31; + mutable uint cache_enabled : 1; + mutable uint fileFlags; + mutable qint64 fileSize; + mutable QDateTime fileTimes[3]; + inline bool getCachedFlag(uint c) const + { return cache_enabled ? (cachedFlags & c) : 0; } + inline void setCachedFlag(uint c) + { if (cache_enabled) cachedFlags |= c; } + } *data; + inline void reset() { + detach(); + data->clear(); + } + void detach(); +}; + +QT_END_NAMESPACE + +#endif // QFILEINFO_P_H diff --git a/tests/auto/qfileinfo/tst_qfileinfo.cpp b/tests/auto/qfileinfo/tst_qfileinfo.cpp index 3d7e6f8..cccdd64 100644 --- a/tests/auto/qfileinfo/tst_qfileinfo.cpp +++ b/tests/auto/qfileinfo/tst_qfileinfo.cpp @@ -61,6 +61,7 @@ #include #include "../network-settings.h" +#include //TESTED_CLASS= //TESTED_FILES= @@ -75,6 +76,9 @@ public: private slots: void getSetCheck(); + + void copy(); + void isFile_data(); void isFile(); @@ -178,6 +182,58 @@ void tst_QFileInfo::getSetCheck() QCOMPARE(true, obj1.caching()); } +static QFileInfoPrivate* getPrivate(QFileInfo &info) +{ + return (*reinterpret_cast(&info)); +} + +void tst_QFileInfo::copy() +{ + QTemporaryFile *t; + t = new QTemporaryFile; + t->open(); + QFileInfo info(t->fileName()); + QVERIFY(info.exists()); + + //copy constructor + QFileInfo info2(info); + QFileInfoPrivate *privateInfo = getPrivate(info); + QFileInfoPrivate *privateInfo2 = getPrivate(info2); + QCOMPARE(privateInfo->data, privateInfo2->data); + + //operator = + QFileInfo info3 = info; + QFileInfoPrivate *privateInfo3 = getPrivate(info3); + QCOMPARE(privateInfo->data, privateInfo3->data); + QCOMPARE(privateInfo2->data, privateInfo3->data); + + //refreshing info3 will detach it + QFile file(info.absoluteFilePath()); + QVERIFY(file.open(QFile::WriteOnly)); + QCOMPARE(file.write("JAJAJAA"), qint64(7)); + file.flush(); + + QTest::qWait(250); +#if defined(Q_OS_WIN) || defined(Q_OS_WINCE) + if (QSysInfo::windowsVersion() & QSysInfo::WV_VISTA || + QSysInfo::windowsVersion() & QSysInfo::WV_CE_based) + file.close(); +#endif +#if defined(Q_OS_WINCE) + // On Windows CE we need to close the file. + // Otherwise the content will be cached and not + // flushed to the storage, although we flushed it + // manually!!! CE has interim cache, we cannot influence. + QTest::qWait(5000); +#endif + info3.refresh(); + QVERIFY(privateInfo->data != privateInfo3->data); + QVERIFY(privateInfo2->data != privateInfo3->data); + QCOMPARE(privateInfo->data, privateInfo2->data); + + +} + tst_QFileInfo::tst_QFileInfo() { } -- cgit v0.12 From a66525c2e4c760f8ceda344cd7252431ed263654 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Fri, 29 May 2009 11:16:20 +0200 Subject: Use a linked list for the senders list inside QObject Speed up the disconnection and object destruction Reviewed-by: Brad --- src/corelib/kernel/qobject.cpp | 67 +++++++++++++++++++++++------------------- src/corelib/kernel/qobject_p.h | 5 +++- 2 files changed, 40 insertions(+), 32 deletions(-) diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index 5e33a71..e953bcb 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -123,7 +123,7 @@ extern "C" Q_CORE_EXPORT void qt_removeObject(QObject *) } QObjectPrivate::QObjectPrivate(int version) - : threadData(0), currentSender(0), currentChildBeingDeleted(0), connectionLists(0) + : threadData(0), currentSender(0), currentChildBeingDeleted(0), connectionLists(0), senders(0) { if (version != QObjectPrivateVersion) qFatal("Cannot mix incompatible Qt libraries"); @@ -287,8 +287,8 @@ QObjectList QObjectPrivate::senderList() const { QObjectList returnValue; QMutexLocker locker(signalSlotLock(q_func())); - for (int i = 0; i < senders.count(); ++i) - returnValue << senders.at(i)->sender; + for (Connection *c = senders; c; c = c->next) + returnValue << c->sender; return returnValue; } @@ -756,8 +756,10 @@ QObject::~QObject() QMutex *m = signalSlotLock(c->receiver); bool needToUnlock = QOrderedMutexLocker::relock(locker.mutex(), m); c = connectionList[i]; - if (c->receiver) - c->receiver->d_func()->senders.removeOne(c); + if (c->receiver) { + *c->prev = c->next; + if (c->next) c->next->prev = c->prev; + } if (needToUnlock) m->unlock(); @@ -774,29 +776,25 @@ QObject::~QObject() } // disconnect all senders - for (int i = 0; i < d->senders.count(); ) { - QObjectPrivate::Connection *s = d->senders[i]; - - QMutex *m = signalSlotLock(s->sender); + QObjectPrivate::Connection *node = d->senders; + while (node) { + QMutex *m = signalSlotLock(node->sender); + node->prev = &node; bool needToUnlock = QOrderedMutexLocker::relock(locker.mutex(), m); - if (m < locker.mutex()) { - if (i >= d->senders.count() || s != d->senders[i]) { - if (needToUnlock) - m->unlock(); - continue; - } + //the node has maybe been removed while the mutex was unlocked in relock? + if (!node || signalSlotLock(node->sender) != m) { + m->unlock(); + continue; } - s->receiver = 0; - QObjectConnectionListVector *senderLists = s->sender->d_func()->connectionLists; + node->receiver = 0; + QObjectConnectionListVector *senderLists = node->sender->d_func()->connectionLists; if (senderLists) senderLists->dirty = true; if (needToUnlock) m->unlock(); - ++i; + node = node->next; } - - d->senders.clear(); } if (d->pendTimer) { @@ -2281,8 +2279,8 @@ QObject *QObject::sender() const // Return 0 if d->currentSender isn't in d->senders bool found = false; - for (int i = 0; !found && i < d->senders.count(); ++i) - found = (d->senders.at(i)->sender == d->currentSender->sender); + for (QObjectPrivate::Connection *c = d->senders; c && !found; c = c->next) + found = (c->sender == d->currentSender->sender); if (!found) return 0; return d->currentSender->sender; @@ -2799,9 +2797,13 @@ bool QMetaObject::connect(const QObject *sender, int signal_index, c->method = method_index; c->connectionType = type; c->argumentTypes = types; + c->prev = &r->d_func()->senders; + c->next = *c->prev; + *c->prev = c; + if (c->next) + c->next->prev = &c->next; s->d_func()->addConnection(signal_index, c); - r->d_func()->senders.append(c); if (signal_index < 0) sender->d_func()->connectedSignals = ~0u; @@ -2851,8 +2853,10 @@ bool QMetaObject::disconnect(const QObject *sender, int signal_index, needToUnlock = QOrderedMutexLocker::relock(senderMutex, m); c = connectionList[i]; } - if (c->receiver) - c->receiver->d_func()->senders.removeOne(c); + if (c->receiver) { + *c->prev = c->next; + if (c->next) c->next->prev = c->prev; + } if (needToUnlock) m->unlock(); @@ -2878,8 +2882,10 @@ bool QMetaObject::disconnect(const QObject *sender, int signal_index, needToUnlock = QOrderedMutexLocker::relock(senderMutex, m); c = connectionList[i]; } - if (c->receiver) - c->receiver->d_func()->senders.removeOne(c); + if (c->receiver) { + *c->prev = c->next; + if (c->next) c->next->prev = c->prev; + } if (needToUnlock) m->unlock(); @@ -3417,9 +3423,8 @@ void QObject::dumpObjectInfo() // now look for connections where this object is the receiver qDebug(" SIGNALS IN"); - if (!d->senders.isEmpty()) { - for (int i = 0; i < d->senders.count(); ++i) { - const QObjectPrivate::Connection *s = d->senders.at(i); + if (d->senders) { + for (QObjectPrivate::Connection *s = d->senders; s; s = s->next) const QMetaMethod slot = metaObject()->method(s->method); qDebug(" <-- %s::%s %s", s->sender->metaObject()->className(), @@ -3427,7 +3432,7 @@ void QObject::dumpObjectInfo() slot.signature()); } } else { - qDebug(" "); + qDebug(" "); } #endif } diff --git a/src/corelib/kernel/qobject_p.h b/src/corelib/kernel/qobject_p.h index 96d79af..d699061 100644 --- a/src/corelib/kernel/qobject_p.h +++ b/src/corelib/kernel/qobject_p.h @@ -152,6 +152,9 @@ public: int method; uint connectionType : 3; // 0 == auto, 1 == direct, 2 == queued, 4 == blocking QBasicAtomicPointer argumentTypes; + //senders linked list + Connection *next; + Connection **prev; ~Connection(); }; typedef QList ConnectionList; @@ -160,7 +163,7 @@ public: void addConnection(int signal, Connection *c); void cleanConnectionLists(); - ConnectionList senders; + Connection *senders; //linked list; static Sender *setCurrentSender(QObject *receiver, Sender *sender); -- cgit v0.12 From 1a5e7171b9da383ca5f6be92b7cb6e502fd79fc4 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 3 Jun 2009 20:47:06 +0200 Subject: Avoid locking and search on the global hash if there is no QPointer As less than 10% of the object have QPointers, we can avoid locking if we know there is no QPointer. And keeping track of which object has a QPointer is easy. Reviewed-by: Brad --- src/corelib/kernel/qobject.cpp | 22 +++++++++++++++++++--- src/corelib/kernel/qobject.h | 3 ++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index e953bcb..a095e0a 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -143,6 +143,7 @@ QObjectPrivate::QObjectPrivate(int version) inEventHandler = false; inThreadChangeEvent = false; deleteWatch = 0; + hasGuards = false; } QObjectPrivate::~QObjectPrivate() @@ -359,6 +360,7 @@ void QMetaObject::addGuard(QObject **ptr) return; } QMutexLocker locker(guardHashLock()); + QObjectPrivate::get(*ptr)->hasGuards = true; hash->insert(*ptr, ptr); } @@ -374,12 +376,17 @@ void QMetaObject::removeGuard(QObject **ptr) QMutexLocker locker(guardHashLock()); GuardHash::iterator it = hash->find(*ptr); const GuardHash::iterator end = hash->end(); + bool more = false; //if the QObject has more pointer attached to it. for (; it.key() == *ptr && it != end; ++it) { if (it.value() == ptr) { - (void) hash->erase(it); + it = hash->erase(it); + if (!more) more = (it != end && it.key() == *ptr); break; } + more = true; } + if (!more) + QObjectPrivate::get(*ptr)->hasGuards = false; } /*!\internal @@ -393,24 +400,33 @@ void QMetaObject::changeGuard(QObject **ptr, QObject *o) } QMutexLocker locker(guardHashLock()); if (*ptr) { + bool more = false; //if the QObject has more pointer attached to it. GuardHash::iterator it = hash->find(*ptr); const GuardHash::iterator end = hash->end(); for (; it.key() == *ptr && it != end; ++it) { if (it.value() == ptr) { - (void) hash->erase(it); + it = hash->erase(it); + if (!more) more = (it != end && it.key() == *ptr); break; } + more = true; } + if (!more) + QObjectPrivate::get(*ptr)->hasGuards = false; } *ptr = o; - if (*ptr) + if (*ptr) { hash->insert(*ptr, ptr); + QObjectPrivate::get(*ptr)->hasGuards = true; + } } /*! \internal */ void QObjectPrivate::clearGuards(QObject *object) { + if (!QObjectPrivate::get(object)->hasGuards) + return; GuardHash *hash = guardHash(); if (hash) { QMutexLocker locker(guardHashLock()); diff --git a/src/corelib/kernel/qobject.h b/src/corelib/kernel/qobject.h index dbec0a6..b1f41ad 100644 --- a/src/corelib/kernel/qobject.h +++ b/src/corelib/kernel/qobject.h @@ -106,7 +106,8 @@ public: uint receiveChildEvents : 1; uint inEventHandler : 1; uint inThreadChangeEvent : 1; - uint unused : 23; + uint hasGuards : 1; //true iff there is one or more QPointer attached to this object + uint unused : 22; int postedEvents; }; -- cgit v0.12 From dd3ee408148368a6f900844afc68fff9d86c2e8c Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 10 Jun 2009 15:44:11 +0200 Subject: Compile with debug enabled --- src/corelib/kernel/qobject.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/kernel/qobject.cpp b/src/corelib/kernel/qobject.cpp index a095e0a..55d70c1 100644 --- a/src/corelib/kernel/qobject.cpp +++ b/src/corelib/kernel/qobject.cpp @@ -3440,7 +3440,7 @@ void QObject::dumpObjectInfo() qDebug(" SIGNALS IN"); if (d->senders) { - for (QObjectPrivate::Connection *s = d->senders; s; s = s->next) + for (QObjectPrivate::Connection *s = d->senders; s; s = s->next) { const QMetaMethod slot = metaObject()->method(s->method); qDebug(" <-- %s::%s %s", s->sender->metaObject()->className(), -- cgit v0.12 From 09faf56a2e44b4dfa1b341ced75803100483834f Mon Sep 17 00:00:00 2001 From: J-P Nurmi Date: Tue, 9 Jun 2009 23:44:32 +0300 Subject: Added QAbstractItemModelPrivate::canConvertToDouble(). And changed QTreeWidgetItem::operator<() and QTableWidgetItem::operator<() to use it Merge-request: 631 Reviewed-by: Olivier Goffart --- src/corelib/kernel/qabstractitemmodel.cpp | 17 +++++++++++++++++ src/corelib/kernel/qabstractitemmodel_p.h | 1 + src/gui/itemviews/qtablewidget.cpp | 20 +------------------- src/gui/itemviews/qtablewidget_p.h | 1 - src/gui/itemviews/qtreewidget.cpp | 25 +------------------------ src/gui/itemviews/qtreewidget_p.h | 1 - 6 files changed, 20 insertions(+), 45 deletions(-) diff --git a/src/corelib/kernel/qabstractitemmodel.cpp b/src/corelib/kernel/qabstractitemmodel.cpp index 935c0aa..0a84ddb 100644 --- a/src/corelib/kernel/qabstractitemmodel.cpp +++ b/src/corelib/kernel/qabstractitemmodel.cpp @@ -467,6 +467,23 @@ QAbstractItemModel *QAbstractItemModelPrivate::staticEmptyModel() return qEmptyModel(); } +bool QAbstractItemModelPrivate::canConvertToDouble(const QVariant &value) +{ + switch (value.type()) { + case QVariant::Bool: + case QVariant::Int: + case QVariant::UInt: + case QVariant::LongLong: + case QVariant::ULongLong: + case QVariant::Double: + case QVariant::Char: + return true; + default: + return false; + } + return false; +} + void QAbstractItemModelPrivate::removePersistentIndexData(QPersistentModelIndexData *data) { if (data->index.isValid()) { diff --git a/src/corelib/kernel/qabstractitemmodel_p.h b/src/corelib/kernel/qabstractitemmodel_p.h index 27f1b28..70c35cb 100644 --- a/src/corelib/kernel/qabstractitemmodel_p.h +++ b/src/corelib/kernel/qabstractitemmodel_p.h @@ -89,6 +89,7 @@ public: void columnsAboutToBeRemoved(const QModelIndex &parent, int first, int last); void columnsRemoved(const QModelIndex &parent, int first, int last); static QAbstractItemModel *staticEmptyModel(); + static bool canConvertToDouble(const QVariant &value); inline QModelIndex createIndex(int row, int column, void *data = 0) const { return q_func()->createIndex(row, column, data); diff --git a/src/gui/itemviews/qtablewidget.cpp b/src/gui/itemviews/qtablewidget.cpp index 8cb2e55..072e435 100644 --- a/src/gui/itemviews/qtablewidget.cpp +++ b/src/gui/itemviews/qtablewidget.cpp @@ -530,24 +530,6 @@ void QTableModel::sort(int column, Qt::SortOrder order) emit layoutChanged(); } -bool QTableModel::canConvertToDouble(const QVariant &value) -{ - switch (value.type()) { - case QVariant::Bool: - case QVariant::Int: - case QVariant::UInt: - case QVariant::LongLong: - case QVariant::ULongLong: - case QVariant::Double: - case QVariant::Char: - return true; - default: - return false; - } - return false; -} - - /* \internal @@ -1410,7 +1392,7 @@ QVariant QTableWidgetItem::data(int role) const bool QTableWidgetItem::operator<(const QTableWidgetItem &other) const { const QVariant v1 = data(Qt::DisplayRole), v2 = other.data(Qt::DisplayRole); - if (QTableModel::canConvertToDouble(v1) && QTableModel::canConvertToDouble(v2)) + if (QAbstractItemModelPrivate::canConvertToDouble(v1) && QAbstractItemModelPrivate::canConvertToDouble(v2)) return v1.toDouble() < v2.toDouble(); return v1.toString() < v2.toString(); } diff --git a/src/gui/itemviews/qtablewidget_p.h b/src/gui/itemviews/qtablewidget_p.h index 2e1dab6..d8bfcc5 100644 --- a/src/gui/itemviews/qtablewidget_p.h +++ b/src/gui/itemviews/qtablewidget_p.h @@ -144,7 +144,6 @@ public: const QPair &right); static bool itemGreaterThan(const QPair &left, const QPair &right); - static bool canConvertToDouble(const QVariant &value); void ensureSorted(int column, Qt::SortOrder order, int start, int end); QVector columnItems(int column) const; diff --git a/src/gui/itemviews/qtreewidget.cpp b/src/gui/itemviews/qtreewidget.cpp index 1c87580..5604f8d 100644 --- a/src/gui/itemviews/qtreewidget.cpp +++ b/src/gui/itemviews/qtreewidget.cpp @@ -695,29 +695,6 @@ bool QTreeModel::itemGreaterThan(const QPair &left, } /*! - \internal - - Returns true if the type of the variant \a value - can be casted as double. -*/ -bool QTreeModel::canConvertToDouble(const QVariant &value) -{ - switch (value.type()) { - case QVariant::Bool: - case QVariant::Int: - case QVariant::UInt: - case QVariant::LongLong: - case QVariant::ULongLong: - case QVariant::Double: - case QVariant::Char: - return true; - default: - return false; - } - return false; -} - -/*! \internal */ QList::iterator QTreeModel::sortedInsertionIterator( @@ -1812,7 +1789,7 @@ bool QTreeWidgetItem::operator<(const QTreeWidgetItem &other) const int column = view ? view->sortColumn() : 0; const QVariant v1 = data(column, Qt::DisplayRole); const QVariant v2 = other.data(column, Qt::DisplayRole); - if (QTreeModel::canConvertToDouble(v1) && QTreeModel::canConvertToDouble(v2)) + if (QAbstractItemModelPrivate::canConvertToDouble(v1) && QAbstractItemModelPrivate::canConvertToDouble(v2)) return v1.toDouble() < v2.toDouble(); return v1.toString() < v2.toString(); } diff --git a/src/gui/itemviews/qtreewidget_p.h b/src/gui/itemviews/qtreewidget_p.h index 96f734d..a089cf5 100644 --- a/src/gui/itemviews/qtreewidget_p.h +++ b/src/gui/itemviews/qtreewidget_p.h @@ -116,7 +116,6 @@ public: const QPair &right); static bool itemGreaterThan(const QPair &left, const QPair &right); - static bool canConvertToDouble(const QVariant &value); static QList::iterator sortedInsertionIterator( const QList::iterator &begin, const QList::iterator &end, -- cgit v0.12 From 3e2ee19553c2423e1e76264f3c3eb088cd31747a Mon Sep 17 00:00:00 2001 From: J-P Nurmi Date: Tue, 9 Jun 2009 23:52:27 +0300 Subject: Made QListWidgetItem::operator<() check if the data is numerical when comparing. Merge-request: 631 Reviewed-by: Olivier Goffart --- src/gui/itemviews/qlistwidget.cpp | 5 +++- tests/auto/qlistwidget/tst_qlistwidget.cpp | 39 +++++++++++++++++++++--------- 2 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/gui/itemviews/qlistwidget.cpp b/src/gui/itemviews/qlistwidget.cpp index e1e509d..504908f 100644 --- a/src/gui/itemviews/qlistwidget.cpp +++ b/src/gui/itemviews/qlistwidget.cpp @@ -687,7 +687,10 @@ QVariant QListWidgetItem::data(int role) const */ bool QListWidgetItem::operator<(const QListWidgetItem &other) const { - return text() < other.text(); + const QVariant v1 = data(Qt::DisplayRole), v2 = other.data(Qt::DisplayRole); + if (QAbstractItemModelPrivate::canConvertToDouble(v1) && QAbstractItemModelPrivate::canConvertToDouble(v2)) + return v1.toDouble() < v2.toDouble(); + return v1.toString() < v2.toString(); } #ifndef QT_NO_DATASTREAM diff --git a/tests/auto/qlistwidget/tst_qlistwidget.cpp b/tests/auto/qlistwidget/tst_qlistwidget.cpp index 8d15aa4..8468cf3 100644 --- a/tests/auto/qlistwidget/tst_qlistwidget.cpp +++ b/tests/auto/qlistwidget/tst_qlistwidget.cpp @@ -883,31 +883,46 @@ void tst_QListWidget::itemStreaming() void tst_QListWidget::sortItems_data() { QTest::addColumn("order"); - QTest::addColumn("initialList"); - QTest::addColumn("expectedList"); + QTest::addColumn("initialList"); + QTest::addColumn("expectedList"); QTest::addColumn("expectedRows"); - QTest::newRow("ascending order") + QTest::newRow("ascending strings") << static_cast(Qt::AscendingOrder) - << (QStringList() << "c" << "d" << "a" << "b") - << (QStringList() << "a" << "b" << "c" << "d") + << (QVariantList() << QString("c") << QString("d") << QString("a") << QString("b")) + << (QVariantList() << QString("a") << QString("b") << QString("c") << QString("d")) << (IntList() << 2 << 3 << 0 << 1); - QTest::newRow("descending order") + QTest::newRow("descending strings") << static_cast(Qt::DescendingOrder) - << (QStringList() << "c" << "d" << "a" << "b") - << (QStringList() << "d" << "c" << "b" << "a") + << (QVariantList() << QString("c") << QString("d") << QString("a") << QString("b")) + << (QVariantList() << QString("d") << QString("c") << QString("b") << QString("a")) << (IntList() << 1 << 0 << 3 << 2); + + QTest::newRow("ascending numbers") + << static_cast(Qt::AscendingOrder) + << (QVariantList() << 1 << 11 << 2 << 22) + << (QVariantList() << 1 << 2 << 11 << 22) + << (IntList() << 0 << 2 << 1 << 3); + + QTest::newRow("descending numbers") + << static_cast(Qt::DescendingOrder) + << (QVariantList() << 1 << 11 << 2 << 22) + << (QVariantList() << 22 << 11 << 2 << 1) + << (IntList() << 3 << 1 << 2 << 0); } void tst_QListWidget::sortItems() { QFETCH(int, order); - QFETCH(QStringList, initialList); - QFETCH(QStringList, expectedList); + QFETCH(QVariantList, initialList); + QFETCH(QVariantList, expectedList); QFETCH(IntList, expectedRows); - testWidget->addItems(initialList); + foreach (const QVariant &data, initialList) { + QListWidgetItem *item = new QListWidgetItem(testWidget); + item->setData(Qt::DisplayRole, data); + } QAbstractItemModel *model = testWidget->model(); QList persistent; @@ -918,7 +933,7 @@ void tst_QListWidget::sortItems() QCOMPARE(testWidget->count(), expectedList.count()); for (int i = 0; i < testWidget->count(); ++i) - QCOMPARE(testWidget->item(i)->text(), expectedList.at(i)); + QCOMPARE(testWidget->item(i)->text(), expectedList.at(i).toString()); for (int k = 0; k < testWidget->count(); ++k) QCOMPARE(persistent.at(k).row(), expectedRows.at(k)); -- cgit v0.12 From 188a4ab62c99dcb113cad1833a0701d84a886e65 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 10 Jun 2009 15:35:45 +0200 Subject: Internal documentation for QAbstractItemModelPrivate::canConvertToDouble Also add QMetaType types as list or recognized numerical types Reviewed-by: thierry --- src/corelib/kernel/qabstractitemmodel.cpp | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/src/corelib/kernel/qabstractitemmodel.cpp b/src/corelib/kernel/qabstractitemmodel.cpp index 0a84ddb..6d6caf5 100644 --- a/src/corelib/kernel/qabstractitemmodel.cpp +++ b/src/corelib/kernel/qabstractitemmodel.cpp @@ -467,9 +467,17 @@ QAbstractItemModel *QAbstractItemModelPrivate::staticEmptyModel() return qEmptyModel(); } +/*! + \internal + return true if \a value contains a numerical type + + This function is used by our Q{Tree,Widget,Table}WidgetModel classes to sort. + We cannot rely on QVariant::canConvert because this would take strings as double + and then not sort strings correctly +*/ bool QAbstractItemModelPrivate::canConvertToDouble(const QVariant &value) { - switch (value.type()) { + switch (value.userType()) { case QVariant::Bool: case QVariant::Int: case QVariant::UInt: @@ -477,6 +485,12 @@ bool QAbstractItemModelPrivate::canConvertToDouble(const QVariant &value) case QVariant::ULongLong: case QVariant::Double: case QVariant::Char: + case QMetaType::Float: + case QMetaType::Short: + case QMetaType::UShort: + case QMetaType::UChar: + case QMetaType::ULong: + case QMetaType::Long: return true; default: return false; -- cgit v0.12 From 32f32ee3e752a6cc03505ddaa48d2849eaedc2a6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Wed, 10 Jun 2009 14:31:20 +0200 Subject: QPainter::worldTransform() does not return identity matrix. QPainter::worldTransform() does not return identity matrix when created on a redirected widget. It should always be identity by default, and should only change as a result of QPainter::setWorldTransform. The reason it didn't return identity for redirected widgets, was that we translated the shared painter's world matrix directly. Since we cannot modify the world matrix directly, we have to store the shared painter's current world transform in a separate matrix (redirectedMatrix), reset the world transform to identity, and later combine the redirectedMatrix with world transforms set on the painter. Note that redirection_offset was in negative coordinates before, and that redirectionMatrix now is in positive coordinates, hence opposite signs around. Auto-test included. Reviewed-by: lars Reviewed-by: Samuel --- src/gui/painting/qpaintengineex.cpp | 3 +- src/gui/painting/qpainter.cpp | 47 ++++++++----------- src/gui/painting/qpainter_p.h | 2 +- tests/auto/qwidget/tst_qwidget.cpp | 94 +++++++++++++++++++++++++++++++++++++ 4 files changed, 115 insertions(+), 31 deletions(-) diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index 3cf5ff9..d2671c8 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -151,8 +151,7 @@ void QPaintEngineExPrivate::replayClipOperations() QTransform transform = q->state()->matrix; - QTransform redirection; - redirection.translate(-q->state()->redirection_offset.x(), -q->state()->redirection_offset.y()); + const QTransform &redirection = q->state()->redirectionMatrix; for (int i = 0; i < clipInfo.size(); ++i) { const QPainterClipInfo &info = clipInfo.at(i); diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index 4744f14..0ece498 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -281,10 +281,14 @@ bool QPainterPrivate::attachPainterPrivate(QPainter *q, QPaintDevice *pdev) q->d_ptr->state->wh = q->d_ptr->state->vh = widget->height(); // Update matrix. - if (q->d_ptr->state->WxF) - q->d_ptr->state->worldMatrix.translate(-offset.x(), -offset.y()); - else - q->d_ptr->state->redirection_offset = offset; + if (q->d_ptr->state->WxF) { + q->d_ptr->state->redirectionMatrix *= q->d_ptr->state->worldMatrix; + q->d_ptr->state->redirectionMatrix.translate(-offset.x(), -offset.y()); + q->d_ptr->state->worldMatrix = QTransform(); + q->d_ptr->state->WxF = false; + } else { + q->d_ptr->state->redirectionMatrix = QTransform::fromTranslate(-offset.x(), -offset.y()); + } q->d_ptr->updateMatrix(); QPaintEnginePrivate *enginePrivate = q->d_ptr->engine->d_func(); @@ -410,7 +414,7 @@ void QPainterPrivate::draw_helper(const QPainterPath &originalPath, DrawOperatio bool old_txinv = txinv; QTransform old_invMatrix = invMatrix; txinv = true; - invMatrix = QTransform().translate(-state->redirection_offset.x(), -state->redirection_offset.y()); + invMatrix = state->redirectionMatrix; QPainterPath clipPath = q->clipPath(); QRectF r = clipPath.boundingRect().intersected(absPathRect); absPathRect = r.toAlignedRect(); @@ -634,20 +638,7 @@ void QPainterPrivate::updateMatrix() state->matrix *= viewTransform(); txinv = false; // no inverted matrix - if (!state->redirection_offset.isNull()) { - // We want to translate in dev space so we do the adding of the redirection - // offset manually. - if (state->matrix.isAffine()) { - state->matrix = QTransform(state->matrix.m11(), state->matrix.m12(), - state->matrix.m21(), state->matrix.m22(), - state->matrix.dx()-state->redirection_offset.x(), - state->matrix.dy()-state->redirection_offset.y()); - } else { - QTransform temp; - temp.translate(-state->redirection_offset.x(), -state->redirection_offset.y()); - state->matrix *= temp; - } - } + state->matrix *= state->redirectionMatrix; if (extended) extended->transformChanged(); else @@ -1572,10 +1563,8 @@ void QPainter::restore() // replay the list of clip states, for (int i=0; istate->clipInfo.size(); ++i) { const QPainterClipInfo &info = d->state->clipInfo.at(i); - tmp->matrix.setMatrix(info.matrix.m11(), info.matrix.m12(), info.matrix.m13(), - info.matrix.m21(), info.matrix.m22(), info.matrix.m23(), - info.matrix.dx() - d->state->redirection_offset.x(), - info.matrix.dy() - d->state->redirection_offset.y(), info.matrix.m33()); + tmp->matrix = info.matrix; + tmp->matrix *= d->state->redirectionMatrix; tmp->clipOperation = info.operation; if (info.clipType == QPainterClipInfo::RectClip) { tmp->dirtyFlags = QPaintEngine::DirtyClipRegion | QPaintEngine::DirtyTransform; @@ -1689,7 +1678,7 @@ bool QPainter::begin(QPaintDevice *pd) d->state->painter = this; d->states.push_back(d->state); - d->state->redirection_offset = redirectionOffset; + d->state->redirectionMatrix.translate(-redirectionOffset.x(), -redirectionOffset.y()); d->state->brushOrigin = QPointF(); if (!d->engine) { @@ -1723,7 +1712,8 @@ bool QPainter::begin(QPaintDevice *pd) // Adjust offset for alien widgets painting outside the paint event. if (!inPaintEvent && paintOutsidePaintEvent && !widget->internalWinId() && widget->testAttribute(Qt::WA_WState_Created)) { - d->state->redirection_offset -= widget->mapTo(widget->nativeParentWidget(), QPoint()); + const QPoint offset = widget->mapTo(widget->nativeParentWidget(), QPoint()); + d->state->redirectionMatrix.translate(offset.x(), offset.y()); } break; } @@ -1805,11 +1795,12 @@ bool QPainter::begin(QPaintDevice *pd) d->state->wh = d->state->vh = pd->metric(QPaintDevice::PdmHeight); } - d->state->redirection_offset += d->engine->coordinateOffset(); + const QPoint coordinateOffset = d->engine->coordinateOffset(); + d->state->redirectionMatrix.translate(-coordinateOffset.x(), -coordinateOffset.y()); Q_ASSERT(d->engine->isActive()); - if (!d->state->redirection_offset.isNull()) + if (!d->state->redirectionMatrix.isIdentity()) d->updateMatrix(); Q_ASSERT(d->engine->isActive()); @@ -7704,7 +7695,7 @@ QPainterState::QPainterState(const QPainterState *s) clipRegion(s->clipRegion), clipPath(s->clipPath), clipOperation(s->clipOperation), renderHints(s->renderHints), clipInfo(s->clipInfo), - worldMatrix(s->worldMatrix), matrix(s->matrix), redirection_offset(s->redirection_offset), + worldMatrix(s->worldMatrix), matrix(s->matrix), redirectionMatrix(s->redirectionMatrix), wx(s->wx), wy(s->wy), ww(s->ww), wh(s->wh), vx(s->vx), vy(s->vy), vw(s->vw), vh(s->vh), opacity(s->opacity), WxF(s->WxF), VxF(s->VxF), diff --git a/src/gui/painting/qpainter_p.h b/src/gui/painting/qpainter_p.h index 6c8821a..8d4e6c5 100644 --- a/src/gui/painting/qpainter_p.h +++ b/src/gui/painting/qpainter_p.h @@ -158,7 +158,7 @@ public: QList clipInfo; // ### Make me smaller and faster to copy around... QTransform worldMatrix; // World transformation matrix, not window and viewport QTransform matrix; // Complete transformation matrix, - QPoint redirection_offset; + QTransform redirectionMatrix; int wx, wy, ww, wh; // window rectangle int vx, vy, vw, vh; // viewport rectangle qreal opacity; diff --git a/tests/auto/qwidget/tst_qwidget.cpp b/tests/auto/qwidget/tst_qwidget.cpp index 041aa7a..85d7de1 100644 --- a/tests/auto/qwidget/tst_qwidget.cpp +++ b/tests/auto/qwidget/tst_qwidget.cpp @@ -288,6 +288,7 @@ private slots: void render_systemClip3_data(); void render_systemClip3(); void render_task252837(); + void render_worldTransform(); void setContentsMargins(); @@ -7151,6 +7152,99 @@ void tst_QWidget::render_task252837() // Please do not crash. widget.render(&painter); } + +void tst_QWidget::render_worldTransform() +{ + class MyWidget : public QWidget + { public: + void paintEvent(QPaintEvent *) + { + QPainter painter(this); + // Make sure world transform is identity. + QCOMPARE(painter.worldTransform(), QTransform()); + + // Make sure device transform is correct. + const QPoint widgetOffset = geometry().topLeft(); + QTransform expectedDeviceTransform = QTransform::fromTranslate(105, 5); + expectedDeviceTransform.rotate(90); + expectedDeviceTransform.translate(widgetOffset.x(), widgetOffset.y()); + QCOMPARE(painter.deviceTransform(), expectedDeviceTransform); + + // Set new world transform. + QTransform newWorldTransform = QTransform::fromTranslate(10, 10); + newWorldTransform.rotate(90); + painter.setWorldTransform(newWorldTransform); + QCOMPARE(painter.worldTransform(), newWorldTransform); + + // Again, check device transform. + expectedDeviceTransform.translate(10, 10); + expectedDeviceTransform.rotate(90); + QCOMPARE(painter.deviceTransform(), expectedDeviceTransform); + + painter.fillRect(QRect(0, 0, 20, 10), Qt::green); + } + }; + + MyWidget widget; + widget.setFixedSize(100, 100); + widget.setPalette(Qt::red); + widget.setAutoFillBackground(true); + + MyWidget child; + child.setParent(&widget); + child.move(50, 50); + child.setFixedSize(50, 50); + child.setPalette(Qt::blue); + child.setAutoFillBackground(true); + + QImage image(QSize(110, 110), QImage::Format_RGB32); + image.fill(QColor(Qt::black).rgb()); + + QPainter painter(&image); + painter.translate(105, 5); + painter.rotate(90); + + const QTransform worldTransform = painter.worldTransform(); + const QTransform deviceTransform = painter.deviceTransform(); + + // Render widgets onto image. + widget.render(&painter); +#ifdef RENDER_DEBUG + image.save("render_worldTransform_image.png"); +#endif + + // Ensure the transforms are unchanged after render. + QCOMPARE(painter.worldTransform(), painter.worldTransform()); + QCOMPARE(painter.deviceTransform(), painter.deviceTransform()); + painter.end(); + + // Paint expected image. + QImage expected(QSize(110, 110), QImage::Format_RGB32); + expected.fill(QColor(Qt::black).rgb()); + + QPainter expectedPainter(&expected); + expectedPainter.translate(105, 5); + expectedPainter.rotate(90); + expectedPainter.save(); + expectedPainter.fillRect(widget.rect(),Qt::red); + expectedPainter.translate(10, 10); + expectedPainter.rotate(90); + expectedPainter.fillRect(QRect(0, 0, 20, 10), Qt::green); + expectedPainter.restore(); + expectedPainter.translate(50, 50); + expectedPainter.fillRect(child.rect(),Qt::blue); + expectedPainter.translate(10, 10); + expectedPainter.rotate(90); + expectedPainter.fillRect(QRect(0, 0, 20, 10), Qt::green); + expectedPainter.end(); + +#ifdef RENDER_DEBUG + expected.save("render_worldTransform_expected.png"); +#endif + + QCOMPARE(image, expected); +} + void tst_QWidget::setContentsMargins() { QLabel label("why does it always rain on me?"); -- cgit v0.12 From 9eeec42f67e3e5c344d024eb28ac4f09d7c96c41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 10 Jun 2009 12:13:06 +0200 Subject: Make QVectorPath::controlPointRect() return a QRectF. This makes debugging etc much easier, plus most of the places controlPointRect() was called the caller had to convert the rect to a QRectF manually. --- src/gui/painting/qemulationpaintengine.cpp | 12 ++++++------ src/gui/painting/qpaintengine_raster.cpp | 3 +-- src/gui/painting/qpaintengineex.cpp | 12 +++++------- src/gui/painting/qvectorpath_p.h | 2 +- 4 files changed, 13 insertions(+), 16 deletions(-) diff --git a/src/gui/painting/qemulationpaintengine.cpp b/src/gui/painting/qemulationpaintengine.cpp index 175f1ab..5ce1136 100644 --- a/src/gui/painting/qemulationpaintengine.cpp +++ b/src/gui/painting/qemulationpaintengine.cpp @@ -99,9 +99,9 @@ void QEmulationPaintEngine::fill(const QVectorPath &path, const QBrush &brush) } else if (g->coordinateMode() == QGradient::ObjectBoundingMode) { QBrush copy = brush; QTransform mat = copy.transform(); - QRealRect r = path.controlPointRect(); - mat.translate(r.x1, r.y1); - mat.scale(r.x2 - r.x1, r.y2 - r.y1); + QRectF r = path.controlPointRect(); + mat.translate(r.x(), r.y()); + mat.scale(r.width(), r.height()); copy.setTransform(mat); real_engine->fill(path, copy); return; @@ -139,9 +139,9 @@ void QEmulationPaintEngine::stroke(const QVectorPath &path, const QPen &pen) return; } else if (g->coordinateMode() == QGradient::ObjectBoundingMode) { QTransform mat = brush.transform(); - QRealRect r = path.controlPointRect(); - mat.translate(r.x1, r.y1); - mat.scale(r.x2 - r.x1, r.y2 - r.y1); + QRectF r = path.controlPointRect(); + mat.translate(r.x(), r.y()); + mat.scale(r.width(), r.height()); brush.setTransform(mat); copy.setBrush(brush); real_engine->stroke(path, copy); diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 7ed2dfd..2ce1d09 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -1852,8 +1852,7 @@ void QRasterPaintEngine::fill(const QVectorPath &path, const QBrush &brush) } // ### Optimize for non transformed ellipses and rectangles... - QRealRect r = path.controlPointRect(); - QRectF cpRect(r.x1, r.y1, r.x2 - r.x1, r.y2 - r.y1); + QRectF cpRect = path.controlPointRect(); const QRect deviceRect = s->matrix.mapRect(cpRect).toRect(); ProcessSpans blend = d->getBrushFunc(deviceRect, &s->brushData); diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index d2671c8..67a3fa9 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -56,15 +56,15 @@ QT_BEGIN_NAMESPACE * */ -const QRealRect &QVectorPath::controlPointRect() const +QRectF QVectorPath::controlPointRect() const { if (m_hints & ControlPointRect) - return m_cp_rect; + return QRectF(QPointF(m_cp_rect.x1, m_cp_rect.y1), QPointF(m_cp_rect.x2, m_cp_rect.y2)); if (m_count == 0) { m_cp_rect.x1 = m_cp_rect.x2 = m_cp_rect.y1 = m_cp_rect.y2 = 0; m_hints |= ControlPointRect; - return m_cp_rect; + return QRectF(QPointF(m_cp_rect.x1, m_cp_rect.y1), QPointF(m_cp_rect.x2, m_cp_rect.y2)); } Q_ASSERT(m_points && m_count > 0); @@ -88,7 +88,7 @@ const QRealRect &QVectorPath::controlPointRect() const } m_hints |= ControlPointRect; - return m_cp_rect; + return QRectF(QPointF(m_cp_rect.x1, m_cp_rect.y1), QPointF(m_cp_rect.x2, m_cp_rect.y2)); } const QVectorPath &qtVectorPathForPath(const QPainterPath &path) @@ -100,9 +100,7 @@ const QVectorPath &qtVectorPathForPath(const QPainterPath &path) #ifndef QT_NO_DEBUG_STREAM QDebug Q_GUI_EXPORT &operator<<(QDebug &s, const QVectorPath &path) { - QRealRect vectorPathBounds = path.controlPointRect(); - QRectF rf(vectorPathBounds.x1, vectorPathBounds.y1, - vectorPathBounds.x2 - vectorPathBounds.x1, vectorPathBounds.y2 - vectorPathBounds.y1); + QRectF rf = path.controlPointRect(); s << "QVectorPath(size:" << path.elementCount() << " hints:" << hex << path.hints() << rf << ')'; diff --git a/src/gui/painting/qvectorpath_p.h b/src/gui/painting/qvectorpath_p.h index 2602a3d..b073f8c 100644 --- a/src/gui/painting/qvectorpath_p.h +++ b/src/gui/painting/qvectorpath_p.h @@ -112,7 +112,7 @@ public: { } - const QRealRect &controlPointRect() const; + QRectF controlPointRect() const; inline Hint shape() const { return (Hint) (m_hints & ShapeHintMask); } -- cgit v0.12 From 747444c6776d948dad479e7b6f3564d0515d4e52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Wed, 10 Jun 2009 16:46:39 +0200 Subject: Fixed memory leak in raster paint engine. Unlike the span array, the clip line array is only free'd in the destructor, so if it's already allocated we shouldn't allocate it again. Reviewed-by: Denis Dzyubenko --- src/gui/painting/qpaintengine_raster.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gui/painting/qpaintengine_raster.cpp b/src/gui/painting/qpaintengine_raster.cpp index 2ce1d09..4711455 100644 --- a/src/gui/painting/qpaintengine_raster.cpp +++ b/src/gui/painting/qpaintengine_raster.cpp @@ -4332,7 +4332,9 @@ void QClipData::initialize() if (m_spans) return; - m_clipLines = (ClipLine *)calloc(sizeof(ClipLine), clipSpanHeight); + if (!m_clipLines) + m_clipLines = (ClipLine *)calloc(sizeof(ClipLine), clipSpanHeight); + m_spans = (QSpan *)malloc(clipSpanHeight*sizeof(QSpan)); allocated = clipSpanHeight; -- cgit v0.12 From 4a8a851315ba10824ac107084ccff9de649418ea Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 10 Jun 2009 15:31:43 +0200 Subject: removed superflous indirection (ie. using q->..) instead of using the private class member. --- src/gui/graphicsview/qgraphicsitem_p.h | 2 +- src/gui/graphicsview/qgraphicsview.cpp | 63 +++++++++++++++------------------ src/gui/itemviews/qabstractitemview.cpp | 12 +++---- src/gui/itemviews/qcolumnview.cpp | 38 ++++++++++---------- src/gui/itemviews/qheaderview.cpp | 7 ++-- src/gui/itemviews/qlistview.cpp | 10 +++--- src/gui/itemviews/qtreeview.cpp | 45 +++++++++++------------ src/gui/kernel/qwidget.cpp | 4 +-- src/gui/text/qtextcontrol.cpp | 2 +- src/gui/widgets/qabstractbutton.cpp | 20 +++++------ src/gui/widgets/qmdiarea.cpp | 32 ++++++++--------- src/gui/widgets/qmdisubwindow.cpp | 24 ++++++------- src/gui/widgets/qmdisubwindow_p.h | 2 +- 13 files changed, 123 insertions(+), 138 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index c502655..5626867 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -365,7 +365,7 @@ public: QGraphicsScene *scene; QGraphicsItem *parent; QList children; - class TransformData; + struct TransformData; TransformData *transformData; QTransform sceneTransform; int index; diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 4891e81..4a8099c 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -387,7 +387,7 @@ void QGraphicsViewPrivate::recalculateContentSize() int left = q_round_bound(viewRect.left()); int right = q_round_bound(viewRect.right() - width); if (left >= right) { - q->horizontalScrollBar()->setRange(0, 0); + hbar->setRange(0, 0); switch (alignment & Qt::AlignHorizontal_Mask) { case Qt::AlignLeft: @@ -402,9 +402,9 @@ void QGraphicsViewPrivate::recalculateContentSize() break; } } else { - q->horizontalScrollBar()->setRange(left, right); - q->horizontalScrollBar()->setPageStep(width); - q->horizontalScrollBar()->setSingleStep(width / 20); + hbar->setRange(left, right); + hbar->setPageStep(width); + hbar->setSingleStep(width / 20); leftIndent = 0; } @@ -413,7 +413,7 @@ void QGraphicsViewPrivate::recalculateContentSize() int top = q_round_bound(viewRect.top()); int bottom = q_round_bound(viewRect.bottom() - height); if (top >= bottom) { - q->verticalScrollBar()->setRange(0, 0); + vbar->setRange(0, 0); switch (alignment & Qt::AlignVertical_Mask) { case Qt::AlignTop: @@ -428,9 +428,9 @@ void QGraphicsViewPrivate::recalculateContentSize() break; } } else { - q->verticalScrollBar()->setRange(top, bottom); - q->verticalScrollBar()->setPageStep(height); - q->verticalScrollBar()->setSingleStep(height / 20); + vbar->setRange(top, bottom); + vbar->setPageStep(height); + vbar->setSingleStep(height / 20); topIndent = 0; } @@ -442,7 +442,7 @@ void QGraphicsViewPrivate::recalculateContentSize() // scroll instead. if (oldLeftIndent != leftIndent || oldTopIndent != topIndent) { dirtyScroll = true; - q->viewport()->update(); + viewport->update(); } else if (q->isRightToLeft() && !leftIndent) { // In reverse mode, the horizontal scroll always changes after the content // size has changed, as the scroll is calculated by summing the min and @@ -468,7 +468,7 @@ void QGraphicsViewPrivate::centerView(QGraphicsView::ViewportAnchor anchor) if (q->underMouse()) { // Last scene pos: lastMouseMoveScenePoint // Current mouse pos: - QPointF transformationDiff = q->mapToScene(q->viewport()->rect().center()) + QPointF transformationDiff = q->mapToScene(viewport->rect().center()) - q->mapToScene(q->mapFromGlobal(QCursor::pos())); q->centerOn(lastMouseMoveScenePoint + transformationDiff);; } else { @@ -490,7 +490,7 @@ void QGraphicsViewPrivate::centerView(QGraphicsView::ViewportAnchor anchor) void QGraphicsViewPrivate::updateLastCenterPoint() { Q_Q(QGraphicsView); - lastCenterPoint = q->mapToScene(q->viewport()->rect().center()); + lastCenterPoint = q->mapToScene(viewport->rect().center()); } /*! @@ -528,15 +528,15 @@ void QGraphicsViewPrivate::updateScroll() scrollX = qint64(-leftIndent); if (q->isRightToLeft()) { if (!leftIndent) { - scrollX += q->horizontalScrollBar()->minimum(); - scrollX += q->horizontalScrollBar()->maximum(); - scrollX -= q->horizontalScrollBar()->value(); + scrollX += hbar->minimum(); + scrollX += hbar->maximum(); + scrollX -= hbar->value(); } } else { - scrollX += q->horizontalScrollBar()->value(); + scrollX += hbar->value(); } - scrollY = qint64(q->verticalScrollBar()->value() - topIndent); + scrollY = qint64(vbar->value() - topIndent); dirtyScroll = false; } @@ -576,7 +576,7 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event) return; QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove); - mouseEvent.setWidget(q->viewport()); + mouseEvent.setWidget(viewport); mouseEvent.setButtonDownScenePos(mousePressButton, mousePressScenePoint); mouseEvent.setButtonDownScreenPos(mousePressButton, mousePressScreenPoint); mouseEvent.setScenePos(q->mapToScene(event->pos())); @@ -623,7 +623,7 @@ void QGraphicsViewPrivate::mouseMoveEventHandler(QMouseEvent *event) if (hasStoredOriginalCursor) { // Restore the original viewport cursor. hasStoredOriginalCursor = false; - q->viewport()->setCursor(originalCursor); + viewport->setCursor(originalCursor); } #endif } @@ -655,8 +655,6 @@ QRegion QGraphicsViewPrivate::rubberBandRegion(const QWidget *widget, const QRec #ifndef QT_NO_CURSOR void QGraphicsViewPrivate::_q_setViewportCursor(const QCursor &cursor) { - Q_Q(QGraphicsView); - QWidget *viewport = q->viewport(); if (!hasStoredOriginalCursor) { hasStoredOriginalCursor = true; originalCursor = viewport->cursor(); @@ -682,9 +680,9 @@ void QGraphicsViewPrivate::_q_unsetViewportCursor() // Restore the original viewport cursor. hasStoredOriginalCursor = false; if (dragMode == QGraphicsView::ScrollHandDrag) - q->viewport()->setCursor(Qt::OpenHandCursor); + viewport->setCursor(Qt::OpenHandCursor); else - q->viewport()->setCursor(originalCursor); + viewport->setCursor(originalCursor); } #endif @@ -723,7 +721,7 @@ void QGraphicsViewPrivate::populateSceneDragDropEvent(QGraphicsSceneDragDropEven dest->setProposedAction(source->proposedAction()); dest->setDropAction(source->dropAction()); dest->setMimeData(source->mimeData()); - dest->setWidget(q->viewport()); + dest->setWidget(viewport); dest->setSource(source->source()); #else Q_UNUSED(dest) @@ -827,8 +825,7 @@ void QGraphicsViewPrivate::processPendingUpdates() void QGraphicsViewPrivate::updateAll() { - Q_Q(QGraphicsView); - q->viewport()->update(); + viewport->update(); fullUpdatePending = true; dirtyBoundingRect = QRect(); dirtyRegion = QRegion(); @@ -839,19 +836,17 @@ void QGraphicsViewPrivate::updateRegion(const QRegion &r) if (r.isEmpty() || fullUpdatePending) return; - Q_Q(QGraphicsView); - // Rect intersects viewport - update everything? switch (viewportUpdateMode) { case QGraphicsView::FullViewportUpdate: fullUpdatePending = true; - q->viewport()->update(); + viewport->update(); break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r.boundingRect(); - if (dirtyBoundingRect.contains(q->viewport()->rect())) { + if (dirtyBoundingRect.contains(viewport->rect())) { fullUpdatePending = true; - q->viewport()->update(); + viewport->update(); } break; case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE @@ -875,19 +870,17 @@ void QGraphicsViewPrivate::updateRect(const QRect &r) if (r.isEmpty() || fullUpdatePending) return; - Q_Q(QGraphicsView); - // Rect intersects viewport - update everything? switch (viewportUpdateMode) { case QGraphicsView::FullViewportUpdate: fullUpdatePending = true; - q->viewport()->update(); + viewport->update(); break; case QGraphicsView::BoundingRectViewportUpdate: dirtyBoundingRect |= r; - if (dirtyBoundingRect.contains(q->viewport()->rect())) { + if (dirtyBoundingRect.contains(viewport->rect())) { fullUpdatePending = true; - q->viewport()->update(); + viewport->update(); } break; case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE diff --git a/src/gui/itemviews/qabstractitemview.cpp b/src/gui/itemviews/qabstractitemview.cpp index d353c2d..7890e1f 100644 --- a/src/gui/itemviews/qabstractitemview.cpp +++ b/src/gui/itemviews/qabstractitemview.cpp @@ -108,16 +108,16 @@ void QAbstractItemViewPrivate::init() Q_Q(QAbstractItemView); q->setItemDelegate(new QStyledItemDelegate(q)); - q->verticalScrollBar()->setRange(0, 0); - q->horizontalScrollBar()->setRange(0, 0); + vbar->setRange(0, 0); + hbar->setRange(0, 0); - QObject::connect(q->verticalScrollBar(), SIGNAL(actionTriggered(int)), + QObject::connect(vbar, SIGNAL(actionTriggered(int)), q, SLOT(verticalScrollbarAction(int))); - QObject::connect(q->horizontalScrollBar(), SIGNAL(actionTriggered(int)), + QObject::connect(hbar, SIGNAL(actionTriggered(int)), q, SLOT(horizontalScrollbarAction(int))); - QObject::connect(q->verticalScrollBar(), SIGNAL(valueChanged(int)), + QObject::connect(vbar, SIGNAL(valueChanged(int)), q, SLOT(verticalScrollbarValueChanged(int))); - QObject::connect(q->horizontalScrollBar(), SIGNAL(valueChanged(int)), + QObject::connect(hbar, SIGNAL(valueChanged(int)), q, SLOT(horizontalScrollbarValueChanged(int))); viewport->setBackgroundRole(QPalette::Base); diff --git a/src/gui/itemviews/qcolumnview.cpp b/src/gui/itemviews/qcolumnview.cpp index 4fb08bb..1f88f7c 100644 --- a/src/gui/itemviews/qcolumnview.cpp +++ b/src/gui/itemviews/qcolumnview.cpp @@ -108,9 +108,9 @@ void QColumnViewPrivate::initialize() { Q_Q(QColumnView); q->setTextElideMode(Qt::ElideMiddle); - q->connect(¤tAnimation, SIGNAL(frameChanged(int)), - q->horizontalScrollBar(), SLOT(setValue(int))); - q->connect(¤tAnimation, SIGNAL(finished()), q, SLOT(_q_changeCurrentColumn())); + QObject::connect(¤tAnimation, SIGNAL(frameChanged(int)), + hbar, SLOT(setValue(int))); + QObject::connect(¤tAnimation, SIGNAL(finished()), q, SLOT(_q_changeCurrentColumn())); delete itemDelegate; q->setItemDelegate(new QColumnViewDelegate(q)); } @@ -421,23 +421,23 @@ void QColumnViewPrivate::updateScrollbars() horizontalLength = (columns.first()->x() + columns.first()->width()) - columns.last()->x(); } - QSize viewportSize = q->viewport()->size(); - if (horizontalLength < viewportSize.width() && q->horizontalScrollBar()->value() == 0) { - q->horizontalScrollBar()->setRange(0, 0); + QSize viewportSize = viewport->size(); + if (horizontalLength < viewportSize.width() && hbar->value() == 0) { + hbar->setRange(0, 0); } else { int visibleLength = qMin(horizontalLength + q->horizontalOffset(), viewportSize.width()); int hiddenLength = horizontalLength - visibleLength; - if (hiddenLength != q->horizontalScrollBar()->maximum()) - q->horizontalScrollBar()->setRange(0, hiddenLength); + if (hiddenLength != hbar->maximum()) + hbar->setRange(0, hiddenLength); } if (!columns.isEmpty()) { int pageStepSize = columns.at(0)->width(); - if (pageStepSize != q->horizontalScrollBar()->pageStep()) - q->horizontalScrollBar()->setPageStep(pageStepSize); + if (pageStepSize != hbar->pageStep()) + hbar->setPageStep(pageStepSize); } - bool visible = (q->horizontalScrollBar()->maximum() > 0); - if (visible != q->horizontalScrollBar()->isVisible()) - q->horizontalScrollBar()->setVisible(visible); + bool visible = (hbar->maximum() > 0); + if (visible != hbar->isVisible()) + hbar->setVisible(visible); } /*! @@ -696,7 +696,7 @@ QAbstractItemView *QColumnViewPrivate::createColumn(const QModelIndex &index, bo q, SIGNAL(pressed(const QModelIndex &))); view->setFocusPolicy(Qt::NoFocus); - view->setParent(q->viewport()); + view->setParent(viewport); Q_ASSERT(view); // Setup corner grip @@ -707,13 +707,13 @@ QAbstractItemView *QColumnViewPrivate::createColumn(const QModelIndex &index, bo } if (columnSizes.count() > columns.count()) { - view->setGeometry(0, 0, columnSizes.at(columns.count()), q->viewport()->height()); + view->setGeometry(0, 0, columnSizes.at(columns.count()), viewport->height()); } else { int initialWidth = view->sizeHint().width(); if (q->isRightToLeft()) - view->setGeometry(q->viewport()->width() - initialWidth, 0, initialWidth, q->viewport()->height()); + view->setGeometry(viewport->width() - initialWidth, 0, initialWidth, viewport->height()); else - view->setGeometry(0, 0, initialWidth, q->viewport()->height()); + view->setGeometry(0, 0, initialWidth, viewport->height()); columnSizes.resize(qMax(columnSizes.count(), columns.count() + 1)); columnSizes[columns.count()] = initialWidth; } @@ -1056,11 +1056,11 @@ void QColumnViewPrivate::doLayout() if (!model || columns.isEmpty()) return; - int viewportHeight = q->viewport()->height(); + int viewportHeight = viewport->height(); int x = columns.at(0)->x(); if (q->isRightToLeft()) { - x = q->viewport()->width() + q->horizontalOffset(); + x = viewport->width() + q->horizontalOffset(); for (int i = 0; i < columns.size(); ++i) { QAbstractItemView *view = columns.at(i); x -= view->width(); diff --git a/src/gui/itemviews/qheaderview.cpp b/src/gui/itemviews/qheaderview.cpp index 7ad825a..d0321d8 100644 --- a/src/gui/itemviews/qheaderview.cpp +++ b/src/gui/itemviews/qheaderview.cpp @@ -3474,11 +3474,10 @@ void QHeaderViewPrivate::setGlobalHeaderResizeMode(QHeaderView::ResizeMode mode) int QHeaderViewPrivate::viewSectionSizeHint(int logical) const { - Q_Q(const QHeaderView); - if (QAbstractItemView *parent = qobject_cast(q->parent())) { + if (QAbstractItemView *view = qobject_cast(parent)) { return (orientation == Qt::Horizontal - ? parent->sizeHintForColumn(logical) - : parent->sizeHintForRow(logical)); + ? view->sizeHintForColumn(logical) + : view->sizeHintForRow(logical)); } return 0; } diff --git a/src/gui/itemviews/qlistview.cpp b/src/gui/itemviews/qlistview.cpp index 03ba641..fe7916c 100644 --- a/src/gui/itemviews/qlistview.cpp +++ b/src/gui/itemviews/qlistview.cpp @@ -610,7 +610,7 @@ int QListViewPrivate::horizontalScrollToValue(const QModelIndex &index, const QR const bool rightOf = q->isRightToLeft() ? rect.right() > area.right() : (rect.right() > area.right()) && (rect.left() > area.left()); - int horizontalValue = q->horizontalScrollBar()->value(); + int horizontalValue = hbar->value(); // ScrollPerItem if (q->horizontalScrollMode() == QAbstractItemView::ScrollPerItem && viewMode == QListView::ListMode) { @@ -652,10 +652,10 @@ int QListViewPrivate::verticalScrollToValue(const QModelIndex &index, const QRec const bool above = (hint == QListView::EnsureVisible && rect.top() < area.top()); const bool below = (hint == QListView::EnsureVisible && rect.bottom() > area.bottom()); - int verticalValue = q->verticalScrollBar()->value(); + int verticalValue = vbar->value(); // ScrollPerItem - if (q->verticalScrollMode() == QAbstractItemView::ScrollPerItem && viewMode == QListView::ListMode) { + if (verticalScrollMode == QAbstractItemView::ScrollPerItem && viewMode == QListView::ListMode) { const QListViewItem item = indexToListViewItem(index); const QRect rect = q->visualRect(index); verticalValue = staticListView->verticalPerItemValue(itemIndex(item), @@ -1972,10 +1972,10 @@ void QListViewPrivate::prepareItemsLayout() // Qt::ScrollBarAlwaysOn but scrollbar extent must be deduced if policy // is Qt::ScrollBarAsNeeded int verticalMargin = vbarpolicy==Qt::ScrollBarAsNeeded - ? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, q->verticalScrollBar()) + frameAroundContents + ? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, vbar) + frameAroundContents : 0; int horizontalMargin = hbarpolicy==Qt::ScrollBarAsNeeded - ? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, q->horizontalScrollBar()) + frameAroundContents + ? q->style()->pixelMetric(QStyle::PM_ScrollBarExtent, 0, hbar) + frameAroundContents : 0; layoutBounds.adjust(0, 0, -verticalMargin, -horizontalMargin); diff --git a/src/gui/itemviews/qtreeview.cpp b/src/gui/itemviews/qtreeview.cpp index 9910118..53fa170 100644 --- a/src/gui/itemviews/qtreeview.cpp +++ b/src/gui/itemviews/qtreeview.cpp @@ -1319,7 +1319,7 @@ bool QTreeViewPrivate::expandOrCollapseItemAtPos(const QPoint &pos) expand(i, true); if (!isAnimating()) { q->updateGeometries(); - q->viewport()->update(); + viewport->update(); } return true; } @@ -3201,19 +3201,18 @@ int QTreeViewPrivate::itemHeight(int item) const */ int QTreeViewPrivate::coordinateForItem(int item) const { - Q_Q(const QTreeView); if (verticalScrollMode == QAbstractItemView::ScrollPerPixel) { if (uniformRowHeights) - return (item * defaultItemHeight) - q->verticalScrollBar()->value(); + return (item * defaultItemHeight) - vbar->value(); // ### optimize (spans or caching) int y = 0; for (int i = 0; i < viewItems.count(); ++i) { if (i == item) - return y - q->verticalScrollBar()->value(); + return y - vbar->value(); y += itemHeight(i); } } else { // ScrollPerItem - int topViewItemIndex = q->verticalScrollBar()->value(); + int topViewItemIndex = vbar->value(); if (uniformRowHeights) return defaultItemHeight * (item - topViewItemIndex); if (item >= topViewItemIndex) { @@ -3253,7 +3252,6 @@ int QTreeViewPrivate::coordinateForItem(int item) const */ int QTreeViewPrivate::itemAtCoordinate(int coordinate) const { - Q_Q(const QTreeView); const int itemCount = viewItems.count(); if (itemCount == 0) return -1; @@ -3261,19 +3259,19 @@ int QTreeViewPrivate::itemAtCoordinate(int coordinate) const return -1; if (verticalScrollMode == QAbstractItemView::ScrollPerPixel) { if (uniformRowHeights) { - const int viewItemIndex = (coordinate + q->verticalScrollBar()->value()) / defaultItemHeight; + const int viewItemIndex = (coordinate + vbar->value()) / defaultItemHeight; return ((viewItemIndex >= itemCount || viewItemIndex < 0) ? -1 : viewItemIndex); } // ### optimize int viewItemCoordinate = 0; - const int contentsCoordinate = coordinate + q->verticalScrollBar()->value(); + const int contentsCoordinate = coordinate + vbar->value(); for (int viewItemIndex = 0; viewItemIndex < viewItems.count(); ++viewItemIndex) { viewItemCoordinate += itemHeight(viewItemIndex); if (viewItemCoordinate >= contentsCoordinate) return (viewItemIndex >= itemCount ? -1 : viewItemIndex); } } else { // ScrollPerItem - int topViewItemIndex = q->verticalScrollBar()->value(); + int topViewItemIndex = vbar->value(); if (uniformRowHeights) { if (coordinate < 0) coordinate -= defaultItemHeight - 1; @@ -3365,8 +3363,7 @@ QModelIndex QTreeViewPrivate::modelIndex(int i, int column) const int QTreeViewPrivate::firstVisibleItem(int *offset) const { - Q_Q(const QTreeView); - const int value = q->verticalScrollBar()->value(); + const int value = vbar->value(); if (verticalScrollMode == QAbstractItemView::ScrollPerItem) { if (offset) *offset = 0; @@ -3443,9 +3440,9 @@ void QTreeViewPrivate::updateScrollBars() if (verticalScrollMode == QAbstractItemView::ScrollPerItem) { if (!viewItems.isEmpty()) itemsInViewport = qMax(1, itemsInViewport); - q->verticalScrollBar()->setRange(0, viewItems.count() - itemsInViewport); - q->verticalScrollBar()->setPageStep(itemsInViewport); - q->verticalScrollBar()->setSingleStep(1); + vbar->setRange(0, viewItems.count() - itemsInViewport); + vbar->setPageStep(itemsInViewport); + vbar->setSingleStep(1); } else { // scroll per pixel int contentsHeight = 0; if (uniformRowHeights) { @@ -3454,9 +3451,9 @@ void QTreeViewPrivate::updateScrollBars() for (int i = 0; i < viewItems.count(); ++i) contentsHeight += itemHeight(i); } - q->verticalScrollBar()->setRange(0, contentsHeight - viewportSize.height()); - q->verticalScrollBar()->setPageStep(viewportSize.height()); - q->verticalScrollBar()->setSingleStep(qMax(viewportSize.height() / (itemsInViewport + 1), 2)); + vbar->setRange(0, contentsHeight - viewportSize.height()); + vbar->setPageStep(viewportSize.height()); + vbar->setSingleStep(qMax(viewportSize.height() / (itemsInViewport + 1), 2)); } const int columnCount = header->count(); @@ -3472,17 +3469,17 @@ void QTreeViewPrivate::updateScrollBars() if (columnCount > 0) columnsInViewport = qMax(1, columnsInViewport); if (horizontalScrollMode == QAbstractItemView::ScrollPerItem) { - q->horizontalScrollBar()->setRange(0, columnCount - columnsInViewport); - q->horizontalScrollBar()->setPageStep(columnsInViewport); - q->horizontalScrollBar()->setSingleStep(1); + hbar->setRange(0, columnCount - columnsInViewport); + hbar->setPageStep(columnsInViewport); + hbar->setSingleStep(1); } else { // scroll per pixel const int horizontalLength = header->length(); const QSize maxSize = q->maximumViewportSize(); - if (maxSize.width() >= horizontalLength && q->verticalScrollBar()->maximum() <= 0) + if (maxSize.width() >= horizontalLength && vbar->maximum() <= 0) viewportSize = maxSize; - q->horizontalScrollBar()->setPageStep(viewportSize.width()); - q->horizontalScrollBar()->setRange(0, qMax(horizontalLength - viewportSize.width(), 0)); - q->horizontalScrollBar()->setSingleStep(qMax(viewportSize.width() / (columnsInViewport + 1), 2)); + hbar->setPageStep(viewportSize.width()); + hbar->setRange(0, qMax(horizontalLength - viewportSize.width(), 0)); + hbar->setSingleStep(qMax(viewportSize.width() / (columnsInViewport + 1), 2)); } } diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index 6026821..61d8f20 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -1067,7 +1067,7 @@ void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f) q->data = &data; #ifndef QT_NO_THREAD - if (!q->parent()) { + if (!parent) { Q_ASSERT_X(q->thread() == qApp->thread(), "QWidget", "Widgets must be created in the GUI thread."); } @@ -4993,7 +4993,7 @@ void QWidgetPrivate::drawWidget(QPaintDevice *pdev, const QRegion &rgn, const QP QPoint scrollAreaOffset; #ifndef QT_NO_SCROLLAREA - QAbstractScrollArea *scrollArea = qobject_cast(q->parent()); + QAbstractScrollArea *scrollArea = qobject_cast(parent); if (scrollArea && scrollArea->viewport() == q) { QObjectData *scrollPrivate = static_cast(scrollArea)->d_ptr; QAbstractScrollAreaPrivate *priv = static_cast(scrollPrivate); diff --git a/src/gui/text/qtextcontrol.cpp b/src/gui/text/qtextcontrol.cpp index 0958b52..780891b 100644 --- a/src/gui/text/qtextcontrol.cpp +++ b/src/gui/text/qtextcontrol.cpp @@ -394,7 +394,7 @@ void QTextControlPrivate::init(Qt::TextFormat format, const QString &text, QText Q_Q(QTextControl); setContent(format, text, document); - QWidget *parentWidget = qobject_cast(q->parent()); + QWidget *parentWidget = qobject_cast(parent); if (parentWidget) { QTextOption opt = doc->defaultTextOption(); opt.setTextDirection(parentWidget->layoutDirection()); diff --git a/src/gui/widgets/qabstractbutton.cpp b/src/gui/widgets/qabstractbutton.cpp index 1900016..f28288e 100644 --- a/src/gui/widgets/qabstractbutton.cpp +++ b/src/gui/widgets/qabstractbutton.cpp @@ -319,20 +319,16 @@ QListQAbstractButtonPrivate::queryButtonList() const return group->d_func()->buttonList; #endif - Q_Q(const QAbstractButton); - QListcandidates; - if (q->parentWidget()) { - candidates = qFindChildren(q->parentWidget()); - if (autoExclusive) { - for (int i = candidates.count() - 1; i >= 0; --i) { - QAbstractButton *candidate = candidates.at(i); - if (!candidate->autoExclusive() + QListcandidates = qFindChildren(parent); + if (autoExclusive) { + for (int i = candidates.count() - 1; i >= 0; --i) { + QAbstractButton *candidate = candidates.at(i); + if (!candidate->autoExclusive() #ifndef QT_NO_BUTTONGROUP - || candidate->group() + || candidate->group() #endif - ) - candidates.removeAt(i); - } + ) + candidates.removeAt(i); } } return candidates; diff --git a/src/gui/widgets/qmdiarea.cpp b/src/gui/widgets/qmdiarea.cpp index 6acd977..0235c04 100644 --- a/src/gui/widgets/qmdiarea.cpp +++ b/src/gui/widgets/qmdiarea.cpp @@ -800,12 +800,12 @@ void QMdiAreaPrivate::appendChild(QMdiSubWindow *child) Q_Q(QMdiArea); Q_ASSERT(child && childWindows.indexOf(child) == -1); - if (child->parent() != q->viewport()) - child->setParent(q->viewport(), child->windowFlags()); + if (child->parent() != viewport) + child->setParent(viewport, child->windowFlags()); childWindows.append(QPointer(child)); if (!child->testAttribute(Qt::WA_Resized) && q->isVisible()) { - QSize newSize(child->sizeHint().boundedTo(q->viewport()->size())); + QSize newSize(child->sizeHint().boundedTo(viewport->size())); child->resize(newSize.expandedTo(qSmartMinSize(child))); } @@ -931,7 +931,7 @@ void QMdiAreaPrivate::rearrange(Rearranger *rearranger) widgets.move(indexToActive, 0); } - QRect domain = q->viewport()->rect(); + QRect domain = viewport->rect(); if (rearranger->type() == Rearranger::RegularTiler && !widgets.isEmpty()) domain = resizeToMinimumTileSize(minSubWindowSize, widgets.count()); @@ -1236,7 +1236,7 @@ QRect QMdiAreaPrivate::resizeToMinimumTileSize(const QSize &minSubWindowSize, in { Q_Q(QMdiArea); if (!minSubWindowSize.isValid() || subWindowCount <= 0) - return q->viewport()->rect(); + return viewport->rect(); // Calculate minimum size. const int columns = qMax(qCeil(qSqrt(qreal(subWindowCount))), 1); @@ -1255,10 +1255,10 @@ QRect QMdiAreaPrivate::resizeToMinimumTileSize(const QSize &minSubWindowSize, in // We don't want sub-subwindows to be placed at the edge, thus add 2 pixels. int minAreaWidth = minWidth + left + right + 2; int minAreaHeight = minHeight + top + bottom + 2; - if (q->horizontalScrollBar()->isVisible()) - minAreaHeight += q->horizontalScrollBar()->height(); - if (q->verticalScrollBar()->isVisible()) - minAreaWidth += q->verticalScrollBar()->width(); + if (hbar->isVisible()) + minAreaHeight += hbar->height(); + if (vbar->isVisible()) + minAreaWidth += vbar->width(); if (q->style()->styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, 0, q)) { const int frame = q->style()->pixelMetric(QStyle::PM_DefaultFrameWidth, 0, q); minAreaWidth += 2 * frame; @@ -1268,23 +1268,23 @@ QRect QMdiAreaPrivate::resizeToMinimumTileSize(const QSize &minSubWindowSize, in topLevel->resize(topLevel->size() + diff); } - QRect domain = q->viewport()->rect(); + QRect domain = viewport->rect(); // Adjust domain width and provide horizontal scroll bar. if (domain.width() < minWidth) { domain.setWidth(minWidth); - if (q->horizontalScrollBarPolicy() == Qt::ScrollBarAlwaysOff) + if (hbarpolicy == Qt::ScrollBarAlwaysOff) q->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded); - else if (q->horizontalScrollBar()->value() != 0) - q->horizontalScrollBar()->setValue(0); + else + hbar->setValue(0); } // Adjust domain height and provide vertical scroll bar. if (domain.height() < minHeight) { domain.setHeight(minHeight); - if (q->verticalScrollBarPolicy() == Qt::ScrollBarAlwaysOff) + if (vbarpolicy == Qt::ScrollBarAlwaysOff) q->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded); - else if (q->verticalScrollBar()->value() != 0) - q->verticalScrollBar()->setValue(0); + else + vbar->setValue(0); } return domain; } diff --git a/src/gui/widgets/qmdisubwindow.cpp b/src/gui/widgets/qmdisubwindow.cpp index 56df8ea..b366c28 100644 --- a/src/gui/widgets/qmdisubwindow.cpp +++ b/src/gui/widgets/qmdisubwindow.cpp @@ -1115,7 +1115,7 @@ void QMdiSubWindowPrivate::updateDirtyRegions() void QMdiSubWindowPrivate::updateGeometryConstraints() { Q_Q(QMdiSubWindow); - if (!q->parent()) + if (!parent) return; internalMinimumSize = (!q->isMinimized() && !q->minimumSize().isNull()) @@ -1145,7 +1145,7 @@ void QMdiSubWindowPrivate::updateMask() if (!q->mask().isEmpty()) q->clearMask(); - if (!q->parent()) + if (!parent) return; if ((q->isMaximized() && !drawTitleBarWhenMaximized()) @@ -1168,7 +1168,7 @@ void QMdiSubWindowPrivate::setNewGeometry(const QPoint &pos) { Q_Q(QMdiSubWindow); Q_ASSERT(currentOperation != None); - Q_ASSERT(q->parent()); + Q_ASSERT(parent); uint cflags = operationMap.find(currentOperation).value().changeFlags; int posX = pos.x(); @@ -1235,7 +1235,7 @@ void QMdiSubWindowPrivate::setNewGeometry(const QPoint &pos) void QMdiSubWindowPrivate::setMinimizeMode() { Q_Q(QMdiSubWindow); - Q_ASSERT(q->parent()); + Q_ASSERT(parent); ensureWindowState(Qt::WindowMinimized); isShadeRequestFromMinimizeMode = true; @@ -1263,7 +1263,7 @@ void QMdiSubWindowPrivate::setMinimizeMode() void QMdiSubWindowPrivate::setNormalMode() { Q_Q(QMdiSubWindow); - Q_ASSERT(q->parent()); + Q_ASSERT(parent); isShadeMode = false; isMaximizeMode = false; @@ -1334,7 +1334,7 @@ void QMdiSubWindowPrivate::setNormalMode() void QMdiSubWindowPrivate::setMaximizeMode() { Q_Q(QMdiSubWindow); - Q_ASSERT(q->parent()); + Q_ASSERT(parent); ensureWindowState(Qt::WindowMaximized); isShadeMode = false; @@ -1423,7 +1423,7 @@ void QMdiSubWindowPrivate::setMaximizeMode() void QMdiSubWindowPrivate::setActive(bool activate, bool changeFocus) { Q_Q(QMdiSubWindow); - if (!q->parent() || !activationEnabled) + if (!parent || !activationEnabled) return; if (activate && !isActive && q->isEnabled()) { @@ -1711,7 +1711,7 @@ void QMdiSubWindowPrivate::ensureWindowState(Qt::WindowState state) int QMdiSubWindowPrivate::titleBarHeight(const QStyleOptionTitleBar &options) const { Q_Q(const QMdiSubWindow); - if (!q->parent() || q->windowFlags() & Qt::FramelessWindowHint + if (!parent || q->windowFlags() & Qt::FramelessWindowHint || (q->isMaximized() && !drawTitleBarWhenMaximized())) { return 0; } @@ -1734,7 +1734,7 @@ void QMdiSubWindowPrivate::sizeParameters(int *margin, int *minWidth) const { Q_Q(const QMdiSubWindow); Qt::WindowFlags flags = q->windowFlags(); - if (!q->parent() || flags & Qt::FramelessWindowHint) { + if (!parent || flags & Qt::FramelessWindowHint) { *margin = 0; *minWidth = 0; return; @@ -1893,7 +1893,7 @@ void QMdiSubWindowPrivate::enterRubberBandMode() if (q->isMaximized()) return; Q_ASSERT(oldGeometry.isValid()); - Q_ASSERT(q->parent()); + Q_ASSERT(parent); if (!rubberBand) { rubberBand = new QRubberBand(QRubberBand::Rectangle, q->parentWidget()); // For accessibility to identify this special widget. @@ -2079,7 +2079,7 @@ void QMdiSubWindowPrivate::restoreFocus() void QMdiSubWindowPrivate::setWindowFlags(Qt::WindowFlags windowFlags) { Q_Q(QMdiSubWindow); - if (!q->parent()) { + if (!parent) { q->setWindowFlags(windowFlags); return; } @@ -2164,7 +2164,7 @@ void QMdiSubWindowPrivate::addToSystemMenu(WindowStateAction action, const QStri QSize QMdiSubWindowPrivate::iconSize() const { Q_Q(const QMdiSubWindow); - if (!q->parent() || q->windowFlags() & Qt::FramelessWindowHint) + if (!parent || q->windowFlags() & Qt::FramelessWindowHint) return QSize(-1, -1); return QSize(q->style()->pixelMetric(QStyle::PM_MdiSubWindowMinimizedWidth, 0, q), titleBarHeight()); } diff --git a/src/gui/widgets/qmdisubwindow_p.h b/src/gui/widgets/qmdisubwindow_p.h index 2e672d6..394f11c 100644 --- a/src/gui/widgets/qmdisubwindow_p.h +++ b/src/gui/widgets/qmdisubwindow_p.h @@ -287,7 +287,7 @@ public: inline int titleBarHeight() const { Q_Q(const QMdiSubWindow); - if (!q->parent() || q->windowFlags() & Qt::FramelessWindowHint + if (!parent || q->windowFlags() & Qt::FramelessWindowHint || (q->isMaximized() && !drawTitleBarWhenMaximized())) { return 0; } -- cgit v0.12 From 060727ed4f8b1ffea58229817640a03be5b095ed Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Wed, 10 Jun 2009 16:58:06 +0200 Subject: Adding support in QVariant for conversions between QUrl and QString Reviewed-by: ogoffart --- src/corelib/kernel/qvariant.cpp | 16 ++++++++++++++-- tests/auto/qvariant/tst_qvariant.cpp | 14 +++++++++++--- 2 files changed, 25 insertions(+), 5 deletions(-) diff --git a/src/corelib/kernel/qvariant.cpp b/src/corelib/kernel/qvariant.cpp index e6f1c48..a3434a4 100644 --- a/src/corelib/kernel/qvariant.cpp +++ b/src/corelib/kernel/qvariant.cpp @@ -591,6 +591,15 @@ static bool convert(const QVariant::Private *d, QVariant::Type t, void *result, ok = &dummy; switch (uint(t)) { + case QVariant::Url: + switch (d->type) { + case QVariant::String: + *static_cast(result) = QUrl(*v_cast(d)); + break; + default: + return false; + } + break; case QVariant::String: { QString *str = static_cast(result); switch (d->type) { @@ -640,6 +649,8 @@ static bool convert(const QVariant::Private *d, QVariant::Type t, void *result, if (v_cast(d)->count() == 1) *str = v_cast(d)->at(0); break; + case QVariant::Url: + *str = v_cast(d)->toString(); default: return false; } @@ -2484,7 +2495,8 @@ static const quint32 qCanConvertMatrix[QVariant::LastCoreType + 1] = /*QString*/ 1 << QVariant::StringList | 1 << QVariant::ByteArray | 1 << QVariant::Int | 1 << QVariant::UInt | 1 << QVariant::Bool | 1 << QVariant::Double | 1 << QVariant::Date | 1 << QVariant::Time | 1 << QVariant::DateTime - | 1 << QVariant::LongLong | 1 << QVariant::ULongLong | 1 << QVariant::Char, + | 1 << QVariant::LongLong | 1 << QVariant::ULongLong | 1 << QVariant::Char + | 1 << QVariant::Url, /*QStringList*/ 1 << QVariant::List | 1 << QVariant::String, @@ -2499,7 +2511,7 @@ static const quint32 qCanConvertMatrix[QVariant::LastCoreType + 1] = /*QDateTime*/ 1 << QVariant::String | 1 << QVariant::Date, -/*QUrl*/ 0, +/*QUrl*/ 1 << QVariant::String, /*QLocale*/ 0, diff --git a/tests/auto/qvariant/tst_qvariant.cpp b/tests/auto/qvariant/tst_qvariant.cpp index 0ede920..2d26914 100644 --- a/tests/auto/qvariant/tst_qvariant.cpp +++ b/tests/auto/qvariant/tst_qvariant.cpp @@ -2449,14 +2449,22 @@ void tst_QVariant::saveLoadCustomTypes() void tst_QVariant::url() { - QUrl url("http://www.trolltech.com"); + QString str("http://www.trolltech.com"); + QUrl url(str); - QVariant v(url); + QVariant v(url); //built with a QUrl QVariant v2 = v; - QVERIFY(v2.toUrl() == url); + QVariant v3(str); //built with a QString + QCOMPARE(v2.toUrl(), url); + QVERIFY(qVariantCanConvert(v3)); + QCOMPARE(v2.toUrl(), v3.toUrl()); + + QVERIFY(qVariantCanConvert(v2)); + QCOMPARE(v2.toString(), str); + QCOMPARE(v3.toString(), str); } void tst_QVariant::globalColor() -- cgit v0.12 From de74fcaeba4551afaa06f3d295e8e834fd5d3eb7 Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Wed, 10 Jun 2009 17:05:11 +0200 Subject: Some adjustments to the documentation Headers are slightly lighter now. Not all tables are affected by the changes any more. --- doc/src/index.qdoc | 20 ++++++------- tools/qdoc3/test/classic.css | 71 ++++++++++++++++++++++++-------------------- 2 files changed, 49 insertions(+), 42 deletions(-) diff --git a/doc/src/index.qdoc b/doc/src/index.qdoc index 23e8623..b18a50d 100644 --- a/doc/src/index.qdoc +++ b/doc/src/index.qdoc @@ -86,15 +86,15 @@ \endif \raw HTML - +
      - - - @@ -128,13 +128,13 @@ - - - @@ -194,13 +194,13 @@ - - - diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index 9c59c81..5087f9e 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -17,7 +17,7 @@ h3.fn,span.fn background-color: #eee; border-width: 1px; border-style: solid; - border-color: #ddd #ddd #ddd #ddd ; + border-color: #ddd; font-weight: bold; padding: 6px 0px 6px 10px; margin: 42px 0px 0px 0px; @@ -25,7 +25,7 @@ h3.fn,span.fn hr { border: 0; - color: #9E9E9E; + color: #a0a0a0; background-color: #ccc; height: 1px; width: 100%; @@ -33,7 +33,7 @@ hr { margin: 34px 0px 34px 0px; } -table { +table.valuelist { border-width: 1px 1px 1px 1px; border-style: solid; border-color: #dddddd; @@ -43,13 +43,32 @@ table { width: 97% } -table th { +table.indextable { + border-width: 1px 1px 1px 1px; + border-collapse: collapse; + background-color: #f0f0f0; + border-color:#555; + margin-left: 1.5%; + width: 97% +} + + +table.valuelist th { border-width: 1px 1px 1px 2px; padding: 4px; border-style: solid; + border-color: #666; + color:white; + background-color:#666; +} + +th.titleheader { + border-width: 1px 0px 1px 0px; + padding: 4px; + border-style: solid; border-color: #444; color:white; - background-color:#444; + background-color:#555555; } p { @@ -101,42 +120,30 @@ body color: black } +table.generic, table.annotated +{ + border-width: 1px; + border-color:#bbb; + border-style:solid; + border-collapse:collapse; +} + table td.memItemLeft { - width: 200px; + width: 160px; padding: 2px 0px 0px 8px; margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: none; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - background-color: #FAFAFA; + border-width: 1px; + border-color: #E0E0E0; + border-style: none; font-size: 100%; white-space: nowrap } table td.memItemRight { padding: 2px 8px 0px 8px; margin: 4px; - border-top-width: 1px; - border-right-width: 1px; - border-bottom-width: 1px; - border-left-width: 1px; - border-top-color: #E0E0E0; - border-right-color: #E0E0E0; - border-bottom-color: #E0E0E0; - border-left-color: #E0E0E0; - border-top-style: none; - border-right-style: none; - border-bottom-style: none; - border-left-style: none; - background-color: #FAFAFA; + border-width: 1px; + border-color: #E0E0E0; + border-style: none; font-size: 100%; } -- cgit v0.12 From 4eda7463c9626ab47ef465a5174887250b7561d9 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Wed, 10 Jun 2009 17:10:44 +0200 Subject: qdoc: Fixed XML-level breakage. Reviewed-by: Trust Me --- tools/qdoc3/htmlgenerator.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/qdoc3/htmlgenerator.cpp b/tools/qdoc3/htmlgenerator.cpp index cff8331..8df932e 100644 --- a/tools/qdoc3/htmlgenerator.cpp +++ b/tools/qdoc3/htmlgenerator.cpp @@ -2424,7 +2424,7 @@ void HtmlGenerator::generateSectionInheritedList(const Section& section, QList >::ConstIterator p = section.inherited.begin(); while (p != section.inherited.end()) { if (nameAlignment) - out() << "
    • "; + out() << "
    • "; else out() << "
    • "; out() << (*p).second << " "; @@ -2712,7 +2712,7 @@ void HtmlGenerator::generateSectionInheritedList(const Section& section, { QList >::ConstIterator p = section.inherited.begin(); while (p != section.inherited.end()) { - out() << "
    • "; + out() << "
    • "; out() << (*p).second << " "; if ((*p).second == 1) { out() << section.singularMember; -- cgit v0.12 From 11730b27413218c9e9bf1fc35f5e46a35baad874 Mon Sep 17 00:00:00 2001 From: Joerg Bornemann Date: Wed, 10 Jun 2009 16:09:46 +0200 Subject: tst_qpixmap compile fix QPixmap(QImage) works with Qt3 support only... Reviewed-by: thartman --- tests/auto/qpixmap/tst_qpixmap.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/auto/qpixmap/tst_qpixmap.cpp b/tests/auto/qpixmap/tst_qpixmap.cpp index 8a6b63b..058c3c6 100644 --- a/tests/auto/qpixmap/tst_qpixmap.cpp +++ b/tests/auto/qpixmap/tst_qpixmap.cpp @@ -376,7 +376,7 @@ void tst_QPixmap::scroll() QFETCH(QRegion, exposed); QFETCH(bool, newPix); - QPixmap pixmap(input); + QPixmap pixmap = QPixmap::fromImage(input); QRegion exp; qint64 oldKey = pixmap.cacheKey(); pixmap.scroll(dx, dy, rect, &exp); -- cgit v0.12 From 859c0d5f2fe8234e9f1b8f638a3e3c592e7f3224 Mon Sep 17 00:00:00 2001 From: Ritt Konstantin Date: Wed, 10 Jun 2009 17:18:20 +0200 Subject: Optimize QDirPrivate::sortFileList by using a QFileInfoList directly instead of "constructing" a new one with empty file infos Reviewed-by:alexis Request-url: http://qt.gitorious.org/qt/qt/merge_requests/636 Task-number:253382 Merge-request: 636 Reviewed-by: Alexis Menard --- src/corelib/io/qdir.cpp | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp index 7d330e6..1795245 100644 --- a/src/corelib/io/qdir.cpp +++ b/src/corelib/io/qdir.cpp @@ -45,6 +45,7 @@ #ifndef QT_NO_DEBUG_STREAM #include "qdebug.h" #endif +#include "qdiriterator.h" #include "qfsfileengine.h" #include "qdatetime.h" #include "qstring.h" @@ -92,7 +93,7 @@ protected: QString initFileEngine(const QString &file); void updateFileLists() const; - void sortFileList(QDir::SortFlags, QStringList &, QStringList *, QFileInfoList *) const; + void sortFileList(QDir::SortFlags, QFileInfoList &, QStringList *, QFileInfoList *) const; private: #ifdef QT3_SUPPORT @@ -268,7 +269,7 @@ bool QDirSortItemComparator::operator()(const QDirSortItem &n1, const QDirSortIt return r < 0; } -inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QStringList &l, +inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QFileInfoList &l, QStringList *names, QFileInfoList *infos) const { if(names) @@ -278,16 +279,12 @@ inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QStringList &l, if(!l.isEmpty()) { QDirSortItem *si= new QDirSortItem[l.count()]; int i; - for (i = 0; i < l.size(); ++i) { - QString path = data->path; - if (!path.isEmpty() && !path.endsWith(QLatin1Char('/'))) - path += QLatin1Char('/'); - si[i].item = QFileInfo(path + l.at(i)); - } + for (i = 0; i < l.size(); ++i) + si[i].item = l.at(i); if ((sort & QDir::SortByMask) != QDir::Unsorted) - qStableSort(si, si+i, QDirSortItemComparator(sort)); + qStableSort(si, si + i, QDirSortItemComparator(sort)); // put them back in the list(s) - for (int j = 0; jappend(si[j].item); if(names) @@ -300,7 +297,12 @@ inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QStringList &l, inline void QDirPrivate::updateFileLists() const { if(data->listsDirty) { - QStringList l = data->fileEngine->entryList(data->filters, data->nameFilters); + QFileInfoList l; + QDirIterator it(data->path, data->nameFilters, data->filters); + while (it.hasNext()) { + it.next(); + l.append(it.fileInfo()); + } sortFileList(data->sort, l, &data->files, &data->fileInfos); data->listsDirty = 0; } @@ -1346,7 +1348,12 @@ QStringList QDir::entryList(const QStringList &nameFilters, Filters filters, d->updateFileLists(); return d->data->files; } - QStringList l = d->data->fileEngine->entryList(filters, nameFilters); + QFileInfoList l; + QDirIterator it(d->data->path, nameFilters, filters); + while (it.hasNext()) { + it.next(); + l.append(it.fileInfo()); + } if ((sort & QDir::SortByMask) == QDir::Unsorted) return l; @@ -1389,8 +1396,16 @@ QFileInfoList QDir::entryInfoList(const QStringList &nameFilters, Filters filter d->updateFileLists(); return d->data->fileInfos; } + QFileInfoList l; + QDirIterator it(d->data->path, nameFilters, filters); + while (it.hasNext()) { + it.next(); + l.append(it.fileInfo()); + } + if ((sort & QDir::SortByMask) == QDir::Unsorted) + return l; + QFileInfoList ret; - QStringList l = d->data->fileEngine->entryList(filters, nameFilters); d->sortFileList(sort, l, 0, &ret); return ret; } -- cgit v0.12 From 28323eab144cdc3db9d947b9b94fb2ebfa477234 Mon Sep 17 00:00:00 2001 From: Ritt Konstantin Date: Wed, 10 Jun 2009 17:18:21 +0200 Subject: Improve QDirPrivate::sortFileList by leaving right avway is we don't need to sort. Reviewed-by:alexis Request-url: http://qt.gitorious.org/qt/qt/merge_requests/636 Merge-request: 636 Reviewed-by: Alexis Menard --- src/corelib/io/qdir.cpp | 42 +++++++++++++++++++++++------------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp index 1795245..302d9b5 100644 --- a/src/corelib/io/qdir.cpp +++ b/src/corelib/io/qdir.cpp @@ -276,21 +276,31 @@ inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QFileInfoList &l, names->clear(); if(infos) infos->clear(); - if(!l.isEmpty()) { - QDirSortItem *si= new QDirSortItem[l.count()]; - int i; - for (i = 0; i < l.size(); ++i) - si[i].item = l.at(i); - if ((sort & QDir::SortByMask) != QDir::Unsorted) - qStableSort(si, si + i, QDirSortItemComparator(sort)); - // put them back in the list(s) - for (int j = 0; j < i; j++) { + int n = l.size(); + if(n > 0) { + if (n == 1 || (sort & QDir::SortByMask) == QDir::Unsorted) { if(infos) - infos->append(si[j].item); - if(names) - names->append(si[j].item.fileName()); + *infos = l; + if(names) { + for (int i = 0; i < n; ++i) + names->append(l.at(i).fileName()); + } + } else { + QDirSortItem *si = new QDirSortItem[n]; + for (int i = 0; i < n; ++i) + si[i].item = l.at(i); + qStableSort(si, si + n, QDirSortItemComparator(sort)); + // put them back in the list(s) + if(infos) { + for (int i = 0; i < n; ++i) + infos->append(si[i].item); + } + if(names) { + for (int i = 0; i < n; ++i) + names->append(si[i].item.fileName()); + } + delete [] si; } - delete [] si; } } @@ -1354,9 +1364,6 @@ QStringList QDir::entryList(const QStringList &nameFilters, Filters filters, it.next(); l.append(it.fileInfo()); } - if ((sort & QDir::SortByMask) == QDir::Unsorted) - return l; - QStringList ret; d->sortFileList(sort, l, &ret, 0); return ret; @@ -1402,9 +1409,6 @@ QFileInfoList QDir::entryInfoList(const QStringList &nameFilters, Filters filter it.next(); l.append(it.fileInfo()); } - if ((sort & QDir::SortByMask) == QDir::Unsorted) - return l; - QFileInfoList ret; d->sortFileList(sort, l, 0, &ret); return ret; -- cgit v0.12 From a863beab4c18f4bda777b61e55e7b66074a467f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Wed, 10 Jun 2009 16:41:14 +0200 Subject: We don't have to combine the world matrix anymore. See also: 32f32ee3e752a6cc03505ddaa48d2849eaedc2a6 Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsview.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 4a8099c..de7b9f4 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -3238,7 +3238,6 @@ void QGraphicsView::paintEvent(QPaintEvent *event) // Set up the painter QPainter painter(viewport()); - QTransform original = painter.worldTransform(); #ifndef QT_NO_RUBBERBAND if (d->rubberBanding && !d->rubberBandRect.isEmpty()) painter.save(); @@ -3249,7 +3248,7 @@ void QGraphicsView::paintEvent(QPaintEvent *event) // Set up viewport transform const QTransform viewTransform = viewportTransform(); - painter.setTransform(viewTransform, true); + painter.setWorldTransform(viewTransform); // Draw background if ((d->cacheMode & CacheBackground) @@ -3281,10 +3280,9 @@ void QGraphicsView::paintEvent(QPaintEvent *event) } // Blit the background from the background pixmap - QTransform oldMatrix = painter.worldTransform(); - painter.setWorldTransform(original); + painter.setWorldTransform(QTransform()); painter.drawPixmap(QPoint(), d->backgroundPixmap); - painter.setWorldTransform(oldMatrix); + painter.setWorldTransform(viewTransform); } else { if (!(d->optimizationFlags & DontSavePainterState)) painter.save(); -- cgit v0.12 From 2e41f3fd234a31a57c111b16e0339dea52d77d4d Mon Sep 17 00:00:00 2001 From: Jens Bache-Wiig Date: Wed, 10 Jun 2009 17:26:57 +0200 Subject: Reduce left-margins in qdoc The current implementation is a bit hackish and does not work for all cases. It is better to remove it for now until we have a proper way of supporting it. --- tools/qdoc3/test/classic.css | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/tools/qdoc3/test/classic.css b/tools/qdoc3/test/classic.css index 5087f9e..7f22861 100644 --- a/tools/qdoc3/test/classic.css +++ b/tools/qdoc3/test/classic.css @@ -39,8 +39,6 @@ table.valuelist { border-color: #dddddd; border-collapse: collapse; background-color: #f0f0f0; - margin-left: 1.5%; - width: 97% } table.indextable { @@ -48,8 +46,6 @@ table.indextable { border-collapse: collapse; background-color: #f0f0f0; border-color:#555; - margin-left: 1.5%; - width: 97% } @@ -72,9 +68,9 @@ th.titleheader { } p { - margin-left: 1.5%; + + margin-left: 4px; margin-top: 8px; - width: 97% margin-bottom: 8px; } @@ -138,6 +134,7 @@ table td.memItemLeft { font-size: 100%; white-space: nowrap } + table td.memItemRight { padding: 2px 8px 0px 8px; margin: 4px; -- cgit v0.12 From 7faaa967a4e872cc31f1bcb9e96fe08edbf639b3 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Thu, 11 Jun 2009 09:39:43 +1000 Subject: typo in my recent change --- src/declarative/fx/qfxblendedimage.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/fx/qfxblendedimage.cpp b/src/declarative/fx/qfxblendedimage.cpp index 1f805df..e216196 100644 --- a/src/declarative/fx/qfxblendedimage.cpp +++ b/src/declarative/fx/qfxblendedimage.cpp @@ -102,7 +102,7 @@ void QFxBlendedImage::setPrimaryUrl(const QUrl &url) return; if (!primUrl.isEmpty()) QFxPixmap::cancelGet(primUrl,this); - Q_ASSERT(!primUrl.isRelative()); + Q_ASSERT(!url.isRelative()); primUrl = url; if (!primUrl.isEmpty()) QFxPixmap::get(qmlEngine(this), primUrl,this,SLOT(primaryLoaded())); -- cgit v0.12 From ee66f86c529fd939b74589d8131b653ef5f799b5 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Thu, 11 Jun 2009 15:14:47 +1000 Subject: Use the most derived extension object, not the least derived --- src/declarative/qml/qmlproxymetaobject.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/qml/qmlproxymetaobject.cpp b/src/declarative/qml/qmlproxymetaobject.cpp index d24c5c4..686c6d7 100644 --- a/src/declarative/qml/qmlproxymetaobject.cpp +++ b/src/declarative/qml/qmlproxymetaobject.cpp @@ -50,7 +50,7 @@ QmlProxyMetaObject::QmlProxyMetaObject(QObject *obj, QList *mList) qWarning() << "QmlProxyMetaObject" << obj->metaObject()->className(); #endif - *static_cast(this) = *metaObjects->last().metaObject; + *static_cast(this) = *metaObjects->first().metaObject; QObjectPrivate *op = QObjectPrivate::get(obj); if (op->metaObject) -- cgit v0.12 From 0989cbe2b164560eef14334a540fcbcb2e2ec8cb Mon Sep 17 00:00:00 2001 From: Marius Storm-Olsen Date: Thu, 11 Jun 2009 08:29:11 +0200 Subject: Remove var->QMAKE_COMP_var docs, and mark feature unsupported. Reviewed By: andy --- doc/src/qmake-manual.qdoc | 4 ---- qmake/generators/makefile.cpp | 1 + 2 files changed, 1 insertion(+), 4 deletions(-) diff --git a/doc/src/qmake-manual.qdoc b/doc/src/qmake-manual.qdoc index 172bc60..9714a44 100644 --- a/doc/src/qmake-manual.qdoc +++ b/doc/src/qmake-manual.qdoc @@ -3303,10 +3303,6 @@ \o output_function \o Specifies a custom qmake function that is used to specify the filename to be created. \row - \o variables - \o Indicates that the variables specified here are replaced with $(QMAKE_COMP_VARNAME) when refered to - in the pro file as $(VARNAME). - \row \o variable_out \o The variable that the files created from the output should be added to. \endtable diff --git a/qmake/generators/makefile.cpp b/qmake/generators/makefile.cpp index 2d4658e..a385748 100644 --- a/qmake/generators/makefile.cpp +++ b/qmake/generators/makefile.cpp @@ -1910,6 +1910,7 @@ MakefileGenerator::writeExtraCompilerTargets(QTextStream &t) deps += replaceExtraCompilerVariables(pre_deps.at(i), (*input), out); } QString cmd = replaceExtraCompilerVariables(tmp_cmd, (*input), out); + // NOTE: The var -> QMAKE_COMP_var replace feature is unsupported, do not use! for(QStringList::ConstIterator it3 = vars.constBegin(); it3 != vars.constEnd(); ++it3) cmd.replace("$(" + (*it3) + ")", "$(QMAKE_COMP_" + (*it3)+")"); if(!tmp_dep_cmd.isEmpty() && doDepends()) { -- cgit v0.12 From 2feffad511c2ea535e59221ae1b0b46c91bb8227 Mon Sep 17 00:00:00 2001 From: Kai Koehne Date: Thu, 4 Jun 2009 14:32:43 +0200 Subject: qdoc: Mention that QML_DECLARE_TYPE only works for non-abstract classes --- doc/src/declarative/qmlforcpp.qdoc | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/doc/src/declarative/qmlforcpp.qdoc b/doc/src/declarative/qmlforcpp.qdoc index 2898499..4095071 100644 --- a/doc/src/declarative/qmlforcpp.qdoc +++ b/doc/src/declarative/qmlforcpp.qdoc @@ -186,7 +186,8 @@ name \a QmlName. Of course there's nothing stopping you using the same name for both the C++ and the QML name! Any type can be added to the QML engine using these macros. The only - requirements are that \a T inherits QObject and that it has a default constructor. + requirements are that \a T inherits QObject, is not abstract, + and that it has a default constructor. \section1 Property Binding -- cgit v0.12 From e83bed831c80657221176b9c0e24962d9c9e7ca2 Mon Sep 17 00:00:00 2001 From: Andreas Aardal Hanssen Date: Fri, 29 May 2009 08:54:31 +0200 Subject: Introduce QGraphicsItem::ItemHasNoContents. This flag helps optimize the case where an item is used only as a transformation node in a scene graph, and where the item itself doesn't paint anything. This is the default for FxItem (the subclasses that do paint enable the HasContents flag). This lets Graphics View know whether there's any point in setting up the world transform, opacity and other things. Reviewed-by: Lars --- src/declarative/canvas/qsimplecanvasitem.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/declarative/canvas/qsimplecanvasitem.cpp b/src/declarative/canvas/qsimplecanvasitem.cpp index 7451a5f..cbdc324 100644 --- a/src/declarative/canvas/qsimplecanvasitem.cpp +++ b/src/declarative/canvas/qsimplecanvasitem.cpp @@ -1300,6 +1300,9 @@ void QSimpleCanvasItem::setOptions(Options options, bool set) d->options &= ~IsFocusRealm; } + if (d->graphicsItem) + d->graphicsItem->setFlag(QGraphicsItem::ItemHasNoContents, !(d->options & HasContents)); + if ((old & MouseFilter) != (d->options & MouseFilter)) { if (d->graphicsItem) { if (d->options & MouseFilter) @@ -1487,6 +1490,7 @@ void QSimpleCanvasItemPrivate::convertToGraphicsItem(QGraphicsItem *parent) Q_Q(QSimpleCanvasItem); Q_ASSERT(!graphicsItem); graphicsItem = new QSimpleGraphicsItem(q); + graphicsItem->setFlag(QGraphicsItem::ItemHasNoContents, !(q->options() & QSimpleCanvasItem::HasContents)); if (parent) graphicsItem->setParentItem(parent); -- cgit v0.12 From f88167c39259967912540cf50d3f9df9524da4b3 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Tue, 2 Jun 2009 21:31:31 +0200 Subject: make the setRotation code a little more efficient This doesn't give us much. The real fix here is to add support for rotation and transformationOrigin to QGraphicsItem. --- src/declarative/fx/qfxitem.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/declarative/fx/qfxitem.cpp b/src/declarative/fx/qfxitem.cpp index 09ec748..648b0fb 100644 --- a/src/declarative/fx/qfxitem.cpp +++ b/src/declarative/fx/qfxitem.cpp @@ -1490,9 +1490,8 @@ void QFxItem::setRotation(qreal rotation) trans.rotate(d->_rotation, 0, 0, 1); trans.translate(-to.x(), -to.y()); #else - QTransform trans; - QPointF to = transformOriginPoint(); - trans.translate(to.x(), to.y()); + QPointF to = d->transformOrigin(); + QTransform trans = QTransform::fromTranslate(to.x(), to.y()); trans.rotate(d->_rotation); trans.translate(-to.x(), -to.y()); #endif -- cgit v0.12 From 65373d007797b559a573b7b08f40c6801da11686 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 11 Jun 2009 10:13:24 +0200 Subject: Compile on the Mac. Broke after this commit: 32f32ee3e752a6cc03505ddaa48d2849eaedc2a6 --- src/gui/painting/qpaintengine_mac.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/gui/painting/qpaintengine_mac.cpp b/src/gui/painting/qpaintengine_mac.cpp index 5889388..3d0a1b7 100644 --- a/src/gui/painting/qpaintengine_mac.cpp +++ b/src/gui/painting/qpaintengine_mac.cpp @@ -131,8 +131,8 @@ QMacCGContext::QMacCGContext(QPainter *p) QPainterState *state = static_cast(pe->state); Q_ASSERT(state); - if (!state->redirection_offset.isNull()) - CGContextTranslateCTM(context, -state->redirection_offset.x(), -state->redirection_offset.y()); + if (!state->redirectionMatrix.isIdentity()) + CGContextTranslateCTM(context, state->redirectionMatrix.dx(), state->redirectionMatrix.dy()); } } CGContextRetain(context); -- cgit v0.12 From 7e541e9e4832a26339a44ee55d325ba089717e17 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Thu, 11 Jun 2009 18:47:07 +1000 Subject: Skeleton for property deferring --- src/declarative/qml/qml.h | 1 + src/declarative/qml/qmlcompiler.cpp | 54 +++++++++++++++-- src/declarative/qml/qmlcompiler_p.h | 1 + src/declarative/qml/qmldeclarativedata_p.h | 94 +++++++++++++++++++++++++++++- src/declarative/qml/qmlengine.cpp | 41 ++++++------- src/declarative/qml/qmlinstruction_p.h | 8 +++ src/declarative/qml/qmlvme.cpp | 13 +++++ 7 files changed, 182 insertions(+), 30 deletions(-) diff --git a/src/declarative/qml/qml.h b/src/declarative/qml/qml.h index 370bb58..51ca612 100644 --- a/src/declarative/qml/qml.h +++ b/src/declarative/qml/qml.h @@ -90,6 +90,7 @@ QT_MODULE(Declarative) class QmlContext; class QmlEngine; +Q_DECLARATIVE_EXPORT void qmlExecuteDeferred(QObject *); Q_DECLARATIVE_EXPORT QmlContext *qmlContext(const QObject *); Q_DECLARATIVE_EXPORT QmlEngine *qmlEngine(const QObject *); Q_DECLARATIVE_EXPORT QObject *qmlAttachedPropertiesObjectById(int, const QObject *); diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index d29ac1f..2a3cc8d 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -621,13 +621,19 @@ bool QmlCompiler::compileObject(Object *obj, const BindingContext &ctxt) output->types.at(obj->type).type->customParser() != 0; QList customProps; + QStringList deferred = deferredProperties(obj); + QList deferredProps; + // Compile all explicit properties specified foreach(Property *prop, obj->properties) { if (isCustomParser) { // Custom parser types don't support signal properties if (testProperty(prop, obj)) { - COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); + if (deferred.contains(prop->name)) + deferredProps << prop; + else + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } else { customProps << QmlCustomParserNodePrivate::fromProperty(prop); } @@ -635,7 +641,10 @@ bool QmlCompiler::compileObject(Object *obj, const BindingContext &ctxt) if (isSignalPropertyName(prop->name)) { COMPILE_CHECK(compileSignal(prop,obj)); } else { - COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); + if (deferred.contains(prop->name)) + deferredProps << prop; + else + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } } @@ -647,12 +656,20 @@ bool QmlCompiler::compileObject(Object *obj, const BindingContext &ctxt) if (isCustomParser) { if (testProperty(prop, obj)) { - COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); + QMetaProperty p = deferred.isEmpty()?QMetaProperty():QmlMetaType::defaultProperty(obj->metaObject()); + if (deferred.contains(p.name())) + deferredProps << prop; + else + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } else { customProps << QmlCustomParserNodePrivate::fromProperty(prop); } } else { - COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); + QMetaProperty p = deferred.isEmpty()?QMetaProperty():QmlMetaType::defaultProperty(obj->metaObject()); + if (deferred.contains(p.name())) + deferredProps << prop; + else + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } } @@ -670,6 +687,22 @@ bool QmlCompiler::compileObject(Object *obj, const BindingContext &ctxt) output->indexForByteArray(customData); } + // Build the deferred block (### Need to check for presence of "id") + if (!deferredProps.isEmpty()) { + QmlInstruction defer; + defer.type = QmlInstruction::Defer; + defer.line = 0; + int deferIdx = output->bytecode.count(); + output->bytecode << defer; + + foreach (Property *prop, deferredProps) { + COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); + } + + output->bytecode[deferIdx].defer.deferCount = + output->bytecode.count() - deferIdx - 1; + } + // If the type support the QmlParserStatusInterface we need to invoke // classComplete() if (parserStatusCast != -1) { @@ -1634,6 +1667,19 @@ bool QmlCompiler::canConvert(int convertType, QmlParser::Object *object) return false; } +QStringList QmlCompiler::deferredProperties(QmlParser::Object *obj) +{ + const QMetaObject *mo = obj->metatype; + + int idx = mo->indexOfClassInfo("DeferredPropertyNames"); + if (idx == -1) + return QStringList(); + + QMetaClassInfo classInfo = mo->classInfo(idx); + QStringList rv = QString(QLatin1String(classInfo.value())).split(','); + return rv; +} + QmlCompiledData::QmlCompiledData() { } diff --git a/src/declarative/qml/qmlcompiler_p.h b/src/declarative/qml/qmlcompiler_p.h index 3b1a496..2559b14 100644 --- a/src/declarative/qml/qmlcompiler_p.h +++ b/src/declarative/qml/qmlcompiler_p.h @@ -180,6 +180,7 @@ private: void finalizeBinding(const BindingReference &); bool canConvert(int, QmlParser::Object *); + QStringList deferredProperties(QmlParser::Object *); struct IdReference { QString id; diff --git a/src/declarative/qml/qmldeclarativedata_p.h b/src/declarative/qml/qmldeclarativedata_p.h index fb7a015..b8d3cf4 100644 --- a/src/declarative/qml/qmldeclarativedata_p.h +++ b/src/declarative/qml/qmldeclarativedata_p.h @@ -52,20 +52,108 @@ public: QmlSimpleDeclarativeData() : flags(0), context(0) {} virtual void destroyed(QObject *); - enum Flag { Extended = 0x00000001 }; + enum Flag { Instance = 0x00000001, Extended = 0x00000002 }; quint32 flags; QmlContext *context; + + static inline QmlSimpleDeclarativeData *get(QObject *object, + bool create = false); }; -class QmlExtendedDeclarativeData : public QmlSimpleDeclarativeData +class QmlCompiledComponent; +class QmlInstanceDeclarativeData : public QmlSimpleDeclarativeData { public: - QmlExtendedDeclarativeData() { flags = Extended; } + QmlInstanceDeclarativeData() { flags |= Instance; } virtual void destroyed(QObject *); + + QmlCompiledComponent *deferredComponent; + unsigned int deferredIdx; + + static inline QmlInstanceDeclarativeData *get(QObject *object, + bool create = false); +}; + +class QmlExtendedDeclarativeData : public QmlInstanceDeclarativeData +{ +public: + QmlExtendedDeclarativeData() { flags |= Extended; } + QHash attachedProperties; + + static inline QmlExtendedDeclarativeData *get(QObject *object, + bool create = false); }; +QmlSimpleDeclarativeData * +QmlSimpleDeclarativeData::get(QObject *object, bool create) +{ + QObjectPrivate *priv = QObjectPrivate::get(object); + + if (create && !priv->declarativeData) + priv->declarativeData = new QmlInstanceDeclarativeData; + + return static_cast(priv->declarativeData); +} + +QmlInstanceDeclarativeData * +QmlInstanceDeclarativeData::get(QObject *object, bool create) +{ + QObjectPrivate *priv = QObjectPrivate::get(object); + + QmlSimpleDeclarativeData *simple = + static_cast(priv->declarativeData); + + if (simple && (simple->flags & Instance)) { + return static_cast(simple); + } else if (create && simple) { + QmlInstanceDeclarativeData *rv = new QmlInstanceDeclarativeData; + rv->context = simple->context; + simple->destroyed(object); + priv->declarativeData = rv; + return rv; + } else if (create) { + QmlInstanceDeclarativeData *rv = new QmlInstanceDeclarativeData; + priv->declarativeData = rv; + return rv; + } + return 0; +} + +QmlExtendedDeclarativeData * +QmlExtendedDeclarativeData::get(QObject *object, bool create) +{ + QObjectPrivate *priv = QObjectPrivate::get(object); + + QmlSimpleDeclarativeData *simple = + static_cast(priv->declarativeData); + + if (simple && (simple->flags & Extended)) { + return static_cast(simple); + } else if (create && simple) { + QmlExtendedDeclarativeData *rv = new QmlExtendedDeclarativeData; + rv->context = simple->context; + + if (simple->flags & Instance) { + QmlInstanceDeclarativeData *instance = + static_cast(priv->declarativeData); + rv->deferredComponent = instance->deferredComponent; + rv->deferredIdx = instance->deferredIdx; + delete simple; + } else { + simple->destroyed(object); + } + priv->declarativeData = rv; + return rv; + } else if (create) { + QmlExtendedDeclarativeData *rv = new QmlExtendedDeclarativeData; + priv->declarativeData = rv; + return rv; + } + return 0; +} + QT_END_NAMESPACE #endif // QMLDECLARATIVEDATA_P_H diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index 66781ce..edc76c2 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -706,6 +706,14 @@ void QmlEngine::setContextForObject(QObject *object, QmlContext *context) context->d_func()->contextObjects.append(object); } +void qmlExecuteDeferred(QObject *object) +{ + QmlInstanceDeclarativeData *data = QmlInstanceDeclarativeData::get(object); + + if (data) { + } +} + QmlContext *qmlContext(const QObject *obj) { return QmlEngine::contextForObject(obj); @@ -719,36 +727,21 @@ QmlEngine *qmlEngine(const QObject *obj) QObject *qmlAttachedPropertiesObjectById(int id, const QObject *object) { - QObjectPrivate *priv = QObjectPrivate::get(const_cast(object)); - - - QmlSimpleDeclarativeData *data = static_cast(priv->declarativeData); + QmlExtendedDeclarativeData *edata = + QmlExtendedDeclarativeData::get(const_cast(object), true); - QmlExtendedDeclarativeData *edata = (data && data->flags & QmlSimpleDeclarativeData::Extended)?static_cast(data):0; - - if (edata) { - QObject *rv = edata->attachedProperties.value(id); - if (rv) - return rv; - } + QObject *rv = edata->attachedProperties.value(id); + if (rv) + return rv; QmlAttachedPropertiesFunc pf = QmlMetaType::attachedPropertiesFuncById(id); if (!pf) return 0; - QObject *rv = pf(const_cast(object)); - - if (rv) { - if (!edata) { - - edata = new QmlExtendedDeclarativeData; - if (data) edata->context = data->context; - priv->declarativeData = edata; - - } + rv = pf(const_cast(object)); + if (rv) edata->attachedProperties.insert(id, rv); - } return rv; } @@ -759,9 +752,11 @@ void QmlSimpleDeclarativeData::destroyed(QObject *object) context->d_func()->contextObjects.removeAll(object); } -void QmlExtendedDeclarativeData::destroyed(QObject *object) +void QmlInstanceDeclarativeData::destroyed(QObject *object) { QmlSimpleDeclarativeData::destroyed(object); + if (deferredComponent) + deferredComponent->release(); delete this; } diff --git a/src/declarative/qml/qmlinstruction_p.h b/src/declarative/qml/qmlinstruction_p.h index 0f1f697..e3b0dfe 100644 --- a/src/declarative/qml/qmlinstruction_p.h +++ b/src/declarative/qml/qmlinstruction_p.h @@ -139,6 +139,11 @@ public: PopFetchedObject, PopQList, + // + // Deferred creation + // + Defer, /* defer */ + // // Expression optimizations // @@ -270,6 +275,9 @@ public: int property; int object; } assignStackObject; + struct { + int deferCount; + } defer; }; void dump(QmlCompiledComponent *); diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 3a66c69..58972ef 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -44,6 +44,7 @@ #include #include #include "private/qmetaobjectbuilder_p.h" +#include "private/qmldeclarativedata_p.h" #include #include #include @@ -745,6 +746,18 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in } break; + case QmlInstruction::Defer: + { + QObject *target = stack.top(); + QmlInstanceDeclarativeData *data = + QmlInstanceDeclarativeData::get(target, true); + comp->addref(); + data->deferredComponent = comp; + data->deferredIdx = ii; + ii += instr.defer.deferCount; + } + break; + case QmlInstruction::PopFetchedObject: { stack.pop(); -- cgit v0.12 From 7d7c1da715474cefa5404df684d680c36e4b6b20 Mon Sep 17 00:00:00 2001 From: Roberto Raggi Date: Thu, 11 Jun 2009 10:46:43 +0200 Subject: Renamed the QML front-end. --- src/declarative/qml/parser/javascript.g | 2880 ------------------- src/declarative/qml/parser/javascriptast.cpp | 962 ------- src/declarative/qml/parser/javascriptast_p.h | 2544 ----------------- src/declarative/qml/parser/javascriptastfwd_p.h | 184 -- .../qml/parser/javascriptastvisitor.cpp | 58 - .../qml/parser/javascriptastvisitor_p.h | 328 --- src/declarative/qml/parser/javascriptengine_p.cpp | 191 -- src/declarative/qml/parser/javascriptengine_p.h | 145 - src/declarative/qml/parser/javascriptgrammar.cpp | 829 ------ src/declarative/qml/parser/javascriptgrammar_p.h | 200 -- src/declarative/qml/parser/javascriptlexer.cpp | 1196 -------- src/declarative/qml/parser/javascriptlexer_p.h | 269 -- .../qml/parser/javascriptmemorypool_p.h | 130 - src/declarative/qml/parser/javascriptnodepool_p.h | 138 - src/declarative/qml/parser/javascriptparser.cpp | 1717 ------------ src/declarative/qml/parser/javascriptparser_p.h | 208 -- .../qml/parser/javascriptprettypretty.cpp | 1334 --------- .../qml/parser/javascriptprettypretty_p.h | 329 --- src/declarative/qml/parser/parser.pri | 34 +- src/declarative/qml/parser/qmljs.g | 2881 ++++++++++++++++++++ src/declarative/qml/parser/qmljsast.cpp | 962 +++++++ src/declarative/qml/parser/qmljsast_p.h | 2544 +++++++++++++++++ src/declarative/qml/parser/qmljsastfwd_p.h | 184 ++ src/declarative/qml/parser/qmljsastvisitor.cpp | 58 + src/declarative/qml/parser/qmljsastvisitor_p.h | 328 +++ src/declarative/qml/parser/qmljsengine_p.cpp | 191 ++ src/declarative/qml/parser/qmljsengine_p.h | 145 + src/declarative/qml/parser/qmljsgrammar.cpp | 829 ++++++ src/declarative/qml/parser/qmljsgrammar_p.h | 200 ++ src/declarative/qml/parser/qmljslexer.cpp | 1196 ++++++++ src/declarative/qml/parser/qmljslexer_p.h | 269 ++ src/declarative/qml/parser/qmljsmemorypool_p.h | 130 + src/declarative/qml/parser/qmljsnodepool_p.h | 138 + src/declarative/qml/parser/qmljsparser.cpp | 1717 ++++++++++++ src/declarative/qml/parser/qmljsparser_p.h | 208 ++ src/declarative/qml/parser/qmljsprettypretty.cpp | 1334 +++++++++ src/declarative/qml/parser/qmljsprettypretty_p.h | 329 +++ src/declarative/qml/qmlbasicscript.cpp | 36 +- src/declarative/qml/qmlcompiler.cpp | 12 +- src/declarative/qml/qmlengine.cpp | 2 +- src/declarative/qml/qmlparser.cpp | 4 +- src/declarative/qml/qmlparser_p.h | 8 +- src/declarative/qml/qmlscriptparser.cpp | 16 +- src/declarative/qml/rewriter/rewriter.cpp | 8 +- src/declarative/qml/rewriter/rewriter_p.h | 6 +- src/declarative/qml/rewriter/textwriter.cpp | 2 +- src/declarative/qml/rewriter/textwriter_p.h | 4 +- tools/linguist/lupdate/qml.cpp | 14 +- 48 files changed, 13716 insertions(+), 13715 deletions(-) delete mode 100644 src/declarative/qml/parser/javascript.g delete mode 100644 src/declarative/qml/parser/javascriptast.cpp delete mode 100644 src/declarative/qml/parser/javascriptast_p.h delete mode 100644 src/declarative/qml/parser/javascriptastfwd_p.h delete mode 100644 src/declarative/qml/parser/javascriptastvisitor.cpp delete mode 100644 src/declarative/qml/parser/javascriptastvisitor_p.h delete mode 100644 src/declarative/qml/parser/javascriptengine_p.cpp delete mode 100644 src/declarative/qml/parser/javascriptengine_p.h delete mode 100644 src/declarative/qml/parser/javascriptgrammar.cpp delete mode 100644 src/declarative/qml/parser/javascriptgrammar_p.h delete mode 100644 src/declarative/qml/parser/javascriptlexer.cpp delete mode 100644 src/declarative/qml/parser/javascriptlexer_p.h delete mode 100644 src/declarative/qml/parser/javascriptmemorypool_p.h delete mode 100644 src/declarative/qml/parser/javascriptnodepool_p.h delete mode 100644 src/declarative/qml/parser/javascriptparser.cpp delete mode 100644 src/declarative/qml/parser/javascriptparser_p.h delete mode 100644 src/declarative/qml/parser/javascriptprettypretty.cpp delete mode 100644 src/declarative/qml/parser/javascriptprettypretty_p.h create mode 100644 src/declarative/qml/parser/qmljs.g create mode 100644 src/declarative/qml/parser/qmljsast.cpp create mode 100644 src/declarative/qml/parser/qmljsast_p.h create mode 100644 src/declarative/qml/parser/qmljsastfwd_p.h create mode 100644 src/declarative/qml/parser/qmljsastvisitor.cpp create mode 100644 src/declarative/qml/parser/qmljsastvisitor_p.h create mode 100644 src/declarative/qml/parser/qmljsengine_p.cpp create mode 100644 src/declarative/qml/parser/qmljsengine_p.h create mode 100644 src/declarative/qml/parser/qmljsgrammar.cpp create mode 100644 src/declarative/qml/parser/qmljsgrammar_p.h create mode 100644 src/declarative/qml/parser/qmljslexer.cpp create mode 100644 src/declarative/qml/parser/qmljslexer_p.h create mode 100644 src/declarative/qml/parser/qmljsmemorypool_p.h create mode 100644 src/declarative/qml/parser/qmljsnodepool_p.h create mode 100644 src/declarative/qml/parser/qmljsparser.cpp create mode 100644 src/declarative/qml/parser/qmljsparser_p.h create mode 100644 src/declarative/qml/parser/qmljsprettypretty.cpp create mode 100644 src/declarative/qml/parser/qmljsprettypretty_p.h diff --git a/src/declarative/qml/parser/javascript.g b/src/declarative/qml/parser/javascript.g deleted file mode 100644 index 884d814..0000000 --- a/src/declarative/qml/parser/javascript.g +++ /dev/null @@ -1,2880 +0,0 @@ ----------------------------------------------------------------------------- --- --- Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). --- Contact: Qt Software Information (qt-info@nokia.com) --- --- This file is part of the QtScript module of the Qt Toolkit. --- --- $QT_BEGIN_LICENSE:LGPL$ --- No Commercial Usage --- This file contains pre-release code and may not be distributed. --- You may use this file in accordance with the terms and conditions --- contained in the either Technology Preview License Agreement or the --- Beta Release License Agreement. --- --- GNU Lesser General Public License Usage --- Alternatively, 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.0, 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. --- --- If you are unsure which license is appropriate for your use, please --- contact the sales department at qt-sales@nokia.com. --- $QT_END_LICENSE$ --- --- This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE --- WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. --- ----------------------------------------------------------------------------- - -%parser JavaScriptGrammar -%decl javascriptparser_p.h -%impl javascriptparser.cpp -%expect 2 -%expect-rr 2 - -%token T_AND "&" T_AND_AND "&&" T_AND_EQ "&=" -%token T_BREAK "break" T_CASE "case" T_CATCH "catch" -%token T_COLON ":" T_COMMA ";" T_CONTINUE "continue" -%token T_DEFAULT "default" T_DELETE "delete" T_DIVIDE_ "/" -%token T_DIVIDE_EQ "/=" T_DO "do" T_DOT "." -%token T_ELSE "else" T_EQ "=" T_EQ_EQ "==" -%token T_EQ_EQ_EQ "===" T_FINALLY "finally" T_FOR "for" -%token T_FUNCTION "function" T_GE ">=" T_GT ">" -%token T_GT_GT ">>" T_GT_GT_EQ ">>=" T_GT_GT_GT ">>>" -%token T_GT_GT_GT_EQ ">>>=" T_IDENTIFIER "identifier" T_IF "if" -%token T_IN "in" T_INSTANCEOF "instanceof" T_LBRACE "{" -%token T_LBRACKET "[" T_LE "<=" T_LPAREN "(" -%token T_LT "<" T_LT_LT "<<" T_LT_LT_EQ "<<=" -%token T_MINUS "-" T_MINUS_EQ "-=" T_MINUS_MINUS "--" -%token T_NEW "new" T_NOT "!" T_NOT_EQ "!=" -%token T_NOT_EQ_EQ "!==" T_NUMERIC_LITERAL "numeric literal" T_OR "|" -%token T_OR_EQ "|=" T_OR_OR "||" T_PLUS "+" -%token T_PLUS_EQ "+=" T_PLUS_PLUS "++" T_QUESTION "?" -%token T_RBRACE "}" T_RBRACKET "]" T_REMAINDER "%" -%token T_REMAINDER_EQ "%=" T_RETURN "return" T_RPAREN ")" -%token T_SEMICOLON ";" T_AUTOMATIC_SEMICOLON T_STAR "*" -%token T_STAR_EQ "*=" T_STRING_LITERAL "string literal" -%token T_PROPERTY "property" T_SIGNAL "signal" -%token T_SWITCH "switch" T_THIS "this" T_THROW "throw" -%token T_TILDE "~" T_TRY "try" T_TYPEOF "typeof" -%token T_VAR "var" T_VOID "void" T_WHILE "while" -%token T_WITH "with" T_XOR "^" T_XOR_EQ "^=" -%token T_NULL "null" T_TRUE "true" T_FALSE "false" -%token T_CONST "const" -%token T_DEBUGGER "debugger" -%token T_RESERVED_WORD "reserved word" -%token T_MULTILINE_STRING_LITERAL "multiline string literal" - ---- context keywords. -%token T_PUBLIC "public" -%token T_IMPORT "import" - -%nonassoc SHIFT_THERE -%nonassoc T_IDENTIFIER T_COLON T_SIGNAL T_PROPERTY -%nonassoc REDUCE_HERE - -%start UiProgram - -/. -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include - -#include "javascriptengine_p.h" -#include "javascriptlexer_p.h" -#include "javascriptast_p.h" -#include "javascriptnodepool_p.h" - -./ - -/: -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -// -// This file is automatically generated from javascript.g. -// Changes will be lost. -// - -#ifndef JAVASCRIPTPARSER_P_H -#define JAVASCRIPTPARSER_P_H - -#include "javascriptgrammar_p.h" -#include "javascriptast_p.h" -#include "javascriptengine_p.h" - -#include - -QT_BEGIN_NAMESPACE - -class QString; - -namespace JavaScript { - -class Engine; -class NameId; - -class Parser: protected $table -{ -public: - union Value { - int ival; - double dval; - NameId *sval; - AST::ArgumentList *ArgumentList; - AST::CaseBlock *CaseBlock; - AST::CaseClause *CaseClause; - AST::CaseClauses *CaseClauses; - AST::Catch *Catch; - AST::DefaultClause *DefaultClause; - AST::ElementList *ElementList; - AST::Elision *Elision; - AST::ExpressionNode *Expression; - AST::Finally *Finally; - AST::FormalParameterList *FormalParameterList; - AST::FunctionBody *FunctionBody; - AST::FunctionDeclaration *FunctionDeclaration; - AST::Node *Node; - AST::PropertyName *PropertyName; - AST::PropertyNameAndValueList *PropertyNameAndValueList; - AST::SourceElement *SourceElement; - AST::SourceElements *SourceElements; - AST::Statement *Statement; - AST::StatementList *StatementList; - AST::Block *Block; - AST::VariableDeclaration *VariableDeclaration; - AST::VariableDeclarationList *VariableDeclarationList; - - AST::UiProgram *UiProgram; - AST::UiImportList *UiImportList; - AST::UiImport *UiImport; - AST::UiPublicMember *UiPublicMember; - AST::UiObjectDefinition *UiObjectDefinition; - AST::UiObjectInitializer *UiObjectInitializer; - AST::UiObjectBinding *UiObjectBinding; - AST::UiScriptBinding *UiScriptBinding; - AST::UiArrayBinding *UiArrayBinding; - AST::UiObjectMember *UiObjectMember; - AST::UiObjectMemberList *UiObjectMemberList; - AST::UiQualifiedId *UiQualifiedId; - }; - -public: - Parser(Engine *engine); - ~Parser(); - - bool parse(); - - AST::UiProgram *ast() - { return program; } - - QList diagnosticMessages() const - { return diagnostic_messages; } - - inline DiagnosticMessage diagnosticMessage() const - { - foreach (const DiagnosticMessage &d, diagnostic_messages) { - if (! d.kind == DiagnosticMessage::Warning) - return d; - } - - return DiagnosticMessage(); - } - - inline QString errorMessage() const - { return diagnosticMessage().message; } - - inline int errorLineNumber() const - { return diagnosticMessage().loc.startLine; } - - inline int errorColumnNumber() const - { return diagnosticMessage().loc.startColumn; } - -protected: - void reallocateStack(); - - inline Value &sym(int index) - { return sym_stack [tos + index - 1]; } - - inline AST::SourceLocation &loc(int index) - { return location_stack [tos + index - 1]; } - - AST::UiQualifiedId *reparseAsQualifiedId(AST::ExpressionNode *expr); - -protected: - Engine *driver; - int tos; - int stack_size; - Value *sym_stack; - int *state_stack; - AST::SourceLocation *location_stack; - - AST::UiProgram *program; - - // error recovery - enum { TOKEN_BUFFER_SIZE = 3 }; - - struct SavedToken { - int token; - double dval; - AST::SourceLocation loc; - }; - - double yylval; - AST::SourceLocation yylloc; - AST::SourceLocation yyprevlloc; - - SavedToken token_buffer[TOKEN_BUFFER_SIZE]; - SavedToken *first_token; - SavedToken *last_token; - - QList diagnostic_messages; -}; - -} // end of namespace JavaScript - - -:/ - - -/. - -#include "javascriptparser_p.h" -#include - -// -// This file is automatically generated from javascript.g. -// Changes will be lost. -// - -using namespace JavaScript; - -QT_BEGIN_NAMESPACE - -void Parser::reallocateStack() -{ - if (! stack_size) - stack_size = 128; - else - stack_size <<= 1; - - sym_stack = reinterpret_cast (qRealloc(sym_stack, stack_size * sizeof(Value))); - state_stack = reinterpret_cast (qRealloc(state_stack, stack_size * sizeof(int))); - location_stack = reinterpret_cast (qRealloc(location_stack, stack_size * sizeof(AST::SourceLocation))); -} - -inline static bool automatic(Engine *driver, int token) -{ - return token == $table::T_RBRACE - || token == 0 - || driver->lexer()->prevTerminator(); -} - - -Parser::Parser(Engine *engine): - driver(engine), - tos(0), - stack_size(0), - sym_stack(0), - state_stack(0), - location_stack(0), - first_token(0), - last_token(0) -{ -} - -Parser::~Parser() -{ - if (stack_size) { - qFree(sym_stack); - qFree(state_stack); - qFree(location_stack); - } -} - -static inline AST::SourceLocation location(Lexer *lexer) -{ - AST::SourceLocation loc; - loc.offset = lexer->tokenOffset(); - loc.length = lexer->tokenLength(); - loc.startLine = lexer->startLineNo(); - loc.startColumn = lexer->startColumnNo(); - return loc; -} - -AST::UiQualifiedId *Parser::reparseAsQualifiedId(AST::ExpressionNode *expr) -{ - QVarLengthArray nameIds; - QVarLengthArray locations; - - AST::ExpressionNode *it = expr; - while (AST::FieldMemberExpression *m = AST::cast(it)) { - nameIds.append(m->name); - locations.append(m->identifierToken); - it = m->base; - } - - if (AST::IdentifierExpression *idExpr = AST::cast(it)) { - AST::UiQualifiedId *q = makeAstNode(driver->nodePool(), idExpr->name); - q->identifierToken = idExpr->identifierToken; - - AST::UiQualifiedId *currentId = q; - for (int i = nameIds.size() - 1; i != -1; --i) { - currentId = makeAstNode(driver->nodePool(), currentId, nameIds[i]); - currentId->identifierToken = locations[i]; - } - - return currentId->finish(); - } - - return 0; -} - -bool Parser::parse() -{ - Lexer *lexer = driver->lexer(); - bool hadErrors = false; - int yytoken = -1; - int action = 0; - - first_token = last_token = 0; - - tos = -1; - program = 0; - - do { - if (++tos == stack_size) - reallocateStack(); - - state_stack[tos] = action; - - _Lcheck_token: - if (yytoken == -1 && -TERMINAL_COUNT != action_index[action]) { - yyprevlloc = yylloc; - - if (first_token == last_token) { - yytoken = lexer->lex(); - yylval = lexer->dval(); - yylloc = location(lexer); - } else { - yytoken = first_token->token; - yylval = first_token->dval; - yylloc = first_token->loc; - ++first_token; - } - } - - action = t_action(action, yytoken); - if (action > 0) { - if (action != ACCEPT_STATE) { - yytoken = -1; - sym(1).dval = yylval; - loc(1) = yylloc; - } else { - --tos; - return ! hadErrors; - } - } else if (action < 0) { - const int r = -action - 1; - tos -= rhs[r]; - - switch (r) { -./ - --------------------------------------------------------------------------------------------------------- --- Declarative UI --------------------------------------------------------------------------------------------------------- - -UiProgram: UiImportListOpt UiRootMember ; -/. -case $rule_number: { - program = makeAstNode (driver->nodePool(), sym(1).UiImportList, - sym(2).UiObjectMemberList->finish()); - sym(1).UiProgram = program; -} break; -./ - -UiImportListOpt: Empty ; -UiImportListOpt: UiImportList ; -/. -case $rule_number: { - sym(1).Node = sym(1).UiImportList->finish(); -} break; -./ - -UiImportList: UiImport ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiImport); -} break; -./ - -UiImportList: UiImportList UiImport ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), - sym(1).UiImportList, sym(2).UiImport); -} break; -./ - -UiImport: T_IMPORT T_STRING_LITERAL T_AUTOMATIC_SEMICOLON; -UiImport: T_IMPORT T_STRING_LITERAL T_SEMICOLON; -/. -case $rule_number: { - AST::UiImport *node = makeAstNode(driver->nodePool(), sym(2).sval); - node->importToken = loc(1); - node->fileNameToken = loc(2); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; -./ - -Empty: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -UiRootMember: UiObjectDefinition ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); -} break; -./ - -UiObjectMemberList: UiObjectMember ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); -} break; -./ - -UiObjectMemberList: UiObjectMemberList UiObjectMember ; -/. -case $rule_number: { - AST::UiObjectMemberList *node = makeAstNode (driver->nodePool(), - sym(1).UiObjectMemberList, sym(2).UiObjectMember); - sym(1).Node = node; -} break; -./ - -UiArrayMemberList: UiObjectDefinition ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); -} break; -./ - -UiArrayMemberList: UiArrayMemberList T_COMMA UiObjectDefinition ; -/. -case $rule_number: { - AST::UiArrayMemberList *node = makeAstNode (driver->nodePool(), - sym(1).UiArrayMemberList, sym(3).UiObjectMember); - node->commaToken = loc(2); - sym(1).Node = node; -} break; -./ - -UiObjectInitializer: T_LBRACE T_RBRACE ; -/. -case $rule_number: { - AST::UiObjectInitializer *node = makeAstNode (driver->nodePool(), (AST::UiObjectMemberList*)0); - node->lbraceToken = loc(1); - node->rbraceToken = loc(2); - sym(1).Node = node; -} break; -./ - -UiObjectInitializer: T_LBRACE UiObjectMemberList T_RBRACE ; -/. -case $rule_number: { - AST::UiObjectInitializer *node = makeAstNode (driver->nodePool(), sym(2).UiObjectMemberList->finish()); - node->lbraceToken = loc(1); - node->rbraceToken = loc(3); - sym(1).Node = node; -} break; -./ - -UiObjectDefinition: UiQualifiedId UiObjectInitializer ; -/. -case $rule_number: { - AST::UiObjectDefinition *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), - sym(2).UiObjectInitializer); - sym(1).Node = node; -} break; -./ - -UiObjectMember: UiObjectDefinition ; - -UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ; -/. -case $rule_number: { - AST::UiArrayBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), - sym(4).UiArrayMemberList->finish()); - node->colonToken = loc(2); - node->lbracketToken = loc(3); - node->rbracketToken = loc(5); - sym(1).Node = node; -} break; -./ - -UiMultilineStringLiteral: T_MULTILINE_STRING_LITERAL ; -/. -case $rule_number: { - AST::StringLiteral *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->literalToken = loc(1); - sym(1).Node = node; -} break; -./ - -UiMultilineStringStatement: UiMultilineStringLiteral T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -UiMultilineStringStatement: UiMultilineStringLiteral T_SEMICOLON ; -/. -case $rule_number: { - AST::ExpressionStatement *node = makeAstNode (driver->nodePool(), sym(1).Expression); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; -./ - - -UiObjectMember: UiQualifiedId T_COLON Expression UiObjectInitializer ; -/. -case $rule_number: { - if (AST::UiQualifiedId *qualifiedId = reparseAsQualifiedId(sym(3).Expression)) { - AST::UiObjectBinding *node = makeAstNode (driver->nodePool(), - sym(1).UiQualifiedId->finish(), qualifiedId, sym(4).UiObjectInitializer); - node->colonToken = loc(2); - sym(1).Node = node; - } else { - sym(1).Node = 0; - - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc(2), - QLatin1String("Expected a type name after token `:'"))); - - return false; // ### recover - } -} break; -./ - -UiObjectMember: UiQualifiedId T_COLON Block ; -/.case $rule_number:./ - -UiObjectMember: UiQualifiedId T_COLON EmptyStatement ; -/.case $rule_number:./ - -UiObjectMember: UiQualifiedId T_COLON ExpressionStatement ; -/.case $rule_number:./ - -UiObjectMember: UiQualifiedId T_COLON DebuggerStatement ; -/.case $rule_number:./ - -UiObjectMember: UiQualifiedId T_COLON UiMultilineStringStatement ; -/.case $rule_number:./ - -UiObjectMember: UiQualifiedId T_COLON IfStatement ; --- ### do we really want if statement in a binding? -/.case $rule_number:./ - -/. -{ - AST::UiScriptBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), - sym(3).Statement); - node->colonToken = loc(2); - sym(1).Node = node; -} break; -./ - -UiPropertyType: T_VAR ; -/. -case $rule_number: -./ -UiPropertyType: T_RESERVED_WORD ; -/. -case $rule_number: { - sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount()); - break; -} -./ - -UiPropertyType: T_IDENTIFIER ; - -UiObjectMember: T_SIGNAL T_IDENTIFIER ; -/. -case $rule_number: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), (NameId *)0, sym(2).sval); - node->type = AST::UiPublicMember::Signal; - node->propertyToken = loc(1); - node->typeToken = loc(2); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; -./ - -UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_AUTOMATIC_SEMICOLON ; -UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_SEMICOLON ; -/. -case $rule_number: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(3).sval); - node->propertyToken = loc(1); - node->typeToken = loc(2); - node->identifierToken = loc(3); - node->semicolonToken = loc(4); - sym(1).Node = node; -} break; -./ - -UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_AUTOMATIC_SEMICOLON ; -UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_SEMICOLON ; -/. -case $rule_number: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(4).sval); - node->isDefaultMember = true; - node->defaultToken = loc(1); - node->propertyToken = loc(2); - node->typeToken = loc(3); - node->identifierToken = loc(4); - node->semicolonToken = loc(5); - sym(1).Node = node; -} break; -./ - -UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_AUTOMATIC_SEMICOLON ; -UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_SEMICOLON ; -/. -case $rule_number: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(3).sval, - sym(5).Expression); - node->propertyToken = loc(1); - node->typeToken = loc(2); - node->identifierToken = loc(3); - node->colonToken = loc(4); - node->semicolonToken = loc(6); - sym(1).Node = node; -} break; -./ - -UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_AUTOMATIC_SEMICOLON ; -UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_SEMICOLON ; -/. -case $rule_number: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(4).sval, - sym(6).Expression); - node->isDefaultMember = true; - node->defaultToken = loc(1); - node->propertyToken = loc(2); - node->typeToken = loc(3); - node->identifierToken = loc(4); - node->colonToken = loc(5); - node->semicolonToken = loc(7); - sym(1).Node = node; -} break; -./ - -UiObjectMember: FunctionDeclaration ; -/. -case $rule_number: { - sym(1).Node = makeAstNode(driver->nodePool(), sym(1).Node); -} break; -./ - -UiObjectMember: VariableStatement ; -/. -case $rule_number: { - sym(1).Node = makeAstNode(driver->nodePool(), sym(1).Node); -} break; -./ - -UiQualifiedId: T_RESERVED_WORD ; -/.case $rule_number: ./ - -UiQualifiedId: T_RETURN ; -/. -case $rule_number: -{ - AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount())); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; -./ - -JsIdentifier: T_IDENTIFIER; - -JsIdentifier: T_PROPERTY ; -/. -case $rule_number: { - QString s = QLatin1String(JavaScriptGrammar::spell[T_PROPERTY]); - sym(1).sval = driver->intern(s.constData(), s.length()); - break; -} -./ - -JsIdentifier: T_SIGNAL ; -/. -case $rule_number: { - QString s = QLatin1String(JavaScriptGrammar::spell[T_SIGNAL]); - sym(1).sval = driver->intern(s.constData(), s.length()); - break; -} -./ - --------------------------------------------------------------------------------------------------------- --- Expressions --------------------------------------------------------------------------------------------------------- - -PrimaryExpression: T_THIS ; -/. -case $rule_number: { - AST::ThisExpression *node = makeAstNode (driver->nodePool()); - node->thisToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: JsIdentifier ; -/. -case $rule_number: { - AST::IdentifierExpression *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_NULL ; -/. -case $rule_number: { - AST::NullExpression *node = makeAstNode (driver->nodePool()); - node->nullToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_TRUE ; -/. -case $rule_number: { - AST::TrueLiteral *node = makeAstNode (driver->nodePool()); - node->trueToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_FALSE ; -/. -case $rule_number: { - AST::FalseLiteral *node = makeAstNode (driver->nodePool()); - node->falseToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_NUMERIC_LITERAL ; -/. -case $rule_number: { - AST::NumericLiteral *node = makeAstNode (driver->nodePool(), sym(1).dval, lexer->flags); - node->literalToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_STRING_LITERAL ; -/. -case $rule_number: { - AST::StringLiteral *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->literalToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_DIVIDE_ ; -/: -#define J_SCRIPT_REGEXPLITERAL_RULE1 $rule_number -:/ -/. -case $rule_number: { - bool rx = lexer->scanRegExp(Lexer::NoPrefix); - if (!rx) { - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage())); - return false; // ### remove me - } - AST::RegExpLiteral *node = makeAstNode (driver->nodePool(), lexer->pattern, lexer->flags); - node->literalToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_DIVIDE_EQ ; -/: -#define J_SCRIPT_REGEXPLITERAL_RULE2 $rule_number -:/ -/. -case $rule_number: { - bool rx = lexer->scanRegExp(Lexer::EqualPrefix); - if (!rx) { - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage())); - return false; - } - AST::RegExpLiteral *node = makeAstNode (driver->nodePool(), lexer->pattern, lexer->flags); - node->literalToken = loc(1); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_LBRACKET T_RBRACKET ; -/. -case $rule_number: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), (AST::Elision *) 0); - node->lbracketToken = loc(1); - node->rbracketToken = loc(2); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_LBRACKET Elision T_RBRACKET ; -/. -case $rule_number: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).Elision->finish()); - node->lbracketToken = loc(1); - node->rbracketToken = loc(3); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_LBRACKET ElementList T_RBRACKET ; -/. -case $rule_number: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish ()); - node->lbracketToken = loc(1); - node->rbracketToken = loc(3); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_LBRACKET ElementList T_COMMA T_RBRACKET ; -/. -case $rule_number: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish (), - (AST::Elision *) 0); - node->lbracketToken = loc(1); - node->commaToken = loc(3); - node->rbracketToken = loc(4); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_LBRACKET ElementList T_COMMA Elision T_RBRACKET ; -/. -case $rule_number: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish (), - sym(4).Elision->finish()); - node->lbracketToken = loc(1); - node->commaToken = loc(3); - node->rbracketToken = loc(5); - sym(1).Node = node; -} break; -./ - --- PrimaryExpression: T_LBRACE T_RBRACE ; --- /. --- case $rule_number: { --- sym(1).Node = makeAstNode (driver->nodePool()); --- } break; --- ./ - -PrimaryExpression: T_LBRACE PropertyNameAndValueListOpt T_RBRACE ; -/. -case $rule_number: { - AST::ObjectLiteral *node = 0; - if (sym(2).Node) - node = makeAstNode (driver->nodePool(), - sym(2).PropertyNameAndValueList->finish ()); - else - node = makeAstNode (driver->nodePool()); - node->lbraceToken = loc(1); - node->lbraceToken = loc(3); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_LBRACE PropertyNameAndValueList T_COMMA T_RBRACE ; -/. -case $rule_number: { - AST::ObjectLiteral *node = makeAstNode (driver->nodePool(), - sym(2).PropertyNameAndValueList->finish ()); - node->lbraceToken = loc(1); - node->lbraceToken = loc(4); - sym(1).Node = node; -} break; -./ - -PrimaryExpression: T_LPAREN Expression T_RPAREN ; -/. -case $rule_number: { - AST::NestedExpression *node = makeAstNode(driver->nodePool(), sym(2).Expression); - node->lparenToken = loc(1); - node->rparenToken = loc(3); - sym(1).Node = node; -} break; -./ - -UiQualifiedId: JsIdentifier ; -/. -case $rule_number: { - AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; -./ - -UiQualifiedId: UiQualifiedId T_DOT JsIdentifier ; -/. -case $rule_number: { - AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId, sym(3).sval); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; -./ - -ElementList: AssignmentExpression ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), (AST::Elision *) 0, sym(1).Expression); -} break; -./ - -ElementList: Elision AssignmentExpression ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Elision->finish(), sym(2).Expression); -} break; -./ - -ElementList: ElementList T_COMMA AssignmentExpression ; -/. -case $rule_number: { - AST::ElementList *node = makeAstNode (driver->nodePool(), sym(1).ElementList, - (AST::Elision *) 0, sym(3).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; -./ - -ElementList: ElementList T_COMMA Elision AssignmentExpression ; -/. -case $rule_number: { - AST::ElementList *node = makeAstNode (driver->nodePool(), sym(1).ElementList, sym(3).Elision->finish(), - sym(4).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; -./ - -Elision: T_COMMA ; -/. -case $rule_number: { - AST::Elision *node = makeAstNode (driver->nodePool()); - node->commaToken = loc(1); - sym(1).Node = node; -} break; -./ - -Elision: Elision T_COMMA ; -/. -case $rule_number: { - AST::Elision *node = makeAstNode (driver->nodePool(), sym(1).Elision); - node->commaToken = loc(2); - sym(1).Node = node; -} break; -./ - -PropertyNameAndValueList: PropertyName T_COLON AssignmentExpression ; -/. -case $rule_number: { - AST::PropertyNameAndValueList *node = makeAstNode (driver->nodePool(), - sym(1).PropertyName, sym(3).Expression); - node->colonToken = loc(2); - sym(1).Node = node; -} break; -./ - -PropertyNameAndValueList: PropertyNameAndValueList T_COMMA PropertyName T_COLON AssignmentExpression ; -/. -case $rule_number: { - AST::PropertyNameAndValueList *node = makeAstNode (driver->nodePool(), - sym(1).PropertyNameAndValueList, sym(3).PropertyName, sym(5).Expression); - node->commaToken = loc(2); - node->colonToken = loc(4); - sym(1).Node = node; -} break; -./ - -PropertyName: T_IDENTIFIER %prec REDUCE_HERE ; -/. -case $rule_number: { - AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; -./ - -PropertyName: T_SIGNAL ; -/.case $rule_number:./ - -PropertyName: T_PROPERTY ; -/. -case $rule_number: { - AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount())); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; -./ - -PropertyName: T_STRING_LITERAL ; -/. -case $rule_number: { - AST::StringLiteralPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; -./ - -PropertyName: T_NUMERIC_LITERAL ; -/. -case $rule_number: { - AST::NumericLiteralPropertyName *node = makeAstNode (driver->nodePool(), sym(1).dval); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; -./ - -PropertyName: ReservedIdentifier ; -/. -case $rule_number: { - AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; -./ - -ReservedIdentifier: T_BREAK ; -/. -case $rule_number: -./ -ReservedIdentifier: T_CASE ; -/. -case $rule_number: -./ -ReservedIdentifier: T_CATCH ; -/. -case $rule_number: -./ -ReservedIdentifier: T_CONTINUE ; -/. -case $rule_number: -./ -ReservedIdentifier: T_DEFAULT ; -/. -case $rule_number: -./ -ReservedIdentifier: T_DELETE ; -/. -case $rule_number: -./ -ReservedIdentifier: T_DO ; -/. -case $rule_number: -./ -ReservedIdentifier: T_ELSE ; -/. -case $rule_number: -./ -ReservedIdentifier: T_FALSE ; -/. -case $rule_number: -./ -ReservedIdentifier: T_FINALLY ; -/. -case $rule_number: -./ -ReservedIdentifier: T_FOR ; -/. -case $rule_number: -./ -ReservedIdentifier: T_FUNCTION ; -/. -case $rule_number: -./ -ReservedIdentifier: T_IF ; -/. -case $rule_number: -./ -ReservedIdentifier: T_IN ; -/. -case $rule_number: -./ -ReservedIdentifier: T_INSTANCEOF ; -/. -case $rule_number: -./ -ReservedIdentifier: T_NEW ; -/. -case $rule_number: -./ -ReservedIdentifier: T_NULL ; -/. -case $rule_number: -./ -ReservedIdentifier: T_RETURN ; -/. -case $rule_number: -./ -ReservedIdentifier: T_SWITCH ; -/. -case $rule_number: -./ -ReservedIdentifier: T_THIS ; -/. -case $rule_number: -./ -ReservedIdentifier: T_THROW ; -/. -case $rule_number: -./ -ReservedIdentifier: T_TRUE ; -/. -case $rule_number: -./ -ReservedIdentifier: T_TRY ; -/. -case $rule_number: -./ -ReservedIdentifier: T_TYPEOF ; -/. -case $rule_number: -./ -ReservedIdentifier: T_VAR ; -/. -case $rule_number: -./ -ReservedIdentifier: T_VOID ; -/. -case $rule_number: -./ -ReservedIdentifier: T_WHILE ; -/. -case $rule_number: -./ -ReservedIdentifier: T_CONST ; -/. -case $rule_number: -./ -ReservedIdentifier: T_DEBUGGER ; -/. -case $rule_number: -./ -ReservedIdentifier: T_RESERVED_WORD ; -/. -case $rule_number: -./ -ReservedIdentifier: T_WITH ; -/. -case $rule_number: -{ - sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount()); -} break; -./ - -PropertyIdentifier: JsIdentifier ; -PropertyIdentifier: ReservedIdentifier ; - -MemberExpression: PrimaryExpression ; -MemberExpression: FunctionExpression ; - -MemberExpression: MemberExpression T_LBRACKET Expression T_RBRACKET ; -/. -case $rule_number: { - AST::ArrayMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); - node->lbracketToken = loc(2); - node->rbracketToken = loc(4); - sym(1).Node = node; -} break; -./ - -MemberExpression: MemberExpression T_DOT PropertyIdentifier ; -/. -case $rule_number: { - AST::FieldMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).sval); - node->dotToken = loc(2); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; -./ - -MemberExpression: T_NEW MemberExpression T_LPAREN ArgumentListOpt T_RPAREN ; -/. -case $rule_number: { - AST::NewMemberExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression, sym(4).ArgumentList); - node->newToken = loc(1); - node->lparenToken = loc(3); - node->rparenToken = loc(5); - sym(1).Node = node; -} break; -./ - -NewExpression: MemberExpression ; - -NewExpression: T_NEW NewExpression ; -/. -case $rule_number: { - AST::NewExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->newToken = loc(1); - sym(1).Node = node; -} break; -./ - -CallExpression: MemberExpression T_LPAREN ArgumentListOpt T_RPAREN ; -/. -case $rule_number: { - AST::CallExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; -./ - -CallExpression: CallExpression T_LPAREN ArgumentListOpt T_RPAREN ; -/. -case $rule_number: { - AST::CallExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; -./ - -CallExpression: CallExpression T_LBRACKET Expression T_RBRACKET ; -/. -case $rule_number: { - AST::ArrayMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); - node->lbracketToken = loc(2); - node->rbracketToken = loc(4); - sym(1).Node = node; -} break; -./ - -CallExpression: CallExpression T_DOT PropertyIdentifier ; -/. -case $rule_number: { - AST::FieldMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).sval); - node->dotToken = loc(2); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; -./ - -ArgumentListOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -ArgumentListOpt: ArgumentList ; -/. -case $rule_number: { - sym(1).Node = sym(1).ArgumentList->finish(); -} break; -./ - -ArgumentList: AssignmentExpression ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Expression); -} break; -./ - -ArgumentList: ArgumentList T_COMMA AssignmentExpression ; -/. -case $rule_number: { - AST::ArgumentList *node = makeAstNode (driver->nodePool(), sym(1).ArgumentList, sym(3).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; -./ - -LeftHandSideExpression: NewExpression ; -LeftHandSideExpression: CallExpression ; -PostfixExpression: LeftHandSideExpression ; - -PostfixExpression: LeftHandSideExpression T_PLUS_PLUS ; -/. -case $rule_number: { - AST::PostIncrementExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression); - node->incrementToken = loc(2); - sym(1).Node = node; -} break; -./ - -PostfixExpression: LeftHandSideExpression T_MINUS_MINUS ; -/. -case $rule_number: { - AST::PostDecrementExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression); - node->decrementToken = loc(2); - sym(1).Node = node; -} break; -./ - -UnaryExpression: PostfixExpression ; - -UnaryExpression: T_DELETE UnaryExpression ; -/. -case $rule_number: { - AST::DeleteExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->deleteToken = loc(1); - sym(1).Node = node; -} break; -./ - -UnaryExpression: T_VOID UnaryExpression ; -/. -case $rule_number: { - AST::VoidExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->voidToken = loc(1); - sym(1).Node = node; -} break; -./ - -UnaryExpression: T_TYPEOF UnaryExpression ; -/. -case $rule_number: { - AST::TypeOfExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->typeofToken = loc(1); - sym(1).Node = node; -} break; -./ - -UnaryExpression: T_PLUS_PLUS UnaryExpression ; -/. -case $rule_number: { - AST::PreIncrementExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->incrementToken = loc(1); - sym(1).Node = node; -} break; -./ - -UnaryExpression: T_MINUS_MINUS UnaryExpression ; -/. -case $rule_number: { - AST::PreDecrementExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->decrementToken = loc(1); - sym(1).Node = node; -} break; -./ - -UnaryExpression: T_PLUS UnaryExpression ; -/. -case $rule_number: { - AST::UnaryPlusExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->plusToken = loc(1); - sym(1).Node = node; -} break; -./ - -UnaryExpression: T_MINUS UnaryExpression ; -/. -case $rule_number: { - AST::UnaryMinusExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->minusToken = loc(1); - sym(1).Node = node; -} break; -./ - -UnaryExpression: T_TILDE UnaryExpression ; -/. -case $rule_number: { - AST::TildeExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->tildeToken = loc(1); - sym(1).Node = node; -} break; -./ - -UnaryExpression: T_NOT UnaryExpression ; -/. -case $rule_number: { - AST::NotExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->notToken = loc(1); - sym(1).Node = node; -} break; -./ - -MultiplicativeExpression: UnaryExpression ; - -MultiplicativeExpression: MultiplicativeExpression T_STAR UnaryExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Mul, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -MultiplicativeExpression: MultiplicativeExpression T_DIVIDE_ UnaryExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Div, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -MultiplicativeExpression: MultiplicativeExpression T_REMAINDER UnaryExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Mod, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -AdditiveExpression: MultiplicativeExpression ; - -AdditiveExpression: AdditiveExpression T_PLUS MultiplicativeExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Add, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -AdditiveExpression: AdditiveExpression T_MINUS MultiplicativeExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Sub, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -ShiftExpression: AdditiveExpression ; - -ShiftExpression: ShiftExpression T_LT_LT AdditiveExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::LShift, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -ShiftExpression: ShiftExpression T_GT_GT AdditiveExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::RShift, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -ShiftExpression: ShiftExpression T_GT_GT_GT AdditiveExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::URShift, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpression: ShiftExpression ; - -RelationalExpression: RelationalExpression T_LT ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Lt, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpression: RelationalExpression T_GT ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Gt, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpression: RelationalExpression T_LE ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Le, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpression: RelationalExpression T_GE ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Ge, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpression: RelationalExpression T_INSTANCEOF ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::InstanceOf, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpression: RelationalExpression T_IN ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::In, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpressionNotIn: ShiftExpression ; - -RelationalExpressionNotIn: RelationalExpressionNotIn T_LT ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Lt, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpressionNotIn: RelationalExpressionNotIn T_GT ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Gt, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpressionNotIn: RelationalExpressionNotIn T_LE ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Le, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpressionNotIn: RelationalExpressionNotIn T_GE ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Ge, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -RelationalExpressionNotIn: RelationalExpressionNotIn T_INSTANCEOF ShiftExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::InstanceOf, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -EqualityExpression: RelationalExpression ; - -EqualityExpression: EqualityExpression T_EQ_EQ RelationalExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Equal, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -EqualityExpression: EqualityExpression T_NOT_EQ RelationalExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::NotEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -EqualityExpression: EqualityExpression T_EQ_EQ_EQ RelationalExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::StrictEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -EqualityExpression: EqualityExpression T_NOT_EQ_EQ RelationalExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::StrictNotEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -EqualityExpressionNotIn: RelationalExpressionNotIn ; - -EqualityExpressionNotIn: EqualityExpressionNotIn T_EQ_EQ RelationalExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Equal, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -EqualityExpressionNotIn: EqualityExpressionNotIn T_NOT_EQ RelationalExpressionNotIn; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::NotEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -EqualityExpressionNotIn: EqualityExpressionNotIn T_EQ_EQ_EQ RelationalExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::StrictEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -EqualityExpressionNotIn: EqualityExpressionNotIn T_NOT_EQ_EQ RelationalExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::StrictNotEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -BitwiseANDExpression: EqualityExpression ; - -BitwiseANDExpression: BitwiseANDExpression T_AND EqualityExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitAnd, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -BitwiseANDExpressionNotIn: EqualityExpressionNotIn ; - -BitwiseANDExpressionNotIn: BitwiseANDExpressionNotIn T_AND EqualityExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitAnd, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -BitwiseXORExpression: BitwiseANDExpression ; - -BitwiseXORExpression: BitwiseXORExpression T_XOR BitwiseANDExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitXor, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -BitwiseXORExpressionNotIn: BitwiseANDExpressionNotIn ; - -BitwiseXORExpressionNotIn: BitwiseXORExpressionNotIn T_XOR BitwiseANDExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitXor, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -BitwiseORExpression: BitwiseXORExpression ; - -BitwiseORExpression: BitwiseORExpression T_OR BitwiseXORExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitOr, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -BitwiseORExpressionNotIn: BitwiseXORExpressionNotIn ; - -BitwiseORExpressionNotIn: BitwiseORExpressionNotIn T_OR BitwiseXORExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitOr, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -LogicalANDExpression: BitwiseORExpression ; - -LogicalANDExpression: LogicalANDExpression T_AND_AND BitwiseORExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::And, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -LogicalANDExpressionNotIn: BitwiseORExpressionNotIn ; - -LogicalANDExpressionNotIn: LogicalANDExpressionNotIn T_AND_AND BitwiseORExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::And, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -LogicalORExpression: LogicalANDExpression ; - -LogicalORExpression: LogicalORExpression T_OR_OR LogicalANDExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Or, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -LogicalORExpressionNotIn: LogicalANDExpressionNotIn ; - -LogicalORExpressionNotIn: LogicalORExpressionNotIn T_OR_OR LogicalANDExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Or, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -ConditionalExpression: LogicalORExpression ; - -ConditionalExpression: LogicalORExpression T_QUESTION AssignmentExpression T_COLON AssignmentExpression ; -/. -case $rule_number: { - AST::ConditionalExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - sym(3).Expression, sym(5).Expression); - node->questionToken = loc(2); - node->colonToken = loc(4); - sym(1).Node = node; -} break; -./ - -ConditionalExpressionNotIn: LogicalORExpressionNotIn ; - -ConditionalExpressionNotIn: LogicalORExpressionNotIn T_QUESTION AssignmentExpressionNotIn T_COLON AssignmentExpressionNotIn ; -/. -case $rule_number: { - AST::ConditionalExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - sym(3).Expression, sym(5).Expression); - node->questionToken = loc(2); - node->colonToken = loc(4); - sym(1).Node = node; -} break; -./ - -AssignmentExpression: ConditionalExpression ; - -AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - sym(2).ival, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -AssignmentExpressionNotIn: ConditionalExpressionNotIn ; - -AssignmentExpressionNotIn: LeftHandSideExpression AssignmentOperator AssignmentExpressionNotIn ; -/. -case $rule_number: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - sym(2).ival, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; -./ - -AssignmentOperator: T_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::Assign; -} break; -./ - -AssignmentOperator: T_STAR_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceMul; -} break; -./ - -AssignmentOperator: T_DIVIDE_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceDiv; -} break; -./ - -AssignmentOperator: T_REMAINDER_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceMod; -} break; -./ - -AssignmentOperator: T_PLUS_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceAdd; -} break; -./ - -AssignmentOperator: T_MINUS_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceSub; -} break; -./ - -AssignmentOperator: T_LT_LT_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceLeftShift; -} break; -./ - -AssignmentOperator: T_GT_GT_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceRightShift; -} break; -./ - -AssignmentOperator: T_GT_GT_GT_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceURightShift; -} break; -./ - -AssignmentOperator: T_AND_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceAnd; -} break; -./ - -AssignmentOperator: T_XOR_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceXor; -} break; -./ - -AssignmentOperator: T_OR_EQ ; -/. -case $rule_number: { - sym(1).ival = QSOperator::InplaceOr; -} break; -./ - -Expression: AssignmentExpression ; - -Expression: Expression T_COMMA AssignmentExpression ; -/. -case $rule_number: { - AST::Expression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; -./ - -ExpressionOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -ExpressionOpt: Expression ; - -ExpressionNotIn: AssignmentExpressionNotIn ; - -ExpressionNotIn: ExpressionNotIn T_COMMA AssignmentExpressionNotIn ; -/. -case $rule_number: { - AST::Expression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; -./ - -ExpressionNotInOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -ExpressionNotInOpt: ExpressionNotIn ; - -Statement: Block ; -Statement: VariableStatement ; -Statement: EmptyStatement ; -Statement: ExpressionStatement ; -Statement: IfStatement ; -Statement: IterationStatement ; -Statement: ContinueStatement ; -Statement: BreakStatement ; -Statement: ReturnStatement ; -Statement: WithStatement ; -Statement: LabelledStatement ; -Statement: SwitchStatement ; -Statement: ThrowStatement ; -Statement: TryStatement ; -Statement: DebuggerStatement ; - - -Block: T_LBRACE StatementListOpt T_RBRACE ; -/. -case $rule_number: { - AST::Block *node = makeAstNode (driver->nodePool(), sym(2).StatementList); - node->lbraceToken = loc(1); - node->rbraceToken = loc(3); - sym(1).Node = node; -} break; -./ - -StatementList: Statement ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Statement); -} break; -./ - -StatementList: StatementList Statement ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).StatementList, sym(2).Statement); -} break; -./ - -StatementListOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -StatementListOpt: StatementList ; -/. -case $rule_number: { - sym(1).Node = sym(1).StatementList->finish (); -} break; -./ - -VariableStatement: VariableDeclarationKind VariableDeclarationList T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -VariableStatement: VariableDeclarationKind VariableDeclarationList T_SEMICOLON ; -/. -case $rule_number: { - AST::VariableStatement *node = makeAstNode (driver->nodePool(), - sym(2).VariableDeclarationList->finish (/*readOnly=*/sym(1).ival == T_CONST)); - node->declarationKindToken = loc(1); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; -./ - -VariableDeclarationKind: T_CONST ; -/. -case $rule_number: { - sym(1).ival = T_CONST; -} break; -./ - -VariableDeclarationKind: T_VAR ; -/. -case $rule_number: { - sym(1).ival = T_VAR; -} break; -./ - -VariableDeclarationList: VariableDeclaration ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclaration); -} break; -./ - -VariableDeclarationList: VariableDeclarationList T_COMMA VariableDeclaration ; -/. -case $rule_number: { - AST::VariableDeclarationList *node = makeAstNode (driver->nodePool(), - sym(1).VariableDeclarationList, sym(3).VariableDeclaration); - node->commaToken = loc(2); - sym(1).Node = node; -} break; -./ - -VariableDeclarationListNotIn: VariableDeclarationNotIn ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclaration); -} break; -./ - -VariableDeclarationListNotIn: VariableDeclarationListNotIn T_COMMA VariableDeclarationNotIn ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclarationList, sym(3).VariableDeclaration); -} break; -./ - -VariableDeclaration: JsIdentifier InitialiserOpt ; -/. -case $rule_number: { - AST::VariableDeclaration *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(2).Expression); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; -./ - -VariableDeclarationNotIn: JsIdentifier InitialiserNotInOpt ; -/. -case $rule_number: { - AST::VariableDeclaration *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(2).Expression); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; -./ - -Initialiser: T_EQ AssignmentExpression ; -/. -case $rule_number: { - // ### TODO: AST for initializer - sym(1) = sym(2); -} break; -./ - -InitialiserOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -InitialiserOpt: Initialiser ; - -InitialiserNotIn: T_EQ AssignmentExpressionNotIn ; -/. -case $rule_number: { - // ### TODO: AST for initializer - sym(1) = sym(2); -} break; -./ - -InitialiserNotInOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -InitialiserNotInOpt: InitialiserNotIn ; - -EmptyStatement: T_SEMICOLON ; -/. -case $rule_number: { - AST::EmptyStatement *node = makeAstNode (driver->nodePool()); - node->semicolonToken = loc(1); - sym(1).Node = node; -} break; -./ - -ExpressionStatement: Expression T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -ExpressionStatement: Expression T_SEMICOLON ; -/. -case $rule_number: { - AST::ExpressionStatement *node = makeAstNode (driver->nodePool(), sym(1).Expression); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; -./ - -IfStatement: T_IF T_LPAREN Expression T_RPAREN Statement T_ELSE Statement ; -/. -case $rule_number: { - AST::IfStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement, sym(7).Statement); - node->ifToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - node->elseToken = loc(5); - sym(1).Node = node; -} break; -./ - -IfStatement: T_IF T_LPAREN Expression T_RPAREN Statement ; -/. -case $rule_number: { - AST::IfStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); - node->ifToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; -./ - - -IterationStatement: T_DO Statement T_WHILE T_LPAREN Expression T_RPAREN T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -IterationStatement: T_DO Statement T_WHILE T_LPAREN Expression T_RPAREN T_SEMICOLON ; -/. -case $rule_number: { - AST::DoWhileStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(5).Expression); - node->doToken = loc(1); - node->whileToken = loc(3); - node->lparenToken = loc(4); - node->rparenToken = loc(6); - node->semicolonToken = loc(7); - sym(1).Node = node; -} break; -./ - -IterationStatement: T_WHILE T_LPAREN Expression T_RPAREN Statement ; -/. -case $rule_number: { - AST::WhileStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); - node->whileToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; -./ - -IterationStatement: T_FOR T_LPAREN ExpressionNotInOpt T_SEMICOLON ExpressionOpt T_SEMICOLON ExpressionOpt T_RPAREN Statement ; -/. -case $rule_number: { - AST::ForStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, - sym(5).Expression, sym(7).Expression, sym(9).Statement); - node->forToken = loc(1); - node->lparenToken = loc(2); - node->firstSemicolonToken = loc(4); - node->secondSemicolonToken = loc(6); - node->rparenToken = loc(8); - sym(1).Node = node; -} break; -./ - -IterationStatement: T_FOR T_LPAREN T_VAR VariableDeclarationListNotIn T_SEMICOLON ExpressionOpt T_SEMICOLON ExpressionOpt T_RPAREN Statement ; -/. -case $rule_number: { - AST::LocalForStatement *node = makeAstNode (driver->nodePool(), - sym(4).VariableDeclarationList->finish (/*readOnly=*/false), sym(6).Expression, - sym(8).Expression, sym(10).Statement); - node->forToken = loc(1); - node->lparenToken = loc(2); - node->varToken = loc(3); - node->firstSemicolonToken = loc(5); - node->secondSemicolonToken = loc(7); - node->rparenToken = loc(9); - sym(1).Node = node; -} break; -./ - -IterationStatement: T_FOR T_LPAREN LeftHandSideExpression T_IN Expression T_RPAREN Statement ; -/. -case $rule_number: { - AST:: ForEachStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, - sym(5).Expression, sym(7).Statement); - node->forToken = loc(1); - node->lparenToken = loc(2); - node->inToken = loc(4); - node->rparenToken = loc(6); - sym(1).Node = node; -} break; -./ - -IterationStatement: T_FOR T_LPAREN T_VAR VariableDeclarationNotIn T_IN Expression T_RPAREN Statement ; -/. -case $rule_number: { - AST::LocalForEachStatement *node = makeAstNode (driver->nodePool(), - sym(4).VariableDeclaration, sym(6).Expression, sym(8).Statement); - node->forToken = loc(1); - node->lparenToken = loc(2); - node->varToken = loc(3); - node->inToken = loc(5); - node->rparenToken = loc(7); - sym(1).Node = node; -} break; -./ - -ContinueStatement: T_CONTINUE T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -ContinueStatement: T_CONTINUE T_SEMICOLON ; -/. -case $rule_number: { - AST::ContinueStatement *node = makeAstNode (driver->nodePool()); - node->continueToken = loc(1); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; -./ - -ContinueStatement: T_CONTINUE JsIdentifier T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -ContinueStatement: T_CONTINUE JsIdentifier T_SEMICOLON ; -/. -case $rule_number: { - AST::ContinueStatement *node = makeAstNode (driver->nodePool(), sym(2).sval); - node->continueToken = loc(1); - node->identifierToken = loc(2); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; -./ - -BreakStatement: T_BREAK T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -BreakStatement: T_BREAK T_SEMICOLON ; -/. -case $rule_number: { - AST::BreakStatement *node = makeAstNode (driver->nodePool()); - node->breakToken = loc(1); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; -./ - -BreakStatement: T_BREAK JsIdentifier T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -BreakStatement: T_BREAK JsIdentifier T_SEMICOLON ; -/. -case $rule_number: { - AST::BreakStatement *node = makeAstNode (driver->nodePool(), sym(2).sval); - node->breakToken = loc(1); - node->identifierToken = loc(2); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; -./ - -ReturnStatement: T_RETURN ExpressionOpt T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -ReturnStatement: T_RETURN ExpressionOpt T_SEMICOLON ; -/. -case $rule_number: { - AST::ReturnStatement *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->returnToken = loc(1); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; -./ - -WithStatement: T_WITH T_LPAREN Expression T_RPAREN Statement ; -/. -case $rule_number: { - AST::WithStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); - node->withToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; -./ - -SwitchStatement: T_SWITCH T_LPAREN Expression T_RPAREN CaseBlock ; -/. -case $rule_number: { - AST::SwitchStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).CaseBlock); - node->switchToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; -./ - -CaseBlock: T_LBRACE CaseClausesOpt T_RBRACE ; -/. -case $rule_number: { - AST::CaseBlock *node = makeAstNode (driver->nodePool(), sym(2).CaseClauses); - node->lbraceToken = loc(1); - node->rbraceToken = loc(3); - sym(1).Node = node; -} break; -./ - -CaseBlock: T_LBRACE CaseClausesOpt DefaultClause CaseClausesOpt T_RBRACE ; -/. -case $rule_number: { - AST::CaseBlock *node = makeAstNode (driver->nodePool(), sym(2).CaseClauses, sym(3).DefaultClause, sym(4).CaseClauses); - node->lbraceToken = loc(1); - node->rbraceToken = loc(5); - sym(1).Node = node; -} break; -./ - -CaseClauses: CaseClause ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).CaseClause); -} break; -./ - -CaseClauses: CaseClauses CaseClause ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).CaseClauses, sym(2).CaseClause); -} break; -./ - -CaseClausesOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -CaseClausesOpt: CaseClauses ; -/. -case $rule_number: { - sym(1).Node = sym(1).CaseClauses->finish (); -} break; -./ - -CaseClause: T_CASE Expression T_COLON StatementListOpt ; -/. -case $rule_number: { - AST::CaseClause *node = makeAstNode (driver->nodePool(), sym(2).Expression, sym(4).StatementList); - node->caseToken = loc(1); - node->colonToken = loc(3); - sym(1).Node = node; -} break; -./ - -DefaultClause: T_DEFAULT T_COLON StatementListOpt ; -/. -case $rule_number: { - AST::DefaultClause *node = makeAstNode (driver->nodePool(), sym(3).StatementList); - node->defaultToken = loc(1); - node->colonToken = loc(2); - sym(1).Node = node; -} break; -./ - -LabelledStatement: T_SIGNAL T_COLON Statement ; -/.case $rule_number:./ - -LabelledStatement: T_PROPERTY T_COLON Statement ; -/. -case $rule_number: { - AST::LabelledStatement *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount()), sym(3).Statement); - node->identifierToken = loc(1); - node->colonToken = loc(2); - sym(1).Node = node; -} break; -./ - -LabelledStatement: T_IDENTIFIER T_COLON Statement ; -/. -case $rule_number: { - AST::LabelledStatement *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(3).Statement); - node->identifierToken = loc(1); - node->colonToken = loc(2); - sym(1).Node = node; -} break; -./ - -ThrowStatement: T_THROW Expression T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -ThrowStatement: T_THROW Expression T_SEMICOLON ; -/. -case $rule_number: { - AST::ThrowStatement *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->throwToken = loc(1); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; -./ - -TryStatement: T_TRY Block Catch ; -/. -case $rule_number: { - AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Catch); - node->tryToken = loc(1); - sym(1).Node = node; -} break; -./ - -TryStatement: T_TRY Block Finally ; -/. -case $rule_number: { - AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Finally); - node->tryToken = loc(1); - sym(1).Node = node; -} break; -./ - -TryStatement: T_TRY Block Catch Finally ; -/. -case $rule_number: { - AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Catch, sym(4).Finally); - node->tryToken = loc(1); - sym(1).Node = node; -} break; -./ - -Catch: T_CATCH T_LPAREN JsIdentifier T_RPAREN Block ; -/. -case $rule_number: { - AST::Catch *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(5).Block); - node->catchToken = loc(1); - node->lparenToken = loc(2); - node->identifierToken = loc(3); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; -./ - -Finally: T_FINALLY Block ; -/. -case $rule_number: { - AST::Finally *node = makeAstNode (driver->nodePool(), sym(2).Block); - node->finallyToken = loc(1); - sym(1).Node = node; -} break; -./ - -DebuggerStatement: T_DEBUGGER T_AUTOMATIC_SEMICOLON ; -- automatic semicolon -DebuggerStatement: T_DEBUGGER T_SEMICOLON ; -/. -case $rule_number: { - AST::DebuggerStatement *node = makeAstNode (driver->nodePool()); - node->debuggerToken = loc(1); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; -./ - -FunctionDeclaration: T_FUNCTION JsIdentifier T_LPAREN FormalParameterListOpt T_RPAREN T_LBRACE FunctionBodyOpt T_RBRACE ; -/. -case $rule_number: { - AST::FunctionDeclaration *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody); - node->functionToken = loc(1); - node->identifierToken = loc(2); - node->lparenToken = loc(3); - node->rparenToken = loc(5); - node->lbraceToken = loc(6); - node->rbraceToken = loc(8); - sym(1).Node = node; -} break; -./ - -FunctionExpression: T_FUNCTION IdentifierOpt T_LPAREN FormalParameterListOpt T_RPAREN T_LBRACE FunctionBodyOpt T_RBRACE ; -/. -case $rule_number: { - AST::FunctionExpression *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody); - node->functionToken = loc(1); - if (sym(2).sval) - node->identifierToken = loc(2); - node->lparenToken = loc(3); - node->rparenToken = loc(5); - node->lbraceToken = loc(6); - node->rbraceToken = loc(8); - sym(1).Node = node; -} break; -./ - -FormalParameterList: JsIdentifier ; -/. -case $rule_number: { - AST::FormalParameterList *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; -./ - -FormalParameterList: FormalParameterList T_COMMA JsIdentifier ; -/. -case $rule_number: { - AST::FormalParameterList *node = makeAstNode (driver->nodePool(), sym(1).FormalParameterList, sym(3).sval); - node->commaToken = loc(2); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; -./ - -FormalParameterListOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -FormalParameterListOpt: FormalParameterList ; -/. -case $rule_number: { - sym(1).Node = sym(1).FormalParameterList->finish (); -} break; -./ - -FunctionBodyOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -FunctionBodyOpt: FunctionBody ; - -FunctionBody: SourceElements ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements->finish ()); -} break; -./ - ---JavaScriptProgram: SourceElements ; ---/. ---case $rule_number: { --- sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements->finish ()); --- driver->changeAbstractSyntaxTree(sym(1).Node); ---} break; ---./ - -SourceElements: SourceElement ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElement); -} break; -./ - -SourceElements: SourceElements SourceElement ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements, sym(2).SourceElement); -} break; -./ - -SourceElement: Statement ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Statement); -} break; -./ - -SourceElement: FunctionDeclaration ; -/. -case $rule_number: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).FunctionDeclaration); -} break; -./ - -IdentifierOpt: ; -/. -case $rule_number: { - sym(1).sval = 0; -} break; -./ - -IdentifierOpt: JsIdentifier ; - -PropertyNameAndValueListOpt: ; -/. -case $rule_number: { - sym(1).Node = 0; -} break; -./ - -PropertyNameAndValueListOpt: PropertyNameAndValueList ; - -/. - } // switch - action = nt_action(state_stack[tos], lhs[r] - TERMINAL_COUNT); - } // if - } while (action != 0); - - if (first_token == last_token) { - const int errorState = state_stack[tos]; - - // automatic insertion of `;' - if (t_action(errorState, T_AUTOMATIC_SEMICOLON) && automatic(driver, yytoken)) { - SavedToken &tk = token_buffer[0]; - tk.token = yytoken; - tk.dval = yylval; - tk.loc = yylloc; - - yylloc = yyprevlloc; - yylloc.offset += yylloc.length; - yylloc.startColumn += yylloc.length; - yylloc.length = 0; - - //const QString msg = QString::fromUtf8("Missing `;'"); - //diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, yylloc, msg)); - - first_token = &token_buffer[0]; - last_token = &token_buffer[1]; - - yytoken = T_SEMICOLON; - yylval = 0; - - action = errorState; - - goto _Lcheck_token; - } - - hadErrors = true; - - token_buffer[0].token = yytoken; - token_buffer[0].dval = yylval; - token_buffer[0].loc = yylloc; - - token_buffer[1].token = yytoken = lexer->lex(); - token_buffer[1].dval = yylval = lexer->dval(); - token_buffer[1].loc = yylloc = location(lexer); - - if (t_action(errorState, yytoken)) { - const QString msg = QString::fromUtf8("Unexpected token `%1'").arg(QLatin1String(spell[token_buffer[0].token])); - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); - - action = errorState; - goto _Lcheck_token; - } - - static int tokens[] = { - T_PLUS, - T_EQ, - - T_COMMA, - T_COLON, - T_SEMICOLON, - - T_RPAREN, T_RBRACKET, T_RBRACE, - - T_NUMERIC_LITERAL, - T_IDENTIFIER, - - T_LPAREN, T_LBRACKET, T_LBRACE, - - EOF_SYMBOL - }; - - for (int *tk = tokens; *tk != EOF_SYMBOL; ++tk) { - int a = t_action(errorState, *tk); - if (a > 0 && t_action(a, yytoken)) { - const QString msg = QString::fromUtf8("Expected token `%1'").arg(QLatin1String(spell[*tk])); - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); - - yytoken = *tk; - yylval = 0; - yylloc = token_buffer[0].loc; - yylloc.length = 0; - - first_token = &token_buffer[0]; - last_token = &token_buffer[2]; - - action = errorState; - goto _Lcheck_token; - } - } - - for (int tk = 1; tk < TERMINAL_COUNT; ++tk) { - if (tk == T_AUTOMATIC_SEMICOLON) - continue; - - int a = t_action(errorState, tk); - if (a > 0 && t_action(a, yytoken)) { - const QString msg = QString::fromUtf8("Expected token `%1'").arg(QLatin1String(spell[tk])); - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); - - yytoken = tk; - yylval = 0; - yylloc = token_buffer[0].loc; - yylloc.length = 0; - - action = errorState; - goto _Lcheck_token; - } - } - - const QString msg = QString::fromUtf8("Syntax error"); - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); - } - - return false; -} - -QT_END_NAMESPACE - - -./ -/: -QT_END_NAMESPACE - - - -#endif // JAVASCRIPTPARSER_P_H -:/ diff --git a/src/declarative/qml/parser/javascriptast.cpp b/src/declarative/qml/parser/javascriptast.cpp deleted file mode 100644 index ada19d5..0000000 --- a/src/declarative/qml/parser/javascriptast.cpp +++ /dev/null @@ -1,962 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "javascriptast_p.h" - - - -#include "javascriptastvisitor_p.h" - -QT_BEGIN_NAMESPACE - -namespace JavaScript { namespace AST { - -int NumericLiteral::suffixLength[] = { - 0, // noSuffix - 2, // emSuffix - 2, // exSuffix - 2, // pxSuffix - 2, // cmSuffix - 2, // mmSuffix - 2, // inSuffix - 2, // ptSuffix - 2, // pcSuffix - 3, // degSuffix - 3, // radSuffix - 4, // gradSuffix - 2, // msSuffix - 1, // sSuffix - 2, // hzSuffix - 3 // khzSuffix -}; - -const char *const NumericLiteral::suffixSpell[] = { - "", - "em", - "ex", - "px", - "cm", - "mm", - "in", - "pt", - "pc", - "deg", - "rad", - "grad", - "ms", - "s", - "hz", - "khz" -}; - -ExpressionNode *Node::expressionCast() -{ - return 0; -} - -BinaryExpression *Node::binaryExpressionCast() -{ - return 0; -} - -Statement *Node::statementCast() -{ - return 0; -} - -ExpressionNode *ExpressionNode::expressionCast() -{ - return this; -} - -BinaryExpression *BinaryExpression::binaryExpressionCast() -{ - return this; -} - -Statement *Statement::statementCast() -{ - return this; -} - -void NestedExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - visitor->endVisit(this); -} - -void ThisExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void IdentifierExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void NullExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void TrueLiteral::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void FalseLiteral::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void StringLiteral::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void NumericLiteral::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void RegExpLiteral::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void ArrayLiteral::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(elements, visitor); - acceptChild(elision, visitor); - } - - visitor->endVisit(this); -} - -void ObjectLiteral::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(properties, visitor); - } - - visitor->endVisit(this); -} - -void ElementList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - ElementList *it = this; - do { - acceptChild(it->elision, visitor); - acceptChild(it->expression, visitor); - it = it->next; - } while (it); - } - - visitor->endVisit(this); -} - -void Elision::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - // ### - } - - visitor->endVisit(this); -} - -void PropertyNameAndValueList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - PropertyNameAndValueList *it = this; - do { - acceptChild(it->name, visitor); - acceptChild(it->value, visitor); - it = it->next; - } while (it); - } - - visitor->endVisit(this); -} - -void IdentifierPropertyName::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void StringLiteralPropertyName::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void NumericLiteralPropertyName::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void ArrayMemberExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(base, visitor); - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void FieldMemberExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(base, visitor); - } - - visitor->endVisit(this); -} - -void NewMemberExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(base, visitor); - acceptChild(arguments, visitor); - } - - visitor->endVisit(this); -} - -void NewExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void CallExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(base, visitor); - acceptChild(arguments, visitor); - } - - visitor->endVisit(this); -} - -void ArgumentList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - ArgumentList *it = this; - do { - acceptChild(it->expression, visitor); - it = it->next; - } while (it); - } - - visitor->endVisit(this); -} - -void PostIncrementExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(base, visitor); - } - - visitor->endVisit(this); -} - -void PostDecrementExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(base, visitor); - } - - visitor->endVisit(this); -} - -void DeleteExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void VoidExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void TypeOfExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void PreIncrementExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void PreDecrementExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void UnaryPlusExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void UnaryMinusExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void TildeExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void NotExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void BinaryExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(left, visitor); - acceptChild(right, visitor); - } - - visitor->endVisit(this); -} - -void ConditionalExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - acceptChild(ok, visitor); - acceptChild(ko, visitor); - } - - visitor->endVisit(this); -} - -void Expression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(left, visitor); - acceptChild(right, visitor); - } - - visitor->endVisit(this); -} - -void Block::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(statements, visitor); - } - - visitor->endVisit(this); -} - -void StatementList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - StatementList *it = this; - do { - acceptChild(it->statement, visitor); - it = it->next; - } while (it); - } - - visitor->endVisit(this); -} - -void VariableStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(declarations, visitor); - } - - visitor->endVisit(this); -} - -void VariableDeclarationList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - VariableDeclarationList *it = this; - do { - acceptChild(it->declaration, visitor); - it = it->next; - } while (it); - } - - visitor->endVisit(this); -} - -void VariableDeclaration::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void EmptyStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void ExpressionStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void IfStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - acceptChild(ok, visitor); - acceptChild(ko, visitor); - } - - visitor->endVisit(this); -} - -void DoWhileStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(statement, visitor); - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void WhileStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void ForStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(initialiser, visitor); - acceptChild(condition, visitor); - acceptChild(expression, visitor); - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void LocalForStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(declarations, visitor); - acceptChild(condition, visitor); - acceptChild(expression, visitor); - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void ForEachStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(initialiser, visitor); - acceptChild(expression, visitor); - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void LocalForEachStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(declaration, visitor); - acceptChild(expression, visitor); - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void ContinueStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void BreakStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void ReturnStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void WithStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void SwitchStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - acceptChild(block, visitor); - } - - visitor->endVisit(this); -} - -void CaseBlock::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(clauses, visitor); - acceptChild(defaultClause, visitor); - acceptChild(moreClauses, visitor); - } - - visitor->endVisit(this); -} - -void CaseClauses::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - CaseClauses *it = this; - do { - acceptChild(it->clause, visitor); - it = it->next; - } while (it); - } - - visitor->endVisit(this); -} - -void CaseClause::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - acceptChild(statements, visitor); - } - - visitor->endVisit(this); -} - -void DefaultClause::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(statements, visitor); - } - - visitor->endVisit(this); -} - -void LabelledStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void ThrowStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void TryStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(statement, visitor); - acceptChild(catchExpression, visitor); - acceptChild(finallyExpression, visitor); - } - - visitor->endVisit(this); -} - -void Catch::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void Finally::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void FunctionDeclaration::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(formals, visitor); - acceptChild(body, visitor); - } - - visitor->endVisit(this); -} - -void FunctionExpression::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(formals, visitor); - acceptChild(body, visitor); - } - - visitor->endVisit(this); -} - -void FormalParameterList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - // ### - } - - visitor->endVisit(this); -} - -void FunctionBody::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(elements, visitor); - } - - visitor->endVisit(this); -} - -void Program::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(elements, visitor); - } - - visitor->endVisit(this); -} - -void SourceElements::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - SourceElements *it = this; - do { - acceptChild(it->element, visitor); - it = it->next; - } while (it); - } - - visitor->endVisit(this); -} - -void FunctionSourceElement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(declaration, visitor); - } - - visitor->endVisit(this); -} - -void StatementSourceElement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void DebuggerStatement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - - -void UiProgram::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - for (UiObjectMemberList *it = members; it; it = it->next) - acceptChild(it->member, visitor); - } - - visitor->endVisit(this); -} - -void UiPublicMember::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(expression, visitor); - } - - visitor->endVisit(this); -} - -void UiObjectDefinition::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(qualifiedTypeNameId, visitor); - acceptChild(initializer, visitor); - } - - visitor->endVisit(this); -} - -void UiObjectInitializer::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - for (UiObjectMemberList *it = members; it; it = it->next) - acceptChild(it->member, visitor); - } - - visitor->endVisit(this); -} - -void UiObjectBinding::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(qualifiedId, visitor); - acceptChild(qualifiedTypeNameId, visitor); - acceptChild(initializer, visitor); - } - - visitor->endVisit(this); -} - -void UiScriptBinding::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(qualifiedId, visitor); - acceptChild(statement, visitor); - } - - visitor->endVisit(this); -} - -void UiArrayBinding::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(qualifiedId, visitor); - for (UiArrayMemberList *it = members; it; it = it->next) - acceptChild(it->member, visitor); - } - - visitor->endVisit(this); -} - -void UiObjectMemberList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - for (UiObjectMemberList *it = this; it; it = it->next) - acceptChild(it->member, visitor); - } - - visitor->endVisit(this); -} - -void UiArrayMemberList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - for (UiArrayMemberList *it = this; it; it = it->next) - acceptChild(it->member, visitor); - } - - visitor->endVisit(this); -} - -void UiQualifiedId::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void UiImport::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - } - - visitor->endVisit(this); -} - -void UiImportList::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(import, visitor); - acceptChild(next, visitor); - } - - visitor->endVisit(this); -} - -void UiSourceElement::accept0(Visitor *visitor) -{ - if (visitor->visit(this)) { - acceptChild(sourceElement, visitor); - } - - visitor->endVisit(this); -} - -} } // namespace JavaScript::AST - -QT_END_NAMESPACE - - diff --git a/src/declarative/qml/parser/javascriptast_p.h b/src/declarative/qml/parser/javascriptast_p.h deleted file mode 100644 index 8c1e2bc..0000000 --- a/src/declarative/qml/parser/javascriptast_p.h +++ /dev/null @@ -1,2544 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JAVASCRIPTAST_P_H -#define JAVASCRIPTAST_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "javascriptastvisitor_p.h" -#include - -QT_BEGIN_NAMESPACE - -#define JAVASCRIPT_DECLARE_AST_NODE(name) \ - enum { K = Kind_##name }; - -namespace QSOperator // ### rename -{ - -enum Op { - Add, - And, - InplaceAnd, - Assign, - BitAnd, - BitOr, - BitXor, - InplaceSub, - Div, - InplaceDiv, - Equal, - Ge, - Gt, - In, - InplaceAdd, - InstanceOf, - Le, - LShift, - InplaceLeftShift, - Lt, - Mod, - InplaceMod, - Mul, - InplaceMul, - NotEqual, - Or, - InplaceOr, - RShift, - InplaceRightShift, - StrictEqual, - StrictNotEqual, - Sub, - URShift, - InplaceURightShift, - InplaceXor -}; - -} // namespace QSOperator - -namespace JavaScript { -class NameId; -namespace AST { - -template -_T1 cast(_T2 *ast) -{ - if (ast && ast->kind == static_cast<_T1>(0)->K) - return static_cast<_T1>(ast); - - return 0; -} - -class Node -{ -public: - enum Kind { - Kind_Undefined, - - Kind_ArgumentList, - Kind_ArrayLiteral, - Kind_ArrayMemberExpression, - Kind_BinaryExpression, - Kind_Block, - Kind_BreakStatement, - Kind_CallExpression, - Kind_CaseBlock, - Kind_CaseClause, - Kind_CaseClauses, - Kind_Catch, - Kind_ConditionalExpression, - Kind_ContinueStatement, - Kind_DebuggerStatement, - Kind_DefaultClause, - Kind_DeleteExpression, - Kind_DoWhileStatement, - Kind_ElementList, - Kind_Elision, - Kind_EmptyStatement, - Kind_Expression, - Kind_ExpressionStatement, - Kind_FalseLiteral, - Kind_FieldMemberExpression, - Kind_Finally, - Kind_ForEachStatement, - Kind_ForStatement, - Kind_FormalParameterList, - Kind_FunctionBody, - Kind_FunctionDeclaration, - Kind_FunctionExpression, - Kind_FunctionSourceElement, - Kind_IdentifierExpression, - Kind_IdentifierPropertyName, - Kind_IfStatement, - Kind_LabelledStatement, - Kind_LocalForEachStatement, - Kind_LocalForStatement, - Kind_NewExpression, - Kind_NewMemberExpression, - Kind_NotExpression, - Kind_NullExpression, - Kind_NumericLiteral, - Kind_NumericLiteralPropertyName, - Kind_ObjectLiteral, - Kind_PostDecrementExpression, - Kind_PostIncrementExpression, - Kind_PreDecrementExpression, - Kind_PreIncrementExpression, - Kind_Program, - Kind_PropertyName, - Kind_PropertyNameAndValueList, - Kind_RegExpLiteral, - Kind_ReturnStatement, - Kind_SourceElement, - Kind_SourceElements, - Kind_StatementList, - Kind_StatementSourceElement, - Kind_StringLiteral, - Kind_StringLiteralPropertyName, - Kind_SwitchStatement, - Kind_ThisExpression, - Kind_ThrowStatement, - Kind_TildeExpression, - Kind_TrueLiteral, - Kind_TryStatement, - Kind_TypeOfExpression, - Kind_UnaryMinusExpression, - Kind_UnaryPlusExpression, - Kind_VariableDeclaration, - Kind_VariableDeclarationList, - Kind_VariableStatement, - Kind_VoidExpression, - Kind_WhileStatement, - Kind_WithStatement, - Kind_NestedExpression, - - Kind_UiArrayBinding, - Kind_UiImport, - Kind_UiImportList, - Kind_UiObjectBinding, - Kind_UiObjectDefinition, - Kind_UiObjectInitializer, - Kind_UiObjectMemberList, - Kind_UiArrayMemberList, - Kind_UiProgram, - Kind_UiPublicMember, - Kind_UiQualifiedId, - Kind_UiScriptBinding, - Kind_UiSourceElement - }; - - inline Node() - : kind(Kind_Undefined) {} - - virtual ~Node() {} - - virtual ExpressionNode *expressionCast(); - virtual BinaryExpression *binaryExpressionCast(); - virtual Statement *statementCast(); - - inline void accept(Visitor *visitor) - { - if (visitor->preVisit(this)) { - accept0(visitor); - visitor->postVisit(this); - } - } - - static void acceptChild(Node *node, Visitor *visitor) - { - if (node) - node->accept(visitor); - } - - virtual void accept0(Visitor *visitor) = 0; - -// attributes - int kind; -}; - -class ExpressionNode: public Node -{ -public: - ExpressionNode() {} - virtual ~ExpressionNode() {} - - virtual ExpressionNode *expressionCast(); - - virtual SourceLocation firstSourceLocation() const = 0; - virtual SourceLocation lastSourceLocation() const = 0; -}; - -class Statement: public Node -{ -public: - Statement() {} - virtual ~Statement() {} - - virtual Statement *statementCast(); - - virtual SourceLocation firstSourceLocation() const = 0; - virtual SourceLocation lastSourceLocation() const = 0; -}; - -class NestedExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(NestedExpression) - - NestedExpression(ExpressionNode *expression) - : expression(expression) - { kind = K; } - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return lparenToken; } - - virtual SourceLocation lastSourceLocation() const - { return rparenToken; } - -// attributes - ExpressionNode *expression; - SourceLocation lparenToken; - SourceLocation rparenToken; -}; - -class ThisExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ThisExpression) - - ThisExpression() { kind = K; } - virtual ~ThisExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return thisToken; } - - virtual SourceLocation lastSourceLocation() const - { return thisToken; } - -// attributes - SourceLocation thisToken; -}; - -class IdentifierExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(IdentifierExpression) - - IdentifierExpression(NameId *n): - name (n) { kind = K; } - - virtual ~IdentifierExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return identifierToken; } - - virtual SourceLocation lastSourceLocation() const - { return identifierToken; } - -// attributes - NameId *name; - SourceLocation identifierToken; -}; - -class NullExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(NullExpression) - - NullExpression() { kind = K; } - virtual ~NullExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return nullToken; } - - virtual SourceLocation lastSourceLocation() const - { return nullToken; } - -// attributes - SourceLocation nullToken; -}; - -class TrueLiteral: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(TrueLiteral) - - TrueLiteral() { kind = K; } - virtual ~TrueLiteral() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return trueToken; } - - virtual SourceLocation lastSourceLocation() const - { return trueToken; } - -// attributes - SourceLocation trueToken; -}; - -class FalseLiteral: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(FalseLiteral) - - FalseLiteral() { kind = K; } - virtual ~FalseLiteral() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return falseToken; } - - virtual SourceLocation lastSourceLocation() const - { return falseToken; } - -// attributes - SourceLocation falseToken; -}; - -class NumericLiteral: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(NumericLiteral) - - enum Suffix { // ### keep it in sync with the Suffix enum in javascriptlexer_p.h - noSuffix, - emSuffix, - exSuffix, - pxSuffix, - cmSuffix, - mmSuffix, - inSuffix, - ptSuffix, - pcSuffix, - degSuffix, - radSuffix, - gradSuffix, - msSuffix, - sSuffix, - hzSuffix, - khzSuffix - }; - - static int suffixLength[]; - static const char *const suffixSpell[]; - - NumericLiteral(double v, int suffix): - value(v), suffix(suffix) { kind = K; } - virtual ~NumericLiteral() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return literalToken; } - - virtual SourceLocation lastSourceLocation() const - { return literalToken; } - -// attributes: - double value; - int suffix; - SourceLocation literalToken; -}; - -class StringLiteral: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(StringLiteral) - - StringLiteral(NameId *v): - value (v) { kind = K; } - - virtual ~StringLiteral() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return literalToken; } - - virtual SourceLocation lastSourceLocation() const - { return literalToken; } - -// attributes: - NameId *value; - SourceLocation literalToken; -}; - -class RegExpLiteral: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(RegExpLiteral) - - RegExpLiteral(NameId *p, int f): - pattern (p), flags (f) { kind = K; } - - virtual ~RegExpLiteral() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return literalToken; } - - virtual SourceLocation lastSourceLocation() const - { return literalToken; } - -// attributes: - NameId *pattern; - int flags; - SourceLocation literalToken; -}; - -class ArrayLiteral: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ArrayLiteral) - - ArrayLiteral(Elision *e): - elements (0), elision (e) - { kind = K; } - - ArrayLiteral(ElementList *elts): - elements (elts), elision (0) - { kind = K; } - - ArrayLiteral(ElementList *elts, Elision *e): - elements (elts), elision (e) - { kind = K; } - - virtual ~ArrayLiteral() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return lbracketToken; } - - virtual SourceLocation lastSourceLocation() const - { return rbracketToken; } - -// attributes - ElementList *elements; - Elision *elision; - SourceLocation lbracketToken; - SourceLocation commaToken; - SourceLocation rbracketToken; -}; - -class ObjectLiteral: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ObjectLiteral) - - ObjectLiteral(): - properties (0) { kind = K; } - - ObjectLiteral(PropertyNameAndValueList *plist): - properties (plist) { kind = K; } - - virtual ~ObjectLiteral() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return lbraceToken; } - - virtual SourceLocation lastSourceLocation() const - { return rbraceToken; } - -// attributes - PropertyNameAndValueList *properties; - SourceLocation lbraceToken; - SourceLocation rbraceToken; -}; - -class ElementList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ElementList) - - ElementList(Elision *e, ExpressionNode *expr): - elision (e), expression (expr), next (this) - { kind = K; } - - ElementList(ElementList *previous, Elision *e, ExpressionNode *expr): - elision (e), expression (expr) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~ElementList() {} - - inline ElementList *finish () - { - ElementList *front = next; - next = 0; - return front; - } - - virtual void accept0(Visitor *visitor); - -// attributes - Elision *elision; - ExpressionNode *expression; - ElementList *next; - SourceLocation commaToken; -}; - -class Elision: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(Elision) - - Elision(): - next (this) { kind = K; } - - Elision(Elision *previous) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~Elision() {} - - virtual void accept0(Visitor *visitor); - - inline Elision *finish () - { - Elision *front = next; - next = 0; - return front; - } - -// attributes - Elision *next; - SourceLocation commaToken; -}; - -class PropertyNameAndValueList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(PropertyNameAndValueList) - - PropertyNameAndValueList(PropertyName *n, ExpressionNode *v): - name (n), value (v), next (this) - { kind = K; } - - PropertyNameAndValueList(PropertyNameAndValueList *previous, PropertyName *n, ExpressionNode *v): - name (n), value (v) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~PropertyNameAndValueList() {} - - virtual void accept0(Visitor *visitor); - - inline PropertyNameAndValueList *finish () - { - PropertyNameAndValueList *front = next; - next = 0; - return front; - } - -// attributes - PropertyName *name; - ExpressionNode *value; - PropertyNameAndValueList *next; - SourceLocation colonToken; - SourceLocation commaToken; -}; - -class PropertyName: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(PropertyName) - - PropertyName() { kind = K; } - virtual ~PropertyName() {} - -// attributes - SourceLocation propertyNameToken; -}; - -class IdentifierPropertyName: public PropertyName -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(IdentifierPropertyName) - - IdentifierPropertyName(NameId *n): - id (n) { kind = K; } - - virtual ~IdentifierPropertyName() {} - - virtual void accept0(Visitor *visitor); - -// attributes - NameId *id; -}; - -class StringLiteralPropertyName: public PropertyName -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(StringLiteralPropertyName) - - StringLiteralPropertyName(NameId *n): - id (n) { kind = K; } - virtual ~StringLiteralPropertyName() {} - - virtual void accept0(Visitor *visitor); - -// attributes - NameId *id; -}; - -class NumericLiteralPropertyName: public PropertyName -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(NumericLiteralPropertyName) - - NumericLiteralPropertyName(double n): - id (n) { kind = K; } - virtual ~NumericLiteralPropertyName() {} - - virtual void accept0(Visitor *visitor); - -// attributes - double id; -}; - -class ArrayMemberExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ArrayMemberExpression) - - ArrayMemberExpression(ExpressionNode *b, ExpressionNode *e): - base (b), expression (e) - { kind = K; } - - virtual ~ArrayMemberExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return base->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return rbracketToken; } - -// attributes - ExpressionNode *base; - ExpressionNode *expression; - SourceLocation lbracketToken; - SourceLocation rbracketToken; -}; - -class FieldMemberExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(FieldMemberExpression) - - FieldMemberExpression(ExpressionNode *b, NameId *n): - base (b), name (n) - { kind = K; } - - virtual ~FieldMemberExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return base->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return identifierToken; } - - // attributes - ExpressionNode *base; - NameId *name; - SourceLocation dotToken; - SourceLocation identifierToken; -}; - -class NewMemberExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(NewMemberExpression) - - NewMemberExpression(ExpressionNode *b, ArgumentList *a): - base (b), arguments (a) - { kind = K; } - - virtual ~NewMemberExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return newToken; } - - virtual SourceLocation lastSourceLocation() const - { return rparenToken; } - - // attributes - ExpressionNode *base; - ArgumentList *arguments; - SourceLocation newToken; - SourceLocation lparenToken; - SourceLocation rparenToken; -}; - -class NewExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(NewExpression) - - NewExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~NewExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return newToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation newToken; -}; - -class CallExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(CallExpression) - - CallExpression(ExpressionNode *b, ArgumentList *a): - base (b), arguments (a) - { kind = K; } - - virtual ~CallExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return base->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return rparenToken; } - -// attributes - ExpressionNode *base; - ArgumentList *arguments; - SourceLocation lparenToken; - SourceLocation rparenToken; -}; - -class ArgumentList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ArgumentList) - - ArgumentList(ExpressionNode *e): - expression (e), next (this) - { kind = K; } - - ArgumentList(ArgumentList *previous, ExpressionNode *e): - expression (e) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~ArgumentList() {} - - virtual void accept0(Visitor *visitor); - - inline ArgumentList *finish () - { - ArgumentList *front = next; - next = 0; - return front; - } - -// attributes - ExpressionNode *expression; - ArgumentList *next; - SourceLocation commaToken; -}; - -class PostIncrementExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(PostIncrementExpression) - - PostIncrementExpression(ExpressionNode *b): - base (b) { kind = K; } - - virtual ~PostIncrementExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return base->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return incrementToken; } - -// attributes - ExpressionNode *base; - SourceLocation incrementToken; -}; - -class PostDecrementExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(PostDecrementExpression) - - PostDecrementExpression(ExpressionNode *b): - base (b) { kind = K; } - - virtual ~PostDecrementExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return base->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return decrementToken; } - -// attributes - ExpressionNode *base; - SourceLocation decrementToken; -}; - -class DeleteExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(DeleteExpression) - - DeleteExpression(ExpressionNode *e): - expression (e) { kind = K; } - virtual ~DeleteExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return deleteToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation deleteToken; -}; - -class VoidExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(VoidExpression) - - VoidExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~VoidExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return voidToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation voidToken; -}; - -class TypeOfExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(TypeOfExpression) - - TypeOfExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~TypeOfExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return typeofToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation typeofToken; -}; - -class PreIncrementExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(PreIncrementExpression) - - PreIncrementExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~PreIncrementExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return incrementToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation incrementToken; -}; - -class PreDecrementExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(PreDecrementExpression) - - PreDecrementExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~PreDecrementExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return decrementToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation decrementToken; -}; - -class UnaryPlusExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UnaryPlusExpression) - - UnaryPlusExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~UnaryPlusExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return plusToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation plusToken; -}; - -class UnaryMinusExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UnaryMinusExpression) - - UnaryMinusExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~UnaryMinusExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return minusToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation minusToken; -}; - -class TildeExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(TildeExpression) - - TildeExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~TildeExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return tildeToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation tildeToken; -}; - -class NotExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(NotExpression) - - NotExpression(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~NotExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return notToken; } - - virtual SourceLocation lastSourceLocation() const - { return expression->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - SourceLocation notToken; -}; - -class BinaryExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(BinaryExpression) - - BinaryExpression(ExpressionNode *l, int o, ExpressionNode *r): - left (l), op (o), right (r) - { kind = K; } - - virtual ~BinaryExpression() {} - - virtual BinaryExpression *binaryExpressionCast(); - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return left->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return right->lastSourceLocation(); } - -// attributes - ExpressionNode *left; - int op; - ExpressionNode *right; - SourceLocation operatorToken; -}; - -class ConditionalExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ConditionalExpression) - - ConditionalExpression(ExpressionNode *e, ExpressionNode *t, ExpressionNode *f): - expression (e), ok (t), ko (f) - { kind = K; } - - virtual ~ConditionalExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return expression->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return ko->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - ExpressionNode *ok; - ExpressionNode *ko; - SourceLocation questionToken; - SourceLocation colonToken; -}; - -class Expression: public ExpressionNode // ### rename -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(Expression) - - Expression(ExpressionNode *l, ExpressionNode *r): - left (l), right (r) { kind = K; } - - virtual ~Expression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return left->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return right->lastSourceLocation(); } - -// attributes - ExpressionNode *left; - ExpressionNode *right; - SourceLocation commaToken; -}; - -class Block: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(Block) - - Block(StatementList *slist): - statements (slist) { kind = K; } - - virtual ~Block() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return lbraceToken; } - - virtual SourceLocation lastSourceLocation() const - { return rbraceToken; } - - // attributes - StatementList *statements; - SourceLocation lbraceToken; - SourceLocation rbraceToken; -}; - -class StatementList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(StatementList) - - StatementList(Statement *stmt): - statement (stmt), next (this) - { kind = K; } - - StatementList(StatementList *previous, Statement *stmt): - statement (stmt) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~StatementList() {} - - virtual void accept0(Visitor *visitor); - - inline StatementList *finish () - { - StatementList *front = next; - next = 0; - return front; - } - -// attributes - Statement *statement; - StatementList *next; -}; - -class VariableStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(VariableStatement) - - VariableStatement(VariableDeclarationList *vlist): - declarations (vlist) - { kind = K; } - - virtual ~VariableStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return declarationKindToken; } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - -// attributes - VariableDeclarationList *declarations; - SourceLocation declarationKindToken; - SourceLocation semicolonToken; -}; - -class VariableDeclaration: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(VariableDeclaration) - - VariableDeclaration(NameId *n, ExpressionNode *e): - name (n), expression (e), readOnly(false) - { kind = K; } - - virtual ~VariableDeclaration() {} - - virtual void accept0(Visitor *visitor); - -// attributes - NameId *name; - ExpressionNode *expression; - bool readOnly; - SourceLocation identifierToken; -}; - -class VariableDeclarationList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(VariableDeclarationList) - - VariableDeclarationList(VariableDeclaration *decl): - declaration (decl), next (this) - { kind = K; } - - VariableDeclarationList(VariableDeclarationList *previous, VariableDeclaration *decl): - declaration (decl) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~VariableDeclarationList() {} - - virtual void accept0(Visitor *visitor); - - inline VariableDeclarationList *finish (bool readOnly) - { - VariableDeclarationList *front = next; - next = 0; - if (readOnly) { - VariableDeclarationList *vdl; - for (vdl = front; vdl != 0; vdl = vdl->next) - vdl->declaration->readOnly = true; - } - return front; - } - -// attributes - VariableDeclaration *declaration; - VariableDeclarationList *next; - SourceLocation commaToken; -}; - -class EmptyStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(EmptyStatement) - - EmptyStatement() { kind = K; } - virtual ~EmptyStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return semicolonToken; } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - -// attributes - SourceLocation semicolonToken; -}; - -class ExpressionStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ExpressionStatement) - - ExpressionStatement(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~ExpressionStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return expression->firstSourceLocation(); } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - -// attributes - ExpressionNode *expression; - SourceLocation semicolonToken; -}; - -class IfStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(IfStatement) - - IfStatement(ExpressionNode *e, Statement *t, Statement *f = 0): - expression (e), ok (t), ko (f) - { kind = K; } - - virtual ~IfStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return ifToken; } - - virtual SourceLocation lastSourceLocation() const - { - if (ko) - return ko->lastSourceLocation(); - - return ok->lastSourceLocation(); - } - -// attributes - ExpressionNode *expression; - Statement *ok; - Statement *ko; - SourceLocation ifToken; - SourceLocation lparenToken; - SourceLocation rparenToken; - SourceLocation elseToken; -}; - -class DoWhileStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(DoWhileStatement) - - DoWhileStatement(Statement *stmt, ExpressionNode *e): - statement (stmt), expression (e) - { kind = K; } - - virtual ~DoWhileStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return doToken; } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - -// attributes - Statement *statement; - ExpressionNode *expression; - SourceLocation doToken; - SourceLocation whileToken; - SourceLocation lparenToken; - SourceLocation rparenToken; - SourceLocation semicolonToken; -}; - -class WhileStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(WhileStatement) - - WhileStatement(ExpressionNode *e, Statement *stmt): - expression (e), statement (stmt) - { kind = K; } - - virtual ~WhileStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return whileToken; } - - virtual SourceLocation lastSourceLocation() const - { return statement->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - Statement *statement; - SourceLocation whileToken; - SourceLocation lparenToken; - SourceLocation rparenToken; -}; - -class ForStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ForStatement) - - ForStatement(ExpressionNode *i, ExpressionNode *c, ExpressionNode *e, Statement *stmt): - initialiser (i), condition (c), expression (e), statement (stmt) - { kind = K; } - - virtual ~ForStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return forToken; } - - virtual SourceLocation lastSourceLocation() const - { return statement->lastSourceLocation(); } - -// attributes - ExpressionNode *initialiser; - ExpressionNode *condition; - ExpressionNode *expression; - Statement *statement; - SourceLocation forToken; - SourceLocation lparenToken; - SourceLocation firstSemicolonToken; - SourceLocation secondSemicolonToken; - SourceLocation rparenToken; -}; - -class LocalForStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(LocalForStatement) - - LocalForStatement(VariableDeclarationList *vlist, ExpressionNode *c, ExpressionNode *e, Statement *stmt): - declarations (vlist), condition (c), expression (e), statement (stmt) - { kind = K; } - - virtual ~LocalForStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return forToken; } - - virtual SourceLocation lastSourceLocation() const - { return statement->lastSourceLocation(); } - -// attributes - VariableDeclarationList *declarations; - ExpressionNode *condition; - ExpressionNode *expression; - Statement *statement; - SourceLocation forToken; - SourceLocation lparenToken; - SourceLocation varToken; - SourceLocation firstSemicolonToken; - SourceLocation secondSemicolonToken; - SourceLocation rparenToken; -}; - -class ForEachStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ForEachStatement) - - ForEachStatement(ExpressionNode *i, ExpressionNode *e, Statement *stmt): - initialiser (i), expression (e), statement (stmt) - { kind = K; } - - virtual ~ForEachStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return forToken; } - - virtual SourceLocation lastSourceLocation() const - { return statement->lastSourceLocation(); } - -// attributes - ExpressionNode *initialiser; - ExpressionNode *expression; - Statement *statement; - SourceLocation forToken; - SourceLocation lparenToken; - SourceLocation inToken; - SourceLocation rparenToken; -}; - -class LocalForEachStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(LocalForEachStatement) - - LocalForEachStatement(VariableDeclaration *v, ExpressionNode *e, Statement *stmt): - declaration (v), expression (e), statement (stmt) - { kind = K; } - - virtual ~LocalForEachStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return forToken; } - - virtual SourceLocation lastSourceLocation() const - { return statement->lastSourceLocation(); } - -// attributes - VariableDeclaration *declaration; - ExpressionNode *expression; - Statement *statement; - SourceLocation forToken; - SourceLocation lparenToken; - SourceLocation varToken; - SourceLocation inToken; - SourceLocation rparenToken; -}; - -class ContinueStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ContinueStatement) - - ContinueStatement(NameId *l = 0): - label (l) { kind = K; } - - virtual ~ContinueStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return continueToken; } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - -// attributes - NameId *label; - SourceLocation continueToken; - SourceLocation identifierToken; - SourceLocation semicolonToken; -}; - -class BreakStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(BreakStatement) - - BreakStatement(NameId *l = 0): - label (l) { kind = K; } - - virtual ~BreakStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return breakToken; } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - - // attributes - NameId *label; - SourceLocation breakToken; - SourceLocation identifierToken; - SourceLocation semicolonToken; -}; - -class ReturnStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ReturnStatement) - - ReturnStatement(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~ReturnStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return returnToken; } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - -// attributes - ExpressionNode *expression; - SourceLocation returnToken; - SourceLocation semicolonToken; -}; - -class WithStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(WithStatement) - - WithStatement(ExpressionNode *e, Statement *stmt): - expression (e), statement (stmt) - { kind = K; } - - virtual ~WithStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return withToken; } - - virtual SourceLocation lastSourceLocation() const - { return statement->lastSourceLocation(); } - -// attributes - ExpressionNode *expression; - Statement *statement; - SourceLocation withToken; - SourceLocation lparenToken; - SourceLocation rparenToken; -}; - -class CaseBlock: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(CaseBlock) - - CaseBlock(CaseClauses *c, DefaultClause *d = 0, CaseClauses *r = 0): - clauses (c), defaultClause (d), moreClauses (r) - { kind = K; } - - virtual ~CaseBlock() {} - - virtual void accept0(Visitor *visitor); - -// attributes - CaseClauses *clauses; - DefaultClause *defaultClause; - CaseClauses *moreClauses; - SourceLocation lbraceToken; - SourceLocation rbraceToken; -}; - -class SwitchStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(SwitchStatement) - - SwitchStatement(ExpressionNode *e, CaseBlock *b): - expression (e), block (b) - { kind = K; } - - virtual ~SwitchStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return switchToken; } - - virtual SourceLocation lastSourceLocation() const - { return block->rbraceToken; } - -// attributes - ExpressionNode *expression; - CaseBlock *block; - SourceLocation switchToken; - SourceLocation lparenToken; - SourceLocation rparenToken; -}; - -class CaseClauses: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(CaseClauses) - - CaseClauses(CaseClause *c): - clause (c), next (this) - { kind = K; } - - CaseClauses(CaseClauses *previous, CaseClause *c): - clause (c) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~CaseClauses() {} - - virtual void accept0(Visitor *visitor); - - inline CaseClauses *finish () - { - CaseClauses *front = next; - next = 0; - return front; - } - -//attributes - CaseClause *clause; - CaseClauses *next; -}; - -class CaseClause: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(CaseClause) - - CaseClause(ExpressionNode *e, StatementList *slist): - expression (e), statements (slist) - { kind = K; } - - virtual ~CaseClause() {} - - virtual void accept0(Visitor *visitor); - -// attributes - ExpressionNode *expression; - StatementList *statements; - SourceLocation caseToken; - SourceLocation colonToken; -}; - -class DefaultClause: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(DefaultClause) - - DefaultClause(StatementList *slist): - statements (slist) - { kind = K; } - - virtual ~DefaultClause() {} - - virtual void accept0(Visitor *visitor); - -// attributes - StatementList *statements; - SourceLocation defaultToken; - SourceLocation colonToken; -}; - -class LabelledStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(LabelledStatement) - - LabelledStatement(NameId *l, Statement *stmt): - label (l), statement (stmt) - { kind = K; } - - virtual ~LabelledStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return identifierToken; } - - virtual SourceLocation lastSourceLocation() const - { return statement->lastSourceLocation(); } - -// attributes - NameId *label; - Statement *statement; - SourceLocation identifierToken; - SourceLocation colonToken; -}; - -class ThrowStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(ThrowStatement) - - ThrowStatement(ExpressionNode *e): - expression (e) { kind = K; } - - virtual ~ThrowStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return throwToken; } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - - // attributes - ExpressionNode *expression; - SourceLocation throwToken; - SourceLocation semicolonToken; -}; - -class Catch: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(Catch) - - Catch(NameId *n, Block *stmt): - name (n), statement (stmt) - { kind = K; } - - virtual ~Catch() {} - - virtual void accept0(Visitor *visitor); - -// attributes - NameId *name; - Block *statement; - SourceLocation catchToken; - SourceLocation lparenToken; - SourceLocation identifierToken; - SourceLocation rparenToken; -}; - -class Finally: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(Finally) - - Finally(Block *stmt): - statement (stmt) - { kind = K; } - - virtual ~Finally() {} - - virtual void accept0(Visitor *visitor); - -// attributes - Block *statement; - SourceLocation finallyToken; -}; - -class TryStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(TryStatement) - - TryStatement(Statement *stmt, Catch *c, Finally *f): - statement (stmt), catchExpression (c), finallyExpression (f) - { kind = K; } - - TryStatement(Statement *stmt, Finally *f): - statement (stmt), catchExpression (0), finallyExpression (f) - { kind = K; } - - TryStatement(Statement *stmt, Catch *c): - statement (stmt), catchExpression (c), finallyExpression (0) - { kind = K; } - - virtual ~TryStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return tryToken; } - - virtual SourceLocation lastSourceLocation() const - { - if (finallyExpression) - return finallyExpression->statement->rbraceToken; - else if (catchExpression) - return catchExpression->statement->rbraceToken; - - return statement->lastSourceLocation(); - } - -// attributes - Statement *statement; - Catch *catchExpression; - Finally *finallyExpression; - SourceLocation tryToken; -}; - -class FunctionExpression: public ExpressionNode -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(FunctionExpression) - - FunctionExpression(NameId *n, FormalParameterList *f, FunctionBody *b): - name (n), formals (f), body (b) - { kind = K; } - - virtual ~FunctionExpression() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return functionToken; } - - virtual SourceLocation lastSourceLocation() const - { return rbraceToken; } - -// attributes - NameId *name; - FormalParameterList *formals; - FunctionBody *body; - SourceLocation functionToken; - SourceLocation identifierToken; - SourceLocation lparenToken; - SourceLocation rparenToken; - SourceLocation lbraceToken; - SourceLocation rbraceToken; -}; - -class FunctionDeclaration: public FunctionExpression -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(FunctionDeclaration) - - FunctionDeclaration(NameId *n, FormalParameterList *f, FunctionBody *b): - FunctionExpression(n, f, b) - { kind = K; } - - virtual ~FunctionDeclaration() {} - - virtual void accept0(Visitor *visitor); -}; - -class FormalParameterList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(FormalParameterList) - - FormalParameterList(NameId *n): - name (n), next (this) - { kind = K; } - - FormalParameterList(FormalParameterList *previous, NameId *n): - name (n) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~FormalParameterList() {} - - virtual void accept0(Visitor *visitor); - - inline FormalParameterList *finish () - { - FormalParameterList *front = next; - next = 0; - return front; - } - -// attributes - NameId *name; - FormalParameterList *next; - SourceLocation commaToken; - SourceLocation identifierToken; -}; - -class FunctionBody: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(FunctionBody) - - FunctionBody(SourceElements *elts): - elements (elts) - { kind = K; } - - virtual ~FunctionBody() {} - - virtual void accept0(Visitor *visitor); - -// attributes - SourceElements *elements; -}; - -class Program: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(Program) - - Program(SourceElements *elts): - elements (elts) - { kind = K; } - - virtual ~Program() {} - - virtual void accept0(Visitor *visitor); - -// attributes - SourceElements *elements; -}; - -class SourceElements: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(SourceElements) - - SourceElements(SourceElement *elt): - element (elt), next (this) - { kind = K; } - - SourceElements(SourceElements *previous, SourceElement *elt): - element (elt) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~SourceElements() {} - - virtual void accept0(Visitor *visitor); - - inline SourceElements *finish () - { - SourceElements *front = next; - next = 0; - return front; - } - -// attributes - SourceElement *element; - SourceElements *next; -}; - -class SourceElement: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(SourceElement) - - inline SourceElement() - { kind = K; } - - virtual ~SourceElement() {} -}; - -class FunctionSourceElement: public SourceElement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(FunctionSourceElement) - - FunctionSourceElement(FunctionDeclaration *f): - declaration (f) - { kind = K; } - - virtual ~FunctionSourceElement() {} - - virtual void accept0(Visitor *visitor); - -// attributes - FunctionDeclaration *declaration; -}; - -class StatementSourceElement: public SourceElement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(StatementSourceElement) - - StatementSourceElement(Statement *stmt): - statement (stmt) - { kind = K; } - - virtual ~StatementSourceElement() {} - - virtual void accept0(Visitor *visitor); - -// attributes - Statement *statement; -}; - -class DebuggerStatement: public Statement -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(DebuggerStatement) - - DebuggerStatement() - { kind = K; } - - virtual ~DebuggerStatement() {} - - virtual void accept0(Visitor *visitor); - - virtual SourceLocation firstSourceLocation() const - { return debuggerToken; } - - virtual SourceLocation lastSourceLocation() const - { return semicolonToken; } - -// attributes - SourceLocation debuggerToken; - SourceLocation semicolonToken; -}; - -class UiProgram: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiProgram) - - UiProgram(UiImportList *imports, UiObjectMemberList *members) - : imports(imports), members(members) - { kind = K; } - - virtual void accept0(Visitor *visitor); - -// attributes - UiImportList *imports; - UiObjectMemberList *members; -}; - -class UiQualifiedId: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiQualifiedId) - - UiQualifiedId(NameId *name) - : next(this), name(name) - { kind = K; } - - UiQualifiedId(UiQualifiedId *previous, NameId *name) - : name(name) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual ~UiQualifiedId() {} - - UiQualifiedId *finish() - { - UiQualifiedId *head = next; - next = 0; - return head; - } - - virtual void accept0(Visitor *visitor); - -// attributes - UiQualifiedId *next; - NameId *name; - SourceLocation identifierToken; -}; - -class UiImport: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiImport) - - UiImport(NameId *fileName) - : fileName(fileName) - { kind = K; } - - virtual void accept0(Visitor *visitor); - -// attributes - NameId *fileName; - SourceLocation importToken; - SourceLocation fileNameToken; - SourceLocation semicolonToken; -}; - -class UiImportList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiImportList) - - UiImportList(UiImport *import) - : import(import), - next(this) - { kind = K; } - - UiImportList(UiImportList *previous, UiImport *import) - : import(import) - { - kind = K; - next = previous->next; - previous->next = this; - } - - UiImportList *finish() - { - UiImportList *head = next; - next = 0; - return head; - } - - virtual void accept0(Visitor *visitor); - -// attributes - UiImport *import; - UiImportList *next; -}; - -class UiObjectMember: public Node -{ -public: - virtual SourceLocation firstSourceLocation() const = 0; - virtual SourceLocation lastSourceLocation() const = 0; -}; - -class UiObjectMemberList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiObjectMemberList) - - UiObjectMemberList(UiObjectMember *member) - : next(this), member(member) - { kind = K; } - - UiObjectMemberList(UiObjectMemberList *previous, UiObjectMember *member) - : member(member) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual void accept0(Visitor *visitor); - - UiObjectMemberList *finish() - { - UiObjectMemberList *head = next; - next = 0; - return head; - } - -// attributes - UiObjectMemberList *next; - UiObjectMember *member; -}; - -class UiArrayMemberList: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiArrayMemberList) - - UiArrayMemberList(UiObjectMember *member) - : next(this), member(member) - { kind = K; } - - UiArrayMemberList(UiArrayMemberList *previous, UiObjectMember *member) - : member(member) - { - kind = K; - next = previous->next; - previous->next = this; - } - - virtual void accept0(Visitor *visitor); - - UiArrayMemberList *finish() - { - UiArrayMemberList *head = next; - next = 0; - return head; - } - -// attributes - UiArrayMemberList *next; - UiObjectMember *member; - SourceLocation commaToken; -}; - -class UiObjectInitializer: public Node -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiObjectInitializer) - - UiObjectInitializer(UiObjectMemberList *members) - : members(members) - { kind = K; } - - virtual void accept0(Visitor *visitor); - -// attributes - SourceLocation lbraceToken; - UiObjectMemberList *members; - SourceLocation rbraceToken; -}; - -class UiPublicMember: public UiObjectMember -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiPublicMember) - - UiPublicMember(NameId *memberType, - NameId *name) - : type(Property), memberType(memberType), name(name), expression(0), isDefaultMember(false) - { kind = K; } - - UiPublicMember(NameId *memberType, - NameId *name, - ExpressionNode *expression) - : type(Property), memberType(memberType), name(name), expression(expression), isDefaultMember(false) - { kind = K; } - - virtual SourceLocation firstSourceLocation() const - { - if (defaultToken.isValid()) - return defaultToken; - - return propertyToken; - } - - virtual SourceLocation lastSourceLocation() const - { - return semicolonToken; - } - - virtual void accept0(Visitor *visitor); - -// attributes - enum { Signal, Property } type; - NameId *memberType; - NameId *name; - ExpressionNode *expression; - bool isDefaultMember; - SourceLocation defaultToken; - SourceLocation propertyToken; - SourceLocation typeToken; - SourceLocation identifierToken; - SourceLocation colonToken; - SourceLocation semicolonToken; -}; - -class UiObjectDefinition: public UiObjectMember -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiObjectDefinition) - - UiObjectDefinition(UiQualifiedId *qualifiedTypeNameId, - UiObjectInitializer *initializer) - : qualifiedTypeNameId(qualifiedTypeNameId), initializer(initializer) - { kind = K; } - - virtual SourceLocation firstSourceLocation() const - { return qualifiedTypeNameId->identifierToken; } - - virtual SourceLocation lastSourceLocation() const - { return initializer->rbraceToken; } - - virtual void accept0(Visitor *visitor); - -// attributes - UiQualifiedId *qualifiedTypeNameId; - UiObjectInitializer *initializer; -}; - -class UiSourceElement: public UiObjectMember -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiSourceElement) - - UiSourceElement(Node *sourceElement) - : sourceElement(sourceElement) - { kind = K; } - - virtual SourceLocation firstSourceLocation() const - { - if (FunctionDeclaration *funDecl = cast(sourceElement)) - return funDecl->firstSourceLocation(); - else if (VariableStatement *varStmt = cast(sourceElement)) - return varStmt->firstSourceLocation(); - - return SourceLocation(); - } - - virtual SourceLocation lastSourceLocation() const - { - if (FunctionDeclaration *funDecl = cast(sourceElement)) - return funDecl->lastSourceLocation(); - else if (VariableStatement *varStmt = cast(sourceElement)) - return varStmt->lastSourceLocation(); - - return SourceLocation(); - } - - - virtual void accept0(Visitor *visitor); - -// attributes - Node *sourceElement; -}; - -class UiObjectBinding: public UiObjectMember -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiObjectBinding) - - UiObjectBinding(UiQualifiedId *qualifiedId, - UiQualifiedId *qualifiedTypeNameId, - UiObjectInitializer *initializer) - : qualifiedId(qualifiedId), - qualifiedTypeNameId(qualifiedTypeNameId), - initializer(initializer) - { kind = K; } - - virtual SourceLocation firstSourceLocation() const - { return qualifiedId->identifierToken; } - - virtual SourceLocation lastSourceLocation() const - { return initializer->rbraceToken; } - - virtual void accept0(Visitor *visitor); - -// attributes - UiQualifiedId *qualifiedId; - UiQualifiedId *qualifiedTypeNameId; - UiObjectInitializer *initializer; - SourceLocation colonToken; -}; - -class UiScriptBinding: public UiObjectMember -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiScriptBinding) - - UiScriptBinding(UiQualifiedId *qualifiedId, - Statement *statement) - : qualifiedId(qualifiedId), - statement(statement) - { kind = K; } - - virtual SourceLocation firstSourceLocation() const - { return qualifiedId->identifierToken; } - - virtual SourceLocation lastSourceLocation() const - { return statement->lastSourceLocation(); } - - virtual void accept0(Visitor *visitor); - -// attributes - UiQualifiedId *qualifiedId; - Statement *statement; - SourceLocation colonToken; -}; - -class UiArrayBinding: public UiObjectMember -{ -public: - JAVASCRIPT_DECLARE_AST_NODE(UiArrayBinding) - - UiArrayBinding(UiQualifiedId *qualifiedId, - UiArrayMemberList *members) - : qualifiedId(qualifiedId), - members(members) - { kind = K; } - - virtual SourceLocation firstSourceLocation() const - { return lbracketToken; } - - virtual SourceLocation lastSourceLocation() const - { return rbracketToken; } - - virtual void accept0(Visitor *visitor); - -// attributes - UiQualifiedId *qualifiedId; - UiArrayMemberList *members; - SourceLocation colonToken; - SourceLocation lbracketToken; - SourceLocation rbracketToken; -}; - -} } // namespace AST - - - -QT_END_NAMESPACE - -#endif diff --git a/src/declarative/qml/parser/javascriptastfwd_p.h b/src/declarative/qml/parser/javascriptastfwd_p.h deleted file mode 100644 index 23270e5..0000000 --- a/src/declarative/qml/parser/javascriptastfwd_p.h +++ /dev/null @@ -1,184 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JAVASCRIPTAST_FWD_P_H -#define JAVASCRIPTAST_FWD_P_H - -#include - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -QT_BEGIN_NAMESPACE - -namespace JavaScript { namespace AST { - -class SourceLocation -{ -public: - SourceLocation(quint32 offset = 0, quint32 length = 0) - : offset(offset), length(length), - startLine(0), startColumn(0) - { } - - bool isValid() const { return length != 0; } - - quint32 begin() const { return offset; } - quint32 end() const { return offset + length; } - -// attributes - // ### encode - quint32 offset; - quint32 length; - quint32 startLine; - quint32 startColumn; -}; - -class Visitor; -class Node; -class ExpressionNode; -class Statement; -class ThisExpression; -class IdentifierExpression; -class NullExpression; -class TrueLiteral; -class FalseLiteral; -class NumericLiteral; -class StringLiteral; -class RegExpLiteral; -class ArrayLiteral; -class ObjectLiteral; -class ElementList; -class Elision; -class PropertyNameAndValueList; -class PropertyName; -class IdentifierPropertyName; -class StringLiteralPropertyName; -class NumericLiteralPropertyName; -class ArrayMemberExpression; -class FieldMemberExpression; -class NewMemberExpression; -class NewExpression; -class CallExpression; -class ArgumentList; -class PostIncrementExpression; -class PostDecrementExpression; -class DeleteExpression; -class VoidExpression; -class TypeOfExpression; -class PreIncrementExpression; -class PreDecrementExpression; -class UnaryPlusExpression; -class UnaryMinusExpression; -class TildeExpression; -class NotExpression; -class BinaryExpression; -class ConditionalExpression; -class Expression; // ### rename -class Block; -class StatementList; -class VariableStatement; -class VariableDeclarationList; -class VariableDeclaration; -class EmptyStatement; -class ExpressionStatement; -class IfStatement; -class DoWhileStatement; -class WhileStatement; -class ForStatement; -class LocalForStatement; -class ForEachStatement; -class LocalForEachStatement; -class ContinueStatement; -class BreakStatement; -class ReturnStatement; -class WithStatement; -class SwitchStatement; -class CaseBlock; -class CaseClauses; -class CaseClause; -class DefaultClause; -class LabelledStatement; -class ThrowStatement; -class TryStatement; -class Catch; -class Finally; -class FunctionDeclaration; -class FunctionExpression; -class FormalParameterList; -class FunctionBody; -class Program; -class SourceElements; -class SourceElement; -class FunctionSourceElement; -class StatementSourceElement; -class DebuggerStatement; -class NestedExpression; - -// ui elements -class UiProgram; -class UiImportList; -class UiImport; -class UiPublicMember; -class UiObjectDefinition; -class UiObjectInitializer; -class UiObjectBinding; -class UiScriptBinding; -class UiSourceElement; -class UiArrayBinding; -class UiObjectMember; -class UiObjectMemberList; -class UiArrayMemberList; -class UiQualifiedId; - -} } // namespace AST - -QT_END_NAMESPACE - -#endif diff --git a/src/declarative/qml/parser/javascriptastvisitor.cpp b/src/declarative/qml/parser/javascriptastvisitor.cpp deleted file mode 100644 index eac291d..0000000 --- a/src/declarative/qml/parser/javascriptastvisitor.cpp +++ /dev/null @@ -1,58 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "javascriptastvisitor_p.h" - -QT_BEGIN_NAMESPACE - -namespace JavaScript { namespace AST { - -Visitor::Visitor() -{ -} - -Visitor::~Visitor() -{ -} - -} } // namespace JavaScript::AST - -QT_END_NAMESPACE diff --git a/src/declarative/qml/parser/javascriptastvisitor_p.h b/src/declarative/qml/parser/javascriptastvisitor_p.h deleted file mode 100644 index 7c73e43..0000000 --- a/src/declarative/qml/parser/javascriptastvisitor_p.h +++ /dev/null @@ -1,328 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JAVASCRIPTASTVISITOR_P_H -#define JAVASCRIPTASTVISITOR_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include "javascriptastfwd_p.h" - -QT_BEGIN_NAMESPACE - -namespace JavaScript { namespace AST { - -class Visitor -{ -public: - Visitor(); - virtual ~Visitor(); - - virtual bool preVisit(Node *) { return true; } - virtual void postVisit(Node *) {} - - // Ui - virtual bool visit(UiProgram *) { return true; } - virtual bool visit(UiImportList *) { return true; } - virtual bool visit(UiImport *) { return true; } - virtual bool visit(UiPublicMember *) { return true; } - virtual bool visit(UiSourceElement *) { return true; } - virtual bool visit(UiObjectDefinition *) { return true; } - virtual bool visit(UiObjectInitializer *) { return true; } - virtual bool visit(UiObjectBinding *) { return true; } - virtual bool visit(UiScriptBinding *) { return true; } - virtual bool visit(UiArrayBinding *) { return true; } - virtual bool visit(UiObjectMemberList *) { return true; } - virtual bool visit(UiArrayMemberList *) { return true; } - virtual bool visit(UiQualifiedId *) { return true; } - - virtual void endVisit(UiProgram *) {} - virtual void endVisit(UiImportList *) {} - virtual void endVisit(UiImport *) {} - virtual void endVisit(UiPublicMember *) {} - virtual void endVisit(UiSourceElement *) {} - virtual void endVisit(UiObjectDefinition *) {} - virtual void endVisit(UiObjectInitializer *) {} - virtual void endVisit(UiObjectBinding *) {} - virtual void endVisit(UiScriptBinding *) {} - virtual void endVisit(UiArrayBinding *) {} - virtual void endVisit(UiObjectMemberList *) {} - virtual void endVisit(UiArrayMemberList *) {} - virtual void endVisit(UiQualifiedId *) {} - - // JavaScript - virtual bool visit(ThisExpression *) { return true; } - virtual void endVisit(ThisExpression *) {} - - virtual bool visit(IdentifierExpression *) { return true; } - virtual void endVisit(IdentifierExpression *) {} - - virtual bool visit(NullExpression *) { return true; } - virtual void endVisit(NullExpression *) {} - - virtual bool visit(TrueLiteral *) { return true; } - virtual void endVisit(TrueLiteral *) {} - - virtual bool visit(FalseLiteral *) { return true; } - virtual void endVisit(FalseLiteral *) {} - - virtual bool visit(StringLiteral *) { return true; } - virtual void endVisit(StringLiteral *) {} - - virtual bool visit(NumericLiteral *) { return true; } - virtual void endVisit(NumericLiteral *) {} - - virtual bool visit(RegExpLiteral *) { return true; } - virtual void endVisit(RegExpLiteral *) {} - - virtual bool visit(ArrayLiteral *) { return true; } - virtual void endVisit(ArrayLiteral *) {} - - virtual bool visit(ObjectLiteral *) { return true; } - virtual void endVisit(ObjectLiteral *) {} - - virtual bool visit(ElementList *) { return true; } - virtual void endVisit(ElementList *) {} - - virtual bool visit(Elision *) { return true; } - virtual void endVisit(Elision *) {} - - virtual bool visit(PropertyNameAndValueList *) { return true; } - virtual void endVisit(PropertyNameAndValueList *) {} - - virtual bool visit(NestedExpression *) { return true; } - virtual void endVisit(NestedExpression *) {} - - virtual bool visit(IdentifierPropertyName *) { return true; } - virtual void endVisit(IdentifierPropertyName *) {} - - virtual bool visit(StringLiteralPropertyName *) { return true; } - virtual void endVisit(StringLiteralPropertyName *) {} - - virtual bool visit(NumericLiteralPropertyName *) { return true; } - virtual void endVisit(NumericLiteralPropertyName *) {} - - virtual bool visit(ArrayMemberExpression *) { return true; } - virtual void endVisit(ArrayMemberExpression *) {} - - virtual bool visit(FieldMemberExpression *) { return true; } - virtual void endVisit(FieldMemberExpression *) {} - - virtual bool visit(NewMemberExpression *) { return true; } - virtual void endVisit(NewMemberExpression *) {} - - virtual bool visit(NewExpression *) { return true; } - virtual void endVisit(NewExpression *) {} - - virtual bool visit(CallExpression *) { return true; } - virtual void endVisit(CallExpression *) {} - - virtual bool visit(ArgumentList *) { return true; } - virtual void endVisit(ArgumentList *) {} - - virtual bool visit(PostIncrementExpression *) { return true; } - virtual void endVisit(PostIncrementExpression *) {} - - virtual bool visit(PostDecrementExpression *) { return true; } - virtual void endVisit(PostDecrementExpression *) {} - - virtual bool visit(DeleteExpression *) { return true; } - virtual void endVisit(DeleteExpression *) {} - - virtual bool visit(VoidExpression *) { return true; } - virtual void endVisit(VoidExpression *) {} - - virtual bool visit(TypeOfExpression *) { return true; } - virtual void endVisit(TypeOfExpression *) {} - - virtual bool visit(PreIncrementExpression *) { return true; } - virtual void endVisit(PreIncrementExpression *) {} - - virtual bool visit(PreDecrementExpression *) { return true; } - virtual void endVisit(PreDecrementExpression *) {} - - virtual bool visit(UnaryPlusExpression *) { return true; } - virtual void endVisit(UnaryPlusExpression *) {} - - virtual bool visit(UnaryMinusExpression *) { return true; } - virtual void endVisit(UnaryMinusExpression *) {} - - virtual bool visit(TildeExpression *) { return true; } - virtual void endVisit(TildeExpression *) {} - - virtual bool visit(NotExpression *) { return true; } - virtual void endVisit(NotExpression *) {} - - virtual bool visit(BinaryExpression *) { return true; } - virtual void endVisit(BinaryExpression *) {} - - virtual bool visit(ConditionalExpression *) { return true; } - virtual void endVisit(ConditionalExpression *) {} - - virtual bool visit(Expression *) { return true; } - virtual void endVisit(Expression *) {} - - virtual bool visit(Block *) { return true; } - virtual void endVisit(Block *) {} - - virtual bool visit(StatementList *) { return true; } - virtual void endVisit(StatementList *) {} - - virtual bool visit(VariableStatement *) { return true; } - virtual void endVisit(VariableStatement *) {} - - virtual bool visit(VariableDeclarationList *) { return true; } - virtual void endVisit(VariableDeclarationList *) {} - - virtual bool visit(VariableDeclaration *) { return true; } - virtual void endVisit(VariableDeclaration *) {} - - virtual bool visit(EmptyStatement *) { return true; } - virtual void endVisit(EmptyStatement *) {} - - virtual bool visit(ExpressionStatement *) { return true; } - virtual void endVisit(ExpressionStatement *) {} - - virtual bool visit(IfStatement *) { return true; } - virtual void endVisit(IfStatement *) {} - - virtual bool visit(DoWhileStatement *) { return true; } - virtual void endVisit(DoWhileStatement *) {} - - virtual bool visit(WhileStatement *) { return true; } - virtual void endVisit(WhileStatement *) {} - - virtual bool visit(ForStatement *) { return true; } - virtual void endVisit(ForStatement *) {} - - virtual bool visit(LocalForStatement *) { return true; } - virtual void endVisit(LocalForStatement *) {} - - virtual bool visit(ForEachStatement *) { return true; } - virtual void endVisit(ForEachStatement *) {} - - virtual bool visit(LocalForEachStatement *) { return true; } - virtual void endVisit(LocalForEachStatement *) {} - - virtual bool visit(ContinueStatement *) { return true; } - virtual void endVisit(ContinueStatement *) {} - - virtual bool visit(BreakStatement *) { return true; } - virtual void endVisit(BreakStatement *) {} - - virtual bool visit(ReturnStatement *) { return true; } - virtual void endVisit(ReturnStatement *) {} - - virtual bool visit(WithStatement *) { return true; } - virtual void endVisit(WithStatement *) {} - - virtual bool visit(SwitchStatement *) { return true; } - virtual void endVisit(SwitchStatement *) {} - - virtual bool visit(CaseBlock *) { return true; } - virtual void endVisit(CaseBlock *) {} - - virtual bool visit(CaseClauses *) { return true; } - virtual void endVisit(CaseClauses *) {} - - virtual bool visit(CaseClause *) { return true; } - virtual void endVisit(CaseClause *) {} - - virtual bool visit(DefaultClause *) { return true; } - virtual void endVisit(DefaultClause *) {} - - virtual bool visit(LabelledStatement *) { return true; } - virtual void endVisit(LabelledStatement *) {} - - virtual bool visit(ThrowStatement *) { return true; } - virtual void endVisit(ThrowStatement *) {} - - virtual bool visit(TryStatement *) { return true; } - virtual void endVisit(TryStatement *) {} - - virtual bool visit(Catch *) { return true; } - virtual void endVisit(Catch *) {} - - virtual bool visit(Finally *) { return true; } - virtual void endVisit(Finally *) {} - - virtual bool visit(FunctionDeclaration *) { return true; } - virtual void endVisit(FunctionDeclaration *) {} - - virtual bool visit(FunctionExpression *) { return true; } - virtual void endVisit(FunctionExpression *) {} - - virtual bool visit(FormalParameterList *) { return true; } - virtual void endVisit(FormalParameterList *) {} - - virtual bool visit(FunctionBody *) { return true; } - virtual void endVisit(FunctionBody *) {} - - virtual bool visit(Program *) { return true; } - virtual void endVisit(Program *) {} - - virtual bool visit(SourceElements *) { return true; } - virtual void endVisit(SourceElements *) {} - - virtual bool visit(FunctionSourceElement *) { return true; } - virtual void endVisit(FunctionSourceElement *) {} - - virtual bool visit(StatementSourceElement *) { return true; } - virtual void endVisit(StatementSourceElement *) {} - - virtual bool visit(DebuggerStatement *) { return true; } - virtual void endVisit(DebuggerStatement *) {} -}; - -} } // namespace AST - -QT_END_NAMESPACE - -#endif // JAVASCRIPTASTVISITOR_P_H diff --git a/src/declarative/qml/parser/javascriptengine_p.cpp b/src/declarative/qml/parser/javascriptengine_p.cpp deleted file mode 100644 index d893a90..0000000 --- a/src/declarative/qml/parser/javascriptengine_p.cpp +++ /dev/null @@ -1,191 +0,0 @@ -/************************************************************************** -** -** This file is part of Qt Creator -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** -** Contact: Qt Software Information (qt-info@nokia.com) -** -** Commercial Usage -** -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Commercial License Agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** -** Alternatively, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** -**************************************************************************/ - -#include "javascriptengine_p.h" -#include "javascriptnodepool_p.h" -#include -#include - -QT_BEGIN_NAMESPACE - -namespace JavaScript { - -uint qHash(const JavaScript::NameId &id) -{ return qHash(id.asString()); } - -QString numberToString(double value) -{ return QString::number(value); } - -int Ecma::RegExp::flagFromChar(const QChar &ch) -{ - static QHash flagsHash; - if (flagsHash.isEmpty()) { - flagsHash[QLatin1Char('g')] = Global; - flagsHash[QLatin1Char('i')] = IgnoreCase; - flagsHash[QLatin1Char('m')] = Multiline; - } - QHash::const_iterator it; - it = flagsHash.constFind(ch); - if (it == flagsHash.constEnd()) - return 0; - return it.value(); -} - -QString Ecma::RegExp::flagsToString(int flags) -{ - QString result; - if (flags & Global) - result += QLatin1Char('g'); - if (flags & IgnoreCase) - result += QLatin1Char('i'); - if (flags & Multiline) - result += QLatin1Char('m'); - return result; -} - -NodePool::NodePool(const QString &fileName, Engine *engine) - : m_fileName(fileName), m_engine(engine) -{ - m_engine->setNodePool(this); -} - -NodePool::~NodePool() -{ -} - -Code *NodePool::createCompiledCode(AST::Node *, CompilationUnit &) -{ - Q_ASSERT(0); - return 0; -} - -static int toDigit(char c) -{ - if ((c >= '0') && (c <= '9')) - return c - '0'; - else if ((c >= 'a') && (c <= 'z')) - return 10 + c - 'a'; - else if ((c >= 'A') && (c <= 'Z')) - return 10 + c - 'A'; - return -1; -} - -double integerFromString(const char *buf, int size, int radix) -{ - if (size == 0) - return qSNaN(); - - double sign = 1.0; - int i = 0; - if (buf[0] == '+') { - ++i; - } else if (buf[0] == '-') { - sign = -1.0; - ++i; - } - - if (((size-i) >= 2) && (buf[i] == '0')) { - if (((buf[i+1] == 'x') || (buf[i+1] == 'X')) - && (radix < 34)) { - if ((radix != 0) && (radix != 16)) - return 0; - radix = 16; - i += 2; - } else { - if (radix == 0) { - radix = 8; - ++i; - } - } - } else if (radix == 0) { - radix = 10; - } - - int j = i; - for ( ; i < size; ++i) { - int d = toDigit(buf[i]); - if ((d == -1) || (d >= radix)) - break; - } - double result; - if (j == i) { - if (!qstrcmp(buf, "Infinity")) - result = qInf(); - else - result = qSNaN(); - } else { - result = 0; - double multiplier = 1; - for (--i ; i >= j; --i, multiplier *= radix) - result += toDigit(buf[i]) * multiplier; - } - result *= sign; - return result; -} - -double integerFromString(const QString &str, int radix) -{ - QByteArray ba = str.trimmed().toUtf8(); - return integerFromString(ba.constData(), ba.size(), radix); -} - - -Engine::Engine() - : _lexer(0), _nodePool(0) -{ } - -Engine::~Engine() -{ } - -QSet Engine::literals() const -{ return _literals; } - -NameId *Engine::intern(const QChar *u, int s) -{ return const_cast(&*_literals.insert(NameId(u, s))); } - -QString Engine::toString(NameId *id) -{ return id->asString(); } - -Lexer *Engine::lexer() const -{ return _lexer; } - -void Engine::setLexer(Lexer *lexer) -{ _lexer = lexer; } - -NodePool *Engine::nodePool() const -{ return _nodePool; } - -void Engine::setNodePool(NodePool *nodePool) -{ _nodePool = nodePool; } - - - -} // end of namespace JavaScript - -QT_END_NAMESPACE diff --git a/src/declarative/qml/parser/javascriptengine_p.h b/src/declarative/qml/parser/javascriptengine_p.h deleted file mode 100644 index 3bd924a..0000000 --- a/src/declarative/qml/parser/javascriptengine_p.h +++ /dev/null @@ -1,145 +0,0 @@ -/************************************************************************** -** -** This file is part of Qt Creator -** -** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). -** -** Contact: Qt Software Information (qt-info@nokia.com) -** -** Commercial Usage -** -** Licensees holding valid Qt Commercial licenses may use this file in -** accordance with the Qt Commercial License Agreement provided with the -** Software or, alternatively, in accordance with the terms contained in -** a written agreement between you and Nokia. -** -** GNU Lesser General Public License Usage -** -** Alternatively, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** -**************************************************************************/ - -#ifndef JAVASCRIPTENGINE_P_H -#define JAVASCRIPTENGINE_P_H - -#include -#include - -#include "javascriptastfwd_p.h" - -QT_BEGIN_NAMESPACE - -namespace JavaScript { -class NameId -{ - QString _text; - -public: - NameId(const QChar *u, int s) - : _text(u, s) - { } - - const QString asString() const - { return _text; } - - bool operator == (const NameId &other) const - { return _text == other._text; } - - bool operator != (const NameId &other) const - { return _text != other._text; } - - bool operator < (const NameId &other) const - { return _text < other._text; } -}; - -uint qHash(const JavaScript::NameId &id); - -} // end of namespace JavaScript - -#if defined(Q_CC_MSVC) && _MSC_VER <= 1300 -//this ensures that code outside JavaScript can use the hash function -//it also a workaround for some compilers -inline uint qHash(const JavaScript::NameId &nameId) { return JavaScript::qHash(nameId); } -#endif - -namespace JavaScript { - -class Lexer; -class NodePool; - -namespace Ecma { - -class RegExp -{ -public: - enum RegExpFlag { - Global = 0x01, - IgnoreCase = 0x02, - Multiline = 0x04 - }; - -public: - static int flagFromChar(const QChar &); - static QString flagsToString(int flags); -}; - -} // end of namespace Ecma - -class DiagnosticMessage -{ -public: - enum Kind { Warning, Error }; - - DiagnosticMessage() - : kind(Error) {} - - DiagnosticMessage(Kind kind, const AST::SourceLocation &loc, const QString &message) - : kind(kind), loc(loc), message(message) {} - - bool isWarning() const - { return kind == Warning; } - - bool isError() const - { return kind == Error; } - - Kind kind; - AST::SourceLocation loc; - QString message; -}; - -class Engine -{ - Lexer *_lexer; - NodePool *_nodePool; - QSet _literals; - -public: - Engine(); - ~Engine(); - - QSet literals() const; - - NameId *intern(const QChar *u, int s); - - static QString toString(NameId *id); - - Lexer *lexer() const; - void setLexer(Lexer *lexer); - - NodePool *nodePool() const; - void setNodePool(NodePool *nodePool); -}; - -} // end of namespace JavaScript - -QT_END_NAMESPACE - -#endif // JAVASCRIPTENGINE_P_H diff --git a/src/declarative/qml/parser/javascriptgrammar.cpp b/src/declarative/qml/parser/javascriptgrammar.cpp deleted file mode 100644 index a879bfe..0000000 --- a/src/declarative/qml/parser/javascriptgrammar.cpp +++ /dev/null @@ -1,829 +0,0 @@ -// This file was generated by qlalr - DO NOT EDIT! -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "javascriptgrammar_p.h" - -const char *const JavaScriptGrammar::spell [] = { - "end of file", "&", "&&", "&=", "break", "case", "catch", ":", ";", "continue", - "default", "delete", "/", "/=", "do", ".", "else", "=", "==", "===", - "finally", "for", "function", ">=", ">", ">>", ">>=", ">>>", ">>>=", "identifier", - "if", "in", "instanceof", "{", "[", "<=", "(", "<", "<<", "<<=", - "-", "-=", "--", "new", "!", "!=", "!==", "numeric literal", "|", "|=", - "||", "+", "+=", "++", "?", "}", "]", "%", "%=", "return", - ")", ";", 0, "*", "*=", "string literal", "property", "signal", "switch", "this", - "throw", "~", "try", "typeof", "var", "void", "while", "with", "^", "^=", - "null", "true", "false", "const", "debugger", "reserved word", "multiline string literal", "public", "import", 0, - 0}; - -const int JavaScriptGrammar::lhs [] = { - 91, 92, 92, 95, 95, 96, 96, 94, 93, 98, - 98, 100, 100, 101, 101, 97, 99, 99, 103, 104, - 104, 99, 99, 99, 99, 99, 99, 99, 111, 111, - 111, 99, 99, 99, 99, 99, 99, 99, 99, 99, - 99, 99, 102, 102, 114, 114, 114, 115, 115, 115, - 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, - 115, 115, 115, 115, 102, 102, 117, 117, 117, 117, - 116, 116, 119, 119, 121, 121, 121, 121, 121, 121, - 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, - 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, - 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, - 122, 123, 123, 124, 124, 124, 124, 124, 127, 127, - 128, 128, 128, 128, 126, 126, 129, 129, 130, 130, - 131, 131, 131, 132, 132, 132, 132, 132, 132, 132, - 132, 132, 132, 133, 133, 133, 133, 134, 134, 134, - 135, 135, 135, 135, 136, 136, 136, 136, 136, 136, - 136, 137, 137, 137, 137, 137, 137, 138, 138, 138, - 138, 138, 139, 139, 139, 139, 139, 140, 140, 141, - 141, 142, 142, 143, 143, 144, 144, 145, 145, 146, - 146, 147, 147, 148, 148, 149, 149, 150, 150, 151, - 151, 120, 120, 152, 152, 153, 153, 153, 153, 153, - 153, 153, 153, 153, 153, 153, 153, 105, 105, 154, - 154, 155, 155, 156, 156, 157, 157, 157, 157, 157, - 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, - 106, 168, 168, 167, 167, 113, 113, 169, 169, 170, - 170, 172, 172, 171, 173, 176, 174, 174, 177, 175, - 175, 107, 108, 108, 110, 110, 158, 158, 158, 158, - 158, 158, 158, 159, 159, 159, 159, 160, 160, 160, - 160, 161, 161, 162, 164, 178, 178, 181, 181, 179, - 179, 182, 180, 163, 163, 163, 165, 165, 166, 166, - 166, 183, 184, 109, 109, 112, 125, 188, 188, 185, - 185, 186, 186, 189, 190, 190, 191, 191, 187, 187, - 118, 118, 192}; - -const int JavaScriptGrammar:: rhs[] = { - 2, 1, 1, 1, 2, 3, 3, 0, 1, 1, - 2, 1, 3, 2, 3, 2, 1, 5, 1, 2, - 2, 4, 3, 3, 3, 3, 3, 3, 1, 1, - 1, 2, 4, 4, 5, 5, 6, 6, 7, 7, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 2, 3, 3, 4, - 5, 3, 4, 3, 1, 3, 1, 2, 3, 4, - 1, 2, 3, 5, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 4, 3, 5, 1, 2, - 4, 4, 4, 3, 0, 1, 1, 3, 1, 1, - 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, - 2, 2, 2, 1, 3, 3, 3, 1, 3, 3, - 1, 3, 3, 3, 1, 3, 3, 3, 3, 3, - 3, 1, 3, 3, 3, 3, 3, 1, 3, 3, - 3, 3, 1, 3, 3, 3, 3, 1, 3, 1, - 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, - 3, 1, 3, 1, 3, 1, 3, 1, 5, 1, - 5, 1, 3, 1, 3, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 3, 0, - 1, 1, 3, 0, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 3, 1, 2, 0, 1, 3, 3, 1, 1, 1, - 3, 1, 3, 2, 2, 2, 0, 1, 2, 0, - 1, 1, 2, 2, 7, 5, 7, 7, 5, 9, - 10, 7, 8, 2, 2, 3, 3, 2, 2, 3, - 3, 3, 3, 5, 5, 3, 5, 1, 2, 0, - 1, 4, 3, 3, 3, 3, 3, 3, 3, 3, - 4, 5, 2, 2, 2, 8, 8, 1, 3, 0, - 1, 0, 1, 1, 1, 2, 1, 1, 0, 1, - 0, 1, 2}; - -const int JavaScriptGrammar::action_default [] = { - 8, 2, 0, 4, 3, 0, 0, 0, 6, 7, - 5, 65, 45, 46, 43, 44, 47, 9, 0, 1, - 0, 0, 16, 66, 41, 248, 0, 0, 46, 14, - 47, 249, 17, 10, 0, 0, 0, 42, 0, 31, - 30, 29, 0, 0, 35, 0, 36, 151, 218, 182, - 190, 186, 130, 202, 178, 0, 115, 49, 131, 194, - 198, 119, 148, 129, 134, 114, 168, 155, 0, 55, - 56, 52, 319, 321, 0, 0, 0, 0, 0, 0, - 50, 53, 0, 0, 54, 48, 0, 51, 0, 0, - 144, 0, 0, 131, 150, 133, 132, 0, 0, 0, - 146, 147, 145, 149, 0, 179, 0, 0, 0, 0, - 169, 0, 0, 0, 0, 0, 0, 159, 0, 0, - 0, 153, 154, 152, 157, 161, 160, 158, 156, 171, - 170, 172, 0, 187, 0, 183, 0, 0, 125, 112, - 124, 113, 81, 82, 83, 108, 84, 109, 85, 86, - 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, - 97, 110, 98, 99, 100, 101, 102, 103, 104, 105, - 106, 107, 111, 0, 0, 123, 219, 126, 0, 127, - 0, 128, 122, 39, 40, 0, 215, 208, 206, 213, - 214, 212, 211, 217, 210, 209, 207, 216, 203, 0, - 191, 0, 0, 195, 0, 0, 199, 0, 0, 125, - 117, 0, 116, 0, 121, 135, 0, 320, 310, 311, - 0, 308, 0, 309, 0, 312, 226, 233, 232, 240, - 228, 0, 229, 313, 0, 318, 230, 231, 236, 234, - 315, 314, 317, 237, 0, 0, 0, 0, 0, 319, - 45, 0, 321, 46, 220, 262, 47, 0, 0, 0, - 0, 0, 238, 239, 227, 235, 263, 264, 307, 316, - 0, 278, 279, 280, 281, 0, 274, 275, 276, 277, - 304, 305, 0, 0, 0, 0, 0, 267, 268, 224, - 222, 184, 192, 188, 204, 180, 225, 0, 131, 196, - 200, 173, 162, 0, 0, 181, 0, 0, 0, 0, - 174, 0, 0, 0, 0, 0, 166, 164, 167, 165, - 163, 176, 175, 177, 0, 189, 0, 185, 0, 223, - 131, 0, 205, 220, 221, 0, 220, 0, 0, 270, - 0, 0, 0, 272, 0, 193, 0, 0, 197, 0, - 0, 201, 260, 0, 252, 261, 255, 0, 259, 0, - 220, 253, 0, 220, 0, 0, 271, 0, 0, 0, - 273, 320, 310, 0, 0, 312, 0, 306, 0, 296, - 0, 0, 0, 266, 0, 265, 0, 322, 0, 80, - 242, 245, 0, 81, 248, 84, 109, 86, 87, 52, - 91, 92, 45, 93, 96, 50, 53, 46, 220, 47, - 54, 99, 48, 101, 51, 103, 104, 249, 106, 107, - 111, 0, 73, 0, 0, 75, 79, 77, 63, 76, - 78, 0, 74, 62, 243, 241, 119, 120, 125, 0, - 118, 0, 295, 0, 282, 283, 0, 294, 0, 0, - 0, 285, 290, 288, 291, 0, 0, 289, 290, 0, - 286, 0, 287, 244, 293, 0, 244, 292, 0, 297, - 298, 0, 244, 299, 300, 0, 0, 301, 0, 0, - 0, 302, 303, 137, 136, 0, 0, 0, 269, 0, - 0, 0, 284, 67, 0, 0, 71, 57, 0, 59, - 69, 0, 60, 70, 72, 61, 68, 58, 0, 64, - 141, 139, 143, 140, 138, 142, 0, 0, 0, 33, - 0, 34, 0, 37, 38, 32, 15, 11, 0, 23, - 26, 24, 0, 25, 28, 244, 0, 19, 0, 27, - 22, 81, 248, 84, 109, 86, 87, 52, 91, 92, - 45, 93, 96, 50, 53, 46, 220, 47, 54, 99, - 48, 101, 51, 103, 104, 249, 106, 107, 111, 49, - 0, 12, 0, 18, 13, 20, 21, 257, 250, 0, - 258, 254, 0, 256, 246, 0, 247, 251, 323}; - -const int JavaScriptGrammar::goto_default [] = { - 6, 5, 19, 1, 4, 3, 32, 34, 33, 570, - 22, 18, 538, 539, 231, 226, 230, 232, 229, 236, - 517, 235, 264, 57, 65, 495, 494, 388, 387, 48, - 386, 389, 140, 61, 56, 178, 63, 52, 177, 58, - 64, 90, 62, 47, 67, 66, 301, 54, 295, 49, - 291, 51, 293, 50, 292, 59, 299, 60, 300, 53, - 294, 290, 331, 443, 296, 297, 390, 237, 228, 227, - 239, 265, 238, 243, 262, 263, 392, 391, 36, 579, - 578, 353, 354, 581, 356, 580, 355, 451, 455, 458, - 454, 453, 473, 474, 220, 234, 216, 219, 233, 241, - 240, 0}; - -const int JavaScriptGrammar::action_index [] = { - 8, -91, 14, -91, -15, 296, 67, 94, -91, -91, - -91, -91, -91, -91, -91, -91, -91, -91, 109, -91, - 184, 408, -91, -91, -91, -91, 45, 125, 170, -91, - 46, -91, -91, -91, 429, 171, 130, -91, 120, -91, - -91, -91, -19, 169, -91, 733, -91, 72, -91, 22, - -26, -59, 173, -91, 278, 174, -91, -91, 574, 51, - 112, 183, 177, -91, -91, -91, 412, 214, 733, -91, - -91, -91, 161, 1566, 980, 733, 733, 733, 653, 733, - -91, -91, 733, 733, -91, -91, 733, -91, 733, 733, - -91, 733, 733, 98, 235, -91, -91, 733, 733, 733, - -91, -91, -91, 230, 733, 276, 733, 733, 733, 733, - 396, 733, 733, 733, 733, 733, 733, 288, 733, 733, - 733, 88, 87, 74, 288, 288, 288, 218, 221, 486, - 372, 362, 733, 4, 733, 76, 1479, 733, 733, -91, - -91, -91, -91, -91, -91, -91, -91, -91, -91, -91, - -91, -91, -91, -91, -91, -91, -91, -91, -91, -91, - -91, -91, -91, -91, -91, -91, -91, -91, -91, -91, - -91, -91, -91, 102, 733, -91, -91, 60, 3, -91, - 733, -91, -91, -91, -91, 733, -91, -91, -91, -91, - -91, -91, -91, -91, -91, -91, -91, -91, -91, 733, - -6, 733, 733, 30, 32, 733, -91, 1479, 733, 733, - -91, 107, -91, -14, -91, -91, 69, -91, 191, 49, - 18, -91, 233, -91, 47, 1827, -91, -91, -91, -91, - -91, 204, -91, -91, 39, -91, -91, -91, -91, -91, - -91, 1827, -91, -91, 322, 281, 103, 1740, 50, 203, - 77, 40, 2001, 53, 733, -91, 52, 29, 733, 25, - 28, 35, -91, -91, -91, -91, -91, -91, -91, -91, - 113, -91, -91, -91, -91, 106, -91, -91, -91, -91, - -91, -91, 15, 68, 733, 135, 119, -91, -91, 897, - -91, 82, 58, 17, -91, 261, 84, 42, 494, 91, - 79, 304, 288, 208, 733, 245, 733, 733, 733, 733, - 418, 733, 733, 733, 733, 733, 288, 288, 288, 288, - 288, 343, 336, 279, 733, -57, 733, 19, 733, -91, - 574, 733, -91, 733, -7, -30, 733, -60, 1740, -91, - 733, 111, 1740, -91, 733, 2, 733, 733, 43, 37, - 733, -91, 34, 118, 23, -91, -91, 733, -91, 238, - 733, -91, -5, 733, -17, 1740, -91, 733, 133, 1740, - -91, -9, 194, -32, -8, 1827, -25, -91, 1740, -91, - 733, 100, 1740, 21, 1740, -91, 31, 26, -20, -91, - -91, 1740, -38, 283, 41, 291, 85, 733, 1740, -1, - -34, 252, 54, -27, 653, 9, 5, -91, 817, -91, - 6, -21, 7, 733, 11, -28, 733, 1, 733, -33, - -10, 733, -91, 1653, 33, -91, -91, -91, -91, -91, - -91, 733, -91, -91, -91, -91, 172, -91, 733, -24, - -91, 1740, -91, 73, -91, -91, 1740, -91, 733, 93, - 0, -91, 24, -91, 36, 122, 733, -91, 44, 48, - -91, -3, -91, 1740, -91, 110, 1740, -91, 192, -91, - -91, 124, 1740, 27, -91, -12, -29, -91, 155, -53, - -22, -91, -91, -91, -91, 733, 123, 1740, -91, 733, - 92, 1740, -91, -91, 105, 1229, -91, -91, 1146, -91, - -91, 1063, -91, -91, -91, -91, -91, -91, 90, -91, - -91, -91, -91, -91, -91, -91, 71, 70, 222, -91, - 733, -91, 164, -91, -91, -91, -91, -91, 1392, -91, - -91, -91, 268, -91, -91, 1914, 1312, -91, 75, -91, - -91, 350, 55, 303, 108, 733, 1740, 59, 38, 242, - 62, 40, 527, 63, 81, -91, 817, -91, 138, 29, - 65, 733, 78, 56, 733, 80, 733, 61, 66, 57, - 101, -91, 347, -91, -91, -91, -91, 64, -91, 140, - -91, -91, 733, -91, -91, 144, -91, -91, -91, - - -102, -102, -102, -102, 19, 103, -102, -102, -102, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -4, 249, -102, -102, -102, -102, -102, -7, -102, -102, - -102, -102, -102, -102, 257, -102, -13, -102, -11, -102, - -102, -102, -102, -102, -102, -3, -102, -102, -102, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -44, -102, - -102, -102, -102, -102, -102, -102, -102, -102, 141, -102, - -102, -102, -8, -102, 0, 16, 116, 122, 129, 119, - -102, -102, 90, 64, -102, -102, 94, -102, 91, 86, - -102, 71, 79, -102, -102, -102, -102, 159, 81, 76, - -102, -102, -102, -102, 98, -102, 67, 63, 47, 163, - -102, 160, 115, 104, 105, 127, 133, -102, 151, 144, - 130, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -102, -102, 145, -102, 152, -102, 162, 31, 21, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -102, -102, -102, -102, 23, -102, -102, -102, -102, -102, - 29, -102, -102, -102, -102, 34, -102, -102, -102, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -102, 89, - -102, 68, 36, -102, -102, 42, -102, 235, 46, 49, - -102, -102, -102, -102, -102, -102, -102, -102, 33, -102, - -102, -102, 26, -102, -102, -18, -102, -102, -102, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -102, 53, -102, -102, 8, 20, -102, -5, -102, 32, - -102, -102, -102, -102, 39, -102, -102, -102, 37, 73, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -102, -102, -102, -102, 40, -102, -102, -102, -102, 97, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - -102, -102, -102, 41, 213, -102, 186, 199, 203, 209, - -102, 50, 51, 38, 57, 60, -102, -102, -102, -102, - -102, -102, -102, -102, 212, -102, 174, -102, 166, -102, - -102, 168, -102, 125, -102, -102, 61, -102, 1, -102, - 45, -102, -9, -102, 172, -102, 184, 176, -102, -102, - 170, -102, -102, -102, -102, -102, -102, 215, -102, 124, - 132, -102, -102, 178, -102, -29, -102, 25, -102, 2, - -102, -102, 62, -102, -102, 102, -102, -102, -28, -102, - 22, -102, -31, -102, -33, -102, -102, -102, -102, -102, - -102, -34, -102, 17, -102, 18, -102, 111, -20, -102, - -102, 24, -102, -102, 153, -102, -102, -102, 30, -102, - -102, -102, -102, 28, -102, 73, 140, -102, 205, -102, - -102, 5, -102, 44, -102, -102, -102, -102, -102, -102, - -102, 43, -102, -102, -102, -102, -102, -102, 135, -102, - -102, 7, -102, -102, -102, -102, 4, -102, 55, -102, - -102, -102, -102, -102, -25, -102, 48, -102, 9, -102, - -102, -102, -102, -69, -102, -102, -70, -102, -102, -102, - -102, -102, -102, -92, -102, -102, -12, -102, -10, -102, - -1, -102, -102, -102, -102, 11, -102, -40, -102, 14, - -102, -39, -102, -102, -102, -17, -102, -102, 54, -102, - -102, -24, -102, -102, -102, -102, -102, -102, -102, -102, - -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, - 3, -102, -102, -102, -102, -102, -102, -102, 267, -102, - -102, -102, 12, -102, -102, -102, 301, -102, -102, -102, - -102, -19, -102, -15, -102, 59, -64, -102, -102, -2, - -102, -102, 142, -102, -102, -102, -14, -102, -102, -102, - -102, 6, -102, 73, 52, -102, 75, -102, -102, -102, - -102, -102, 128, -102, -102, -102, -102, -102, -102, -102, - -102, -102, -6, -102, -102, 58, -102, -102, -102}; - -const int JavaScriptGrammar::action_info [] = { - 338, 174, 289, 485, 472, 472, -89, 480, -105, 380, - 43, 472, -79, -78, -100, 448, -97, 435, -102, 134, - 304, 326, 132, 104, 478, 375, 489, 372, 374, 456, - 377, 336, 199, 452, 423, 433, 440, 384, 421, 205, - 431, 456, 132, 365, 350, 344, 214, 476, -108, 456, - 324, 357, 462, 199, 367, 463, 363, 222, 472, 446, - 441, -75, -108, 182, 485, 448, -89, 588, 180, -75, - -97, 489, -100, 2, 289, 525, 380, 104, 224, 7, - 225, 582, 134, 304, 378, -102, 289, -105, -79, 472, - -65, 283, 328, 344, 268, 326, 2, 485, 174, 518, - 174, 174, 489, 333, 284, 218, 324, 372, 174, 572, - 174, 38, 91, 498, 91, 174, 0, 466, 174, 174, - 0, 0, 0, 92, 20, 92, 359, 91, 91, 346, - 475, 174, 459, 347, 445, 444, 576, 575, 92, 92, - 95, 174, 21, 174, 476, -78, 281, 280, 585, 39, - 509, 96, 491, 450, 12, 9, 8, 573, 175, 12, - 382, 499, 201, 212, 281, 280, 202, 279, 278, 281, - 280, 342, 174, 12, 274, 273, 45, 460, 528, 360, - 288, 287, 174, 487, 12, 0, 20, 207, 136, 97, - 12, 13, 16, 369, 41, 286, 13, 16, 207, 39, - 174, 586, 584, 0, 21, 40, 208, 137, 438, 138, - 13, 16, 174, 12, 0, 0, 0, 208, 0, 209, - 12, 13, 16, 12, 0, 524, 523, 13, 16, 520, - 46, 44, 12, 0, 98, 184, 183, 12, 0, 118, - 99, 119, 97, 118, 41, 119, 118, 97, 119, 0, - 13, 16, 120, 470, 469, 40, 120, 13, 16, 120, - 13, 16, 12, 306, 307, 267, 266, 12, 0, 13, - 16, 12, 0, 0, 13, 16, 174, 0, -319, 306, - 307, 12, 0, 521, 519, 0, 0, 98, -319, 0, - 308, 309, 98, 99, 106, 107, 106, 107, 99, 13, - 16, 21, 311, 312, 13, 16, 308, 309, 13, 16, - 12, 313, 12, 118, 314, 119, 315, 0, 13, 16, - 12, 108, 109, 108, 109, 12, 120, 311, 312, 267, - 266, 0, 12, 0, 0, 0, 313, 0, 0, 314, - 0, 315, 277, 276, 272, 271, 0, 13, 16, 13, - 16, 12, 277, 276, 0, 15, 0, 13, 16, 311, - 312, 0, 13, 16, 277, 276, 311, 312, 313, 13, - 16, 314, 0, 315, 0, 313, 12, 0, 314, 12, - 315, 14, 0, 272, 271, 111, 112, 0, 13, 16, - 0, 0, 0, 113, 114, 111, 112, 115, 0, 116, - 0, 0, 0, 113, 114, 0, 15, 115, 0, 116, - 0, 272, 271, 13, 16, 0, 13, 16, 26, 111, - 112, 0, 0, 0, 0, 0, 0, 113, 114, 0, - 27, 115, 14, 116, 0, 111, 112, 12, 0, 26, - 0, 311, 312, 113, 114, 0, 0, 115, 0, 116, - 313, 27, 0, 314, 0, 315, 0, 0, 12, 0, - 0, 0, 0, 29, 0, 0, 0, 15, 0, 0, - 0, 0, 0, 0, 28, 30, 0, 0, 0, 0, - 0, 0, 31, 0, 526, 0, 0, 0, 15, 0, - 0, 25, 0, 14, 0, 28, 30, 186, 0, 0, - 0, 0, 0, 31, 0, 0, 0, 187, 0, 111, - 112, 188, 25, 0, 14, 0, 0, 113, 114, 0, - 189, 115, 190, 116, 0, 340, 0, 0, 0, 0, - 0, 0, 0, 191, 0, 192, 95, 0, 0, 69, - 70, 0, 0, 193, 0, 0, 194, 96, 0, 72, - 0, 0, 195, 0, 0, 0, 12, 0, 196, 0, - 73, 74, 0, 75, 0, 0, 0, 0, 0, 0, - 78, 0, 0, 197, 81, 0, 0, 186, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 187, 0, 0, - 0, 188, 84, 13, 16, 0, 85, 0, 0, 0, - 189, 0, 190, 0, 0, 0, 0, 80, 87, 71, - 0, 0, 0, 191, 0, 192, 95, 0, 0, 0, - 0, 0, 0, 193, 0, 0, 194, 96, 0, 0, - 0, 0, 195, 0, 0, 0, 0, 0, 196, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 197, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 69, 70, 0, 0, 0, - 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, - 0, 0, 12, 0, 0, 0, 73, 74, 0, 75, - 0, 0, 0, 0, 0, 0, 78, 0, 0, 0, - 81, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 84, 13, - 16, 0, 85, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 80, 87, 71, 0, 0, 0, 0, - 0, 0, 0, 0, 68, 69, 70, 0, 0, 0, - 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, - 0, 0, 12, 0, 0, 0, 73, 74, 0, 75, - 0, 0, 0, 76, 0, 77, 78, 79, 0, 0, - 81, 0, 0, 0, 82, 0, 83, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 84, 13, - 16, 0, 85, 0, 86, 0, 88, 0, 89, 0, - 0, 0, 0, 80, 87, 71, 0, 0, 0, 0, - 0, 0, 0, 0, -98, 0, 0, 0, 68, 69, - 70, 0, 0, 0, 0, 0, 0, 0, 0, 72, - 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, - 73, 74, 0, 75, 0, 0, 0, 76, 0, 77, - 78, 79, 0, 0, 81, 0, 0, 0, 82, 0, - 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 84, 13, 16, 0, 85, 0, 86, 0, - 88, 0, 89, 0, 0, 0, 0, 80, 87, 71, - 0, 0, 0, 0, 0, 0, 0, 0, 68, 69, - 70, 0, 0, 0, 0, 0, 0, 0, 0, 72, - 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, - 73, 74, 0, 75, 0, 0, 0, 76, 0, 77, - 78, 79, 0, 0, 81, 0, 0, 0, 82, 0, - 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 84, 13, 16, 0, 85, 0, 86, 0, - 88, 303, 89, 0, 0, 0, 0, 80, 87, 71, - 0, 0, 0, 0, 0, 0, 0, 0, 496, 0, - 0, 68, 69, 70, 0, 0, 0, 0, 0, 0, - 0, 0, 72, 0, 0, 0, 0, 0, 0, 12, - 0, 0, 0, 73, 74, 0, 75, 0, 0, 0, - 76, 0, 77, 78, 79, 0, 0, 81, 0, 0, - 0, 82, 0, 83, 0, 0, 497, 0, 0, 0, - 0, 0, 0, 0, 0, 84, 13, 16, 0, 85, - 0, 86, 0, 88, 0, 89, 0, 0, 0, 0, - 80, 87, 71, 0, 0, 0, 0, 0, 0, 0, - 0, 504, 0, 0, 68, 69, 70, 0, 0, 0, - 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, - 0, 0, 12, 0, 0, 0, 73, 74, 0, 75, - 0, 0, 0, 76, 0, 77, 78, 79, 0, 0, - 81, 0, 0, 0, 82, 0, 83, 0, 0, 505, - 0, 0, 0, 0, 0, 0, 0, 0, 84, 13, - 16, 0, 85, 0, 86, 0, 88, 0, 89, 0, - 0, 0, 0, 80, 87, 71, 0, 0, 0, 0, - 0, 0, 0, 0, 496, 0, 0, 68, 69, 70, - 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, - 0, 0, 0, 0, 0, 12, 0, 0, 0, 73, - 74, 0, 75, 0, 0, 0, 76, 0, 77, 78, - 79, 0, 0, 81, 0, 0, 0, 82, 0, 83, - 0, 0, 502, 0, 0, 0, 0, 0, 0, 0, - 0, 84, 13, 16, 0, 85, 0, 86, 0, 88, - 0, 89, 0, 0, 0, 0, 80, 87, 71, 0, - 0, 0, 0, 0, 0, 0, 0, 504, 0, 0, - 68, 69, 70, 0, 0, 0, 0, 0, 0, 0, - 0, 72, 0, 0, 0, 0, 0, 0, 12, 0, - 0, 0, 73, 74, 0, 75, 0, 0, 0, 76, - 0, 77, 78, 79, 0, 0, 81, 0, 0, 0, - 82, 0, 83, 0, 0, 507, 0, 0, 0, 0, - 0, 0, 0, 0, 84, 13, 16, 0, 85, 0, - 86, 0, 88, 0, 89, 0, 0, 0, 0, 80, - 87, 71, 0, 0, 0, 0, 0, 0, 0, 0, - 496, 0, 0, 68, 69, 70, 0, 0, 0, 0, - 0, 0, 0, 0, 72, 0, 0, 0, 0, 0, - 0, 12, 0, 0, 0, 73, 74, 0, 75, 0, - 0, 0, 76, 0, 77, 78, 79, 0, 0, 81, - 0, 0, 0, 82, 0, 83, 0, 0, 497, 0, - 0, 15, 0, 0, 0, 0, 0, 84, 13, 16, - 0, 85, 0, 86, 0, 88, 0, 89, 0, 0, - 0, 0, 80, 87, 71, 0, 0, 14, 0, 0, - 0, 0, 0, 68, 69, 70, 0, 0, 0, 0, - 0, 0, 0, 0, 72, 0, 0, 0, 0, 0, - 0, 12, 251, 0, 0, 535, 536, 0, 75, 0, - 0, 0, 76, 0, 77, 78, 79, 0, 0, 81, - 0, 0, 0, 82, 0, 83, 0, 0, 0, 0, - 0, 0, 0, 255, 0, 0, 0, 84, 13, 16, - 0, 85, 0, 86, 0, 88, 0, 89, 0, 0, - 0, 0, 80, 87, 71, 0, 246, 0, 537, 0, - 0, 0, 0, 142, 143, 144, 0, 0, 146, 148, - 149, 0, 0, 150, 0, 151, 0, 0, 0, 153, - 154, 155, 0, 0, 0, 0, 0, 0, 12, 156, - 157, 158, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 159, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 162, 0, - 0, 0, 0, 0, 0, 13, 16, 163, 164, 165, - 0, 167, 168, 169, 170, 171, 172, 0, 0, 160, - 166, 152, 145, 147, 161, 0, 0, 0, 0, 0, - 142, 143, 144, 0, 0, 146, 148, 149, 0, 0, - 150, 0, 151, 0, 0, 0, 153, 154, 155, 0, - 0, 0, 0, 0, 0, 425, 156, 157, 158, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 159, - 0, 0, 0, 426, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 162, 0, 0, 0, 0, - 0, 430, 427, 429, 163, 164, 165, 0, 167, 168, - 169, 170, 171, 172, 0, 0, 160, 166, 152, 145, - 147, 161, 0, 0, 0, 0, 0, 142, 143, 144, - 0, 0, 146, 148, 149, 0, 0, 150, 0, 151, - 0, 0, 0, 153, 154, 155, 0, 0, 0, 0, - 0, 0, 425, 156, 157, 158, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, - 426, 0, 0, 0, 0, 0, 0, 0, 428, 0, - 0, 0, 162, 0, 0, 0, 0, 0, 430, 427, - 429, 163, 164, 165, 0, 167, 168, 169, 170, 171, - 172, 0, 0, 160, 166, 152, 145, 147, 161, 0, - 0, 0, 0, 0, 244, 0, 0, 0, 0, 245, - 0, 68, 69, 70, 247, 0, 0, 0, 0, 0, - 0, 248, 72, 0, 0, 0, 0, 0, 0, 250, - 251, 0, 0, 252, 74, 0, 75, 0, 0, 0, - 76, 0, 77, 78, 79, 0, 0, 81, 0, 0, - 0, 82, 0, 83, 0, 0, 0, 0, 0, 254, - 0, 255, 0, 0, 0, 84, 253, 256, 257, 85, - 258, 86, 259, 88, 31, 89, 260, 261, 0, 0, - 80, 87, 71, 25, 246, 0, 0, 0, 0, 0, - 0, 244, 0, 0, 0, 0, 245, 0, 68, 69, - 70, 247, 0, 0, 0, 0, 0, 0, 248, 249, - 0, 0, 0, 0, 0, 0, 250, 251, 0, 0, - 252, 74, 0, 75, 0, 0, 0, 76, 0, 77, - 78, 79, 0, 0, 81, 0, 0, 0, 82, 0, - 83, 0, 0, 0, 0, 0, 254, 0, 255, 0, - 0, 0, 84, 253, 256, 257, 85, 258, 86, 259, - 88, 31, 89, 260, 261, 0, 0, 80, 87, 71, - 25, 246, 0, 0, 0, 0, 0, 0, 541, 143, - 144, 0, 0, 543, 148, 545, 69, 70, 546, 0, - 151, 0, 0, 0, 153, 548, 549, 0, 0, 0, - 0, 0, 0, 550, 551, 157, 158, 252, 74, 0, - 75, 0, 0, 0, 76, 0, 77, 552, 79, 0, - 0, 554, 0, 0, 0, 82, 0, 83, 0, 0, - 0, 0, 0, 556, 0, 255, 0, 0, 0, 558, - 555, 557, 559, 560, 561, 86, 563, 564, 565, 566, - 567, 568, 0, 0, 553, 562, 547, 542, 544, 161, - 0, 0, 0, 0, 0, 393, 143, 144, 0, 0, - 395, 148, 397, 69, 70, 398, 0, 151, 0, 0, - 0, 153, 400, 401, 0, 0, 0, 0, 0, 0, - 402, 403, 157, 158, 252, 74, 0, 75, 0, 0, - 0, 76, 0, 77, 404, 79, 0, 0, 406, 0, - 0, 0, 82, 0, 83, 0, -244, 0, 0, 0, - 408, 0, 255, 0, 0, 0, 410, 407, 409, 411, - 412, 413, 86, 415, 416, 417, 418, 419, 420, 0, - 0, 405, 414, 399, 394, 396, 161, 0, 0, 0, - 0, 0, - - 334, 477, 282, 482, 270, 503, 467, 464, 275, 42, - 577, 55, 506, 479, 481, 217, 516, 522, 185, 23, - 468, 217, 540, 583, 10, 486, 488, 492, 490, 493, - 508, 270, 434, 385, 422, 383, 381, 366, 379, 368, - 270, 275, 468, 275, 334, 173, 282, 217, 242, 223, - 179, 468, 176, 334, 285, 371, 221, 343, 181, 341, - 211, 282, 465, 198, 352, 204, 457, 339, 370, 449, - 447, 206, 432, 442, 424, 334, 0, 93, 179, 501, - 0, 577, 318, 500, 213, 221, 93, 0, 471, 93, - 93, 93, 130, 483, 316, 317, 93, 461, 93, 93, - 215, 319, 93, 93, 320, 514, 93, 93, 129, 17, - 93, 0, 110, 94, 93, 93, 484, 102, 93, 242, - 93, 103, 101, 203, 337, 93, 11, 484, 93, 93, - 93, 513, 483, 93, 574, 515, 298, 93, 587, 334, - 0, 302, 200, 93, 93, 105, 334, 352, 125, 126, - 93, 11, 215, 269, 93, 93, 373, 510, 93, 124, - 512, 93, 436, 511, 179, 437, 93, 0, 242, 93, - 439, 127, 93, 123, 0, 436, 0, 128, 437, 93, - 93, 483, 215, 93, 93, 139, 436, 122, 335, 437, - 93, 93, 334, 141, 121, 362, 133, 376, 93, 93, - 100, 135, 93, 0, 117, 330, 361, 330, 131, 330, - 302, 93, 302, 93, 302, 330, 302, 0, 302, 0, - 302, 0, 0, 93, 327, 93, 345, 329, 302, 332, - 302, 351, 310, 0, 0, 0, 0, 349, 93, 0, - 348, 364, 93, 302, 93, 321, 484, 302, 93, 322, - 0, 93, 93, 302, 330, 323, 302, 302, 139, 302, - 35, 305, 0, 0, 325, 527, 141, 210, 35, 0, - 24, 37, 11, 0, 0, 0, 358, 0, 24, 37, - 11, 532, 529, 531, 533, 530, 534, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 571, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 569, 0, 0, 0, 0, 0, - 493, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0}; - -const int JavaScriptGrammar::action_check [] = { - 60, 8, 36, 36, 33, 33, 7, 60, 7, 36, - 29, 33, 7, 7, 7, 36, 7, 55, 7, 78, - 1, 78, 48, 1, 36, 33, 36, 36, 60, 5, - 55, 61, 2, 33, 8, 55, 60, 16, 7, 7, - 7, 5, 48, 60, 7, 2, 60, 20, 7, 5, - 48, 17, 55, 2, 31, 7, 61, 8, 33, 7, - 7, 7, 7, 60, 36, 36, 7, 0, 8, 7, - 7, 36, 7, 88, 36, 29, 36, 1, 60, 65, - 33, 17, 78, 1, 7, 7, 36, 7, 7, 33, - 33, 76, 8, 2, 55, 78, 88, 36, 8, 29, - 8, 8, 36, 61, 36, 36, 48, 36, 8, 8, - 8, 66, 40, 8, 40, 8, -1, 7, 8, 8, - -1, -1, -1, 51, 15, 51, 8, 40, 40, 50, - 6, 8, 10, 54, 61, 62, 61, 62, 51, 51, - 42, 8, 33, 8, 20, 7, 61, 62, 8, 29, - 60, 53, 60, 60, 29, 61, 62, 56, 56, 29, - 60, 56, 50, 56, 61, 62, 54, 61, 62, 61, - 62, 60, 8, 29, 61, 62, 7, 55, 7, 61, - 61, 62, 8, 60, 29, -1, 15, 15, 15, 12, - 29, 66, 67, 60, 74, 60, 66, 67, 15, 29, - 8, 61, 62, -1, 33, 85, 34, 34, 36, 36, - 66, 67, 8, 29, -1, -1, -1, 34, -1, 36, - 29, 66, 67, 29, -1, 61, 62, 66, 67, 7, - 61, 62, 29, -1, 57, 61, 62, 29, -1, 25, - 63, 27, 12, 25, 74, 27, 25, 12, 27, -1, - 66, 67, 38, 61, 62, 85, 38, 66, 67, 38, - 66, 67, 29, 18, 19, 61, 62, 29, -1, 66, - 67, 29, -1, -1, 66, 67, 8, -1, 36, 18, - 19, 29, -1, 61, 62, -1, -1, 57, 36, -1, - 45, 46, 57, 63, 18, 19, 18, 19, 63, 66, - 67, 33, 23, 24, 66, 67, 45, 46, 66, 67, - 29, 32, 29, 25, 35, 27, 37, -1, 66, 67, - 29, 45, 46, 45, 46, 29, 38, 23, 24, 61, - 62, -1, 29, -1, -1, -1, 32, -1, -1, 35, - -1, 37, 61, 62, 61, 62, -1, 66, 67, 66, - 67, 29, 61, 62, -1, 59, -1, 66, 67, 23, - 24, -1, 66, 67, 61, 62, 23, 24, 32, 66, - 67, 35, -1, 37, -1, 32, 29, -1, 35, 29, - 37, 85, -1, 61, 62, 23, 24, -1, 66, 67, - -1, -1, -1, 31, 32, 23, 24, 35, -1, 37, - -1, -1, -1, 31, 32, -1, 59, 35, -1, 37, - -1, 61, 62, 66, 67, -1, 66, 67, 10, 23, - 24, -1, -1, -1, -1, -1, -1, 31, 32, -1, - 22, 35, 85, 37, -1, 23, 24, 29, -1, 10, - -1, 23, 24, 31, 32, -1, -1, 35, -1, 37, - 32, 22, -1, 35, -1, 37, -1, -1, 29, -1, - -1, -1, -1, 55, -1, -1, -1, 59, -1, -1, - -1, -1, -1, -1, 66, 67, -1, -1, -1, -1, - -1, -1, 74, -1, 55, -1, -1, -1, 59, -1, - -1, 83, -1, 85, -1, 66, 67, 3, -1, -1, - -1, -1, -1, 74, -1, -1, -1, 13, -1, 23, - 24, 17, 83, -1, 85, -1, -1, 31, 32, -1, - 26, 35, 28, 37, -1, 31, -1, -1, -1, -1, - -1, -1, -1, 39, -1, 41, 42, -1, -1, 12, - 13, -1, -1, 49, -1, -1, 52, 53, -1, 22, - -1, -1, 58, -1, -1, -1, 29, -1, 64, -1, - 33, 34, -1, 36, -1, -1, -1, -1, -1, -1, - 43, -1, -1, 79, 47, -1, -1, 3, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 13, -1, -1, - -1, 17, 65, 66, 67, -1, 69, -1, -1, -1, - 26, -1, 28, -1, -1, -1, -1, 80, 81, 82, - -1, -1, -1, 39, -1, 41, 42, -1, -1, -1, - -1, -1, -1, 49, -1, -1, 52, 53, -1, -1, - -1, -1, 58, -1, -1, -1, -1, -1, 64, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 79, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 12, 13, -1, -1, -1, - -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, - -1, -1, 29, -1, -1, -1, 33, 34, -1, 36, - -1, -1, -1, -1, -1, -1, 43, -1, -1, -1, - 47, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, - 67, -1, 69, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, 80, 81, 82, -1, -1, -1, -1, - -1, -1, -1, -1, 11, 12, 13, -1, -1, -1, - -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, - -1, -1, 29, -1, -1, -1, 33, 34, -1, 36, - -1, -1, -1, 40, -1, 42, 43, 44, -1, -1, - 47, -1, -1, -1, 51, -1, 53, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, - 67, -1, 69, -1, 71, -1, 73, -1, 75, -1, - -1, -1, -1, 80, 81, 82, -1, -1, -1, -1, - -1, -1, -1, -1, 7, -1, -1, -1, 11, 12, - 13, -1, -1, -1, -1, -1, -1, -1, -1, 22, - -1, -1, -1, -1, -1, -1, 29, -1, -1, -1, - 33, 34, -1, 36, -1, -1, -1, 40, -1, 42, - 43, 44, -1, -1, 47, -1, -1, -1, 51, -1, - 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 65, 66, 67, -1, 69, -1, 71, -1, - 73, -1, 75, -1, -1, -1, -1, 80, 81, 82, - -1, -1, -1, -1, -1, -1, -1, -1, 11, 12, - 13, -1, -1, -1, -1, -1, -1, -1, -1, 22, - -1, -1, -1, -1, -1, -1, 29, -1, -1, -1, - 33, 34, -1, 36, -1, -1, -1, 40, -1, 42, - 43, 44, -1, -1, 47, -1, -1, -1, 51, -1, - 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 65, 66, 67, -1, 69, -1, 71, -1, - 73, 74, 75, -1, -1, -1, -1, 80, 81, 82, - -1, -1, -1, -1, -1, -1, -1, -1, 8, -1, - -1, 11, 12, 13, -1, -1, -1, -1, -1, -1, - -1, -1, 22, -1, -1, -1, -1, -1, -1, 29, - -1, -1, -1, 33, 34, -1, 36, -1, -1, -1, - 40, -1, 42, 43, 44, -1, -1, 47, -1, -1, - -1, 51, -1, 53, -1, -1, 56, -1, -1, -1, - -1, -1, -1, -1, -1, 65, 66, 67, -1, 69, - -1, 71, -1, 73, -1, 75, -1, -1, -1, -1, - 80, 81, 82, -1, -1, -1, -1, -1, -1, -1, - -1, 8, -1, -1, 11, 12, 13, -1, -1, -1, - -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, - -1, -1, 29, -1, -1, -1, 33, 34, -1, 36, - -1, -1, -1, 40, -1, 42, 43, 44, -1, -1, - 47, -1, -1, -1, 51, -1, 53, -1, -1, 56, - -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, - 67, -1, 69, -1, 71, -1, 73, -1, 75, -1, - -1, -1, -1, 80, 81, 82, -1, -1, -1, -1, - -1, -1, -1, -1, 8, -1, -1, 11, 12, 13, - -1, -1, -1, -1, -1, -1, -1, -1, 22, -1, - -1, -1, -1, -1, -1, 29, -1, -1, -1, 33, - 34, -1, 36, -1, -1, -1, 40, -1, 42, 43, - 44, -1, -1, 47, -1, -1, -1, 51, -1, 53, - -1, -1, 56, -1, -1, -1, -1, -1, -1, -1, - -1, 65, 66, 67, -1, 69, -1, 71, -1, 73, - -1, 75, -1, -1, -1, -1, 80, 81, 82, -1, - -1, -1, -1, -1, -1, -1, -1, 8, -1, -1, - 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, - -1, 22, -1, -1, -1, -1, -1, -1, 29, -1, - -1, -1, 33, 34, -1, 36, -1, -1, -1, 40, - -1, 42, 43, 44, -1, -1, 47, -1, -1, -1, - 51, -1, 53, -1, -1, 56, -1, -1, -1, -1, - -1, -1, -1, -1, 65, 66, 67, -1, 69, -1, - 71, -1, 73, -1, 75, -1, -1, -1, -1, 80, - 81, 82, -1, -1, -1, -1, -1, -1, -1, -1, - 8, -1, -1, 11, 12, 13, -1, -1, -1, -1, - -1, -1, -1, -1, 22, -1, -1, -1, -1, -1, - -1, 29, -1, -1, -1, 33, 34, -1, 36, -1, - -1, -1, 40, -1, 42, 43, 44, -1, -1, 47, - -1, -1, -1, 51, -1, 53, -1, -1, 56, -1, - -1, 59, -1, -1, -1, -1, -1, 65, 66, 67, - -1, 69, -1, 71, -1, 73, -1, 75, -1, -1, - -1, -1, 80, 81, 82, -1, -1, 85, -1, -1, - -1, -1, -1, 11, 12, 13, -1, -1, -1, -1, - -1, -1, -1, -1, 22, -1, -1, -1, -1, -1, - -1, 29, 30, -1, -1, 33, 34, -1, 36, -1, - -1, -1, 40, -1, 42, 43, 44, -1, -1, 47, - -1, -1, -1, 51, -1, 53, -1, -1, -1, -1, - -1, -1, -1, 61, -1, -1, -1, 65, 66, 67, - -1, 69, -1, 71, -1, 73, -1, 75, -1, -1, - -1, -1, 80, 81, 82, -1, 84, -1, 86, -1, - -1, -1, -1, 4, 5, 6, -1, -1, 9, 10, - 11, -1, -1, 14, -1, 16, -1, -1, -1, 20, - 21, 22, -1, -1, -1, -1, -1, -1, 29, 30, - 31, 32, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, 43, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, 59, -1, - -1, -1, -1, -1, -1, 66, 67, 68, 69, 70, - -1, 72, 73, 74, 75, 76, 77, -1, -1, 80, - 81, 82, 83, 84, 85, -1, -1, -1, -1, -1, - 4, 5, 6, -1, -1, 9, 10, 11, -1, -1, - 14, -1, 16, -1, -1, -1, 20, 21, 22, -1, - -1, -1, -1, -1, -1, 29, 30, 31, 32, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, - -1, -1, -1, 47, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, 59, -1, -1, -1, -1, - -1, 65, 66, 67, 68, 69, 70, -1, 72, 73, - 74, 75, 76, 77, -1, -1, 80, 81, 82, 83, - 84, 85, -1, -1, -1, -1, -1, 4, 5, 6, - -1, -1, 9, 10, 11, -1, -1, 14, -1, 16, - -1, -1, -1, 20, 21, 22, -1, -1, -1, -1, - -1, -1, 29, 30, 31, 32, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, 43, -1, -1, -1, - 47, -1, -1, -1, -1, -1, -1, -1, 55, -1, - -1, -1, 59, -1, -1, -1, -1, -1, 65, 66, - 67, 68, 69, 70, -1, 72, 73, 74, 75, 76, - 77, -1, -1, 80, 81, 82, 83, 84, 85, -1, - -1, -1, -1, -1, 4, -1, -1, -1, -1, 9, - -1, 11, 12, 13, 14, -1, -1, -1, -1, -1, - -1, 21, 22, -1, -1, -1, -1, -1, -1, 29, - 30, -1, -1, 33, 34, -1, 36, -1, -1, -1, - 40, -1, 42, 43, 44, -1, -1, 47, -1, -1, - -1, 51, -1, 53, -1, -1, -1, -1, -1, 59, - -1, 61, -1, -1, -1, 65, 66, 67, 68, 69, - 70, 71, 72, 73, 74, 75, 76, 77, -1, -1, - 80, 81, 82, 83, 84, -1, -1, -1, -1, -1, - -1, 4, -1, -1, -1, -1, 9, -1, 11, 12, - 13, 14, -1, -1, -1, -1, -1, -1, 21, 22, - -1, -1, -1, -1, -1, -1, 29, 30, -1, -1, - 33, 34, -1, 36, -1, -1, -1, 40, -1, 42, - 43, 44, -1, -1, 47, -1, -1, -1, 51, -1, - 53, -1, -1, -1, -1, -1, 59, -1, 61, -1, - -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, - 73, 74, 75, 76, 77, -1, -1, 80, 81, 82, - 83, 84, -1, -1, -1, -1, -1, -1, 4, 5, - 6, -1, -1, 9, 10, 11, 12, 13, 14, -1, - 16, -1, -1, -1, 20, 21, 22, -1, -1, -1, - -1, -1, -1, 29, 30, 31, 32, 33, 34, -1, - 36, -1, -1, -1, 40, -1, 42, 43, 44, -1, - -1, 47, -1, -1, -1, 51, -1, 53, -1, -1, - -1, -1, -1, 59, -1, 61, -1, -1, -1, 65, - 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, - 76, 77, -1, -1, 80, 81, 82, 83, 84, 85, - -1, -1, -1, -1, -1, 4, 5, 6, -1, -1, - 9, 10, 11, 12, 13, 14, -1, 16, -1, -1, - -1, 20, 21, 22, -1, -1, -1, -1, -1, -1, - 29, 30, 31, 32, 33, 34, -1, 36, -1, -1, - -1, 40, -1, 42, 43, 44, -1, -1, 47, -1, - -1, -1, 51, -1, 53, -1, 55, -1, -1, -1, - 59, -1, 61, -1, -1, -1, 65, 66, 67, 68, - 69, 70, 71, 72, 73, 74, 75, 76, 77, -1, - -1, 80, 81, 82, 83, 84, 85, -1, -1, -1, - -1, -1, - - 14, 93, 66, 15, 23, 29, 76, 76, 23, 20, - 23, 14, 29, 23, 15, 23, 23, 14, 62, 23, - 14, 23, 10, 29, 5, 14, 66, 66, 14, 29, - 14, 23, 66, 66, 29, 66, 14, 66, 66, 14, - 23, 23, 14, 23, 14, 14, 66, 23, 66, 23, - 29, 14, 29, 14, 14, 23, 23, 66, 29, 14, - 14, 66, 14, 29, 23, 29, 91, 66, 66, 14, - 66, 29, 29, 66, 30, 14, -1, 39, 29, 25, - -1, 23, 44, 29, 35, 23, 39, -1, 15, 39, - 39, 39, 45, 41, 44, 44, 39, 88, 39, 39, - 41, 44, 39, 39, 44, 41, 39, 39, 45, 6, - 39, -1, 45, 42, 39, 39, 41, 41, 39, 66, - 39, 42, 41, 55, 63, 39, 23, 41, 39, 39, - 39, 41, 41, 39, 6, 41, 39, 39, 80, 14, - -1, 44, 53, 39, 39, 47, 14, 23, 44, 44, - 39, 23, 41, 100, 39, 39, 94, 41, 39, 44, - 41, 39, 33, 41, 29, 36, 39, -1, 66, 39, - 35, 44, 39, 43, -1, 33, -1, 44, 36, 39, - 39, 41, 41, 39, 39, 23, 33, 43, 63, 36, - 39, 39, 14, 31, 43, 63, 51, 95, 39, 39, - 41, 49, 39, -1, 44, 39, 82, 39, 45, 39, - 44, 39, 44, 39, 44, 39, 44, -1, 44, -1, - 44, -1, -1, 39, 50, 39, 54, 61, 44, 61, - 44, 61, 46, -1, -1, -1, -1, 61, 39, -1, - 56, 63, 39, 44, 39, 46, 41, 44, 39, 46, - -1, 39, 39, 44, 39, 46, 44, 44, 23, 44, - 11, 48, -1, -1, 52, 8, 31, 32, 11, -1, - 21, 22, 23, -1, -1, -1, 61, -1, 21, 22, - 23, 14, 15, 16, 17, 18, 19, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, 23, -1, -1, -1, -1, -1, - 29, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, - -1, -1, -1}; - diff --git a/src/declarative/qml/parser/javascriptgrammar_p.h b/src/declarative/qml/parser/javascriptgrammar_p.h deleted file mode 100644 index 830f533..0000000 --- a/src/declarative/qml/parser/javascriptgrammar_p.h +++ /dev/null @@ -1,200 +0,0 @@ -// This file was generated by qlalr - DO NOT EDIT! -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtCore module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists for the convenience -// of other Qt classes. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#ifndef JAVASCRIPTGRAMMAR_P_H -#define JAVASCRIPTGRAMMAR_P_H - -class JavaScriptGrammar -{ -public: - enum { - EOF_SYMBOL = 0, - REDUCE_HERE = 90, - SHIFT_THERE = 89, - T_AND = 1, - T_AND_AND = 2, - T_AND_EQ = 3, - T_AUTOMATIC_SEMICOLON = 62, - T_BREAK = 4, - T_CASE = 5, - T_CATCH = 6, - T_COLON = 7, - T_COMMA = 8, - T_CONST = 83, - T_CONTINUE = 9, - T_DEBUGGER = 84, - T_DEFAULT = 10, - T_DELETE = 11, - T_DIVIDE_ = 12, - T_DIVIDE_EQ = 13, - T_DO = 14, - T_DOT = 15, - T_ELSE = 16, - T_EQ = 17, - T_EQ_EQ = 18, - T_EQ_EQ_EQ = 19, - T_FALSE = 82, - T_FINALLY = 20, - T_FOR = 21, - T_FUNCTION = 22, - T_GE = 23, - T_GT = 24, - T_GT_GT = 25, - T_GT_GT_EQ = 26, - T_GT_GT_GT = 27, - T_GT_GT_GT_EQ = 28, - T_IDENTIFIER = 29, - T_IF = 30, - T_IMPORT = 88, - T_IN = 31, - T_INSTANCEOF = 32, - T_LBRACE = 33, - T_LBRACKET = 34, - T_LE = 35, - T_LPAREN = 36, - T_LT = 37, - T_LT_LT = 38, - T_LT_LT_EQ = 39, - T_MINUS = 40, - T_MINUS_EQ = 41, - T_MINUS_MINUS = 42, - T_MULTILINE_STRING_LITERAL = 86, - T_NEW = 43, - T_NOT = 44, - T_NOT_EQ = 45, - T_NOT_EQ_EQ = 46, - T_NULL = 80, - T_NUMERIC_LITERAL = 47, - T_OR = 48, - T_OR_EQ = 49, - T_OR_OR = 50, - T_PLUS = 51, - T_PLUS_EQ = 52, - T_PLUS_PLUS = 53, - T_PROPERTY = 66, - T_PUBLIC = 87, - T_QUESTION = 54, - T_RBRACE = 55, - T_RBRACKET = 56, - T_REMAINDER = 57, - T_REMAINDER_EQ = 58, - T_RESERVED_WORD = 85, - T_RETURN = 59, - T_RPAREN = 60, - T_SEMICOLON = 61, - T_SIGNAL = 67, - T_STAR = 63, - T_STAR_EQ = 64, - T_STRING_LITERAL = 65, - T_SWITCH = 68, - T_THIS = 69, - T_THROW = 70, - T_TILDE = 71, - T_TRUE = 81, - T_TRY = 72, - T_TYPEOF = 73, - T_VAR = 74, - T_VOID = 75, - T_WHILE = 76, - T_WITH = 77, - T_XOR = 78, - T_XOR_EQ = 79, - - ACCEPT_STATE = 588, - RULE_COUNT = 323, - STATE_COUNT = 589, - TERMINAL_COUNT = 91, - NON_TERMINAL_COUNT = 102, - - GOTO_INDEX_OFFSET = 589, - GOTO_INFO_OFFSET = 2092, - GOTO_CHECK_OFFSET = 2092 - }; - - static const char *const spell []; - static const int lhs []; - static const int rhs []; - static const int goto_default []; - static const int action_default []; - static const int action_index []; - static const int action_info []; - static const int action_check []; - - static inline int nt_action (int state, int nt) - { - const int *const goto_index = &action_index [GOTO_INDEX_OFFSET]; - const int *const goto_check = &action_check [GOTO_CHECK_OFFSET]; - - const int yyn = goto_index [state] + nt; - - if (yyn < 0 || goto_check [yyn] != nt) - return goto_default [nt]; - - const int *const goto_info = &action_info [GOTO_INFO_OFFSET]; - return goto_info [yyn]; - } - - static inline int t_action (int state, int token) - { - const int yyn = action_index [state] + token; - - if (yyn < 0 || action_check [yyn] != token) - return - action_default [state]; - - return action_info [yyn]; - } -}; - - -#endif // JAVASCRIPTGRAMMAR_P_H - diff --git a/src/declarative/qml/parser/javascriptlexer.cpp b/src/declarative/qml/parser/javascriptlexer.cpp deleted file mode 100644 index ea36a7a..0000000 --- a/src/declarative/qml/parser/javascriptlexer.cpp +++ /dev/null @@ -1,1196 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifdef HAVE_CONFIG_H -#include "config.h" -#endif - -#include "javascriptengine_p.h" -#include "javascriptlexer_p.h" -#include "javascriptgrammar_p.h" - -#include -#include -#include -#include - -QT_BEGIN_NAMESPACE - -extern double qstrtod(const char *s00, char const **se, bool *ok); - -#define shiftWindowsLineBreak() \ - do { \ - if (((current == '\r') && (next1 == '\n')) \ - || ((current == '\n') && (next1 == '\r'))) { \ - shift(1); \ - } \ - } \ - while (0) - -namespace JavaScript { -extern double integerFromString(const char *buf, int size, int radix); -} - -using namespace JavaScript; - -Lexer::Lexer(Engine *eng) - : driver(eng), - yylineno(0), - done(false), - size8(128), size16(128), - pos8(0), pos16(0), - terminator(false), - restrKeyword(false), - delimited(false), - stackToken(-1), - state(Start), - pos(0), - code(0), length(0), - yycolumn(0), - startpos(0), - startlineno(0), startcolumn(0), - bol(true), - current(0), next1(0), next2(0), next3(0), - err(NoError), - wantRx(false), - check_reserved(true), - parenthesesState(IgnoreParentheses), - parenthesesCount(0), - prohibitAutomaticSemicolon(false) -{ - driver->setLexer(this); - // allocate space for read buffers - buffer8 = new char[size8]; - buffer16 = new QChar[size16]; - pattern = 0; - flags = 0; - -} - -Lexer::~Lexer() -{ - delete [] buffer8; - delete [] buffer16; -} - -void Lexer::setCode(const QString &c, int lineno) -{ - errmsg = QString(); - yylineno = lineno; - yycolumn = 1; - restrKeyword = false; - delimited = false; - stackToken = -1; - pos = 0; - code = c.unicode(); - length = c.length(); - bol = true; - - // read first characters - current = (length > 0) ? code[0].unicode() : 0; - next1 = (length > 1) ? code[1].unicode() : 0; - next2 = (length > 2) ? code[2].unicode() : 0; - next3 = (length > 3) ? code[3].unicode() : 0; -} - -void Lexer::shift(uint p) -{ - while (p--) { - ++pos; - ++yycolumn; - current = next1; - next1 = next2; - next2 = next3; - next3 = (pos + 3 < length) ? code[pos+3].unicode() : 0; - } -} - -void Lexer::setDone(State s) -{ - state = s; - done = true; -} - -int Lexer::findReservedWord(const QChar *c, int size) const -{ - switch (size) { - case 2: { - if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o')) - return JavaScriptGrammar::T_DO; - else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('f')) - return JavaScriptGrammar::T_IF; - else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n')) - return JavaScriptGrammar::T_IN; - } break; - - case 3: { - if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('o') && c[2] == QLatin1Char('r')) - return JavaScriptGrammar::T_FOR; - else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('e') && c[2] == QLatin1Char('w')) - return JavaScriptGrammar::T_NEW; - else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') && c[2] == QLatin1Char('y')) - return JavaScriptGrammar::T_TRY; - else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('a') && c[2] == QLatin1Char('r')) - return JavaScriptGrammar::T_VAR; - else if (check_reserved) { - if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') && c[2] == QLatin1Char('t')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - case 4: { - if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a') - && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e')) - return JavaScriptGrammar::T_CASE; - else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('l') - && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e')) - return JavaScriptGrammar::T_ELSE; - else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h') - && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('s')) - return JavaScriptGrammar::T_THIS; - else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o') - && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('d')) - return JavaScriptGrammar::T_VOID; - else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('i') - && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('h')) - return JavaScriptGrammar::T_WITH; - else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') - && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('e')) - return JavaScriptGrammar::T_TRUE; - else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('u') - && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('l')) - return JavaScriptGrammar::T_NULL; - else if (check_reserved) { - if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('n') - && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('m')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('y') - && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('l') && c[1] == QLatin1Char('o') - && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('g')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('h') - && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('r')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('g') && c[1] == QLatin1Char('o') - && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('o')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - case 5: { - if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('r') - && c[2] == QLatin1Char('e') && c[3] == QLatin1Char('a') - && c[4] == QLatin1Char('k')) - return JavaScriptGrammar::T_BREAK; - else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a') - && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('c') - && c[4] == QLatin1Char('h')) - return JavaScriptGrammar::T_CATCH; - else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h') - && c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o') - && c[4] == QLatin1Char('w')) - return JavaScriptGrammar::T_THROW; - else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('h') - && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('l') - && c[4] == QLatin1Char('e')) - return JavaScriptGrammar::T_WHILE; - else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o') - && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('s') - && c[4] == QLatin1Char('t')) - return JavaScriptGrammar::T_CONST; - else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('a') - && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('s') - && c[4] == QLatin1Char('e')) - return JavaScriptGrammar::T_FALSE; - else if (check_reserved) { - if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('h') - && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('r') - && c[4] == QLatin1Char('t')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('u') - && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e') - && c[4] == QLatin1Char('r')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i') - && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a') - && c[4] == QLatin1Char('l')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('l') - && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('s') - && c[4] == QLatin1Char('s')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('l') - && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('a') - && c[4] == QLatin1Char('t')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - case 6: { - if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e') - && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('e') - && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('e')) - return JavaScriptGrammar::T_DELETE; - else if (c[0] == QLatin1Char('r') && c[1] == QLatin1Char('e') - && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('u') - && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('n')) - return JavaScriptGrammar::T_RETURN; - else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('w') - && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('t') - && c[4] == QLatin1Char('c') && c[5] == QLatin1Char('h')) - return JavaScriptGrammar::T_SWITCH; - else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('y') - && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e') - && c[4] == QLatin1Char('o') && c[5] == QLatin1Char('f')) - return JavaScriptGrammar::T_TYPEOF; - else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m') - && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o') - && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t')) - return JavaScriptGrammar::T_IMPORT; - else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('i') - && c[2] == QLatin1Char('g') && c[3] == QLatin1Char('n') - && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('l')) - return JavaScriptGrammar::T_SIGNAL; - else if (check_reserved) { - if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x') - && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o') - && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('t') - && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('t') - && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o') - && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('b') - && c[4] == QLatin1Char('l') && c[5] == QLatin1Char('e')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m') - && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o') - && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('u') - && c[2] == QLatin1Char('b') && c[3] == QLatin1Char('l') - && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c')) - return JavaScriptGrammar::T_PUBLIC; - else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('a') - && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('i') - && c[4] == QLatin1Char('v') && c[5] == QLatin1Char('e')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h') - && c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o') - && c[4] == QLatin1Char('w') && c[5] == QLatin1Char('s')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - case 7: { - if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e') - && c[2] == QLatin1Char('f') && c[3] == QLatin1Char('a') - && c[4] == QLatin1Char('u') && c[5] == QLatin1Char('l') - && c[6] == QLatin1Char('t')) - return JavaScriptGrammar::T_DEFAULT; - else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i') - && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a') - && c[4] == QLatin1Char('l') && c[5] == QLatin1Char('l') - && c[6] == QLatin1Char('y')) - return JavaScriptGrammar::T_FINALLY; - else if (check_reserved) { - if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('o') - && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('l') - && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('a') - && c[6] == QLatin1Char('n')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x') - && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e') - && c[4] == QLatin1Char('n') && c[5] == QLatin1Char('d') - && c[6] == QLatin1Char('s')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('a') - && c[2] == QLatin1Char('c') && c[3] == QLatin1Char('k') - && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('g') - && c[6] == QLatin1Char('e')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r') - && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('v') - && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('t') - && c[6] == QLatin1Char('e')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - case 8: { - if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o') - && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('t') - && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('n') - && c[6] == QLatin1Char('u') && c[7] == QLatin1Char('e')) - return JavaScriptGrammar::T_CONTINUE; - else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('u') - && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c') - && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i') - && c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n')) - return JavaScriptGrammar::T_FUNCTION; - else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e') - && c[2] == QLatin1Char('b') && c[3] == QLatin1Char('u') - && c[4] == QLatin1Char('g') && c[5] == QLatin1Char('g') - && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('r')) - return JavaScriptGrammar::T_DEBUGGER; - else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r') - && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('p') - && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('r') - && c[6] == QLatin1Char('t') && c[7] == QLatin1Char('y')) - return JavaScriptGrammar::T_PROPERTY; - else if (check_reserved) { - if (c[0] == QLatin1Char('a') && c[1] == QLatin1Char('b') - && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t') - && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('a') - && c[6] == QLatin1Char('c') && c[7] == QLatin1Char('t')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o') - && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('a') - && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i') - && c[6] == QLatin1Char('l') && c[7] == QLatin1Char('e')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - case 9: { - if (check_reserved) { - if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') - && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e') - && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('f') - && c[6] == QLatin1Char('a') && c[7] == QLatin1Char('c') - && c[8] == QLatin1Char('e')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') - && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('n') - && c[4] == QLatin1Char('s') && c[5] == QLatin1Char('i') - && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n') - && c[8] == QLatin1Char('t')) - return JavaScriptGrammar::T_RESERVED_WORD; - else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r') - && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('t') - && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('c') - && c[6] == QLatin1Char('t') && c[7] == QLatin1Char('e') - && c[8] == QLatin1Char('d')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - case 10: { - if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') - && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t') - && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('n') - && c[6] == QLatin1Char('c') && c[7] == QLatin1Char('e') - && c[8] == QLatin1Char('o') && c[9] == QLatin1Char('f')) - return JavaScriptGrammar::T_INSTANCEOF; - else if (check_reserved) { - if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m') - && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('l') - && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('m') - && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n') - && c[8] == QLatin1Char('t') && c[9] == QLatin1Char('s')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - case 12: { - if (check_reserved) { - if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('y') - && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c') - && c[4] == QLatin1Char('h') && c[5] == QLatin1Char('r') - && c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n') - && c[8] == QLatin1Char('i') && c[9] == QLatin1Char('z') - && c[10] == QLatin1Char('e') && c[11] == QLatin1Char('d')) - return JavaScriptGrammar::T_RESERVED_WORD; - } - } break; - - } // switch - - return -1; -} - -int Lexer::lex() -{ - int token = 0; - state = Start; - ushort stringType = 0; // either single or double quotes - bool multiLineString = false; - pos8 = pos16 = 0; - done = false; - terminator = false; - - // did we push a token on the stack previously ? - // (after an automatic semicolon insertion) - if (stackToken >= 0) { - setDone(Other); - token = stackToken; - stackToken = -1; - } - - while (!done) { - switch (state) { - case Start: - if (isWhiteSpace()) { - // do nothing - } else if (current == '/' && next1 == '/') { - recordStartPos(); - shift(1); - state = InSingleLineComment; - } else if (current == '/' && next1 == '*') { - recordStartPos(); - shift(1); - state = InMultiLineComment; - } else if (current == 0) { - syncProhibitAutomaticSemicolon(); - if (!terminator && !delimited && !prohibitAutomaticSemicolon) { - // automatic semicolon insertion if program incomplete - token = JavaScriptGrammar::T_SEMICOLON; - stackToken = 0; - setDone(Other); - } else { - setDone(Eof); - } - } else if (isLineTerminator()) { - shiftWindowsLineBreak(); - yylineno++; - yycolumn = 0; - bol = true; - terminator = true; - syncProhibitAutomaticSemicolon(); - if (restrKeyword) { - token = JavaScriptGrammar::T_SEMICOLON; - setDone(Other); - } - } else if (current == '"' || current == '\'') { - recordStartPos(); - state = InString; - multiLineString = false; - stringType = current; - } else if (isIdentLetter(current)) { - recordStartPos(); - record16(current); - state = InIdentifier; - } else if (current == '0') { - recordStartPos(); - record8(current); - state = InNum0; - } else if (isDecimalDigit(current)) { - recordStartPos(); - record8(current); - state = InNum; - } else if (current == '.' && isDecimalDigit(next1)) { - recordStartPos(); - record8(current); - state = InDecimal; - } else { - recordStartPos(); - token = matchPunctuator(current, next1, next2, next3); - if (token != -1) { - if (terminator && !delimited && !prohibitAutomaticSemicolon - && (token == JavaScriptGrammar::T_PLUS_PLUS - || token == JavaScriptGrammar::T_MINUS_MINUS)) { - // automatic semicolon insertion - stackToken = token; - token = JavaScriptGrammar::T_SEMICOLON; - } - setDone(Other); - } - else { - setDone(Bad); - err = IllegalCharacter; - errmsg = QLatin1String("Illegal character"); - } - } - break; - case InString: - if (current == stringType) { - shift(1); - setDone(String); - } else if (isLineTerminator()) { - multiLineString = true; - record16(current); - } else if (current == 0 || isLineTerminator()) { - setDone(Bad); - err = UnclosedStringLiteral; - errmsg = QLatin1String("Unclosed string at end of line"); - } else if (current == '\\') { - state = InEscapeSequence; - } else { - record16(current); - } - break; - // Escape Sequences inside of strings - case InEscapeSequence: - if (isOctalDigit(current)) { - if (current >= '0' && current <= '3' && - isOctalDigit(next1) && isOctalDigit(next2)) { - record16(convertOctal(current, next1, next2)); - shift(2); - state = InString; - } else if (isOctalDigit(current) && - isOctalDigit(next1)) { - record16(convertOctal('0', current, next1)); - shift(1); - state = InString; - } else if (isOctalDigit(current)) { - record16(convertOctal('0', '0', current)); - state = InString; - } else { - setDone(Bad); - err = IllegalEscapeSequence; - errmsg = QLatin1String("Illegal escape squence"); - } - } else if (current == 'x') - state = InHexEscape; - else if (current == 'u') - state = InUnicodeEscape; - else { - if (isLineTerminator()) { - shiftWindowsLineBreak(); - yylineno++; - yycolumn = 0; - bol = true; - } else { - record16(singleEscape(current)); - } - state = InString; - } - break; - case InHexEscape: - if (isHexDigit(current) && isHexDigit(next1)) { - state = InString; - record16(QLatin1Char(convertHex(current, next1))); - shift(1); - } else if (current == stringType) { - record16(QLatin1Char('x')); - shift(1); - setDone(String); - } else { - record16(QLatin1Char('x')); - record16(current); - state = InString; - } - break; - case InUnicodeEscape: - if (isHexDigit(current) && isHexDigit(next1) && - isHexDigit(next2) && isHexDigit(next3)) { - record16(convertUnicode(current, next1, next2, next3)); - shift(3); - state = InString; - } else if (current == stringType) { - record16(QLatin1Char('u')); - shift(1); - setDone(String); - } else { - setDone(Bad); - err = IllegalUnicodeEscapeSequence; - errmsg = QLatin1String("Illegal unicode escape sequence"); - } - break; - case InSingleLineComment: - if (isLineTerminator()) { - shiftWindowsLineBreak(); - yylineno++; - yycolumn = 0; - terminator = true; - bol = true; - if (restrKeyword) { - token = JavaScriptGrammar::T_SEMICOLON; - setDone(Other); - } else - state = Start; - } else if (current == 0) { - setDone(Eof); - } - break; - case InMultiLineComment: - if (current == 0) { - setDone(Bad); - err = UnclosedComment; - errmsg = QLatin1String("Unclosed comment at end of file"); - } else if (isLineTerminator()) { - shiftWindowsLineBreak(); - yylineno++; - } else if (current == '*' && next1 == '/') { - state = Start; - shift(1); - } - break; - case InIdentifier: - if (isIdentLetter(current) || isDecimalDigit(current)) { - record16(current); - break; - } - setDone(Identifier); - break; - case InNum0: - if (current == 'x' || current == 'X') { - record8(current); - state = InHex; - } else if (current == '.') { - record8(current); - state = InDecimal; - } else if (current == 'e' || current == 'E') { - record8(current); - state = InExponentIndicator; - } else if (isOctalDigit(current)) { - record8(current); - state = InOctal; - } else if (isDecimalDigit(current)) { - record8(current); - state = InDecimal; - } else { - setDone(Number); - } - break; - case InHex: - if (isHexDigit(current)) - record8(current); - else - setDone(Hex); - break; - case InOctal: - if (isOctalDigit(current)) { - record8(current); - } else if (isDecimalDigit(current)) { - record8(current); - state = InDecimal; - } else { - setDone(Octal); - } - break; - case InNum: - if (isDecimalDigit(current)) { - record8(current); - } else if (current == '.') { - record8(current); - state = InDecimal; - } else if (current == 'e' || current == 'E') { - record8(current); - state = InExponentIndicator; - } else { - setDone(Number); - } - break; - case InDecimal: - if (isDecimalDigit(current)) { - record8(current); - } else if (current == 'e' || current == 'E') { - record8(current); - state = InExponentIndicator; - } else { - setDone(Number); - } - break; - case InExponentIndicator: - if (current == '+' || current == '-') { - record8(current); - } else if (isDecimalDigit(current)) { - record8(current); - state = InExponent; - } else { - setDone(Bad); - err = IllegalExponentIndicator; - errmsg = QLatin1String("Illegal syntax for exponential number"); - } - break; - case InExponent: - if (isDecimalDigit(current)) { - record8(current); - } else { - setDone(Number); - } - break; - default: - Q_ASSERT_X(0, "Lexer::lex", "Unhandled state in switch statement"); - } - - // move on to the next character - if (!done) - shift(1); - if (state != Start && state != InSingleLineComment) - bol = false; - } - - if (state == Number) { - // CSS-style suffix for numeric literals - - flags = noSuffix; - - const ushort c = QChar::toLower(current); - const ushort n1 = QChar::toLower(next1); - const ushort n2 = QChar::toLower(next2); - const ushort n3 = QChar::toLower(next3); - - if (c == 'e' && n1 == 'm') { - flags = emSuffix; - shift(2); - } else if (c == 'e' && n1 == 'x') { - flags = exSuffix; - shift(2); - } else if (c == 'p' && n1 == 'x') { - flags = pxSuffix; - shift(2); - } else if (c == 'c' && n1 == 'm') { - flags = cmSuffix; - shift(2); - } else if (c == 'm' && n1 == 'm') { - flags = mmSuffix; - shift(2); - } else if (c == 'i' && n1 == 'n') { - flags = inSuffix; - shift(2); - } else if (c == 'p' && n1 == 't') { - flags = ptSuffix; - shift(2); - } else if (c == 'p' && n1 == 'c') { - flags = pcSuffix; - shift(1); - } else if (c == 'd' && n1 == 'e' && n2 == 'g') { - flags = degSuffix; - shift(3); - } else if (c == 'r' && n1 == 'a' && n2 == 'd') { - flags = radSuffix; - shift(3); - } else if (c == 'g' && n1 == 'r' && n2 == 'a' && n3 == 'd') { - flags = gradSuffix; - shift(4); - } else if (c == 'm' && n1 == 's') { - flags = msSuffix; - shift(2); - } else if (c == 's') { - flags = sSuffix; - shift(1); - } else if (c == 'h' && n1 == 'z') { - flags = hzSuffix; - shift(2); - } else if (c == 'k' && n1 == 'h' && n2 == 'z') { - flags = khzSuffix; - shift(3); - } - } - - // no identifiers allowed directly after numeric literal, e.g. "3in" is bad - if ((state == Number || state == Octal || state == Hex) - && isIdentLetter(current)) { - state = Bad; - err = IllegalIdentifier; - errmsg = QLatin1String("Identifier cannot start with numeric literal"); - } - - // terminate string - buffer8[pos8] = '\0'; - - double dval = 0; - if (state == Number) { - dval = qstrtod(buffer8, 0, 0); - } else if (state == Hex) { // scan hex numbers - dval = integerFromString(buffer8, pos8, 16); - state = Number; - } else if (state == Octal) { // scan octal number - dval = integerFromString(buffer8, pos8, 8); - state = Number; - } - - restrKeyword = false; - delimited = false; - - switch (parenthesesState) { - case IgnoreParentheses: - break; - case CountParentheses: - if (token == JavaScriptGrammar::T_RPAREN) { - --parenthesesCount; - if (parenthesesCount == 0) - parenthesesState = BalancedParentheses; - } else if (token == JavaScriptGrammar::T_LPAREN) { - ++parenthesesCount; - } - break; - case BalancedParentheses: - parenthesesState = IgnoreParentheses; - break; - } - - switch (state) { - case Eof: - return 0; - case Other: - if (token == JavaScriptGrammar::T_RBRACE || token == JavaScriptGrammar::T_SEMICOLON) - delimited = true; - return token; - case Identifier: - if ((token = findReservedWord(buffer16, pos16)) < 0) { - /* TODO: close leak on parse error. same holds true for String */ - if (driver) - qsyylval.ustr = driver->intern(buffer16, pos16); - else - qsyylval.ustr = 0; - return JavaScriptGrammar::T_IDENTIFIER; - } - if (token == JavaScriptGrammar::T_CONTINUE || token == JavaScriptGrammar::T_BREAK - || token == JavaScriptGrammar::T_RETURN || token == JavaScriptGrammar::T_THROW) { - restrKeyword = true; - } else if (token == JavaScriptGrammar::T_IF || token == JavaScriptGrammar::T_FOR - || token == JavaScriptGrammar::T_WHILE || token == JavaScriptGrammar::T_WITH) { - parenthesesState = CountParentheses; - parenthesesCount = 0; - } else if (token == JavaScriptGrammar::T_DO) { - parenthesesState = BalancedParentheses; - } - return token; - case String: - if (driver) - qsyylval.ustr = driver->intern(buffer16, pos16); - else - qsyylval.ustr = 0; - return multiLineString?JavaScriptGrammar::T_MULTILINE_STRING_LITERAL:JavaScriptGrammar::T_STRING_LITERAL; - case Number: - qsyylval.dval = dval; - return JavaScriptGrammar::T_NUMERIC_LITERAL; - case Bad: - return -1; - default: - Q_ASSERT(!"unhandled numeration value in switch"); - return -1; - } -} - -bool Lexer::isWhiteSpace() const -{ - return (current == ' ' || current == '\t' || - current == 0x0b || current == 0x0c); -} - -bool Lexer::isLineTerminator() const -{ - return (current == '\n' || current == '\r'); -} - -bool Lexer::isIdentLetter(ushort c) -{ - /* TODO: allow other legitimate unicode chars */ - return ((c >= 'a' && c <= 'z') - || (c >= 'A' && c <= 'Z') - || c == '$' - || c == '_'); -} - -bool Lexer::isDecimalDigit(ushort c) -{ - return (c >= '0' && c <= '9'); -} - -bool Lexer::isHexDigit(ushort c) const -{ - return ((c >= '0' && c <= '9') - || (c >= 'a' && c <= 'f') - || (c >= 'A' && c <= 'F')); -} - -bool Lexer::isOctalDigit(ushort c) const -{ - return (c >= '0' && c <= '7'); -} - -int Lexer::matchPunctuator(ushort c1, ushort c2, - ushort c3, ushort c4) -{ - if (c1 == '>' && c2 == '>' && c3 == '>' && c4 == '=') { - shift(4); - return JavaScriptGrammar::T_GT_GT_GT_EQ; - } else if (c1 == '=' && c2 == '=' && c3 == '=') { - shift(3); - return JavaScriptGrammar::T_EQ_EQ_EQ; - } else if (c1 == '!' && c2 == '=' && c3 == '=') { - shift(3); - return JavaScriptGrammar::T_NOT_EQ_EQ; - } else if (c1 == '>' && c2 == '>' && c3 == '>') { - shift(3); - return JavaScriptGrammar::T_GT_GT_GT; - } else if (c1 == '<' && c2 == '<' && c3 == '=') { - shift(3); - return JavaScriptGrammar::T_LT_LT_EQ; - } else if (c1 == '>' && c2 == '>' && c3 == '=') { - shift(3); - return JavaScriptGrammar::T_GT_GT_EQ; - } else if (c1 == '<' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_LE; - } else if (c1 == '>' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_GE; - } else if (c1 == '!' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_NOT_EQ; - } else if (c1 == '+' && c2 == '+') { - shift(2); - return JavaScriptGrammar::T_PLUS_PLUS; - } else if (c1 == '-' && c2 == '-') { - shift(2); - return JavaScriptGrammar::T_MINUS_MINUS; - } else if (c1 == '=' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_EQ_EQ; - } else if (c1 == '+' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_PLUS_EQ; - } else if (c1 == '-' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_MINUS_EQ; - } else if (c1 == '*' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_STAR_EQ; - } else if (c1 == '/' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_DIVIDE_EQ; - } else if (c1 == '&' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_AND_EQ; - } else if (c1 == '^' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_XOR_EQ; - } else if (c1 == '%' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_REMAINDER_EQ; - } else if (c1 == '|' && c2 == '=') { - shift(2); - return JavaScriptGrammar::T_OR_EQ; - } else if (c1 == '<' && c2 == '<') { - shift(2); - return JavaScriptGrammar::T_LT_LT; - } else if (c1 == '>' && c2 == '>') { - shift(2); - return JavaScriptGrammar::T_GT_GT; - } else if (c1 == '&' && c2 == '&') { - shift(2); - return JavaScriptGrammar::T_AND_AND; - } else if (c1 == '|' && c2 == '|') { - shift(2); - return JavaScriptGrammar::T_OR_OR; - } - - switch(c1) { - case '=': shift(1); return JavaScriptGrammar::T_EQ; - case '>': shift(1); return JavaScriptGrammar::T_GT; - case '<': shift(1); return JavaScriptGrammar::T_LT; - case ',': shift(1); return JavaScriptGrammar::T_COMMA; - case '!': shift(1); return JavaScriptGrammar::T_NOT; - case '~': shift(1); return JavaScriptGrammar::T_TILDE; - case '?': shift(1); return JavaScriptGrammar::T_QUESTION; - case ':': shift(1); return JavaScriptGrammar::T_COLON; - case '.': shift(1); return JavaScriptGrammar::T_DOT; - case '+': shift(1); return JavaScriptGrammar::T_PLUS; - case '-': shift(1); return JavaScriptGrammar::T_MINUS; - case '*': shift(1); return JavaScriptGrammar::T_STAR; - case '/': shift(1); return JavaScriptGrammar::T_DIVIDE_; - case '&': shift(1); return JavaScriptGrammar::T_AND; - case '|': shift(1); return JavaScriptGrammar::T_OR; - case '^': shift(1); return JavaScriptGrammar::T_XOR; - case '%': shift(1); return JavaScriptGrammar::T_REMAINDER; - case '(': shift(1); return JavaScriptGrammar::T_LPAREN; - case ')': shift(1); return JavaScriptGrammar::T_RPAREN; - case '{': shift(1); return JavaScriptGrammar::T_LBRACE; - case '}': shift(1); return JavaScriptGrammar::T_RBRACE; - case '[': shift(1); return JavaScriptGrammar::T_LBRACKET; - case ']': shift(1); return JavaScriptGrammar::T_RBRACKET; - case ';': shift(1); return JavaScriptGrammar::T_SEMICOLON; - - default: return -1; - } -} - -ushort Lexer::singleEscape(ushort c) const -{ - switch(c) { - case 'b': - return 0x08; - case 't': - return 0x09; - case 'n': - return 0x0A; - case 'v': - return 0x0B; - case 'f': - return 0x0C; - case 'r': - return 0x0D; - case '"': - return 0x22; - case '\'': - return 0x27; - case '\\': - return 0x5C; - default: - return c; - } -} - -ushort Lexer::convertOctal(ushort c1, ushort c2, - ushort c3) const -{ - return ((c1 - '0') * 64 + (c2 - '0') * 8 + c3 - '0'); -} - -unsigned char Lexer::convertHex(ushort c) -{ - if (c >= '0' && c <= '9') - return (c - '0'); - else if (c >= 'a' && c <= 'f') - return (c - 'a' + 10); - else - return (c - 'A' + 10); -} - -unsigned char Lexer::convertHex(ushort c1, ushort c2) -{ - return ((convertHex(c1) << 4) + convertHex(c2)); -} - -QChar Lexer::convertUnicode(ushort c1, ushort c2, - ushort c3, ushort c4) -{ - return QChar((convertHex(c3) << 4) + convertHex(c4), - (convertHex(c1) << 4) + convertHex(c2)); -} - -void Lexer::record8(ushort c) -{ - Q_ASSERT(c <= 0xff); - - // enlarge buffer if full - if (pos8 >= size8 - 1) { - char *tmp = new char[2 * size8]; - memcpy(tmp, buffer8, size8 * sizeof(char)); - delete [] buffer8; - buffer8 = tmp; - size8 *= 2; - } - - buffer8[pos8++] = (char) c; -} - -void Lexer::record16(QChar c) -{ - // enlarge buffer if full - if (pos16 >= size16 - 1) { - QChar *tmp = new QChar[2 * size16]; - memcpy(tmp, buffer16, size16 * sizeof(QChar)); - delete [] buffer16; - buffer16 = tmp; - size16 *= 2; - } - - buffer16[pos16++] = c; -} - -void Lexer::recordStartPos() -{ - startpos = pos; - startlineno = yylineno; - startcolumn = yycolumn; -} - -bool Lexer::scanRegExp(RegExpBodyPrefix prefix) -{ - pos16 = 0; - bool lastWasEscape = false; - - if (prefix == EqualPrefix) - record16(QLatin1Char('=')); - - while (1) { - if (isLineTerminator() || current == 0) { - errmsg = QLatin1String("Unterminated regular expression literal"); - return false; - } - else if (current != '/' || lastWasEscape == true) - { - record16(current); - lastWasEscape = !lastWasEscape && (current == '\\'); - } - else { - if (driver) - pattern = driver->intern(buffer16, pos16); - else - pattern = 0; - pos16 = 0; - shift(1); - break; - } - shift(1); - } - - flags = 0; - while (isIdentLetter(current)) { - int flag = Ecma::RegExp::flagFromChar(current); - if (flag == 0) { - errmsg = QString::fromLatin1("Invalid regular expression flag '%0'") - .arg(QChar(current)); - return false; - } - flags |= flag; - record16(current); - shift(1); - } - - return true; -} - -void Lexer::syncProhibitAutomaticSemicolon() -{ - if (parenthesesState == BalancedParentheses) { - // we have seen something like "if (foo)", which means we should - // never insert an automatic semicolon at this point, since it would - // then be expanded into an empty statement (ECMA-262 7.9.1) - prohibitAutomaticSemicolon = true; - parenthesesState = IgnoreParentheses; - } else { - prohibitAutomaticSemicolon = false; - } -} - -QT_END_NAMESPACE - - diff --git a/src/declarative/qml/parser/javascriptlexer_p.h b/src/declarative/qml/parser/javascriptlexer_p.h deleted file mode 100644 index a47c1ae..0000000 --- a/src/declarative/qml/parser/javascriptlexer_p.h +++ /dev/null @@ -1,269 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JAVASCRIPTLEXER_P_H -#define JAVASCRIPTLEXER_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - - - -QT_BEGIN_NAMESPACE - -namespace JavaScript { - -class Engine; -class NameId; - -class Lexer -{ -public: - Lexer(Engine *eng); - ~Lexer(); - - void setCode(const QString &c, int lineno); - int lex(); - - int currentLineNo() const { return yylineno; } - int currentColumnNo() const { return yycolumn; } - - int tokenOffset() const { return startpos; } - int tokenLength() const { return pos - startpos; } - - int startLineNo() const { return startlineno; } - int startColumnNo() const { return startcolumn; } - - int endLineNo() const { return currentLineNo(); } - int endColumnNo() const - { int col = currentColumnNo(); return (col > 0) ? col - 1 : col; } - - bool prevTerminator() const { return terminator; } - - enum State { Start, - Identifier, - InIdentifier, - InSingleLineComment, - InMultiLineComment, - InNum, - InNum0, - InHex, - InOctal, - InDecimal, - InExponentIndicator, - InExponent, - Hex, - Octal, - Number, - String, - Eof, - InString, - InEscapeSequence, - InHexEscape, - InUnicodeEscape, - Other, - Bad }; - - enum Suffix { - noSuffix, - emSuffix, - exSuffix, - pxSuffix, - cmSuffix, - mmSuffix, - inSuffix, - ptSuffix, - pcSuffix, - degSuffix, - radSuffix, - gradSuffix, - msSuffix, - sSuffix, - hzSuffix, - khzSuffix - }; - - enum Error { - NoError, - IllegalCharacter, - UnclosedStringLiteral, - IllegalEscapeSequence, - IllegalUnicodeEscapeSequence, - UnclosedComment, - IllegalExponentIndicator, - IllegalIdentifier - }; - - enum ParenthesesState { - IgnoreParentheses, - CountParentheses, - BalancedParentheses - }; - - enum RegExpBodyPrefix { - NoPrefix, - EqualPrefix - }; - - bool scanRegExp(RegExpBodyPrefix prefix = NoPrefix); - - NameId *pattern; - int flags; - - State lexerState() const - { return state; } - - QString errorMessage() const - { return errmsg; } - void setErrorMessage(const QString &err) - { errmsg = err; } - void setErrorMessage(const char *err) - { setErrorMessage(QString::fromLatin1(err)); } - - Error error() const - { return err; } - void clearError() - { err = NoError; } - -private: - Engine *driver; - int yylineno; - bool done; - char *buffer8; - QChar *buffer16; - uint size8, size16; - uint pos8, pos16; - bool terminator; - bool restrKeyword; - // encountered delimiter like "'" and "}" on last run - bool delimited; - int stackToken; - - State state; - void setDone(State s); - uint pos; - void shift(uint p); - int lookupKeyword(const char *); - - bool isWhiteSpace() const; - bool isLineTerminator() const; - bool isHexDigit(ushort c) const; - bool isOctalDigit(ushort c) const; - - int matchPunctuator(ushort c1, ushort c2, - ushort c3, ushort c4); - ushort singleEscape(ushort c) const; - ushort convertOctal(ushort c1, ushort c2, - ushort c3) const; -public: - static unsigned char convertHex(ushort c1); - static unsigned char convertHex(ushort c1, ushort c2); - static QChar convertUnicode(ushort c1, ushort c2, - ushort c3, ushort c4); - static bool isIdentLetter(ushort c); - static bool isDecimalDigit(ushort c); - - inline int ival() const { return qsyylval.ival; } - inline double dval() const { return qsyylval.dval; } - inline NameId *ustr() const { return qsyylval.ustr; } - - const QChar *characterBuffer() const { return buffer16; } - int characterCount() const { return pos16; } - -private: - void record8(ushort c); - void record16(QChar c); - void recordStartPos(); - - int findReservedWord(const QChar *buffer, int size) const; - - void syncProhibitAutomaticSemicolon(); - - const QChar *code; - uint length; - int yycolumn; - int startpos; - int startlineno; - int startcolumn; - int bol; // begin of line - - union { - int ival; - double dval; - NameId *ustr; - } qsyylval; - - // current and following unicode characters - ushort current, next1, next2, next3; - - struct keyword { - const char *name; - int token; - }; - - QString errmsg; - Error err; - - bool wantRx; - bool check_reserved; - - ParenthesesState parenthesesState; - int parenthesesCount; - bool prohibitAutomaticSemicolon; -}; - -} // namespace JavaScript - -QT_END_NAMESPACE - - - -#endif diff --git a/src/declarative/qml/parser/javascriptmemorypool_p.h b/src/declarative/qml/parser/javascriptmemorypool_p.h deleted file mode 100644 index cff7677..0000000 --- a/src/declarative/qml/parser/javascriptmemorypool_p.h +++ /dev/null @@ -1,130 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JAVASCRIPTMEMORYPOOL_P_H -#define JAVASCRIPTMEMORYPOOL_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace JavaScript { - -class MemoryPool : public QSharedData -{ -public: - enum { maxBlockCount = -1 }; - enum { defaultBlockSize = 1 << 12 }; - - MemoryPool() { - m_blockIndex = maxBlockCount; - m_currentIndex = 0; - m_storage = 0; - m_currentBlock = 0; - m_currentBlockSize = 0; - } - - virtual ~MemoryPool() { - for (int index = 0; index < m_blockIndex + 1; ++index) - qFree(m_storage[index]); - - qFree(m_storage); - } - - char *allocate(int bytes) { - bytes += (8 - bytes) & 7; // ensure multiple of 8 bytes (maintain alignment) - if (m_currentBlock == 0 || m_currentBlockSize < m_currentIndex + bytes) { - ++m_blockIndex; - m_currentBlockSize = defaultBlockSize << m_blockIndex; - - m_storage = reinterpret_cast(qRealloc(m_storage, sizeof(char*) * (1 + m_blockIndex))); - m_currentBlock = m_storage[m_blockIndex] = reinterpret_cast(qMalloc(m_currentBlockSize)); - ::memset(m_currentBlock, 0, m_currentBlockSize); - - m_currentIndex = (8 - quintptr(m_currentBlock)) & 7; // ensure first chunk is 64-bit aligned - Q_ASSERT(m_currentIndex + bytes <= m_currentBlockSize); - } - - char *p = reinterpret_cast - (m_currentBlock + m_currentIndex); - - m_currentIndex += bytes; - - return p; - } - - int bytesAllocated() const { - int bytes = 0; - for (int index = 0; index < m_blockIndex; ++index) - bytes += (defaultBlockSize << index); - bytes += m_currentIndex; - return bytes; - } - -private: - int m_blockIndex; - int m_currentIndex; - char *m_currentBlock; - int m_currentBlockSize; - char **m_storage; - -private: - Q_DISABLE_COPY(MemoryPool) -}; - -} // namespace JavaScript - -QT_END_NAMESPACE - -#endif diff --git a/src/declarative/qml/parser/javascriptnodepool_p.h b/src/declarative/qml/parser/javascriptnodepool_p.h deleted file mode 100644 index cb56fbb..0000000 --- a/src/declarative/qml/parser/javascriptnodepool_p.h +++ /dev/null @@ -1,138 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JAVASCRIPTNODEPOOL_P_H -#define JAVASCRIPTNODEPOOL_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include -#include - -#include "javascriptmemorypool_p.h" - -QT_BEGIN_NAMESPACE - -namespace JavaScript { - -namespace AST { -class Node; -} // namespace AST - -class Code; -class CompilationUnit; -class Engine; - -template -inline NodeType *makeAstNode(MemoryPool *storage) -{ - NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(); - return node; -} - -template -inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1) -{ - NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1); - return node; -} - -template -inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2) -{ - NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2); - return node; -} - -template -inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2, Arg3 arg3) -{ - NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2, arg3); - return node; -} - -template -inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4) -{ - NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2, arg3, arg4); - return node; -} - -class NodePool : public MemoryPool -{ -public: - NodePool(const QString &fileName, Engine *engine); - virtual ~NodePool(); - - Code *createCompiledCode(AST::Node *node, CompilationUnit &compilation); - - inline QString fileName() const { return m_fileName; } - inline Engine *engine() const { return m_engine; } -#ifndef J_SCRIPT_NO_EVENT_NOTIFY - inline qint64 id() const { return m_id; } -#endif - -private: - QHash m_codeCache; - QString m_fileName; - Engine *m_engine; -#ifndef J_SCRIPT_NO_EVENT_NOTIFY - qint64 m_id; -#endif - -private: - Q_DISABLE_COPY(NodePool) -}; - -} // namespace JavaScript - -QT_END_NAMESPACE - -#endif diff --git a/src/declarative/qml/parser/javascriptparser.cpp b/src/declarative/qml/parser/javascriptparser.cpp deleted file mode 100644 index bbffc4f..0000000 --- a/src/declarative/qml/parser/javascriptparser.cpp +++ /dev/null @@ -1,1717 +0,0 @@ -// This file was generated by qlalr - DO NOT EDIT! - -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include - -#include - -#include "javascriptengine_p.h" -#include "javascriptlexer_p.h" -#include "javascriptast_p.h" -#include "javascriptnodepool_p.h" - - - -#include "javascriptparser_p.h" -#include - -// -// This file is automatically generated from javascript.g. -// Changes will be lost. -// - -using namespace JavaScript; - -QT_BEGIN_NAMESPACE - -void Parser::reallocateStack() -{ - if (! stack_size) - stack_size = 128; - else - stack_size <<= 1; - - sym_stack = reinterpret_cast (qRealloc(sym_stack, stack_size * sizeof(Value))); - state_stack = reinterpret_cast (qRealloc(state_stack, stack_size * sizeof(int))); - location_stack = reinterpret_cast (qRealloc(location_stack, stack_size * sizeof(AST::SourceLocation))); -} - -inline static bool automatic(Engine *driver, int token) -{ - return token == JavaScriptGrammar::T_RBRACE - || token == 0 - || driver->lexer()->prevTerminator(); -} - - -Parser::Parser(Engine *engine): - driver(engine), - tos(0), - stack_size(0), - sym_stack(0), - state_stack(0), - location_stack(0), - first_token(0), - last_token(0) -{ -} - -Parser::~Parser() -{ - if (stack_size) { - qFree(sym_stack); - qFree(state_stack); - qFree(location_stack); - } -} - -static inline AST::SourceLocation location(Lexer *lexer) -{ - AST::SourceLocation loc; - loc.offset = lexer->tokenOffset(); - loc.length = lexer->tokenLength(); - loc.startLine = lexer->startLineNo(); - loc.startColumn = lexer->startColumnNo(); - return loc; -} - -AST::UiQualifiedId *Parser::reparseAsQualifiedId(AST::ExpressionNode *expr) -{ - QVarLengthArray nameIds; - QVarLengthArray locations; - - AST::ExpressionNode *it = expr; - while (AST::FieldMemberExpression *m = AST::cast(it)) { - nameIds.append(m->name); - locations.append(m->identifierToken); - it = m->base; - } - - if (AST::IdentifierExpression *idExpr = AST::cast(it)) { - AST::UiQualifiedId *q = makeAstNode(driver->nodePool(), idExpr->name); - q->identifierToken = idExpr->identifierToken; - - AST::UiQualifiedId *currentId = q; - for (int i = nameIds.size() - 1; i != -1; --i) { - currentId = makeAstNode(driver->nodePool(), currentId, nameIds[i]); - currentId->identifierToken = locations[i]; - } - - return currentId->finish(); - } - - return 0; -} - -bool Parser::parse() -{ - Lexer *lexer = driver->lexer(); - bool hadErrors = false; - int yytoken = -1; - int action = 0; - - first_token = last_token = 0; - - tos = -1; - program = 0; - - do { - if (++tos == stack_size) - reallocateStack(); - - state_stack[tos] = action; - - _Lcheck_token: - if (yytoken == -1 && -TERMINAL_COUNT != action_index[action]) { - yyprevlloc = yylloc; - - if (first_token == last_token) { - yytoken = lexer->lex(); - yylval = lexer->dval(); - yylloc = location(lexer); - } else { - yytoken = first_token->token; - yylval = first_token->dval; - yylloc = first_token->loc; - ++first_token; - } - } - - action = t_action(action, yytoken); - if (action > 0) { - if (action != ACCEPT_STATE) { - yytoken = -1; - sym(1).dval = yylval; - loc(1) = yylloc; - } else { - --tos; - return ! hadErrors; - } - } else if (action < 0) { - const int r = -action - 1; - tos -= rhs[r]; - - switch (r) { - -case 0: { - program = makeAstNode (driver->nodePool(), sym(1).UiImportList, - sym(2).UiObjectMemberList->finish()); - sym(1).UiProgram = program; -} break; - -case 2: { - sym(1).Node = sym(1).UiImportList->finish(); -} break; - -case 3: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiImport); -} break; - -case 4: { - sym(1).Node = makeAstNode (driver->nodePool(), - sym(1).UiImportList, sym(2).UiImport); -} break; - -case 6: { - AST::UiImport *node = makeAstNode(driver->nodePool(), sym(2).sval); - node->importToken = loc(1); - node->fileNameToken = loc(2); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; - -case 7: { - sym(1).Node = 0; -} break; - -case 8: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); -} break; - -case 9: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); -} break; - -case 10: { - AST::UiObjectMemberList *node = makeAstNode (driver->nodePool(), - sym(1).UiObjectMemberList, sym(2).UiObjectMember); - sym(1).Node = node; -} break; - -case 11: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); -} break; - -case 12: { - AST::UiArrayMemberList *node = makeAstNode (driver->nodePool(), - sym(1).UiArrayMemberList, sym(3).UiObjectMember); - node->commaToken = loc(2); - sym(1).Node = node; -} break; - -case 13: { - AST::UiObjectInitializer *node = makeAstNode (driver->nodePool(), (AST::UiObjectMemberList*)0); - node->lbraceToken = loc(1); - node->rbraceToken = loc(2); - sym(1).Node = node; -} break; - -case 14: { - AST::UiObjectInitializer *node = makeAstNode (driver->nodePool(), sym(2).UiObjectMemberList->finish()); - node->lbraceToken = loc(1); - node->rbraceToken = loc(3); - sym(1).Node = node; -} break; - -case 15: { - AST::UiObjectDefinition *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), - sym(2).UiObjectInitializer); - sym(1).Node = node; -} break; - -case 17: { - AST::UiArrayBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), - sym(4).UiArrayMemberList->finish()); - node->colonToken = loc(2); - node->lbracketToken = loc(3); - node->rbracketToken = loc(5); - sym(1).Node = node; -} break; - -case 18: { - AST::StringLiteral *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->literalToken = loc(1); - sym(1).Node = node; -} break; - -case 20: { - AST::ExpressionStatement *node = makeAstNode (driver->nodePool(), sym(1).Expression); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; - -case 21: { - if (AST::UiQualifiedId *qualifiedId = reparseAsQualifiedId(sym(3).Expression)) { - AST::UiObjectBinding *node = makeAstNode (driver->nodePool(), - sym(1).UiQualifiedId->finish(), qualifiedId, sym(4).UiObjectInitializer); - node->colonToken = loc(2); - sym(1).Node = node; - } else { - sym(1).Node = 0; - - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc(2), - QLatin1String("Expected a type name after token `:'"))); - - return false; // ### recover - } -} break; -case 22:case 23:case 24:case 25:case 26:case 27: -{ - AST::UiScriptBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), - sym(3).Statement); - node->colonToken = loc(2); - sym(1).Node = node; -} break; - -case 28: - -case 29: { - sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount()); - break; -} - -case 31: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), (NameId *)0, sym(2).sval); - node->type = AST::UiPublicMember::Signal; - node->propertyToken = loc(1); - node->typeToken = loc(2); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; - -case 33: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(3).sval); - node->propertyToken = loc(1); - node->typeToken = loc(2); - node->identifierToken = loc(3); - node->semicolonToken = loc(4); - sym(1).Node = node; -} break; - -case 35: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(4).sval); - node->isDefaultMember = true; - node->defaultToken = loc(1); - node->propertyToken = loc(2); - node->typeToken = loc(3); - node->identifierToken = loc(4); - node->semicolonToken = loc(5); - sym(1).Node = node; -} break; - -case 37: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(3).sval, - sym(5).Expression); - node->propertyToken = loc(1); - node->typeToken = loc(2); - node->identifierToken = loc(3); - node->colonToken = loc(4); - node->semicolonToken = loc(6); - sym(1).Node = node; -} break; - -case 39: { - AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(4).sval, - sym(6).Expression); - node->isDefaultMember = true; - node->defaultToken = loc(1); - node->propertyToken = loc(2); - node->typeToken = loc(3); - node->identifierToken = loc(4); - node->colonToken = loc(5); - node->semicolonToken = loc(7); - sym(1).Node = node; -} break; - -case 40: { - sym(1).Node = makeAstNode(driver->nodePool(), sym(1).Node); -} break; - -case 41: { - sym(1).Node = makeAstNode(driver->nodePool(), sym(1).Node); -} break; -case 42: -case 43: -{ - AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount())); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; - -case 45: { - QString s = QLatin1String(JavaScriptGrammar::spell[T_PROPERTY]); - sym(1).sval = driver->intern(s.constData(), s.length()); - break; -} - -case 46: { - QString s = QLatin1String(JavaScriptGrammar::spell[T_SIGNAL]); - sym(1).sval = driver->intern(s.constData(), s.length()); - break; -} - -case 47: { - AST::ThisExpression *node = makeAstNode (driver->nodePool()); - node->thisToken = loc(1); - sym(1).Node = node; -} break; - -case 48: { - AST::IdentifierExpression *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; - -case 49: { - AST::NullExpression *node = makeAstNode (driver->nodePool()); - node->nullToken = loc(1); - sym(1).Node = node; -} break; - -case 50: { - AST::TrueLiteral *node = makeAstNode (driver->nodePool()); - node->trueToken = loc(1); - sym(1).Node = node; -} break; - -case 51: { - AST::FalseLiteral *node = makeAstNode (driver->nodePool()); - node->falseToken = loc(1); - sym(1).Node = node; -} break; - -case 52: { - AST::NumericLiteral *node = makeAstNode (driver->nodePool(), sym(1).dval, lexer->flags); - node->literalToken = loc(1); - sym(1).Node = node; -} break; - -case 53: { - AST::StringLiteral *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->literalToken = loc(1); - sym(1).Node = node; -} break; - -case 54: { - bool rx = lexer->scanRegExp(Lexer::NoPrefix); - if (!rx) { - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage())); - return false; // ### remove me - } - AST::RegExpLiteral *node = makeAstNode (driver->nodePool(), lexer->pattern, lexer->flags); - node->literalToken = loc(1); - sym(1).Node = node; -} break; - -case 55: { - bool rx = lexer->scanRegExp(Lexer::EqualPrefix); - if (!rx) { - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage())); - return false; - } - AST::RegExpLiteral *node = makeAstNode (driver->nodePool(), lexer->pattern, lexer->flags); - node->literalToken = loc(1); - sym(1).Node = node; -} break; - -case 56: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), (AST::Elision *) 0); - node->lbracketToken = loc(1); - node->rbracketToken = loc(2); - sym(1).Node = node; -} break; - -case 57: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).Elision->finish()); - node->lbracketToken = loc(1); - node->rbracketToken = loc(3); - sym(1).Node = node; -} break; - -case 58: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish ()); - node->lbracketToken = loc(1); - node->rbracketToken = loc(3); - sym(1).Node = node; -} break; - -case 59: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish (), - (AST::Elision *) 0); - node->lbracketToken = loc(1); - node->commaToken = loc(3); - node->rbracketToken = loc(4); - sym(1).Node = node; -} break; - -case 60: { - AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish (), - sym(4).Elision->finish()); - node->lbracketToken = loc(1); - node->commaToken = loc(3); - node->rbracketToken = loc(5); - sym(1).Node = node; -} break; - -case 61: { - AST::ObjectLiteral *node = 0; - if (sym(2).Node) - node = makeAstNode (driver->nodePool(), - sym(2).PropertyNameAndValueList->finish ()); - else - node = makeAstNode (driver->nodePool()); - node->lbraceToken = loc(1); - node->lbraceToken = loc(3); - sym(1).Node = node; -} break; - -case 62: { - AST::ObjectLiteral *node = makeAstNode (driver->nodePool(), - sym(2).PropertyNameAndValueList->finish ()); - node->lbraceToken = loc(1); - node->lbraceToken = loc(4); - sym(1).Node = node; -} break; - -case 63: { - AST::NestedExpression *node = makeAstNode(driver->nodePool(), sym(2).Expression); - node->lparenToken = loc(1); - node->rparenToken = loc(3); - sym(1).Node = node; -} break; - -case 64: { - AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; - -case 65: { - AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId, sym(3).sval); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; - -case 66: { - sym(1).Node = makeAstNode (driver->nodePool(), (AST::Elision *) 0, sym(1).Expression); -} break; - -case 67: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Elision->finish(), sym(2).Expression); -} break; - -case 68: { - AST::ElementList *node = makeAstNode (driver->nodePool(), sym(1).ElementList, - (AST::Elision *) 0, sym(3).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; - -case 69: { - AST::ElementList *node = makeAstNode (driver->nodePool(), sym(1).ElementList, sym(3).Elision->finish(), - sym(4).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; - -case 70: { - AST::Elision *node = makeAstNode (driver->nodePool()); - node->commaToken = loc(1); - sym(1).Node = node; -} break; - -case 71: { - AST::Elision *node = makeAstNode (driver->nodePool(), sym(1).Elision); - node->commaToken = loc(2); - sym(1).Node = node; -} break; - -case 72: { - AST::PropertyNameAndValueList *node = makeAstNode (driver->nodePool(), - sym(1).PropertyName, sym(3).Expression); - node->colonToken = loc(2); - sym(1).Node = node; -} break; - -case 73: { - AST::PropertyNameAndValueList *node = makeAstNode (driver->nodePool(), - sym(1).PropertyNameAndValueList, sym(3).PropertyName, sym(5).Expression); - node->commaToken = loc(2); - node->colonToken = loc(4); - sym(1).Node = node; -} break; - -case 74: { - AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; -case 75: -case 76: { - AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount())); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; - -case 77: { - AST::StringLiteralPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; - -case 78: { - AST::NumericLiteralPropertyName *node = makeAstNode (driver->nodePool(), sym(1).dval); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; - -case 79: { - AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->propertyNameToken = loc(1); - sym(1).Node = node; -} break; - -case 80: - -case 81: - -case 82: - -case 83: - -case 84: - -case 85: - -case 86: - -case 87: - -case 88: - -case 89: - -case 90: - -case 91: - -case 92: - -case 93: - -case 94: - -case 95: - -case 96: - -case 97: - -case 98: - -case 99: - -case 100: - -case 101: - -case 102: - -case 103: - -case 104: - -case 105: - -case 106: - -case 107: - -case 108: - -case 109: - -case 110: -{ - sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount()); -} break; - -case 115: { - AST::ArrayMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); - node->lbracketToken = loc(2); - node->rbracketToken = loc(4); - sym(1).Node = node; -} break; - -case 116: { - AST::FieldMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).sval); - node->dotToken = loc(2); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; - -case 117: { - AST::NewMemberExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression, sym(4).ArgumentList); - node->newToken = loc(1); - node->lparenToken = loc(3); - node->rparenToken = loc(5); - sym(1).Node = node; -} break; - -case 119: { - AST::NewExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->newToken = loc(1); - sym(1).Node = node; -} break; - -case 120: { - AST::CallExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; - -case 121: { - AST::CallExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; - -case 122: { - AST::ArrayMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); - node->lbracketToken = loc(2); - node->rbracketToken = loc(4); - sym(1).Node = node; -} break; - -case 123: { - AST::FieldMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).sval); - node->dotToken = loc(2); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; - -case 124: { - sym(1).Node = 0; -} break; - -case 125: { - sym(1).Node = sym(1).ArgumentList->finish(); -} break; - -case 126: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Expression); -} break; - -case 127: { - AST::ArgumentList *node = makeAstNode (driver->nodePool(), sym(1).ArgumentList, sym(3).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; - -case 131: { - AST::PostIncrementExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression); - node->incrementToken = loc(2); - sym(1).Node = node; -} break; - -case 132: { - AST::PostDecrementExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression); - node->decrementToken = loc(2); - sym(1).Node = node; -} break; - -case 134: { - AST::DeleteExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->deleteToken = loc(1); - sym(1).Node = node; -} break; - -case 135: { - AST::VoidExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->voidToken = loc(1); - sym(1).Node = node; -} break; - -case 136: { - AST::TypeOfExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->typeofToken = loc(1); - sym(1).Node = node; -} break; - -case 137: { - AST::PreIncrementExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->incrementToken = loc(1); - sym(1).Node = node; -} break; - -case 138: { - AST::PreDecrementExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->decrementToken = loc(1); - sym(1).Node = node; -} break; - -case 139: { - AST::UnaryPlusExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->plusToken = loc(1); - sym(1).Node = node; -} break; - -case 140: { - AST::UnaryMinusExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->minusToken = loc(1); - sym(1).Node = node; -} break; - -case 141: { - AST::TildeExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->tildeToken = loc(1); - sym(1).Node = node; -} break; - -case 142: { - AST::NotExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->notToken = loc(1); - sym(1).Node = node; -} break; - -case 144: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Mul, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 145: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Div, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 146: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Mod, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 148: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Add, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 149: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Sub, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 151: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::LShift, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 152: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::RShift, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 153: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::URShift, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 155: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Lt, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 156: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Gt, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 157: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Le, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 158: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Ge, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 159: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::InstanceOf, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 160: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::In, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 162: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Lt, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 163: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Gt, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 164: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Le, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 165: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Ge, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 166: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::InstanceOf, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 168: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Equal, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 169: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::NotEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 170: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::StrictEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 171: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::StrictNotEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 173: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Equal, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 174: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::NotEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 175: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::StrictEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 176: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::StrictNotEqual, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 178: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitAnd, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 180: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitAnd, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 182: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitXor, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 184: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitXor, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 186: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitOr, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 188: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::BitOr, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 190: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::And, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 192: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::And, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 194: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Or, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 196: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - QSOperator::Or, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 198: { - AST::ConditionalExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - sym(3).Expression, sym(5).Expression); - node->questionToken = loc(2); - node->colonToken = loc(4); - sym(1).Node = node; -} break; - -case 200: { - AST::ConditionalExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - sym(3).Expression, sym(5).Expression); - node->questionToken = loc(2); - node->colonToken = loc(4); - sym(1).Node = node; -} break; - -case 202: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - sym(2).ival, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 204: { - AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, - sym(2).ival, sym(3).Expression); - node->operatorToken = loc(2); - sym(1).Node = node; -} break; - -case 205: { - sym(1).ival = QSOperator::Assign; -} break; - -case 206: { - sym(1).ival = QSOperator::InplaceMul; -} break; - -case 207: { - sym(1).ival = QSOperator::InplaceDiv; -} break; - -case 208: { - sym(1).ival = QSOperator::InplaceMod; -} break; - -case 209: { - sym(1).ival = QSOperator::InplaceAdd; -} break; - -case 210: { - sym(1).ival = QSOperator::InplaceSub; -} break; - -case 211: { - sym(1).ival = QSOperator::InplaceLeftShift; -} break; - -case 212: { - sym(1).ival = QSOperator::InplaceRightShift; -} break; - -case 213: { - sym(1).ival = QSOperator::InplaceURightShift; -} break; - -case 214: { - sym(1).ival = QSOperator::InplaceAnd; -} break; - -case 215: { - sym(1).ival = QSOperator::InplaceXor; -} break; - -case 216: { - sym(1).ival = QSOperator::InplaceOr; -} break; - -case 218: { - AST::Expression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; - -case 219: { - sym(1).Node = 0; -} break; - -case 222: { - AST::Expression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); - node->commaToken = loc(2); - sym(1).Node = node; -} break; - -case 223: { - sym(1).Node = 0; -} break; - -case 240: { - AST::Block *node = makeAstNode (driver->nodePool(), sym(2).StatementList); - node->lbraceToken = loc(1); - node->rbraceToken = loc(3); - sym(1).Node = node; -} break; - -case 241: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Statement); -} break; - -case 242: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).StatementList, sym(2).Statement); -} break; - -case 243: { - sym(1).Node = 0; -} break; - -case 244: { - sym(1).Node = sym(1).StatementList->finish (); -} break; - -case 246: { - AST::VariableStatement *node = makeAstNode (driver->nodePool(), - sym(2).VariableDeclarationList->finish (/*readOnly=*/sym(1).ival == T_CONST)); - node->declarationKindToken = loc(1); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; - -case 247: { - sym(1).ival = T_CONST; -} break; - -case 248: { - sym(1).ival = T_VAR; -} break; - -case 249: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclaration); -} break; - -case 250: { - AST::VariableDeclarationList *node = makeAstNode (driver->nodePool(), - sym(1).VariableDeclarationList, sym(3).VariableDeclaration); - node->commaToken = loc(2); - sym(1).Node = node; -} break; - -case 251: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclaration); -} break; - -case 252: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclarationList, sym(3).VariableDeclaration); -} break; - -case 253: { - AST::VariableDeclaration *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(2).Expression); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; - -case 254: { - AST::VariableDeclaration *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(2).Expression); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; - -case 255: { - // ### TODO: AST for initializer - sym(1) = sym(2); -} break; - -case 256: { - sym(1).Node = 0; -} break; - -case 258: { - // ### TODO: AST for initializer - sym(1) = sym(2); -} break; - -case 259: { - sym(1).Node = 0; -} break; - -case 261: { - AST::EmptyStatement *node = makeAstNode (driver->nodePool()); - node->semicolonToken = loc(1); - sym(1).Node = node; -} break; - -case 263: { - AST::ExpressionStatement *node = makeAstNode (driver->nodePool(), sym(1).Expression); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; - -case 264: { - AST::IfStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement, sym(7).Statement); - node->ifToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - node->elseToken = loc(5); - sym(1).Node = node; -} break; - -case 265: { - AST::IfStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); - node->ifToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; - -case 267: { - AST::DoWhileStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(5).Expression); - node->doToken = loc(1); - node->whileToken = loc(3); - node->lparenToken = loc(4); - node->rparenToken = loc(6); - node->semicolonToken = loc(7); - sym(1).Node = node; -} break; - -case 268: { - AST::WhileStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); - node->whileToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; - -case 269: { - AST::ForStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, - sym(5).Expression, sym(7).Expression, sym(9).Statement); - node->forToken = loc(1); - node->lparenToken = loc(2); - node->firstSemicolonToken = loc(4); - node->secondSemicolonToken = loc(6); - node->rparenToken = loc(8); - sym(1).Node = node; -} break; - -case 270: { - AST::LocalForStatement *node = makeAstNode (driver->nodePool(), - sym(4).VariableDeclarationList->finish (/*readOnly=*/false), sym(6).Expression, - sym(8).Expression, sym(10).Statement); - node->forToken = loc(1); - node->lparenToken = loc(2); - node->varToken = loc(3); - node->firstSemicolonToken = loc(5); - node->secondSemicolonToken = loc(7); - node->rparenToken = loc(9); - sym(1).Node = node; -} break; - -case 271: { - AST:: ForEachStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, - sym(5).Expression, sym(7).Statement); - node->forToken = loc(1); - node->lparenToken = loc(2); - node->inToken = loc(4); - node->rparenToken = loc(6); - sym(1).Node = node; -} break; - -case 272: { - AST::LocalForEachStatement *node = makeAstNode (driver->nodePool(), - sym(4).VariableDeclaration, sym(6).Expression, sym(8).Statement); - node->forToken = loc(1); - node->lparenToken = loc(2); - node->varToken = loc(3); - node->inToken = loc(5); - node->rparenToken = loc(7); - sym(1).Node = node; -} break; - -case 274: { - AST::ContinueStatement *node = makeAstNode (driver->nodePool()); - node->continueToken = loc(1); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; - -case 276: { - AST::ContinueStatement *node = makeAstNode (driver->nodePool(), sym(2).sval); - node->continueToken = loc(1); - node->identifierToken = loc(2); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; - -case 278: { - AST::BreakStatement *node = makeAstNode (driver->nodePool()); - node->breakToken = loc(1); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; - -case 280: { - AST::BreakStatement *node = makeAstNode (driver->nodePool(), sym(2).sval); - node->breakToken = loc(1); - node->identifierToken = loc(2); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; - -case 282: { - AST::ReturnStatement *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->returnToken = loc(1); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; - -case 283: { - AST::WithStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); - node->withToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; - -case 284: { - AST::SwitchStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).CaseBlock); - node->switchToken = loc(1); - node->lparenToken = loc(2); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; - -case 285: { - AST::CaseBlock *node = makeAstNode (driver->nodePool(), sym(2).CaseClauses); - node->lbraceToken = loc(1); - node->rbraceToken = loc(3); - sym(1).Node = node; -} break; - -case 286: { - AST::CaseBlock *node = makeAstNode (driver->nodePool(), sym(2).CaseClauses, sym(3).DefaultClause, sym(4).CaseClauses); - node->lbraceToken = loc(1); - node->rbraceToken = loc(5); - sym(1).Node = node; -} break; - -case 287: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).CaseClause); -} break; - -case 288: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).CaseClauses, sym(2).CaseClause); -} break; - -case 289: { - sym(1).Node = 0; -} break; - -case 290: { - sym(1).Node = sym(1).CaseClauses->finish (); -} break; - -case 291: { - AST::CaseClause *node = makeAstNode (driver->nodePool(), sym(2).Expression, sym(4).StatementList); - node->caseToken = loc(1); - node->colonToken = loc(3); - sym(1).Node = node; -} break; - -case 292: { - AST::DefaultClause *node = makeAstNode (driver->nodePool(), sym(3).StatementList); - node->defaultToken = loc(1); - node->colonToken = loc(2); - sym(1).Node = node; -} break; -case 293: -case 294: { - AST::LabelledStatement *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount()), sym(3).Statement); - node->identifierToken = loc(1); - node->colonToken = loc(2); - sym(1).Node = node; -} break; - -case 295: { - AST::LabelledStatement *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(3).Statement); - node->identifierToken = loc(1); - node->colonToken = loc(2); - sym(1).Node = node; -} break; - -case 297: { - AST::ThrowStatement *node = makeAstNode (driver->nodePool(), sym(2).Expression); - node->throwToken = loc(1); - node->semicolonToken = loc(3); - sym(1).Node = node; -} break; - -case 298: { - AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Catch); - node->tryToken = loc(1); - sym(1).Node = node; -} break; - -case 299: { - AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Finally); - node->tryToken = loc(1); - sym(1).Node = node; -} break; - -case 300: { - AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Catch, sym(4).Finally); - node->tryToken = loc(1); - sym(1).Node = node; -} break; - -case 301: { - AST::Catch *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(5).Block); - node->catchToken = loc(1); - node->lparenToken = loc(2); - node->identifierToken = loc(3); - node->rparenToken = loc(4); - sym(1).Node = node; -} break; - -case 302: { - AST::Finally *node = makeAstNode (driver->nodePool(), sym(2).Block); - node->finallyToken = loc(1); - sym(1).Node = node; -} break; - -case 304: { - AST::DebuggerStatement *node = makeAstNode (driver->nodePool()); - node->debuggerToken = loc(1); - node->semicolonToken = loc(2); - sym(1).Node = node; -} break; - -case 305: { - AST::FunctionDeclaration *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody); - node->functionToken = loc(1); - node->identifierToken = loc(2); - node->lparenToken = loc(3); - node->rparenToken = loc(5); - node->lbraceToken = loc(6); - node->rbraceToken = loc(8); - sym(1).Node = node; -} break; - -case 306: { - AST::FunctionExpression *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody); - node->functionToken = loc(1); - if (sym(2).sval) - node->identifierToken = loc(2); - node->lparenToken = loc(3); - node->rparenToken = loc(5); - node->lbraceToken = loc(6); - node->rbraceToken = loc(8); - sym(1).Node = node; -} break; - -case 307: { - AST::FormalParameterList *node = makeAstNode (driver->nodePool(), sym(1).sval); - node->identifierToken = loc(1); - sym(1).Node = node; -} break; - -case 308: { - AST::FormalParameterList *node = makeAstNode (driver->nodePool(), sym(1).FormalParameterList, sym(3).sval); - node->commaToken = loc(2); - node->identifierToken = loc(3); - sym(1).Node = node; -} break; - -case 309: { - sym(1).Node = 0; -} break; - -case 310: { - sym(1).Node = sym(1).FormalParameterList->finish (); -} break; - -case 311: { - sym(1).Node = 0; -} break; - -case 313: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements->finish ()); -} break; - -case 314: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElement); -} break; - -case 315: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements, sym(2).SourceElement); -} break; - -case 316: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Statement); -} break; - -case 317: { - sym(1).Node = makeAstNode (driver->nodePool(), sym(1).FunctionDeclaration); -} break; - -case 318: { - sym(1).sval = 0; -} break; - -case 320: { - sym(1).Node = 0; -} break; - - } // switch - action = nt_action(state_stack[tos], lhs[r] - TERMINAL_COUNT); - } // if - } while (action != 0); - - if (first_token == last_token) { - const int errorState = state_stack[tos]; - - // automatic insertion of `;' - if (t_action(errorState, T_AUTOMATIC_SEMICOLON) && automatic(driver, yytoken)) { - SavedToken &tk = token_buffer[0]; - tk.token = yytoken; - tk.dval = yylval; - tk.loc = yylloc; - - yylloc = yyprevlloc; - yylloc.offset += yylloc.length; - yylloc.startColumn += yylloc.length; - yylloc.length = 0; - - //const QString msg = QString::fromUtf8("Missing `;'"); - //diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, yylloc, msg)); - - first_token = &token_buffer[0]; - last_token = &token_buffer[1]; - - yytoken = T_SEMICOLON; - yylval = 0; - - action = errorState; - - goto _Lcheck_token; - } - - hadErrors = true; - - token_buffer[0].token = yytoken; - token_buffer[0].dval = yylval; - token_buffer[0].loc = yylloc; - - token_buffer[1].token = yytoken = lexer->lex(); - token_buffer[1].dval = yylval = lexer->dval(); - token_buffer[1].loc = yylloc = location(lexer); - - if (t_action(errorState, yytoken)) { - const QString msg = QString::fromUtf8("Unexpected token `%1'").arg(QLatin1String(spell[token_buffer[0].token])); - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); - - action = errorState; - goto _Lcheck_token; - } - - static int tokens[] = { - T_PLUS, - T_EQ, - - T_COMMA, - T_COLON, - T_SEMICOLON, - - T_RPAREN, T_RBRACKET, T_RBRACE, - - T_NUMERIC_LITERAL, - T_IDENTIFIER, - - T_LPAREN, T_LBRACKET, T_LBRACE, - - EOF_SYMBOL - }; - - for (int *tk = tokens; *tk != EOF_SYMBOL; ++tk) { - int a = t_action(errorState, *tk); - if (a > 0 && t_action(a, yytoken)) { - const QString msg = QString::fromUtf8("Expected token `%1'").arg(QLatin1String(spell[*tk])); - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); - - yytoken = *tk; - yylval = 0; - yylloc = token_buffer[0].loc; - yylloc.length = 0; - - first_token = &token_buffer[0]; - last_token = &token_buffer[2]; - - action = errorState; - goto _Lcheck_token; - } - } - - for (int tk = 1; tk < TERMINAL_COUNT; ++tk) { - if (tk == T_AUTOMATIC_SEMICOLON) - continue; - - int a = t_action(errorState, tk); - if (a > 0 && t_action(a, yytoken)) { - const QString msg = QString::fromUtf8("Expected token `%1'").arg(QLatin1String(spell[tk])); - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); - - yytoken = tk; - yylval = 0; - yylloc = token_buffer[0].loc; - yylloc.length = 0; - - action = errorState; - goto _Lcheck_token; - } - } - - const QString msg = QString::fromUtf8("Syntax error"); - diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); - } - - return false; -} - -QT_END_NAMESPACE - - diff --git a/src/declarative/qml/parser/javascriptparser_p.h b/src/declarative/qml/parser/javascriptparser_p.h deleted file mode 100644 index b6a2432..0000000 --- a/src/declarative/qml/parser/javascriptparser_p.h +++ /dev/null @@ -1,208 +0,0 @@ -// This file was generated by qlalr - DO NOT EDIT! - -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -// -// This file is automatically generated from javascript.g. -// Changes will be lost. -// - -#ifndef JAVASCRIPTPARSER_P_H -#define JAVASCRIPTPARSER_P_H - -#include "javascriptgrammar_p.h" -#include "javascriptast_p.h" -#include "javascriptengine_p.h" - -#include - -QT_BEGIN_NAMESPACE - -class QString; - -namespace JavaScript { - -class Engine; -class NameId; - -class Parser: protected JavaScriptGrammar -{ -public: - union Value { - int ival; - double dval; - NameId *sval; - AST::ArgumentList *ArgumentList; - AST::CaseBlock *CaseBlock; - AST::CaseClause *CaseClause; - AST::CaseClauses *CaseClauses; - AST::Catch *Catch; - AST::DefaultClause *DefaultClause; - AST::ElementList *ElementList; - AST::Elision *Elision; - AST::ExpressionNode *Expression; - AST::Finally *Finally; - AST::FormalParameterList *FormalParameterList; - AST::FunctionBody *FunctionBody; - AST::FunctionDeclaration *FunctionDeclaration; - AST::Node *Node; - AST::PropertyName *PropertyName; - AST::PropertyNameAndValueList *PropertyNameAndValueList; - AST::SourceElement *SourceElement; - AST::SourceElements *SourceElements; - AST::Statement *Statement; - AST::StatementList *StatementList; - AST::Block *Block; - AST::VariableDeclaration *VariableDeclaration; - AST::VariableDeclarationList *VariableDeclarationList; - - AST::UiProgram *UiProgram; - AST::UiImportList *UiImportList; - AST::UiImport *UiImport; - AST::UiPublicMember *UiPublicMember; - AST::UiObjectDefinition *UiObjectDefinition; - AST::UiObjectInitializer *UiObjectInitializer; - AST::UiObjectBinding *UiObjectBinding; - AST::UiScriptBinding *UiScriptBinding; - AST::UiArrayBinding *UiArrayBinding; - AST::UiObjectMember *UiObjectMember; - AST::UiObjectMemberList *UiObjectMemberList; - AST::UiArrayMemberList *UiArrayMemberList; - AST::UiQualifiedId *UiQualifiedId; - }; - -public: - Parser(Engine *engine); - ~Parser(); - - bool parse(); - - AST::UiProgram *ast() - { return program; } - - QList diagnosticMessages() const - { return diagnostic_messages; } - - inline DiagnosticMessage diagnosticMessage() const - { - foreach (const DiagnosticMessage &d, diagnostic_messages) { - if (! d.kind == DiagnosticMessage::Warning) - return d; - } - - return DiagnosticMessage(); - } - - inline QString errorMessage() const - { return diagnosticMessage().message; } - - inline int errorLineNumber() const - { return diagnosticMessage().loc.startLine; } - - inline int errorColumnNumber() const - { return diagnosticMessage().loc.startColumn; } - -protected: - void reallocateStack(); - - inline Value &sym(int index) - { return sym_stack [tos + index - 1]; } - - inline AST::SourceLocation &loc(int index) - { return location_stack [tos + index - 1]; } - - AST::UiQualifiedId *reparseAsQualifiedId(AST::ExpressionNode *expr); - -protected: - Engine *driver; - int tos; - int stack_size; - Value *sym_stack; - int *state_stack; - AST::SourceLocation *location_stack; - - AST::UiProgram *program; - - // error recovery - enum { TOKEN_BUFFER_SIZE = 3 }; - - struct SavedToken { - int token; - double dval; - AST::SourceLocation loc; - }; - - double yylval; - AST::SourceLocation yylloc; - AST::SourceLocation yyprevlloc; - - SavedToken token_buffer[TOKEN_BUFFER_SIZE]; - SavedToken *first_token; - SavedToken *last_token; - - QList diagnostic_messages; -}; - -} // end of namespace JavaScript - - - -#define J_SCRIPT_REGEXPLITERAL_RULE1 54 - -#define J_SCRIPT_REGEXPLITERAL_RULE2 55 - -QT_END_NAMESPACE - - - -#endif // JAVASCRIPTPARSER_P_H diff --git a/src/declarative/qml/parser/javascriptprettypretty.cpp b/src/declarative/qml/parser/javascriptprettypretty.cpp deleted file mode 100644 index 0342b39..0000000 --- a/src/declarative/qml/parser/javascriptprettypretty.cpp +++ /dev/null @@ -1,1334 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#include "javascriptprettypretty_p.h" - - - -#include "javascriptengine_p.h" - - - - -#include "javascriptast_p.h" - -#include -#include -#include - -QT_BEGIN_NAMESPACE - -namespace JavaScript { -QString numberToString(double value); -} - -using namespace JavaScript; - -PrettyPretty::PrettyPretty(QTextStream &o): - out(o), m_indentLevel(0) -{ -} - -PrettyPretty::~PrettyPretty() -{ -} - -void PrettyPretty::acceptAsBlock(AST::Node *node) -{ - out << "{"; - pushIndentLevel(); - newlineAndIndent(); - accept(node); - popIndentLevel(); - newlineAndIndent(); - out << "}"; -} - -int PrettyPretty::operatorPrecedenceLevel(int op) -{ - switch (op) { - case QSOperator::Div: - case QSOperator::Mod: - case QSOperator::Mul: - return 5; - case QSOperator::Add: - case QSOperator::Sub: - return 6; - case QSOperator::LShift: - case QSOperator::RShift: - case QSOperator::URShift: - return 7; - case QSOperator::Ge: - case QSOperator::Gt: - case QSOperator::In: - case QSOperator::InstanceOf: - case QSOperator::Le: - case QSOperator::Lt: - return 8; - case QSOperator::Equal: - case QSOperator::NotEqual: - case QSOperator::StrictEqual: - case QSOperator::StrictNotEqual: - return 9; - case QSOperator::BitAnd: - return 10; - case QSOperator::BitXor: - return 11; - case QSOperator::BitOr: - return 12; - case QSOperator::And: - return 13; - case QSOperator::Or: - return 14; - case QSOperator::InplaceAnd: - case QSOperator::InplaceSub: - case QSOperator::InplaceDiv: - case QSOperator::InplaceAdd: - case QSOperator::InplaceLeftShift: - case QSOperator::InplaceMod: - case QSOperator::InplaceMul: - case QSOperator::InplaceOr: - case QSOperator::InplaceRightShift: - case QSOperator::InplaceURightShift: - case QSOperator::InplaceXor: - case QSOperator::Assign: - return 16; - default: - Q_ASSERT_X(false, "PrettyPretty::operatorPrecedenceLevel()", "bad operator"); - } - return 0; -} - -int PrettyPretty::compareOperatorPrecedence(int op1, int op2) -{ - int prec1 = operatorPrecedenceLevel(op1); - int prec2 = operatorPrecedenceLevel(op2); - if (prec1 == prec2) - return 0; - if (prec1 > prec2) - return -1; - return 1; -} - -QTextStream &PrettyPretty::operator () (AST::Node *node, int level) -{ - int was = indentLevel(level); - accept(node); - indentLevel(was); - return out; -} - -QTextStream &PrettyPretty::newlineAndIndent() -{ - enum { IND = 4 }; - out << endl << QString().fill(QLatin1Char(' '), m_indentLevel * IND); - return out; -} - -void PrettyPretty::accept(AST::Node *node) -{ - AST::Node::acceptChild(node, this); -} - -bool PrettyPretty::visit(AST::ThisExpression *node) -{ - Q_UNUSED(node); - out << "this"; - return true; -} - -void PrettyPretty::endVisit(AST::ThisExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::IdentifierExpression *node) -{ - out << Engine::toString(node->name); - return true; -} - -void PrettyPretty::endVisit(AST::IdentifierExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::NullExpression *node) -{ - Q_UNUSED(node); - out << "null"; - return false; -} - -void PrettyPretty::endVisit(AST::NullExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::TrueLiteral *node) -{ - Q_UNUSED(node); - out << "true"; - return false; -} - -void PrettyPretty::endVisit(AST::TrueLiteral *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::FalseLiteral *node) -{ - Q_UNUSED(node); - out << "false"; - return false; -} - -void PrettyPretty::endVisit(AST::FalseLiteral *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::StringLiteral *node) -{ - QString lit = Engine::toString(node->value); - lit.replace(QLatin1String("\\"), QLatin1String("\\\\")); - out << "\"" << lit << "\""; - return false; -} - -void PrettyPretty::endVisit(AST::StringLiteral *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::NumericLiteral *node) -{ - out << JavaScript::numberToString(node->value); - return true; -} - -void PrettyPretty::endVisit(AST::NumericLiteral *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::RegExpLiteral *node) -{ - out << "/" << Engine::toString(node->pattern) << "/"; - if (node->flags) - out << JavaScript::Ecma::RegExp::flagsToString(node->flags); - - return true; -} - -void PrettyPretty::endVisit(AST::RegExpLiteral *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ArrayLiteral *node) -{ - out << "["; - accept(node->elements); - accept(node->elision); - out << "]"; - return false; -} - -void PrettyPretty::endVisit(AST::ArrayLiteral *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ObjectLiteral *node) -{ - out << "{"; - if (node->properties) { - pushIndentLevel(); - AST::PropertyNameAndValueList *prop; - for (prop = node->properties; prop != 0; prop = prop->next) { - newlineAndIndent(); - accept(prop); - if (prop->next) - out << ","; - } - popIndentLevel(); - newlineAndIndent(); - } - out << "}"; - return false; -} - -void PrettyPretty::endVisit(AST::ObjectLiteral *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ElementList *node) -{ - accept(node->elision); - accept(node->expression); - for (node = node->next; node != 0; node = node->next) { - out << ", "; - accept(node->elision); - accept(node->expression); - } - return false; -} - -void PrettyPretty::endVisit(AST::ElementList *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::Elision *node) -{ - out << ", "; - for (AST::Elision *eit = node->next; eit != 0; eit = eit->next) - out << ", "; - return false; -} - -void PrettyPretty::endVisit(AST::Elision *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::PropertyNameAndValueList *node) -{ - accept(node->name); - out << ": "; - accept(node->value); - return false; -} - -void PrettyPretty::endVisit(AST::PropertyNameAndValueList *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::IdentifierPropertyName *node) -{ - out << Engine::toString(node->id); - return false; -} - -void PrettyPretty::endVisit(AST::IdentifierPropertyName *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::StringLiteralPropertyName *node) -{ - QString lit = Engine::toString(node->id); - lit.replace(QLatin1String("\\"), QLatin1String("\\\\")); - out << lit; - return false; -} - -void PrettyPretty::endVisit(AST::StringLiteralPropertyName *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::NumericLiteralPropertyName *node) -{ - out << node->id; - return false; -} - -void PrettyPretty::endVisit(AST::NumericLiteralPropertyName *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ArrayMemberExpression *node) -{ - accept(node->base); - out << "["; - accept(node->expression); - out << "]"; - return false; -} - -void PrettyPretty::endVisit(AST::ArrayMemberExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::FieldMemberExpression *node) -{ - accept(node->base); - out << "." << Engine::toString(node->name); - return false; -} - -void PrettyPretty::endVisit(AST::FieldMemberExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::NewMemberExpression *node) -{ - out << "new "; - accept(node->base); - out << "("; - accept(node->arguments); - out << ")"; - return false; -} - -void PrettyPretty::endVisit(AST::NewMemberExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::NewExpression *node) -{ - Q_UNUSED(node); - out << "new "; - return true; -} - -void PrettyPretty::endVisit(AST::NewExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::CallExpression *node) -{ - accept(node->base); - out << "("; - accept(node->arguments); - out << ")"; - return false; -} - -void PrettyPretty::endVisit(AST::CallExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ArgumentList *node) -{ - accept(node->expression); - for (node = node->next; node != 0; node = node->next) { - out << ", "; - accept(node->expression); - } - return false; -} - -void PrettyPretty::endVisit(AST::ArgumentList *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::PostIncrementExpression *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::PostIncrementExpression *node) -{ - Q_UNUSED(node); - out << "++"; -} - -bool PrettyPretty::visit(AST::PostDecrementExpression *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::PostDecrementExpression *node) -{ - Q_UNUSED(node); - out << "--"; -} - -bool PrettyPretty::visit(AST::DeleteExpression *node) -{ - Q_UNUSED(node); - out << "delete "; - return true; -} - -void PrettyPretty::endVisit(AST::DeleteExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::VoidExpression *node) -{ - Q_UNUSED(node); - out << "void "; - return true; -} - -void PrettyPretty::endVisit(AST::VoidExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::TypeOfExpression *node) -{ - Q_UNUSED(node); - out << "typeof "; - return true; -} - -void PrettyPretty::endVisit(AST::TypeOfExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::PreIncrementExpression *node) -{ - Q_UNUSED(node); - out << "++"; - return true; -} - -void PrettyPretty::endVisit(AST::PreIncrementExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::PreDecrementExpression *node) -{ - Q_UNUSED(node); - out << "--"; - return true; -} - -void PrettyPretty::endVisit(AST::PreDecrementExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::UnaryPlusExpression *node) -{ - out << "+"; - bool needParens = (node->expression->binaryExpressionCast() != 0); - if (needParens) - out << "("; - accept(node->expression); - if (needParens) - out << ")"; - return false; -} - -void PrettyPretty::endVisit(AST::UnaryPlusExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::UnaryMinusExpression *node) -{ - out << "-"; - bool needParens = (node->expression->binaryExpressionCast() != 0); - if (needParens) - out << "("; - accept(node->expression); - if (needParens) - out << ")"; - return false; -} - -void PrettyPretty::endVisit(AST::UnaryMinusExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::TildeExpression *node) -{ - out << "~"; - bool needParens = (node->expression->binaryExpressionCast() != 0); - if (needParens) - out << "("; - accept(node->expression); - if (needParens) - out << ")"; - return false; -} - -void PrettyPretty::endVisit(AST::TildeExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::NotExpression *node) -{ - out << "!"; - bool needParens = (node->expression->binaryExpressionCast() != 0); - if (needParens) - out << "("; - accept(node->expression); - if (needParens) - out << ")"; - return false; -} - -void PrettyPretty::endVisit(AST::NotExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::BinaryExpression *node) -{ - bool needParens = node->left->binaryExpressionCast() - && (compareOperatorPrecedence(node->left->binaryExpressionCast()->op, node->op) < 0); - if (needParens) - out << "("; - accept(node->left); - if (needParens) - out << ")"; - QString s; - switch (node->op) { - case QSOperator::Add: - s = QLatin1String("+"); break; - case QSOperator::And: - s = QLatin1String("&&"); break; - case QSOperator::InplaceAnd: - s = QLatin1String("&="); break; - case QSOperator::Assign: - s = QLatin1String("="); break; - case QSOperator::BitAnd: - s = QLatin1String("&"); break; - case QSOperator::BitOr: - s = QLatin1String("|"); break; - case QSOperator::BitXor: - s = QLatin1String("^"); break; - case QSOperator::InplaceSub: - s = QLatin1String("-="); break; - case QSOperator::Div: - s = QLatin1String("/"); break; - case QSOperator::InplaceDiv: - s = QLatin1String("/="); break; - case QSOperator::Equal: - s = QLatin1String("=="); break; - case QSOperator::Ge: - s = QLatin1String(">="); break; - case QSOperator::Gt: - s = QLatin1String(">"); break; - case QSOperator::In: - s = QLatin1String("in"); break; - case QSOperator::InplaceAdd: - s = QLatin1String("+="); break; - case QSOperator::InstanceOf: - s = QLatin1String("instanceof"); break; - case QSOperator::Le: - s = QLatin1String("<="); break; - case QSOperator::LShift: - s = QLatin1String("<<"); break; - case QSOperator::InplaceLeftShift: - s = QLatin1String("<<="); break; - case QSOperator::Lt: - s = QLatin1String("<"); break; - case QSOperator::Mod: - s = QLatin1String("%"); break; - case QSOperator::InplaceMod: - s = QLatin1String("%="); break; - case QSOperator::Mul: - s = QLatin1String("*"); break; - case QSOperator::InplaceMul: - s = QLatin1String("*="); break; - case QSOperator::NotEqual: - s = QLatin1String("!="); break; - case QSOperator::Or: - s = QLatin1String("||"); break; - case QSOperator::InplaceOr: - s = QLatin1String("|="); break; - case QSOperator::RShift: - s = QLatin1String(">>"); break; - case QSOperator::InplaceRightShift: - s = QLatin1String(">>="); break; - case QSOperator::StrictEqual: - s = QLatin1String("==="); break; - case QSOperator::StrictNotEqual: - s = QLatin1String("!=="); break; - case QSOperator::Sub: - s = QLatin1String("-"); break; - case QSOperator::URShift: - s = QLatin1String(">>>"); break; - case QSOperator::InplaceURightShift: - s = QLatin1String(">>>="); break; - case QSOperator::InplaceXor: - s = QLatin1String("^="); break; - default: - Q_ASSERT (0); - } - out << " " << s << " "; - needParens = node->right->binaryExpressionCast() - && (compareOperatorPrecedence(node->right->binaryExpressionCast()->op, node->op) <= 0); - if (needParens) - out << "("; - accept(node->right); - if (needParens) - out << ")"; - return false; -} - -void PrettyPretty::endVisit(AST::BinaryExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ConditionalExpression *node) -{ - accept(node->expression); - out << " ? "; - accept(node->ok); - out << " : "; - accept(node->ko); - return false; -} - -void PrettyPretty::endVisit(AST::ConditionalExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::Expression *node) -{ - accept(node->left); - out << ", "; - accept(node->right); - return false; -} - -void PrettyPretty::endVisit(AST::Expression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::Block *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::Block *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::StatementList *node) -{ - accept(node->statement); - for (node = node->next; node != 0; node = node->next) { - newlineAndIndent(); - accept(node->statement); - } - return false; -} - -void PrettyPretty::endVisit(AST::StatementList *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::VariableDeclarationList *node) -{ - AST::VariableDeclarationList *it = node; - - do { - it->declaration->accept(this); - it = it->next; - if (it) - out << ", "; - } while (it); - - return false; -} - -void PrettyPretty::endVisit(AST::VariableDeclarationList *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::VariableStatement *node) -{ - out << "var "; - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::VariableStatement *node) -{ - Q_UNUSED(node); - out << ";"; -} - -bool PrettyPretty::visit(AST::VariableDeclaration *node) -{ - out << Engine::toString(node->name); - if (node->expression) { - out << " = "; - accept(node->expression); - } - return false; -} - -void PrettyPretty::endVisit(AST::VariableDeclaration *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::EmptyStatement *node) -{ - Q_UNUSED(node); - out << ";"; - return true; -} - -void PrettyPretty::endVisit(AST::EmptyStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ExpressionStatement *node) -{ - accept(node->expression); - out << ";"; - return false; -} - -void PrettyPretty::endVisit(AST::ExpressionStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::IfStatement *node) -{ - out << "if ("; - accept(node->expression); - out << ") "; - acceptAsBlock(node->ok); - if (node->ko) { - out << " else "; - acceptAsBlock(node->ko); - } - return false; -} - -void PrettyPretty::endVisit(AST::IfStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::DoWhileStatement *node) -{ - out << "do "; - acceptAsBlock(node->statement); - out << " while ("; - accept(node->expression); - out << ");"; - return false; -} - -void PrettyPretty::endVisit(AST::DoWhileStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::WhileStatement *node) -{ - out << "while ("; - accept(node->expression); - out << ") "; - acceptAsBlock(node->statement); - return false; -} - -void PrettyPretty::endVisit(AST::WhileStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ForStatement *node) -{ - out << "for ("; - accept(node->initialiser); - out << "; "; - accept(node->condition); - out << "; "; - accept(node->expression); - out << ") "; - acceptAsBlock(node->statement); - return false; -} - -void PrettyPretty::endVisit(AST::ForStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::LocalForStatement *node) -{ - out << "for (var "; - accept(node->declarations); - out << "; "; - accept(node->condition); - out << "; "; - accept(node->expression); - out << ") "; - acceptAsBlock(node->statement); - return false; -} - -void PrettyPretty::endVisit(AST::LocalForStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ForEachStatement *node) -{ - out << "for ("; - accept(node->initialiser); - out << " in "; - accept(node->expression); - out << ") "; - acceptAsBlock(node->statement); - return false; -} - -void PrettyPretty::endVisit(AST::ForEachStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::LocalForEachStatement *node) -{ - out << "for (var "; - accept(node->declaration); - out << " in "; - accept(node->expression); - out << ") "; - acceptAsBlock(node->statement); - return false; -} - -void PrettyPretty::endVisit(AST::LocalForEachStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ContinueStatement *node) -{ - out << "continue"; - if (node->label) { - out << " " << Engine::toString(node->label); - } - out << ";"; - return false; -} - -void PrettyPretty::endVisit(AST::ContinueStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::BreakStatement *node) -{ - out << "break"; - if (node->label) { - out << " " << Engine::toString(node->label); - } - out << ";"; - return false; -} - -void PrettyPretty::endVisit(AST::BreakStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ReturnStatement *node) -{ - out << "return"; - if (node->expression) { - out << " "; - accept(node->expression); - } - out << ";"; - return false; -} - -void PrettyPretty::endVisit(AST::ReturnStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::WithStatement *node) -{ - out << "with ("; - accept(node->expression); - out << ") "; - acceptAsBlock(node->statement); - return false; -} - -void PrettyPretty::endVisit(AST::WithStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::SwitchStatement *node) -{ - out << "switch ("; - accept(node->expression); - out << ") "; - acceptAsBlock(node->block); - return false; -} - -void PrettyPretty::endVisit(AST::SwitchStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::CaseBlock *node) -{ - accept(node->clauses); - if (node->defaultClause) { - newlineAndIndent(); - accept(node->defaultClause); - } - if (node->moreClauses) { - newlineAndIndent(); - accept(node->moreClauses); - } - return false; -} - -void PrettyPretty::endVisit(AST::CaseBlock *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::CaseClauses *node) -{ - accept(node->clause); - for (node = node->next; node != 0; node = node->next) { - newlineAndIndent(); - accept(node->clause); - } - return false; -} - -void PrettyPretty::endVisit(AST::CaseClauses *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::CaseClause *node) -{ - out << "case "; - accept(node->expression); - out << ":"; - if (node->statements) { - newlineAndIndent(); - accept(node->statements); - } - return false; -} - -void PrettyPretty::endVisit(AST::CaseClause *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::DefaultClause *node) -{ - Q_UNUSED(node); - out << "default:"; - newlineAndIndent(); - return true; -} - -void PrettyPretty::endVisit(AST::DefaultClause *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::LabelledStatement *node) -{ - out << Engine::toString(node->label) << ": "; - return true; -} - -void PrettyPretty::endVisit(AST::LabelledStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::ThrowStatement *node) -{ - Q_UNUSED(node); - out << "throw "; - accept(node->expression); - out << ";"; - return false; -} - -void PrettyPretty::endVisit(AST::ThrowStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::TryStatement *node) -{ - out << "try "; - acceptAsBlock(node->statement); - if (node->catchExpression) { - out << " catch (" << Engine::toString(node->catchExpression->name) << ") "; - acceptAsBlock(node->catchExpression->statement); - } - if (node->finallyExpression) { - out << " finally "; - acceptAsBlock(node->finallyExpression->statement); - } - return false; -} - -void PrettyPretty::endVisit(AST::TryStatement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::Catch *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::Catch *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::Finally *node) -{ - Q_UNUSED(node); - out << "finally "; - return true; -} - -void PrettyPretty::endVisit(AST::Finally *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::FunctionDeclaration *node) -{ - out << "function"; - - if (node->name) - out << " " << Engine::toString(node->name); - - // the arguments - out << "("; - for (AST::FormalParameterList *it = node->formals; it; it = it->next) { - if (it->name) - out << Engine::toString(it->name); - - if (it->next) - out << ", "; - } - out << ")"; - - // the function body - out << " {"; - - if (node->body) { - pushIndentLevel(); - newlineAndIndent(); - accept(node->body); - popIndentLevel(); - newlineAndIndent(); - } - - out << "}"; - - return false; -} - -void PrettyPretty::endVisit(AST::FunctionDeclaration *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::FunctionExpression *node) -{ - out << "function"; - - if (node->name) - out << " " << Engine::toString(node->name); - - // the arguments - out << "("; - for (AST::FormalParameterList *it = node->formals; it; it = it->next) { - if (it->name) - out << Engine::toString(it->name); - - if (it->next) - out << ", "; - } - out << ")"; - - // the function body - out << " {"; - - if (node->body) { - pushIndentLevel(); - newlineAndIndent(); - accept(node->body); - popIndentLevel(); - newlineAndIndent(); - } - - out << "}"; - - return false; -} - -void PrettyPretty::endVisit(AST::FunctionExpression *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::FormalParameterList *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::FormalParameterList *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::FunctionBody *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::FunctionBody *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::Program *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::Program *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::SourceElements *node) -{ - Q_UNUSED(node); - accept(node->element); - for (node = node->next; node != 0; node = node->next) { - newlineAndIndent(); - accept(node->element); - } - return false; -} - -void PrettyPretty::endVisit(AST::SourceElements *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::FunctionSourceElement *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::FunctionSourceElement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::StatementSourceElement *node) -{ - Q_UNUSED(node); - return true; -} - -void PrettyPretty::endVisit(AST::StatementSourceElement *node) -{ - Q_UNUSED(node); -} - -bool PrettyPretty::visit(AST::DebuggerStatement *node) -{ - Q_UNUSED(node); - out << "debugger"; - return true; -} - -void PrettyPretty::endVisit(AST::DebuggerStatement *node) -{ - Q_UNUSED(node); - out << ";"; -} - -bool PrettyPretty::preVisit(AST::Node *node) -{ - Q_UNUSED(node); - return true; -} - -QT_END_NAMESPACE - - diff --git a/src/declarative/qml/parser/javascriptprettypretty_p.h b/src/declarative/qml/parser/javascriptprettypretty_p.h deleted file mode 100644 index c692da5..0000000 --- a/src/declarative/qml/parser/javascriptprettypretty_p.h +++ /dev/null @@ -1,329 +0,0 @@ -/**************************************************************************** -** -** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). -** Contact: Qt Software Information (qt-info@nokia.com) -** -** This file is part of the QtScript module of the Qt Toolkit. -** -** $QT_BEGIN_LICENSE:LGPL$ -** No Commercial Usage -** This file contains pre-release code and may not be distributed. -** You may use this file in accordance with the terms and conditions -** contained in the either Technology Preview License Agreement or the -** Beta Release License Agreement. -** -** GNU Lesser General Public License Usage -** Alternatively, 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.0, 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. -** -** If you are unsure which license is appropriate for your use, please -** contact the sales department at qt-sales@nokia.com. -** $QT_END_LICENSE$ -** -****************************************************************************/ - -#ifndef JAVASCRIPTPRETTYPRETTY_P_H -#define JAVASCRIPTPRETTYPRETTY_P_H - -// -// W A R N I N G -// ------------- -// -// This file is not part of the Qt API. It exists purely as an -// implementation detail. This header file may change from version to -// version without notice, or even be removed. -// -// We mean it. -// - -#include - -#include "javascriptastvisitor_p.h" - -QT_BEGIN_NAMESPACE - -class QTextStream; - -namespace JavaScript { - -class PrettyPretty: protected AST::Visitor -{ -public: - PrettyPretty(QTextStream &out); - virtual ~PrettyPretty(); - - QTextStream &operator () (AST::Node *node, int level = 0); - -protected: - void accept(AST::Node *node); - - virtual bool preVisit(AST::Node *node); - - virtual bool visit(AST::ThisExpression *node); - virtual void endVisit(AST::ThisExpression *node); - - virtual bool visit(AST::IdentifierExpression *node); - virtual void endVisit(AST::IdentifierExpression *node); - - virtual bool visit(AST::NullExpression *node); - virtual void endVisit(AST::NullExpression *node); - - virtual bool visit(AST::TrueLiteral *node); - virtual void endVisit(AST::TrueLiteral *node); - - virtual bool visit(AST::FalseLiteral *node); - virtual void endVisit(AST::FalseLiteral *node); - - virtual bool visit(AST::StringLiteral *node); - virtual void endVisit(AST::StringLiteral *node); - - virtual bool visit(AST::NumericLiteral *node); - virtual void endVisit(AST::NumericLiteral *node); - - virtual bool visit(AST::RegExpLiteral *node); - virtual void endVisit(AST::RegExpLiteral *node); - - virtual bool visit(AST::ArrayLiteral *node); - virtual void endVisit(AST::ArrayLiteral *node); - - virtual bool visit(AST::ObjectLiteral *node); - virtual void endVisit(AST::ObjectLiteral *node); - - virtual bool visit(AST::ElementList *node); - virtual void endVisit(AST::ElementList *node); - - virtual bool visit(AST::Elision *node); - virtual void endVisit(AST::Elision *node); - - virtual bool visit(AST::PropertyNameAndValueList *node); - virtual void endVisit(AST::PropertyNameAndValueList *node); - - virtual bool visit(AST::IdentifierPropertyName *node); - virtual void endVisit(AST::IdentifierPropertyName *node); - - virtual bool visit(AST::StringLiteralPropertyName *node); - virtual void endVisit(AST::StringLiteralPropertyName *node); - - virtual bool visit(AST::NumericLiteralPropertyName *node); - virtual void endVisit(AST::NumericLiteralPropertyName *node); - - virtual bool visit(AST::ArrayMemberExpression *node); - virtual void endVisit(AST::ArrayMemberExpression *node); - - virtual bool visit(AST::FieldMemberExpression *node); - virtual void endVisit(AST::FieldMemberExpression *node); - - virtual bool visit(AST::NewMemberExpression *node); - virtual void endVisit(AST::NewMemberExpression *node); - - virtual bool visit(AST::NewExpression *node); - virtual void endVisit(AST::NewExpression *node); - - virtual bool visit(AST::CallExpression *node); - virtual void endVisit(AST::CallExpression *node); - - virtual bool visit(AST::ArgumentList *node); - virtual void endVisit(AST::ArgumentList *node); - - virtual bool visit(AST::PostIncrementExpression *node); - virtual void endVisit(AST::PostIncrementExpression *node); - - virtual bool visit(AST::PostDecrementExpression *node); - virtual void endVisit(AST::PostDecrementExpression *node); - - virtual bool visit(AST::DeleteExpression *node); - virtual void endVisit(AST::DeleteExpression *node); - - virtual bool visit(AST::VoidExpression *node); - virtual void endVisit(AST::VoidExpression *node); - - virtual bool visit(AST::TypeOfExpression *node); - virtual void endVisit(AST::TypeOfExpression *node); - - virtual bool visit(AST::PreIncrementExpression *node); - virtual void endVisit(AST::PreIncrementExpression *node); - - virtual bool visit(AST::PreDecrementExpression *node); - virtual void endVisit(AST::PreDecrementExpression *node); - - virtual bool visit(AST::UnaryPlusExpression *node); - virtual void endVisit(AST::UnaryPlusExpression *node); - - virtual bool visit(AST::UnaryMinusExpression *node); - virtual void endVisit(AST::UnaryMinusExpression *node); - - virtual bool visit(AST::TildeExpression *node); - virtual void endVisit(AST::TildeExpression *node); - - virtual bool visit(AST::NotExpression *node); - virtual void endVisit(AST::NotExpression *node); - - virtual bool visit(AST::BinaryExpression *node); - virtual void endVisit(AST::BinaryExpression *node); - - virtual bool visit(AST::ConditionalExpression *node); - virtual void endVisit(AST::ConditionalExpression *node); - - virtual bool visit(AST::Expression *node); - virtual void endVisit(AST::Expression *node); - - virtual bool visit(AST::Block *node); - virtual void endVisit(AST::Block *node); - - virtual bool visit(AST::StatementList *node); - virtual void endVisit(AST::StatementList *node); - - virtual bool visit(AST::VariableStatement *node); - virtual void endVisit(AST::VariableStatement *node); - - virtual bool visit(AST::VariableDeclarationList *node); - virtual void endVisit(AST::VariableDeclarationList *node); - - virtual bool visit(AST::VariableDeclaration *node); - virtual void endVisit(AST::VariableDeclaration *node); - - virtual bool visit(AST::EmptyStatement *node); - virtual void endVisit(AST::EmptyStatement *node); - - virtual bool visit(AST::ExpressionStatement *node); - virtual void endVisit(AST::ExpressionStatement *node); - - virtual bool visit(AST::IfStatement *node); - virtual void endVisit(AST::IfStatement *node); - - virtual bool visit(AST::DoWhileStatement *node); - virtual void endVisit(AST::DoWhileStatement *node); - - virtual bool visit(AST::WhileStatement *node); - virtual void endVisit(AST::WhileStatement *node); - - virtual bool visit(AST::ForStatement *node); - virtual void endVisit(AST::ForStatement *node); - - virtual bool visit(AST::LocalForStatement *node); - virtual void endVisit(AST::LocalForStatement *node); - - virtual bool visit(AST::ForEachStatement *node); - virtual void endVisit(AST::ForEachStatement *node); - - virtual bool visit(AST::LocalForEachStatement *node); - virtual void endVisit(AST::LocalForEachStatement *node); - - virtual bool visit(AST::ContinueStatement *node); - virtual void endVisit(AST::ContinueStatement *node); - - virtual bool visit(AST::BreakStatement *node); - virtual void endVisit(AST::BreakStatement *node); - - virtual bool visit(AST::ReturnStatement *node); - virtual void endVisit(AST::ReturnStatement *node); - - virtual bool visit(AST::WithStatement *node); - virtual void endVisit(AST::WithStatement *node); - - virtual bool visit(AST::SwitchStatement *node); - virtual void endVisit(AST::SwitchStatement *node); - - virtual bool visit(AST::CaseBlock *node); - virtual void endVisit(AST::CaseBlock *node); - - virtual bool visit(AST::CaseClauses *node); - virtual void endVisit(AST::CaseClauses *node); - - virtual bool visit(AST::CaseClause *node); - virtual void endVisit(AST::CaseClause *node); - - virtual bool visit(AST::DefaultClause *node); - virtual void endVisit(AST::DefaultClause *node); - - virtual bool visit(AST::LabelledStatement *node); - virtual void endVisit(AST::LabelledStatement *node); - - virtual bool visit(AST::ThrowStatement *node); - virtual void endVisit(AST::ThrowStatement *node); - - virtual bool visit(AST::TryStatement *node); - virtual void endVisit(AST::TryStatement *node); - - virtual bool visit(AST::Catch *node); - virtual void endVisit(AST::Catch *node); - - virtual bool visit(AST::Finally *node); - virtual void endVisit(AST::Finally *node); - - virtual bool visit(AST::FunctionDeclaration *node); - virtual void endVisit(AST::FunctionDeclaration *node); - - virtual bool visit(AST::FunctionExpression *node); - virtual void endVisit(AST::FunctionExpression *node); - - virtual bool visit(AST::FormalParameterList *node); - virtual void endVisit(AST::FormalParameterList *node); - - virtual bool visit(AST::FunctionBody *node); - virtual void endVisit(AST::FunctionBody *node); - - virtual bool visit(AST::Program *node); - virtual void endVisit(AST::Program *node); - - virtual bool visit(AST::SourceElements *node); - virtual void endVisit(AST::SourceElements *node); - - virtual bool visit(AST::FunctionSourceElement *node); - virtual void endVisit(AST::FunctionSourceElement *node); - - virtual bool visit(AST::StatementSourceElement *node); - virtual void endVisit(AST::StatementSourceElement *node); - - virtual bool visit(AST::DebuggerStatement *node); - virtual void endVisit(AST::DebuggerStatement *node); - - int indentLevel(int level) - { - int was = m_indentLevel; - m_indentLevel = level; - return was; - } - - void pushIndentLevel() - { ++m_indentLevel; } - - void popIndentLevel() - { --m_indentLevel; } - - QTextStream &newlineAndIndent(); - - void acceptAsBlock(AST::Node *node); - - static int operatorPrecedenceLevel(int op); - static int compareOperatorPrecedence(int op1, int op2); - -private: - QTextStream &out; - int m_indentLevel; - - Q_DISABLE_COPY(PrettyPretty) -}; - -} // namespace JavaScript - -QT_END_NAMESPACE - -#endif diff --git a/src/declarative/qml/parser/parser.pri b/src/declarative/qml/parser/parser.pri index 72bd46c..610b2aa 100644 --- a/src/declarative/qml/parser/parser.pri +++ b/src/declarative/qml/parser/parser.pri @@ -1,22 +1,22 @@ INCLUDEPATH += $$PWD -HEADERS += $$PWD/javascriptast_p.h \ - $$PWD/javascriptastfwd_p.h \ - $$PWD/javascriptastvisitor_p.h \ - $$PWD/javascriptengine_p.h \ - $$PWD/javascriptgrammar_p.h \ - $$PWD/javascriptlexer_p.h \ - $$PWD/javascriptmemorypool_p.h \ - $$PWD/javascriptnodepool_p.h \ - $$PWD/javascriptparser_p.h \ - $$PWD/javascriptprettypretty_p.h +HEADERS += $$PWD/qmljsast_p.h \ + $$PWD/qmljsastfwd_p.h \ + $$PWD/qmljsastvisitor_p.h \ + $$PWD/qmljsengine_p.h \ + $$PWD/qmljsgrammar_p.h \ + $$PWD/qmljslexer_p.h \ + $$PWD/qmljsmemorypool_p.h \ + $$PWD/qmljsnodepool_p.h \ + $$PWD/qmljsparser_p.h \ + $$PWD/qmljsprettypretty_p.h -SOURCES += $$PWD/javascriptast.cpp \ - $$PWD/javascriptastvisitor.cpp \ - $$PWD/javascriptengine_p.cpp \ - $$PWD/javascriptgrammar.cpp \ - $$PWD/javascriptlexer.cpp \ - $$PWD/javascriptprettypretty.cpp \ - $$PWD/javascriptparser.cpp +SOURCES += $$PWD/qmljsast.cpp \ + $$PWD/qmljsastvisitor.cpp \ + $$PWD/qmljsengine_p.cpp \ + $$PWD/qmljsgrammar.cpp \ + $$PWD/qmljslexer.cpp \ + $$PWD/qmljsprettypretty.cpp \ + $$PWD/qmljsparser.cpp diff --git a/src/declarative/qml/parser/qmljs.g b/src/declarative/qml/parser/qmljs.g new file mode 100644 index 0000000..907ca52 --- /dev/null +++ b/src/declarative/qml/parser/qmljs.g @@ -0,0 +1,2881 @@ +---------------------------------------------------------------------------- +-- +-- Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +-- Contact: Qt Software Information (qt-info@nokia.com) +-- +-- This file is part of the QtScript module of the Qt Toolkit. +-- +-- $QT_BEGIN_LICENSE:LGPL$ +-- No Commercial Usage +-- This file contains pre-release code and may not be distributed. +-- You may use this file in accordance with the terms and conditions +-- contained in the either Technology Preview License Agreement or the +-- Beta Release License Agreement. +-- +-- GNU Lesser General Public License Usage +-- Alternatively, 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.0, 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. +-- +-- If you are unsure which license is appropriate for your use, please +-- contact the sales department at qt-sales@nokia.com. +-- $QT_END_LICENSE$ +-- +-- This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE +-- WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. +-- +---------------------------------------------------------------------------- + +%parser QmlJSGrammar +%decl qmljsparser_p.h +%impl qmljsparser.cpp +%expect 2 +%expect-rr 3 + +%token T_AND "&" T_AND_AND "&&" T_AND_EQ "&=" +%token T_BREAK "break" T_CASE "case" T_CATCH "catch" +%token T_COLON ":" T_COMMA ";" T_CONTINUE "continue" +%token T_DEFAULT "default" T_DELETE "delete" T_DIVIDE_ "/" +%token T_DIVIDE_EQ "/=" T_DO "do" T_DOT "." +%token T_ELSE "else" T_EQ "=" T_EQ_EQ "==" +%token T_EQ_EQ_EQ "===" T_FINALLY "finally" T_FOR "for" +%token T_FUNCTION "function" T_GE ">=" T_GT ">" +%token T_GT_GT ">>" T_GT_GT_EQ ">>=" T_GT_GT_GT ">>>" +%token T_GT_GT_GT_EQ ">>>=" T_IDENTIFIER "identifier" T_IF "if" +%token T_IN "in" T_INSTANCEOF "instanceof" T_LBRACE "{" +%token T_LBRACKET "[" T_LE "<=" T_LPAREN "(" +%token T_LT "<" T_LT_LT "<<" T_LT_LT_EQ "<<=" +%token T_MINUS "-" T_MINUS_EQ "-=" T_MINUS_MINUS "--" +%token T_NEW "new" T_NOT "!" T_NOT_EQ "!=" +%token T_NOT_EQ_EQ "!==" T_NUMERIC_LITERAL "numeric literal" T_OR "|" +%token T_OR_EQ "|=" T_OR_OR "||" T_PLUS "+" +%token T_PLUS_EQ "+=" T_PLUS_PLUS "++" T_QUESTION "?" +%token T_RBRACE "}" T_RBRACKET "]" T_REMAINDER "%" +%token T_REMAINDER_EQ "%=" T_RETURN "return" T_RPAREN ")" +%token T_SEMICOLON ";" T_AUTOMATIC_SEMICOLON T_STAR "*" +%token T_STAR_EQ "*=" T_STRING_LITERAL "string literal" +%token T_PROPERTY "property" T_SIGNAL "signal" +%token T_SWITCH "switch" T_THIS "this" T_THROW "throw" +%token T_TILDE "~" T_TRY "try" T_TYPEOF "typeof" +%token T_VAR "var" T_VOID "void" T_WHILE "while" +%token T_WITH "with" T_XOR "^" T_XOR_EQ "^=" +%token T_NULL "null" T_TRUE "true" T_FALSE "false" +%token T_CONST "const" +%token T_DEBUGGER "debugger" +%token T_RESERVED_WORD "reserved word" +%token T_MULTILINE_STRING_LITERAL "multiline string literal" + +--- context keywords. +%token T_PUBLIC "public" +%token T_IMPORT "import" + +%nonassoc SHIFT_THERE +%nonassoc T_IDENTIFIER T_COLON T_SIGNAL T_PROPERTY +%nonassoc REDUCE_HERE + +%start UiProgram + +/. +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include + +#include "qmljsengine_p.h" +#include "qmljslexer_p.h" +#include "qmljsast_p.h" +#include "qmljsnodepool_p.h" + +./ + +/: +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +// +// This file is automatically generated from qmljs.g. +// Changes will be lost. +// + +#ifndef QMLJSPARSER_P_H +#define QMLJSPARSER_P_H + +#include "qmljsgrammar_p.h" +#include "qmljsast_p.h" +#include "qmljsengine_p.h" + +#include + +QT_BEGIN_NAMESPACE + +class QString; + +namespace QmlJS { + +class Engine; +class NameId; + +class Parser: protected $table +{ +public: + union Value { + int ival; + double dval; + NameId *sval; + AST::ArgumentList *ArgumentList; + AST::CaseBlock *CaseBlock; + AST::CaseClause *CaseClause; + AST::CaseClauses *CaseClauses; + AST::Catch *Catch; + AST::DefaultClause *DefaultClause; + AST::ElementList *ElementList; + AST::Elision *Elision; + AST::ExpressionNode *Expression; + AST::Finally *Finally; + AST::FormalParameterList *FormalParameterList; + AST::FunctionBody *FunctionBody; + AST::FunctionDeclaration *FunctionDeclaration; + AST::Node *Node; + AST::PropertyName *PropertyName; + AST::PropertyNameAndValueList *PropertyNameAndValueList; + AST::SourceElement *SourceElement; + AST::SourceElements *SourceElements; + AST::Statement *Statement; + AST::StatementList *StatementList; + AST::Block *Block; + AST::VariableDeclaration *VariableDeclaration; + AST::VariableDeclarationList *VariableDeclarationList; + + AST::UiProgram *UiProgram; + AST::UiImportList *UiImportList; + AST::UiImport *UiImport; + AST::UiPublicMember *UiPublicMember; + AST::UiObjectDefinition *UiObjectDefinition; + AST::UiObjectInitializer *UiObjectInitializer; + AST::UiObjectBinding *UiObjectBinding; + AST::UiScriptBinding *UiScriptBinding; + AST::UiArrayBinding *UiArrayBinding; + AST::UiObjectMember *UiObjectMember; + AST::UiObjectMemberList *UiObjectMemberList; + AST::UiArrayMemberList *UiArrayMemberList; + AST::UiQualifiedId *UiQualifiedId; + }; + +public: + Parser(Engine *engine); + ~Parser(); + + bool parse(); + + AST::UiProgram *ast() + { return program; } + + QList diagnosticMessages() const + { return diagnostic_messages; } + + inline DiagnosticMessage diagnosticMessage() const + { + foreach (const DiagnosticMessage &d, diagnostic_messages) { + if (! d.kind == DiagnosticMessage::Warning) + return d; + } + + return DiagnosticMessage(); + } + + inline QString errorMessage() const + { return diagnosticMessage().message; } + + inline int errorLineNumber() const + { return diagnosticMessage().loc.startLine; } + + inline int errorColumnNumber() const + { return diagnosticMessage().loc.startColumn; } + +protected: + void reallocateStack(); + + inline Value &sym(int index) + { return sym_stack [tos + index - 1]; } + + inline AST::SourceLocation &loc(int index) + { return location_stack [tos + index - 1]; } + + AST::UiQualifiedId *reparseAsQualifiedId(AST::ExpressionNode *expr); + +protected: + Engine *driver; + int tos; + int stack_size; + Value *sym_stack; + int *state_stack; + AST::SourceLocation *location_stack; + + AST::UiProgram *program; + + // error recovery + enum { TOKEN_BUFFER_SIZE = 3 }; + + struct SavedToken { + int token; + double dval; + AST::SourceLocation loc; + }; + + double yylval; + AST::SourceLocation yylloc; + AST::SourceLocation yyprevlloc; + + SavedToken token_buffer[TOKEN_BUFFER_SIZE]; + SavedToken *first_token; + SavedToken *last_token; + + QList diagnostic_messages; +}; + +} // end of namespace QmlJS + + +:/ + + +/. + +#include "qmljsparser_p.h" +#include + +// +// This file is automatically generated from qmljs.g. +// Changes will be lost. +// + +using namespace QmlJS; + +QT_BEGIN_NAMESPACE + +void Parser::reallocateStack() +{ + if (! stack_size) + stack_size = 128; + else + stack_size <<= 1; + + sym_stack = reinterpret_cast (qRealloc(sym_stack, stack_size * sizeof(Value))); + state_stack = reinterpret_cast (qRealloc(state_stack, stack_size * sizeof(int))); + location_stack = reinterpret_cast (qRealloc(location_stack, stack_size * sizeof(AST::SourceLocation))); +} + +inline static bool automatic(Engine *driver, int token) +{ + return token == $table::T_RBRACE + || token == 0 + || driver->lexer()->prevTerminator(); +} + + +Parser::Parser(Engine *engine): + driver(engine), + tos(0), + stack_size(0), + sym_stack(0), + state_stack(0), + location_stack(0), + first_token(0), + last_token(0) +{ +} + +Parser::~Parser() +{ + if (stack_size) { + qFree(sym_stack); + qFree(state_stack); + qFree(location_stack); + } +} + +static inline AST::SourceLocation location(Lexer *lexer) +{ + AST::SourceLocation loc; + loc.offset = lexer->tokenOffset(); + loc.length = lexer->tokenLength(); + loc.startLine = lexer->startLineNo(); + loc.startColumn = lexer->startColumnNo(); + return loc; +} + +AST::UiQualifiedId *Parser::reparseAsQualifiedId(AST::ExpressionNode *expr) +{ + QVarLengthArray nameIds; + QVarLengthArray locations; + + AST::ExpressionNode *it = expr; + while (AST::FieldMemberExpression *m = AST::cast(it)) { + nameIds.append(m->name); + locations.append(m->identifierToken); + it = m->base; + } + + if (AST::IdentifierExpression *idExpr = AST::cast(it)) { + AST::UiQualifiedId *q = makeAstNode(driver->nodePool(), idExpr->name); + q->identifierToken = idExpr->identifierToken; + + AST::UiQualifiedId *currentId = q; + for (int i = nameIds.size() - 1; i != -1; --i) { + currentId = makeAstNode(driver->nodePool(), currentId, nameIds[i]); + currentId->identifierToken = locations[i]; + } + + return currentId->finish(); + } + + return 0; +} + +bool Parser::parse() +{ + Lexer *lexer = driver->lexer(); + bool hadErrors = false; + int yytoken = -1; + int action = 0; + + first_token = last_token = 0; + + tos = -1; + program = 0; + + do { + if (++tos == stack_size) + reallocateStack(); + + state_stack[tos] = action; + + _Lcheck_token: + if (yytoken == -1 && -TERMINAL_COUNT != action_index[action]) { + yyprevlloc = yylloc; + + if (first_token == last_token) { + yytoken = lexer->lex(); + yylval = lexer->dval(); + yylloc = location(lexer); + } else { + yytoken = first_token->token; + yylval = first_token->dval; + yylloc = first_token->loc; + ++first_token; + } + } + + action = t_action(action, yytoken); + if (action > 0) { + if (action != ACCEPT_STATE) { + yytoken = -1; + sym(1).dval = yylval; + loc(1) = yylloc; + } else { + --tos; + return ! hadErrors; + } + } else if (action < 0) { + const int r = -action - 1; + tos -= rhs[r]; + + switch (r) { +./ + +-------------------------------------------------------------------------------------------------------- +-- Declarative UI +-------------------------------------------------------------------------------------------------------- + +UiProgram: UiImportListOpt UiRootMember ; +/. +case $rule_number: { + program = makeAstNode (driver->nodePool(), sym(1).UiImportList, + sym(2).UiObjectMemberList->finish()); + sym(1).UiProgram = program; +} break; +./ + +UiImportListOpt: Empty ; +UiImportListOpt: UiImportList ; +/. +case $rule_number: { + sym(1).Node = sym(1).UiImportList->finish(); +} break; +./ + +UiImportList: UiImport ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiImport); +} break; +./ + +UiImportList: UiImportList UiImport ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), + sym(1).UiImportList, sym(2).UiImport); +} break; +./ + +UiImport: T_IMPORT T_STRING_LITERAL T_AUTOMATIC_SEMICOLON; +UiImport: T_IMPORT T_STRING_LITERAL T_SEMICOLON; +/. +case $rule_number: { + AST::UiImport *node = makeAstNode(driver->nodePool(), sym(2).sval); + node->importToken = loc(1); + node->fileNameToken = loc(2); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; +./ + +Empty: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +UiRootMember: UiObjectDefinition ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); +} break; +./ + +UiObjectMemberList: UiObjectMember ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); +} break; +./ + +UiObjectMemberList: UiObjectMemberList UiObjectMember ; +/. +case $rule_number: { + AST::UiObjectMemberList *node = makeAstNode (driver->nodePool(), + sym(1).UiObjectMemberList, sym(2).UiObjectMember); + sym(1).Node = node; +} break; +./ + +UiArrayMemberList: UiObjectDefinition ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); +} break; +./ + +UiArrayMemberList: UiArrayMemberList T_COMMA UiObjectDefinition ; +/. +case $rule_number: { + AST::UiArrayMemberList *node = makeAstNode (driver->nodePool(), + sym(1).UiArrayMemberList, sym(3).UiObjectMember); + node->commaToken = loc(2); + sym(1).Node = node; +} break; +./ + +UiObjectInitializer: T_LBRACE T_RBRACE ; +/. +case $rule_number: { + AST::UiObjectInitializer *node = makeAstNode (driver->nodePool(), (AST::UiObjectMemberList*)0); + node->lbraceToken = loc(1); + node->rbraceToken = loc(2); + sym(1).Node = node; +} break; +./ + +UiObjectInitializer: T_LBRACE UiObjectMemberList T_RBRACE ; +/. +case $rule_number: { + AST::UiObjectInitializer *node = makeAstNode (driver->nodePool(), sym(2).UiObjectMemberList->finish()); + node->lbraceToken = loc(1); + node->rbraceToken = loc(3); + sym(1).Node = node; +} break; +./ + +UiObjectDefinition: UiQualifiedId UiObjectInitializer ; +/. +case $rule_number: { + AST::UiObjectDefinition *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), + sym(2).UiObjectInitializer); + sym(1).Node = node; +} break; +./ + +UiObjectMember: UiObjectDefinition ; + +UiObjectMember: UiQualifiedId T_COLON T_LBRACKET UiArrayMemberList T_RBRACKET ; +/. +case $rule_number: { + AST::UiArrayBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), + sym(4).UiArrayMemberList->finish()); + node->colonToken = loc(2); + node->lbracketToken = loc(3); + node->rbracketToken = loc(5); + sym(1).Node = node; +} break; +./ + +UiMultilineStringLiteral: T_MULTILINE_STRING_LITERAL ; +/. +case $rule_number: { + AST::StringLiteral *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->literalToken = loc(1); + sym(1).Node = node; +} break; +./ + +UiMultilineStringStatement: UiMultilineStringLiteral T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +UiMultilineStringStatement: UiMultilineStringLiteral T_SEMICOLON ; +/. +case $rule_number: { + AST::ExpressionStatement *node = makeAstNode (driver->nodePool(), sym(1).Expression); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; +./ + + +UiObjectMember: UiQualifiedId T_COLON Expression UiObjectInitializer ; +/. +case $rule_number: { + if (AST::UiQualifiedId *qualifiedId = reparseAsQualifiedId(sym(3).Expression)) { + AST::UiObjectBinding *node = makeAstNode (driver->nodePool(), + sym(1).UiQualifiedId->finish(), qualifiedId, sym(4).UiObjectInitializer); + node->colonToken = loc(2); + sym(1).Node = node; + } else { + sym(1).Node = 0; + + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc(2), + QLatin1String("Expected a type name after token `:'"))); + + return false; // ### recover + } +} break; +./ + +UiObjectMember: UiQualifiedId T_COLON Block ; +/.case $rule_number:./ + +UiObjectMember: UiQualifiedId T_COLON EmptyStatement ; +/.case $rule_number:./ + +UiObjectMember: UiQualifiedId T_COLON ExpressionStatement ; +/.case $rule_number:./ + +UiObjectMember: UiQualifiedId T_COLON DebuggerStatement ; +/.case $rule_number:./ + +UiObjectMember: UiQualifiedId T_COLON UiMultilineStringStatement ; +/.case $rule_number:./ + +UiObjectMember: UiQualifiedId T_COLON IfStatement ; --- ### do we really want if statement in a binding? +/.case $rule_number:./ + +/. +{ + AST::UiScriptBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), + sym(3).Statement); + node->colonToken = loc(2); + sym(1).Node = node; +} break; +./ + +UiPropertyType: T_VAR ; +/. +case $rule_number: +./ +UiPropertyType: T_RESERVED_WORD ; +/. +case $rule_number: { + sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount()); + break; +} +./ + +UiPropertyType: T_IDENTIFIER ; + +UiObjectMember: T_SIGNAL T_IDENTIFIER ; +/. +case $rule_number: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), (NameId *)0, sym(2).sval); + node->type = AST::UiPublicMember::Signal; + node->propertyToken = loc(1); + node->typeToken = loc(2); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; +./ + +UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_AUTOMATIC_SEMICOLON ; +UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_SEMICOLON ; +/. +case $rule_number: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(3).sval); + node->propertyToken = loc(1); + node->typeToken = loc(2); + node->identifierToken = loc(3); + node->semicolonToken = loc(4); + sym(1).Node = node; +} break; +./ + +UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_AUTOMATIC_SEMICOLON ; +UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_SEMICOLON ; +/. +case $rule_number: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(4).sval); + node->isDefaultMember = true; + node->defaultToken = loc(1); + node->propertyToken = loc(2); + node->typeToken = loc(3); + node->identifierToken = loc(4); + node->semicolonToken = loc(5); + sym(1).Node = node; +} break; +./ + +UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_AUTOMATIC_SEMICOLON ; +UiObjectMember: T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_SEMICOLON ; +/. +case $rule_number: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(3).sval, + sym(5).Expression); + node->propertyToken = loc(1); + node->typeToken = loc(2); + node->identifierToken = loc(3); + node->colonToken = loc(4); + node->semicolonToken = loc(6); + sym(1).Node = node; +} break; +./ + +UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_AUTOMATIC_SEMICOLON ; +UiObjectMember: T_DEFAULT T_PROPERTY UiPropertyType T_IDENTIFIER T_COLON Expression T_SEMICOLON ; +/. +case $rule_number: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(4).sval, + sym(6).Expression); + node->isDefaultMember = true; + node->defaultToken = loc(1); + node->propertyToken = loc(2); + node->typeToken = loc(3); + node->identifierToken = loc(4); + node->colonToken = loc(5); + node->semicolonToken = loc(7); + sym(1).Node = node; +} break; +./ + +UiObjectMember: FunctionDeclaration ; +/. +case $rule_number: { + sym(1).Node = makeAstNode(driver->nodePool(), sym(1).Node); +} break; +./ + +UiObjectMember: VariableStatement ; +/. +case $rule_number: { + sym(1).Node = makeAstNode(driver->nodePool(), sym(1).Node); +} break; +./ + +UiQualifiedId: T_RESERVED_WORD ; +/.case $rule_number: ./ + +UiQualifiedId: T_RETURN ; +/. +case $rule_number: +{ + AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount())); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; +./ + +JsIdentifier: T_IDENTIFIER; + +JsIdentifier: T_PROPERTY ; +/. +case $rule_number: { + QString s = QLatin1String(QmlJSGrammar::spell[T_PROPERTY]); + sym(1).sval = driver->intern(s.constData(), s.length()); + break; +} +./ + +JsIdentifier: T_SIGNAL ; +/. +case $rule_number: { + QString s = QLatin1String(QmlJSGrammar::spell[T_SIGNAL]); + sym(1).sval = driver->intern(s.constData(), s.length()); + break; +} +./ + +-------------------------------------------------------------------------------------------------------- +-- Expressions +-------------------------------------------------------------------------------------------------------- + +PrimaryExpression: T_THIS ; +/. +case $rule_number: { + AST::ThisExpression *node = makeAstNode (driver->nodePool()); + node->thisToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: JsIdentifier ; +/. +case $rule_number: { + AST::IdentifierExpression *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_NULL ; +/. +case $rule_number: { + AST::NullExpression *node = makeAstNode (driver->nodePool()); + node->nullToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_TRUE ; +/. +case $rule_number: { + AST::TrueLiteral *node = makeAstNode (driver->nodePool()); + node->trueToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_FALSE ; +/. +case $rule_number: { + AST::FalseLiteral *node = makeAstNode (driver->nodePool()); + node->falseToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_NUMERIC_LITERAL ; +/. +case $rule_number: { + AST::NumericLiteral *node = makeAstNode (driver->nodePool(), sym(1).dval, lexer->flags); + node->literalToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_STRING_LITERAL ; +/. +case $rule_number: { + AST::StringLiteral *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->literalToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_DIVIDE_ ; +/: +#define J_SCRIPT_REGEXPLITERAL_RULE1 $rule_number +:/ +/. +case $rule_number: { + bool rx = lexer->scanRegExp(Lexer::NoPrefix); + if (!rx) { + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage())); + return false; // ### remove me + } + AST::RegExpLiteral *node = makeAstNode (driver->nodePool(), lexer->pattern, lexer->flags); + node->literalToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_DIVIDE_EQ ; +/: +#define J_SCRIPT_REGEXPLITERAL_RULE2 $rule_number +:/ +/. +case $rule_number: { + bool rx = lexer->scanRegExp(Lexer::EqualPrefix); + if (!rx) { + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage())); + return false; + } + AST::RegExpLiteral *node = makeAstNode (driver->nodePool(), lexer->pattern, lexer->flags); + node->literalToken = loc(1); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_LBRACKET T_RBRACKET ; +/. +case $rule_number: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), (AST::Elision *) 0); + node->lbracketToken = loc(1); + node->rbracketToken = loc(2); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_LBRACKET Elision T_RBRACKET ; +/. +case $rule_number: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).Elision->finish()); + node->lbracketToken = loc(1); + node->rbracketToken = loc(3); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_LBRACKET ElementList T_RBRACKET ; +/. +case $rule_number: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish ()); + node->lbracketToken = loc(1); + node->rbracketToken = loc(3); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_LBRACKET ElementList T_COMMA T_RBRACKET ; +/. +case $rule_number: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish (), + (AST::Elision *) 0); + node->lbracketToken = loc(1); + node->commaToken = loc(3); + node->rbracketToken = loc(4); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_LBRACKET ElementList T_COMMA Elision T_RBRACKET ; +/. +case $rule_number: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish (), + sym(4).Elision->finish()); + node->lbracketToken = loc(1); + node->commaToken = loc(3); + node->rbracketToken = loc(5); + sym(1).Node = node; +} break; +./ + +-- PrimaryExpression: T_LBRACE T_RBRACE ; +-- /. +-- case $rule_number: { +-- sym(1).Node = makeAstNode (driver->nodePool()); +-- } break; +-- ./ + +PrimaryExpression: T_LBRACE PropertyNameAndValueListOpt T_RBRACE ; +/. +case $rule_number: { + AST::ObjectLiteral *node = 0; + if (sym(2).Node) + node = makeAstNode (driver->nodePool(), + sym(2).PropertyNameAndValueList->finish ()); + else + node = makeAstNode (driver->nodePool()); + node->lbraceToken = loc(1); + node->lbraceToken = loc(3); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_LBRACE PropertyNameAndValueList T_COMMA T_RBRACE ; +/. +case $rule_number: { + AST::ObjectLiteral *node = makeAstNode (driver->nodePool(), + sym(2).PropertyNameAndValueList->finish ()); + node->lbraceToken = loc(1); + node->lbraceToken = loc(4); + sym(1).Node = node; +} break; +./ + +PrimaryExpression: T_LPAREN Expression T_RPAREN ; +/. +case $rule_number: { + AST::NestedExpression *node = makeAstNode(driver->nodePool(), sym(2).Expression); + node->lparenToken = loc(1); + node->rparenToken = loc(3); + sym(1).Node = node; +} break; +./ + +UiQualifiedId: JsIdentifier ; +/. +case $rule_number: { + AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; +./ + +UiQualifiedId: UiQualifiedId T_DOT JsIdentifier ; +/. +case $rule_number: { + AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId, sym(3).sval); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; +./ + +ElementList: AssignmentExpression ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), (AST::Elision *) 0, sym(1).Expression); +} break; +./ + +ElementList: Elision AssignmentExpression ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Elision->finish(), sym(2).Expression); +} break; +./ + +ElementList: ElementList T_COMMA AssignmentExpression ; +/. +case $rule_number: { + AST::ElementList *node = makeAstNode (driver->nodePool(), sym(1).ElementList, + (AST::Elision *) 0, sym(3).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; +./ + +ElementList: ElementList T_COMMA Elision AssignmentExpression ; +/. +case $rule_number: { + AST::ElementList *node = makeAstNode (driver->nodePool(), sym(1).ElementList, sym(3).Elision->finish(), + sym(4).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; +./ + +Elision: T_COMMA ; +/. +case $rule_number: { + AST::Elision *node = makeAstNode (driver->nodePool()); + node->commaToken = loc(1); + sym(1).Node = node; +} break; +./ + +Elision: Elision T_COMMA ; +/. +case $rule_number: { + AST::Elision *node = makeAstNode (driver->nodePool(), sym(1).Elision); + node->commaToken = loc(2); + sym(1).Node = node; +} break; +./ + +PropertyNameAndValueList: PropertyName T_COLON AssignmentExpression ; +/. +case $rule_number: { + AST::PropertyNameAndValueList *node = makeAstNode (driver->nodePool(), + sym(1).PropertyName, sym(3).Expression); + node->colonToken = loc(2); + sym(1).Node = node; +} break; +./ + +PropertyNameAndValueList: PropertyNameAndValueList T_COMMA PropertyName T_COLON AssignmentExpression ; +/. +case $rule_number: { + AST::PropertyNameAndValueList *node = makeAstNode (driver->nodePool(), + sym(1).PropertyNameAndValueList, sym(3).PropertyName, sym(5).Expression); + node->commaToken = loc(2); + node->colonToken = loc(4); + sym(1).Node = node; +} break; +./ + +PropertyName: T_IDENTIFIER %prec REDUCE_HERE ; +/. +case $rule_number: { + AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; +./ + +PropertyName: T_SIGNAL ; +/.case $rule_number:./ + +PropertyName: T_PROPERTY ; +/. +case $rule_number: { + AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount())); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; +./ + +PropertyName: T_STRING_LITERAL ; +/. +case $rule_number: { + AST::StringLiteralPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; +./ + +PropertyName: T_NUMERIC_LITERAL ; +/. +case $rule_number: { + AST::NumericLiteralPropertyName *node = makeAstNode (driver->nodePool(), sym(1).dval); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; +./ + +PropertyName: ReservedIdentifier ; +/. +case $rule_number: { + AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; +./ + +ReservedIdentifier: T_BREAK ; +/. +case $rule_number: +./ +ReservedIdentifier: T_CASE ; +/. +case $rule_number: +./ +ReservedIdentifier: T_CATCH ; +/. +case $rule_number: +./ +ReservedIdentifier: T_CONTINUE ; +/. +case $rule_number: +./ +ReservedIdentifier: T_DEFAULT ; +/. +case $rule_number: +./ +ReservedIdentifier: T_DELETE ; +/. +case $rule_number: +./ +ReservedIdentifier: T_DO ; +/. +case $rule_number: +./ +ReservedIdentifier: T_ELSE ; +/. +case $rule_number: +./ +ReservedIdentifier: T_FALSE ; +/. +case $rule_number: +./ +ReservedIdentifier: T_FINALLY ; +/. +case $rule_number: +./ +ReservedIdentifier: T_FOR ; +/. +case $rule_number: +./ +ReservedIdentifier: T_FUNCTION ; +/. +case $rule_number: +./ +ReservedIdentifier: T_IF ; +/. +case $rule_number: +./ +ReservedIdentifier: T_IN ; +/. +case $rule_number: +./ +ReservedIdentifier: T_INSTANCEOF ; +/. +case $rule_number: +./ +ReservedIdentifier: T_NEW ; +/. +case $rule_number: +./ +ReservedIdentifier: T_NULL ; +/. +case $rule_number: +./ +ReservedIdentifier: T_RETURN ; +/. +case $rule_number: +./ +ReservedIdentifier: T_SWITCH ; +/. +case $rule_number: +./ +ReservedIdentifier: T_THIS ; +/. +case $rule_number: +./ +ReservedIdentifier: T_THROW ; +/. +case $rule_number: +./ +ReservedIdentifier: T_TRUE ; +/. +case $rule_number: +./ +ReservedIdentifier: T_TRY ; +/. +case $rule_number: +./ +ReservedIdentifier: T_TYPEOF ; +/. +case $rule_number: +./ +ReservedIdentifier: T_VAR ; +/. +case $rule_number: +./ +ReservedIdentifier: T_VOID ; +/. +case $rule_number: +./ +ReservedIdentifier: T_WHILE ; +/. +case $rule_number: +./ +ReservedIdentifier: T_CONST ; +/. +case $rule_number: +./ +ReservedIdentifier: T_DEBUGGER ; +/. +case $rule_number: +./ +ReservedIdentifier: T_RESERVED_WORD ; +/. +case $rule_number: +./ +ReservedIdentifier: T_WITH ; +/. +case $rule_number: +{ + sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount()); +} break; +./ + +PropertyIdentifier: JsIdentifier ; +PropertyIdentifier: ReservedIdentifier ; + +MemberExpression: PrimaryExpression ; +MemberExpression: FunctionExpression ; + +MemberExpression: MemberExpression T_LBRACKET Expression T_RBRACKET ; +/. +case $rule_number: { + AST::ArrayMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); + node->lbracketToken = loc(2); + node->rbracketToken = loc(4); + sym(1).Node = node; +} break; +./ + +MemberExpression: MemberExpression T_DOT PropertyIdentifier ; +/. +case $rule_number: { + AST::FieldMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).sval); + node->dotToken = loc(2); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; +./ + +MemberExpression: T_NEW MemberExpression T_LPAREN ArgumentListOpt T_RPAREN ; +/. +case $rule_number: { + AST::NewMemberExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression, sym(4).ArgumentList); + node->newToken = loc(1); + node->lparenToken = loc(3); + node->rparenToken = loc(5); + sym(1).Node = node; +} break; +./ + +NewExpression: MemberExpression ; + +NewExpression: T_NEW NewExpression ; +/. +case $rule_number: { + AST::NewExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->newToken = loc(1); + sym(1).Node = node; +} break; +./ + +CallExpression: MemberExpression T_LPAREN ArgumentListOpt T_RPAREN ; +/. +case $rule_number: { + AST::CallExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; +./ + +CallExpression: CallExpression T_LPAREN ArgumentListOpt T_RPAREN ; +/. +case $rule_number: { + AST::CallExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; +./ + +CallExpression: CallExpression T_LBRACKET Expression T_RBRACKET ; +/. +case $rule_number: { + AST::ArrayMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); + node->lbracketToken = loc(2); + node->rbracketToken = loc(4); + sym(1).Node = node; +} break; +./ + +CallExpression: CallExpression T_DOT PropertyIdentifier ; +/. +case $rule_number: { + AST::FieldMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).sval); + node->dotToken = loc(2); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; +./ + +ArgumentListOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +ArgumentListOpt: ArgumentList ; +/. +case $rule_number: { + sym(1).Node = sym(1).ArgumentList->finish(); +} break; +./ + +ArgumentList: AssignmentExpression ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Expression); +} break; +./ + +ArgumentList: ArgumentList T_COMMA AssignmentExpression ; +/. +case $rule_number: { + AST::ArgumentList *node = makeAstNode (driver->nodePool(), sym(1).ArgumentList, sym(3).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; +./ + +LeftHandSideExpression: NewExpression ; +LeftHandSideExpression: CallExpression ; +PostfixExpression: LeftHandSideExpression ; + +PostfixExpression: LeftHandSideExpression T_PLUS_PLUS ; +/. +case $rule_number: { + AST::PostIncrementExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression); + node->incrementToken = loc(2); + sym(1).Node = node; +} break; +./ + +PostfixExpression: LeftHandSideExpression T_MINUS_MINUS ; +/. +case $rule_number: { + AST::PostDecrementExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression); + node->decrementToken = loc(2); + sym(1).Node = node; +} break; +./ + +UnaryExpression: PostfixExpression ; + +UnaryExpression: T_DELETE UnaryExpression ; +/. +case $rule_number: { + AST::DeleteExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->deleteToken = loc(1); + sym(1).Node = node; +} break; +./ + +UnaryExpression: T_VOID UnaryExpression ; +/. +case $rule_number: { + AST::VoidExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->voidToken = loc(1); + sym(1).Node = node; +} break; +./ + +UnaryExpression: T_TYPEOF UnaryExpression ; +/. +case $rule_number: { + AST::TypeOfExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->typeofToken = loc(1); + sym(1).Node = node; +} break; +./ + +UnaryExpression: T_PLUS_PLUS UnaryExpression ; +/. +case $rule_number: { + AST::PreIncrementExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->incrementToken = loc(1); + sym(1).Node = node; +} break; +./ + +UnaryExpression: T_MINUS_MINUS UnaryExpression ; +/. +case $rule_number: { + AST::PreDecrementExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->decrementToken = loc(1); + sym(1).Node = node; +} break; +./ + +UnaryExpression: T_PLUS UnaryExpression ; +/. +case $rule_number: { + AST::UnaryPlusExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->plusToken = loc(1); + sym(1).Node = node; +} break; +./ + +UnaryExpression: T_MINUS UnaryExpression ; +/. +case $rule_number: { + AST::UnaryMinusExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->minusToken = loc(1); + sym(1).Node = node; +} break; +./ + +UnaryExpression: T_TILDE UnaryExpression ; +/. +case $rule_number: { + AST::TildeExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->tildeToken = loc(1); + sym(1).Node = node; +} break; +./ + +UnaryExpression: T_NOT UnaryExpression ; +/. +case $rule_number: { + AST::NotExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->notToken = loc(1); + sym(1).Node = node; +} break; +./ + +MultiplicativeExpression: UnaryExpression ; + +MultiplicativeExpression: MultiplicativeExpression T_STAR UnaryExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Mul, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +MultiplicativeExpression: MultiplicativeExpression T_DIVIDE_ UnaryExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Div, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +MultiplicativeExpression: MultiplicativeExpression T_REMAINDER UnaryExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Mod, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +AdditiveExpression: MultiplicativeExpression ; + +AdditiveExpression: AdditiveExpression T_PLUS MultiplicativeExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Add, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +AdditiveExpression: AdditiveExpression T_MINUS MultiplicativeExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Sub, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +ShiftExpression: AdditiveExpression ; + +ShiftExpression: ShiftExpression T_LT_LT AdditiveExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::LShift, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +ShiftExpression: ShiftExpression T_GT_GT AdditiveExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::RShift, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +ShiftExpression: ShiftExpression T_GT_GT_GT AdditiveExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::URShift, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpression: ShiftExpression ; + +RelationalExpression: RelationalExpression T_LT ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Lt, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpression: RelationalExpression T_GT ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Gt, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpression: RelationalExpression T_LE ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Le, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpression: RelationalExpression T_GE ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Ge, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpression: RelationalExpression T_INSTANCEOF ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::InstanceOf, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpression: RelationalExpression T_IN ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::In, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpressionNotIn: ShiftExpression ; + +RelationalExpressionNotIn: RelationalExpressionNotIn T_LT ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Lt, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpressionNotIn: RelationalExpressionNotIn T_GT ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Gt, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpressionNotIn: RelationalExpressionNotIn T_LE ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Le, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpressionNotIn: RelationalExpressionNotIn T_GE ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Ge, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +RelationalExpressionNotIn: RelationalExpressionNotIn T_INSTANCEOF ShiftExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::InstanceOf, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +EqualityExpression: RelationalExpression ; + +EqualityExpression: EqualityExpression T_EQ_EQ RelationalExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Equal, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +EqualityExpression: EqualityExpression T_NOT_EQ RelationalExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::NotEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +EqualityExpression: EqualityExpression T_EQ_EQ_EQ RelationalExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::StrictEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +EqualityExpression: EqualityExpression T_NOT_EQ_EQ RelationalExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::StrictNotEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +EqualityExpressionNotIn: RelationalExpressionNotIn ; + +EqualityExpressionNotIn: EqualityExpressionNotIn T_EQ_EQ RelationalExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Equal, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +EqualityExpressionNotIn: EqualityExpressionNotIn T_NOT_EQ RelationalExpressionNotIn; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::NotEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +EqualityExpressionNotIn: EqualityExpressionNotIn T_EQ_EQ_EQ RelationalExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::StrictEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +EqualityExpressionNotIn: EqualityExpressionNotIn T_NOT_EQ_EQ RelationalExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::StrictNotEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +BitwiseANDExpression: EqualityExpression ; + +BitwiseANDExpression: BitwiseANDExpression T_AND EqualityExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitAnd, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +BitwiseANDExpressionNotIn: EqualityExpressionNotIn ; + +BitwiseANDExpressionNotIn: BitwiseANDExpressionNotIn T_AND EqualityExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitAnd, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +BitwiseXORExpression: BitwiseANDExpression ; + +BitwiseXORExpression: BitwiseXORExpression T_XOR BitwiseANDExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitXor, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +BitwiseXORExpressionNotIn: BitwiseANDExpressionNotIn ; + +BitwiseXORExpressionNotIn: BitwiseXORExpressionNotIn T_XOR BitwiseANDExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitXor, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +BitwiseORExpression: BitwiseXORExpression ; + +BitwiseORExpression: BitwiseORExpression T_OR BitwiseXORExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitOr, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +BitwiseORExpressionNotIn: BitwiseXORExpressionNotIn ; + +BitwiseORExpressionNotIn: BitwiseORExpressionNotIn T_OR BitwiseXORExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitOr, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +LogicalANDExpression: BitwiseORExpression ; + +LogicalANDExpression: LogicalANDExpression T_AND_AND BitwiseORExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::And, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +LogicalANDExpressionNotIn: BitwiseORExpressionNotIn ; + +LogicalANDExpressionNotIn: LogicalANDExpressionNotIn T_AND_AND BitwiseORExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::And, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +LogicalORExpression: LogicalANDExpression ; + +LogicalORExpression: LogicalORExpression T_OR_OR LogicalANDExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Or, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +LogicalORExpressionNotIn: LogicalANDExpressionNotIn ; + +LogicalORExpressionNotIn: LogicalORExpressionNotIn T_OR_OR LogicalANDExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Or, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +ConditionalExpression: LogicalORExpression ; + +ConditionalExpression: LogicalORExpression T_QUESTION AssignmentExpression T_COLON AssignmentExpression ; +/. +case $rule_number: { + AST::ConditionalExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + sym(3).Expression, sym(5).Expression); + node->questionToken = loc(2); + node->colonToken = loc(4); + sym(1).Node = node; +} break; +./ + +ConditionalExpressionNotIn: LogicalORExpressionNotIn ; + +ConditionalExpressionNotIn: LogicalORExpressionNotIn T_QUESTION AssignmentExpressionNotIn T_COLON AssignmentExpressionNotIn ; +/. +case $rule_number: { + AST::ConditionalExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + sym(3).Expression, sym(5).Expression); + node->questionToken = loc(2); + node->colonToken = loc(4); + sym(1).Node = node; +} break; +./ + +AssignmentExpression: ConditionalExpression ; + +AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + sym(2).ival, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +AssignmentExpressionNotIn: ConditionalExpressionNotIn ; + +AssignmentExpressionNotIn: LeftHandSideExpression AssignmentOperator AssignmentExpressionNotIn ; +/. +case $rule_number: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + sym(2).ival, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; +./ + +AssignmentOperator: T_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::Assign; +} break; +./ + +AssignmentOperator: T_STAR_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceMul; +} break; +./ + +AssignmentOperator: T_DIVIDE_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceDiv; +} break; +./ + +AssignmentOperator: T_REMAINDER_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceMod; +} break; +./ + +AssignmentOperator: T_PLUS_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceAdd; +} break; +./ + +AssignmentOperator: T_MINUS_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceSub; +} break; +./ + +AssignmentOperator: T_LT_LT_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceLeftShift; +} break; +./ + +AssignmentOperator: T_GT_GT_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceRightShift; +} break; +./ + +AssignmentOperator: T_GT_GT_GT_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceURightShift; +} break; +./ + +AssignmentOperator: T_AND_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceAnd; +} break; +./ + +AssignmentOperator: T_XOR_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceXor; +} break; +./ + +AssignmentOperator: T_OR_EQ ; +/. +case $rule_number: { + sym(1).ival = QSOperator::InplaceOr; +} break; +./ + +Expression: AssignmentExpression ; + +Expression: Expression T_COMMA AssignmentExpression ; +/. +case $rule_number: { + AST::Expression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; +./ + +ExpressionOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +ExpressionOpt: Expression ; + +ExpressionNotIn: AssignmentExpressionNotIn ; + +ExpressionNotIn: ExpressionNotIn T_COMMA AssignmentExpressionNotIn ; +/. +case $rule_number: { + AST::Expression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; +./ + +ExpressionNotInOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +ExpressionNotInOpt: ExpressionNotIn ; + +Statement: Block ; +Statement: VariableStatement ; +Statement: EmptyStatement ; +Statement: ExpressionStatement ; +Statement: IfStatement ; +Statement: IterationStatement ; +Statement: ContinueStatement ; +Statement: BreakStatement ; +Statement: ReturnStatement ; +Statement: WithStatement ; +Statement: LabelledStatement ; +Statement: SwitchStatement ; +Statement: ThrowStatement ; +Statement: TryStatement ; +Statement: DebuggerStatement ; + + +Block: T_LBRACE StatementListOpt T_RBRACE ; +/. +case $rule_number: { + AST::Block *node = makeAstNode (driver->nodePool(), sym(2).StatementList); + node->lbraceToken = loc(1); + node->rbraceToken = loc(3); + sym(1).Node = node; +} break; +./ + +StatementList: Statement ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Statement); +} break; +./ + +StatementList: StatementList Statement ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).StatementList, sym(2).Statement); +} break; +./ + +StatementListOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +StatementListOpt: StatementList ; +/. +case $rule_number: { + sym(1).Node = sym(1).StatementList->finish (); +} break; +./ + +VariableStatement: VariableDeclarationKind VariableDeclarationList T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +VariableStatement: VariableDeclarationKind VariableDeclarationList T_SEMICOLON ; +/. +case $rule_number: { + AST::VariableStatement *node = makeAstNode (driver->nodePool(), + sym(2).VariableDeclarationList->finish (/*readOnly=*/sym(1).ival == T_CONST)); + node->declarationKindToken = loc(1); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; +./ + +VariableDeclarationKind: T_CONST ; +/. +case $rule_number: { + sym(1).ival = T_CONST; +} break; +./ + +VariableDeclarationKind: T_VAR ; +/. +case $rule_number: { + sym(1).ival = T_VAR; +} break; +./ + +VariableDeclarationList: VariableDeclaration ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclaration); +} break; +./ + +VariableDeclarationList: VariableDeclarationList T_COMMA VariableDeclaration ; +/. +case $rule_number: { + AST::VariableDeclarationList *node = makeAstNode (driver->nodePool(), + sym(1).VariableDeclarationList, sym(3).VariableDeclaration); + node->commaToken = loc(2); + sym(1).Node = node; +} break; +./ + +VariableDeclarationListNotIn: VariableDeclarationNotIn ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclaration); +} break; +./ + +VariableDeclarationListNotIn: VariableDeclarationListNotIn T_COMMA VariableDeclarationNotIn ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclarationList, sym(3).VariableDeclaration); +} break; +./ + +VariableDeclaration: JsIdentifier InitialiserOpt ; +/. +case $rule_number: { + AST::VariableDeclaration *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(2).Expression); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; +./ + +VariableDeclarationNotIn: JsIdentifier InitialiserNotInOpt ; +/. +case $rule_number: { + AST::VariableDeclaration *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(2).Expression); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; +./ + +Initialiser: T_EQ AssignmentExpression ; +/. +case $rule_number: { + // ### TODO: AST for initializer + sym(1) = sym(2); +} break; +./ + +InitialiserOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +InitialiserOpt: Initialiser ; + +InitialiserNotIn: T_EQ AssignmentExpressionNotIn ; +/. +case $rule_number: { + // ### TODO: AST for initializer + sym(1) = sym(2); +} break; +./ + +InitialiserNotInOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +InitialiserNotInOpt: InitialiserNotIn ; + +EmptyStatement: T_SEMICOLON ; +/. +case $rule_number: { + AST::EmptyStatement *node = makeAstNode (driver->nodePool()); + node->semicolonToken = loc(1); + sym(1).Node = node; +} break; +./ + +ExpressionStatement: Expression T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +ExpressionStatement: Expression T_SEMICOLON ; +/. +case $rule_number: { + AST::ExpressionStatement *node = makeAstNode (driver->nodePool(), sym(1).Expression); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; +./ + +IfStatement: T_IF T_LPAREN Expression T_RPAREN Statement T_ELSE Statement ; +/. +case $rule_number: { + AST::IfStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement, sym(7).Statement); + node->ifToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + node->elseToken = loc(5); + sym(1).Node = node; +} break; +./ + +IfStatement: T_IF T_LPAREN Expression T_RPAREN Statement ; +/. +case $rule_number: { + AST::IfStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); + node->ifToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; +./ + + +IterationStatement: T_DO Statement T_WHILE T_LPAREN Expression T_RPAREN T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +IterationStatement: T_DO Statement T_WHILE T_LPAREN Expression T_RPAREN T_SEMICOLON ; +/. +case $rule_number: { + AST::DoWhileStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(5).Expression); + node->doToken = loc(1); + node->whileToken = loc(3); + node->lparenToken = loc(4); + node->rparenToken = loc(6); + node->semicolonToken = loc(7); + sym(1).Node = node; +} break; +./ + +IterationStatement: T_WHILE T_LPAREN Expression T_RPAREN Statement ; +/. +case $rule_number: { + AST::WhileStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); + node->whileToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; +./ + +IterationStatement: T_FOR T_LPAREN ExpressionNotInOpt T_SEMICOLON ExpressionOpt T_SEMICOLON ExpressionOpt T_RPAREN Statement ; +/. +case $rule_number: { + AST::ForStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, + sym(5).Expression, sym(7).Expression, sym(9).Statement); + node->forToken = loc(1); + node->lparenToken = loc(2); + node->firstSemicolonToken = loc(4); + node->secondSemicolonToken = loc(6); + node->rparenToken = loc(8); + sym(1).Node = node; +} break; +./ + +IterationStatement: T_FOR T_LPAREN T_VAR VariableDeclarationListNotIn T_SEMICOLON ExpressionOpt T_SEMICOLON ExpressionOpt T_RPAREN Statement ; +/. +case $rule_number: { + AST::LocalForStatement *node = makeAstNode (driver->nodePool(), + sym(4).VariableDeclarationList->finish (/*readOnly=*/false), sym(6).Expression, + sym(8).Expression, sym(10).Statement); + node->forToken = loc(1); + node->lparenToken = loc(2); + node->varToken = loc(3); + node->firstSemicolonToken = loc(5); + node->secondSemicolonToken = loc(7); + node->rparenToken = loc(9); + sym(1).Node = node; +} break; +./ + +IterationStatement: T_FOR T_LPAREN LeftHandSideExpression T_IN Expression T_RPAREN Statement ; +/. +case $rule_number: { + AST:: ForEachStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, + sym(5).Expression, sym(7).Statement); + node->forToken = loc(1); + node->lparenToken = loc(2); + node->inToken = loc(4); + node->rparenToken = loc(6); + sym(1).Node = node; +} break; +./ + +IterationStatement: T_FOR T_LPAREN T_VAR VariableDeclarationNotIn T_IN Expression T_RPAREN Statement ; +/. +case $rule_number: { + AST::LocalForEachStatement *node = makeAstNode (driver->nodePool(), + sym(4).VariableDeclaration, sym(6).Expression, sym(8).Statement); + node->forToken = loc(1); + node->lparenToken = loc(2); + node->varToken = loc(3); + node->inToken = loc(5); + node->rparenToken = loc(7); + sym(1).Node = node; +} break; +./ + +ContinueStatement: T_CONTINUE T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +ContinueStatement: T_CONTINUE T_SEMICOLON ; +/. +case $rule_number: { + AST::ContinueStatement *node = makeAstNode (driver->nodePool()); + node->continueToken = loc(1); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; +./ + +ContinueStatement: T_CONTINUE JsIdentifier T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +ContinueStatement: T_CONTINUE JsIdentifier T_SEMICOLON ; +/. +case $rule_number: { + AST::ContinueStatement *node = makeAstNode (driver->nodePool(), sym(2).sval); + node->continueToken = loc(1); + node->identifierToken = loc(2); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; +./ + +BreakStatement: T_BREAK T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +BreakStatement: T_BREAK T_SEMICOLON ; +/. +case $rule_number: { + AST::BreakStatement *node = makeAstNode (driver->nodePool()); + node->breakToken = loc(1); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; +./ + +BreakStatement: T_BREAK JsIdentifier T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +BreakStatement: T_BREAK JsIdentifier T_SEMICOLON ; +/. +case $rule_number: { + AST::BreakStatement *node = makeAstNode (driver->nodePool(), sym(2).sval); + node->breakToken = loc(1); + node->identifierToken = loc(2); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; +./ + +ReturnStatement: T_RETURN ExpressionOpt T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +ReturnStatement: T_RETURN ExpressionOpt T_SEMICOLON ; +/. +case $rule_number: { + AST::ReturnStatement *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->returnToken = loc(1); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; +./ + +WithStatement: T_WITH T_LPAREN Expression T_RPAREN Statement ; +/. +case $rule_number: { + AST::WithStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); + node->withToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; +./ + +SwitchStatement: T_SWITCH T_LPAREN Expression T_RPAREN CaseBlock ; +/. +case $rule_number: { + AST::SwitchStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).CaseBlock); + node->switchToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; +./ + +CaseBlock: T_LBRACE CaseClausesOpt T_RBRACE ; +/. +case $rule_number: { + AST::CaseBlock *node = makeAstNode (driver->nodePool(), sym(2).CaseClauses); + node->lbraceToken = loc(1); + node->rbraceToken = loc(3); + sym(1).Node = node; +} break; +./ + +CaseBlock: T_LBRACE CaseClausesOpt DefaultClause CaseClausesOpt T_RBRACE ; +/. +case $rule_number: { + AST::CaseBlock *node = makeAstNode (driver->nodePool(), sym(2).CaseClauses, sym(3).DefaultClause, sym(4).CaseClauses); + node->lbraceToken = loc(1); + node->rbraceToken = loc(5); + sym(1).Node = node; +} break; +./ + +CaseClauses: CaseClause ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).CaseClause); +} break; +./ + +CaseClauses: CaseClauses CaseClause ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).CaseClauses, sym(2).CaseClause); +} break; +./ + +CaseClausesOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +CaseClausesOpt: CaseClauses ; +/. +case $rule_number: { + sym(1).Node = sym(1).CaseClauses->finish (); +} break; +./ + +CaseClause: T_CASE Expression T_COLON StatementListOpt ; +/. +case $rule_number: { + AST::CaseClause *node = makeAstNode (driver->nodePool(), sym(2).Expression, sym(4).StatementList); + node->caseToken = loc(1); + node->colonToken = loc(3); + sym(1).Node = node; +} break; +./ + +DefaultClause: T_DEFAULT T_COLON StatementListOpt ; +/. +case $rule_number: { + AST::DefaultClause *node = makeAstNode (driver->nodePool(), sym(3).StatementList); + node->defaultToken = loc(1); + node->colonToken = loc(2); + sym(1).Node = node; +} break; +./ + +LabelledStatement: T_SIGNAL T_COLON Statement ; +/.case $rule_number:./ + +LabelledStatement: T_PROPERTY T_COLON Statement ; +/. +case $rule_number: { + AST::LabelledStatement *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount()), sym(3).Statement); + node->identifierToken = loc(1); + node->colonToken = loc(2); + sym(1).Node = node; +} break; +./ + +LabelledStatement: T_IDENTIFIER T_COLON Statement ; +/. +case $rule_number: { + AST::LabelledStatement *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(3).Statement); + node->identifierToken = loc(1); + node->colonToken = loc(2); + sym(1).Node = node; +} break; +./ + +ThrowStatement: T_THROW Expression T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +ThrowStatement: T_THROW Expression T_SEMICOLON ; +/. +case $rule_number: { + AST::ThrowStatement *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->throwToken = loc(1); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; +./ + +TryStatement: T_TRY Block Catch ; +/. +case $rule_number: { + AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Catch); + node->tryToken = loc(1); + sym(1).Node = node; +} break; +./ + +TryStatement: T_TRY Block Finally ; +/. +case $rule_number: { + AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Finally); + node->tryToken = loc(1); + sym(1).Node = node; +} break; +./ + +TryStatement: T_TRY Block Catch Finally ; +/. +case $rule_number: { + AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Catch, sym(4).Finally); + node->tryToken = loc(1); + sym(1).Node = node; +} break; +./ + +Catch: T_CATCH T_LPAREN JsIdentifier T_RPAREN Block ; +/. +case $rule_number: { + AST::Catch *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(5).Block); + node->catchToken = loc(1); + node->lparenToken = loc(2); + node->identifierToken = loc(3); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; +./ + +Finally: T_FINALLY Block ; +/. +case $rule_number: { + AST::Finally *node = makeAstNode (driver->nodePool(), sym(2).Block); + node->finallyToken = loc(1); + sym(1).Node = node; +} break; +./ + +DebuggerStatement: T_DEBUGGER T_AUTOMATIC_SEMICOLON ; -- automatic semicolon +DebuggerStatement: T_DEBUGGER T_SEMICOLON ; +/. +case $rule_number: { + AST::DebuggerStatement *node = makeAstNode (driver->nodePool()); + node->debuggerToken = loc(1); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; +./ + +FunctionDeclaration: T_FUNCTION JsIdentifier T_LPAREN FormalParameterListOpt T_RPAREN T_LBRACE FunctionBodyOpt T_RBRACE ; +/. +case $rule_number: { + AST::FunctionDeclaration *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody); + node->functionToken = loc(1); + node->identifierToken = loc(2); + node->lparenToken = loc(3); + node->rparenToken = loc(5); + node->lbraceToken = loc(6); + node->rbraceToken = loc(8); + sym(1).Node = node; +} break; +./ + +FunctionExpression: T_FUNCTION IdentifierOpt T_LPAREN FormalParameterListOpt T_RPAREN T_LBRACE FunctionBodyOpt T_RBRACE ; +/. +case $rule_number: { + AST::FunctionExpression *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody); + node->functionToken = loc(1); + if (sym(2).sval) + node->identifierToken = loc(2); + node->lparenToken = loc(3); + node->rparenToken = loc(5); + node->lbraceToken = loc(6); + node->rbraceToken = loc(8); + sym(1).Node = node; +} break; +./ + +FormalParameterList: JsIdentifier ; +/. +case $rule_number: { + AST::FormalParameterList *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; +./ + +FormalParameterList: FormalParameterList T_COMMA JsIdentifier ; +/. +case $rule_number: { + AST::FormalParameterList *node = makeAstNode (driver->nodePool(), sym(1).FormalParameterList, sym(3).sval); + node->commaToken = loc(2); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; +./ + +FormalParameterListOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +FormalParameterListOpt: FormalParameterList ; +/. +case $rule_number: { + sym(1).Node = sym(1).FormalParameterList->finish (); +} break; +./ + +FunctionBodyOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +FunctionBodyOpt: FunctionBody ; + +FunctionBody: SourceElements ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements->finish ()); +} break; +./ + +--QmlJSProgram: SourceElements ; +--/. +--case $rule_number: { +-- sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements->finish ()); +-- driver->changeAbstractSyntaxTree(sym(1).Node); +--} break; +--./ + +SourceElements: SourceElement ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElement); +} break; +./ + +SourceElements: SourceElements SourceElement ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements, sym(2).SourceElement); +} break; +./ + +SourceElement: Statement ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Statement); +} break; +./ + +SourceElement: FunctionDeclaration ; +/. +case $rule_number: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).FunctionDeclaration); +} break; +./ + +IdentifierOpt: ; +/. +case $rule_number: { + sym(1).sval = 0; +} break; +./ + +IdentifierOpt: JsIdentifier ; + +PropertyNameAndValueListOpt: ; +/. +case $rule_number: { + sym(1).Node = 0; +} break; +./ + +PropertyNameAndValueListOpt: PropertyNameAndValueList ; + +/. + } // switch + action = nt_action(state_stack[tos], lhs[r] - TERMINAL_COUNT); + } // if + } while (action != 0); + + if (first_token == last_token) { + const int errorState = state_stack[tos]; + + // automatic insertion of `;' + if (t_action(errorState, T_AUTOMATIC_SEMICOLON) && automatic(driver, yytoken)) { + SavedToken &tk = token_buffer[0]; + tk.token = yytoken; + tk.dval = yylval; + tk.loc = yylloc; + + yylloc = yyprevlloc; + yylloc.offset += yylloc.length; + yylloc.startColumn += yylloc.length; + yylloc.length = 0; + + //const QString msg = QString::fromUtf8("Missing `;'"); + //diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, yylloc, msg)); + + first_token = &token_buffer[0]; + last_token = &token_buffer[1]; + + yytoken = T_SEMICOLON; + yylval = 0; + + action = errorState; + + goto _Lcheck_token; + } + + hadErrors = true; + + token_buffer[0].token = yytoken; + token_buffer[0].dval = yylval; + token_buffer[0].loc = yylloc; + + token_buffer[1].token = yytoken = lexer->lex(); + token_buffer[1].dval = yylval = lexer->dval(); + token_buffer[1].loc = yylloc = location(lexer); + + if (t_action(errorState, yytoken)) { + const QString msg = QString::fromUtf8("Unexpected token `%1'").arg(QLatin1String(spell[token_buffer[0].token])); + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); + + action = errorState; + goto _Lcheck_token; + } + + static int tokens[] = { + T_PLUS, + T_EQ, + + T_COMMA, + T_COLON, + T_SEMICOLON, + + T_RPAREN, T_RBRACKET, T_RBRACE, + + T_NUMERIC_LITERAL, + T_IDENTIFIER, + + T_LPAREN, T_LBRACKET, T_LBRACE, + + EOF_SYMBOL + }; + + for (int *tk = tokens; *tk != EOF_SYMBOL; ++tk) { + int a = t_action(errorState, *tk); + if (a > 0 && t_action(a, yytoken)) { + const QString msg = QString::fromUtf8("Expected token `%1'").arg(QLatin1String(spell[*tk])); + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); + + yytoken = *tk; + yylval = 0; + yylloc = token_buffer[0].loc; + yylloc.length = 0; + + first_token = &token_buffer[0]; + last_token = &token_buffer[2]; + + action = errorState; + goto _Lcheck_token; + } + } + + for (int tk = 1; tk < TERMINAL_COUNT; ++tk) { + if (tk == T_AUTOMATIC_SEMICOLON) + continue; + + int a = t_action(errorState, tk); + if (a > 0 && t_action(a, yytoken)) { + const QString msg = QString::fromUtf8("Expected token `%1'").arg(QLatin1String(spell[tk])); + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); + + yytoken = tk; + yylval = 0; + yylloc = token_buffer[0].loc; + yylloc.length = 0; + + action = errorState; + goto _Lcheck_token; + } + } + + const QString msg = QString::fromUtf8("Syntax error"); + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); + } + + return false; +} + +QT_END_NAMESPACE + + +./ +/: +QT_END_NAMESPACE + + + +#endif // QMLJSPARSER_P_H +:/ diff --git a/src/declarative/qml/parser/qmljsast.cpp b/src/declarative/qml/parser/qmljsast.cpp new file mode 100644 index 0000000..d10c071 --- /dev/null +++ b/src/declarative/qml/parser/qmljsast.cpp @@ -0,0 +1,962 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmljsast_p.h" + + + +#include "qmljsastvisitor_p.h" + +QT_BEGIN_NAMESPACE + +namespace QmlJS { namespace AST { + +int NumericLiteral::suffixLength[] = { + 0, // noSuffix + 2, // emSuffix + 2, // exSuffix + 2, // pxSuffix + 2, // cmSuffix + 2, // mmSuffix + 2, // inSuffix + 2, // ptSuffix + 2, // pcSuffix + 3, // degSuffix + 3, // radSuffix + 4, // gradSuffix + 2, // msSuffix + 1, // sSuffix + 2, // hzSuffix + 3 // khzSuffix +}; + +const char *const NumericLiteral::suffixSpell[] = { + "", + "em", + "ex", + "px", + "cm", + "mm", + "in", + "pt", + "pc", + "deg", + "rad", + "grad", + "ms", + "s", + "hz", + "khz" +}; + +ExpressionNode *Node::expressionCast() +{ + return 0; +} + +BinaryExpression *Node::binaryExpressionCast() +{ + return 0; +} + +Statement *Node::statementCast() +{ + return 0; +} + +ExpressionNode *ExpressionNode::expressionCast() +{ + return this; +} + +BinaryExpression *BinaryExpression::binaryExpressionCast() +{ + return this; +} + +Statement *Statement::statementCast() +{ + return this; +} + +void NestedExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + visitor->endVisit(this); +} + +void ThisExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void IdentifierExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void NullExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void TrueLiteral::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void FalseLiteral::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void StringLiteral::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void NumericLiteral::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void RegExpLiteral::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void ArrayLiteral::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(elements, visitor); + acceptChild(elision, visitor); + } + + visitor->endVisit(this); +} + +void ObjectLiteral::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(properties, visitor); + } + + visitor->endVisit(this); +} + +void ElementList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + ElementList *it = this; + do { + acceptChild(it->elision, visitor); + acceptChild(it->expression, visitor); + it = it->next; + } while (it); + } + + visitor->endVisit(this); +} + +void Elision::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + // ### + } + + visitor->endVisit(this); +} + +void PropertyNameAndValueList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + PropertyNameAndValueList *it = this; + do { + acceptChild(it->name, visitor); + acceptChild(it->value, visitor); + it = it->next; + } while (it); + } + + visitor->endVisit(this); +} + +void IdentifierPropertyName::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void StringLiteralPropertyName::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void NumericLiteralPropertyName::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void ArrayMemberExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(base, visitor); + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void FieldMemberExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(base, visitor); + } + + visitor->endVisit(this); +} + +void NewMemberExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(base, visitor); + acceptChild(arguments, visitor); + } + + visitor->endVisit(this); +} + +void NewExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void CallExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(base, visitor); + acceptChild(arguments, visitor); + } + + visitor->endVisit(this); +} + +void ArgumentList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + ArgumentList *it = this; + do { + acceptChild(it->expression, visitor); + it = it->next; + } while (it); + } + + visitor->endVisit(this); +} + +void PostIncrementExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(base, visitor); + } + + visitor->endVisit(this); +} + +void PostDecrementExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(base, visitor); + } + + visitor->endVisit(this); +} + +void DeleteExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void VoidExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void TypeOfExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void PreIncrementExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void PreDecrementExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void UnaryPlusExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void UnaryMinusExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void TildeExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void NotExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void BinaryExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(left, visitor); + acceptChild(right, visitor); + } + + visitor->endVisit(this); +} + +void ConditionalExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + acceptChild(ok, visitor); + acceptChild(ko, visitor); + } + + visitor->endVisit(this); +} + +void Expression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(left, visitor); + acceptChild(right, visitor); + } + + visitor->endVisit(this); +} + +void Block::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(statements, visitor); + } + + visitor->endVisit(this); +} + +void StatementList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + StatementList *it = this; + do { + acceptChild(it->statement, visitor); + it = it->next; + } while (it); + } + + visitor->endVisit(this); +} + +void VariableStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(declarations, visitor); + } + + visitor->endVisit(this); +} + +void VariableDeclarationList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + VariableDeclarationList *it = this; + do { + acceptChild(it->declaration, visitor); + it = it->next; + } while (it); + } + + visitor->endVisit(this); +} + +void VariableDeclaration::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void EmptyStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void ExpressionStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void IfStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + acceptChild(ok, visitor); + acceptChild(ko, visitor); + } + + visitor->endVisit(this); +} + +void DoWhileStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(statement, visitor); + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void WhileStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void ForStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(initialiser, visitor); + acceptChild(condition, visitor); + acceptChild(expression, visitor); + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void LocalForStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(declarations, visitor); + acceptChild(condition, visitor); + acceptChild(expression, visitor); + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void ForEachStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(initialiser, visitor); + acceptChild(expression, visitor); + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void LocalForEachStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(declaration, visitor); + acceptChild(expression, visitor); + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void ContinueStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void BreakStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void ReturnStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void WithStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void SwitchStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + acceptChild(block, visitor); + } + + visitor->endVisit(this); +} + +void CaseBlock::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(clauses, visitor); + acceptChild(defaultClause, visitor); + acceptChild(moreClauses, visitor); + } + + visitor->endVisit(this); +} + +void CaseClauses::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + CaseClauses *it = this; + do { + acceptChild(it->clause, visitor); + it = it->next; + } while (it); + } + + visitor->endVisit(this); +} + +void CaseClause::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + acceptChild(statements, visitor); + } + + visitor->endVisit(this); +} + +void DefaultClause::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(statements, visitor); + } + + visitor->endVisit(this); +} + +void LabelledStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void ThrowStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void TryStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(statement, visitor); + acceptChild(catchExpression, visitor); + acceptChild(finallyExpression, visitor); + } + + visitor->endVisit(this); +} + +void Catch::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void Finally::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void FunctionDeclaration::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(formals, visitor); + acceptChild(body, visitor); + } + + visitor->endVisit(this); +} + +void FunctionExpression::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(formals, visitor); + acceptChild(body, visitor); + } + + visitor->endVisit(this); +} + +void FormalParameterList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + // ### + } + + visitor->endVisit(this); +} + +void FunctionBody::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(elements, visitor); + } + + visitor->endVisit(this); +} + +void Program::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(elements, visitor); + } + + visitor->endVisit(this); +} + +void SourceElements::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + SourceElements *it = this; + do { + acceptChild(it->element, visitor); + it = it->next; + } while (it); + } + + visitor->endVisit(this); +} + +void FunctionSourceElement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(declaration, visitor); + } + + visitor->endVisit(this); +} + +void StatementSourceElement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void DebuggerStatement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + + +void UiProgram::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + for (UiObjectMemberList *it = members; it; it = it->next) + acceptChild(it->member, visitor); + } + + visitor->endVisit(this); +} + +void UiPublicMember::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(expression, visitor); + } + + visitor->endVisit(this); +} + +void UiObjectDefinition::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(qualifiedTypeNameId, visitor); + acceptChild(initializer, visitor); + } + + visitor->endVisit(this); +} + +void UiObjectInitializer::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + for (UiObjectMemberList *it = members; it; it = it->next) + acceptChild(it->member, visitor); + } + + visitor->endVisit(this); +} + +void UiObjectBinding::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(qualifiedId, visitor); + acceptChild(qualifiedTypeNameId, visitor); + acceptChild(initializer, visitor); + } + + visitor->endVisit(this); +} + +void UiScriptBinding::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(qualifiedId, visitor); + acceptChild(statement, visitor); + } + + visitor->endVisit(this); +} + +void UiArrayBinding::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(qualifiedId, visitor); + for (UiArrayMemberList *it = members; it; it = it->next) + acceptChild(it->member, visitor); + } + + visitor->endVisit(this); +} + +void UiObjectMemberList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + for (UiObjectMemberList *it = this; it; it = it->next) + acceptChild(it->member, visitor); + } + + visitor->endVisit(this); +} + +void UiArrayMemberList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + for (UiArrayMemberList *it = this; it; it = it->next) + acceptChild(it->member, visitor); + } + + visitor->endVisit(this); +} + +void UiQualifiedId::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void UiImport::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + } + + visitor->endVisit(this); +} + +void UiImportList::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(import, visitor); + acceptChild(next, visitor); + } + + visitor->endVisit(this); +} + +void UiSourceElement::accept0(Visitor *visitor) +{ + if (visitor->visit(this)) { + acceptChild(sourceElement, visitor); + } + + visitor->endVisit(this); +} + +} } // namespace QmlJS::AST + +QT_END_NAMESPACE + + diff --git a/src/declarative/qml/parser/qmljsast_p.h b/src/declarative/qml/parser/qmljsast_p.h new file mode 100644 index 0000000..8dc32ed --- /dev/null +++ b/src/declarative/qml/parser/qmljsast_p.h @@ -0,0 +1,2544 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLJSAST_P_H +#define QMLJSAST_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qmljsastvisitor_p.h" +#include + +QT_BEGIN_NAMESPACE + +#define QMLJS_DECLARE_AST_NODE(name) \ + enum { K = Kind_##name }; + +namespace QSOperator // ### rename +{ + +enum Op { + Add, + And, + InplaceAnd, + Assign, + BitAnd, + BitOr, + BitXor, + InplaceSub, + Div, + InplaceDiv, + Equal, + Ge, + Gt, + In, + InplaceAdd, + InstanceOf, + Le, + LShift, + InplaceLeftShift, + Lt, + Mod, + InplaceMod, + Mul, + InplaceMul, + NotEqual, + Or, + InplaceOr, + RShift, + InplaceRightShift, + StrictEqual, + StrictNotEqual, + Sub, + URShift, + InplaceURightShift, + InplaceXor +}; + +} // namespace QSOperator + +namespace QmlJS { +class NameId; +namespace AST { + +template +_T1 cast(_T2 *ast) +{ + if (ast && ast->kind == static_cast<_T1>(0)->K) + return static_cast<_T1>(ast); + + return 0; +} + +class Node +{ +public: + enum Kind { + Kind_Undefined, + + Kind_ArgumentList, + Kind_ArrayLiteral, + Kind_ArrayMemberExpression, + Kind_BinaryExpression, + Kind_Block, + Kind_BreakStatement, + Kind_CallExpression, + Kind_CaseBlock, + Kind_CaseClause, + Kind_CaseClauses, + Kind_Catch, + Kind_ConditionalExpression, + Kind_ContinueStatement, + Kind_DebuggerStatement, + Kind_DefaultClause, + Kind_DeleteExpression, + Kind_DoWhileStatement, + Kind_ElementList, + Kind_Elision, + Kind_EmptyStatement, + Kind_Expression, + Kind_ExpressionStatement, + Kind_FalseLiteral, + Kind_FieldMemberExpression, + Kind_Finally, + Kind_ForEachStatement, + Kind_ForStatement, + Kind_FormalParameterList, + Kind_FunctionBody, + Kind_FunctionDeclaration, + Kind_FunctionExpression, + Kind_FunctionSourceElement, + Kind_IdentifierExpression, + Kind_IdentifierPropertyName, + Kind_IfStatement, + Kind_LabelledStatement, + Kind_LocalForEachStatement, + Kind_LocalForStatement, + Kind_NewExpression, + Kind_NewMemberExpression, + Kind_NotExpression, + Kind_NullExpression, + Kind_NumericLiteral, + Kind_NumericLiteralPropertyName, + Kind_ObjectLiteral, + Kind_PostDecrementExpression, + Kind_PostIncrementExpression, + Kind_PreDecrementExpression, + Kind_PreIncrementExpression, + Kind_Program, + Kind_PropertyName, + Kind_PropertyNameAndValueList, + Kind_RegExpLiteral, + Kind_ReturnStatement, + Kind_SourceElement, + Kind_SourceElements, + Kind_StatementList, + Kind_StatementSourceElement, + Kind_StringLiteral, + Kind_StringLiteralPropertyName, + Kind_SwitchStatement, + Kind_ThisExpression, + Kind_ThrowStatement, + Kind_TildeExpression, + Kind_TrueLiteral, + Kind_TryStatement, + Kind_TypeOfExpression, + Kind_UnaryMinusExpression, + Kind_UnaryPlusExpression, + Kind_VariableDeclaration, + Kind_VariableDeclarationList, + Kind_VariableStatement, + Kind_VoidExpression, + Kind_WhileStatement, + Kind_WithStatement, + Kind_NestedExpression, + + Kind_UiArrayBinding, + Kind_UiImport, + Kind_UiImportList, + Kind_UiObjectBinding, + Kind_UiObjectDefinition, + Kind_UiObjectInitializer, + Kind_UiObjectMemberList, + Kind_UiArrayMemberList, + Kind_UiProgram, + Kind_UiPublicMember, + Kind_UiQualifiedId, + Kind_UiScriptBinding, + Kind_UiSourceElement + }; + + inline Node() + : kind(Kind_Undefined) {} + + virtual ~Node() {} + + virtual ExpressionNode *expressionCast(); + virtual BinaryExpression *binaryExpressionCast(); + virtual Statement *statementCast(); + + inline void accept(Visitor *visitor) + { + if (visitor->preVisit(this)) { + accept0(visitor); + visitor->postVisit(this); + } + } + + static void acceptChild(Node *node, Visitor *visitor) + { + if (node) + node->accept(visitor); + } + + virtual void accept0(Visitor *visitor) = 0; + +// attributes + int kind; +}; + +class ExpressionNode: public Node +{ +public: + ExpressionNode() {} + virtual ~ExpressionNode() {} + + virtual ExpressionNode *expressionCast(); + + virtual SourceLocation firstSourceLocation() const = 0; + virtual SourceLocation lastSourceLocation() const = 0; +}; + +class Statement: public Node +{ +public: + Statement() {} + virtual ~Statement() {} + + virtual Statement *statementCast(); + + virtual SourceLocation firstSourceLocation() const = 0; + virtual SourceLocation lastSourceLocation() const = 0; +}; + +class NestedExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(NestedExpression) + + NestedExpression(ExpressionNode *expression) + : expression(expression) + { kind = K; } + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return lparenToken; } + + virtual SourceLocation lastSourceLocation() const + { return rparenToken; } + +// attributes + ExpressionNode *expression; + SourceLocation lparenToken; + SourceLocation rparenToken; +}; + +class ThisExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(ThisExpression) + + ThisExpression() { kind = K; } + virtual ~ThisExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return thisToken; } + + virtual SourceLocation lastSourceLocation() const + { return thisToken; } + +// attributes + SourceLocation thisToken; +}; + +class IdentifierExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(IdentifierExpression) + + IdentifierExpression(NameId *n): + name (n) { kind = K; } + + virtual ~IdentifierExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return identifierToken; } + + virtual SourceLocation lastSourceLocation() const + { return identifierToken; } + +// attributes + NameId *name; + SourceLocation identifierToken; +}; + +class NullExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(NullExpression) + + NullExpression() { kind = K; } + virtual ~NullExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return nullToken; } + + virtual SourceLocation lastSourceLocation() const + { return nullToken; } + +// attributes + SourceLocation nullToken; +}; + +class TrueLiteral: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(TrueLiteral) + + TrueLiteral() { kind = K; } + virtual ~TrueLiteral() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return trueToken; } + + virtual SourceLocation lastSourceLocation() const + { return trueToken; } + +// attributes + SourceLocation trueToken; +}; + +class FalseLiteral: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(FalseLiteral) + + FalseLiteral() { kind = K; } + virtual ~FalseLiteral() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return falseToken; } + + virtual SourceLocation lastSourceLocation() const + { return falseToken; } + +// attributes + SourceLocation falseToken; +}; + +class NumericLiteral: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(NumericLiteral) + + enum Suffix { // ### keep it in sync with the Suffix enum in qmljslexer_p.h + noSuffix, + emSuffix, + exSuffix, + pxSuffix, + cmSuffix, + mmSuffix, + inSuffix, + ptSuffix, + pcSuffix, + degSuffix, + radSuffix, + gradSuffix, + msSuffix, + sSuffix, + hzSuffix, + khzSuffix + }; + + static int suffixLength[]; + static const char *const suffixSpell[]; + + NumericLiteral(double v, int suffix): + value(v), suffix(suffix) { kind = K; } + virtual ~NumericLiteral() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return literalToken; } + + virtual SourceLocation lastSourceLocation() const + { return literalToken; } + +// attributes: + double value; + int suffix; + SourceLocation literalToken; +}; + +class StringLiteral: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(StringLiteral) + + StringLiteral(NameId *v): + value (v) { kind = K; } + + virtual ~StringLiteral() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return literalToken; } + + virtual SourceLocation lastSourceLocation() const + { return literalToken; } + +// attributes: + NameId *value; + SourceLocation literalToken; +}; + +class RegExpLiteral: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(RegExpLiteral) + + RegExpLiteral(NameId *p, int f): + pattern (p), flags (f) { kind = K; } + + virtual ~RegExpLiteral() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return literalToken; } + + virtual SourceLocation lastSourceLocation() const + { return literalToken; } + +// attributes: + NameId *pattern; + int flags; + SourceLocation literalToken; +}; + +class ArrayLiteral: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(ArrayLiteral) + + ArrayLiteral(Elision *e): + elements (0), elision (e) + { kind = K; } + + ArrayLiteral(ElementList *elts): + elements (elts), elision (0) + { kind = K; } + + ArrayLiteral(ElementList *elts, Elision *e): + elements (elts), elision (e) + { kind = K; } + + virtual ~ArrayLiteral() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return lbracketToken; } + + virtual SourceLocation lastSourceLocation() const + { return rbracketToken; } + +// attributes + ElementList *elements; + Elision *elision; + SourceLocation lbracketToken; + SourceLocation commaToken; + SourceLocation rbracketToken; +}; + +class ObjectLiteral: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(ObjectLiteral) + + ObjectLiteral(): + properties (0) { kind = K; } + + ObjectLiteral(PropertyNameAndValueList *plist): + properties (plist) { kind = K; } + + virtual ~ObjectLiteral() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return lbraceToken; } + + virtual SourceLocation lastSourceLocation() const + { return rbraceToken; } + +// attributes + PropertyNameAndValueList *properties; + SourceLocation lbraceToken; + SourceLocation rbraceToken; +}; + +class ElementList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(ElementList) + + ElementList(Elision *e, ExpressionNode *expr): + elision (e), expression (expr), next (this) + { kind = K; } + + ElementList(ElementList *previous, Elision *e, ExpressionNode *expr): + elision (e), expression (expr) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~ElementList() {} + + inline ElementList *finish () + { + ElementList *front = next; + next = 0; + return front; + } + + virtual void accept0(Visitor *visitor); + +// attributes + Elision *elision; + ExpressionNode *expression; + ElementList *next; + SourceLocation commaToken; +}; + +class Elision: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(Elision) + + Elision(): + next (this) { kind = K; } + + Elision(Elision *previous) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~Elision() {} + + virtual void accept0(Visitor *visitor); + + inline Elision *finish () + { + Elision *front = next; + next = 0; + return front; + } + +// attributes + Elision *next; + SourceLocation commaToken; +}; + +class PropertyNameAndValueList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(PropertyNameAndValueList) + + PropertyNameAndValueList(PropertyName *n, ExpressionNode *v): + name (n), value (v), next (this) + { kind = K; } + + PropertyNameAndValueList(PropertyNameAndValueList *previous, PropertyName *n, ExpressionNode *v): + name (n), value (v) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~PropertyNameAndValueList() {} + + virtual void accept0(Visitor *visitor); + + inline PropertyNameAndValueList *finish () + { + PropertyNameAndValueList *front = next; + next = 0; + return front; + } + +// attributes + PropertyName *name; + ExpressionNode *value; + PropertyNameAndValueList *next; + SourceLocation colonToken; + SourceLocation commaToken; +}; + +class PropertyName: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(PropertyName) + + PropertyName() { kind = K; } + virtual ~PropertyName() {} + +// attributes + SourceLocation propertyNameToken; +}; + +class IdentifierPropertyName: public PropertyName +{ +public: + QMLJS_DECLARE_AST_NODE(IdentifierPropertyName) + + IdentifierPropertyName(NameId *n): + id (n) { kind = K; } + + virtual ~IdentifierPropertyName() {} + + virtual void accept0(Visitor *visitor); + +// attributes + NameId *id; +}; + +class StringLiteralPropertyName: public PropertyName +{ +public: + QMLJS_DECLARE_AST_NODE(StringLiteralPropertyName) + + StringLiteralPropertyName(NameId *n): + id (n) { kind = K; } + virtual ~StringLiteralPropertyName() {} + + virtual void accept0(Visitor *visitor); + +// attributes + NameId *id; +}; + +class NumericLiteralPropertyName: public PropertyName +{ +public: + QMLJS_DECLARE_AST_NODE(NumericLiteralPropertyName) + + NumericLiteralPropertyName(double n): + id (n) { kind = K; } + virtual ~NumericLiteralPropertyName() {} + + virtual void accept0(Visitor *visitor); + +// attributes + double id; +}; + +class ArrayMemberExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(ArrayMemberExpression) + + ArrayMemberExpression(ExpressionNode *b, ExpressionNode *e): + base (b), expression (e) + { kind = K; } + + virtual ~ArrayMemberExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return base->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return rbracketToken; } + +// attributes + ExpressionNode *base; + ExpressionNode *expression; + SourceLocation lbracketToken; + SourceLocation rbracketToken; +}; + +class FieldMemberExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(FieldMemberExpression) + + FieldMemberExpression(ExpressionNode *b, NameId *n): + base (b), name (n) + { kind = K; } + + virtual ~FieldMemberExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return base->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return identifierToken; } + + // attributes + ExpressionNode *base; + NameId *name; + SourceLocation dotToken; + SourceLocation identifierToken; +}; + +class NewMemberExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(NewMemberExpression) + + NewMemberExpression(ExpressionNode *b, ArgumentList *a): + base (b), arguments (a) + { kind = K; } + + virtual ~NewMemberExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return newToken; } + + virtual SourceLocation lastSourceLocation() const + { return rparenToken; } + + // attributes + ExpressionNode *base; + ArgumentList *arguments; + SourceLocation newToken; + SourceLocation lparenToken; + SourceLocation rparenToken; +}; + +class NewExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(NewExpression) + + NewExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~NewExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return newToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation newToken; +}; + +class CallExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(CallExpression) + + CallExpression(ExpressionNode *b, ArgumentList *a): + base (b), arguments (a) + { kind = K; } + + virtual ~CallExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return base->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return rparenToken; } + +// attributes + ExpressionNode *base; + ArgumentList *arguments; + SourceLocation lparenToken; + SourceLocation rparenToken; +}; + +class ArgumentList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(ArgumentList) + + ArgumentList(ExpressionNode *e): + expression (e), next (this) + { kind = K; } + + ArgumentList(ArgumentList *previous, ExpressionNode *e): + expression (e) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~ArgumentList() {} + + virtual void accept0(Visitor *visitor); + + inline ArgumentList *finish () + { + ArgumentList *front = next; + next = 0; + return front; + } + +// attributes + ExpressionNode *expression; + ArgumentList *next; + SourceLocation commaToken; +}; + +class PostIncrementExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(PostIncrementExpression) + + PostIncrementExpression(ExpressionNode *b): + base (b) { kind = K; } + + virtual ~PostIncrementExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return base->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return incrementToken; } + +// attributes + ExpressionNode *base; + SourceLocation incrementToken; +}; + +class PostDecrementExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(PostDecrementExpression) + + PostDecrementExpression(ExpressionNode *b): + base (b) { kind = K; } + + virtual ~PostDecrementExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return base->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return decrementToken; } + +// attributes + ExpressionNode *base; + SourceLocation decrementToken; +}; + +class DeleteExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(DeleteExpression) + + DeleteExpression(ExpressionNode *e): + expression (e) { kind = K; } + virtual ~DeleteExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return deleteToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation deleteToken; +}; + +class VoidExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(VoidExpression) + + VoidExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~VoidExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return voidToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation voidToken; +}; + +class TypeOfExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(TypeOfExpression) + + TypeOfExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~TypeOfExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return typeofToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation typeofToken; +}; + +class PreIncrementExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(PreIncrementExpression) + + PreIncrementExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~PreIncrementExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return incrementToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation incrementToken; +}; + +class PreDecrementExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(PreDecrementExpression) + + PreDecrementExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~PreDecrementExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return decrementToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation decrementToken; +}; + +class UnaryPlusExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(UnaryPlusExpression) + + UnaryPlusExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~UnaryPlusExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return plusToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation plusToken; +}; + +class UnaryMinusExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(UnaryMinusExpression) + + UnaryMinusExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~UnaryMinusExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return minusToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation minusToken; +}; + +class TildeExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(TildeExpression) + + TildeExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~TildeExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return tildeToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation tildeToken; +}; + +class NotExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(NotExpression) + + NotExpression(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~NotExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return notToken; } + + virtual SourceLocation lastSourceLocation() const + { return expression->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + SourceLocation notToken; +}; + +class BinaryExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(BinaryExpression) + + BinaryExpression(ExpressionNode *l, int o, ExpressionNode *r): + left (l), op (o), right (r) + { kind = K; } + + virtual ~BinaryExpression() {} + + virtual BinaryExpression *binaryExpressionCast(); + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return left->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return right->lastSourceLocation(); } + +// attributes + ExpressionNode *left; + int op; + ExpressionNode *right; + SourceLocation operatorToken; +}; + +class ConditionalExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(ConditionalExpression) + + ConditionalExpression(ExpressionNode *e, ExpressionNode *t, ExpressionNode *f): + expression (e), ok (t), ko (f) + { kind = K; } + + virtual ~ConditionalExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return expression->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return ko->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + ExpressionNode *ok; + ExpressionNode *ko; + SourceLocation questionToken; + SourceLocation colonToken; +}; + +class Expression: public ExpressionNode // ### rename +{ +public: + QMLJS_DECLARE_AST_NODE(Expression) + + Expression(ExpressionNode *l, ExpressionNode *r): + left (l), right (r) { kind = K; } + + virtual ~Expression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return left->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return right->lastSourceLocation(); } + +// attributes + ExpressionNode *left; + ExpressionNode *right; + SourceLocation commaToken; +}; + +class Block: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(Block) + + Block(StatementList *slist): + statements (slist) { kind = K; } + + virtual ~Block() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return lbraceToken; } + + virtual SourceLocation lastSourceLocation() const + { return rbraceToken; } + + // attributes + StatementList *statements; + SourceLocation lbraceToken; + SourceLocation rbraceToken; +}; + +class StatementList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(StatementList) + + StatementList(Statement *stmt): + statement (stmt), next (this) + { kind = K; } + + StatementList(StatementList *previous, Statement *stmt): + statement (stmt) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~StatementList() {} + + virtual void accept0(Visitor *visitor); + + inline StatementList *finish () + { + StatementList *front = next; + next = 0; + return front; + } + +// attributes + Statement *statement; + StatementList *next; +}; + +class VariableStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(VariableStatement) + + VariableStatement(VariableDeclarationList *vlist): + declarations (vlist) + { kind = K; } + + virtual ~VariableStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return declarationKindToken; } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + +// attributes + VariableDeclarationList *declarations; + SourceLocation declarationKindToken; + SourceLocation semicolonToken; +}; + +class VariableDeclaration: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(VariableDeclaration) + + VariableDeclaration(NameId *n, ExpressionNode *e): + name (n), expression (e), readOnly(false) + { kind = K; } + + virtual ~VariableDeclaration() {} + + virtual void accept0(Visitor *visitor); + +// attributes + NameId *name; + ExpressionNode *expression; + bool readOnly; + SourceLocation identifierToken; +}; + +class VariableDeclarationList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(VariableDeclarationList) + + VariableDeclarationList(VariableDeclaration *decl): + declaration (decl), next (this) + { kind = K; } + + VariableDeclarationList(VariableDeclarationList *previous, VariableDeclaration *decl): + declaration (decl) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~VariableDeclarationList() {} + + virtual void accept0(Visitor *visitor); + + inline VariableDeclarationList *finish (bool readOnly) + { + VariableDeclarationList *front = next; + next = 0; + if (readOnly) { + VariableDeclarationList *vdl; + for (vdl = front; vdl != 0; vdl = vdl->next) + vdl->declaration->readOnly = true; + } + return front; + } + +// attributes + VariableDeclaration *declaration; + VariableDeclarationList *next; + SourceLocation commaToken; +}; + +class EmptyStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(EmptyStatement) + + EmptyStatement() { kind = K; } + virtual ~EmptyStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return semicolonToken; } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + +// attributes + SourceLocation semicolonToken; +}; + +class ExpressionStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(ExpressionStatement) + + ExpressionStatement(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~ExpressionStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return expression->firstSourceLocation(); } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + +// attributes + ExpressionNode *expression; + SourceLocation semicolonToken; +}; + +class IfStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(IfStatement) + + IfStatement(ExpressionNode *e, Statement *t, Statement *f = 0): + expression (e), ok (t), ko (f) + { kind = K; } + + virtual ~IfStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return ifToken; } + + virtual SourceLocation lastSourceLocation() const + { + if (ko) + return ko->lastSourceLocation(); + + return ok->lastSourceLocation(); + } + +// attributes + ExpressionNode *expression; + Statement *ok; + Statement *ko; + SourceLocation ifToken; + SourceLocation lparenToken; + SourceLocation rparenToken; + SourceLocation elseToken; +}; + +class DoWhileStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(DoWhileStatement) + + DoWhileStatement(Statement *stmt, ExpressionNode *e): + statement (stmt), expression (e) + { kind = K; } + + virtual ~DoWhileStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return doToken; } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + +// attributes + Statement *statement; + ExpressionNode *expression; + SourceLocation doToken; + SourceLocation whileToken; + SourceLocation lparenToken; + SourceLocation rparenToken; + SourceLocation semicolonToken; +}; + +class WhileStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(WhileStatement) + + WhileStatement(ExpressionNode *e, Statement *stmt): + expression (e), statement (stmt) + { kind = K; } + + virtual ~WhileStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return whileToken; } + + virtual SourceLocation lastSourceLocation() const + { return statement->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + Statement *statement; + SourceLocation whileToken; + SourceLocation lparenToken; + SourceLocation rparenToken; +}; + +class ForStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(ForStatement) + + ForStatement(ExpressionNode *i, ExpressionNode *c, ExpressionNode *e, Statement *stmt): + initialiser (i), condition (c), expression (e), statement (stmt) + { kind = K; } + + virtual ~ForStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return forToken; } + + virtual SourceLocation lastSourceLocation() const + { return statement->lastSourceLocation(); } + +// attributes + ExpressionNode *initialiser; + ExpressionNode *condition; + ExpressionNode *expression; + Statement *statement; + SourceLocation forToken; + SourceLocation lparenToken; + SourceLocation firstSemicolonToken; + SourceLocation secondSemicolonToken; + SourceLocation rparenToken; +}; + +class LocalForStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(LocalForStatement) + + LocalForStatement(VariableDeclarationList *vlist, ExpressionNode *c, ExpressionNode *e, Statement *stmt): + declarations (vlist), condition (c), expression (e), statement (stmt) + { kind = K; } + + virtual ~LocalForStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return forToken; } + + virtual SourceLocation lastSourceLocation() const + { return statement->lastSourceLocation(); } + +// attributes + VariableDeclarationList *declarations; + ExpressionNode *condition; + ExpressionNode *expression; + Statement *statement; + SourceLocation forToken; + SourceLocation lparenToken; + SourceLocation varToken; + SourceLocation firstSemicolonToken; + SourceLocation secondSemicolonToken; + SourceLocation rparenToken; +}; + +class ForEachStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(ForEachStatement) + + ForEachStatement(ExpressionNode *i, ExpressionNode *e, Statement *stmt): + initialiser (i), expression (e), statement (stmt) + { kind = K; } + + virtual ~ForEachStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return forToken; } + + virtual SourceLocation lastSourceLocation() const + { return statement->lastSourceLocation(); } + +// attributes + ExpressionNode *initialiser; + ExpressionNode *expression; + Statement *statement; + SourceLocation forToken; + SourceLocation lparenToken; + SourceLocation inToken; + SourceLocation rparenToken; +}; + +class LocalForEachStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(LocalForEachStatement) + + LocalForEachStatement(VariableDeclaration *v, ExpressionNode *e, Statement *stmt): + declaration (v), expression (e), statement (stmt) + { kind = K; } + + virtual ~LocalForEachStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return forToken; } + + virtual SourceLocation lastSourceLocation() const + { return statement->lastSourceLocation(); } + +// attributes + VariableDeclaration *declaration; + ExpressionNode *expression; + Statement *statement; + SourceLocation forToken; + SourceLocation lparenToken; + SourceLocation varToken; + SourceLocation inToken; + SourceLocation rparenToken; +}; + +class ContinueStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(ContinueStatement) + + ContinueStatement(NameId *l = 0): + label (l) { kind = K; } + + virtual ~ContinueStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return continueToken; } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + +// attributes + NameId *label; + SourceLocation continueToken; + SourceLocation identifierToken; + SourceLocation semicolonToken; +}; + +class BreakStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(BreakStatement) + + BreakStatement(NameId *l = 0): + label (l) { kind = K; } + + virtual ~BreakStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return breakToken; } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + + // attributes + NameId *label; + SourceLocation breakToken; + SourceLocation identifierToken; + SourceLocation semicolonToken; +}; + +class ReturnStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(ReturnStatement) + + ReturnStatement(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~ReturnStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return returnToken; } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + +// attributes + ExpressionNode *expression; + SourceLocation returnToken; + SourceLocation semicolonToken; +}; + +class WithStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(WithStatement) + + WithStatement(ExpressionNode *e, Statement *stmt): + expression (e), statement (stmt) + { kind = K; } + + virtual ~WithStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return withToken; } + + virtual SourceLocation lastSourceLocation() const + { return statement->lastSourceLocation(); } + +// attributes + ExpressionNode *expression; + Statement *statement; + SourceLocation withToken; + SourceLocation lparenToken; + SourceLocation rparenToken; +}; + +class CaseBlock: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(CaseBlock) + + CaseBlock(CaseClauses *c, DefaultClause *d = 0, CaseClauses *r = 0): + clauses (c), defaultClause (d), moreClauses (r) + { kind = K; } + + virtual ~CaseBlock() {} + + virtual void accept0(Visitor *visitor); + +// attributes + CaseClauses *clauses; + DefaultClause *defaultClause; + CaseClauses *moreClauses; + SourceLocation lbraceToken; + SourceLocation rbraceToken; +}; + +class SwitchStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(SwitchStatement) + + SwitchStatement(ExpressionNode *e, CaseBlock *b): + expression (e), block (b) + { kind = K; } + + virtual ~SwitchStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return switchToken; } + + virtual SourceLocation lastSourceLocation() const + { return block->rbraceToken; } + +// attributes + ExpressionNode *expression; + CaseBlock *block; + SourceLocation switchToken; + SourceLocation lparenToken; + SourceLocation rparenToken; +}; + +class CaseClauses: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(CaseClauses) + + CaseClauses(CaseClause *c): + clause (c), next (this) + { kind = K; } + + CaseClauses(CaseClauses *previous, CaseClause *c): + clause (c) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~CaseClauses() {} + + virtual void accept0(Visitor *visitor); + + inline CaseClauses *finish () + { + CaseClauses *front = next; + next = 0; + return front; + } + +//attributes + CaseClause *clause; + CaseClauses *next; +}; + +class CaseClause: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(CaseClause) + + CaseClause(ExpressionNode *e, StatementList *slist): + expression (e), statements (slist) + { kind = K; } + + virtual ~CaseClause() {} + + virtual void accept0(Visitor *visitor); + +// attributes + ExpressionNode *expression; + StatementList *statements; + SourceLocation caseToken; + SourceLocation colonToken; +}; + +class DefaultClause: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(DefaultClause) + + DefaultClause(StatementList *slist): + statements (slist) + { kind = K; } + + virtual ~DefaultClause() {} + + virtual void accept0(Visitor *visitor); + +// attributes + StatementList *statements; + SourceLocation defaultToken; + SourceLocation colonToken; +}; + +class LabelledStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(LabelledStatement) + + LabelledStatement(NameId *l, Statement *stmt): + label (l), statement (stmt) + { kind = K; } + + virtual ~LabelledStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return identifierToken; } + + virtual SourceLocation lastSourceLocation() const + { return statement->lastSourceLocation(); } + +// attributes + NameId *label; + Statement *statement; + SourceLocation identifierToken; + SourceLocation colonToken; +}; + +class ThrowStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(ThrowStatement) + + ThrowStatement(ExpressionNode *e): + expression (e) { kind = K; } + + virtual ~ThrowStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return throwToken; } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + + // attributes + ExpressionNode *expression; + SourceLocation throwToken; + SourceLocation semicolonToken; +}; + +class Catch: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(Catch) + + Catch(NameId *n, Block *stmt): + name (n), statement (stmt) + { kind = K; } + + virtual ~Catch() {} + + virtual void accept0(Visitor *visitor); + +// attributes + NameId *name; + Block *statement; + SourceLocation catchToken; + SourceLocation lparenToken; + SourceLocation identifierToken; + SourceLocation rparenToken; +}; + +class Finally: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(Finally) + + Finally(Block *stmt): + statement (stmt) + { kind = K; } + + virtual ~Finally() {} + + virtual void accept0(Visitor *visitor); + +// attributes + Block *statement; + SourceLocation finallyToken; +}; + +class TryStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(TryStatement) + + TryStatement(Statement *stmt, Catch *c, Finally *f): + statement (stmt), catchExpression (c), finallyExpression (f) + { kind = K; } + + TryStatement(Statement *stmt, Finally *f): + statement (stmt), catchExpression (0), finallyExpression (f) + { kind = K; } + + TryStatement(Statement *stmt, Catch *c): + statement (stmt), catchExpression (c), finallyExpression (0) + { kind = K; } + + virtual ~TryStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return tryToken; } + + virtual SourceLocation lastSourceLocation() const + { + if (finallyExpression) + return finallyExpression->statement->rbraceToken; + else if (catchExpression) + return catchExpression->statement->rbraceToken; + + return statement->lastSourceLocation(); + } + +// attributes + Statement *statement; + Catch *catchExpression; + Finally *finallyExpression; + SourceLocation tryToken; +}; + +class FunctionExpression: public ExpressionNode +{ +public: + QMLJS_DECLARE_AST_NODE(FunctionExpression) + + FunctionExpression(NameId *n, FormalParameterList *f, FunctionBody *b): + name (n), formals (f), body (b) + { kind = K; } + + virtual ~FunctionExpression() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return functionToken; } + + virtual SourceLocation lastSourceLocation() const + { return rbraceToken; } + +// attributes + NameId *name; + FormalParameterList *formals; + FunctionBody *body; + SourceLocation functionToken; + SourceLocation identifierToken; + SourceLocation lparenToken; + SourceLocation rparenToken; + SourceLocation lbraceToken; + SourceLocation rbraceToken; +}; + +class FunctionDeclaration: public FunctionExpression +{ +public: + QMLJS_DECLARE_AST_NODE(FunctionDeclaration) + + FunctionDeclaration(NameId *n, FormalParameterList *f, FunctionBody *b): + FunctionExpression(n, f, b) + { kind = K; } + + virtual ~FunctionDeclaration() {} + + virtual void accept0(Visitor *visitor); +}; + +class FormalParameterList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(FormalParameterList) + + FormalParameterList(NameId *n): + name (n), next (this) + { kind = K; } + + FormalParameterList(FormalParameterList *previous, NameId *n): + name (n) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~FormalParameterList() {} + + virtual void accept0(Visitor *visitor); + + inline FormalParameterList *finish () + { + FormalParameterList *front = next; + next = 0; + return front; + } + +// attributes + NameId *name; + FormalParameterList *next; + SourceLocation commaToken; + SourceLocation identifierToken; +}; + +class FunctionBody: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(FunctionBody) + + FunctionBody(SourceElements *elts): + elements (elts) + { kind = K; } + + virtual ~FunctionBody() {} + + virtual void accept0(Visitor *visitor); + +// attributes + SourceElements *elements; +}; + +class Program: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(Program) + + Program(SourceElements *elts): + elements (elts) + { kind = K; } + + virtual ~Program() {} + + virtual void accept0(Visitor *visitor); + +// attributes + SourceElements *elements; +}; + +class SourceElements: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(SourceElements) + + SourceElements(SourceElement *elt): + element (elt), next (this) + { kind = K; } + + SourceElements(SourceElements *previous, SourceElement *elt): + element (elt) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~SourceElements() {} + + virtual void accept0(Visitor *visitor); + + inline SourceElements *finish () + { + SourceElements *front = next; + next = 0; + return front; + } + +// attributes + SourceElement *element; + SourceElements *next; +}; + +class SourceElement: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(SourceElement) + + inline SourceElement() + { kind = K; } + + virtual ~SourceElement() {} +}; + +class FunctionSourceElement: public SourceElement +{ +public: + QMLJS_DECLARE_AST_NODE(FunctionSourceElement) + + FunctionSourceElement(FunctionDeclaration *f): + declaration (f) + { kind = K; } + + virtual ~FunctionSourceElement() {} + + virtual void accept0(Visitor *visitor); + +// attributes + FunctionDeclaration *declaration; +}; + +class StatementSourceElement: public SourceElement +{ +public: + QMLJS_DECLARE_AST_NODE(StatementSourceElement) + + StatementSourceElement(Statement *stmt): + statement (stmt) + { kind = K; } + + virtual ~StatementSourceElement() {} + + virtual void accept0(Visitor *visitor); + +// attributes + Statement *statement; +}; + +class DebuggerStatement: public Statement +{ +public: + QMLJS_DECLARE_AST_NODE(DebuggerStatement) + + DebuggerStatement() + { kind = K; } + + virtual ~DebuggerStatement() {} + + virtual void accept0(Visitor *visitor); + + virtual SourceLocation firstSourceLocation() const + { return debuggerToken; } + + virtual SourceLocation lastSourceLocation() const + { return semicolonToken; } + +// attributes + SourceLocation debuggerToken; + SourceLocation semicolonToken; +}; + +class UiProgram: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(UiProgram) + + UiProgram(UiImportList *imports, UiObjectMemberList *members) + : imports(imports), members(members) + { kind = K; } + + virtual void accept0(Visitor *visitor); + +// attributes + UiImportList *imports; + UiObjectMemberList *members; +}; + +class UiQualifiedId: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(UiQualifiedId) + + UiQualifiedId(NameId *name) + : next(this), name(name) + { kind = K; } + + UiQualifiedId(UiQualifiedId *previous, NameId *name) + : name(name) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual ~UiQualifiedId() {} + + UiQualifiedId *finish() + { + UiQualifiedId *head = next; + next = 0; + return head; + } + + virtual void accept0(Visitor *visitor); + +// attributes + UiQualifiedId *next; + NameId *name; + SourceLocation identifierToken; +}; + +class UiImport: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(UiImport) + + UiImport(NameId *fileName) + : fileName(fileName) + { kind = K; } + + virtual void accept0(Visitor *visitor); + +// attributes + NameId *fileName; + SourceLocation importToken; + SourceLocation fileNameToken; + SourceLocation semicolonToken; +}; + +class UiImportList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(UiImportList) + + UiImportList(UiImport *import) + : import(import), + next(this) + { kind = K; } + + UiImportList(UiImportList *previous, UiImport *import) + : import(import) + { + kind = K; + next = previous->next; + previous->next = this; + } + + UiImportList *finish() + { + UiImportList *head = next; + next = 0; + return head; + } + + virtual void accept0(Visitor *visitor); + +// attributes + UiImport *import; + UiImportList *next; +}; + +class UiObjectMember: public Node +{ +public: + virtual SourceLocation firstSourceLocation() const = 0; + virtual SourceLocation lastSourceLocation() const = 0; +}; + +class UiObjectMemberList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(UiObjectMemberList) + + UiObjectMemberList(UiObjectMember *member) + : next(this), member(member) + { kind = K; } + + UiObjectMemberList(UiObjectMemberList *previous, UiObjectMember *member) + : member(member) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual void accept0(Visitor *visitor); + + UiObjectMemberList *finish() + { + UiObjectMemberList *head = next; + next = 0; + return head; + } + +// attributes + UiObjectMemberList *next; + UiObjectMember *member; +}; + +class UiArrayMemberList: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(UiArrayMemberList) + + UiArrayMemberList(UiObjectMember *member) + : next(this), member(member) + { kind = K; } + + UiArrayMemberList(UiArrayMemberList *previous, UiObjectMember *member) + : member(member) + { + kind = K; + next = previous->next; + previous->next = this; + } + + virtual void accept0(Visitor *visitor); + + UiArrayMemberList *finish() + { + UiArrayMemberList *head = next; + next = 0; + return head; + } + +// attributes + UiArrayMemberList *next; + UiObjectMember *member; + SourceLocation commaToken; +}; + +class UiObjectInitializer: public Node +{ +public: + QMLJS_DECLARE_AST_NODE(UiObjectInitializer) + + UiObjectInitializer(UiObjectMemberList *members) + : members(members) + { kind = K; } + + virtual void accept0(Visitor *visitor); + +// attributes + SourceLocation lbraceToken; + UiObjectMemberList *members; + SourceLocation rbraceToken; +}; + +class UiPublicMember: public UiObjectMember +{ +public: + QMLJS_DECLARE_AST_NODE(UiPublicMember) + + UiPublicMember(NameId *memberType, + NameId *name) + : type(Property), memberType(memberType), name(name), expression(0), isDefaultMember(false) + { kind = K; } + + UiPublicMember(NameId *memberType, + NameId *name, + ExpressionNode *expression) + : type(Property), memberType(memberType), name(name), expression(expression), isDefaultMember(false) + { kind = K; } + + virtual SourceLocation firstSourceLocation() const + { + if (defaultToken.isValid()) + return defaultToken; + + return propertyToken; + } + + virtual SourceLocation lastSourceLocation() const + { + return semicolonToken; + } + + virtual void accept0(Visitor *visitor); + +// attributes + enum { Signal, Property } type; + NameId *memberType; + NameId *name; + ExpressionNode *expression; + bool isDefaultMember; + SourceLocation defaultToken; + SourceLocation propertyToken; + SourceLocation typeToken; + SourceLocation identifierToken; + SourceLocation colonToken; + SourceLocation semicolonToken; +}; + +class UiObjectDefinition: public UiObjectMember +{ +public: + QMLJS_DECLARE_AST_NODE(UiObjectDefinition) + + UiObjectDefinition(UiQualifiedId *qualifiedTypeNameId, + UiObjectInitializer *initializer) + : qualifiedTypeNameId(qualifiedTypeNameId), initializer(initializer) + { kind = K; } + + virtual SourceLocation firstSourceLocation() const + { return qualifiedTypeNameId->identifierToken; } + + virtual SourceLocation lastSourceLocation() const + { return initializer->rbraceToken; } + + virtual void accept0(Visitor *visitor); + +// attributes + UiQualifiedId *qualifiedTypeNameId; + UiObjectInitializer *initializer; +}; + +class UiSourceElement: public UiObjectMember +{ +public: + QMLJS_DECLARE_AST_NODE(UiSourceElement) + + UiSourceElement(Node *sourceElement) + : sourceElement(sourceElement) + { kind = K; } + + virtual SourceLocation firstSourceLocation() const + { + if (FunctionDeclaration *funDecl = cast(sourceElement)) + return funDecl->firstSourceLocation(); + else if (VariableStatement *varStmt = cast(sourceElement)) + return varStmt->firstSourceLocation(); + + return SourceLocation(); + } + + virtual SourceLocation lastSourceLocation() const + { + if (FunctionDeclaration *funDecl = cast(sourceElement)) + return funDecl->lastSourceLocation(); + else if (VariableStatement *varStmt = cast(sourceElement)) + return varStmt->lastSourceLocation(); + + return SourceLocation(); + } + + + virtual void accept0(Visitor *visitor); + +// attributes + Node *sourceElement; +}; + +class UiObjectBinding: public UiObjectMember +{ +public: + QMLJS_DECLARE_AST_NODE(UiObjectBinding) + + UiObjectBinding(UiQualifiedId *qualifiedId, + UiQualifiedId *qualifiedTypeNameId, + UiObjectInitializer *initializer) + : qualifiedId(qualifiedId), + qualifiedTypeNameId(qualifiedTypeNameId), + initializer(initializer) + { kind = K; } + + virtual SourceLocation firstSourceLocation() const + { return qualifiedId->identifierToken; } + + virtual SourceLocation lastSourceLocation() const + { return initializer->rbraceToken; } + + virtual void accept0(Visitor *visitor); + +// attributes + UiQualifiedId *qualifiedId; + UiQualifiedId *qualifiedTypeNameId; + UiObjectInitializer *initializer; + SourceLocation colonToken; +}; + +class UiScriptBinding: public UiObjectMember +{ +public: + QMLJS_DECLARE_AST_NODE(UiScriptBinding) + + UiScriptBinding(UiQualifiedId *qualifiedId, + Statement *statement) + : qualifiedId(qualifiedId), + statement(statement) + { kind = K; } + + virtual SourceLocation firstSourceLocation() const + { return qualifiedId->identifierToken; } + + virtual SourceLocation lastSourceLocation() const + { return statement->lastSourceLocation(); } + + virtual void accept0(Visitor *visitor); + +// attributes + UiQualifiedId *qualifiedId; + Statement *statement; + SourceLocation colonToken; +}; + +class UiArrayBinding: public UiObjectMember +{ +public: + QMLJS_DECLARE_AST_NODE(UiArrayBinding) + + UiArrayBinding(UiQualifiedId *qualifiedId, + UiArrayMemberList *members) + : qualifiedId(qualifiedId), + members(members) + { kind = K; } + + virtual SourceLocation firstSourceLocation() const + { return lbracketToken; } + + virtual SourceLocation lastSourceLocation() const + { return rbracketToken; } + + virtual void accept0(Visitor *visitor); + +// attributes + UiQualifiedId *qualifiedId; + UiArrayMemberList *members; + SourceLocation colonToken; + SourceLocation lbracketToken; + SourceLocation rbracketToken; +}; + +} } // namespace AST + + + +QT_END_NAMESPACE + +#endif diff --git a/src/declarative/qml/parser/qmljsastfwd_p.h b/src/declarative/qml/parser/qmljsastfwd_p.h new file mode 100644 index 0000000..339bea4 --- /dev/null +++ b/src/declarative/qml/parser/qmljsastfwd_p.h @@ -0,0 +1,184 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLJSAST_FWD_P_H +#define QMLJSAST_FWD_P_H + +#include + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +QT_BEGIN_NAMESPACE + +namespace QmlJS { namespace AST { + +class SourceLocation +{ +public: + SourceLocation(quint32 offset = 0, quint32 length = 0) + : offset(offset), length(length), + startLine(0), startColumn(0) + { } + + bool isValid() const { return length != 0; } + + quint32 begin() const { return offset; } + quint32 end() const { return offset + length; } + +// attributes + // ### encode + quint32 offset; + quint32 length; + quint32 startLine; + quint32 startColumn; +}; + +class Visitor; +class Node; +class ExpressionNode; +class Statement; +class ThisExpression; +class IdentifierExpression; +class NullExpression; +class TrueLiteral; +class FalseLiteral; +class NumericLiteral; +class StringLiteral; +class RegExpLiteral; +class ArrayLiteral; +class ObjectLiteral; +class ElementList; +class Elision; +class PropertyNameAndValueList; +class PropertyName; +class IdentifierPropertyName; +class StringLiteralPropertyName; +class NumericLiteralPropertyName; +class ArrayMemberExpression; +class FieldMemberExpression; +class NewMemberExpression; +class NewExpression; +class CallExpression; +class ArgumentList; +class PostIncrementExpression; +class PostDecrementExpression; +class DeleteExpression; +class VoidExpression; +class TypeOfExpression; +class PreIncrementExpression; +class PreDecrementExpression; +class UnaryPlusExpression; +class UnaryMinusExpression; +class TildeExpression; +class NotExpression; +class BinaryExpression; +class ConditionalExpression; +class Expression; // ### rename +class Block; +class StatementList; +class VariableStatement; +class VariableDeclarationList; +class VariableDeclaration; +class EmptyStatement; +class ExpressionStatement; +class IfStatement; +class DoWhileStatement; +class WhileStatement; +class ForStatement; +class LocalForStatement; +class ForEachStatement; +class LocalForEachStatement; +class ContinueStatement; +class BreakStatement; +class ReturnStatement; +class WithStatement; +class SwitchStatement; +class CaseBlock; +class CaseClauses; +class CaseClause; +class DefaultClause; +class LabelledStatement; +class ThrowStatement; +class TryStatement; +class Catch; +class Finally; +class FunctionDeclaration; +class FunctionExpression; +class FormalParameterList; +class FunctionBody; +class Program; +class SourceElements; +class SourceElement; +class FunctionSourceElement; +class StatementSourceElement; +class DebuggerStatement; +class NestedExpression; + +// ui elements +class UiProgram; +class UiImportList; +class UiImport; +class UiPublicMember; +class UiObjectDefinition; +class UiObjectInitializer; +class UiObjectBinding; +class UiScriptBinding; +class UiSourceElement; +class UiArrayBinding; +class UiObjectMember; +class UiObjectMemberList; +class UiArrayMemberList; +class UiQualifiedId; + +} } // namespace AST + +QT_END_NAMESPACE + +#endif diff --git a/src/declarative/qml/parser/qmljsastvisitor.cpp b/src/declarative/qml/parser/qmljsastvisitor.cpp new file mode 100644 index 0000000..642bcee --- /dev/null +++ b/src/declarative/qml/parser/qmljsastvisitor.cpp @@ -0,0 +1,58 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmljsastvisitor_p.h" + +QT_BEGIN_NAMESPACE + +namespace QmlJS { namespace AST { + +Visitor::Visitor() +{ +} + +Visitor::~Visitor() +{ +} + +} } // namespace QmlJS::AST + +QT_END_NAMESPACE diff --git a/src/declarative/qml/parser/qmljsastvisitor_p.h b/src/declarative/qml/parser/qmljsastvisitor_p.h new file mode 100644 index 0000000..3677b1a --- /dev/null +++ b/src/declarative/qml/parser/qmljsastvisitor_p.h @@ -0,0 +1,328 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLJSASTVISITOR_P_H +#define QMLJSASTVISITOR_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include "qmljsastfwd_p.h" + +QT_BEGIN_NAMESPACE + +namespace QmlJS { namespace AST { + +class Visitor +{ +public: + Visitor(); + virtual ~Visitor(); + + virtual bool preVisit(Node *) { return true; } + virtual void postVisit(Node *) {} + + // Ui + virtual bool visit(UiProgram *) { return true; } + virtual bool visit(UiImportList *) { return true; } + virtual bool visit(UiImport *) { return true; } + virtual bool visit(UiPublicMember *) { return true; } + virtual bool visit(UiSourceElement *) { return true; } + virtual bool visit(UiObjectDefinition *) { return true; } + virtual bool visit(UiObjectInitializer *) { return true; } + virtual bool visit(UiObjectBinding *) { return true; } + virtual bool visit(UiScriptBinding *) { return true; } + virtual bool visit(UiArrayBinding *) { return true; } + virtual bool visit(UiObjectMemberList *) { return true; } + virtual bool visit(UiArrayMemberList *) { return true; } + virtual bool visit(UiQualifiedId *) { return true; } + + virtual void endVisit(UiProgram *) {} + virtual void endVisit(UiImportList *) {} + virtual void endVisit(UiImport *) {} + virtual void endVisit(UiPublicMember *) {} + virtual void endVisit(UiSourceElement *) {} + virtual void endVisit(UiObjectDefinition *) {} + virtual void endVisit(UiObjectInitializer *) {} + virtual void endVisit(UiObjectBinding *) {} + virtual void endVisit(UiScriptBinding *) {} + virtual void endVisit(UiArrayBinding *) {} + virtual void endVisit(UiObjectMemberList *) {} + virtual void endVisit(UiArrayMemberList *) {} + virtual void endVisit(UiQualifiedId *) {} + + // QmlJS + virtual bool visit(ThisExpression *) { return true; } + virtual void endVisit(ThisExpression *) {} + + virtual bool visit(IdentifierExpression *) { return true; } + virtual void endVisit(IdentifierExpression *) {} + + virtual bool visit(NullExpression *) { return true; } + virtual void endVisit(NullExpression *) {} + + virtual bool visit(TrueLiteral *) { return true; } + virtual void endVisit(TrueLiteral *) {} + + virtual bool visit(FalseLiteral *) { return true; } + virtual void endVisit(FalseLiteral *) {} + + virtual bool visit(StringLiteral *) { return true; } + virtual void endVisit(StringLiteral *) {} + + virtual bool visit(NumericLiteral *) { return true; } + virtual void endVisit(NumericLiteral *) {} + + virtual bool visit(RegExpLiteral *) { return true; } + virtual void endVisit(RegExpLiteral *) {} + + virtual bool visit(ArrayLiteral *) { return true; } + virtual void endVisit(ArrayLiteral *) {} + + virtual bool visit(ObjectLiteral *) { return true; } + virtual void endVisit(ObjectLiteral *) {} + + virtual bool visit(ElementList *) { return true; } + virtual void endVisit(ElementList *) {} + + virtual bool visit(Elision *) { return true; } + virtual void endVisit(Elision *) {} + + virtual bool visit(PropertyNameAndValueList *) { return true; } + virtual void endVisit(PropertyNameAndValueList *) {} + + virtual bool visit(NestedExpression *) { return true; } + virtual void endVisit(NestedExpression *) {} + + virtual bool visit(IdentifierPropertyName *) { return true; } + virtual void endVisit(IdentifierPropertyName *) {} + + virtual bool visit(StringLiteralPropertyName *) { return true; } + virtual void endVisit(StringLiteralPropertyName *) {} + + virtual bool visit(NumericLiteralPropertyName *) { return true; } + virtual void endVisit(NumericLiteralPropertyName *) {} + + virtual bool visit(ArrayMemberExpression *) { return true; } + virtual void endVisit(ArrayMemberExpression *) {} + + virtual bool visit(FieldMemberExpression *) { return true; } + virtual void endVisit(FieldMemberExpression *) {} + + virtual bool visit(NewMemberExpression *) { return true; } + virtual void endVisit(NewMemberExpression *) {} + + virtual bool visit(NewExpression *) { return true; } + virtual void endVisit(NewExpression *) {} + + virtual bool visit(CallExpression *) { return true; } + virtual void endVisit(CallExpression *) {} + + virtual bool visit(ArgumentList *) { return true; } + virtual void endVisit(ArgumentList *) {} + + virtual bool visit(PostIncrementExpression *) { return true; } + virtual void endVisit(PostIncrementExpression *) {} + + virtual bool visit(PostDecrementExpression *) { return true; } + virtual void endVisit(PostDecrementExpression *) {} + + virtual bool visit(DeleteExpression *) { return true; } + virtual void endVisit(DeleteExpression *) {} + + virtual bool visit(VoidExpression *) { return true; } + virtual void endVisit(VoidExpression *) {} + + virtual bool visit(TypeOfExpression *) { return true; } + virtual void endVisit(TypeOfExpression *) {} + + virtual bool visit(PreIncrementExpression *) { return true; } + virtual void endVisit(PreIncrementExpression *) {} + + virtual bool visit(PreDecrementExpression *) { return true; } + virtual void endVisit(PreDecrementExpression *) {} + + virtual bool visit(UnaryPlusExpression *) { return true; } + virtual void endVisit(UnaryPlusExpression *) {} + + virtual bool visit(UnaryMinusExpression *) { return true; } + virtual void endVisit(UnaryMinusExpression *) {} + + virtual bool visit(TildeExpression *) { return true; } + virtual void endVisit(TildeExpression *) {} + + virtual bool visit(NotExpression *) { return true; } + virtual void endVisit(NotExpression *) {} + + virtual bool visit(BinaryExpression *) { return true; } + virtual void endVisit(BinaryExpression *) {} + + virtual bool visit(ConditionalExpression *) { return true; } + virtual void endVisit(ConditionalExpression *) {} + + virtual bool visit(Expression *) { return true; } + virtual void endVisit(Expression *) {} + + virtual bool visit(Block *) { return true; } + virtual void endVisit(Block *) {} + + virtual bool visit(StatementList *) { return true; } + virtual void endVisit(StatementList *) {} + + virtual bool visit(VariableStatement *) { return true; } + virtual void endVisit(VariableStatement *) {} + + virtual bool visit(VariableDeclarationList *) { return true; } + virtual void endVisit(VariableDeclarationList *) {} + + virtual bool visit(VariableDeclaration *) { return true; } + virtual void endVisit(VariableDeclaration *) {} + + virtual bool visit(EmptyStatement *) { return true; } + virtual void endVisit(EmptyStatement *) {} + + virtual bool visit(ExpressionStatement *) { return true; } + virtual void endVisit(ExpressionStatement *) {} + + virtual bool visit(IfStatement *) { return true; } + virtual void endVisit(IfStatement *) {} + + virtual bool visit(DoWhileStatement *) { return true; } + virtual void endVisit(DoWhileStatement *) {} + + virtual bool visit(WhileStatement *) { return true; } + virtual void endVisit(WhileStatement *) {} + + virtual bool visit(ForStatement *) { return true; } + virtual void endVisit(ForStatement *) {} + + virtual bool visit(LocalForStatement *) { return true; } + virtual void endVisit(LocalForStatement *) {} + + virtual bool visit(ForEachStatement *) { return true; } + virtual void endVisit(ForEachStatement *) {} + + virtual bool visit(LocalForEachStatement *) { return true; } + virtual void endVisit(LocalForEachStatement *) {} + + virtual bool visit(ContinueStatement *) { return true; } + virtual void endVisit(ContinueStatement *) {} + + virtual bool visit(BreakStatement *) { return true; } + virtual void endVisit(BreakStatement *) {} + + virtual bool visit(ReturnStatement *) { return true; } + virtual void endVisit(ReturnStatement *) {} + + virtual bool visit(WithStatement *) { return true; } + virtual void endVisit(WithStatement *) {} + + virtual bool visit(SwitchStatement *) { return true; } + virtual void endVisit(SwitchStatement *) {} + + virtual bool visit(CaseBlock *) { return true; } + virtual void endVisit(CaseBlock *) {} + + virtual bool visit(CaseClauses *) { return true; } + virtual void endVisit(CaseClauses *) {} + + virtual bool visit(CaseClause *) { return true; } + virtual void endVisit(CaseClause *) {} + + virtual bool visit(DefaultClause *) { return true; } + virtual void endVisit(DefaultClause *) {} + + virtual bool visit(LabelledStatement *) { return true; } + virtual void endVisit(LabelledStatement *) {} + + virtual bool visit(ThrowStatement *) { return true; } + virtual void endVisit(ThrowStatement *) {} + + virtual bool visit(TryStatement *) { return true; } + virtual void endVisit(TryStatement *) {} + + virtual bool visit(Catch *) { return true; } + virtual void endVisit(Catch *) {} + + virtual bool visit(Finally *) { return true; } + virtual void endVisit(Finally *) {} + + virtual bool visit(FunctionDeclaration *) { return true; } + virtual void endVisit(FunctionDeclaration *) {} + + virtual bool visit(FunctionExpression *) { return true; } + virtual void endVisit(FunctionExpression *) {} + + virtual bool visit(FormalParameterList *) { return true; } + virtual void endVisit(FormalParameterList *) {} + + virtual bool visit(FunctionBody *) { return true; } + virtual void endVisit(FunctionBody *) {} + + virtual bool visit(Program *) { return true; } + virtual void endVisit(Program *) {} + + virtual bool visit(SourceElements *) { return true; } + virtual void endVisit(SourceElements *) {} + + virtual bool visit(FunctionSourceElement *) { return true; } + virtual void endVisit(FunctionSourceElement *) {} + + virtual bool visit(StatementSourceElement *) { return true; } + virtual void endVisit(StatementSourceElement *) {} + + virtual bool visit(DebuggerStatement *) { return true; } + virtual void endVisit(DebuggerStatement *) {} +}; + +} } // namespace AST + +QT_END_NAMESPACE + +#endif // QMLJSASTVISITOR_P_H diff --git a/src/declarative/qml/parser/qmljsengine_p.cpp b/src/declarative/qml/parser/qmljsengine_p.cpp new file mode 100644 index 0000000..42885d8 --- /dev/null +++ b/src/declarative/qml/parser/qmljsengine_p.cpp @@ -0,0 +1,191 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Qt Software Information (qt-info@nokia.com) +** +** Commercial Usage +** +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** +** Alternatively, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** +**************************************************************************/ + +#include "qmljsengine_p.h" +#include "qmljsnodepool_p.h" +#include +#include + +QT_BEGIN_NAMESPACE + +namespace QmlJS { + +uint qHash(const QmlJS::NameId &id) +{ return qHash(id.asString()); } + +QString numberToString(double value) +{ return QString::number(value); } + +int Ecma::RegExp::flagFromChar(const QChar &ch) +{ + static QHash flagsHash; + if (flagsHash.isEmpty()) { + flagsHash[QLatin1Char('g')] = Global; + flagsHash[QLatin1Char('i')] = IgnoreCase; + flagsHash[QLatin1Char('m')] = Multiline; + } + QHash::const_iterator it; + it = flagsHash.constFind(ch); + if (it == flagsHash.constEnd()) + return 0; + return it.value(); +} + +QString Ecma::RegExp::flagsToString(int flags) +{ + QString result; + if (flags & Global) + result += QLatin1Char('g'); + if (flags & IgnoreCase) + result += QLatin1Char('i'); + if (flags & Multiline) + result += QLatin1Char('m'); + return result; +} + +NodePool::NodePool(const QString &fileName, Engine *engine) + : m_fileName(fileName), m_engine(engine) +{ + m_engine->setNodePool(this); +} + +NodePool::~NodePool() +{ +} + +Code *NodePool::createCompiledCode(AST::Node *, CompilationUnit &) +{ + Q_ASSERT(0); + return 0; +} + +static int toDigit(char c) +{ + if ((c >= '0') && (c <= '9')) + return c - '0'; + else if ((c >= 'a') && (c <= 'z')) + return 10 + c - 'a'; + else if ((c >= 'A') && (c <= 'Z')) + return 10 + c - 'A'; + return -1; +} + +double integerFromString(const char *buf, int size, int radix) +{ + if (size == 0) + return qSNaN(); + + double sign = 1.0; + int i = 0; + if (buf[0] == '+') { + ++i; + } else if (buf[0] == '-') { + sign = -1.0; + ++i; + } + + if (((size-i) >= 2) && (buf[i] == '0')) { + if (((buf[i+1] == 'x') || (buf[i+1] == 'X')) + && (radix < 34)) { + if ((radix != 0) && (radix != 16)) + return 0; + radix = 16; + i += 2; + } else { + if (radix == 0) { + radix = 8; + ++i; + } + } + } else if (radix == 0) { + radix = 10; + } + + int j = i; + for ( ; i < size; ++i) { + int d = toDigit(buf[i]); + if ((d == -1) || (d >= radix)) + break; + } + double result; + if (j == i) { + if (!qstrcmp(buf, "Infinity")) + result = qInf(); + else + result = qSNaN(); + } else { + result = 0; + double multiplier = 1; + for (--i ; i >= j; --i, multiplier *= radix) + result += toDigit(buf[i]) * multiplier; + } + result *= sign; + return result; +} + +double integerFromString(const QString &str, int radix) +{ + QByteArray ba = str.trimmed().toUtf8(); + return integerFromString(ba.constData(), ba.size(), radix); +} + + +Engine::Engine() + : _lexer(0), _nodePool(0) +{ } + +Engine::~Engine() +{ } + +QSet Engine::literals() const +{ return _literals; } + +NameId *Engine::intern(const QChar *u, int s) +{ return const_cast(&*_literals.insert(NameId(u, s))); } + +QString Engine::toString(NameId *id) +{ return id->asString(); } + +Lexer *Engine::lexer() const +{ return _lexer; } + +void Engine::setLexer(Lexer *lexer) +{ _lexer = lexer; } + +NodePool *Engine::nodePool() const +{ return _nodePool; } + +void Engine::setNodePool(NodePool *nodePool) +{ _nodePool = nodePool; } + + + +} // end of namespace QmlJS + +QT_END_NAMESPACE diff --git a/src/declarative/qml/parser/qmljsengine_p.h b/src/declarative/qml/parser/qmljsengine_p.h new file mode 100644 index 0000000..b9ff042 --- /dev/null +++ b/src/declarative/qml/parser/qmljsengine_p.h @@ -0,0 +1,145 @@ +/************************************************************************** +** +** This file is part of Qt Creator +** +** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). +** +** Contact: Qt Software Information (qt-info@nokia.com) +** +** Commercial Usage +** +** Licensees holding valid Qt Commercial licenses may use this file in +** accordance with the Qt Commercial License Agreement provided with the +** Software or, alternatively, in accordance with the terms contained in +** a written agreement between you and Nokia. +** +** GNU Lesser General Public License Usage +** +** Alternatively, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** +**************************************************************************/ + +#ifndef QMLJSENGINE_P_H +#define QMLJSENGINE_P_H + +#include +#include + +#include "qmljsastfwd_p.h" + +QT_BEGIN_NAMESPACE + +namespace QmlJS { +class NameId +{ + QString _text; + +public: + NameId(const QChar *u, int s) + : _text(u, s) + { } + + const QString asString() const + { return _text; } + + bool operator == (const NameId &other) const + { return _text == other._text; } + + bool operator != (const NameId &other) const + { return _text != other._text; } + + bool operator < (const NameId &other) const + { return _text < other._text; } +}; + +uint qHash(const QmlJS::NameId &id); + +} // end of namespace QmlJS + +#if defined(Q_CC_MSVC) && _MSC_VER <= 1300 +//this ensures that code outside QmlJS can use the hash function +//it also a workaround for some compilers +inline uint qHash(const QmlJS::NameId &nameId) { return QmlJS::qHash(nameId); } +#endif + +namespace QmlJS { + +class Lexer; +class NodePool; + +namespace Ecma { + +class RegExp +{ +public: + enum RegExpFlag { + Global = 0x01, + IgnoreCase = 0x02, + Multiline = 0x04 + }; + +public: + static int flagFromChar(const QChar &); + static QString flagsToString(int flags); +}; + +} // end of namespace Ecma + +class DiagnosticMessage +{ +public: + enum Kind { Warning, Error }; + + DiagnosticMessage() + : kind(Error) {} + + DiagnosticMessage(Kind kind, const AST::SourceLocation &loc, const QString &message) + : kind(kind), loc(loc), message(message) {} + + bool isWarning() const + { return kind == Warning; } + + bool isError() const + { return kind == Error; } + + Kind kind; + AST::SourceLocation loc; + QString message; +}; + +class Engine +{ + Lexer *_lexer; + NodePool *_nodePool; + QSet _literals; + +public: + Engine(); + ~Engine(); + + QSet literals() const; + + NameId *intern(const QChar *u, int s); + + static QString toString(NameId *id); + + Lexer *lexer() const; + void setLexer(Lexer *lexer); + + NodePool *nodePool() const; + void setNodePool(NodePool *nodePool); +}; + +} // end of namespace QmlJS + +QT_END_NAMESPACE + +#endif // QMLJSENGINE_P_H diff --git a/src/declarative/qml/parser/qmljsgrammar.cpp b/src/declarative/qml/parser/qmljsgrammar.cpp new file mode 100644 index 0000000..835ee44 --- /dev/null +++ b/src/declarative/qml/parser/qmljsgrammar.cpp @@ -0,0 +1,829 @@ +// This file was generated by qlalr - DO NOT EDIT! +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmljsgrammar_p.h" + +const char *const QmlJSGrammar::spell [] = { + "end of file", "&", "&&", "&=", "break", "case", "catch", ":", ";", "continue", + "default", "delete", "/", "/=", "do", ".", "else", "=", "==", "===", + "finally", "for", "function", ">=", ">", ">>", ">>=", ">>>", ">>>=", "identifier", + "if", "in", "instanceof", "{", "[", "<=", "(", "<", "<<", "<<=", + "-", "-=", "--", "new", "!", "!=", "!==", "numeric literal", "|", "|=", + "||", "+", "+=", "++", "?", "}", "]", "%", "%=", "return", + ")", ";", 0, "*", "*=", "string literal", "property", "signal", "switch", "this", + "throw", "~", "try", "typeof", "var", "void", "while", "with", "^", "^=", + "null", "true", "false", "const", "debugger", "reserved word", "multiline string literal", "public", "import", 0, + 0}; + +const int QmlJSGrammar::lhs [] = { + 91, 92, 92, 95, 95, 96, 96, 94, 93, 98, + 98, 100, 100, 101, 101, 97, 99, 99, 103, 104, + 104, 99, 99, 99, 99, 99, 99, 99, 111, 111, + 111, 99, 99, 99, 99, 99, 99, 99, 99, 99, + 99, 99, 102, 102, 114, 114, 114, 115, 115, 115, + 115, 115, 115, 115, 115, 115, 115, 115, 115, 115, + 115, 115, 115, 115, 102, 102, 117, 117, 117, 117, + 116, 116, 119, 119, 121, 121, 121, 121, 121, 121, + 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, + 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, + 122, 122, 122, 122, 122, 122, 122, 122, 122, 122, + 122, 123, 123, 124, 124, 124, 124, 124, 127, 127, + 128, 128, 128, 128, 126, 126, 129, 129, 130, 130, + 131, 131, 131, 132, 132, 132, 132, 132, 132, 132, + 132, 132, 132, 133, 133, 133, 133, 134, 134, 134, + 135, 135, 135, 135, 136, 136, 136, 136, 136, 136, + 136, 137, 137, 137, 137, 137, 137, 138, 138, 138, + 138, 138, 139, 139, 139, 139, 139, 140, 140, 141, + 141, 142, 142, 143, 143, 144, 144, 145, 145, 146, + 146, 147, 147, 148, 148, 149, 149, 150, 150, 151, + 151, 120, 120, 152, 152, 153, 153, 153, 153, 153, + 153, 153, 153, 153, 153, 153, 153, 105, 105, 154, + 154, 155, 155, 156, 156, 157, 157, 157, 157, 157, + 157, 157, 157, 157, 157, 157, 157, 157, 157, 157, + 106, 168, 168, 167, 167, 113, 113, 169, 169, 170, + 170, 172, 172, 171, 173, 176, 174, 174, 177, 175, + 175, 107, 108, 108, 110, 110, 158, 158, 158, 158, + 158, 158, 158, 159, 159, 159, 159, 160, 160, 160, + 160, 161, 161, 162, 164, 178, 178, 181, 181, 179, + 179, 182, 180, 163, 163, 163, 165, 165, 166, 166, + 166, 183, 184, 109, 109, 112, 125, 188, 188, 185, + 185, 186, 186, 189, 190, 190, 191, 191, 187, 187, + 118, 118, 192}; + +const int QmlJSGrammar:: rhs[] = { + 2, 1, 1, 1, 2, 3, 3, 0, 1, 1, + 2, 1, 3, 2, 3, 2, 1, 5, 1, 2, + 2, 4, 3, 3, 3, 3, 3, 3, 1, 1, + 1, 2, 4, 4, 5, 5, 6, 6, 7, 7, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 2, 3, 3, 4, + 5, 3, 4, 3, 1, 3, 1, 2, 3, 4, + 1, 2, 3, 5, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 4, 3, 5, 1, 2, + 4, 4, 4, 3, 0, 1, 1, 3, 1, 1, + 1, 2, 2, 1, 2, 2, 2, 2, 2, 2, + 2, 2, 2, 1, 3, 3, 3, 1, 3, 3, + 1, 3, 3, 3, 1, 3, 3, 3, 3, 3, + 3, 1, 3, 3, 3, 3, 3, 1, 3, 3, + 3, 3, 1, 3, 3, 3, 3, 1, 3, 1, + 3, 1, 3, 1, 3, 1, 3, 1, 3, 1, + 3, 1, 3, 1, 3, 1, 3, 1, 5, 1, + 5, 1, 3, 1, 3, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 3, 0, + 1, 1, 3, 0, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 3, 1, 2, 0, 1, 3, 3, 1, 1, 1, + 3, 1, 3, 2, 2, 2, 0, 1, 2, 0, + 1, 1, 2, 2, 7, 5, 7, 7, 5, 9, + 10, 7, 8, 2, 2, 3, 3, 2, 2, 3, + 3, 3, 3, 5, 5, 3, 5, 1, 2, 0, + 1, 4, 3, 3, 3, 3, 3, 3, 3, 3, + 4, 5, 2, 2, 2, 8, 8, 1, 3, 0, + 1, 0, 1, 1, 1, 2, 1, 1, 0, 1, + 0, 1, 2}; + +const int QmlJSGrammar::action_default [] = { + 8, 2, 0, 4, 3, 0, 0, 0, 6, 7, + 5, 65, 45, 46, 43, 44, 47, 9, 0, 1, + 0, 0, 16, 66, 41, 248, 0, 0, 46, 14, + 47, 249, 17, 10, 0, 0, 0, 42, 0, 31, + 30, 29, 0, 0, 35, 0, 36, 151, 218, 182, + 190, 186, 130, 202, 178, 0, 115, 49, 131, 194, + 198, 119, 148, 129, 134, 114, 168, 155, 0, 55, + 56, 52, 319, 321, 0, 0, 0, 0, 0, 0, + 50, 53, 0, 0, 54, 48, 0, 51, 0, 0, + 144, 0, 0, 131, 150, 133, 132, 0, 0, 0, + 146, 147, 145, 149, 0, 179, 0, 0, 0, 0, + 169, 0, 0, 0, 0, 0, 0, 159, 0, 0, + 0, 153, 154, 152, 157, 161, 160, 158, 156, 171, + 170, 172, 0, 187, 0, 183, 0, 0, 125, 112, + 124, 113, 81, 82, 83, 108, 84, 109, 85, 86, + 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, + 97, 110, 98, 99, 100, 101, 102, 103, 104, 105, + 106, 107, 111, 0, 0, 123, 219, 126, 0, 127, + 0, 128, 122, 39, 40, 0, 215, 208, 206, 213, + 214, 212, 211, 217, 210, 209, 207, 216, 203, 0, + 191, 0, 0, 195, 0, 0, 199, 0, 0, 125, + 117, 0, 116, 0, 121, 135, 0, 320, 310, 311, + 0, 308, 0, 309, 0, 312, 226, 233, 232, 240, + 228, 0, 229, 313, 0, 318, 230, 231, 236, 234, + 315, 314, 317, 237, 0, 0, 0, 0, 0, 319, + 45, 0, 321, 46, 220, 262, 47, 0, 0, 0, + 0, 0, 238, 239, 227, 235, 263, 264, 307, 316, + 0, 278, 279, 280, 281, 0, 274, 275, 276, 277, + 304, 305, 0, 0, 0, 0, 0, 267, 268, 224, + 222, 184, 192, 188, 204, 180, 225, 0, 131, 196, + 200, 173, 162, 0, 0, 181, 0, 0, 0, 0, + 174, 0, 0, 0, 0, 0, 166, 164, 167, 165, + 163, 176, 175, 177, 0, 189, 0, 185, 0, 223, + 131, 0, 205, 220, 221, 0, 220, 0, 0, 270, + 0, 0, 0, 272, 0, 193, 0, 0, 197, 0, + 0, 201, 260, 0, 252, 261, 255, 0, 259, 0, + 220, 253, 0, 220, 0, 0, 271, 0, 0, 0, + 273, 320, 310, 0, 0, 312, 0, 306, 0, 296, + 0, 0, 0, 266, 0, 265, 0, 322, 0, 80, + 242, 245, 0, 81, 248, 84, 109, 86, 87, 52, + 91, 92, 45, 93, 96, 50, 53, 46, 220, 47, + 54, 99, 48, 101, 51, 103, 104, 249, 106, 107, + 111, 0, 73, 0, 0, 75, 79, 77, 63, 76, + 78, 0, 74, 62, 243, 241, 119, 120, 125, 0, + 118, 0, 295, 0, 282, 283, 0, 294, 0, 0, + 0, 285, 290, 288, 291, 0, 0, 289, 290, 0, + 286, 0, 287, 244, 293, 0, 244, 292, 0, 297, + 298, 0, 244, 299, 300, 0, 0, 301, 0, 0, + 0, 302, 303, 137, 136, 0, 0, 0, 269, 0, + 0, 0, 284, 67, 0, 0, 71, 57, 0, 59, + 69, 0, 60, 70, 72, 61, 68, 58, 0, 64, + 141, 139, 143, 140, 138, 142, 0, 0, 0, 33, + 0, 34, 0, 37, 38, 32, 15, 11, 0, 23, + 26, 24, 0, 25, 28, 244, 0, 19, 0, 27, + 22, 81, 248, 84, 109, 86, 87, 52, 91, 92, + 45, 93, 96, 50, 53, 46, 220, 47, 54, 99, + 48, 101, 51, 103, 104, 249, 106, 107, 111, 49, + 0, 12, 0, 18, 13, 20, 21, 257, 250, 0, + 258, 254, 0, 256, 246, 0, 247, 251, 323}; + +const int QmlJSGrammar::goto_default [] = { + 6, 5, 19, 1, 4, 3, 32, 34, 33, 570, + 22, 18, 538, 539, 231, 226, 230, 232, 229, 236, + 517, 235, 264, 57, 65, 495, 494, 388, 387, 48, + 386, 389, 140, 61, 56, 178, 63, 52, 177, 58, + 64, 90, 62, 47, 67, 66, 301, 54, 295, 49, + 291, 51, 293, 50, 292, 59, 299, 60, 300, 53, + 294, 290, 331, 443, 296, 297, 390, 237, 228, 227, + 239, 265, 238, 243, 262, 263, 392, 391, 36, 579, + 578, 353, 354, 581, 356, 580, 355, 451, 455, 458, + 454, 453, 473, 474, 220, 234, 216, 219, 233, 241, + 240, 0}; + +const int QmlJSGrammar::action_index [] = { + 8, -91, 14, -91, -15, 296, 67, 94, -91, -91, + -91, -91, -91, -91, -91, -91, -91, -91, 109, -91, + 184, 408, -91, -91, -91, -91, 45, 125, 170, -91, + 46, -91, -91, -91, 429, 171, 130, -91, 120, -91, + -91, -91, -19, 169, -91, 733, -91, 72, -91, 22, + -26, -59, 173, -91, 278, 174, -91, -91, 574, 51, + 112, 183, 177, -91, -91, -91, 412, 214, 733, -91, + -91, -91, 161, 1566, 980, 733, 733, 733, 653, 733, + -91, -91, 733, 733, -91, -91, 733, -91, 733, 733, + -91, 733, 733, 98, 235, -91, -91, 733, 733, 733, + -91, -91, -91, 230, 733, 276, 733, 733, 733, 733, + 396, 733, 733, 733, 733, 733, 733, 288, 733, 733, + 733, 88, 87, 74, 288, 288, 288, 218, 221, 486, + 372, 362, 733, 4, 733, 76, 1479, 733, 733, -91, + -91, -91, -91, -91, -91, -91, -91, -91, -91, -91, + -91, -91, -91, -91, -91, -91, -91, -91, -91, -91, + -91, -91, -91, -91, -91, -91, -91, -91, -91, -91, + -91, -91, -91, 102, 733, -91, -91, 60, 3, -91, + 733, -91, -91, -91, -91, 733, -91, -91, -91, -91, + -91, -91, -91, -91, -91, -91, -91, -91, -91, 733, + -6, 733, 733, 30, 32, 733, -91, 1479, 733, 733, + -91, 107, -91, -14, -91, -91, 69, -91, 191, 49, + 18, -91, 233, -91, 47, 1827, -91, -91, -91, -91, + -91, 204, -91, -91, 39, -91, -91, -91, -91, -91, + -91, 1827, -91, -91, 322, 281, 103, 1740, 50, 203, + 77, 40, 2001, 53, 733, -91, 52, 29, 733, 25, + 28, 35, -91, -91, -91, -91, -91, -91, -91, -91, + 113, -91, -91, -91, -91, 106, -91, -91, -91, -91, + -91, -91, 15, 68, 733, 135, 119, -91, -91, 897, + -91, 82, 58, 17, -91, 261, 84, 42, 494, 91, + 79, 304, 288, 208, 733, 245, 733, 733, 733, 733, + 418, 733, 733, 733, 733, 733, 288, 288, 288, 288, + 288, 343, 336, 279, 733, -57, 733, 19, 733, -91, + 574, 733, -91, 733, -7, -30, 733, -60, 1740, -91, + 733, 111, 1740, -91, 733, 2, 733, 733, 43, 37, + 733, -91, 34, 118, 23, -91, -91, 733, -91, 238, + 733, -91, -5, 733, -17, 1740, -91, 733, 133, 1740, + -91, -9, 194, -32, -8, 1827, -25, -91, 1740, -91, + 733, 100, 1740, 21, 1740, -91, 31, 26, -20, -91, + -91, 1740, -38, 283, 41, 291, 85, 733, 1740, -1, + -34, 252, 54, -27, 653, 9, 5, -91, 817, -91, + 6, -21, 7, 733, 11, -28, 733, 1, 733, -33, + -10, 733, -91, 1653, 33, -91, -91, -91, -91, -91, + -91, 733, -91, -91, -91, -91, 172, -91, 733, -24, + -91, 1740, -91, 73, -91, -91, 1740, -91, 733, 93, + 0, -91, 24, -91, 36, 122, 733, -91, 44, 48, + -91, -3, -91, 1740, -91, 110, 1740, -91, 192, -91, + -91, 124, 1740, 27, -91, -12, -29, -91, 155, -53, + -22, -91, -91, -91, -91, 733, 123, 1740, -91, 733, + 92, 1740, -91, -91, 105, 1229, -91, -91, 1146, -91, + -91, 1063, -91, -91, -91, -91, -91, -91, 90, -91, + -91, -91, -91, -91, -91, -91, 71, 70, 222, -91, + 733, -91, 164, -91, -91, -91, -91, -91, 1392, -91, + -91, -91, 268, -91, -91, 1914, 1312, -91, 75, -91, + -91, 350, 55, 303, 108, 733, 1740, 59, 38, 242, + 62, 40, 527, 63, 81, -91, 817, -91, 138, 29, + 65, 733, 78, 56, 733, 80, 733, 61, 66, 57, + 101, -91, 347, -91, -91, -91, -91, 64, -91, 140, + -91, -91, 733, -91, -91, 144, -91, -91, -91, + + -102, -102, -102, -102, 19, 103, -102, -102, -102, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -4, 249, -102, -102, -102, -102, -102, -7, -102, -102, + -102, -102, -102, -102, 257, -102, -13, -102, -11, -102, + -102, -102, -102, -102, -102, -3, -102, -102, -102, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -44, -102, + -102, -102, -102, -102, -102, -102, -102, -102, 141, -102, + -102, -102, -8, -102, 0, 16, 116, 122, 129, 119, + -102, -102, 90, 64, -102, -102, 94, -102, 91, 86, + -102, 71, 79, -102, -102, -102, -102, 159, 81, 76, + -102, -102, -102, -102, 98, -102, 67, 63, 47, 163, + -102, 160, 115, 104, 105, 127, 133, -102, 151, 144, + 130, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -102, -102, 145, -102, 152, -102, 162, 31, 21, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -102, -102, -102, -102, 23, -102, -102, -102, -102, -102, + 29, -102, -102, -102, -102, 34, -102, -102, -102, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -102, 89, + -102, 68, 36, -102, -102, 42, -102, 235, 46, 49, + -102, -102, -102, -102, -102, -102, -102, -102, 33, -102, + -102, -102, 26, -102, -102, -18, -102, -102, -102, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -102, 53, -102, -102, 8, 20, -102, -5, -102, 32, + -102, -102, -102, -102, 39, -102, -102, -102, 37, 73, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -102, -102, -102, -102, 40, -102, -102, -102, -102, 97, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + -102, -102, -102, 41, 213, -102, 186, 199, 203, 209, + -102, 50, 51, 38, 57, 60, -102, -102, -102, -102, + -102, -102, -102, -102, 212, -102, 174, -102, 166, -102, + -102, 168, -102, 125, -102, -102, 61, -102, 1, -102, + 45, -102, -9, -102, 172, -102, 184, 176, -102, -102, + 170, -102, -102, -102, -102, -102, -102, 215, -102, 124, + 132, -102, -102, 178, -102, -29, -102, 25, -102, 2, + -102, -102, 62, -102, -102, 102, -102, -102, -28, -102, + 22, -102, -31, -102, -33, -102, -102, -102, -102, -102, + -102, -34, -102, 17, -102, 18, -102, 111, -20, -102, + -102, 24, -102, -102, 153, -102, -102, -102, 30, -102, + -102, -102, -102, 28, -102, 73, 140, -102, 205, -102, + -102, 5, -102, 44, -102, -102, -102, -102, -102, -102, + -102, 43, -102, -102, -102, -102, -102, -102, 135, -102, + -102, 7, -102, -102, -102, -102, 4, -102, 55, -102, + -102, -102, -102, -102, -25, -102, 48, -102, 9, -102, + -102, -102, -102, -69, -102, -102, -70, -102, -102, -102, + -102, -102, -102, -92, -102, -102, -12, -102, -10, -102, + -1, -102, -102, -102, -102, 11, -102, -40, -102, 14, + -102, -39, -102, -102, -102, -17, -102, -102, 54, -102, + -102, -24, -102, -102, -102, -102, -102, -102, -102, -102, + -102, -102, -102, -102, -102, -102, -102, -102, -102, -102, + 3, -102, -102, -102, -102, -102, -102, -102, 267, -102, + -102, -102, 12, -102, -102, -102, 301, -102, -102, -102, + -102, -19, -102, -15, -102, 59, -64, -102, -102, -2, + -102, -102, 142, -102, -102, -102, -14, -102, -102, -102, + -102, 6, -102, 73, 52, -102, 75, -102, -102, -102, + -102, -102, 128, -102, -102, -102, -102, -102, -102, -102, + -102, -102, -6, -102, -102, 58, -102, -102, -102}; + +const int QmlJSGrammar::action_info [] = { + 338, 174, 289, 485, 472, 472, -89, 480, -105, 380, + 43, 472, -79, -78, -100, 448, -97, 435, -102, 134, + 304, 326, 132, 104, 478, 375, 489, 372, 374, 456, + 377, 336, 199, 452, 423, 433, 440, 384, 421, 205, + 431, 456, 132, 365, 350, 344, 214, 476, -108, 456, + 324, 357, 462, 199, 367, 463, 363, 222, 472, 446, + 441, -75, -108, 182, 485, 448, -89, 588, 180, -75, + -97, 489, -100, 2, 289, 525, 380, 104, 224, 7, + 225, 582, 134, 304, 378, -102, 289, -105, -79, 472, + -65, 283, 328, 344, 268, 326, 2, 485, 174, 518, + 174, 174, 489, 333, 284, 218, 324, 372, 174, 572, + 174, 38, 91, 498, 91, 174, 0, 466, 174, 174, + 0, 0, 0, 92, 20, 92, 359, 91, 91, 346, + 475, 174, 459, 347, 445, 444, 576, 575, 92, 92, + 95, 174, 21, 174, 476, -78, 281, 280, 585, 39, + 509, 96, 491, 450, 12, 9, 8, 573, 175, 12, + 382, 499, 201, 212, 281, 280, 202, 279, 278, 281, + 280, 342, 174, 12, 274, 273, 45, 460, 528, 360, + 288, 287, 174, 487, 12, 0, 20, 207, 136, 97, + 12, 13, 16, 369, 41, 286, 13, 16, 207, 39, + 174, 586, 584, 0, 21, 40, 208, 137, 438, 138, + 13, 16, 174, 12, 0, 0, 0, 208, 0, 209, + 12, 13, 16, 12, 0, 524, 523, 13, 16, 520, + 46, 44, 12, 0, 98, 184, 183, 12, 0, 118, + 99, 119, 97, 118, 41, 119, 118, 97, 119, 0, + 13, 16, 120, 470, 469, 40, 120, 13, 16, 120, + 13, 16, 12, 306, 307, 267, 266, 12, 0, 13, + 16, 12, 0, 0, 13, 16, 174, 0, -319, 306, + 307, 12, 0, 521, 519, 0, 0, 98, -319, 0, + 308, 309, 98, 99, 106, 107, 106, 107, 99, 13, + 16, 21, 311, 312, 13, 16, 308, 309, 13, 16, + 12, 313, 12, 118, 314, 119, 315, 0, 13, 16, + 12, 108, 109, 108, 109, 12, 120, 311, 312, 267, + 266, 0, 12, 0, 0, 0, 313, 0, 0, 314, + 0, 315, 277, 276, 272, 271, 0, 13, 16, 13, + 16, 12, 277, 276, 0, 15, 0, 13, 16, 311, + 312, 0, 13, 16, 277, 276, 311, 312, 313, 13, + 16, 314, 0, 315, 0, 313, 12, 0, 314, 12, + 315, 14, 0, 272, 271, 111, 112, 0, 13, 16, + 0, 0, 0, 113, 114, 111, 112, 115, 0, 116, + 0, 0, 0, 113, 114, 0, 15, 115, 0, 116, + 0, 272, 271, 13, 16, 0, 13, 16, 26, 111, + 112, 0, 0, 0, 0, 0, 0, 113, 114, 0, + 27, 115, 14, 116, 0, 111, 112, 12, 0, 26, + 0, 311, 312, 113, 114, 0, 0, 115, 0, 116, + 313, 27, 0, 314, 0, 315, 0, 0, 12, 0, + 0, 0, 0, 29, 0, 0, 0, 15, 0, 0, + 0, 0, 0, 0, 28, 30, 0, 0, 0, 0, + 0, 0, 31, 0, 526, 0, 0, 0, 15, 0, + 0, 25, 0, 14, 0, 28, 30, 186, 0, 0, + 0, 0, 0, 31, 0, 0, 0, 187, 0, 111, + 112, 188, 25, 0, 14, 0, 0, 113, 114, 0, + 189, 115, 190, 116, 0, 340, 0, 0, 0, 0, + 0, 0, 0, 191, 0, 192, 95, 0, 0, 69, + 70, 0, 0, 193, 0, 0, 194, 96, 0, 72, + 0, 0, 195, 0, 0, 0, 12, 0, 196, 0, + 73, 74, 0, 75, 0, 0, 0, 0, 0, 0, + 78, 0, 0, 197, 81, 0, 0, 186, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 187, 0, 0, + 0, 188, 84, 13, 16, 0, 85, 0, 0, 0, + 189, 0, 190, 0, 0, 0, 0, 80, 87, 71, + 0, 0, 0, 191, 0, 192, 95, 0, 0, 0, + 0, 0, 0, 193, 0, 0, 194, 96, 0, 0, + 0, 0, 195, 0, 0, 0, 0, 0, 196, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 197, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 69, 70, 0, 0, 0, + 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, + 0, 0, 12, 0, 0, 0, 73, 74, 0, 75, + 0, 0, 0, 0, 0, 0, 78, 0, 0, 0, + 81, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 84, 13, + 16, 0, 85, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 80, 87, 71, 0, 0, 0, 0, + 0, 0, 0, 0, 68, 69, 70, 0, 0, 0, + 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, + 0, 0, 12, 0, 0, 0, 73, 74, 0, 75, + 0, 0, 0, 76, 0, 77, 78, 79, 0, 0, + 81, 0, 0, 0, 82, 0, 83, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 84, 13, + 16, 0, 85, 0, 86, 0, 88, 0, 89, 0, + 0, 0, 0, 80, 87, 71, 0, 0, 0, 0, + 0, 0, 0, 0, -98, 0, 0, 0, 68, 69, + 70, 0, 0, 0, 0, 0, 0, 0, 0, 72, + 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, + 73, 74, 0, 75, 0, 0, 0, 76, 0, 77, + 78, 79, 0, 0, 81, 0, 0, 0, 82, 0, + 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 84, 13, 16, 0, 85, 0, 86, 0, + 88, 0, 89, 0, 0, 0, 0, 80, 87, 71, + 0, 0, 0, 0, 0, 0, 0, 0, 68, 69, + 70, 0, 0, 0, 0, 0, 0, 0, 0, 72, + 0, 0, 0, 0, 0, 0, 12, 0, 0, 0, + 73, 74, 0, 75, 0, 0, 0, 76, 0, 77, + 78, 79, 0, 0, 81, 0, 0, 0, 82, 0, + 83, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 84, 13, 16, 0, 85, 0, 86, 0, + 88, 303, 89, 0, 0, 0, 0, 80, 87, 71, + 0, 0, 0, 0, 0, 0, 0, 0, 496, 0, + 0, 68, 69, 70, 0, 0, 0, 0, 0, 0, + 0, 0, 72, 0, 0, 0, 0, 0, 0, 12, + 0, 0, 0, 73, 74, 0, 75, 0, 0, 0, + 76, 0, 77, 78, 79, 0, 0, 81, 0, 0, + 0, 82, 0, 83, 0, 0, 497, 0, 0, 0, + 0, 0, 0, 0, 0, 84, 13, 16, 0, 85, + 0, 86, 0, 88, 0, 89, 0, 0, 0, 0, + 80, 87, 71, 0, 0, 0, 0, 0, 0, 0, + 0, 504, 0, 0, 68, 69, 70, 0, 0, 0, + 0, 0, 0, 0, 0, 72, 0, 0, 0, 0, + 0, 0, 12, 0, 0, 0, 73, 74, 0, 75, + 0, 0, 0, 76, 0, 77, 78, 79, 0, 0, + 81, 0, 0, 0, 82, 0, 83, 0, 0, 505, + 0, 0, 0, 0, 0, 0, 0, 0, 84, 13, + 16, 0, 85, 0, 86, 0, 88, 0, 89, 0, + 0, 0, 0, 80, 87, 71, 0, 0, 0, 0, + 0, 0, 0, 0, 496, 0, 0, 68, 69, 70, + 0, 0, 0, 0, 0, 0, 0, 0, 72, 0, + 0, 0, 0, 0, 0, 12, 0, 0, 0, 73, + 74, 0, 75, 0, 0, 0, 76, 0, 77, 78, + 79, 0, 0, 81, 0, 0, 0, 82, 0, 83, + 0, 0, 502, 0, 0, 0, 0, 0, 0, 0, + 0, 84, 13, 16, 0, 85, 0, 86, 0, 88, + 0, 89, 0, 0, 0, 0, 80, 87, 71, 0, + 0, 0, 0, 0, 0, 0, 0, 504, 0, 0, + 68, 69, 70, 0, 0, 0, 0, 0, 0, 0, + 0, 72, 0, 0, 0, 0, 0, 0, 12, 0, + 0, 0, 73, 74, 0, 75, 0, 0, 0, 76, + 0, 77, 78, 79, 0, 0, 81, 0, 0, 0, + 82, 0, 83, 0, 0, 507, 0, 0, 0, 0, + 0, 0, 0, 0, 84, 13, 16, 0, 85, 0, + 86, 0, 88, 0, 89, 0, 0, 0, 0, 80, + 87, 71, 0, 0, 0, 0, 0, 0, 0, 0, + 496, 0, 0, 68, 69, 70, 0, 0, 0, 0, + 0, 0, 0, 0, 72, 0, 0, 0, 0, 0, + 0, 12, 0, 0, 0, 73, 74, 0, 75, 0, + 0, 0, 76, 0, 77, 78, 79, 0, 0, 81, + 0, 0, 0, 82, 0, 83, 0, 0, 497, 0, + 0, 15, 0, 0, 0, 0, 0, 84, 13, 16, + 0, 85, 0, 86, 0, 88, 0, 89, 0, 0, + 0, 0, 80, 87, 71, 0, 0, 14, 0, 0, + 0, 0, 0, 68, 69, 70, 0, 0, 0, 0, + 0, 0, 0, 0, 72, 0, 0, 0, 0, 0, + 0, 12, 251, 0, 0, 535, 536, 0, 75, 0, + 0, 0, 76, 0, 77, 78, 79, 0, 0, 81, + 0, 0, 0, 82, 0, 83, 0, 0, 0, 0, + 0, 0, 0, 255, 0, 0, 0, 84, 13, 16, + 0, 85, 0, 86, 0, 88, 0, 89, 0, 0, + 0, 0, 80, 87, 71, 0, 246, 0, 537, 0, + 0, 0, 0, 142, 143, 144, 0, 0, 146, 148, + 149, 0, 0, 150, 0, 151, 0, 0, 0, 153, + 154, 155, 0, 0, 0, 0, 0, 0, 12, 156, + 157, 158, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 159, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 162, 0, + 0, 0, 0, 0, 0, 13, 16, 163, 164, 165, + 0, 167, 168, 169, 170, 171, 172, 0, 0, 160, + 166, 152, 145, 147, 161, 0, 0, 0, 0, 0, + 142, 143, 144, 0, 0, 146, 148, 149, 0, 0, + 150, 0, 151, 0, 0, 0, 153, 154, 155, 0, + 0, 0, 0, 0, 0, 425, 156, 157, 158, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 159, + 0, 0, 0, 426, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 162, 0, 0, 0, 0, + 0, 430, 427, 429, 163, 164, 165, 0, 167, 168, + 169, 170, 171, 172, 0, 0, 160, 166, 152, 145, + 147, 161, 0, 0, 0, 0, 0, 142, 143, 144, + 0, 0, 146, 148, 149, 0, 0, 150, 0, 151, + 0, 0, 0, 153, 154, 155, 0, 0, 0, 0, + 0, 0, 425, 156, 157, 158, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 159, 0, 0, 0, + 426, 0, 0, 0, 0, 0, 0, 0, 428, 0, + 0, 0, 162, 0, 0, 0, 0, 0, 430, 427, + 429, 163, 164, 165, 0, 167, 168, 169, 170, 171, + 172, 0, 0, 160, 166, 152, 145, 147, 161, 0, + 0, 0, 0, 0, 244, 0, 0, 0, 0, 245, + 0, 68, 69, 70, 247, 0, 0, 0, 0, 0, + 0, 248, 72, 0, 0, 0, 0, 0, 0, 250, + 251, 0, 0, 252, 74, 0, 75, 0, 0, 0, + 76, 0, 77, 78, 79, 0, 0, 81, 0, 0, + 0, 82, 0, 83, 0, 0, 0, 0, 0, 254, + 0, 255, 0, 0, 0, 84, 253, 256, 257, 85, + 258, 86, 259, 88, 31, 89, 260, 261, 0, 0, + 80, 87, 71, 25, 246, 0, 0, 0, 0, 0, + 0, 244, 0, 0, 0, 0, 245, 0, 68, 69, + 70, 247, 0, 0, 0, 0, 0, 0, 248, 249, + 0, 0, 0, 0, 0, 0, 250, 251, 0, 0, + 252, 74, 0, 75, 0, 0, 0, 76, 0, 77, + 78, 79, 0, 0, 81, 0, 0, 0, 82, 0, + 83, 0, 0, 0, 0, 0, 254, 0, 255, 0, + 0, 0, 84, 253, 256, 257, 85, 258, 86, 259, + 88, 31, 89, 260, 261, 0, 0, 80, 87, 71, + 25, 246, 0, 0, 0, 0, 0, 0, 541, 143, + 144, 0, 0, 543, 148, 545, 69, 70, 546, 0, + 151, 0, 0, 0, 153, 548, 549, 0, 0, 0, + 0, 0, 0, 550, 551, 157, 158, 252, 74, 0, + 75, 0, 0, 0, 76, 0, 77, 552, 79, 0, + 0, 554, 0, 0, 0, 82, 0, 83, 0, 0, + 0, 0, 0, 556, 0, 255, 0, 0, 0, 558, + 555, 557, 559, 560, 561, 86, 563, 564, 565, 566, + 567, 568, 0, 0, 553, 562, 547, 542, 544, 161, + 0, 0, 0, 0, 0, 393, 143, 144, 0, 0, + 395, 148, 397, 69, 70, 398, 0, 151, 0, 0, + 0, 153, 400, 401, 0, 0, 0, 0, 0, 0, + 402, 403, 157, 158, 252, 74, 0, 75, 0, 0, + 0, 76, 0, 77, 404, 79, 0, 0, 406, 0, + 0, 0, 82, 0, 83, 0, -244, 0, 0, 0, + 408, 0, 255, 0, 0, 0, 410, 407, 409, 411, + 412, 413, 86, 415, 416, 417, 418, 419, 420, 0, + 0, 405, 414, 399, 394, 396, 161, 0, 0, 0, + 0, 0, + + 334, 477, 282, 482, 270, 503, 467, 464, 275, 42, + 577, 55, 506, 479, 481, 217, 516, 522, 185, 23, + 468, 217, 540, 583, 10, 486, 488, 492, 490, 493, + 508, 270, 434, 385, 422, 383, 381, 366, 379, 368, + 270, 275, 468, 275, 334, 173, 282, 217, 242, 223, + 179, 468, 176, 334, 285, 371, 221, 343, 181, 341, + 211, 282, 465, 198, 352, 204, 457, 339, 370, 449, + 447, 206, 432, 442, 424, 334, 0, 93, 179, 501, + 0, 577, 318, 500, 213, 221, 93, 0, 471, 93, + 93, 93, 130, 483, 316, 317, 93, 461, 93, 93, + 215, 319, 93, 93, 320, 514, 93, 93, 129, 17, + 93, 0, 110, 94, 93, 93, 484, 102, 93, 242, + 93, 103, 101, 203, 337, 93, 11, 484, 93, 93, + 93, 513, 483, 93, 574, 515, 298, 93, 587, 334, + 0, 302, 200, 93, 93, 105, 334, 352, 125, 126, + 93, 11, 215, 269, 93, 93, 373, 510, 93, 124, + 512, 93, 436, 511, 179, 437, 93, 0, 242, 93, + 439, 127, 93, 123, 0, 436, 0, 128, 437, 93, + 93, 483, 215, 93, 93, 139, 436, 122, 335, 437, + 93, 93, 334, 141, 121, 362, 133, 376, 93, 93, + 100, 135, 93, 0, 117, 330, 361, 330, 131, 330, + 302, 93, 302, 93, 302, 330, 302, 0, 302, 0, + 302, 0, 0, 93, 327, 93, 345, 329, 302, 332, + 302, 351, 310, 0, 0, 0, 0, 349, 93, 0, + 348, 364, 93, 302, 93, 321, 484, 302, 93, 322, + 0, 93, 93, 302, 330, 323, 302, 302, 139, 302, + 35, 305, 0, 0, 325, 527, 141, 210, 35, 0, + 24, 37, 11, 0, 0, 0, 358, 0, 24, 37, + 11, 532, 529, 531, 533, 530, 534, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 571, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 569, 0, 0, 0, 0, 0, + 493, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0}; + +const int QmlJSGrammar::action_check [] = { + 60, 8, 36, 36, 33, 33, 7, 60, 7, 36, + 29, 33, 7, 7, 7, 36, 7, 55, 7, 78, + 1, 78, 48, 1, 36, 33, 36, 36, 60, 5, + 55, 61, 2, 33, 8, 55, 60, 16, 7, 7, + 7, 5, 48, 60, 7, 2, 60, 20, 7, 5, + 48, 17, 55, 2, 31, 7, 61, 8, 33, 7, + 7, 7, 7, 60, 36, 36, 7, 0, 8, 7, + 7, 36, 7, 88, 36, 29, 36, 1, 60, 65, + 33, 17, 78, 1, 7, 7, 36, 7, 7, 33, + 33, 76, 8, 2, 55, 78, 88, 36, 8, 29, + 8, 8, 36, 61, 36, 36, 48, 36, 8, 8, + 8, 66, 40, 8, 40, 8, -1, 7, 8, 8, + -1, -1, -1, 51, 15, 51, 8, 40, 40, 50, + 6, 8, 10, 54, 61, 62, 61, 62, 51, 51, + 42, 8, 33, 8, 20, 7, 61, 62, 8, 29, + 60, 53, 60, 60, 29, 61, 62, 56, 56, 29, + 60, 56, 50, 56, 61, 62, 54, 61, 62, 61, + 62, 60, 8, 29, 61, 62, 7, 55, 7, 61, + 61, 62, 8, 60, 29, -1, 15, 15, 15, 12, + 29, 66, 67, 60, 74, 60, 66, 67, 15, 29, + 8, 61, 62, -1, 33, 85, 34, 34, 36, 36, + 66, 67, 8, 29, -1, -1, -1, 34, -1, 36, + 29, 66, 67, 29, -1, 61, 62, 66, 67, 7, + 61, 62, 29, -1, 57, 61, 62, 29, -1, 25, + 63, 27, 12, 25, 74, 27, 25, 12, 27, -1, + 66, 67, 38, 61, 62, 85, 38, 66, 67, 38, + 66, 67, 29, 18, 19, 61, 62, 29, -1, 66, + 67, 29, -1, -1, 66, 67, 8, -1, 36, 18, + 19, 29, -1, 61, 62, -1, -1, 57, 36, -1, + 45, 46, 57, 63, 18, 19, 18, 19, 63, 66, + 67, 33, 23, 24, 66, 67, 45, 46, 66, 67, + 29, 32, 29, 25, 35, 27, 37, -1, 66, 67, + 29, 45, 46, 45, 46, 29, 38, 23, 24, 61, + 62, -1, 29, -1, -1, -1, 32, -1, -1, 35, + -1, 37, 61, 62, 61, 62, -1, 66, 67, 66, + 67, 29, 61, 62, -1, 59, -1, 66, 67, 23, + 24, -1, 66, 67, 61, 62, 23, 24, 32, 66, + 67, 35, -1, 37, -1, 32, 29, -1, 35, 29, + 37, 85, -1, 61, 62, 23, 24, -1, 66, 67, + -1, -1, -1, 31, 32, 23, 24, 35, -1, 37, + -1, -1, -1, 31, 32, -1, 59, 35, -1, 37, + -1, 61, 62, 66, 67, -1, 66, 67, 10, 23, + 24, -1, -1, -1, -1, -1, -1, 31, 32, -1, + 22, 35, 85, 37, -1, 23, 24, 29, -1, 10, + -1, 23, 24, 31, 32, -1, -1, 35, -1, 37, + 32, 22, -1, 35, -1, 37, -1, -1, 29, -1, + -1, -1, -1, 55, -1, -1, -1, 59, -1, -1, + -1, -1, -1, -1, 66, 67, -1, -1, -1, -1, + -1, -1, 74, -1, 55, -1, -1, -1, 59, -1, + -1, 83, -1, 85, -1, 66, 67, 3, -1, -1, + -1, -1, -1, 74, -1, -1, -1, 13, -1, 23, + 24, 17, 83, -1, 85, -1, -1, 31, 32, -1, + 26, 35, 28, 37, -1, 31, -1, -1, -1, -1, + -1, -1, -1, 39, -1, 41, 42, -1, -1, 12, + 13, -1, -1, 49, -1, -1, 52, 53, -1, 22, + -1, -1, 58, -1, -1, -1, 29, -1, 64, -1, + 33, 34, -1, 36, -1, -1, -1, -1, -1, -1, + 43, -1, -1, 79, 47, -1, -1, 3, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 13, -1, -1, + -1, 17, 65, 66, 67, -1, 69, -1, -1, -1, + 26, -1, 28, -1, -1, -1, -1, 80, 81, 82, + -1, -1, -1, 39, -1, 41, 42, -1, -1, -1, + -1, -1, -1, 49, -1, -1, 52, 53, -1, -1, + -1, -1, 58, -1, -1, -1, -1, -1, 64, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 79, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 12, 13, -1, -1, -1, + -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, + -1, -1, 29, -1, -1, -1, 33, 34, -1, 36, + -1, -1, -1, -1, -1, -1, 43, -1, -1, -1, + 47, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, + 67, -1, 69, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 80, 81, 82, -1, -1, -1, -1, + -1, -1, -1, -1, 11, 12, 13, -1, -1, -1, + -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, + -1, -1, 29, -1, -1, -1, 33, 34, -1, 36, + -1, -1, -1, 40, -1, 42, 43, 44, -1, -1, + 47, -1, -1, -1, 51, -1, 53, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, + 67, -1, 69, -1, 71, -1, 73, -1, 75, -1, + -1, -1, -1, 80, 81, 82, -1, -1, -1, -1, + -1, -1, -1, -1, 7, -1, -1, -1, 11, 12, + 13, -1, -1, -1, -1, -1, -1, -1, -1, 22, + -1, -1, -1, -1, -1, -1, 29, -1, -1, -1, + 33, 34, -1, 36, -1, -1, -1, 40, -1, 42, + 43, 44, -1, -1, 47, -1, -1, -1, 51, -1, + 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 65, 66, 67, -1, 69, -1, 71, -1, + 73, -1, 75, -1, -1, -1, -1, 80, 81, 82, + -1, -1, -1, -1, -1, -1, -1, -1, 11, 12, + 13, -1, -1, -1, -1, -1, -1, -1, -1, 22, + -1, -1, -1, -1, -1, -1, 29, -1, -1, -1, + 33, 34, -1, 36, -1, -1, -1, 40, -1, 42, + 43, 44, -1, -1, 47, -1, -1, -1, 51, -1, + 53, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 65, 66, 67, -1, 69, -1, 71, -1, + 73, 74, 75, -1, -1, -1, -1, 80, 81, 82, + -1, -1, -1, -1, -1, -1, -1, -1, 8, -1, + -1, 11, 12, 13, -1, -1, -1, -1, -1, -1, + -1, -1, 22, -1, -1, -1, -1, -1, -1, 29, + -1, -1, -1, 33, 34, -1, 36, -1, -1, -1, + 40, -1, 42, 43, 44, -1, -1, 47, -1, -1, + -1, 51, -1, 53, -1, -1, 56, -1, -1, -1, + -1, -1, -1, -1, -1, 65, 66, 67, -1, 69, + -1, 71, -1, 73, -1, 75, -1, -1, -1, -1, + 80, 81, 82, -1, -1, -1, -1, -1, -1, -1, + -1, 8, -1, -1, 11, 12, 13, -1, -1, -1, + -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, + -1, -1, 29, -1, -1, -1, 33, 34, -1, 36, + -1, -1, -1, 40, -1, 42, 43, 44, -1, -1, + 47, -1, -1, -1, 51, -1, 53, -1, -1, 56, + -1, -1, -1, -1, -1, -1, -1, -1, 65, 66, + 67, -1, 69, -1, 71, -1, 73, -1, 75, -1, + -1, -1, -1, 80, 81, 82, -1, -1, -1, -1, + -1, -1, -1, -1, 8, -1, -1, 11, 12, 13, + -1, -1, -1, -1, -1, -1, -1, -1, 22, -1, + -1, -1, -1, -1, -1, 29, -1, -1, -1, 33, + 34, -1, 36, -1, -1, -1, 40, -1, 42, 43, + 44, -1, -1, 47, -1, -1, -1, 51, -1, 53, + -1, -1, 56, -1, -1, -1, -1, -1, -1, -1, + -1, 65, 66, 67, -1, 69, -1, 71, -1, 73, + -1, 75, -1, -1, -1, -1, 80, 81, 82, -1, + -1, -1, -1, -1, -1, -1, -1, 8, -1, -1, + 11, 12, 13, -1, -1, -1, -1, -1, -1, -1, + -1, 22, -1, -1, -1, -1, -1, -1, 29, -1, + -1, -1, 33, 34, -1, 36, -1, -1, -1, 40, + -1, 42, 43, 44, -1, -1, 47, -1, -1, -1, + 51, -1, 53, -1, -1, 56, -1, -1, -1, -1, + -1, -1, -1, -1, 65, 66, 67, -1, 69, -1, + 71, -1, 73, -1, 75, -1, -1, -1, -1, 80, + 81, 82, -1, -1, -1, -1, -1, -1, -1, -1, + 8, -1, -1, 11, 12, 13, -1, -1, -1, -1, + -1, -1, -1, -1, 22, -1, -1, -1, -1, -1, + -1, 29, -1, -1, -1, 33, 34, -1, 36, -1, + -1, -1, 40, -1, 42, 43, 44, -1, -1, 47, + -1, -1, -1, 51, -1, 53, -1, -1, 56, -1, + -1, 59, -1, -1, -1, -1, -1, 65, 66, 67, + -1, 69, -1, 71, -1, 73, -1, 75, -1, -1, + -1, -1, 80, 81, 82, -1, -1, 85, -1, -1, + -1, -1, -1, 11, 12, 13, -1, -1, -1, -1, + -1, -1, -1, -1, 22, -1, -1, -1, -1, -1, + -1, 29, 30, -1, -1, 33, 34, -1, 36, -1, + -1, -1, 40, -1, 42, 43, 44, -1, -1, 47, + -1, -1, -1, 51, -1, 53, -1, -1, -1, -1, + -1, -1, -1, 61, -1, -1, -1, 65, 66, 67, + -1, 69, -1, 71, -1, 73, -1, 75, -1, -1, + -1, -1, 80, 81, 82, -1, 84, -1, 86, -1, + -1, -1, -1, 4, 5, 6, -1, -1, 9, 10, + 11, -1, -1, 14, -1, 16, -1, -1, -1, 20, + 21, 22, -1, -1, -1, -1, -1, -1, 29, 30, + 31, 32, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 43, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, 59, -1, + -1, -1, -1, -1, -1, 66, 67, 68, 69, 70, + -1, 72, 73, 74, 75, 76, 77, -1, -1, 80, + 81, 82, 83, 84, 85, -1, -1, -1, -1, -1, + 4, 5, 6, -1, -1, 9, 10, 11, -1, -1, + 14, -1, 16, -1, -1, -1, 20, 21, 22, -1, + -1, -1, -1, -1, -1, 29, 30, 31, 32, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, + -1, -1, -1, 47, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 59, -1, -1, -1, -1, + -1, 65, 66, 67, 68, 69, 70, -1, 72, 73, + 74, 75, 76, 77, -1, -1, 80, 81, 82, 83, + 84, 85, -1, -1, -1, -1, -1, 4, 5, 6, + -1, -1, 9, 10, 11, -1, -1, 14, -1, 16, + -1, -1, -1, 20, 21, 22, -1, -1, -1, -1, + -1, -1, 29, 30, 31, 32, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 43, -1, -1, -1, + 47, -1, -1, -1, -1, -1, -1, -1, 55, -1, + -1, -1, 59, -1, -1, -1, -1, -1, 65, 66, + 67, 68, 69, 70, -1, 72, 73, 74, 75, 76, + 77, -1, -1, 80, 81, 82, 83, 84, 85, -1, + -1, -1, -1, -1, 4, -1, -1, -1, -1, 9, + -1, 11, 12, 13, 14, -1, -1, -1, -1, -1, + -1, 21, 22, -1, -1, -1, -1, -1, -1, 29, + 30, -1, -1, 33, 34, -1, 36, -1, -1, -1, + 40, -1, 42, 43, 44, -1, -1, 47, -1, -1, + -1, 51, -1, 53, -1, -1, -1, -1, -1, 59, + -1, 61, -1, -1, -1, 65, 66, 67, 68, 69, + 70, 71, 72, 73, 74, 75, 76, 77, -1, -1, + 80, 81, 82, 83, 84, -1, -1, -1, -1, -1, + -1, 4, -1, -1, -1, -1, 9, -1, 11, 12, + 13, 14, -1, -1, -1, -1, -1, -1, 21, 22, + -1, -1, -1, -1, -1, -1, 29, 30, -1, -1, + 33, 34, -1, 36, -1, -1, -1, 40, -1, 42, + 43, 44, -1, -1, 47, -1, -1, -1, 51, -1, + 53, -1, -1, -1, -1, -1, 59, -1, 61, -1, + -1, -1, 65, 66, 67, 68, 69, 70, 71, 72, + 73, 74, 75, 76, 77, -1, -1, 80, 81, 82, + 83, 84, -1, -1, -1, -1, -1, -1, 4, 5, + 6, -1, -1, 9, 10, 11, 12, 13, 14, -1, + 16, -1, -1, -1, 20, 21, 22, -1, -1, -1, + -1, -1, -1, 29, 30, 31, 32, 33, 34, -1, + 36, -1, -1, -1, 40, -1, 42, 43, 44, -1, + -1, 47, -1, -1, -1, 51, -1, 53, -1, -1, + -1, -1, -1, 59, -1, 61, -1, -1, -1, 65, + 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, + 76, 77, -1, -1, 80, 81, 82, 83, 84, 85, + -1, -1, -1, -1, -1, 4, 5, 6, -1, -1, + 9, 10, 11, 12, 13, 14, -1, 16, -1, -1, + -1, 20, 21, 22, -1, -1, -1, -1, -1, -1, + 29, 30, 31, 32, 33, 34, -1, 36, -1, -1, + -1, 40, -1, 42, 43, 44, -1, -1, 47, -1, + -1, -1, 51, -1, 53, -1, 55, -1, -1, -1, + 59, -1, 61, -1, -1, -1, 65, 66, 67, 68, + 69, 70, 71, 72, 73, 74, 75, 76, 77, -1, + -1, 80, 81, 82, 83, 84, 85, -1, -1, -1, + -1, -1, + + 14, 93, 66, 15, 23, 29, 76, 76, 23, 20, + 23, 14, 29, 23, 15, 23, 23, 14, 62, 23, + 14, 23, 10, 29, 5, 14, 66, 66, 14, 29, + 14, 23, 66, 66, 29, 66, 14, 66, 66, 14, + 23, 23, 14, 23, 14, 14, 66, 23, 66, 23, + 29, 14, 29, 14, 14, 23, 23, 66, 29, 14, + 14, 66, 14, 29, 23, 29, 91, 66, 66, 14, + 66, 29, 29, 66, 30, 14, -1, 39, 29, 25, + -1, 23, 44, 29, 35, 23, 39, -1, 15, 39, + 39, 39, 45, 41, 44, 44, 39, 88, 39, 39, + 41, 44, 39, 39, 44, 41, 39, 39, 45, 6, + 39, -1, 45, 42, 39, 39, 41, 41, 39, 66, + 39, 42, 41, 55, 63, 39, 23, 41, 39, 39, + 39, 41, 41, 39, 6, 41, 39, 39, 80, 14, + -1, 44, 53, 39, 39, 47, 14, 23, 44, 44, + 39, 23, 41, 100, 39, 39, 94, 41, 39, 44, + 41, 39, 33, 41, 29, 36, 39, -1, 66, 39, + 35, 44, 39, 43, -1, 33, -1, 44, 36, 39, + 39, 41, 41, 39, 39, 23, 33, 43, 63, 36, + 39, 39, 14, 31, 43, 63, 51, 95, 39, 39, + 41, 49, 39, -1, 44, 39, 82, 39, 45, 39, + 44, 39, 44, 39, 44, 39, 44, -1, 44, -1, + 44, -1, -1, 39, 50, 39, 54, 61, 44, 61, + 44, 61, 46, -1, -1, -1, -1, 61, 39, -1, + 56, 63, 39, 44, 39, 46, 41, 44, 39, 46, + -1, 39, 39, 44, 39, 46, 44, 44, 23, 44, + 11, 48, -1, -1, 52, 8, 31, 32, 11, -1, + 21, 22, 23, -1, -1, -1, 61, -1, 21, 22, + 23, 14, 15, 16, 17, 18, 19, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 6, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 23, -1, -1, -1, -1, -1, + 29, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1}; + diff --git a/src/declarative/qml/parser/qmljsgrammar_p.h b/src/declarative/qml/parser/qmljsgrammar_p.h new file mode 100644 index 0000000..c514485 --- /dev/null +++ b/src/declarative/qml/parser/qmljsgrammar_p.h @@ -0,0 +1,200 @@ +// This file was generated by qlalr - DO NOT EDIT! +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtCore module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists for the convenience +// of other Qt classes. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#ifndef QMLJSGRAMMAR_P_H +#define QMLJSGRAMMAR_P_H + +class QmlJSGrammar +{ +public: + enum { + EOF_SYMBOL = 0, + REDUCE_HERE = 90, + SHIFT_THERE = 89, + T_AND = 1, + T_AND_AND = 2, + T_AND_EQ = 3, + T_AUTOMATIC_SEMICOLON = 62, + T_BREAK = 4, + T_CASE = 5, + T_CATCH = 6, + T_COLON = 7, + T_COMMA = 8, + T_CONST = 83, + T_CONTINUE = 9, + T_DEBUGGER = 84, + T_DEFAULT = 10, + T_DELETE = 11, + T_DIVIDE_ = 12, + T_DIVIDE_EQ = 13, + T_DO = 14, + T_DOT = 15, + T_ELSE = 16, + T_EQ = 17, + T_EQ_EQ = 18, + T_EQ_EQ_EQ = 19, + T_FALSE = 82, + T_FINALLY = 20, + T_FOR = 21, + T_FUNCTION = 22, + T_GE = 23, + T_GT = 24, + T_GT_GT = 25, + T_GT_GT_EQ = 26, + T_GT_GT_GT = 27, + T_GT_GT_GT_EQ = 28, + T_IDENTIFIER = 29, + T_IF = 30, + T_IMPORT = 88, + T_IN = 31, + T_INSTANCEOF = 32, + T_LBRACE = 33, + T_LBRACKET = 34, + T_LE = 35, + T_LPAREN = 36, + T_LT = 37, + T_LT_LT = 38, + T_LT_LT_EQ = 39, + T_MINUS = 40, + T_MINUS_EQ = 41, + T_MINUS_MINUS = 42, + T_MULTILINE_STRING_LITERAL = 86, + T_NEW = 43, + T_NOT = 44, + T_NOT_EQ = 45, + T_NOT_EQ_EQ = 46, + T_NULL = 80, + T_NUMERIC_LITERAL = 47, + T_OR = 48, + T_OR_EQ = 49, + T_OR_OR = 50, + T_PLUS = 51, + T_PLUS_EQ = 52, + T_PLUS_PLUS = 53, + T_PROPERTY = 66, + T_PUBLIC = 87, + T_QUESTION = 54, + T_RBRACE = 55, + T_RBRACKET = 56, + T_REMAINDER = 57, + T_REMAINDER_EQ = 58, + T_RESERVED_WORD = 85, + T_RETURN = 59, + T_RPAREN = 60, + T_SEMICOLON = 61, + T_SIGNAL = 67, + T_STAR = 63, + T_STAR_EQ = 64, + T_STRING_LITERAL = 65, + T_SWITCH = 68, + T_THIS = 69, + T_THROW = 70, + T_TILDE = 71, + T_TRUE = 81, + T_TRY = 72, + T_TYPEOF = 73, + T_VAR = 74, + T_VOID = 75, + T_WHILE = 76, + T_WITH = 77, + T_XOR = 78, + T_XOR_EQ = 79, + + ACCEPT_STATE = 588, + RULE_COUNT = 323, + STATE_COUNT = 589, + TERMINAL_COUNT = 91, + NON_TERMINAL_COUNT = 102, + + GOTO_INDEX_OFFSET = 589, + GOTO_INFO_OFFSET = 2092, + GOTO_CHECK_OFFSET = 2092 + }; + + static const char *const spell []; + static const int lhs []; + static const int rhs []; + static const int goto_default []; + static const int action_default []; + static const int action_index []; + static const int action_info []; + static const int action_check []; + + static inline int nt_action (int state, int nt) + { + const int *const goto_index = &action_index [GOTO_INDEX_OFFSET]; + const int *const goto_check = &action_check [GOTO_CHECK_OFFSET]; + + const int yyn = goto_index [state] + nt; + + if (yyn < 0 || goto_check [yyn] != nt) + return goto_default [nt]; + + const int *const goto_info = &action_info [GOTO_INFO_OFFSET]; + return goto_info [yyn]; + } + + static inline int t_action (int state, int token) + { + const int yyn = action_index [state] + token; + + if (yyn < 0 || action_check [yyn] != token) + return - action_default [state]; + + return action_info [yyn]; + } +}; + + +#endif // QMLJSGRAMMAR_P_H + diff --git a/src/declarative/qml/parser/qmljslexer.cpp b/src/declarative/qml/parser/qmljslexer.cpp new file mode 100644 index 0000000..843f6ae --- /dev/null +++ b/src/declarative/qml/parser/qmljslexer.cpp @@ -0,0 +1,1196 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "qmljsengine_p.h" +#include "qmljslexer_p.h" +#include "qmljsgrammar_p.h" + +#include +#include +#include +#include + +QT_BEGIN_NAMESPACE + +extern double qstrtod(const char *s00, char const **se, bool *ok); + +#define shiftWindowsLineBreak() \ + do { \ + if (((current == '\r') && (next1 == '\n')) \ + || ((current == '\n') && (next1 == '\r'))) { \ + shift(1); \ + } \ + } \ + while (0) + +namespace QmlJS { +extern double integerFromString(const char *buf, int size, int radix); +} + +using namespace QmlJS; + +Lexer::Lexer(Engine *eng) + : driver(eng), + yylineno(0), + done(false), + size8(128), size16(128), + pos8(0), pos16(0), + terminator(false), + restrKeyword(false), + delimited(false), + stackToken(-1), + state(Start), + pos(0), + code(0), length(0), + yycolumn(0), + startpos(0), + startlineno(0), startcolumn(0), + bol(true), + current(0), next1(0), next2(0), next3(0), + err(NoError), + wantRx(false), + check_reserved(true), + parenthesesState(IgnoreParentheses), + parenthesesCount(0), + prohibitAutomaticSemicolon(false) +{ + driver->setLexer(this); + // allocate space for read buffers + buffer8 = new char[size8]; + buffer16 = new QChar[size16]; + pattern = 0; + flags = 0; + +} + +Lexer::~Lexer() +{ + delete [] buffer8; + delete [] buffer16; +} + +void Lexer::setCode(const QString &c, int lineno) +{ + errmsg = QString(); + yylineno = lineno; + yycolumn = 1; + restrKeyword = false; + delimited = false; + stackToken = -1; + pos = 0; + code = c.unicode(); + length = c.length(); + bol = true; + + // read first characters + current = (length > 0) ? code[0].unicode() : 0; + next1 = (length > 1) ? code[1].unicode() : 0; + next2 = (length > 2) ? code[2].unicode() : 0; + next3 = (length > 3) ? code[3].unicode() : 0; +} + +void Lexer::shift(uint p) +{ + while (p--) { + ++pos; + ++yycolumn; + current = next1; + next1 = next2; + next2 = next3; + next3 = (pos + 3 < length) ? code[pos+3].unicode() : 0; + } +} + +void Lexer::setDone(State s) +{ + state = s; + done = true; +} + +int Lexer::findReservedWord(const QChar *c, int size) const +{ + switch (size) { + case 2: { + if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o')) + return QmlJSGrammar::T_DO; + else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('f')) + return QmlJSGrammar::T_IF; + else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n')) + return QmlJSGrammar::T_IN; + } break; + + case 3: { + if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('o') && c[2] == QLatin1Char('r')) + return QmlJSGrammar::T_FOR; + else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('e') && c[2] == QLatin1Char('w')) + return QmlJSGrammar::T_NEW; + else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') && c[2] == QLatin1Char('y')) + return QmlJSGrammar::T_TRY; + else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('a') && c[2] == QLatin1Char('r')) + return QmlJSGrammar::T_VAR; + else if (check_reserved) { + if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') && c[2] == QLatin1Char('t')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + case 4: { + if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a') + && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e')) + return QmlJSGrammar::T_CASE; + else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('l') + && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('e')) + return QmlJSGrammar::T_ELSE; + else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h') + && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('s')) + return QmlJSGrammar::T_THIS; + else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o') + && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('d')) + return QmlJSGrammar::T_VOID; + else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('i') + && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('h')) + return QmlJSGrammar::T_WITH; + else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') + && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('e')) + return QmlJSGrammar::T_TRUE; + else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('u') + && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('l')) + return QmlJSGrammar::T_NULL; + else if (check_reserved) { + if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('n') + && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('m')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('y') + && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('l') && c[1] == QLatin1Char('o') + && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('g')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('h') + && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('r')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('g') && c[1] == QLatin1Char('o') + && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('o')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + case 5: { + if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('r') + && c[2] == QLatin1Char('e') && c[3] == QLatin1Char('a') + && c[4] == QLatin1Char('k')) + return QmlJSGrammar::T_BREAK; + else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('a') + && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('c') + && c[4] == QLatin1Char('h')) + return QmlJSGrammar::T_CATCH; + else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h') + && c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o') + && c[4] == QLatin1Char('w')) + return QmlJSGrammar::T_THROW; + else if (c[0] == QLatin1Char('w') && c[1] == QLatin1Char('h') + && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('l') + && c[4] == QLatin1Char('e')) + return QmlJSGrammar::T_WHILE; + else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o') + && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('s') + && c[4] == QLatin1Char('t')) + return QmlJSGrammar::T_CONST; + else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('a') + && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('s') + && c[4] == QLatin1Char('e')) + return QmlJSGrammar::T_FALSE; + else if (check_reserved) { + if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('h') + && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('r') + && c[4] == QLatin1Char('t')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('u') + && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e') + && c[4] == QLatin1Char('r')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i') + && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a') + && c[4] == QLatin1Char('l')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('l') + && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('s') + && c[4] == QLatin1Char('s')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('l') + && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('a') + && c[4] == QLatin1Char('t')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + case 6: { + if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e') + && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('e') + && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('e')) + return QmlJSGrammar::T_DELETE; + else if (c[0] == QLatin1Char('r') && c[1] == QLatin1Char('e') + && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('u') + && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('n')) + return QmlJSGrammar::T_RETURN; + else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('w') + && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('t') + && c[4] == QLatin1Char('c') && c[5] == QLatin1Char('h')) + return QmlJSGrammar::T_SWITCH; + else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('y') + && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('e') + && c[4] == QLatin1Char('o') && c[5] == QLatin1Char('f')) + return QmlJSGrammar::T_TYPEOF; + else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m') + && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o') + && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t')) + return QmlJSGrammar::T_IMPORT; + else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('i') + && c[2] == QLatin1Char('g') && c[3] == QLatin1Char('n') + && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('l')) + return QmlJSGrammar::T_SIGNAL; + else if (check_reserved) { + if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x') + && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o') + && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('t') + && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('t') + && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('o') + && c[2] == QLatin1Char('u') && c[3] == QLatin1Char('b') + && c[4] == QLatin1Char('l') && c[5] == QLatin1Char('e')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m') + && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('o') + && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('t')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('u') + && c[2] == QLatin1Char('b') && c[3] == QLatin1Char('l') + && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('c')) + return QmlJSGrammar::T_PUBLIC; + else if (c[0] == QLatin1Char('n') && c[1] == QLatin1Char('a') + && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('i') + && c[4] == QLatin1Char('v') && c[5] == QLatin1Char('e')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('h') + && c[2] == QLatin1Char('r') && c[3] == QLatin1Char('o') + && c[4] == QLatin1Char('w') && c[5] == QLatin1Char('s')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + case 7: { + if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e') + && c[2] == QLatin1Char('f') && c[3] == QLatin1Char('a') + && c[4] == QLatin1Char('u') && c[5] == QLatin1Char('l') + && c[6] == QLatin1Char('t')) + return QmlJSGrammar::T_DEFAULT; + else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('i') + && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('a') + && c[4] == QLatin1Char('l') && c[5] == QLatin1Char('l') + && c[6] == QLatin1Char('y')) + return QmlJSGrammar::T_FINALLY; + else if (check_reserved) { + if (c[0] == QLatin1Char('b') && c[1] == QLatin1Char('o') + && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('l') + && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('a') + && c[6] == QLatin1Char('n')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('e') && c[1] == QLatin1Char('x') + && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e') + && c[4] == QLatin1Char('n') && c[5] == QLatin1Char('d') + && c[6] == QLatin1Char('s')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('a') + && c[2] == QLatin1Char('c') && c[3] == QLatin1Char('k') + && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('g') + && c[6] == QLatin1Char('e')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r') + && c[2] == QLatin1Char('i') && c[3] == QLatin1Char('v') + && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('t') + && c[6] == QLatin1Char('e')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + case 8: { + if (c[0] == QLatin1Char('c') && c[1] == QLatin1Char('o') + && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('t') + && c[4] == QLatin1Char('i') && c[5] == QLatin1Char('n') + && c[6] == QLatin1Char('u') && c[7] == QLatin1Char('e')) + return QmlJSGrammar::T_CONTINUE; + else if (c[0] == QLatin1Char('f') && c[1] == QLatin1Char('u') + && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c') + && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i') + && c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n')) + return QmlJSGrammar::T_FUNCTION; + else if (c[0] == QLatin1Char('d') && c[1] == QLatin1Char('e') + && c[2] == QLatin1Char('b') && c[3] == QLatin1Char('u') + && c[4] == QLatin1Char('g') && c[5] == QLatin1Char('g') + && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('r')) + return QmlJSGrammar::T_DEBUGGER; + else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r') + && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('p') + && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('r') + && c[6] == QLatin1Char('t') && c[7] == QLatin1Char('y')) + return QmlJSGrammar::T_PROPERTY; + else if (check_reserved) { + if (c[0] == QLatin1Char('a') && c[1] == QLatin1Char('b') + && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t') + && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('a') + && c[6] == QLatin1Char('c') && c[7] == QLatin1Char('t')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('v') && c[1] == QLatin1Char('o') + && c[2] == QLatin1Char('l') && c[3] == QLatin1Char('a') + && c[4] == QLatin1Char('t') && c[5] == QLatin1Char('i') + && c[6] == QLatin1Char('l') && c[7] == QLatin1Char('e')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + case 9: { + if (check_reserved) { + if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') + && c[2] == QLatin1Char('t') && c[3] == QLatin1Char('e') + && c[4] == QLatin1Char('r') && c[5] == QLatin1Char('f') + && c[6] == QLatin1Char('a') && c[7] == QLatin1Char('c') + && c[8] == QLatin1Char('e')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('t') && c[1] == QLatin1Char('r') + && c[2] == QLatin1Char('a') && c[3] == QLatin1Char('n') + && c[4] == QLatin1Char('s') && c[5] == QLatin1Char('i') + && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n') + && c[8] == QLatin1Char('t')) + return QmlJSGrammar::T_RESERVED_WORD; + else if (c[0] == QLatin1Char('p') && c[1] == QLatin1Char('r') + && c[2] == QLatin1Char('o') && c[3] == QLatin1Char('t') + && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('c') + && c[6] == QLatin1Char('t') && c[7] == QLatin1Char('e') + && c[8] == QLatin1Char('d')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + case 10: { + if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('n') + && c[2] == QLatin1Char('s') && c[3] == QLatin1Char('t') + && c[4] == QLatin1Char('a') && c[5] == QLatin1Char('n') + && c[6] == QLatin1Char('c') && c[7] == QLatin1Char('e') + && c[8] == QLatin1Char('o') && c[9] == QLatin1Char('f')) + return QmlJSGrammar::T_INSTANCEOF; + else if (check_reserved) { + if (c[0] == QLatin1Char('i') && c[1] == QLatin1Char('m') + && c[2] == QLatin1Char('p') && c[3] == QLatin1Char('l') + && c[4] == QLatin1Char('e') && c[5] == QLatin1Char('m') + && c[6] == QLatin1Char('e') && c[7] == QLatin1Char('n') + && c[8] == QLatin1Char('t') && c[9] == QLatin1Char('s')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + case 12: { + if (check_reserved) { + if (c[0] == QLatin1Char('s') && c[1] == QLatin1Char('y') + && c[2] == QLatin1Char('n') && c[3] == QLatin1Char('c') + && c[4] == QLatin1Char('h') && c[5] == QLatin1Char('r') + && c[6] == QLatin1Char('o') && c[7] == QLatin1Char('n') + && c[8] == QLatin1Char('i') && c[9] == QLatin1Char('z') + && c[10] == QLatin1Char('e') && c[11] == QLatin1Char('d')) + return QmlJSGrammar::T_RESERVED_WORD; + } + } break; + + } // switch + + return -1; +} + +int Lexer::lex() +{ + int token = 0; + state = Start; + ushort stringType = 0; // either single or double quotes + bool multiLineString = false; + pos8 = pos16 = 0; + done = false; + terminator = false; + + // did we push a token on the stack previously ? + // (after an automatic semicolon insertion) + if (stackToken >= 0) { + setDone(Other); + token = stackToken; + stackToken = -1; + } + + while (!done) { + switch (state) { + case Start: + if (isWhiteSpace()) { + // do nothing + } else if (current == '/' && next1 == '/') { + recordStartPos(); + shift(1); + state = InSingleLineComment; + } else if (current == '/' && next1 == '*') { + recordStartPos(); + shift(1); + state = InMultiLineComment; + } else if (current == 0) { + syncProhibitAutomaticSemicolon(); + if (!terminator && !delimited && !prohibitAutomaticSemicolon) { + // automatic semicolon insertion if program incomplete + token = QmlJSGrammar::T_SEMICOLON; + stackToken = 0; + setDone(Other); + } else { + setDone(Eof); + } + } else if (isLineTerminator()) { + shiftWindowsLineBreak(); + yylineno++; + yycolumn = 0; + bol = true; + terminator = true; + syncProhibitAutomaticSemicolon(); + if (restrKeyword) { + token = QmlJSGrammar::T_SEMICOLON; + setDone(Other); + } + } else if (current == '"' || current == '\'') { + recordStartPos(); + state = InString; + multiLineString = false; + stringType = current; + } else if (isIdentLetter(current)) { + recordStartPos(); + record16(current); + state = InIdentifier; + } else if (current == '0') { + recordStartPos(); + record8(current); + state = InNum0; + } else if (isDecimalDigit(current)) { + recordStartPos(); + record8(current); + state = InNum; + } else if (current == '.' && isDecimalDigit(next1)) { + recordStartPos(); + record8(current); + state = InDecimal; + } else { + recordStartPos(); + token = matchPunctuator(current, next1, next2, next3); + if (token != -1) { + if (terminator && !delimited && !prohibitAutomaticSemicolon + && (token == QmlJSGrammar::T_PLUS_PLUS + || token == QmlJSGrammar::T_MINUS_MINUS)) { + // automatic semicolon insertion + stackToken = token; + token = QmlJSGrammar::T_SEMICOLON; + } + setDone(Other); + } + else { + setDone(Bad); + err = IllegalCharacter; + errmsg = QLatin1String("Illegal character"); + } + } + break; + case InString: + if (current == stringType) { + shift(1); + setDone(String); + } else if (isLineTerminator()) { + multiLineString = true; + record16(current); + } else if (current == 0 || isLineTerminator()) { + setDone(Bad); + err = UnclosedStringLiteral; + errmsg = QLatin1String("Unclosed string at end of line"); + } else if (current == '\\') { + state = InEscapeSequence; + } else { + record16(current); + } + break; + // Escape Sequences inside of strings + case InEscapeSequence: + if (isOctalDigit(current)) { + if (current >= '0' && current <= '3' && + isOctalDigit(next1) && isOctalDigit(next2)) { + record16(convertOctal(current, next1, next2)); + shift(2); + state = InString; + } else if (isOctalDigit(current) && + isOctalDigit(next1)) { + record16(convertOctal('0', current, next1)); + shift(1); + state = InString; + } else if (isOctalDigit(current)) { + record16(convertOctal('0', '0', current)); + state = InString; + } else { + setDone(Bad); + err = IllegalEscapeSequence; + errmsg = QLatin1String("Illegal escape squence"); + } + } else if (current == 'x') + state = InHexEscape; + else if (current == 'u') + state = InUnicodeEscape; + else { + if (isLineTerminator()) { + shiftWindowsLineBreak(); + yylineno++; + yycolumn = 0; + bol = true; + } else { + record16(singleEscape(current)); + } + state = InString; + } + break; + case InHexEscape: + if (isHexDigit(current) && isHexDigit(next1)) { + state = InString; + record16(QLatin1Char(convertHex(current, next1))); + shift(1); + } else if (current == stringType) { + record16(QLatin1Char('x')); + shift(1); + setDone(String); + } else { + record16(QLatin1Char('x')); + record16(current); + state = InString; + } + break; + case InUnicodeEscape: + if (isHexDigit(current) && isHexDigit(next1) && + isHexDigit(next2) && isHexDigit(next3)) { + record16(convertUnicode(current, next1, next2, next3)); + shift(3); + state = InString; + } else if (current == stringType) { + record16(QLatin1Char('u')); + shift(1); + setDone(String); + } else { + setDone(Bad); + err = IllegalUnicodeEscapeSequence; + errmsg = QLatin1String("Illegal unicode escape sequence"); + } + break; + case InSingleLineComment: + if (isLineTerminator()) { + shiftWindowsLineBreak(); + yylineno++; + yycolumn = 0; + terminator = true; + bol = true; + if (restrKeyword) { + token = QmlJSGrammar::T_SEMICOLON; + setDone(Other); + } else + state = Start; + } else if (current == 0) { + setDone(Eof); + } + break; + case InMultiLineComment: + if (current == 0) { + setDone(Bad); + err = UnclosedComment; + errmsg = QLatin1String("Unclosed comment at end of file"); + } else if (isLineTerminator()) { + shiftWindowsLineBreak(); + yylineno++; + } else if (current == '*' && next1 == '/') { + state = Start; + shift(1); + } + break; + case InIdentifier: + if (isIdentLetter(current) || isDecimalDigit(current)) { + record16(current); + break; + } + setDone(Identifier); + break; + case InNum0: + if (current == 'x' || current == 'X') { + record8(current); + state = InHex; + } else if (current == '.') { + record8(current); + state = InDecimal; + } else if (current == 'e' || current == 'E') { + record8(current); + state = InExponentIndicator; + } else if (isOctalDigit(current)) { + record8(current); + state = InOctal; + } else if (isDecimalDigit(current)) { + record8(current); + state = InDecimal; + } else { + setDone(Number); + } + break; + case InHex: + if (isHexDigit(current)) + record8(current); + else + setDone(Hex); + break; + case InOctal: + if (isOctalDigit(current)) { + record8(current); + } else if (isDecimalDigit(current)) { + record8(current); + state = InDecimal; + } else { + setDone(Octal); + } + break; + case InNum: + if (isDecimalDigit(current)) { + record8(current); + } else if (current == '.') { + record8(current); + state = InDecimal; + } else if (current == 'e' || current == 'E') { + record8(current); + state = InExponentIndicator; + } else { + setDone(Number); + } + break; + case InDecimal: + if (isDecimalDigit(current)) { + record8(current); + } else if (current == 'e' || current == 'E') { + record8(current); + state = InExponentIndicator; + } else { + setDone(Number); + } + break; + case InExponentIndicator: + if (current == '+' || current == '-') { + record8(current); + } else if (isDecimalDigit(current)) { + record8(current); + state = InExponent; + } else { + setDone(Bad); + err = IllegalExponentIndicator; + errmsg = QLatin1String("Illegal syntax for exponential number"); + } + break; + case InExponent: + if (isDecimalDigit(current)) { + record8(current); + } else { + setDone(Number); + } + break; + default: + Q_ASSERT_X(0, "Lexer::lex", "Unhandled state in switch statement"); + } + + // move on to the next character + if (!done) + shift(1); + if (state != Start && state != InSingleLineComment) + bol = false; + } + + if (state == Number) { + // CSS-style suffix for numeric literals + + flags = noSuffix; + + const ushort c = QChar::toLower(current); + const ushort n1 = QChar::toLower(next1); + const ushort n2 = QChar::toLower(next2); + const ushort n3 = QChar::toLower(next3); + + if (c == 'e' && n1 == 'm') { + flags = emSuffix; + shift(2); + } else if (c == 'e' && n1 == 'x') { + flags = exSuffix; + shift(2); + } else if (c == 'p' && n1 == 'x') { + flags = pxSuffix; + shift(2); + } else if (c == 'c' && n1 == 'm') { + flags = cmSuffix; + shift(2); + } else if (c == 'm' && n1 == 'm') { + flags = mmSuffix; + shift(2); + } else if (c == 'i' && n1 == 'n') { + flags = inSuffix; + shift(2); + } else if (c == 'p' && n1 == 't') { + flags = ptSuffix; + shift(2); + } else if (c == 'p' && n1 == 'c') { + flags = pcSuffix; + shift(1); + } else if (c == 'd' && n1 == 'e' && n2 == 'g') { + flags = degSuffix; + shift(3); + } else if (c == 'r' && n1 == 'a' && n2 == 'd') { + flags = radSuffix; + shift(3); + } else if (c == 'g' && n1 == 'r' && n2 == 'a' && n3 == 'd') { + flags = gradSuffix; + shift(4); + } else if (c == 'm' && n1 == 's') { + flags = msSuffix; + shift(2); + } else if (c == 's') { + flags = sSuffix; + shift(1); + } else if (c == 'h' && n1 == 'z') { + flags = hzSuffix; + shift(2); + } else if (c == 'k' && n1 == 'h' && n2 == 'z') { + flags = khzSuffix; + shift(3); + } + } + + // no identifiers allowed directly after numeric literal, e.g. "3in" is bad + if ((state == Number || state == Octal || state == Hex) + && isIdentLetter(current)) { + state = Bad; + err = IllegalIdentifier; + errmsg = QLatin1String("Identifier cannot start with numeric literal"); + } + + // terminate string + buffer8[pos8] = '\0'; + + double dval = 0; + if (state == Number) { + dval = qstrtod(buffer8, 0, 0); + } else if (state == Hex) { // scan hex numbers + dval = integerFromString(buffer8, pos8, 16); + state = Number; + } else if (state == Octal) { // scan octal number + dval = integerFromString(buffer8, pos8, 8); + state = Number; + } + + restrKeyword = false; + delimited = false; + + switch (parenthesesState) { + case IgnoreParentheses: + break; + case CountParentheses: + if (token == QmlJSGrammar::T_RPAREN) { + --parenthesesCount; + if (parenthesesCount == 0) + parenthesesState = BalancedParentheses; + } else if (token == QmlJSGrammar::T_LPAREN) { + ++parenthesesCount; + } + break; + case BalancedParentheses: + parenthesesState = IgnoreParentheses; + break; + } + + switch (state) { + case Eof: + return 0; + case Other: + if (token == QmlJSGrammar::T_RBRACE || token == QmlJSGrammar::T_SEMICOLON) + delimited = true; + return token; + case Identifier: + if ((token = findReservedWord(buffer16, pos16)) < 0) { + /* TODO: close leak on parse error. same holds true for String */ + if (driver) + qsyylval.ustr = driver->intern(buffer16, pos16); + else + qsyylval.ustr = 0; + return QmlJSGrammar::T_IDENTIFIER; + } + if (token == QmlJSGrammar::T_CONTINUE || token == QmlJSGrammar::T_BREAK + || token == QmlJSGrammar::T_RETURN || token == QmlJSGrammar::T_THROW) { + restrKeyword = true; + } else if (token == QmlJSGrammar::T_IF || token == QmlJSGrammar::T_FOR + || token == QmlJSGrammar::T_WHILE || token == QmlJSGrammar::T_WITH) { + parenthesesState = CountParentheses; + parenthesesCount = 0; + } else if (token == QmlJSGrammar::T_DO) { + parenthesesState = BalancedParentheses; + } + return token; + case String: + if (driver) + qsyylval.ustr = driver->intern(buffer16, pos16); + else + qsyylval.ustr = 0; + return multiLineString?QmlJSGrammar::T_MULTILINE_STRING_LITERAL:QmlJSGrammar::T_STRING_LITERAL; + case Number: + qsyylval.dval = dval; + return QmlJSGrammar::T_NUMERIC_LITERAL; + case Bad: + return -1; + default: + Q_ASSERT(!"unhandled numeration value in switch"); + return -1; + } +} + +bool Lexer::isWhiteSpace() const +{ + return (current == ' ' || current == '\t' || + current == 0x0b || current == 0x0c); +} + +bool Lexer::isLineTerminator() const +{ + return (current == '\n' || current == '\r'); +} + +bool Lexer::isIdentLetter(ushort c) +{ + /* TODO: allow other legitimate unicode chars */ + return ((c >= 'a' && c <= 'z') + || (c >= 'A' && c <= 'Z') + || c == '$' + || c == '_'); +} + +bool Lexer::isDecimalDigit(ushort c) +{ + return (c >= '0' && c <= '9'); +} + +bool Lexer::isHexDigit(ushort c) const +{ + return ((c >= '0' && c <= '9') + || (c >= 'a' && c <= 'f') + || (c >= 'A' && c <= 'F')); +} + +bool Lexer::isOctalDigit(ushort c) const +{ + return (c >= '0' && c <= '7'); +} + +int Lexer::matchPunctuator(ushort c1, ushort c2, + ushort c3, ushort c4) +{ + if (c1 == '>' && c2 == '>' && c3 == '>' && c4 == '=') { + shift(4); + return QmlJSGrammar::T_GT_GT_GT_EQ; + } else if (c1 == '=' && c2 == '=' && c3 == '=') { + shift(3); + return QmlJSGrammar::T_EQ_EQ_EQ; + } else if (c1 == '!' && c2 == '=' && c3 == '=') { + shift(3); + return QmlJSGrammar::T_NOT_EQ_EQ; + } else if (c1 == '>' && c2 == '>' && c3 == '>') { + shift(3); + return QmlJSGrammar::T_GT_GT_GT; + } else if (c1 == '<' && c2 == '<' && c3 == '=') { + shift(3); + return QmlJSGrammar::T_LT_LT_EQ; + } else if (c1 == '>' && c2 == '>' && c3 == '=') { + shift(3); + return QmlJSGrammar::T_GT_GT_EQ; + } else if (c1 == '<' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_LE; + } else if (c1 == '>' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_GE; + } else if (c1 == '!' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_NOT_EQ; + } else if (c1 == '+' && c2 == '+') { + shift(2); + return QmlJSGrammar::T_PLUS_PLUS; + } else if (c1 == '-' && c2 == '-') { + shift(2); + return QmlJSGrammar::T_MINUS_MINUS; + } else if (c1 == '=' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_EQ_EQ; + } else if (c1 == '+' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_PLUS_EQ; + } else if (c1 == '-' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_MINUS_EQ; + } else if (c1 == '*' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_STAR_EQ; + } else if (c1 == '/' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_DIVIDE_EQ; + } else if (c1 == '&' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_AND_EQ; + } else if (c1 == '^' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_XOR_EQ; + } else if (c1 == '%' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_REMAINDER_EQ; + } else if (c1 == '|' && c2 == '=') { + shift(2); + return QmlJSGrammar::T_OR_EQ; + } else if (c1 == '<' && c2 == '<') { + shift(2); + return QmlJSGrammar::T_LT_LT; + } else if (c1 == '>' && c2 == '>') { + shift(2); + return QmlJSGrammar::T_GT_GT; + } else if (c1 == '&' && c2 == '&') { + shift(2); + return QmlJSGrammar::T_AND_AND; + } else if (c1 == '|' && c2 == '|') { + shift(2); + return QmlJSGrammar::T_OR_OR; + } + + switch(c1) { + case '=': shift(1); return QmlJSGrammar::T_EQ; + case '>': shift(1); return QmlJSGrammar::T_GT; + case '<': shift(1); return QmlJSGrammar::T_LT; + case ',': shift(1); return QmlJSGrammar::T_COMMA; + case '!': shift(1); return QmlJSGrammar::T_NOT; + case '~': shift(1); return QmlJSGrammar::T_TILDE; + case '?': shift(1); return QmlJSGrammar::T_QUESTION; + case ':': shift(1); return QmlJSGrammar::T_COLON; + case '.': shift(1); return QmlJSGrammar::T_DOT; + case '+': shift(1); return QmlJSGrammar::T_PLUS; + case '-': shift(1); return QmlJSGrammar::T_MINUS; + case '*': shift(1); return QmlJSGrammar::T_STAR; + case '/': shift(1); return QmlJSGrammar::T_DIVIDE_; + case '&': shift(1); return QmlJSGrammar::T_AND; + case '|': shift(1); return QmlJSGrammar::T_OR; + case '^': shift(1); return QmlJSGrammar::T_XOR; + case '%': shift(1); return QmlJSGrammar::T_REMAINDER; + case '(': shift(1); return QmlJSGrammar::T_LPAREN; + case ')': shift(1); return QmlJSGrammar::T_RPAREN; + case '{': shift(1); return QmlJSGrammar::T_LBRACE; + case '}': shift(1); return QmlJSGrammar::T_RBRACE; + case '[': shift(1); return QmlJSGrammar::T_LBRACKET; + case ']': shift(1); return QmlJSGrammar::T_RBRACKET; + case ';': shift(1); return QmlJSGrammar::T_SEMICOLON; + + default: return -1; + } +} + +ushort Lexer::singleEscape(ushort c) const +{ + switch(c) { + case 'b': + return 0x08; + case 't': + return 0x09; + case 'n': + return 0x0A; + case 'v': + return 0x0B; + case 'f': + return 0x0C; + case 'r': + return 0x0D; + case '"': + return 0x22; + case '\'': + return 0x27; + case '\\': + return 0x5C; + default: + return c; + } +} + +ushort Lexer::convertOctal(ushort c1, ushort c2, + ushort c3) const +{ + return ((c1 - '0') * 64 + (c2 - '0') * 8 + c3 - '0'); +} + +unsigned char Lexer::convertHex(ushort c) +{ + if (c >= '0' && c <= '9') + return (c - '0'); + else if (c >= 'a' && c <= 'f') + return (c - 'a' + 10); + else + return (c - 'A' + 10); +} + +unsigned char Lexer::convertHex(ushort c1, ushort c2) +{ + return ((convertHex(c1) << 4) + convertHex(c2)); +} + +QChar Lexer::convertUnicode(ushort c1, ushort c2, + ushort c3, ushort c4) +{ + return QChar((convertHex(c3) << 4) + convertHex(c4), + (convertHex(c1) << 4) + convertHex(c2)); +} + +void Lexer::record8(ushort c) +{ + Q_ASSERT(c <= 0xff); + + // enlarge buffer if full + if (pos8 >= size8 - 1) { + char *tmp = new char[2 * size8]; + memcpy(tmp, buffer8, size8 * sizeof(char)); + delete [] buffer8; + buffer8 = tmp; + size8 *= 2; + } + + buffer8[pos8++] = (char) c; +} + +void Lexer::record16(QChar c) +{ + // enlarge buffer if full + if (pos16 >= size16 - 1) { + QChar *tmp = new QChar[2 * size16]; + memcpy(tmp, buffer16, size16 * sizeof(QChar)); + delete [] buffer16; + buffer16 = tmp; + size16 *= 2; + } + + buffer16[pos16++] = c; +} + +void Lexer::recordStartPos() +{ + startpos = pos; + startlineno = yylineno; + startcolumn = yycolumn; +} + +bool Lexer::scanRegExp(RegExpBodyPrefix prefix) +{ + pos16 = 0; + bool lastWasEscape = false; + + if (prefix == EqualPrefix) + record16(QLatin1Char('=')); + + while (1) { + if (isLineTerminator() || current == 0) { + errmsg = QLatin1String("Unterminated regular expression literal"); + return false; + } + else if (current != '/' || lastWasEscape == true) + { + record16(current); + lastWasEscape = !lastWasEscape && (current == '\\'); + } + else { + if (driver) + pattern = driver->intern(buffer16, pos16); + else + pattern = 0; + pos16 = 0; + shift(1); + break; + } + shift(1); + } + + flags = 0; + while (isIdentLetter(current)) { + int flag = Ecma::RegExp::flagFromChar(current); + if (flag == 0) { + errmsg = QString::fromLatin1("Invalid regular expression flag '%0'") + .arg(QChar(current)); + return false; + } + flags |= flag; + record16(current); + shift(1); + } + + return true; +} + +void Lexer::syncProhibitAutomaticSemicolon() +{ + if (parenthesesState == BalancedParentheses) { + // we have seen something like "if (foo)", which means we should + // never insert an automatic semicolon at this point, since it would + // then be expanded into an empty statement (ECMA-262 7.9.1) + prohibitAutomaticSemicolon = true; + parenthesesState = IgnoreParentheses; + } else { + prohibitAutomaticSemicolon = false; + } +} + +QT_END_NAMESPACE + + diff --git a/src/declarative/qml/parser/qmljslexer_p.h b/src/declarative/qml/parser/qmljslexer_p.h new file mode 100644 index 0000000..e1ff23e --- /dev/null +++ b/src/declarative/qml/parser/qmljslexer_p.h @@ -0,0 +1,269 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLJSLEXER_P_H +#define QMLJSLEXER_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + + + +QT_BEGIN_NAMESPACE + +namespace QmlJS { + +class Engine; +class NameId; + +class Lexer +{ +public: + Lexer(Engine *eng); + ~Lexer(); + + void setCode(const QString &c, int lineno); + int lex(); + + int currentLineNo() const { return yylineno; } + int currentColumnNo() const { return yycolumn; } + + int tokenOffset() const { return startpos; } + int tokenLength() const { return pos - startpos; } + + int startLineNo() const { return startlineno; } + int startColumnNo() const { return startcolumn; } + + int endLineNo() const { return currentLineNo(); } + int endColumnNo() const + { int col = currentColumnNo(); return (col > 0) ? col - 1 : col; } + + bool prevTerminator() const { return terminator; } + + enum State { Start, + Identifier, + InIdentifier, + InSingleLineComment, + InMultiLineComment, + InNum, + InNum0, + InHex, + InOctal, + InDecimal, + InExponentIndicator, + InExponent, + Hex, + Octal, + Number, + String, + Eof, + InString, + InEscapeSequence, + InHexEscape, + InUnicodeEscape, + Other, + Bad }; + + enum Suffix { + noSuffix, + emSuffix, + exSuffix, + pxSuffix, + cmSuffix, + mmSuffix, + inSuffix, + ptSuffix, + pcSuffix, + degSuffix, + radSuffix, + gradSuffix, + msSuffix, + sSuffix, + hzSuffix, + khzSuffix + }; + + enum Error { + NoError, + IllegalCharacter, + UnclosedStringLiteral, + IllegalEscapeSequence, + IllegalUnicodeEscapeSequence, + UnclosedComment, + IllegalExponentIndicator, + IllegalIdentifier + }; + + enum ParenthesesState { + IgnoreParentheses, + CountParentheses, + BalancedParentheses + }; + + enum RegExpBodyPrefix { + NoPrefix, + EqualPrefix + }; + + bool scanRegExp(RegExpBodyPrefix prefix = NoPrefix); + + NameId *pattern; + int flags; + + State lexerState() const + { return state; } + + QString errorMessage() const + { return errmsg; } + void setErrorMessage(const QString &err) + { errmsg = err; } + void setErrorMessage(const char *err) + { setErrorMessage(QString::fromLatin1(err)); } + + Error error() const + { return err; } + void clearError() + { err = NoError; } + +private: + Engine *driver; + int yylineno; + bool done; + char *buffer8; + QChar *buffer16; + uint size8, size16; + uint pos8, pos16; + bool terminator; + bool restrKeyword; + // encountered delimiter like "'" and "}" on last run + bool delimited; + int stackToken; + + State state; + void setDone(State s); + uint pos; + void shift(uint p); + int lookupKeyword(const char *); + + bool isWhiteSpace() const; + bool isLineTerminator() const; + bool isHexDigit(ushort c) const; + bool isOctalDigit(ushort c) const; + + int matchPunctuator(ushort c1, ushort c2, + ushort c3, ushort c4); + ushort singleEscape(ushort c) const; + ushort convertOctal(ushort c1, ushort c2, + ushort c3) const; +public: + static unsigned char convertHex(ushort c1); + static unsigned char convertHex(ushort c1, ushort c2); + static QChar convertUnicode(ushort c1, ushort c2, + ushort c3, ushort c4); + static bool isIdentLetter(ushort c); + static bool isDecimalDigit(ushort c); + + inline int ival() const { return qsyylval.ival; } + inline double dval() const { return qsyylval.dval; } + inline NameId *ustr() const { return qsyylval.ustr; } + + const QChar *characterBuffer() const { return buffer16; } + int characterCount() const { return pos16; } + +private: + void record8(ushort c); + void record16(QChar c); + void recordStartPos(); + + int findReservedWord(const QChar *buffer, int size) const; + + void syncProhibitAutomaticSemicolon(); + + const QChar *code; + uint length; + int yycolumn; + int startpos; + int startlineno; + int startcolumn; + int bol; // begin of line + + union { + int ival; + double dval; + NameId *ustr; + } qsyylval; + + // current and following unicode characters + ushort current, next1, next2, next3; + + struct keyword { + const char *name; + int token; + }; + + QString errmsg; + Error err; + + bool wantRx; + bool check_reserved; + + ParenthesesState parenthesesState; + int parenthesesCount; + bool prohibitAutomaticSemicolon; +}; + +} // namespace QmlJS + +QT_END_NAMESPACE + + + +#endif diff --git a/src/declarative/qml/parser/qmljsmemorypool_p.h b/src/declarative/qml/parser/qmljsmemorypool_p.h new file mode 100644 index 0000000..d7506be --- /dev/null +++ b/src/declarative/qml/parser/qmljsmemorypool_p.h @@ -0,0 +1,130 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLJSMEMORYPOOL_P_H +#define QMLJSMEMORYPOOL_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace QmlJS { + +class MemoryPool : public QSharedData +{ +public: + enum { maxBlockCount = -1 }; + enum { defaultBlockSize = 1 << 12 }; + + MemoryPool() { + m_blockIndex = maxBlockCount; + m_currentIndex = 0; + m_storage = 0; + m_currentBlock = 0; + m_currentBlockSize = 0; + } + + virtual ~MemoryPool() { + for (int index = 0; index < m_blockIndex + 1; ++index) + qFree(m_storage[index]); + + qFree(m_storage); + } + + char *allocate(int bytes) { + bytes += (8 - bytes) & 7; // ensure multiple of 8 bytes (maintain alignment) + if (m_currentBlock == 0 || m_currentBlockSize < m_currentIndex + bytes) { + ++m_blockIndex; + m_currentBlockSize = defaultBlockSize << m_blockIndex; + + m_storage = reinterpret_cast(qRealloc(m_storage, sizeof(char*) * (1 + m_blockIndex))); + m_currentBlock = m_storage[m_blockIndex] = reinterpret_cast(qMalloc(m_currentBlockSize)); + ::memset(m_currentBlock, 0, m_currentBlockSize); + + m_currentIndex = (8 - quintptr(m_currentBlock)) & 7; // ensure first chunk is 64-bit aligned + Q_ASSERT(m_currentIndex + bytes <= m_currentBlockSize); + } + + char *p = reinterpret_cast + (m_currentBlock + m_currentIndex); + + m_currentIndex += bytes; + + return p; + } + + int bytesAllocated() const { + int bytes = 0; + for (int index = 0; index < m_blockIndex; ++index) + bytes += (defaultBlockSize << index); + bytes += m_currentIndex; + return bytes; + } + +private: + int m_blockIndex; + int m_currentIndex; + char *m_currentBlock; + int m_currentBlockSize; + char **m_storage; + +private: + Q_DISABLE_COPY(MemoryPool) +}; + +} // namespace QmlJS + +QT_END_NAMESPACE + +#endif diff --git a/src/declarative/qml/parser/qmljsnodepool_p.h b/src/declarative/qml/parser/qmljsnodepool_p.h new file mode 100644 index 0000000..1a5b7f6 --- /dev/null +++ b/src/declarative/qml/parser/qmljsnodepool_p.h @@ -0,0 +1,138 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLJSNODEPOOL_P_H +#define QMLJSNODEPOOL_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include +#include + +#include "qmljsmemorypool_p.h" + +QT_BEGIN_NAMESPACE + +namespace QmlJS { + +namespace AST { +class Node; +} // namespace AST + +class Code; +class CompilationUnit; +class Engine; + +template +inline NodeType *makeAstNode(MemoryPool *storage) +{ + NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(); + return node; +} + +template +inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1) +{ + NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1); + return node; +} + +template +inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2) +{ + NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2); + return node; +} + +template +inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2, Arg3 arg3) +{ + NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2, arg3); + return node; +} + +template +inline NodeType *makeAstNode(MemoryPool *storage, Arg1 arg1, Arg2 arg2, Arg3 arg3, Arg4 arg4) +{ + NodeType *node = new (storage->allocate(sizeof(NodeType))) NodeType(arg1, arg2, arg3, arg4); + return node; +} + +class NodePool : public MemoryPool +{ +public: + NodePool(const QString &fileName, Engine *engine); + virtual ~NodePool(); + + Code *createCompiledCode(AST::Node *node, CompilationUnit &compilation); + + inline QString fileName() const { return m_fileName; } + inline Engine *engine() const { return m_engine; } +#ifndef J_SCRIPT_NO_EVENT_NOTIFY + inline qint64 id() const { return m_id; } +#endif + +private: + QHash m_codeCache; + QString m_fileName; + Engine *m_engine; +#ifndef J_SCRIPT_NO_EVENT_NOTIFY + qint64 m_id; +#endif + +private: + Q_DISABLE_COPY(NodePool) +}; + +} // namespace QmlJS + +QT_END_NAMESPACE + +#endif diff --git a/src/declarative/qml/parser/qmljsparser.cpp b/src/declarative/qml/parser/qmljsparser.cpp new file mode 100644 index 0000000..6ecff3d --- /dev/null +++ b/src/declarative/qml/parser/qmljsparser.cpp @@ -0,0 +1,1717 @@ +// This file was generated by qlalr - DO NOT EDIT! + +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include + +#include + +#include "qmljsengine_p.h" +#include "qmljslexer_p.h" +#include "qmljsast_p.h" +#include "qmljsnodepool_p.h" + + + +#include "qmljsparser_p.h" +#include + +// +// This file is automatically generated from qmljs.g. +// Changes will be lost. +// + +using namespace QmlJS; + +QT_BEGIN_NAMESPACE + +void Parser::reallocateStack() +{ + if (! stack_size) + stack_size = 128; + else + stack_size <<= 1; + + sym_stack = reinterpret_cast (qRealloc(sym_stack, stack_size * sizeof(Value))); + state_stack = reinterpret_cast (qRealloc(state_stack, stack_size * sizeof(int))); + location_stack = reinterpret_cast (qRealloc(location_stack, stack_size * sizeof(AST::SourceLocation))); +} + +inline static bool automatic(Engine *driver, int token) +{ + return token == QmlJSGrammar::T_RBRACE + || token == 0 + || driver->lexer()->prevTerminator(); +} + + +Parser::Parser(Engine *engine): + driver(engine), + tos(0), + stack_size(0), + sym_stack(0), + state_stack(0), + location_stack(0), + first_token(0), + last_token(0) +{ +} + +Parser::~Parser() +{ + if (stack_size) { + qFree(sym_stack); + qFree(state_stack); + qFree(location_stack); + } +} + +static inline AST::SourceLocation location(Lexer *lexer) +{ + AST::SourceLocation loc; + loc.offset = lexer->tokenOffset(); + loc.length = lexer->tokenLength(); + loc.startLine = lexer->startLineNo(); + loc.startColumn = lexer->startColumnNo(); + return loc; +} + +AST::UiQualifiedId *Parser::reparseAsQualifiedId(AST::ExpressionNode *expr) +{ + QVarLengthArray nameIds; + QVarLengthArray locations; + + AST::ExpressionNode *it = expr; + while (AST::FieldMemberExpression *m = AST::cast(it)) { + nameIds.append(m->name); + locations.append(m->identifierToken); + it = m->base; + } + + if (AST::IdentifierExpression *idExpr = AST::cast(it)) { + AST::UiQualifiedId *q = makeAstNode(driver->nodePool(), idExpr->name); + q->identifierToken = idExpr->identifierToken; + + AST::UiQualifiedId *currentId = q; + for (int i = nameIds.size() - 1; i != -1; --i) { + currentId = makeAstNode(driver->nodePool(), currentId, nameIds[i]); + currentId->identifierToken = locations[i]; + } + + return currentId->finish(); + } + + return 0; +} + +bool Parser::parse() +{ + Lexer *lexer = driver->lexer(); + bool hadErrors = false; + int yytoken = -1; + int action = 0; + + first_token = last_token = 0; + + tos = -1; + program = 0; + + do { + if (++tos == stack_size) + reallocateStack(); + + state_stack[tos] = action; + + _Lcheck_token: + if (yytoken == -1 && -TERMINAL_COUNT != action_index[action]) { + yyprevlloc = yylloc; + + if (first_token == last_token) { + yytoken = lexer->lex(); + yylval = lexer->dval(); + yylloc = location(lexer); + } else { + yytoken = first_token->token; + yylval = first_token->dval; + yylloc = first_token->loc; + ++first_token; + } + } + + action = t_action(action, yytoken); + if (action > 0) { + if (action != ACCEPT_STATE) { + yytoken = -1; + sym(1).dval = yylval; + loc(1) = yylloc; + } else { + --tos; + return ! hadErrors; + } + } else if (action < 0) { + const int r = -action - 1; + tos -= rhs[r]; + + switch (r) { + +case 0: { + program = makeAstNode (driver->nodePool(), sym(1).UiImportList, + sym(2).UiObjectMemberList->finish()); + sym(1).UiProgram = program; +} break; + +case 2: { + sym(1).Node = sym(1).UiImportList->finish(); +} break; + +case 3: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiImport); +} break; + +case 4: { + sym(1).Node = makeAstNode (driver->nodePool(), + sym(1).UiImportList, sym(2).UiImport); +} break; + +case 6: { + AST::UiImport *node = makeAstNode(driver->nodePool(), sym(2).sval); + node->importToken = loc(1); + node->fileNameToken = loc(2); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; + +case 7: { + sym(1).Node = 0; +} break; + +case 8: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); +} break; + +case 9: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); +} break; + +case 10: { + AST::UiObjectMemberList *node = makeAstNode (driver->nodePool(), + sym(1).UiObjectMemberList, sym(2).UiObjectMember); + sym(1).Node = node; +} break; + +case 11: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).UiObjectMember); +} break; + +case 12: { + AST::UiArrayMemberList *node = makeAstNode (driver->nodePool(), + sym(1).UiArrayMemberList, sym(3).UiObjectMember); + node->commaToken = loc(2); + sym(1).Node = node; +} break; + +case 13: { + AST::UiObjectInitializer *node = makeAstNode (driver->nodePool(), (AST::UiObjectMemberList*)0); + node->lbraceToken = loc(1); + node->rbraceToken = loc(2); + sym(1).Node = node; +} break; + +case 14: { + AST::UiObjectInitializer *node = makeAstNode (driver->nodePool(), sym(2).UiObjectMemberList->finish()); + node->lbraceToken = loc(1); + node->rbraceToken = loc(3); + sym(1).Node = node; +} break; + +case 15: { + AST::UiObjectDefinition *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), + sym(2).UiObjectInitializer); + sym(1).Node = node; +} break; + +case 17: { + AST::UiArrayBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), + sym(4).UiArrayMemberList->finish()); + node->colonToken = loc(2); + node->lbracketToken = loc(3); + node->rbracketToken = loc(5); + sym(1).Node = node; +} break; + +case 18: { + AST::StringLiteral *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->literalToken = loc(1); + sym(1).Node = node; +} break; + +case 20: { + AST::ExpressionStatement *node = makeAstNode (driver->nodePool(), sym(1).Expression); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; + +case 21: { + if (AST::UiQualifiedId *qualifiedId = reparseAsQualifiedId(sym(3).Expression)) { + AST::UiObjectBinding *node = makeAstNode (driver->nodePool(), + sym(1).UiQualifiedId->finish(), qualifiedId, sym(4).UiObjectInitializer); + node->colonToken = loc(2); + sym(1).Node = node; + } else { + sym(1).Node = 0; + + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, loc(2), + QLatin1String("Expected a type name after token `:'"))); + + return false; // ### recover + } +} break; +case 22:case 23:case 24:case 25:case 26:case 27: +{ + AST::UiScriptBinding *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId->finish(), + sym(3).Statement); + node->colonToken = loc(2); + sym(1).Node = node; +} break; + +case 28: + +case 29: { + sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount()); + break; +} + +case 31: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), (NameId *)0, sym(2).sval); + node->type = AST::UiPublicMember::Signal; + node->propertyToken = loc(1); + node->typeToken = loc(2); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; + +case 33: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(3).sval); + node->propertyToken = loc(1); + node->typeToken = loc(2); + node->identifierToken = loc(3); + node->semicolonToken = loc(4); + sym(1).Node = node; +} break; + +case 35: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(4).sval); + node->isDefaultMember = true; + node->defaultToken = loc(1); + node->propertyToken = loc(2); + node->typeToken = loc(3); + node->identifierToken = loc(4); + node->semicolonToken = loc(5); + sym(1).Node = node; +} break; + +case 37: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(3).sval, + sym(5).Expression); + node->propertyToken = loc(1); + node->typeToken = loc(2); + node->identifierToken = loc(3); + node->colonToken = loc(4); + node->semicolonToken = loc(6); + sym(1).Node = node; +} break; + +case 39: { + AST::UiPublicMember *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(4).sval, + sym(6).Expression); + node->isDefaultMember = true; + node->defaultToken = loc(1); + node->propertyToken = loc(2); + node->typeToken = loc(3); + node->identifierToken = loc(4); + node->colonToken = loc(5); + node->semicolonToken = loc(7); + sym(1).Node = node; +} break; + +case 40: { + sym(1).Node = makeAstNode(driver->nodePool(), sym(1).Node); +} break; + +case 41: { + sym(1).Node = makeAstNode(driver->nodePool(), sym(1).Node); +} break; +case 42: +case 43: +{ + AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount())); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; + +case 45: { + QString s = QLatin1String(QmlJSGrammar::spell[T_PROPERTY]); + sym(1).sval = driver->intern(s.constData(), s.length()); + break; +} + +case 46: { + QString s = QLatin1String(QmlJSGrammar::spell[T_SIGNAL]); + sym(1).sval = driver->intern(s.constData(), s.length()); + break; +} + +case 47: { + AST::ThisExpression *node = makeAstNode (driver->nodePool()); + node->thisToken = loc(1); + sym(1).Node = node; +} break; + +case 48: { + AST::IdentifierExpression *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; + +case 49: { + AST::NullExpression *node = makeAstNode (driver->nodePool()); + node->nullToken = loc(1); + sym(1).Node = node; +} break; + +case 50: { + AST::TrueLiteral *node = makeAstNode (driver->nodePool()); + node->trueToken = loc(1); + sym(1).Node = node; +} break; + +case 51: { + AST::FalseLiteral *node = makeAstNode (driver->nodePool()); + node->falseToken = loc(1); + sym(1).Node = node; +} break; + +case 52: { + AST::NumericLiteral *node = makeAstNode (driver->nodePool(), sym(1).dval, lexer->flags); + node->literalToken = loc(1); + sym(1).Node = node; +} break; + +case 53: { + AST::StringLiteral *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->literalToken = loc(1); + sym(1).Node = node; +} break; + +case 54: { + bool rx = lexer->scanRegExp(Lexer::NoPrefix); + if (!rx) { + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage())); + return false; // ### remove me + } + AST::RegExpLiteral *node = makeAstNode (driver->nodePool(), lexer->pattern, lexer->flags); + node->literalToken = loc(1); + sym(1).Node = node; +} break; + +case 55: { + bool rx = lexer->scanRegExp(Lexer::EqualPrefix); + if (!rx) { + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, location(lexer), lexer->errorMessage())); + return false; + } + AST::RegExpLiteral *node = makeAstNode (driver->nodePool(), lexer->pattern, lexer->flags); + node->literalToken = loc(1); + sym(1).Node = node; +} break; + +case 56: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), (AST::Elision *) 0); + node->lbracketToken = loc(1); + node->rbracketToken = loc(2); + sym(1).Node = node; +} break; + +case 57: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).Elision->finish()); + node->lbracketToken = loc(1); + node->rbracketToken = loc(3); + sym(1).Node = node; +} break; + +case 58: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish ()); + node->lbracketToken = loc(1); + node->rbracketToken = loc(3); + sym(1).Node = node; +} break; + +case 59: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish (), + (AST::Elision *) 0); + node->lbracketToken = loc(1); + node->commaToken = loc(3); + node->rbracketToken = loc(4); + sym(1).Node = node; +} break; + +case 60: { + AST::ArrayLiteral *node = makeAstNode (driver->nodePool(), sym(2).ElementList->finish (), + sym(4).Elision->finish()); + node->lbracketToken = loc(1); + node->commaToken = loc(3); + node->rbracketToken = loc(5); + sym(1).Node = node; +} break; + +case 61: { + AST::ObjectLiteral *node = 0; + if (sym(2).Node) + node = makeAstNode (driver->nodePool(), + sym(2).PropertyNameAndValueList->finish ()); + else + node = makeAstNode (driver->nodePool()); + node->lbraceToken = loc(1); + node->lbraceToken = loc(3); + sym(1).Node = node; +} break; + +case 62: { + AST::ObjectLiteral *node = makeAstNode (driver->nodePool(), + sym(2).PropertyNameAndValueList->finish ()); + node->lbraceToken = loc(1); + node->lbraceToken = loc(4); + sym(1).Node = node; +} break; + +case 63: { + AST::NestedExpression *node = makeAstNode(driver->nodePool(), sym(2).Expression); + node->lparenToken = loc(1); + node->rparenToken = loc(3); + sym(1).Node = node; +} break; + +case 64: { + AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; + +case 65: { + AST::UiQualifiedId *node = makeAstNode (driver->nodePool(), sym(1).UiQualifiedId, sym(3).sval); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; + +case 66: { + sym(1).Node = makeAstNode (driver->nodePool(), (AST::Elision *) 0, sym(1).Expression); +} break; + +case 67: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Elision->finish(), sym(2).Expression); +} break; + +case 68: { + AST::ElementList *node = makeAstNode (driver->nodePool(), sym(1).ElementList, + (AST::Elision *) 0, sym(3).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; + +case 69: { + AST::ElementList *node = makeAstNode (driver->nodePool(), sym(1).ElementList, sym(3).Elision->finish(), + sym(4).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; + +case 70: { + AST::Elision *node = makeAstNode (driver->nodePool()); + node->commaToken = loc(1); + sym(1).Node = node; +} break; + +case 71: { + AST::Elision *node = makeAstNode (driver->nodePool(), sym(1).Elision); + node->commaToken = loc(2); + sym(1).Node = node; +} break; + +case 72: { + AST::PropertyNameAndValueList *node = makeAstNode (driver->nodePool(), + sym(1).PropertyName, sym(3).Expression); + node->colonToken = loc(2); + sym(1).Node = node; +} break; + +case 73: { + AST::PropertyNameAndValueList *node = makeAstNode (driver->nodePool(), + sym(1).PropertyNameAndValueList, sym(3).PropertyName, sym(5).Expression); + node->commaToken = loc(2); + node->colonToken = loc(4); + sym(1).Node = node; +} break; + +case 74: { + AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; +case 75: +case 76: { + AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount())); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; + +case 77: { + AST::StringLiteralPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; + +case 78: { + AST::NumericLiteralPropertyName *node = makeAstNode (driver->nodePool(), sym(1).dval); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; + +case 79: { + AST::IdentifierPropertyName *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->propertyNameToken = loc(1); + sym(1).Node = node; +} break; + +case 80: + +case 81: + +case 82: + +case 83: + +case 84: + +case 85: + +case 86: + +case 87: + +case 88: + +case 89: + +case 90: + +case 91: + +case 92: + +case 93: + +case 94: + +case 95: + +case 96: + +case 97: + +case 98: + +case 99: + +case 100: + +case 101: + +case 102: + +case 103: + +case 104: + +case 105: + +case 106: + +case 107: + +case 108: + +case 109: + +case 110: +{ + sym(1).sval = driver->intern(lexer->characterBuffer(), lexer->characterCount()); +} break; + +case 115: { + AST::ArrayMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); + node->lbracketToken = loc(2); + node->rbracketToken = loc(4); + sym(1).Node = node; +} break; + +case 116: { + AST::FieldMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).sval); + node->dotToken = loc(2); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; + +case 117: { + AST::NewMemberExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression, sym(4).ArgumentList); + node->newToken = loc(1); + node->lparenToken = loc(3); + node->rparenToken = loc(5); + sym(1).Node = node; +} break; + +case 119: { + AST::NewExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->newToken = loc(1); + sym(1).Node = node; +} break; + +case 120: { + AST::CallExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; + +case 121: { + AST::CallExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).ArgumentList); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; + +case 122: { + AST::ArrayMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); + node->lbracketToken = loc(2); + node->rbracketToken = loc(4); + sym(1).Node = node; +} break; + +case 123: { + AST::FieldMemberExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).sval); + node->dotToken = loc(2); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; + +case 124: { + sym(1).Node = 0; +} break; + +case 125: { + sym(1).Node = sym(1).ArgumentList->finish(); +} break; + +case 126: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Expression); +} break; + +case 127: { + AST::ArgumentList *node = makeAstNode (driver->nodePool(), sym(1).ArgumentList, sym(3).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; + +case 131: { + AST::PostIncrementExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression); + node->incrementToken = loc(2); + sym(1).Node = node; +} break; + +case 132: { + AST::PostDecrementExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression); + node->decrementToken = loc(2); + sym(1).Node = node; +} break; + +case 134: { + AST::DeleteExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->deleteToken = loc(1); + sym(1).Node = node; +} break; + +case 135: { + AST::VoidExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->voidToken = loc(1); + sym(1).Node = node; +} break; + +case 136: { + AST::TypeOfExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->typeofToken = loc(1); + sym(1).Node = node; +} break; + +case 137: { + AST::PreIncrementExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->incrementToken = loc(1); + sym(1).Node = node; +} break; + +case 138: { + AST::PreDecrementExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->decrementToken = loc(1); + sym(1).Node = node; +} break; + +case 139: { + AST::UnaryPlusExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->plusToken = loc(1); + sym(1).Node = node; +} break; + +case 140: { + AST::UnaryMinusExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->minusToken = loc(1); + sym(1).Node = node; +} break; + +case 141: { + AST::TildeExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->tildeToken = loc(1); + sym(1).Node = node; +} break; + +case 142: { + AST::NotExpression *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->notToken = loc(1); + sym(1).Node = node; +} break; + +case 144: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Mul, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 145: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Div, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 146: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Mod, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 148: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Add, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 149: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Sub, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 151: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::LShift, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 152: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::RShift, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 153: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::URShift, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 155: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Lt, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 156: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Gt, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 157: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Le, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 158: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Ge, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 159: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::InstanceOf, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 160: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::In, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 162: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Lt, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 163: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Gt, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 164: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Le, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 165: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Ge, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 166: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::InstanceOf, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 168: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Equal, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 169: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::NotEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 170: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::StrictEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 171: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::StrictNotEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 173: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Equal, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 174: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::NotEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 175: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::StrictEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 176: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::StrictNotEqual, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 178: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitAnd, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 180: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitAnd, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 182: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitXor, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 184: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitXor, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 186: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitOr, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 188: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::BitOr, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 190: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::And, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 192: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::And, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 194: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Or, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 196: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + QSOperator::Or, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 198: { + AST::ConditionalExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + sym(3).Expression, sym(5).Expression); + node->questionToken = loc(2); + node->colonToken = loc(4); + sym(1).Node = node; +} break; + +case 200: { + AST::ConditionalExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + sym(3).Expression, sym(5).Expression); + node->questionToken = loc(2); + node->colonToken = loc(4); + sym(1).Node = node; +} break; + +case 202: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + sym(2).ival, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 204: { + AST::BinaryExpression *node = makeAstNode (driver->nodePool(), sym(1).Expression, + sym(2).ival, sym(3).Expression); + node->operatorToken = loc(2); + sym(1).Node = node; +} break; + +case 205: { + sym(1).ival = QSOperator::Assign; +} break; + +case 206: { + sym(1).ival = QSOperator::InplaceMul; +} break; + +case 207: { + sym(1).ival = QSOperator::InplaceDiv; +} break; + +case 208: { + sym(1).ival = QSOperator::InplaceMod; +} break; + +case 209: { + sym(1).ival = QSOperator::InplaceAdd; +} break; + +case 210: { + sym(1).ival = QSOperator::InplaceSub; +} break; + +case 211: { + sym(1).ival = QSOperator::InplaceLeftShift; +} break; + +case 212: { + sym(1).ival = QSOperator::InplaceRightShift; +} break; + +case 213: { + sym(1).ival = QSOperator::InplaceURightShift; +} break; + +case 214: { + sym(1).ival = QSOperator::InplaceAnd; +} break; + +case 215: { + sym(1).ival = QSOperator::InplaceXor; +} break; + +case 216: { + sym(1).ival = QSOperator::InplaceOr; +} break; + +case 218: { + AST::Expression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; + +case 219: { + sym(1).Node = 0; +} break; + +case 222: { + AST::Expression *node = makeAstNode (driver->nodePool(), sym(1).Expression, sym(3).Expression); + node->commaToken = loc(2); + sym(1).Node = node; +} break; + +case 223: { + sym(1).Node = 0; +} break; + +case 240: { + AST::Block *node = makeAstNode (driver->nodePool(), sym(2).StatementList); + node->lbraceToken = loc(1); + node->rbraceToken = loc(3); + sym(1).Node = node; +} break; + +case 241: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Statement); +} break; + +case 242: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).StatementList, sym(2).Statement); +} break; + +case 243: { + sym(1).Node = 0; +} break; + +case 244: { + sym(1).Node = sym(1).StatementList->finish (); +} break; + +case 246: { + AST::VariableStatement *node = makeAstNode (driver->nodePool(), + sym(2).VariableDeclarationList->finish (/*readOnly=*/sym(1).ival == T_CONST)); + node->declarationKindToken = loc(1); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; + +case 247: { + sym(1).ival = T_CONST; +} break; + +case 248: { + sym(1).ival = T_VAR; +} break; + +case 249: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclaration); +} break; + +case 250: { + AST::VariableDeclarationList *node = makeAstNode (driver->nodePool(), + sym(1).VariableDeclarationList, sym(3).VariableDeclaration); + node->commaToken = loc(2); + sym(1).Node = node; +} break; + +case 251: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclaration); +} break; + +case 252: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).VariableDeclarationList, sym(3).VariableDeclaration); +} break; + +case 253: { + AST::VariableDeclaration *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(2).Expression); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; + +case 254: { + AST::VariableDeclaration *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(2).Expression); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; + +case 255: { + // ### TODO: AST for initializer + sym(1) = sym(2); +} break; + +case 256: { + sym(1).Node = 0; +} break; + +case 258: { + // ### TODO: AST for initializer + sym(1) = sym(2); +} break; + +case 259: { + sym(1).Node = 0; +} break; + +case 261: { + AST::EmptyStatement *node = makeAstNode (driver->nodePool()); + node->semicolonToken = loc(1); + sym(1).Node = node; +} break; + +case 263: { + AST::ExpressionStatement *node = makeAstNode (driver->nodePool(), sym(1).Expression); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; + +case 264: { + AST::IfStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement, sym(7).Statement); + node->ifToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + node->elseToken = loc(5); + sym(1).Node = node; +} break; + +case 265: { + AST::IfStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); + node->ifToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; + +case 267: { + AST::DoWhileStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(5).Expression); + node->doToken = loc(1); + node->whileToken = loc(3); + node->lparenToken = loc(4); + node->rparenToken = loc(6); + node->semicolonToken = loc(7); + sym(1).Node = node; +} break; + +case 268: { + AST::WhileStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); + node->whileToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; + +case 269: { + AST::ForStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, + sym(5).Expression, sym(7).Expression, sym(9).Statement); + node->forToken = loc(1); + node->lparenToken = loc(2); + node->firstSemicolonToken = loc(4); + node->secondSemicolonToken = loc(6); + node->rparenToken = loc(8); + sym(1).Node = node; +} break; + +case 270: { + AST::LocalForStatement *node = makeAstNode (driver->nodePool(), + sym(4).VariableDeclarationList->finish (/*readOnly=*/false), sym(6).Expression, + sym(8).Expression, sym(10).Statement); + node->forToken = loc(1); + node->lparenToken = loc(2); + node->varToken = loc(3); + node->firstSemicolonToken = loc(5); + node->secondSemicolonToken = loc(7); + node->rparenToken = loc(9); + sym(1).Node = node; +} break; + +case 271: { + AST:: ForEachStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, + sym(5).Expression, sym(7).Statement); + node->forToken = loc(1); + node->lparenToken = loc(2); + node->inToken = loc(4); + node->rparenToken = loc(6); + sym(1).Node = node; +} break; + +case 272: { + AST::LocalForEachStatement *node = makeAstNode (driver->nodePool(), + sym(4).VariableDeclaration, sym(6).Expression, sym(8).Statement); + node->forToken = loc(1); + node->lparenToken = loc(2); + node->varToken = loc(3); + node->inToken = loc(5); + node->rparenToken = loc(7); + sym(1).Node = node; +} break; + +case 274: { + AST::ContinueStatement *node = makeAstNode (driver->nodePool()); + node->continueToken = loc(1); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; + +case 276: { + AST::ContinueStatement *node = makeAstNode (driver->nodePool(), sym(2).sval); + node->continueToken = loc(1); + node->identifierToken = loc(2); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; + +case 278: { + AST::BreakStatement *node = makeAstNode (driver->nodePool()); + node->breakToken = loc(1); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; + +case 280: { + AST::BreakStatement *node = makeAstNode (driver->nodePool(), sym(2).sval); + node->breakToken = loc(1); + node->identifierToken = loc(2); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; + +case 282: { + AST::ReturnStatement *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->returnToken = loc(1); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; + +case 283: { + AST::WithStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).Statement); + node->withToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; + +case 284: { + AST::SwitchStatement *node = makeAstNode (driver->nodePool(), sym(3).Expression, sym(5).CaseBlock); + node->switchToken = loc(1); + node->lparenToken = loc(2); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; + +case 285: { + AST::CaseBlock *node = makeAstNode (driver->nodePool(), sym(2).CaseClauses); + node->lbraceToken = loc(1); + node->rbraceToken = loc(3); + sym(1).Node = node; +} break; + +case 286: { + AST::CaseBlock *node = makeAstNode (driver->nodePool(), sym(2).CaseClauses, sym(3).DefaultClause, sym(4).CaseClauses); + node->lbraceToken = loc(1); + node->rbraceToken = loc(5); + sym(1).Node = node; +} break; + +case 287: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).CaseClause); +} break; + +case 288: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).CaseClauses, sym(2).CaseClause); +} break; + +case 289: { + sym(1).Node = 0; +} break; + +case 290: { + sym(1).Node = sym(1).CaseClauses->finish (); +} break; + +case 291: { + AST::CaseClause *node = makeAstNode (driver->nodePool(), sym(2).Expression, sym(4).StatementList); + node->caseToken = loc(1); + node->colonToken = loc(3); + sym(1).Node = node; +} break; + +case 292: { + AST::DefaultClause *node = makeAstNode (driver->nodePool(), sym(3).StatementList); + node->defaultToken = loc(1); + node->colonToken = loc(2); + sym(1).Node = node; +} break; +case 293: +case 294: { + AST::LabelledStatement *node = makeAstNode (driver->nodePool(), driver->intern(lexer->characterBuffer(), lexer->characterCount()), sym(3).Statement); + node->identifierToken = loc(1); + node->colonToken = loc(2); + sym(1).Node = node; +} break; + +case 295: { + AST::LabelledStatement *node = makeAstNode (driver->nodePool(), sym(1).sval, sym(3).Statement); + node->identifierToken = loc(1); + node->colonToken = loc(2); + sym(1).Node = node; +} break; + +case 297: { + AST::ThrowStatement *node = makeAstNode (driver->nodePool(), sym(2).Expression); + node->throwToken = loc(1); + node->semicolonToken = loc(3); + sym(1).Node = node; +} break; + +case 298: { + AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Catch); + node->tryToken = loc(1); + sym(1).Node = node; +} break; + +case 299: { + AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Finally); + node->tryToken = loc(1); + sym(1).Node = node; +} break; + +case 300: { + AST::TryStatement *node = makeAstNode (driver->nodePool(), sym(2).Statement, sym(3).Catch, sym(4).Finally); + node->tryToken = loc(1); + sym(1).Node = node; +} break; + +case 301: { + AST::Catch *node = makeAstNode (driver->nodePool(), sym(3).sval, sym(5).Block); + node->catchToken = loc(1); + node->lparenToken = loc(2); + node->identifierToken = loc(3); + node->rparenToken = loc(4); + sym(1).Node = node; +} break; + +case 302: { + AST::Finally *node = makeAstNode (driver->nodePool(), sym(2).Block); + node->finallyToken = loc(1); + sym(1).Node = node; +} break; + +case 304: { + AST::DebuggerStatement *node = makeAstNode (driver->nodePool()); + node->debuggerToken = loc(1); + node->semicolonToken = loc(2); + sym(1).Node = node; +} break; + +case 305: { + AST::FunctionDeclaration *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody); + node->functionToken = loc(1); + node->identifierToken = loc(2); + node->lparenToken = loc(3); + node->rparenToken = loc(5); + node->lbraceToken = loc(6); + node->rbraceToken = loc(8); + sym(1).Node = node; +} break; + +case 306: { + AST::FunctionExpression *node = makeAstNode (driver->nodePool(), sym(2).sval, sym(4).FormalParameterList, sym(7).FunctionBody); + node->functionToken = loc(1); + if (sym(2).sval) + node->identifierToken = loc(2); + node->lparenToken = loc(3); + node->rparenToken = loc(5); + node->lbraceToken = loc(6); + node->rbraceToken = loc(8); + sym(1).Node = node; +} break; + +case 307: { + AST::FormalParameterList *node = makeAstNode (driver->nodePool(), sym(1).sval); + node->identifierToken = loc(1); + sym(1).Node = node; +} break; + +case 308: { + AST::FormalParameterList *node = makeAstNode (driver->nodePool(), sym(1).FormalParameterList, sym(3).sval); + node->commaToken = loc(2); + node->identifierToken = loc(3); + sym(1).Node = node; +} break; + +case 309: { + sym(1).Node = 0; +} break; + +case 310: { + sym(1).Node = sym(1).FormalParameterList->finish (); +} break; + +case 311: { + sym(1).Node = 0; +} break; + +case 313: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements->finish ()); +} break; + +case 314: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElement); +} break; + +case 315: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).SourceElements, sym(2).SourceElement); +} break; + +case 316: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).Statement); +} break; + +case 317: { + sym(1).Node = makeAstNode (driver->nodePool(), sym(1).FunctionDeclaration); +} break; + +case 318: { + sym(1).sval = 0; +} break; + +case 320: { + sym(1).Node = 0; +} break; + + } // switch + action = nt_action(state_stack[tos], lhs[r] - TERMINAL_COUNT); + } // if + } while (action != 0); + + if (first_token == last_token) { + const int errorState = state_stack[tos]; + + // automatic insertion of `;' + if (t_action(errorState, T_AUTOMATIC_SEMICOLON) && automatic(driver, yytoken)) { + SavedToken &tk = token_buffer[0]; + tk.token = yytoken; + tk.dval = yylval; + tk.loc = yylloc; + + yylloc = yyprevlloc; + yylloc.offset += yylloc.length; + yylloc.startColumn += yylloc.length; + yylloc.length = 0; + + //const QString msg = QString::fromUtf8("Missing `;'"); + //diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Warning, yylloc, msg)); + + first_token = &token_buffer[0]; + last_token = &token_buffer[1]; + + yytoken = T_SEMICOLON; + yylval = 0; + + action = errorState; + + goto _Lcheck_token; + } + + hadErrors = true; + + token_buffer[0].token = yytoken; + token_buffer[0].dval = yylval; + token_buffer[0].loc = yylloc; + + token_buffer[1].token = yytoken = lexer->lex(); + token_buffer[1].dval = yylval = lexer->dval(); + token_buffer[1].loc = yylloc = location(lexer); + + if (t_action(errorState, yytoken)) { + const QString msg = QString::fromUtf8("Unexpected token `%1'").arg(QLatin1String(spell[token_buffer[0].token])); + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); + + action = errorState; + goto _Lcheck_token; + } + + static int tokens[] = { + T_PLUS, + T_EQ, + + T_COMMA, + T_COLON, + T_SEMICOLON, + + T_RPAREN, T_RBRACKET, T_RBRACE, + + T_NUMERIC_LITERAL, + T_IDENTIFIER, + + T_LPAREN, T_LBRACKET, T_LBRACE, + + EOF_SYMBOL + }; + + for (int *tk = tokens; *tk != EOF_SYMBOL; ++tk) { + int a = t_action(errorState, *tk); + if (a > 0 && t_action(a, yytoken)) { + const QString msg = QString::fromUtf8("Expected token `%1'").arg(QLatin1String(spell[*tk])); + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); + + yytoken = *tk; + yylval = 0; + yylloc = token_buffer[0].loc; + yylloc.length = 0; + + first_token = &token_buffer[0]; + last_token = &token_buffer[2]; + + action = errorState; + goto _Lcheck_token; + } + } + + for (int tk = 1; tk < TERMINAL_COUNT; ++tk) { + if (tk == T_AUTOMATIC_SEMICOLON) + continue; + + int a = t_action(errorState, tk); + if (a > 0 && t_action(a, yytoken)) { + const QString msg = QString::fromUtf8("Expected token `%1'").arg(QLatin1String(spell[tk])); + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); + + yytoken = tk; + yylval = 0; + yylloc = token_buffer[0].loc; + yylloc.length = 0; + + action = errorState; + goto _Lcheck_token; + } + } + + const QString msg = QString::fromUtf8("Syntax error"); + diagnostic_messages.append(DiagnosticMessage(DiagnosticMessage::Error, token_buffer[0].loc, msg)); + } + + return false; +} + +QT_END_NAMESPACE + + diff --git a/src/declarative/qml/parser/qmljsparser_p.h b/src/declarative/qml/parser/qmljsparser_p.h new file mode 100644 index 0000000..cd2c7f5 --- /dev/null +++ b/src/declarative/qml/parser/qmljsparser_p.h @@ -0,0 +1,208 @@ +// This file was generated by qlalr - DO NOT EDIT! + +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +// +// This file is automatically generated from qmljs.g. +// Changes will be lost. +// + +#ifndef QMLJSPARSER_P_H +#define QMLJSPARSER_P_H + +#include "qmljsgrammar_p.h" +#include "qmljsast_p.h" +#include "qmljsengine_p.h" + +#include + +QT_BEGIN_NAMESPACE + +class QString; + +namespace QmlJS { + +class Engine; +class NameId; + +class Parser: protected QmlJSGrammar +{ +public: + union Value { + int ival; + double dval; + NameId *sval; + AST::ArgumentList *ArgumentList; + AST::CaseBlock *CaseBlock; + AST::CaseClause *CaseClause; + AST::CaseClauses *CaseClauses; + AST::Catch *Catch; + AST::DefaultClause *DefaultClause; + AST::ElementList *ElementList; + AST::Elision *Elision; + AST::ExpressionNode *Expression; + AST::Finally *Finally; + AST::FormalParameterList *FormalParameterList; + AST::FunctionBody *FunctionBody; + AST::FunctionDeclaration *FunctionDeclaration; + AST::Node *Node; + AST::PropertyName *PropertyName; + AST::PropertyNameAndValueList *PropertyNameAndValueList; + AST::SourceElement *SourceElement; + AST::SourceElements *SourceElements; + AST::Statement *Statement; + AST::StatementList *StatementList; + AST::Block *Block; + AST::VariableDeclaration *VariableDeclaration; + AST::VariableDeclarationList *VariableDeclarationList; + + AST::UiProgram *UiProgram; + AST::UiImportList *UiImportList; + AST::UiImport *UiImport; + AST::UiPublicMember *UiPublicMember; + AST::UiObjectDefinition *UiObjectDefinition; + AST::UiObjectInitializer *UiObjectInitializer; + AST::UiObjectBinding *UiObjectBinding; + AST::UiScriptBinding *UiScriptBinding; + AST::UiArrayBinding *UiArrayBinding; + AST::UiObjectMember *UiObjectMember; + AST::UiObjectMemberList *UiObjectMemberList; + AST::UiArrayMemberList *UiArrayMemberList; + AST::UiQualifiedId *UiQualifiedId; + }; + +public: + Parser(Engine *engine); + ~Parser(); + + bool parse(); + + AST::UiProgram *ast() + { return program; } + + QList diagnosticMessages() const + { return diagnostic_messages; } + + inline DiagnosticMessage diagnosticMessage() const + { + foreach (const DiagnosticMessage &d, diagnostic_messages) { + if (! d.kind == DiagnosticMessage::Warning) + return d; + } + + return DiagnosticMessage(); + } + + inline QString errorMessage() const + { return diagnosticMessage().message; } + + inline int errorLineNumber() const + { return diagnosticMessage().loc.startLine; } + + inline int errorColumnNumber() const + { return diagnosticMessage().loc.startColumn; } + +protected: + void reallocateStack(); + + inline Value &sym(int index) + { return sym_stack [tos + index - 1]; } + + inline AST::SourceLocation &loc(int index) + { return location_stack [tos + index - 1]; } + + AST::UiQualifiedId *reparseAsQualifiedId(AST::ExpressionNode *expr); + +protected: + Engine *driver; + int tos; + int stack_size; + Value *sym_stack; + int *state_stack; + AST::SourceLocation *location_stack; + + AST::UiProgram *program; + + // error recovery + enum { TOKEN_BUFFER_SIZE = 3 }; + + struct SavedToken { + int token; + double dval; + AST::SourceLocation loc; + }; + + double yylval; + AST::SourceLocation yylloc; + AST::SourceLocation yyprevlloc; + + SavedToken token_buffer[TOKEN_BUFFER_SIZE]; + SavedToken *first_token; + SavedToken *last_token; + + QList diagnostic_messages; +}; + +} // end of namespace QmlJS + + + +#define J_SCRIPT_REGEXPLITERAL_RULE1 54 + +#define J_SCRIPT_REGEXPLITERAL_RULE2 55 + +QT_END_NAMESPACE + + + +#endif // QMLJSPARSER_P_H diff --git a/src/declarative/qml/parser/qmljsprettypretty.cpp b/src/declarative/qml/parser/qmljsprettypretty.cpp new file mode 100644 index 0000000..1045792 --- /dev/null +++ b/src/declarative/qml/parser/qmljsprettypretty.cpp @@ -0,0 +1,1334 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include "qmljsprettypretty_p.h" + + + +#include "qmljsengine_p.h" + + + + +#include "qmljsast_p.h" + +#include +#include +#include + +QT_BEGIN_NAMESPACE + +namespace QmlJS { +QString numberToString(double value); +} + +using namespace QmlJS; + +PrettyPretty::PrettyPretty(QTextStream &o): + out(o), m_indentLevel(0) +{ +} + +PrettyPretty::~PrettyPretty() +{ +} + +void PrettyPretty::acceptAsBlock(AST::Node *node) +{ + out << "{"; + pushIndentLevel(); + newlineAndIndent(); + accept(node); + popIndentLevel(); + newlineAndIndent(); + out << "}"; +} + +int PrettyPretty::operatorPrecedenceLevel(int op) +{ + switch (op) { + case QSOperator::Div: + case QSOperator::Mod: + case QSOperator::Mul: + return 5; + case QSOperator::Add: + case QSOperator::Sub: + return 6; + case QSOperator::LShift: + case QSOperator::RShift: + case QSOperator::URShift: + return 7; + case QSOperator::Ge: + case QSOperator::Gt: + case QSOperator::In: + case QSOperator::InstanceOf: + case QSOperator::Le: + case QSOperator::Lt: + return 8; + case QSOperator::Equal: + case QSOperator::NotEqual: + case QSOperator::StrictEqual: + case QSOperator::StrictNotEqual: + return 9; + case QSOperator::BitAnd: + return 10; + case QSOperator::BitXor: + return 11; + case QSOperator::BitOr: + return 12; + case QSOperator::And: + return 13; + case QSOperator::Or: + return 14; + case QSOperator::InplaceAnd: + case QSOperator::InplaceSub: + case QSOperator::InplaceDiv: + case QSOperator::InplaceAdd: + case QSOperator::InplaceLeftShift: + case QSOperator::InplaceMod: + case QSOperator::InplaceMul: + case QSOperator::InplaceOr: + case QSOperator::InplaceRightShift: + case QSOperator::InplaceURightShift: + case QSOperator::InplaceXor: + case QSOperator::Assign: + return 16; + default: + Q_ASSERT_X(false, "PrettyPretty::operatorPrecedenceLevel()", "bad operator"); + } + return 0; +} + +int PrettyPretty::compareOperatorPrecedence(int op1, int op2) +{ + int prec1 = operatorPrecedenceLevel(op1); + int prec2 = operatorPrecedenceLevel(op2); + if (prec1 == prec2) + return 0; + if (prec1 > prec2) + return -1; + return 1; +} + +QTextStream &PrettyPretty::operator () (AST::Node *node, int level) +{ + int was = indentLevel(level); + accept(node); + indentLevel(was); + return out; +} + +QTextStream &PrettyPretty::newlineAndIndent() +{ + enum { IND = 4 }; + out << endl << QString().fill(QLatin1Char(' '), m_indentLevel * IND); + return out; +} + +void PrettyPretty::accept(AST::Node *node) +{ + AST::Node::acceptChild(node, this); +} + +bool PrettyPretty::visit(AST::ThisExpression *node) +{ + Q_UNUSED(node); + out << "this"; + return true; +} + +void PrettyPretty::endVisit(AST::ThisExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::IdentifierExpression *node) +{ + out << Engine::toString(node->name); + return true; +} + +void PrettyPretty::endVisit(AST::IdentifierExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::NullExpression *node) +{ + Q_UNUSED(node); + out << "null"; + return false; +} + +void PrettyPretty::endVisit(AST::NullExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::TrueLiteral *node) +{ + Q_UNUSED(node); + out << "true"; + return false; +} + +void PrettyPretty::endVisit(AST::TrueLiteral *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::FalseLiteral *node) +{ + Q_UNUSED(node); + out << "false"; + return false; +} + +void PrettyPretty::endVisit(AST::FalseLiteral *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::StringLiteral *node) +{ + QString lit = Engine::toString(node->value); + lit.replace(QLatin1String("\\"), QLatin1String("\\\\")); + out << "\"" << lit << "\""; + return false; +} + +void PrettyPretty::endVisit(AST::StringLiteral *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::NumericLiteral *node) +{ + out << QmlJS::numberToString(node->value); + return true; +} + +void PrettyPretty::endVisit(AST::NumericLiteral *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::RegExpLiteral *node) +{ + out << "/" << Engine::toString(node->pattern) << "/"; + if (node->flags) + out << QmlJS::Ecma::RegExp::flagsToString(node->flags); + + return true; +} + +void PrettyPretty::endVisit(AST::RegExpLiteral *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ArrayLiteral *node) +{ + out << "["; + accept(node->elements); + accept(node->elision); + out << "]"; + return false; +} + +void PrettyPretty::endVisit(AST::ArrayLiteral *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ObjectLiteral *node) +{ + out << "{"; + if (node->properties) { + pushIndentLevel(); + AST::PropertyNameAndValueList *prop; + for (prop = node->properties; prop != 0; prop = prop->next) { + newlineAndIndent(); + accept(prop); + if (prop->next) + out << ","; + } + popIndentLevel(); + newlineAndIndent(); + } + out << "}"; + return false; +} + +void PrettyPretty::endVisit(AST::ObjectLiteral *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ElementList *node) +{ + accept(node->elision); + accept(node->expression); + for (node = node->next; node != 0; node = node->next) { + out << ", "; + accept(node->elision); + accept(node->expression); + } + return false; +} + +void PrettyPretty::endVisit(AST::ElementList *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::Elision *node) +{ + out << ", "; + for (AST::Elision *eit = node->next; eit != 0; eit = eit->next) + out << ", "; + return false; +} + +void PrettyPretty::endVisit(AST::Elision *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::PropertyNameAndValueList *node) +{ + accept(node->name); + out << ": "; + accept(node->value); + return false; +} + +void PrettyPretty::endVisit(AST::PropertyNameAndValueList *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::IdentifierPropertyName *node) +{ + out << Engine::toString(node->id); + return false; +} + +void PrettyPretty::endVisit(AST::IdentifierPropertyName *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::StringLiteralPropertyName *node) +{ + QString lit = Engine::toString(node->id); + lit.replace(QLatin1String("\\"), QLatin1String("\\\\")); + out << lit; + return false; +} + +void PrettyPretty::endVisit(AST::StringLiteralPropertyName *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::NumericLiteralPropertyName *node) +{ + out << node->id; + return false; +} + +void PrettyPretty::endVisit(AST::NumericLiteralPropertyName *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ArrayMemberExpression *node) +{ + accept(node->base); + out << "["; + accept(node->expression); + out << "]"; + return false; +} + +void PrettyPretty::endVisit(AST::ArrayMemberExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::FieldMemberExpression *node) +{ + accept(node->base); + out << "." << Engine::toString(node->name); + return false; +} + +void PrettyPretty::endVisit(AST::FieldMemberExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::NewMemberExpression *node) +{ + out << "new "; + accept(node->base); + out << "("; + accept(node->arguments); + out << ")"; + return false; +} + +void PrettyPretty::endVisit(AST::NewMemberExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::NewExpression *node) +{ + Q_UNUSED(node); + out << "new "; + return true; +} + +void PrettyPretty::endVisit(AST::NewExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::CallExpression *node) +{ + accept(node->base); + out << "("; + accept(node->arguments); + out << ")"; + return false; +} + +void PrettyPretty::endVisit(AST::CallExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ArgumentList *node) +{ + accept(node->expression); + for (node = node->next; node != 0; node = node->next) { + out << ", "; + accept(node->expression); + } + return false; +} + +void PrettyPretty::endVisit(AST::ArgumentList *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::PostIncrementExpression *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::PostIncrementExpression *node) +{ + Q_UNUSED(node); + out << "++"; +} + +bool PrettyPretty::visit(AST::PostDecrementExpression *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::PostDecrementExpression *node) +{ + Q_UNUSED(node); + out << "--"; +} + +bool PrettyPretty::visit(AST::DeleteExpression *node) +{ + Q_UNUSED(node); + out << "delete "; + return true; +} + +void PrettyPretty::endVisit(AST::DeleteExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::VoidExpression *node) +{ + Q_UNUSED(node); + out << "void "; + return true; +} + +void PrettyPretty::endVisit(AST::VoidExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::TypeOfExpression *node) +{ + Q_UNUSED(node); + out << "typeof "; + return true; +} + +void PrettyPretty::endVisit(AST::TypeOfExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::PreIncrementExpression *node) +{ + Q_UNUSED(node); + out << "++"; + return true; +} + +void PrettyPretty::endVisit(AST::PreIncrementExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::PreDecrementExpression *node) +{ + Q_UNUSED(node); + out << "--"; + return true; +} + +void PrettyPretty::endVisit(AST::PreDecrementExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::UnaryPlusExpression *node) +{ + out << "+"; + bool needParens = (node->expression->binaryExpressionCast() != 0); + if (needParens) + out << "("; + accept(node->expression); + if (needParens) + out << ")"; + return false; +} + +void PrettyPretty::endVisit(AST::UnaryPlusExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::UnaryMinusExpression *node) +{ + out << "-"; + bool needParens = (node->expression->binaryExpressionCast() != 0); + if (needParens) + out << "("; + accept(node->expression); + if (needParens) + out << ")"; + return false; +} + +void PrettyPretty::endVisit(AST::UnaryMinusExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::TildeExpression *node) +{ + out << "~"; + bool needParens = (node->expression->binaryExpressionCast() != 0); + if (needParens) + out << "("; + accept(node->expression); + if (needParens) + out << ")"; + return false; +} + +void PrettyPretty::endVisit(AST::TildeExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::NotExpression *node) +{ + out << "!"; + bool needParens = (node->expression->binaryExpressionCast() != 0); + if (needParens) + out << "("; + accept(node->expression); + if (needParens) + out << ")"; + return false; +} + +void PrettyPretty::endVisit(AST::NotExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::BinaryExpression *node) +{ + bool needParens = node->left->binaryExpressionCast() + && (compareOperatorPrecedence(node->left->binaryExpressionCast()->op, node->op) < 0); + if (needParens) + out << "("; + accept(node->left); + if (needParens) + out << ")"; + QString s; + switch (node->op) { + case QSOperator::Add: + s = QLatin1String("+"); break; + case QSOperator::And: + s = QLatin1String("&&"); break; + case QSOperator::InplaceAnd: + s = QLatin1String("&="); break; + case QSOperator::Assign: + s = QLatin1String("="); break; + case QSOperator::BitAnd: + s = QLatin1String("&"); break; + case QSOperator::BitOr: + s = QLatin1String("|"); break; + case QSOperator::BitXor: + s = QLatin1String("^"); break; + case QSOperator::InplaceSub: + s = QLatin1String("-="); break; + case QSOperator::Div: + s = QLatin1String("/"); break; + case QSOperator::InplaceDiv: + s = QLatin1String("/="); break; + case QSOperator::Equal: + s = QLatin1String("=="); break; + case QSOperator::Ge: + s = QLatin1String(">="); break; + case QSOperator::Gt: + s = QLatin1String(">"); break; + case QSOperator::In: + s = QLatin1String("in"); break; + case QSOperator::InplaceAdd: + s = QLatin1String("+="); break; + case QSOperator::InstanceOf: + s = QLatin1String("instanceof"); break; + case QSOperator::Le: + s = QLatin1String("<="); break; + case QSOperator::LShift: + s = QLatin1String("<<"); break; + case QSOperator::InplaceLeftShift: + s = QLatin1String("<<="); break; + case QSOperator::Lt: + s = QLatin1String("<"); break; + case QSOperator::Mod: + s = QLatin1String("%"); break; + case QSOperator::InplaceMod: + s = QLatin1String("%="); break; + case QSOperator::Mul: + s = QLatin1String("*"); break; + case QSOperator::InplaceMul: + s = QLatin1String("*="); break; + case QSOperator::NotEqual: + s = QLatin1String("!="); break; + case QSOperator::Or: + s = QLatin1String("||"); break; + case QSOperator::InplaceOr: + s = QLatin1String("|="); break; + case QSOperator::RShift: + s = QLatin1String(">>"); break; + case QSOperator::InplaceRightShift: + s = QLatin1String(">>="); break; + case QSOperator::StrictEqual: + s = QLatin1String("==="); break; + case QSOperator::StrictNotEqual: + s = QLatin1String("!=="); break; + case QSOperator::Sub: + s = QLatin1String("-"); break; + case QSOperator::URShift: + s = QLatin1String(">>>"); break; + case QSOperator::InplaceURightShift: + s = QLatin1String(">>>="); break; + case QSOperator::InplaceXor: + s = QLatin1String("^="); break; + default: + Q_ASSERT (0); + } + out << " " << s << " "; + needParens = node->right->binaryExpressionCast() + && (compareOperatorPrecedence(node->right->binaryExpressionCast()->op, node->op) <= 0); + if (needParens) + out << "("; + accept(node->right); + if (needParens) + out << ")"; + return false; +} + +void PrettyPretty::endVisit(AST::BinaryExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ConditionalExpression *node) +{ + accept(node->expression); + out << " ? "; + accept(node->ok); + out << " : "; + accept(node->ko); + return false; +} + +void PrettyPretty::endVisit(AST::ConditionalExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::Expression *node) +{ + accept(node->left); + out << ", "; + accept(node->right); + return false; +} + +void PrettyPretty::endVisit(AST::Expression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::Block *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::Block *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::StatementList *node) +{ + accept(node->statement); + for (node = node->next; node != 0; node = node->next) { + newlineAndIndent(); + accept(node->statement); + } + return false; +} + +void PrettyPretty::endVisit(AST::StatementList *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::VariableDeclarationList *node) +{ + AST::VariableDeclarationList *it = node; + + do { + it->declaration->accept(this); + it = it->next; + if (it) + out << ", "; + } while (it); + + return false; +} + +void PrettyPretty::endVisit(AST::VariableDeclarationList *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::VariableStatement *node) +{ + out << "var "; + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::VariableStatement *node) +{ + Q_UNUSED(node); + out << ";"; +} + +bool PrettyPretty::visit(AST::VariableDeclaration *node) +{ + out << Engine::toString(node->name); + if (node->expression) { + out << " = "; + accept(node->expression); + } + return false; +} + +void PrettyPretty::endVisit(AST::VariableDeclaration *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::EmptyStatement *node) +{ + Q_UNUSED(node); + out << ";"; + return true; +} + +void PrettyPretty::endVisit(AST::EmptyStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ExpressionStatement *node) +{ + accept(node->expression); + out << ";"; + return false; +} + +void PrettyPretty::endVisit(AST::ExpressionStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::IfStatement *node) +{ + out << "if ("; + accept(node->expression); + out << ") "; + acceptAsBlock(node->ok); + if (node->ko) { + out << " else "; + acceptAsBlock(node->ko); + } + return false; +} + +void PrettyPretty::endVisit(AST::IfStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::DoWhileStatement *node) +{ + out << "do "; + acceptAsBlock(node->statement); + out << " while ("; + accept(node->expression); + out << ");"; + return false; +} + +void PrettyPretty::endVisit(AST::DoWhileStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::WhileStatement *node) +{ + out << "while ("; + accept(node->expression); + out << ") "; + acceptAsBlock(node->statement); + return false; +} + +void PrettyPretty::endVisit(AST::WhileStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ForStatement *node) +{ + out << "for ("; + accept(node->initialiser); + out << "; "; + accept(node->condition); + out << "; "; + accept(node->expression); + out << ") "; + acceptAsBlock(node->statement); + return false; +} + +void PrettyPretty::endVisit(AST::ForStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::LocalForStatement *node) +{ + out << "for (var "; + accept(node->declarations); + out << "; "; + accept(node->condition); + out << "; "; + accept(node->expression); + out << ") "; + acceptAsBlock(node->statement); + return false; +} + +void PrettyPretty::endVisit(AST::LocalForStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ForEachStatement *node) +{ + out << "for ("; + accept(node->initialiser); + out << " in "; + accept(node->expression); + out << ") "; + acceptAsBlock(node->statement); + return false; +} + +void PrettyPretty::endVisit(AST::ForEachStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::LocalForEachStatement *node) +{ + out << "for (var "; + accept(node->declaration); + out << " in "; + accept(node->expression); + out << ") "; + acceptAsBlock(node->statement); + return false; +} + +void PrettyPretty::endVisit(AST::LocalForEachStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ContinueStatement *node) +{ + out << "continue"; + if (node->label) { + out << " " << Engine::toString(node->label); + } + out << ";"; + return false; +} + +void PrettyPretty::endVisit(AST::ContinueStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::BreakStatement *node) +{ + out << "break"; + if (node->label) { + out << " " << Engine::toString(node->label); + } + out << ";"; + return false; +} + +void PrettyPretty::endVisit(AST::BreakStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ReturnStatement *node) +{ + out << "return"; + if (node->expression) { + out << " "; + accept(node->expression); + } + out << ";"; + return false; +} + +void PrettyPretty::endVisit(AST::ReturnStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::WithStatement *node) +{ + out << "with ("; + accept(node->expression); + out << ") "; + acceptAsBlock(node->statement); + return false; +} + +void PrettyPretty::endVisit(AST::WithStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::SwitchStatement *node) +{ + out << "switch ("; + accept(node->expression); + out << ") "; + acceptAsBlock(node->block); + return false; +} + +void PrettyPretty::endVisit(AST::SwitchStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::CaseBlock *node) +{ + accept(node->clauses); + if (node->defaultClause) { + newlineAndIndent(); + accept(node->defaultClause); + } + if (node->moreClauses) { + newlineAndIndent(); + accept(node->moreClauses); + } + return false; +} + +void PrettyPretty::endVisit(AST::CaseBlock *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::CaseClauses *node) +{ + accept(node->clause); + for (node = node->next; node != 0; node = node->next) { + newlineAndIndent(); + accept(node->clause); + } + return false; +} + +void PrettyPretty::endVisit(AST::CaseClauses *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::CaseClause *node) +{ + out << "case "; + accept(node->expression); + out << ":"; + if (node->statements) { + newlineAndIndent(); + accept(node->statements); + } + return false; +} + +void PrettyPretty::endVisit(AST::CaseClause *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::DefaultClause *node) +{ + Q_UNUSED(node); + out << "default:"; + newlineAndIndent(); + return true; +} + +void PrettyPretty::endVisit(AST::DefaultClause *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::LabelledStatement *node) +{ + out << Engine::toString(node->label) << ": "; + return true; +} + +void PrettyPretty::endVisit(AST::LabelledStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::ThrowStatement *node) +{ + Q_UNUSED(node); + out << "throw "; + accept(node->expression); + out << ";"; + return false; +} + +void PrettyPretty::endVisit(AST::ThrowStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::TryStatement *node) +{ + out << "try "; + acceptAsBlock(node->statement); + if (node->catchExpression) { + out << " catch (" << Engine::toString(node->catchExpression->name) << ") "; + acceptAsBlock(node->catchExpression->statement); + } + if (node->finallyExpression) { + out << " finally "; + acceptAsBlock(node->finallyExpression->statement); + } + return false; +} + +void PrettyPretty::endVisit(AST::TryStatement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::Catch *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::Catch *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::Finally *node) +{ + Q_UNUSED(node); + out << "finally "; + return true; +} + +void PrettyPretty::endVisit(AST::Finally *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::FunctionDeclaration *node) +{ + out << "function"; + + if (node->name) + out << " " << Engine::toString(node->name); + + // the arguments + out << "("; + for (AST::FormalParameterList *it = node->formals; it; it = it->next) { + if (it->name) + out << Engine::toString(it->name); + + if (it->next) + out << ", "; + } + out << ")"; + + // the function body + out << " {"; + + if (node->body) { + pushIndentLevel(); + newlineAndIndent(); + accept(node->body); + popIndentLevel(); + newlineAndIndent(); + } + + out << "}"; + + return false; +} + +void PrettyPretty::endVisit(AST::FunctionDeclaration *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::FunctionExpression *node) +{ + out << "function"; + + if (node->name) + out << " " << Engine::toString(node->name); + + // the arguments + out << "("; + for (AST::FormalParameterList *it = node->formals; it; it = it->next) { + if (it->name) + out << Engine::toString(it->name); + + if (it->next) + out << ", "; + } + out << ")"; + + // the function body + out << " {"; + + if (node->body) { + pushIndentLevel(); + newlineAndIndent(); + accept(node->body); + popIndentLevel(); + newlineAndIndent(); + } + + out << "}"; + + return false; +} + +void PrettyPretty::endVisit(AST::FunctionExpression *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::FormalParameterList *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::FormalParameterList *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::FunctionBody *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::FunctionBody *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::Program *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::Program *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::SourceElements *node) +{ + Q_UNUSED(node); + accept(node->element); + for (node = node->next; node != 0; node = node->next) { + newlineAndIndent(); + accept(node->element); + } + return false; +} + +void PrettyPretty::endVisit(AST::SourceElements *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::FunctionSourceElement *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::FunctionSourceElement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::StatementSourceElement *node) +{ + Q_UNUSED(node); + return true; +} + +void PrettyPretty::endVisit(AST::StatementSourceElement *node) +{ + Q_UNUSED(node); +} + +bool PrettyPretty::visit(AST::DebuggerStatement *node) +{ + Q_UNUSED(node); + out << "debugger"; + return true; +} + +void PrettyPretty::endVisit(AST::DebuggerStatement *node) +{ + Q_UNUSED(node); + out << ";"; +} + +bool PrettyPretty::preVisit(AST::Node *node) +{ + Q_UNUSED(node); + return true; +} + +QT_END_NAMESPACE + + diff --git a/src/declarative/qml/parser/qmljsprettypretty_p.h b/src/declarative/qml/parser/qmljsprettypretty_p.h new file mode 100644 index 0000000..fe82ca2 --- /dev/null +++ b/src/declarative/qml/parser/qmljsprettypretty_p.h @@ -0,0 +1,329 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the QtScript module of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef QMLJSPRETTYPRETTY_P_H +#define QMLJSPRETTYPRETTY_P_H + +// +// W A R N I N G +// ------------- +// +// This file is not part of the Qt API. It exists purely as an +// implementation detail. This header file may change from version to +// version without notice, or even be removed. +// +// We mean it. +// + +#include + +#include "qmljsastvisitor_p.h" + +QT_BEGIN_NAMESPACE + +class QTextStream; + +namespace QmlJS { + +class PrettyPretty: protected AST::Visitor +{ +public: + PrettyPretty(QTextStream &out); + virtual ~PrettyPretty(); + + QTextStream &operator () (AST::Node *node, int level = 0); + +protected: + void accept(AST::Node *node); + + virtual bool preVisit(AST::Node *node); + + virtual bool visit(AST::ThisExpression *node); + virtual void endVisit(AST::ThisExpression *node); + + virtual bool visit(AST::IdentifierExpression *node); + virtual void endVisit(AST::IdentifierExpression *node); + + virtual bool visit(AST::NullExpression *node); + virtual void endVisit(AST::NullExpression *node); + + virtual bool visit(AST::TrueLiteral *node); + virtual void endVisit(AST::TrueLiteral *node); + + virtual bool visit(AST::FalseLiteral *node); + virtual void endVisit(AST::FalseLiteral *node); + + virtual bool visit(AST::StringLiteral *node); + virtual void endVisit(AST::StringLiteral *node); + + virtual bool visit(AST::NumericLiteral *node); + virtual void endVisit(AST::NumericLiteral *node); + + virtual bool visit(AST::RegExpLiteral *node); + virtual void endVisit(AST::RegExpLiteral *node); + + virtual bool visit(AST::ArrayLiteral *node); + virtual void endVisit(AST::ArrayLiteral *node); + + virtual bool visit(AST::ObjectLiteral *node); + virtual void endVisit(AST::ObjectLiteral *node); + + virtual bool visit(AST::ElementList *node); + virtual void endVisit(AST::ElementList *node); + + virtual bool visit(AST::Elision *node); + virtual void endVisit(AST::Elision *node); + + virtual bool visit(AST::PropertyNameAndValueList *node); + virtual void endVisit(AST::PropertyNameAndValueList *node); + + virtual bool visit(AST::IdentifierPropertyName *node); + virtual void endVisit(AST::IdentifierPropertyName *node); + + virtual bool visit(AST::StringLiteralPropertyName *node); + virtual void endVisit(AST::StringLiteralPropertyName *node); + + virtual bool visit(AST::NumericLiteralPropertyName *node); + virtual void endVisit(AST::NumericLiteralPropertyName *node); + + virtual bool visit(AST::ArrayMemberExpression *node); + virtual void endVisit(AST::ArrayMemberExpression *node); + + virtual bool visit(AST::FieldMemberExpression *node); + virtual void endVisit(AST::FieldMemberExpression *node); + + virtual bool visit(AST::NewMemberExpression *node); + virtual void endVisit(AST::NewMemberExpression *node); + + virtual bool visit(AST::NewExpression *node); + virtual void endVisit(AST::NewExpression *node); + + virtual bool visit(AST::CallExpression *node); + virtual void endVisit(AST::CallExpression *node); + + virtual bool visit(AST::ArgumentList *node); + virtual void endVisit(AST::ArgumentList *node); + + virtual bool visit(AST::PostIncrementExpression *node); + virtual void endVisit(AST::PostIncrementExpression *node); + + virtual bool visit(AST::PostDecrementExpression *node); + virtual void endVisit(AST::PostDecrementExpression *node); + + virtual bool visit(AST::DeleteExpression *node); + virtual void endVisit(AST::DeleteExpression *node); + + virtual bool visit(AST::VoidExpression *node); + virtual void endVisit(AST::VoidExpression *node); + + virtual bool visit(AST::TypeOfExpression *node); + virtual void endVisit(AST::TypeOfExpression *node); + + virtual bool visit(AST::PreIncrementExpression *node); + virtual void endVisit(AST::PreIncrementExpression *node); + + virtual bool visit(AST::PreDecrementExpression *node); + virtual void endVisit(AST::PreDecrementExpression *node); + + virtual bool visit(AST::UnaryPlusExpression *node); + virtual void endVisit(AST::UnaryPlusExpression *node); + + virtual bool visit(AST::UnaryMinusExpression *node); + virtual void endVisit(AST::UnaryMinusExpression *node); + + virtual bool visit(AST::TildeExpression *node); + virtual void endVisit(AST::TildeExpression *node); + + virtual bool visit(AST::NotExpression *node); + virtual void endVisit(AST::NotExpression *node); + + virtual bool visit(AST::BinaryExpression *node); + virtual void endVisit(AST::BinaryExpression *node); + + virtual bool visit(AST::ConditionalExpression *node); + virtual void endVisit(AST::ConditionalExpression *node); + + virtual bool visit(AST::Expression *node); + virtual void endVisit(AST::Expression *node); + + virtual bool visit(AST::Block *node); + virtual void endVisit(AST::Block *node); + + virtual bool visit(AST::StatementList *node); + virtual void endVisit(AST::StatementList *node); + + virtual bool visit(AST::VariableStatement *node); + virtual void endVisit(AST::VariableStatement *node); + + virtual bool visit(AST::VariableDeclarationList *node); + virtual void endVisit(AST::VariableDeclarationList *node); + + virtual bool visit(AST::VariableDeclaration *node); + virtual void endVisit(AST::VariableDeclaration *node); + + virtual bool visit(AST::EmptyStatement *node); + virtual void endVisit(AST::EmptyStatement *node); + + virtual bool visit(AST::ExpressionStatement *node); + virtual void endVisit(AST::ExpressionStatement *node); + + virtual bool visit(AST::IfStatement *node); + virtual void endVisit(AST::IfStatement *node); + + virtual bool visit(AST::DoWhileStatement *node); + virtual void endVisit(AST::DoWhileStatement *node); + + virtual bool visit(AST::WhileStatement *node); + virtual void endVisit(AST::WhileStatement *node); + + virtual bool visit(AST::ForStatement *node); + virtual void endVisit(AST::ForStatement *node); + + virtual bool visit(AST::LocalForStatement *node); + virtual void endVisit(AST::LocalForStatement *node); + + virtual bool visit(AST::ForEachStatement *node); + virtual void endVisit(AST::ForEachStatement *node); + + virtual bool visit(AST::LocalForEachStatement *node); + virtual void endVisit(AST::LocalForEachStatement *node); + + virtual bool visit(AST::ContinueStatement *node); + virtual void endVisit(AST::ContinueStatement *node); + + virtual bool visit(AST::BreakStatement *node); + virtual void endVisit(AST::BreakStatement *node); + + virtual bool visit(AST::ReturnStatement *node); + virtual void endVisit(AST::ReturnStatement *node); + + virtual bool visit(AST::WithStatement *node); + virtual void endVisit(AST::WithStatement *node); + + virtual bool visit(AST::SwitchStatement *node); + virtual void endVisit(AST::SwitchStatement *node); + + virtual bool visit(AST::CaseBlock *node); + virtual void endVisit(AST::CaseBlock *node); + + virtual bool visit(AST::CaseClauses *node); + virtual void endVisit(AST::CaseClauses *node); + + virtual bool visit(AST::CaseClause *node); + virtual void endVisit(AST::CaseClause *node); + + virtual bool visit(AST::DefaultClause *node); + virtual void endVisit(AST::DefaultClause *node); + + virtual bool visit(AST::LabelledStatement *node); + virtual void endVisit(AST::LabelledStatement *node); + + virtual bool visit(AST::ThrowStatement *node); + virtual void endVisit(AST::ThrowStatement *node); + + virtual bool visit(AST::TryStatement *node); + virtual void endVisit(AST::TryStatement *node); + + virtual bool visit(AST::Catch *node); + virtual void endVisit(AST::Catch *node); + + virtual bool visit(AST::Finally *node); + virtual void endVisit(AST::Finally *node); + + virtual bool visit(AST::FunctionDeclaration *node); + virtual void endVisit(AST::FunctionDeclaration *node); + + virtual bool visit(AST::FunctionExpression *node); + virtual void endVisit(AST::FunctionExpression *node); + + virtual bool visit(AST::FormalParameterList *node); + virtual void endVisit(AST::FormalParameterList *node); + + virtual bool visit(AST::FunctionBody *node); + virtual void endVisit(AST::FunctionBody *node); + + virtual bool visit(AST::Program *node); + virtual void endVisit(AST::Program *node); + + virtual bool visit(AST::SourceElements *node); + virtual void endVisit(AST::SourceElements *node); + + virtual bool visit(AST::FunctionSourceElement *node); + virtual void endVisit(AST::FunctionSourceElement *node); + + virtual bool visit(AST::StatementSourceElement *node); + virtual void endVisit(AST::StatementSourceElement *node); + + virtual bool visit(AST::DebuggerStatement *node); + virtual void endVisit(AST::DebuggerStatement *node); + + int indentLevel(int level) + { + int was = m_indentLevel; + m_indentLevel = level; + return was; + } + + void pushIndentLevel() + { ++m_indentLevel; } + + void popIndentLevel() + { --m_indentLevel; } + + QTextStream &newlineAndIndent(); + + void acceptAsBlock(AST::Node *node); + + static int operatorPrecedenceLevel(int op); + static int compareOperatorPrecedence(int op1, int op2); + +private: + QTextStream &out; + int m_indentLevel; + + Q_DISABLE_COPY(PrettyPretty) +}; + +} // namespace QmlJS + +QT_END_NAMESPACE + +#endif diff --git a/src/declarative/qml/qmlbasicscript.cpp b/src/declarative/qml/qmlbasicscript.cpp index d8e65bf..dd6766e 100644 --- a/src/declarative/qml/qmlbasicscript.cpp +++ b/src/declarative/qml/qmlbasicscript.cpp @@ -17,12 +17,12 @@ #include #include #include -#include -#include +#include +#include QT_BEGIN_NAMESPACE -using namespace JavaScript; +using namespace QmlJS; struct ScriptInstruction { enum { @@ -270,16 +270,16 @@ struct QmlBasicScriptCompiler QmlParser::Object *component; QHash > ids; - bool compile(JavaScript::AST::Node *); + bool compile(QmlJS::AST::Node *); - bool compileExpression(JavaScript::AST::Node *); + bool compileExpression(QmlJS::AST::Node *); - bool tryConstant(JavaScript::AST::Node *); - bool parseConstant(JavaScript::AST::Node *); - bool tryName(JavaScript::AST::Node *); - bool parseName(JavaScript::AST::Node *, QmlParser::Object ** = 0); - bool tryBinaryExpression(JavaScript::AST::Node *); - bool compileBinaryExpression(JavaScript::AST::Node *); + bool tryConstant(QmlJS::AST::Node *); + bool parseConstant(QmlJS::AST::Node *); + bool tryName(QmlJS::AST::Node *); + bool parseName(QmlJS::AST::Node *, QmlParser::Object ** = 0); + bool tryBinaryExpression(QmlJS::AST::Node *); + bool compileBinaryExpression(QmlJS::AST::Node *); QByteArray data; QList bytecode; @@ -288,10 +288,10 @@ struct QmlBasicScriptCompiler /*! \internal \class QmlBasicScript - \brief The QmlBasicScript class provides a fast implementation of a limited subset of JavaScript bindings. + \brief The QmlBasicScript class provides a fast implementation of a limited subset of QmlJS bindings. QmlBasicScript instances are used to accelerate binding. Instead of using - the slower, fully fledged JavaScript engine, many simple bindings can be + the slower, fully fledged QmlJS engine, many simple bindings can be evaluated using the QmlBasicScript engine. To see if the QmlBasicScript engine can handle a binding, call compile() @@ -495,12 +495,12 @@ bool QmlBasicScript::compile(const Expression &expression) return d != 0; } -bool QmlBasicScriptCompiler::compile(JavaScript::AST::Node *node) +bool QmlBasicScriptCompiler::compile(QmlJS::AST::Node *node) { return compileExpression(node); } -bool QmlBasicScriptCompiler::tryConstant(JavaScript::AST::Node *node) +bool QmlBasicScriptCompiler::tryConstant(QmlJS::AST::Node *node) { if (node->kind == AST::Node::Kind_TrueLiteral || node->kind == AST::Node::Kind_FalseLiteral) @@ -516,7 +516,7 @@ bool QmlBasicScriptCompiler::tryConstant(JavaScript::AST::Node *node) return false; } -bool QmlBasicScriptCompiler::parseConstant(JavaScript::AST::Node *node) +bool QmlBasicScriptCompiler::parseConstant(QmlJS::AST::Node *node) { ScriptInstruction instr; @@ -534,7 +534,7 @@ bool QmlBasicScriptCompiler::parseConstant(JavaScript::AST::Node *node) return true; } -bool QmlBasicScriptCompiler::tryName(JavaScript::AST::Node *node) +bool QmlBasicScriptCompiler::tryName(QmlJS::AST::Node *node) { return node->kind == AST::Node::Kind_IdentifierExpression || node->kind == AST::Node::Kind_FieldMemberExpression; @@ -629,7 +629,7 @@ bool QmlBasicScriptCompiler::parseName(AST::Node *node, return true; } -bool QmlBasicScriptCompiler::compileExpression(JavaScript::AST::Node *node) +bool QmlBasicScriptCompiler::compileExpression(QmlJS::AST::Node *node) { if (tryBinaryExpression(node)) return compileBinaryExpression(node); diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index d29ac1f..3123254 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -62,7 +62,7 @@ #include "private/qmlcustomparser_p_p.h" #include #include -#include "parser/javascriptast_p.h" +#include "parser/qmljsast_p.h" #include "qmlscriptparser_p.h" @@ -1484,7 +1484,7 @@ bool QmlCompiler::compileBinding(QmlParser::Value *value, //////////////////////////////////////////////////////////////////////////////// // AST Dump //////////////////////////////////////////////////////////////////////////////// -class Dump: protected JavaScript::AST::Visitor +class Dump: protected QmlJS::AST::Visitor { std::ostream &out; int depth; @@ -1494,11 +1494,11 @@ public: : out(out), depth(-1) { } - void operator()(JavaScript::AST::Node *node) - { JavaScript::AST::Node::acceptChild(node, this); } + void operator()(QmlJS::AST::Node *node) + { QmlJS::AST::Node::acceptChild(node, this); } protected: - virtual bool preVisit(JavaScript::AST::Node *node) + virtual bool preVisit(QmlJS::AST::Node *node) { const char *name = typeid(*node).name(); #ifdef Q_CC_GNU @@ -1508,7 +1508,7 @@ protected: return true; } - virtual void postVisit(JavaScript::AST::Node *) + virtual void postVisit(QmlJS::AST::Node *) { --depth; } diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index 66781ce..2c1d324 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -823,7 +823,7 @@ QScriptValue QmlEngine::qmlScriptObject(QObject* object, QmlEngine* engine) This function takes the URL of a QML file as its only argument. It returns a component object which can be used to create and load that QML file. - Example JavaScript is below, remember that QML files that might be loaded + Example QmlJS is below, remember that QML files that might be loaded over the network cannot be expected to be ready immediately. \code var component; diff --git a/src/declarative/qml/qmlparser.cpp b/src/declarative/qml/qmlparser.cpp index fadfbb1..5ad4a6e 100644 --- a/src/declarative/qml/qmlparser.cpp +++ b/src/declarative/qml/qmlparser.cpp @@ -290,7 +290,7 @@ QmlParser::Variant::Variant(const QString &v) { } -QmlParser::Variant::Variant(const QString &v, JavaScript::AST::Node *n) +QmlParser::Variant::Variant(const QString &v, QmlJS::AST::Node *n) : t(Script), n(n), s(v) { } @@ -342,7 +342,7 @@ QString QmlParser::Variant::asScript() const } } -JavaScript::AST::Node *QmlParser::Variant::asAST() const +QmlJS::AST::Node *QmlParser::Variant::asAST() const { if (type() == Script) return n; diff --git a/src/declarative/qml/qmlparser_p.h b/src/declarative/qml/qmlparser_p.h index 1481391..a38ce69 100644 --- a/src/declarative/qml/qmlparser_p.h +++ b/src/declarative/qml/qmlparser_p.h @@ -55,7 +55,7 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) -namespace JavaScript { namespace AST { class Node; } } +namespace QmlJS { namespace AST { class Node; } } /* XXX @@ -178,7 +178,7 @@ namespace QmlParser Variant(bool); Variant(double, const QString &asWritten=QString()); Variant(const QString &); - Variant(const QString &, JavaScript::AST::Node *); + Variant(const QString &, QmlJS::AST::Node *); Variant &operator=(const Variant &); Type type() const; @@ -192,14 +192,14 @@ namespace QmlParser QString asString() const; double asNumber() const; QString asScript() const; - JavaScript::AST::Node *asAST() const; + QmlJS::AST::Node *asAST() const; private: Type t; union { bool b; double d; - JavaScript::AST::Node *n; + QmlJS::AST::Node *n; }; QString s; }; diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index ee2981e..6c2e3e0 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -42,12 +42,12 @@ #include "qmlscriptparser_p.h" #include "qmlparser_p.h" -#include "parser/javascriptengine_p.h" -#include "parser/javascriptparser_p.h" -#include "parser/javascriptlexer_p.h" -#include "parser/javascriptnodepool_p.h" -#include "parser/javascriptastvisitor_p.h" -#include "parser/javascriptast_p.h" +#include "parser/qmljsengine_p.h" +#include "parser/qmljsparser_p.h" +#include "parser/qmljslexer_p.h" +#include "parser/qmljsnodepool_p.h" +#include "parser/qmljsastvisitor_p.h" +#include "parser/qmljsast_p.h" #include "rewriter/textwriter_p.h" @@ -59,7 +59,7 @@ QT_BEGIN_NAMESPACE -using namespace JavaScript; +using namespace QmlJS; using namespace QmlParser; namespace { @@ -715,7 +715,7 @@ bool ProcessAST::visit(AST::UiSourceElement *node) obj->dynamicSlots << slot; } else { QmlError error; - error.setDescription(QCoreApplication::translate("QmlParser","JavaScript declaration outside Script element")); + error.setDescription(QCoreApplication::translate("QmlParser","QmlJS declaration outside Script element")); error.setLine(node->firstSourceLocation().startLine); error.setColumn(node->firstSourceLocation().startColumn); _parser->_errors << error; diff --git a/src/declarative/qml/rewriter/rewriter.cpp b/src/declarative/qml/rewriter/rewriter.cpp index fce4fdf..2ce927c 100644 --- a/src/declarative/qml/rewriter/rewriter.cpp +++ b/src/declarative/qml/rewriter/rewriter.cpp @@ -40,11 +40,11 @@ ****************************************************************************/ #include "rewriter_p.h" -#include "javascriptast_p.h" +#include "qmljsast_p.h" QT_BEGIN_NAMESPACE -using namespace JavaScript; +using namespace QmlJS; void Rewriter::replace(const AST::SourceLocation &loc, const QString &text) { replace(loc.offset, loc.length, text); } @@ -76,8 +76,8 @@ QString Rewriter::textAt(const AST::SourceLocation &loc) const QString Rewriter::textAt(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc) const { return _code.mid(firstLoc.offset, lastLoc.offset + lastLoc.length - firstLoc.offset); } -void Rewriter::accept(JavaScript::AST::Node *node) -{ JavaScript::AST::Node::acceptChild(node, this); } +void Rewriter::accept(QmlJS::AST::Node *node) +{ QmlJS::AST::Node::acceptChild(node, this); } void Rewriter::moveTextBefore(const AST::SourceLocation &firstLoc, const AST::SourceLocation &lastLoc, diff --git a/src/declarative/qml/rewriter/rewriter_p.h b/src/declarative/qml/rewriter/rewriter_p.h index 02b4ee4..fcb9ca5 100644 --- a/src/declarative/qml/rewriter/rewriter_p.h +++ b/src/declarative/qml/rewriter/rewriter_p.h @@ -46,12 +46,12 @@ #include #include "textwriter_p.h" -#include "javascriptastvisitor_p.h" +#include "qmljsastvisitor_p.h" QT_BEGIN_HEADER QT_BEGIN_NAMESPACE -namespace JavaScript { +namespace QmlJS { //////////////////////////////////////////////////////////////////////////////// // Replacement @@ -143,7 +143,7 @@ private: QList _replacementList; }; -} // end of namespace JavaScript +} // end of namespace QmlJS QT_END_NAMESPACE QT_END_HEADER diff --git a/src/declarative/qml/rewriter/textwriter.cpp b/src/declarative/qml/rewriter/textwriter.cpp index 21122ff..fbbdb2bbab 100644 --- a/src/declarative/qml/rewriter/textwriter.cpp +++ b/src/declarative/qml/rewriter/textwriter.cpp @@ -43,7 +43,7 @@ QT_BEGIN_NAMESPACE -using namespace JavaScript; +using namespace QmlJS; TextWriter::TextWriter() :string(0), cursor(0) diff --git a/src/declarative/qml/rewriter/textwriter_p.h b/src/declarative/qml/rewriter/textwriter_p.h index 57800bf..3041e04 100644 --- a/src/declarative/qml/rewriter/textwriter_p.h +++ b/src/declarative/qml/rewriter/textwriter_p.h @@ -49,7 +49,7 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE -namespace JavaScript { +namespace QmlJS { class TextWriter { @@ -91,7 +91,7 @@ public: }; -} // end of namespace JavaScript +} // end of namespace QmlJS QT_END_NAMESPACE QT_END_HEADER diff --git a/tools/linguist/lupdate/qml.cpp b/tools/linguist/lupdate/qml.cpp index 78a9afd..f33eae3 100644 --- a/tools/linguist/lupdate/qml.cpp +++ b/tools/linguist/lupdate/qml.cpp @@ -49,12 +49,12 @@ QT_BEGIN_NAMESPACE -#include "parser/javascriptengine_p.h" -#include "parser/javascriptparser_p.h" -#include "parser/javascriptlexer_p.h" -#include "parser/javascriptnodepool_p.h" -#include "parser/javascriptastvisitor_p.h" -#include "parser/javascriptast_p.h" +#include "parser/qmljsengine_p.h" +#include "parser/qmljsparser_p.h" +#include "parser/qmljslexer_p.h" +#include "parser/qmljsnodepool_p.h" +#include "parser/qmljsastvisitor_p.h" +#include "parser/qmljsast_p.h" #include #include @@ -65,7 +65,7 @@ QT_BEGIN_NAMESPACE #include #include -using namespace JavaScript; +using namespace QmlJS; class FindTrCalls: protected AST::Visitor { -- cgit v0.12 From f10791eb1c45b090f60a2c2ecca3cc5fd237278e Mon Sep 17 00:00:00 2001 From: Erik Verbruggen Date: Thu, 11 Jun 2009 11:30:37 +0200 Subject: Getting kinetic compiling again on MacOS. --- src/gui/painting/qpaintengineex.cpp | 83 ++----------------------------------- src/gui/painting/qpaintengineex_p.h | 34 +++++++-------- src/gui/painting/qpainter.cpp | 71 +++++++++++++++++-------------- src/gui/painting/qpainter.h | 1 - src/gui/painting/qpainter_p.h | 6 +-- 5 files changed, 61 insertions(+), 134 deletions(-) diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index d2671c8..8eaad60 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -105,7 +105,7 @@ QDebug Q_GUI_EXPORT &operator<<(QDebug &s, const QVectorPath &path) vectorPathBounds.x2 - vectorPathBounds.x1, vectorPathBounds.y2 - vectorPathBounds.y1); s << "QVectorPath(size:" << path.elementCount() << " hints:" << hex << path.hints() - << rf << ')'; + << rf << ")"; return s; } #endif @@ -138,75 +138,6 @@ QPaintEngineExPrivate::~QPaintEngineExPrivate() } -void QPaintEngineExPrivate::replayClipOperations() -{ - Q_Q(QPaintEngineEx); - - QPainter *p = q->painter(); - if (!p || !p->d_ptr) - return; - - QPainterPrivate *pp = p->d_ptr; - QList clipInfo = pp->state->clipInfo; - - QTransform transform = q->state()->matrix; - - const QTransform &redirection = q->state()->redirectionMatrix; - - for (int i = 0; i < clipInfo.size(); ++i) { - const QPainterClipInfo &info = clipInfo.at(i); - - QTransform combined = info.matrix * redirection; - - if (combined != q->state()->matrix) { - q->state()->matrix = combined; - q->transformChanged(); - } - - switch (info.clipType) { - case QPainterClipInfo::RegionClip: - q->clip(info.region, info.operation); - break; - case QPainterClipInfo::PathClip: - q->clip(info.path, info.operation); - break; - case QPainterClipInfo::RectClip: - q->clip(info.rect, info.operation); - break; - case QPainterClipInfo::RectFClip: { - qreal right = info.rectf.x() + info.rectf.width(); - qreal bottom = info.rectf.y() + info.rectf.height(); - qreal pts[] = { info.rectf.x(), info.rectf.y(), - right, info.rectf.y(), - right, bottom, - info.rectf.x(), bottom }; - QVectorPath vp(pts, 4, 0, QVectorPath::RectangleHint); - q->clip(vp, info.operation); - break; - } - } - } - - if (transform != q->state()->matrix) { - q->state()->matrix = transform; - q->transformChanged(); - } -} - - -bool QPaintEngineExPrivate::hasClipOperations() const -{ - Q_Q(const QPaintEngineEx); - - QPainter *p = q->painter(); - if (!p || !p->d_ptr) - return false; - - QPainterPrivate *pp = p->d_ptr; - QList clipInfo = pp->state->clipInfo; - - return !clipInfo.isEmpty(); -} /******************************************************************************* * @@ -313,18 +244,13 @@ static void qpaintengineex_cubicTo(qreal c1x, qreal c1y, qreal c2x, qreal c2y, q ((StrokeHandler *) data)->types.add(QPainterPath::CurveToDataElement); } -QPaintEngineEx::QPaintEngineEx() - : QPaintEngine(*new QPaintEngineExPrivate, AllFeatures) -{ - extended = true; -} - QPaintEngineEx::QPaintEngineEx(QPaintEngineExPrivate &data) : QPaintEngine(data, AllFeatures) { extended = true; } + QPainterState *QPaintEngineEx::createState(QPainterState *orig) const { if (!orig) @@ -557,9 +483,6 @@ void QPaintEngineEx::clip(const QRect &r, Qt::ClipOperation op) void QPaintEngineEx::clip(const QRegion ®ion, Qt::ClipOperation op) { - if (region.numRects() == 1) - clip(region.boundingRect(), op); - QVector rects = region.rects(); if (rects.size() <= 32) { qreal pts[2*32*4]; @@ -855,7 +778,7 @@ void QPaintEngineEx::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, con { QBrush brush(state()->pen.color(), pixmap); QTransform xform; - xform.translate(r.x() - s.x(), r.y() - s.y()); + xform.translate(-s.x(), -s.y()); brush.setTransform(xform); qreal pts[] = { r.x(), r.y(), diff --git a/src/gui/painting/qpaintengineex_p.h b/src/gui/painting/qpaintengineex_p.h index 3f64260..593726c 100644 --- a/src/gui/painting/qpaintengineex_p.h +++ b/src/gui/painting/qpaintengineex_p.h @@ -139,13 +139,27 @@ public: QDebug Q_GUI_EXPORT &operator<<(QDebug &, const QVectorPath &path); #endif +class Q_GUI_EXPORT QPaintEngineExPrivate : public QPaintEnginePrivate +{ +public: + QPaintEngineExPrivate(); + ~QPaintEngineExPrivate(); + + QStroker stroker; + QDashStroker dasher; + StrokeHandler *strokeHandler; + QStrokerOps *activeStroker; + QPen strokerPen; +}; + class QPixmapFilter; class Q_GUI_EXPORT QPaintEngineEx : public QPaintEngine { Q_DECLARE_PRIVATE(QPaintEngineEx) public: - QPaintEngineEx(); + inline QPaintEngineEx() + : QPaintEngine(*new QPaintEngineExPrivate, AllFeatures) { extended = true; } virtual QPainterState *createState(QPainterState *orig) const; @@ -202,30 +216,12 @@ public: inline QPainterState *state() { return static_cast(QPaintEngine::state); } inline const QPainterState *state() const { return static_cast(QPaintEngine::state); } - virtual void sync() {} - virtual QPixmapFilter *createPixmapFilter(int /*type*/) const { return 0; } protected: QPaintEngineEx(QPaintEngineExPrivate &data); }; -class Q_GUI_EXPORT QPaintEngineExPrivate : public QPaintEnginePrivate -{ - Q_DECLARE_PUBLIC(QPaintEngineEx) -public: - QPaintEngineExPrivate(); - ~QPaintEngineExPrivate(); - - void replayClipOperations(); - bool hasClipOperations() const; - - QStroker stroker; - QDashStroker dasher; - StrokeHandler *strokeHandler; - QStrokerOps *activeStroker; - QPen strokerPen; -}; inline uint QVectorPath::polygonFlags(QPaintEngine::PolygonDrawMode mode) { switch (mode) { diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index 0ece498..cc48d24 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -281,14 +281,10 @@ bool QPainterPrivate::attachPainterPrivate(QPainter *q, QPaintDevice *pdev) q->d_ptr->state->wh = q->d_ptr->state->vh = widget->height(); // Update matrix. - if (q->d_ptr->state->WxF) { - q->d_ptr->state->redirectionMatrix *= q->d_ptr->state->worldMatrix; - q->d_ptr->state->redirectionMatrix.translate(-offset.x(), -offset.y()); - q->d_ptr->state->worldMatrix = QTransform(); - q->d_ptr->state->WxF = false; - } else { - q->d_ptr->state->redirectionMatrix = QTransform::fromTranslate(-offset.x(), -offset.y()); - } + if (q->d_ptr->state->WxF) + q->d_ptr->state->worldMatrix.translate(-offset.x(), -offset.y()); + else + q->d_ptr->state->redirection_offset = offset; q->d_ptr->updateMatrix(); QPaintEnginePrivate *enginePrivate = q->d_ptr->engine->d_func(); @@ -414,7 +410,7 @@ void QPainterPrivate::draw_helper(const QPainterPath &originalPath, DrawOperatio bool old_txinv = txinv; QTransform old_invMatrix = invMatrix; txinv = true; - invMatrix = state->redirectionMatrix; + invMatrix = QTransform().translate(-state->redirection_offset.x(), -state->redirection_offset.y()); QPainterPath clipPath = q->clipPath(); QRectF r = clipPath.boundingRect().intersected(absPathRect); absPathRect = r.toAlignedRect(); @@ -638,7 +634,20 @@ void QPainterPrivate::updateMatrix() state->matrix *= viewTransform(); txinv = false; // no inverted matrix - state->matrix *= state->redirectionMatrix; + if (!state->redirection_offset.isNull()) { + // We want to translate in dev space so we do the adding of the redirection + // offset manually. + if (state->matrix.isAffine()) { + state->matrix = QTransform(state->matrix.m11(), state->matrix.m12(), + state->matrix.m21(), state->matrix.m22(), + state->matrix.dx()-state->redirection_offset.x(), + state->matrix.dy()-state->redirection_offset.y()); + } else { + QTransform temp; + temp.translate(-state->redirection_offset.x(), -state->redirection_offset.y()); + state->matrix *= temp; + } + } if (extended) extended->transformChanged(); else @@ -1563,8 +1572,10 @@ void QPainter::restore() // replay the list of clip states, for (int i=0; istate->clipInfo.size(); ++i) { const QPainterClipInfo &info = d->state->clipInfo.at(i); - tmp->matrix = info.matrix; - tmp->matrix *= d->state->redirectionMatrix; + tmp->matrix.setMatrix(info.matrix.m11(), info.matrix.m12(), info.matrix.m13(), + info.matrix.m21(), info.matrix.m22(), info.matrix.m23(), + info.matrix.dx() - d->state->redirection_offset.x(), + info.matrix.dy() - d->state->redirection_offset.y(), info.matrix.m33()); tmp->clipOperation = info.operation; if (info.clipType == QPainterClipInfo::RectClip) { tmp->dirtyFlags = QPaintEngine::DirtyClipRegion | QPaintEngine::DirtyTransform; @@ -1678,7 +1689,7 @@ bool QPainter::begin(QPaintDevice *pd) d->state->painter = this; d->states.push_back(d->state); - d->state->redirectionMatrix.translate(-redirectionOffset.x(), -redirectionOffset.y()); + d->state->redirection_offset = redirectionOffset; d->state->brushOrigin = QPointF(); if (!d->engine) { @@ -1712,8 +1723,7 @@ bool QPainter::begin(QPaintDevice *pd) // Adjust offset for alien widgets painting outside the paint event. if (!inPaintEvent && paintOutsidePaintEvent && !widget->internalWinId() && widget->testAttribute(Qt::WA_WState_Created)) { - const QPoint offset = widget->mapTo(widget->nativeParentWidget(), QPoint()); - d->state->redirectionMatrix.translate(offset.x(), offset.y()); + d->state->redirection_offset -= widget->mapTo(widget->nativeParentWidget(), QPoint()); } break; } @@ -1795,12 +1805,11 @@ bool QPainter::begin(QPaintDevice *pd) d->state->wh = d->state->vh = pd->metric(QPaintDevice::PdmHeight); } - const QPoint coordinateOffset = d->engine->coordinateOffset(); - d->state->redirectionMatrix.translate(-coordinateOffset.x(), -coordinateOffset.y()); + d->state->redirection_offset += d->engine->coordinateOffset(); Q_ASSERT(d->engine->isActive()); - if (!d->state->redirectionMatrix.isIdentity()) + if (!d->state->redirection_offset.isNull()) d->updateMatrix(); Q_ASSERT(d->engine->isActive()); @@ -6073,22 +6082,22 @@ void QPainter::drawTextItem(const QPointF &p, const QTextItem &_ti) const QTransform &m = d->state->matrix; if (d->state->matrix.type() < QTransform::TxShear) { bool isPlain90DegreeRotation = - (qFuzzyIsNull(m.m11()) - && qFuzzyIsNull(m.m12() - qreal(1)) - && qFuzzyIsNull(m.m21() + qreal(1)) - && qFuzzyIsNull(m.m22()) + (qFuzzyCompare(m.m11() + 1, qreal(1)) + && qFuzzyCompare(m.m12(), qreal(1)) + && qFuzzyCompare(m.m21(), qreal(-1)) + && qFuzzyCompare(m.m22() + 1, qreal(1)) ) || - (qFuzzyIsNull(m.m11() + qreal(1)) - && qFuzzyIsNull(m.m12()) - && qFuzzyIsNull(m.m21()) - && qFuzzyIsNull(m.m22() + qreal(1)) + (qFuzzyCompare(m.m11(), qreal(-1)) + && qFuzzyCompare(m.m12() + 1, qreal(1)) + && qFuzzyCompare(m.m21() + 1, qreal(1)) + && qFuzzyCompare(m.m22(), qreal(-1)) ) || - (qFuzzyIsNull(m.m11()) - && qFuzzyIsNull(m.m12() + qreal(1)) - && qFuzzyIsNull(m.m21() - qreal(1)) - && qFuzzyIsNull(m.m22()) + (qFuzzyCompare(m.m11() + 1, qreal(1)) + && qFuzzyCompare(m.m12(), qreal(-1)) + && qFuzzyCompare(m.m21(), qreal(1)) + && qFuzzyCompare(m.m22() + 1, qreal(1)) ) ; aa = !isPlain90DegreeRotation; @@ -7695,7 +7704,7 @@ QPainterState::QPainterState(const QPainterState *s) clipRegion(s->clipRegion), clipPath(s->clipPath), clipOperation(s->clipOperation), renderHints(s->renderHints), clipInfo(s->clipInfo), - worldMatrix(s->worldMatrix), matrix(s->matrix), redirectionMatrix(s->redirectionMatrix), + worldMatrix(s->worldMatrix), matrix(s->matrix), redirection_offset(s->redirection_offset), wx(s->wx), wy(s->wy), ww(s->ww), wh(s->wh), vx(s->vx), vy(s->vy), vw(s->vw), vh(s->vh), opacity(s->opacity), WxF(s->WxF), VxF(s->VxF), diff --git a/src/gui/painting/qpainter.h b/src/gui/painting/qpainter.h index 78cd713..f3df7a3 100644 --- a/src/gui/painting/qpainter.h +++ b/src/gui/painting/qpainter.h @@ -507,7 +507,6 @@ private: friend class QFontEngineXLFD; friend class QWSManager; friend class QPaintEngine; - friend class QPaintEngineExPrivate; friend class QOpenGLPaintEngine; friend class QX11PaintEngine; friend class QX11PaintEnginePrivate; diff --git a/src/gui/painting/qpainter_p.h b/src/gui/painting/qpainter_p.h index 8d4e6c5..258b25a 100644 --- a/src/gui/painting/qpainter_p.h +++ b/src/gui/painting/qpainter_p.h @@ -92,8 +92,8 @@ inline Qt::PenJoinStyle qpen_joinStyle(const QPen &p) { return data_ptr(p)->join // QBrush inline functions... inline QBrush::DataPtr &data_ptr(const QBrush &p) { return const_cast(p).data_ptr(); } inline bool qbrush_fast_equals(const QBrush &a, const QBrush &b) { return data_ptr(a) == data_ptr(b); } -inline Qt::BrushStyle qbrush_style(const QBrush &b) { return data_ptr(b)->style; } -inline const QColor &qbrush_color(const QBrush &b) { return data_ptr(b)->color; } +inline Qt::BrushStyle qbrush_style(const QBrush &b) { return data_ptr(b)->style; }; +inline const QColor &qbrush_color(const QBrush &b) { return data_ptr(b)->color; }; inline bool qbrush_has_transform(const QBrush &b) { return data_ptr(b)->transform.type() > QTransform::TxNone; } class QPainterClipInfo @@ -158,7 +158,7 @@ public: QList clipInfo; // ### Make me smaller and faster to copy around... QTransform worldMatrix; // World transformation matrix, not window and viewport QTransform matrix; // Complete transformation matrix, - QTransform redirectionMatrix; + QPoint redirection_offset; int wx, wy, ww, wh; // window rectangle int vx, vy, vw, vh; // viewport rectangle qreal opacity; -- cgit v0.12 From 615f8a53355ea501e489eecddab1d5c4295cab80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 11 Jun 2009 11:42:05 +0200 Subject: Partially revert "Add (back) properties to QGraphicsItem to change the transformations component" This partially reverts commit 56f23d4c, which changed the logic in updateCachedClipPathFromSetPosHelper. We cannot compute the item's transform relative to the parent by using transformToParent() because the new position is not yet set on the item, that's why the new position is passed into the function. However, I'll look into how we can get rid of the entire function, but keep it as is for now. Reviewed-by: Olivier --- src/gui/graphicsview/qgraphicsitem.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index f50d210..eae2bf3 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -4281,7 +4281,9 @@ void QGraphicsItemPrivate::updateCachedClipPathFromSetPosHelper(const QPointF &n // Find closest clip ancestor and transform. Q_Q(QGraphicsItem); // COMBINE - QTransform thisToParentTransform = transformToParent(); + QTransform thisToParentTransform = transformData + ? transformData->computedFullTransform() * QTransform::fromTranslate(newPos.x(), newPos.y()) + : QTransform::fromTranslate(newPos.x(), newPos.y()); QGraphicsItem *clipParent = parent; while (clipParent && !(clipParent->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)) { thisToParentTransform *= clipParent->d_ptr->transformToParent(); -- cgit v0.12 From 05cb12eb18605aa32ff7a6761ff82d86aa339995 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Wed, 3 Jun 2009 14:14:09 +0200 Subject: add a QGraphicsObject class and change QGraphicsWidget and QGraphicsTextItem to inherit from it This changes the inheritance hierarchy of QGraphicsWidget from multiply inheriting from QObject, QGraphicsItem and QGraphicsLayoutItem to inherit from QGraphicsObject and QGraphicsLayoutItem. QGraphicsObject then simply inherits from QObject and QGraphicsItem. This change is binary compatible as it will leave the vtable layout unchanged and as the parent class doesn't appear in the C++ name mangling on any of our platforms. It's also source compatible as it isn't noticable by existing code. The restriction we have on QGraphicsObject is that we can not add any new virtual methods to it, or add data members to the class. We can however implement a QGraphicsObjectprivate inheriting from QGraphicsItemPrivate if there is a need to add data members to the class. This change will allow us to now have one single base for all QGraphicsItems that inherit from QObject: QGraphicsTextItem, QGraphicsWidget and in the future QFxItem. Having that single base class will significantly simplify our work in the qml engine. Reviewed-by: Andreas --- src/gui/graphicsview/graphicsview.pri | 77 ++++++++++++++------------------ src/gui/graphicsview/qgraphicsitem.cpp | 16 ++++++- src/gui/graphicsview/qgraphicsitem.h | 12 ++++- src/gui/graphicsview/qgraphicswidget.cpp | 4 +- src/gui/graphicsview/qgraphicswidget.h | 3 +- 5 files changed, 63 insertions(+), 49 deletions(-) diff --git a/src/gui/graphicsview/graphicsview.pri b/src/gui/graphicsview/graphicsview.pri index 02d9bb1..4cee6d6 100644 --- a/src/gui/graphicsview/graphicsview.pri +++ b/src/gui/graphicsview/graphicsview.pri @@ -1,46 +1,37 @@ # Qt graphicsview module - -HEADERS += \ - graphicsview/qgraphicsitem.h \ - graphicsview/qgraphicsitem_p.h \ - graphicsview/qgraphicsitemanimation.h \ - graphicsview/qgraphicsscene.h \ - graphicsview/qgraphicsscene_p.h \ - graphicsview/qgraphicsscene_bsp_p.h \ - graphicsview/qgraphicssceneevent.h \ - graphicsview/qgraphicsview_p.h \ - graphicsview/qgraphicsview.h - -SOURCES += \ - graphicsview/qgraphicsitem.cpp \ - graphicsview/qgraphicsitemanimation.cpp \ - graphicsview/qgraphicsscene.cpp \ - graphicsview/qgraphicsscene_bsp.cpp \ - graphicsview/qgraphicssceneevent.cpp \ - graphicsview/qgraphicsview.cpp +HEADERS += graphicsview/qgraphicsitem.h \ + graphicsview/qgraphicsitem_p.h \ + graphicsview/qgraphicsitemanimation.h \ + graphicsview/qgraphicsscene.h \ + graphicsview/qgraphicsscene_p.h \ + graphicsview/qgraphicsscene_bsp_p.h \ + graphicsview/qgraphicssceneevent.h \ + graphicsview/qgraphicsview_p.h \ + graphicsview/qgraphicsview.h +SOURCES += graphicsview/qgraphicsitem.cpp \ + graphicsview/qgraphicsitemanimation.cpp \ + graphicsview/qgraphicsscene.cpp \ + graphicsview/qgraphicsscene_bsp.cpp \ + graphicsview/qgraphicssceneevent.cpp \ + graphicsview/qgraphicsview.cpp # Widgets on the canvas - -HEADERS += \ - graphicsview/qgraphicslayout.h \ - graphicsview/qgraphicslayout_p.h \ - graphicsview/qgraphicslayoutitem.h \ - graphicsview/qgraphicslayoutitem_p.h \ - graphicsview/qgraphicslinearlayout.h \ - graphicsview/qgraphicswidget.h \ - graphicsview/qgraphicswidget_p.h \ - graphicsview/qgridlayoutengine_p.h \ - graphicsview/qgraphicsproxywidget.h \ - graphicsview/qgraphicsgridlayout.h - -SOURCES += \ - graphicsview/qgraphicslayout.cpp \ - graphicsview/qgraphicslayout_p.cpp \ - graphicsview/qgraphicslayoutitem.cpp \ - graphicsview/qgraphicslinearlayout.cpp \ - graphicsview/qgraphicswidget.cpp \ - graphicsview/qgraphicswidget_p.cpp \ - graphicsview/qgridlayoutengine.cpp \ - graphicsview/qgraphicsproxywidget.cpp \ - graphicsview/qgraphicsgridlayout.cpp - +HEADERS += graphicsview/qgraphicslayout.h \ + graphicsview/qgraphicslayout_p.h \ + graphicsview/qgraphicslayoutitem.h \ + graphicsview/qgraphicslayoutitem_p.h \ + graphicsview/qgraphicslinearlayout.h \ + graphicsview/qgraphicswidget.h \ + graphicsview/qgraphicswidget_p.h \ + graphicsview/qgridlayoutengine_p.h \ + graphicsview/qgraphicsproxywidget.h \ + graphicsview/qgraphicsgridlayout.h +SOURCES += graphicsview/qgraphicslayout.cpp \ + graphicsview/qgraphicslayout_p.cpp \ + graphicsview/qgraphicslayoutitem.cpp \ + graphicsview/qgraphicslinearlayout.cpp \ + graphicsview/qgraphicswidget.cpp \ + graphicsview/qgraphicswidget_p.cpp \ + graphicsview/qgridlayoutengine.cpp \ + graphicsview/qgraphicsproxywidget.cpp \ + graphicsview/qgraphicsgridlayout.cpp diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index eae2bf3..b83f9db 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -8147,6 +8147,18 @@ public: QGraphicsTextItem *qq; }; + +QGraphicsObject::QGraphicsObject(QGraphicsItem *parent) + : QGraphicsItem(parent) +{ +} + +QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene) + : QGraphicsItem(dd, parent, scene) +{ +} + + /*! Constructs a QGraphicsTextItem, using \a text as the default plain text. \a parent is passed to QGraphicsItem's constructor. @@ -8159,7 +8171,7 @@ QGraphicsTextItem::QGraphicsTextItem(const QString &text, QGraphicsItem *parent , QGraphicsScene *scene #endif ) - : QGraphicsItem(parent, scene), dd(new QGraphicsTextItemPrivate) + : QGraphicsObject(*new QGraphicsItemPrivate, parent, scene), dd(new QGraphicsTextItemPrivate) { dd->qq = this; if (!text.isEmpty()) @@ -8181,7 +8193,7 @@ QGraphicsTextItem::QGraphicsTextItem(QGraphicsItem *parent , QGraphicsScene *scene #endif ) - : QGraphicsItem(parent, scene), dd(new QGraphicsTextItemPrivate) + : QGraphicsObject(*new QGraphicsItemPrivate, parent, scene), dd(new QGraphicsTextItemPrivate) { dd->qq = this; setAcceptDrops(true); diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index cff4f1f..a9b5d71 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -832,10 +832,20 @@ private: inline void QGraphicsPixmapItem::setOffset(qreal ax, qreal ay) { setOffset(QPointF(ax, ay)); } +class Q_GUI_EXPORT QGraphicsObject : public QObject, public QGraphicsItem +{ + Q_OBJECT + Q_INTERFACES(QGraphicsItem) +public: + QGraphicsObject(QGraphicsItem *parent = 0); +protected: + QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene); +}; + class QGraphicsTextItemPrivate; class QTextDocument; class QTextCursor; -class Q_GUI_EXPORT QGraphicsTextItem : public QObject, public QGraphicsItem +class Q_GUI_EXPORT QGraphicsTextItem : public QGraphicsObject { Q_OBJECT QDOC_PROPERTY(bool openExternalLinks READ openExternalLinks WRITE setOpenExternalLinks) diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 7314167..84434db 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -257,7 +257,7 @@ QT_BEGIN_NAMESPACE window, a tool, a popup, etc). */ QGraphicsWidget::QGraphicsWidget(QGraphicsItem *parent, Qt::WindowFlags wFlags) - : QGraphicsItem(*new QGraphicsWidgetPrivate, 0, 0), QGraphicsLayoutItem(0, false) + : QGraphicsObject(*new QGraphicsWidgetPrivate, 0, 0), QGraphicsLayoutItem(0, false) { Q_D(QGraphicsWidget); d->init(parent, wFlags); @@ -269,7 +269,7 @@ QGraphicsWidget::QGraphicsWidget(QGraphicsItem *parent, Qt::WindowFlags wFlags) Constructs a new QGraphicsWidget, using \a dd as parent. */ QGraphicsWidget::QGraphicsWidget(QGraphicsWidgetPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene, Qt::WindowFlags wFlags) - : QGraphicsItem(dd, 0, scene), QGraphicsLayoutItem(0, false) + : QGraphicsObject(dd, 0, scene), QGraphicsLayoutItem(0, false) { Q_D(QGraphicsWidget); d->init(parent, wFlags); diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h index a5c9068..6f324cf 100644 --- a/src/gui/graphicsview/qgraphicswidget.h +++ b/src/gui/graphicsview/qgraphicswidget.h @@ -66,9 +66,10 @@ class QStyleOption; class QGraphicsWidgetPrivate; -class Q_GUI_EXPORT QGraphicsWidget : public QObject, public QGraphicsItem, public QGraphicsLayoutItem +class Q_GUI_EXPORT QGraphicsWidget : public QGraphicsObject, public QGraphicsLayoutItem { Q_OBJECT + Q_INTERFACES(QGraphicsLayoutItem) Q_PROPERTY(QPalette palette READ palette WRITE setPalette) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection RESET unsetLayoutDirection) -- cgit v0.12 From 27f602b3c6075f7f664a7d3fd71f03f795f490fb Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 4 Jun 2009 11:14:31 +0200 Subject: move some properties from QGraphicsWidget to QGraphicsObject These are properties of QGraphicsItem. QGraphicsObject should expose these. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.h | 4 ++++ src/gui/graphicsview/qgraphicswidget.h | 4 ---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index a9b5d71..69aab20 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -836,6 +836,10 @@ class Q_GUI_EXPORT QGraphicsObject : public QObject, public QGraphicsItem { Q_OBJECT Q_INTERFACES(QGraphicsItem) + Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity) + Q_PROPERTY(QPointF pos READ pos WRITE setPos) + Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) + Q_PROPERTY(bool visible READ isVisible WRITE setVisible) public: QGraphicsObject(QGraphicsItem *parent = 0); protected: diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h index 6f324cf..e19513d 100644 --- a/src/gui/graphicsview/qgraphicswidget.h +++ b/src/gui/graphicsview/qgraphicswidget.h @@ -75,12 +75,8 @@ class Q_GUI_EXPORT QGraphicsWidget : public QGraphicsObject, public QGraphicsLay Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection RESET unsetLayoutDirection) Q_PROPERTY(QSizeF size READ size WRITE resize) Q_PROPERTY(Qt::FocusPolicy focusPolicy READ focusPolicy WRITE setFocusPolicy) - Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) - Q_PROPERTY(bool visible READ isVisible WRITE setVisible) Q_PROPERTY(Qt::WindowFlags windowFlags READ windowFlags WRITE setWindowFlags) Q_PROPERTY(QString windowTitle READ windowTitle WRITE setWindowTitle) - Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity) - Q_PROPERTY(QPointF pos READ pos WRITE setPos) Q_PROPERTY(QRectF geometry READ geometry WRITE setGeometry) Q_PROPERTY(QPointF transformOrigin READ transformOrigin WRITE setTransformOrigin) Q_PROPERTY(qreal xRotation READ xRotation WRITE setXRotation) -- cgit v0.12 From e9876fdfaece0dcb09188cb4ddd5801ebb588647 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 4 Jun 2009 12:14:55 +0200 Subject: Add some meat to QGraphicsObject Added a toGraphicsObject() method to QGraphicsItem to allow upcasting. Expose some of QGraphicsItems setter/getter pairs as real properties in QGraphicsObject, including NOTIFY signals. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 145 ++++++++++++++++++++++++++++--- src/gui/graphicsview/qgraphicsitem.h | 43 ++++++--- src/gui/graphicsview/qgraphicsitem_p.h | 4 +- src/gui/graphicsview/qgraphicswidget.cpp | 81 ----------------- 4 files changed, 166 insertions(+), 107 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index b83f9db..6d87c36 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1260,6 +1260,28 @@ QGraphicsWidget *QGraphicsItem::window() const } /*! + \since 4.6 + + Return the graphics item cast to a QGraphicsObject, if the class is actually a + graphics object, 0 otherwise. +*/ +QGraphicsObject *QGraphicsItem::toGraphicsObject() +{ + return d_ptr->isObject ? static_cast(this) : 0; +} + +/*! + \since 4.6 + + Return the graphics item cast to a QGraphicsObject, if the class is actually a + graphics object, 0 otherwise. +*/ +const QGraphicsObject *QGraphicsItem::toGraphicsObject() const +{ + return d_ptr->isObject ? static_cast(this) : 0; +} + +/*! Sets this item's parent item to \a parent. If this item already has a parent, it is first removed from the previous parent. If \a parent is 0, this item will become a top-level item. @@ -1799,6 +1821,9 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo void QGraphicsItem::setVisible(bool visible) { d_ptr->setVisibleHelper(visible, /* explicit = */ true); + + if (d_ptr->isObject) + emit static_cast(this)->visibleChanged(); } /*! @@ -1920,6 +1945,9 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo void QGraphicsItem::setEnabled(bool enabled) { d_ptr->setEnabledHelper(enabled, /* explicitly = */ true); + + if (d_ptr->isObject) + emit static_cast(this)->enabledChanged(); } /*! @@ -2082,6 +2110,8 @@ void QGraphicsItem::setOpacity(qreal opacity) /*maybeDirtyClipPath=*/false, /*force=*/false, /*ignoreOpacity=*/true); + if (d_ptr->isObject) + emit static_cast(this)->opacityChanged(); } /*! @@ -2524,6 +2554,8 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) this->pos = pos; dirtySceneTransform = 1; inSetPosHelper = 0; + if (isObject) + emit static_cast(q)->positionChanged(); } /*! @@ -6324,6 +6356,108 @@ static void qt_graphicsItem_highlightSelected( } /*! + \class QGraphicsObject + \brief The QGraphicsObject class provides a base class for all graphics items that + require signals, slots and properties. + \since 4.6 + \ingroup graphicsview-api + + The class extends a QGraphicsItem with QObject's signal/slot and property mechanisms. + It maps many of QGraphicsItem's basic setters and getters to properties and adds notification + signals for many of them. +*/ + +/*! + Constructs a QGraphicsObject with \a parent. +*/ +QGraphicsObject::QGraphicsObject(QGraphicsItem *parent) + : QGraphicsItem(parent) +{ + QGraphicsItem::d_ptr->isObject = true; +} + +/*! + \internal +*/ +QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene) + : QGraphicsItem(dd, parent, scene) +{ + QGraphicsItem::d_ptr->isObject = true; +} + +/*! + \property QGraphicsObject::opacity + \brief the opacity of the item + + \sa QGraphicsItem::setOpacity, QGraphicsItem::opacity +*/ + +/*! + \fn QGraphicsObject::opacityChanged() + + This signal gets emitted whenever the opacity of the item changes + + \sa opacity +*/ + +/*! + \property QGraphicsObject::pos + \brief the position of the item + + Describes the items position. + + \sa QGraphicsItem::setPos, QGraphicsItem::pos, positionChanged +*/ + +/*! + \fn QGraphicsObject::positionChanged() + + This signal gets emitted whenever the position of the item changes + + \sa pos +*/ + +/*! + \property QGraphicsObject::enabled + \brief whether the item is enabled or not + + This property is declared in QGraphicsItem. + + By default, this property is true. + + \sa QGraphicsItem::isEnabled(), QGraphicsItem::setEnabled(), enabledChanged() +*/ + +/*! + \fn QGraphicsObject::enabledChanged() + + This signal gets emitted whenever the item get's enabled or disabled. + + \sa enabled +*/ + +/*! + \property QGraphicsObject::visible + \brief whether the item is visible or not + + This property is declared in QGraphicsItem. + + By default, this property is true. + + \sa QGraphicsItem::isVisible(), QGraphicsItem::setVisible(), visibleChanged() +*/ + +/*! + \fn QGraphicsObject::visibleChanged() + + This signal gets emitted whenever the visibility of the item changes + + \sa visible +*/ + + + +/*! \class QAbstractGraphicsShapeItem \brief The QAbstractGraphicsShapeItem class provides a common base for all path items. @@ -8148,17 +8282,6 @@ public: }; -QGraphicsObject::QGraphicsObject(QGraphicsItem *parent) - : QGraphicsItem(parent) -{ -} - -QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene) - : QGraphicsItem(dd, parent, scene) -{ -} - - /*! Constructs a QGraphicsTextItem, using \a text as the default plain text. \a parent is passed to QGraphicsItem's constructor. diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index 69aab20..a5ccef2 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -63,6 +63,7 @@ class QBrush; class QCursor; class QFocusEvent; class QGraphicsItemGroup; +class QGraphicsObject; class QGraphicsSceneContextMenuEvent; class QGraphicsSceneDragDropEvent; class QGraphicsSceneEvent; @@ -159,6 +160,9 @@ public: bool isWidget() const; bool isWindow() const; + QGraphicsObject *toGraphicsObject(); + const QGraphicsObject *toGraphicsObject() const; + QGraphicsItemGroup *group() const; void setGroup(QGraphicsItemGroup *group); @@ -484,6 +488,31 @@ inline QRectF QGraphicsItem::mapRectFromParent(qreal ax, qreal ay, qreal w, qrea inline QRectF QGraphicsItem::mapRectFromScene(qreal ax, qreal ay, qreal w, qreal h) const { return mapRectFromScene(QRectF(ax, ay, w, h)); } + +class Q_GUI_EXPORT QGraphicsObject : public QObject, public QGraphicsItem +{ + Q_OBJECT + Q_INTERFACES(QGraphicsItem) + Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged) + Q_PROPERTY(QPointF pos READ pos WRITE setPos NOTIFY positionChanged) + Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged) + Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged) +public: + QGraphicsObject(QGraphicsItem *parent = 0); + +Q_SIGNALS: + void opacityChanged(); + void visibleChanged(); + void enabledChanged(); + void positionChanged(); + +protected: + QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene); +private: + friend class QGraphicsItem; +}; + + class QAbstractGraphicsShapeItemPrivate; class Q_GUI_EXPORT QAbstractGraphicsShapeItem : public QGraphicsItem { @@ -832,20 +861,6 @@ private: inline void QGraphicsPixmapItem::setOffset(qreal ax, qreal ay) { setOffset(QPointF(ax, ay)); } -class Q_GUI_EXPORT QGraphicsObject : public QObject, public QGraphicsItem -{ - Q_OBJECT - Q_INTERFACES(QGraphicsItem) - Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity) - Q_PROPERTY(QPointF pos READ pos WRITE setPos) - Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled) - Q_PROPERTY(bool visible READ isVisible WRITE setVisible) -public: - QGraphicsObject(QGraphicsItem *parent = 0); -protected: - QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene); -}; - class QGraphicsTextItemPrivate; class QTextDocument; class QTextCursor; diff --git a/src/gui/graphicsview/qgraphicsitem_p.h b/src/gui/graphicsview/qgraphicsitem_p.h index 5626867..0e6658c 100644 --- a/src/gui/graphicsview/qgraphicsitem_p.h +++ b/src/gui/graphicsview/qgraphicsitem_p.h @@ -149,6 +149,7 @@ public: dirtySceneTransform(1), geometryChanged(0), inDestructor(0), + isObject(0), globalStackingOrder(-1), q_ptr(0) { @@ -405,7 +406,8 @@ public: quint32 dirtySceneTransform : 1; quint32 geometryChanged : 1; quint32 inDestructor : 1; - quint32 unused : 15; // feel free to use + quint32 isObject : 1; + quint32 unused : 14; // feel free to use // Optional stacking order int globalStackingOrder; diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 84434db..419277d 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -170,87 +170,6 @@ QT_BEGIN_NAMESPACE */ /*! - \property QGraphicsWidget::enabled - \brief whether the item is enabled or not - - This property is declared in QGraphicsItem. - - By default, this property is true. - - \sa QGraphicsItem::isEnabled(), QGraphicsItem::setEnabled() -*/ - -/*! - \property QGraphicsWidget::visible - \brief whether the item is visible or not - - This property is declared in QGraphicsItem. - - By default, this property is true. - - \sa QGraphicsItem::isVisible(), QGraphicsItem::setVisible(), show(), - hide() -*/ - -/*! - \property QGraphicsWidget::opacity - \brief the opacity of the widget -*/ - -/*! - \property QGraphicsWidget::pos - \brief the position of the widget -*/ - -/*! - \property QGraphicsWidget::xRotation - \since 4.6 - \brief the rotation angle in degrees around the X axis -*/ - -/*! - \property QGraphicsWidget::yRotation - \since 4.6 - \brief the rotation angle in degrees around the Y axis -*/ - -/*! - \property QGraphicsWidget::zRotation - \since 4.6 - \brief the rotation angle in degrees around the Z axis -*/ - -/*! - \property QGraphicsWidget::xScale - \since 4.6 - \brief the scale factor on the X axis. -*/ - -/*! - \property QGraphicsWidget::yScale - \since 4.6 - \brief the scale factor on the Y axis. -*/ - -/*! - \property QGraphicsWidget::horizontalShear - \since 4.6 - \brief the horizontal shear. -*/ - -/*! - \property QGraphicsWidget::verticalShear - \since 4.6 - \brief the vertical shear. -*/ - -/*! - \property QGraphicsWidget::transformOrigin - \since 4.6 - \brief the transformation origin for the transformation properties. -*/ - -/*! Constructs a QGraphicsWidget instance. The optional \a parent argument is passed to QGraphicsItem's constructor. The optional \a wFlags argument specifies the widget's window flags (e.g., whether the widget should be a -- cgit v0.12 From b3ff3392128c9c701b687887ef2c21b000209908 Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Thu, 4 Jun 2009 14:38:05 +0200 Subject: added properties for x,y and z. Removed the notify for the pos property, add auto tests for QGraphicsObject FX items are better off with property notifications on each component rather than on the position. Added some basic testing for QGraphicsObject and fixed the failures exposed. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 47 +++- src/gui/graphicsview/qgraphicsitem.h | 13 +- src/gui/graphicsview/qgraphicswidget.h | 1 - tests/auto/auto.pro | 10 +- tests/auto/qgraphicsobject/qgraphicsobject.pro | 2 + tests/auto/qgraphicsobject/tst_qgraphicsobject.cpp | 255 +++++++++++++++++++++ 6 files changed, 315 insertions(+), 13 deletions(-) create mode 100644 tests/auto/qgraphicsobject/qgraphicsobject.pro create mode 100644 tests/auto/qgraphicsobject/tst_qgraphicsobject.cpp diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 6d87c36..3622c82 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -1789,6 +1789,9 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo // Deliver post-change notification. q_ptr->itemChange(QGraphicsItem::ItemVisibleHasChanged, newVisibleVariant); + + if (isObject) + emit static_cast(q_ptr)->visibleChanged(); } /*! @@ -1821,9 +1824,6 @@ void QGraphicsItemPrivate::setVisibleHelper(bool newVisible, bool explicitly, bo void QGraphicsItem::setVisible(bool visible) { d_ptr->setVisibleHelper(visible, /* explicit = */ true); - - if (d_ptr->isObject) - emit static_cast(this)->visibleChanged(); } /*! @@ -1912,6 +1912,9 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo // Deliver post-change notification. q_ptr->itemChange(QGraphicsItem::ItemEnabledHasChanged, newEnabledVariant); + + if (isObject) + emit static_cast(q_ptr)->enabledChanged(); } /*! @@ -1945,9 +1948,6 @@ void QGraphicsItemPrivate::setEnabledHelper(bool newEnabled, bool explicitly, bo void QGraphicsItem::setEnabled(bool enabled) { d_ptr->setEnabledHelper(enabled, /* explicitly = */ true); - - if (d_ptr->isObject) - emit static_cast(this)->enabledChanged(); } /*! @@ -2110,6 +2110,7 @@ void QGraphicsItem::setOpacity(qreal opacity) /*maybeDirtyClipPath=*/false, /*force=*/false, /*ignoreOpacity=*/true); + if (d_ptr->isObject) emit static_cast(this)->opacityChanged(); } @@ -2520,6 +2521,17 @@ QPointF QGraphicsItem::pos() const \sa y() */ +/* + Set's the x coordinate of the item's position. Equivalent to + calling setPos(x, y()). + + \sa x(), setPos() +*/ +void QGraphicsItem::setX(qreal x) +{ + d_ptr->setPosHelper(QPointF(x, d_ptr->pos.y())); +} + /*! \fn QGraphicsItem::y() const @@ -2528,6 +2540,17 @@ QPointF QGraphicsItem::pos() const \sa x() */ +/* + Set's the y coordinate of the item's position. Equivalent to + calling setPos(x(), y). + + \sa x(), setPos() +*/ +void QGraphicsItem::setY(qreal y) +{ + d_ptr->setPosHelper(QPointF(d_ptr->pos.x(), y)); +} + /*! Returns the item's position in scene coordinates. This is equivalent to calling \c mapToScene(0, 0). @@ -2551,11 +2574,16 @@ void QGraphicsItemPrivate::setPosHelper(const QPointF &pos) updateCachedClipPathFromSetPosHelper(pos); if (scene) q->prepareGeometryChange(); + QPointF oldPos = this->pos; this->pos = pos; dirtySceneTransform = 1; inSetPosHelper = 0; - if (isObject) - emit static_cast(q)->positionChanged(); + if (isObject) { + if (pos.x() != oldPos.x()) + emit static_cast(q_ptr)->xChanged(); + if (pos.y() != oldPos.y()) + emit static_cast(q_ptr)->yChanged(); + } } /*! @@ -3535,6 +3563,9 @@ void QGraphicsItem::setZValue(qreal z) } itemChange(ItemZValueHasChanged, newZVariant); + + if (d_ptr->isObject) + emit static_cast(this)->zChanged(); } /*! diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index a5ccef2..a69eced 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -227,7 +227,9 @@ public: // Positioning in scene coordinates QPointF pos() const; inline qreal x() const { return pos().x(); } + void setX(qreal x); inline qreal y() const { return pos().y(); } + void setY(qreal y); QPointF scenePos() const; void setPos(const QPointF &pos); inline void setPos(qreal x, qreal y); @@ -492,11 +494,13 @@ inline QRectF QGraphicsItem::mapRectFromScene(qreal ax, qreal ay, qreal w, qreal class Q_GUI_EXPORT QGraphicsObject : public QObject, public QGraphicsItem { Q_OBJECT - Q_INTERFACES(QGraphicsItem) Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged) - Q_PROPERTY(QPointF pos READ pos WRITE setPos NOTIFY positionChanged) + Q_PROPERTY(QPointF pos READ pos WRITE setPos) Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged) Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged) + Q_PROPERTY(qreal x READ x WRITE setX NOTIFY xChanged) + Q_PROPERTY(qreal y READ y WRITE setY NOTIFY yChanged) + Q_PROPERTY(qreal z READ zValue WRITE setZValue NOTIFY zChanged) public: QGraphicsObject(QGraphicsItem *parent = 0); @@ -504,12 +508,15 @@ Q_SIGNALS: void opacityChanged(); void visibleChanged(); void enabledChanged(); - void positionChanged(); + void xChanged(); + void yChanged(); + void zChanged(); protected: QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent, QGraphicsScene *scene); private: friend class QGraphicsItem; + friend class QGraphicsItemPrivate; }; diff --git a/src/gui/graphicsview/qgraphicswidget.h b/src/gui/graphicsview/qgraphicswidget.h index e19513d..337490c 100644 --- a/src/gui/graphicsview/qgraphicswidget.h +++ b/src/gui/graphicsview/qgraphicswidget.h @@ -69,7 +69,6 @@ class QGraphicsWidgetPrivate; class Q_GUI_EXPORT QGraphicsWidget : public QGraphicsObject, public QGraphicsLayoutItem { Q_OBJECT - Q_INTERFACES(QGraphicsLayoutItem) Q_PROPERTY(QPalette palette READ palette WRITE setPalette) Q_PROPERTY(QFont font READ font WRITE setFont) Q_PROPERTY(Qt::LayoutDirection layoutDirection READ layoutDirection WRITE setLayoutDirection RESET unsetLayoutDirection) diff --git a/tests/auto/auto.pro b/tests/auto/auto.pro index a65c172..d5803bc 100644 --- a/tests/auto/auto.pro +++ b/tests/auto/auto.pro @@ -141,9 +141,17 @@ SUBDIRS += _networkselftest \ qglobal \ qgraphicsitem \ qgraphicsitemanimation \ + qgraphicslayout \ + qgraphicslayoutitem \ + qgraphicslinearlayout \ + qgraphicsobject \ + qgraphicspixmapitem \ + qgraphicspolygonitem \ + qgraphicsproxywidget \ qgraphicsscene \ qgraphicsview \ - qgridlayout \ + qgraphicswidget \ + qgridlayout \ qgroupbox \ qguivariant \ qhash \ diff --git a/tests/auto/qgraphicsobject/qgraphicsobject.pro b/tests/auto/qgraphicsobject/qgraphicsobject.pro new file mode 100644 index 0000000..965b319 --- /dev/null +++ b/tests/auto/qgraphicsobject/qgraphicsobject.pro @@ -0,0 +1,2 @@ +load(qttest_p4) +SOURCES += tst_qgraphicsobject.cpp diff --git a/tests/auto/qgraphicsobject/tst_qgraphicsobject.cpp b/tests/auto/qgraphicsobject/tst_qgraphicsobject.cpp new file mode 100644 index 0000000..eb12c48 --- /dev/null +++ b/tests/auto/qgraphicsobject/tst_qgraphicsobject.cpp @@ -0,0 +1,255 @@ +/**************************************************************************** +** +** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). +** Contact: Qt Software Information (qt-info@nokia.com) +** +** This file is part of the test suite of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:LGPL$ +** No Commercial Usage +** This file contains pre-release code and may not be distributed. +** You may use this file in accordance with the terms and conditions +** contained in the either Technology Preview License Agreement or the +** Beta Release License Agreement. +** +** GNU Lesser General Public License Usage +** Alternatively, 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.0, 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. +** +** If you are unsure which license is appropriate for your use, please +** contact the sales department at qt-sales@nokia.com. +** $QT_END_LICENSE$ +** +****************************************************************************/ + + +#include +#include +#include +#include +#include +#include +#include "../../shared/util.h" + +class tst_QGraphicsObject : public QObject { + Q_OBJECT + +public slots: + void initTestCase(); + void cleanupTestCase(); + void init(); + void cleanup(); + +private slots: + void pos(); + void x(); + void y(); + void z(); + void opacity(); + void enabled(); + void visible(); +}; + + +// This will be called before the first test function is executed. +// It is only called once. +void tst_QGraphicsObject::initTestCase() +{ +} + +// This will be called after the last test function is executed. +// It is only called once. +void tst_QGraphicsObject::cleanupTestCase() +{ +} + +// This will be called before each test function is executed. +void tst_QGraphicsObject::init() +{ +} + +// This will be called after every test function. +void tst_QGraphicsObject::cleanup() +{ +} + + +class MyGraphicsObject : public QGraphicsObject +{ +public: + MyGraphicsObject() : QGraphicsObject() {} + virtual QRectF boundingRect() const { return QRectF(); } + virtual void paint(QPainter *, const QStyleOptionGraphicsItem *, QWidget *) {} +}; + +void tst_QGraphicsObject::pos() +{ + MyGraphicsObject object; + QSignalSpy xSpy(&object, SIGNAL(xChanged())); + QSignalSpy ySpy(&object, SIGNAL(yChanged())); + QVERIFY(object.pos() == QPointF(0, 0)); + object.setPos(10, 10); + QCOMPARE(xSpy.count(), 1); + QCOMPARE(ySpy.count(), 1); + + QVERIFY(object.pos() == QPointF(10,10)); + + object.setPos(10, 10); + QCOMPARE(xSpy.count(), 1); + QCOMPARE(ySpy.count(), 1); + + object.setProperty("pos", QPointF(0, 0)); + QCOMPARE(xSpy.count(), 2); + QCOMPARE(ySpy.count(), 2); + QVERIFY(object.property("pos") == QPointF(0,0)); + + object.setProperty("pos", QPointF(10, 0)); + QCOMPARE(xSpy.count(), 3); + QCOMPARE(ySpy.count(), 2); + QVERIFY(object.property("pos") == QPointF(10,0)); + + object.setProperty("pos", QPointF(10, 10)); + QCOMPARE(xSpy.count(), 3); + QCOMPARE(ySpy.count(), 3); + QVERIFY(object.property("pos") == QPointF(10, 10)); +} + +void tst_QGraphicsObject::x() +{ + MyGraphicsObject object; + QSignalSpy xSpy(&object, SIGNAL(xChanged())); + QSignalSpy ySpy(&object, SIGNAL(yChanged())); + QVERIFY(object.pos() == QPointF(0, 0)); + object.setX(10); + QCOMPARE(xSpy.count(), 1); + QCOMPARE(ySpy.count(), 0); + + QVERIFY(object.pos() == QPointF(10, 0)); + QVERIFY(object.x() == 10); + + object.setX(10); + QCOMPARE(xSpy.count(), 1); + QCOMPARE(ySpy.count(), 0); + + object.setProperty("x", 0); + QCOMPARE(xSpy.count(), 2); + QCOMPARE(ySpy.count(), 0); + QVERIFY(object.property("x") == 0); +} + +void tst_QGraphicsObject::y() +{ + MyGraphicsObject object; + QSignalSpy xSpy(&object, SIGNAL(xChanged())); + QSignalSpy ySpy(&object, SIGNAL(yChanged())); + QVERIFY(object.pos() == QPointF(0, 0)); + object.setY(10); + QCOMPARE(xSpy.count(), 0); + QCOMPARE(ySpy.count(), 1); + + QVERIFY(object.pos() == QPointF(0, 10)); + QVERIFY(object.y() == 10); + + object.setY(10); + QCOMPARE(xSpy.count(), 0); + QCOMPARE(ySpy.count(), 1); + + object.setProperty("y", 0); + QCOMPARE(xSpy.count(), 0); + QCOMPARE(ySpy.count(), 2); + QVERIFY(object.property("y") == 0); +} + +void tst_QGraphicsObject::z() +{ + MyGraphicsObject object; + QSignalSpy zSpy(&object, SIGNAL(zChanged())); + QVERIFY(object.zValue() == 0); + object.setZValue(10); + QCOMPARE(zSpy.count(), 1); + + QVERIFY(object.zValue() == 10); + + object.setZValue(10); + QCOMPARE(zSpy.count(), 1); + + object.setProperty("z", 0); + QCOMPARE(zSpy.count(), 2); + QVERIFY(object.property("z") == 0); +} + +void tst_QGraphicsObject::opacity() +{ + MyGraphicsObject object; + QSignalSpy spy(&object, SIGNAL(opacityChanged())); + QVERIFY(object.opacity() == 1.); + object.setOpacity(0); + QCOMPARE(spy.count(), 1); + + QVERIFY(object.opacity() == 0.); + + object.setOpacity(0); + QCOMPARE(spy.count(), 1); + + object.setProperty("opacity", .5); + QCOMPARE(spy.count(), 2); + QVERIFY(object.property("opacity") == .5); +} + +void tst_QGraphicsObject::enabled() +{ + MyGraphicsObject object; + QSignalSpy spy(&object, SIGNAL(enabledChanged())); + QVERIFY(object.isEnabled() == true); + object.setEnabled(false); + QCOMPARE(spy.count(), 1); + + QVERIFY(object.isEnabled() == false); + + object.setEnabled(false); + QCOMPARE(spy.count(), 1); + + object.setProperty("enabled", true); + QCOMPARE(spy.count(), 2); + QVERIFY(object.property("enabled") == true); +} + +void tst_QGraphicsObject::visible() +{ + MyGraphicsObject object; + QSignalSpy spy(&object, SIGNAL(visibleChanged())); + QVERIFY(object.isVisible() == true); + object.setVisible(false); + QCOMPARE(spy.count(), 1); + + QVERIFY(object.isVisible() == false); + + object.setVisible(false); + QCOMPARE(spy.count(), 1); + + object.setProperty("visible", true); + QCOMPARE(spy.count(), 2); + QVERIFY(object.property("visible") == true); +} + + +QTEST_MAIN(tst_QGraphicsObject) +#include "tst_qgraphicsobject.moc" + -- cgit v0.12 From 15366ae05397cdf322e0a34e729eb5db2bae9c2a Mon Sep 17 00:00:00 2001 From: Lars Knoll Date: Mon, 8 Jun 2009 10:18:59 +0200 Subject: add parent and id properties to QGraphicsObject In addition added documentation for the other properties. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsitem.cpp | 73 +++++++++++++++++++++++++++++++++- src/gui/graphicsview/qgraphicsitem.h | 6 ++- 2 files changed, 76 insertions(+), 3 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 3622c82..0390a83 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -959,6 +959,9 @@ void QGraphicsItemPrivate::setParentItemHelper(QGraphicsItem *newParent) // Deliver post-change notification q->itemChange(QGraphicsItem::ItemParentHasChanged, newParentVariant); + + if (isObject) + emit static_cast(q)->parentChanged(); } /*! @@ -1213,6 +1216,20 @@ QGraphicsItem *QGraphicsItem::topLevelItem() const /*! \since 4.4 + Returns a pointer to the item's parent, cast to a QGraphicsObject. returns 0 if the parent item + is not a QGraphicsObject. + + \sa parentItem(), childItems() +*/ +QGraphicsObject *QGraphicsItem::parentObject() const +{ + QGraphicsItem *p = d_ptr->parent; + return (p && p->d_ptr->isObject) ? static_cast(p) : 0; +} + +/*! + \since 4.4 + Returns a pointer to the item's parent widget. The item's parent widget is the closest parent item that is a widget. @@ -6417,6 +6434,14 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent } /*! + \property QGraphicsObject::parent + \brief the parent of the item + + \sa QGraphicsItem::setParentItem, QGraphicsItem::parentObject +*/ + + +/*! \property QGraphicsObject::opacity \brief the opacity of the item @@ -6441,13 +6466,57 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent */ /*! - \fn QGraphicsObject::positionChanged() + \property QGraphicsObject::x + \brief the x position of the item + + Describes the items x position. + + \sa QGraphicsItem::setX, setPos, xChanged +*/ + +/*! + \fn QGraphicsObject::xChanged() + + This signal gets emitted whenever the x position of the item changes + + \sa pos +*/ + +/*! + \property QGraphicsObject:y + \brief the y position of the item + + Describes the items y position. + + \sa QGraphicsItem::setY, setPos, yChanged +*/ + +/*! + \fn QGraphicsObject::yChanged() + + This signal gets emitted whenever the y position of the item changes + + \sa pos +*/ + +/*! + \property QGraphicsObject::z + \brief the z value of the item - This signal gets emitted whenever the position of the item changes + Describes the items z value. + + \sa QGraphicsItem::setZValue, zValue, zChanged +*/ + +/*! + \fn QGraphicsObject::zChanged() + + This signal gets emitted whenever the z value of the item changes \sa pos */ + /*! \property QGraphicsObject::enabled \brief whether the item is enabled or not diff --git a/src/gui/graphicsview/qgraphicsitem.h b/src/gui/graphicsview/qgraphicsitem.h index a69eced..6ea17c2 100644 --- a/src/gui/graphicsview/qgraphicsitem.h +++ b/src/gui/graphicsview/qgraphicsitem.h @@ -151,6 +151,7 @@ public: QGraphicsItem *parentItem() const; QGraphicsItem *topLevelItem() const; + QGraphicsObject *parentObject() const; QGraphicsWidget *parentWidget() const; QGraphicsWidget *topLevelWidget() const; QGraphicsWidget *window() const; @@ -494,10 +495,12 @@ inline QRectF QGraphicsItem::mapRectFromScene(qreal ax, qreal ay, qreal w, qreal class Q_GUI_EXPORT QGraphicsObject : public QObject, public QGraphicsItem { Q_OBJECT + Q_PROPERTY(QGraphicsObject * parent READ parentObject WRITE setParentItem NOTIFY parentChanged DESIGNABLE false) + Q_PROPERTY(QString id READ objectName WRITE setObjectName) Q_PROPERTY(qreal opacity READ opacity WRITE setOpacity NOTIFY opacityChanged) - Q_PROPERTY(QPointF pos READ pos WRITE setPos) Q_PROPERTY(bool enabled READ isEnabled WRITE setEnabled NOTIFY enabledChanged) Q_PROPERTY(bool visible READ isVisible WRITE setVisible NOTIFY visibleChanged) + Q_PROPERTY(QPointF pos READ pos WRITE setPos) Q_PROPERTY(qreal x READ x WRITE setX NOTIFY xChanged) Q_PROPERTY(qreal y READ y WRITE setY NOTIFY yChanged) Q_PROPERTY(qreal z READ zValue WRITE setZValue NOTIFY zChanged) @@ -505,6 +508,7 @@ public: QGraphicsObject(QGraphicsItem *parent = 0); Q_SIGNALS: + void parentChanged(); void opacityChanged(); void visibleChanged(); void enabledChanged(); -- cgit v0.12 From a6eac57ee46c150aabd5cff331d6859e7999680f Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 10 Jun 2009 18:41:41 +0200 Subject: Autotest compile. This one is for qstandarditemmodel autotest --- src/gui/itemviews/qabstractitemview_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/itemviews/qabstractitemview_p.h b/src/gui/itemviews/qabstractitemview_p.h index 139d0b7..8594ad7 100644 --- a/src/gui/itemviews/qabstractitemview_p.h +++ b/src/gui/itemviews/qabstractitemview_p.h @@ -99,7 +99,7 @@ public: QVariant data(const QModelIndex &, int) const { return QVariant(); } }; -class QAbstractItemViewPrivate : public QAbstractScrollAreaPrivate +class Q_AUTOTEST_EXPORT QAbstractItemViewPrivate : public QAbstractScrollAreaPrivate { Q_DECLARE_PUBLIC(QAbstractItemView) -- cgit v0.12 From e0be99974d5d66f548543df9b5b919c8e81ade62 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Wed, 10 Jun 2009 18:42:35 +0200 Subject: Invalid QPersistentIndexes after QStandardItem::takeRow We need the parent of each potential QPersistentModelIndex in order to cleanup when removing the rows. They need not to change in order QSortFilterProxyModel maping to be still valid. takeRow must not change the internal data before calling beginRemoveRow. Same thing for takeColumn Task-number: 255652 Reviewed-by: Thierry Reviewed-by: Leo --- src/gui/itemviews/qstandarditemmodel.cpp | 36 ++++---- .../tst_qsortfilterproxymodel.cpp | 99 +++++++++++++++++----- .../qstandarditemmodel/tst_qstandarditemmodel.cpp | 49 ++++++++++- 3 files changed, 148 insertions(+), 36 deletions(-) diff --git a/src/gui/itemviews/qstandarditemmodel.cpp b/src/gui/itemviews/qstandarditemmodel.cpp index 9d0f796..30daed2 100644 --- a/src/gui/itemviews/qstandarditemmodel.cpp +++ b/src/gui/itemviews/qstandarditemmodel.cpp @@ -1742,18 +1742,21 @@ QList QStandardItem::takeRow(int row) Q_D(QStandardItem); if ((row < 0) || (row >= rowCount())) return QList(); + if (d->model) + d->model->d_func()->rowsAboutToBeRemoved(this, row, row); QList items; int index = d->childIndex(row, 0); - for (int column = 0; column < d->columnCount(); ++column) { - QStandardItem *ch = d->children.at(index); - if (ch) { + int col_count = d->columnCount(); + for (int column = 0; column < col_count; ++column) { + QStandardItem *ch = d->children.at(index + column); + if (ch) ch->d_func()->setParentAndModel(0, 0); - d->children.replace(index, 0); - } items.append(ch); - ++index; } - removeRow(row); + d->children.remove(index, col_count); + d->rows--; + if (d->model) + d->model->d_func()->rowsRemoved(this, row, 1); return items; } @@ -1769,18 +1772,21 @@ QList QStandardItem::takeColumn(int column) Q_D(QStandardItem); if ((column < 0) || (column >= columnCount())) return QList(); + if (d->model) + d->model->d_func()->columnsAboutToBeRemoved(this, column, column); QList items; - int index = d->childIndex(0, column); - for (int row = 0; row < d->rowCount(); ++row) { + + for (int row = d->rowCount() - 1; row >= 0; --row) { + int index = d->childIndex(row, column); QStandardItem *ch = d->children.at(index); - if (ch) { + if (ch) ch->d_func()->setParentAndModel(0, 0); - d->children.replace(index, 0); - } - items.append(ch); - index += d->columnCount(); + d->children.remove(index); + items.prepend(ch); } - removeColumn(column); + d->columns--; + if (d->model) + d->model->d_func()->columnsRemoved(this, column, 1); return items; } diff --git a/tests/auto/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp b/tests/auto/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp index d7c231f..274b177 100644 --- a/tests/auto/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp +++ b/tests/auto/qsortfilterproxymodel/tst_qsortfilterproxymodel.cpp @@ -134,6 +134,7 @@ private slots: void task250023_fetchMore(); void task251296_hiddenChildren(); void task252507_mapFromToSource(); + void task255652_removeRowsRecursive(); protected: void buildHierarchy(const QStringList &data, QAbstractItemModel *model); @@ -390,7 +391,7 @@ void tst_QSortFilterProxyModel::sort() QModelIndex index = m_proxy->index(row, 0, QModelIndex()); QCOMPARE(m_proxy->data(index, Qt::DisplayRole).toString(), initial.at(row)); } - + } void tst_QSortFilterProxyModel::sortHierarchy_data() @@ -411,7 +412,7 @@ void tst_QSortFilterProxyModel::sortHierarchy_data() << static_cast(Qt::AscendingOrder) << (QStringList() << "a" << "<" << "b" << "<" << "c" << ">" << ">") << (QStringList() << "a" << "<" << "b" << "<" << "c" << ">" << ">"); - + #if 1 QTest::newRow("hierarchical ascending") << static_cast(Qt::AscendingOrder) @@ -571,7 +572,7 @@ void tst_QSortFilterProxyModel::insertRows() QModelIndex index = m_proxy->index(row, 0, QModelIndex()); QCOMPARE(m_proxy->data(index, Qt::DisplayRole).toString(), initial.at(row)); } - + // insert the row m_proxy->insertRows(position, insert.count(), QModelIndex()); QCOMPARE(m_model->rowCount(QModelIndex()), expected.count()); @@ -615,7 +616,7 @@ void tst_QSortFilterProxyModel::prependRow() QStandardItem sub2("sub2"); sub2.appendRow(new QStandardItem("sub3")); item.insertRow(0, &sub2); - + QModelIndex index_sub2 = proxy.mapFromSource(model.indexFromItem(&sub2)); QCOMPARE(sub2.rowCount(), proxy.rowCount(index_sub2)); @@ -626,7 +627,7 @@ void tst_QSortFilterProxyModel::prependRow() /* void tst_QSortFilterProxyModel::insertColumns_data() { - + } void tst_QSortFilterProxyModel::insertColumns() @@ -923,7 +924,7 @@ void tst_QSortFilterProxyModel::removeRows() // prepare model foreach (QString s, initial) model.appendRow(new QStandardItem(s)); - + // remove the rows QCOMPARE(proxy.removeRows(position, count, QModelIndex()), success); QCOMPARE(model.rowCount(QModelIndex()), expectedSource.count()); @@ -1164,10 +1165,10 @@ void tst_QSortFilterProxyModel::removeColumns() proxy.setSourceModel(&model); if (!filter.isEmpty()) proxy.setFilterRegExp(QRegExp(filter)); - + // prepare model model.setHorizontalHeaderLabels(initial); - + // remove the columns QCOMPARE(proxy.removeColumns(position, count, QModelIndex()), success); QCOMPARE(model.columnCount(QModelIndex()), expectedSource.count()); @@ -1266,7 +1267,7 @@ void tst_QSortFilterProxyModel::filter_data() << "golf" << "quebec" << "foxtrot" - << "india" + << "india" << "romeo" << "november" << "oskar" @@ -1274,9 +1275,9 @@ void tst_QSortFilterProxyModel::filter_data() << "kilo" << "whiskey" << "mike" - << "papa" + << "papa" << "sierra" - << "xray" + << "xray" << "viktor") << (QStringList() << "delta" @@ -1334,7 +1335,7 @@ void tst_QSortFilterProxyModel::filterHierarchy_data() << "foo" << "boo" << "baz" << "moo" << "laa" << "haa") << (QStringList() << "foo" << "boo" << "moo"); - + QTest::newRow("simple hierarchy") << "b.*z" << (QStringList() << "baz" << "<" << "boz" << "<" << "moo" << ">" << ">") << (QStringList() << "baz" << "<" << "boz" << ">"); @@ -1671,7 +1672,7 @@ void tst_QSortFilterProxyModel::removeSourceRows() QSignalSpy insertSpy(&proxy, SIGNAL(rowsInserted(QModelIndex, int, int))); QSignalSpy aboutToRemoveSpy(&proxy, SIGNAL(rowsAboutToBeRemoved(QModelIndex, int, int))); QSignalSpy aboutToInsertSpy(&proxy, SIGNAL(rowsAboutToBeInserted(QModelIndex, int, int))); - + model.removeRows(start, count, QModelIndex()); QCOMPARE(aboutToRemoveSpy.count(), expectedRemovedProxyIntervals.count()); @@ -1827,7 +1828,7 @@ void tst_QSortFilterProxyModel::changeFilter() QFETCH(IntPairList, finalRemoveIntervals); QFETCH(IntPairList, insertIntervals); QFETCH(QStringList, finalProxyItems); - + QStandardItemModel model; QSortFilterProxyModel proxy; @@ -1880,7 +1881,7 @@ void tst_QSortFilterProxyModel::changeFilter() #ifdef Q_OS_IRIX QEXPECT_FAIL("filter (2)", "Not reliable on IRIX", Abort); -#endif +#endif QCOMPARE(finalInsertSpy.count(), insertIntervals.count()); for (int i = 0; i < finalInsertSpy.count(); ++i) { QList args = finalInsertSpy.at(i); @@ -2068,7 +2069,7 @@ void tst_QSortFilterProxyModel::sortFilterRole() model.setData(index, sourceItems.at(i).first, Qt::DisplayRole); model.setData(index, sourceItems.at(i).second, Qt::UserRole); } - + proxy.setFilterRegExp("2"); QCOMPARE(proxy.rowCount(), 0); // Qt::DisplayRole is default role @@ -2358,7 +2359,7 @@ void tst_QSortFilterProxyModel::sourceInsertRows() model.insertColumns(0, 1, parent); model.insertRows(0, 1, parent); } - + model.insertRows(0, 1, QModelIndex()); model.insertRows(0, 1, QModelIndex()); @@ -2462,7 +2463,7 @@ void tst_QSortFilterProxyModel::task236755_hiddenColumns() QVERIFY(view.isColumnHidden(0)); } -void tst_QSortFilterProxyModel::task247867_insertRowsSort() +void tst_QSortFilterProxyModel::task247867_insertRowsSort() { QStandardItemModel model(2,2); QSortFilterProxyModel proxyModel; @@ -2567,7 +2568,7 @@ void tst_QSortFilterProxyModel::task248868_dynamicSorting() QStringList initial2 = initial; initial2.replaceInStrings("bateau", "girafe"); model1.setStringList(initial2); //this will cause a reset - + QStringList expected2 = initial2; expected2.sort(); @@ -2648,7 +2649,7 @@ class QtTestModel: public QAbstractItemModel { if (!idx.isValid()) return QVariant(); - + if (role == Qt::DisplayRole) { if (idx.row() < 0 || idx.column() < 0 || idx.column() >= cols || idx.row() >= rows) { wrongIndex = true; @@ -2756,5 +2757,63 @@ void tst_QSortFilterProxyModel::task252507_mapFromToSource() QCOMPARE(proxy.mapFromSource(proxy.index(6, 2)), QModelIndex()); } +static QStandardItem *addEntry(QStandardItem* pParent, const QString &description) +{ + QStandardItem* pItem = new QStandardItem(description); + pParent->appendRow(pItem); + return pItem; +} + + +void tst_QSortFilterProxyModel::task255652_removeRowsRecursive() +{ + QStandardItemModel pModel; + QStandardItem *pItem1 = new QStandardItem("root"); + pModel.appendRow(pItem1); + QList items; + + QStandardItem *pItem11 = addEntry(pItem1,"Sub-heading"); + items << pItem11; + QStandardItem *pItem111 = addEntry(pItem11,"A"); + items << pItem111; + items << addEntry(pItem111,"A1"); + items << addEntry(pItem111,"A2"); + QStandardItem *pItem112 = addEntry(pItem11,"B"); + items << pItem112; + items << addEntry(pItem112,"B1"); + items << addEntry(pItem112,"B2"); + QStandardItem *pItem1123 = addEntry(pItem112,"B3"); + items << pItem1123; + items << addEntry(pItem1123,"B3-"); + + QSortFilterProxyModel proxy; + proxy.setSourceModel(&pModel); + + QList sourceIndexes; + QList proxyIndexes; + foreach (QStandardItem *item, items) { + QModelIndex idx = item->index(); + sourceIndexes << idx; + proxyIndexes << proxy.mapFromSource(idx); + } + + foreach (const QPersistentModelIndex &pidx, sourceIndexes) + QVERIFY(pidx.isValid()); + foreach (const QPersistentModelIndex &pidx, proxyIndexes) + QVERIFY(pidx.isValid()); + + QList itemRow = pItem1->takeRow(0); + + QCOMPARE(itemRow.count(), 1); + QCOMPARE(itemRow.first(), pItem11); + + foreach (const QPersistentModelIndex &pidx, sourceIndexes) + QVERIFY(!pidx.isValid()); + foreach (const QPersistentModelIndex &pidx, proxyIndexes) + QVERIFY(!pidx.isValid()); + + delete pItem11; +} + QTEST_MAIN(tst_QSortFilterProxyModel) #include "tst_qsortfilterproxymodel.moc" diff --git a/tests/auto/qstandarditemmodel/tst_qstandarditemmodel.cpp b/tests/auto/qstandarditemmodel/tst_qstandarditemmodel.cpp index 84bda92..8067554 100644 --- a/tests/auto/qstandarditemmodel/tst_qstandarditemmodel.cpp +++ b/tests/auto/qstandarditemmodel/tst_qstandarditemmodel.cpp @@ -135,6 +135,7 @@ private slots: void rootItemFlags(); void treeDragAndDrop(); + void removeRowsAndColumns(); private: QAbstractItemModel *m_model; @@ -1403,7 +1404,7 @@ bool tst_QStandardItemModel::compareItems(QStandardItem *item1, QStandardItem *i return true; if (!item1 || !item2) return false; - if (item1->text() != item2->text()){ + if (item1->text() != item2->text()){ qDebug() << item1->text() << item2->text(); return false; } @@ -1606,6 +1607,52 @@ void tst_QStandardItemModel::treeDragAndDrop() } } +void tst_QStandardItemModel::removeRowsAndColumns() +{ +#define VERIFY_MODEL \ + for (int c = 0; c < col_list.count(); c++) \ + for (int r = 0; r < row_list.count(); r++) \ + QCOMPARE(model.item(r,c)->text() , row_list[r] + "x" + col_list[c]); + + QVector row_list = QString("1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20").split(',').toVector(); + QVector col_list = row_list; + QStandardItemModel model; + for (int c = 0; c < col_list.count(); c++) + for (int r = 0; r < row_list.count(); r++) + model.setItem(r, c, new QStandardItem(row_list[r] + "x" + col_list[c])); + VERIFY_MODEL + + row_list.remove(3); + model.removeRow(3); + VERIFY_MODEL + + col_list.remove(5); + model.removeColumn(5); + VERIFY_MODEL + + row_list.remove(2, 5); + model.removeRows(2, 5); + VERIFY_MODEL + + col_list.remove(1, 6); + model.removeColumns(1, 6); + VERIFY_MODEL + + QList row_taken = model.takeRow(6); + QCOMPARE(row_taken.count(), col_list.count()); + for (int c = 0; c < col_list.count(); c++) + QCOMPARE(row_taken[c]->text() , row_list[6] + "x" + col_list[c]); + row_list.remove(6); + VERIFY_MODEL + + QList col_taken = model.takeColumn(10); + QCOMPARE(col_taken.count(), row_list.count()); + for (int r = 0; r < row_list.count(); r++) + QCOMPARE(col_taken[r]->text() , row_list[r] + "x" + col_list[10]); + col_list.remove(10); + VERIFY_MODEL +} + QTEST_MAIN(tst_QStandardItemModel) #include "tst_qstandarditemmodel.moc" -- cgit v0.12 From 0295d0aa5111f31eec8dd8109b4df6389f4efbce Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 11 Jun 2009 11:02:11 +0200 Subject: Clean up qwidget_p.h since the last change Reviewed-by: bnilsen Reviewed-by: Denis --- src/gui/kernel/qwidget_p.h | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/src/gui/kernel/qwidget_p.h b/src/gui/kernel/qwidget_p.h index ff194f7..2bc4da6 100644 --- a/src/gui/kernel/qwidget_p.h +++ b/src/gui/kernel/qwidget_p.h @@ -131,10 +131,6 @@ struct QTLWExtra { uint embedded : 1; // *************************** Platform specific values (bit fields first) ********** -#ifndef QT_NO_XSYNC - int newCounterValueHi : 32; - uint newCounterValueLo : 32; -#endif #if defined(Q_WS_X11) // <----------------------------------------------------------- X11 uint spont_unmapped: 1; // window was spontaneously unmapped uint dnd : 1; // DND properties installed @@ -143,6 +139,12 @@ struct QTLWExtra { WId parentWinId; // parent window Id (valid after reparenting) WId userTimeWindow; // window id that contains user-time timestamp when WM supports a _NET_WM_USER_TIME_WINDOW atom QPoint fullScreenOffset; +#ifndef QT_NO_XSYNC + WId syncUpdateCounter; + ulong syncRequestTimestamp; + qint32 newCounterValueHi; + quint32 newCounterValueLo; +#endif #elif defined(Q_WS_WIN) // <--------------------------------------------------------- WIN HICON winIconBig; // internal big Windows icon HICON winIconSmall; // internal small Windows icon @@ -160,10 +162,6 @@ struct QTLWExtra { QWSManager *qwsManager; #endif #endif -#ifndef QT_NO_XSYNC - WId syncUpdateCounter; - ulong syncRequestTimestamp; -#endif }; struct QWExtra { -- cgit v0.12 From 713e52d9531277b8c13856246701729de16d4502 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 11 Jun 2009 11:11:46 +0200 Subject: Only include QMetaType if required in moc generated files Including it might cause build errors. (and thus break source compatibility) The problem was seen on KDE where some cpp files included x11 headers and then later included the .moc file, then qmetatype.h complains that Bool is defined Reviewed-by: Brad --- src/tools/moc/moc.cpp | 8 ++++++-- src/tools/moc/moc.h | 3 ++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/tools/moc/moc.cpp b/src/tools/moc/moc.cpp index 4629ac5..a1738a5 100644 --- a/src/tools/moc/moc.cpp +++ b/src/tools/moc/moc.cpp @@ -767,7 +767,8 @@ void Moc::generate(FILE *out) if (classList.size() && classList.first().classname == "Qt") fprintf(out, "#include \n"); - fprintf(out, "#include \n"); + if (mustIncludeQMetaTypeH) + fprintf(out, "#include \n"); fprintf(out, "#if !defined(Q_MOC_OUTPUT_REVISION)\n" "#error \"The header file '%s' doesn't include .\"\n", (const char *)fn); @@ -900,6 +901,9 @@ void Moc::parseProperty(ClassDef *def) type = "qlonglong"; else if (type == "ULongLong") type = "qulonglong"; + else if (type == "qreal") + mustIncludeQMetaTypeH = true; + propDef.type = type; next(); @@ -961,7 +965,7 @@ void Moc::parseProperty(ClassDef *def) msg += " has no READ accessor function. The property will be invalid."; warning(msg.constData()); } - if(!propDef.notify.isEmpty()) + if(!propDef.notify.isEmpty()) def->notifyableProperties++; def->propertyList += propDef; diff --git a/src/tools/moc/moc.h b/src/tools/moc/moc.h index 689104c..4a1dee9 100644 --- a/src/tools/moc/moc.h +++ b/src/tools/moc/moc.h @@ -177,13 +177,14 @@ class Moc : public Parser { public: Moc() - : noInclude(false), generatedCode(false) + : noInclude(false), generatedCode(false), mustIncludeQMetaTypeH(false) {} QByteArray filename; bool noInclude; bool generatedCode; + bool mustIncludeQMetaTypeH; QByteArray includePath; QList includeFiles; QList classList; -- cgit v0.12 From f20f242c7d45ad675c6d955628d318ffecdfe517 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 11 Jun 2009 12:07:50 +0200 Subject: Make sure custom arrow images works if we only specify it. Include change for spinbox, combobox, and menu. Task-number: 255849 Tested-by: Pierre Reviewed-by: jbache --- src/gui/styles/qstylesheetstyle.cpp | 18 ++- .../uiloader/baseline/css_task255849_downarrow.ui | 144 +++++++++++++++++++++ tests/auto/uiloader/baseline/images/arrow-down.png | Bin 0 -> 1006 bytes tests/auto/uiloader/baseline/images/arrow-up.png | Bin 0 -> 927 bytes 4 files changed, 158 insertions(+), 4 deletions(-) create mode 100644 tests/auto/uiloader/baseline/css_task255849_downarrow.ui create mode 100644 tests/auto/uiloader/baseline/images/arrow-down.png create mode 100644 tests/auto/uiloader/baseline/images/arrow-up.png diff --git a/src/gui/styles/qstylesheetstyle.cpp b/src/gui/styles/qstylesheetstyle.cpp index 9a8f97e..fe0e53c 100644 --- a/src/gui/styles/qstylesheetstyle.cpp +++ b/src/gui/styles/qstylesheetstyle.cpp @@ -2850,7 +2850,7 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC rule.drawBackgroundImage(p, cmbOpt.rect); rule.configurePalette(&cmbOpt.palette, QPalette::ButtonText, QPalette::Button); bool customDropDown = (opt->subControls & QStyle::SC_ComboBoxArrow) - && hasStyleRule(w, PseudoElement_ComboBoxDropDown); + && (hasStyleRule(w, PseudoElement_ComboBoxDropDown) || hasStyleRule(w, PseudoElement_ComboBoxArrow)); if (customDropDown) cmbOpt.subControls &= ~QStyle::SC_ComboBoxArrow; if (rule.baseStyleCanDraw()) { @@ -2896,11 +2896,11 @@ void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionC if (rule.hasNativeBorder() && !upRuleMatch && !downRuleMatch) { rule.drawBackgroundImage(p, spinOpt.rect); customUp = (opt->subControls & QStyle::SC_SpinBoxUp) - && hasStyleRule(w, PseudoElement_SpinBoxUpButton); + && (hasStyleRule(w, PseudoElement_SpinBoxUpButton) || hasStyleRule(w, PseudoElement_UpArrow)); if (customUp) spinOpt.subControls &= ~QStyle::SC_SpinBoxUp; customDown = (opt->subControls & QStyle::SC_SpinBoxDown) - && hasStyleRule(w, PseudoElement_SpinBoxDownButton); + && (hasStyleRule(w, PseudoElement_SpinBoxDownButton) || hasStyleRule(w, PseudoElement_DownArrow)); if (customDown) spinOpt.subControls &= ~QStyle::SC_SpinBoxDown; if (rule.baseStyleCanDraw()) { @@ -3573,7 +3573,7 @@ void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, Q mi.rect = positionRect(w, subRule, subRule2, PseudoElement_MenuRightArrow, opt->rect, mi.direction); drawPrimitive(arrow, &mi, p, w); } - } else if (hasStyleRule(w, PseudoElement_MenuCheckMark)) { + } else if (hasStyleRule(w, PseudoElement_MenuCheckMark) || hasStyleRule(w, PseudoElement_MenuRightArrow)) { QWindowsStyle::drawControl(ce, &mi, p, w); } else { if (rule.hasDrawable() && !subRule.hasDrawable() && !(opt->state & QStyle::State_Selected)) { @@ -4339,6 +4339,16 @@ void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *op pseudoElement = PseudoElement_ScrollAreaCorner; break; + case PE_IndicatorSpinDown: + case PE_IndicatorSpinMinus: + pseudoElement = PseudoElement_SpinBoxDownArrow; + break; + + case PE_IndicatorSpinUp: + case PE_IndicatorSpinPlus: + pseudoElement = PseudoElement_SpinBoxUpArrow; + break; + default: break; } diff --git a/tests/auto/uiloader/baseline/css_task255849_downarrow.ui b/tests/auto/uiloader/baseline/css_task255849_downarrow.ui new file mode 100644 index 0000000..d3e99b1 --- /dev/null +++ b/tests/auto/uiloader/baseline/css_task255849_downarrow.ui @@ -0,0 +1,144 @@ + + + Form + + + + 0 + 0 + 275 + 175 + + + + Form + + + /* Some widget were not displaying the arrow if only the arrow was set */ +*::down-arrow { image: url("images/arrow-down.png") } +*::up-arrow { image: url("images/arrow-up.png") } + + + + + + + + + + + + true + + + true + + + true + + + + 1 + + + + + New Item + + + + + New Item + + + + + New Item + + + + + New Item + + + + + New Item + + + + + New Item + + + + + New Item + + + + + New Item + + + + + New Item + + + + + New Item + + + + + New Item + + + + + + + + + + + foo + + + Qt::DownArrow + + + + + + + + + + Qt::NoContextMenu + + + PushButton + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + diff --git a/tests/auto/uiloader/baseline/images/arrow-down.png b/tests/auto/uiloader/baseline/images/arrow-down.png new file mode 100644 index 0000000..7c9274f Binary files /dev/null and b/tests/auto/uiloader/baseline/images/arrow-down.png differ diff --git a/tests/auto/uiloader/baseline/images/arrow-up.png b/tests/auto/uiloader/baseline/images/arrow-up.png new file mode 100644 index 0000000..758a0d1 Binary files /dev/null and b/tests/auto/uiloader/baseline/images/arrow-up.png differ -- cgit v0.12 From 0ba0f0ceba0aa9469d965bd97d1cb5f738504ebb Mon Sep 17 00:00:00 2001 From: Markus Goetz Date: Thu, 11 Jun 2009 12:18:17 +0200 Subject: QHttpNetworkConnection: Some renamings Reviewed-by: Prasanth --- src/network/access/qhttpnetworkconnection.cpp | 20 ++++++++++---------- src/network/access/qhttpnetworkconnection_p.h | 11 ++++------- 2 files changed, 14 insertions(+), 17 deletions(-) diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp index 43fbb16..741a9a5 100644 --- a/src/network/access/qhttpnetworkconnection.cpp +++ b/src/network/access/qhttpnetworkconnection.cpp @@ -468,7 +468,7 @@ bool QHttpNetworkConnectionPrivate::sendRequest(QAbstractSocket *socket) return true; } -bool QHttpNetworkConnectionPrivate::emitSignals(QHttpNetworkReply *reply) +bool QHttpNetworkConnectionPrivate::shouldEmitSignals(QHttpNetworkReply *reply) { // for 401 & 407 don't emit the data signals. Content along with these // responses are send only if the authentication fails. @@ -484,7 +484,7 @@ bool QHttpNetworkConnectionPrivate::expectContent(QHttpNetworkReply *reply) || reply->d_func()->statusCode == 204 || reply->d_func()->statusCode == 304) return false; if (reply->d_func()->request.operation() == QHttpNetworkRequest::Head) - return !emitSignals(reply); + return !shouldEmitSignals(reply); if (reply->d_func()->contentLength() == 0) return false; return true; @@ -528,7 +528,7 @@ bool QHttpNetworkConnectionPrivate::expand(QAbstractSocket *socket, QHttpNetwork if (inflated.size()) { reply->d_func()->totalProgress += inflated.size(); appendData(*reply, inflated, false); - if (emitSignals(reply)) { + if (shouldEmitSignals(reply)) { emit reply->readyRead(); // make sure that the reply is valid if (channels[i].reply != reply) @@ -613,7 +613,7 @@ void QHttpNetworkConnectionPrivate::receiveReply(QAbstractSocket *socket, QHttpN reply->d_func()->state = QHttpNetworkReplyPrivate::ReadingStatusState; break; // ignore } - if (emitSignals(reply)) + if (shouldEmitSignals(reply)) emit reply->headerChanged(); if (!expectContent(reply)) { reply->d_func()->state = QHttpNetworkReplyPrivate::AllDoneState; @@ -631,7 +631,7 @@ void QHttpNetworkConnectionPrivate::receiveReply(QAbstractSocket *socket, QHttpN appendData(*reply, fragment.data(), reply->d_func()->autoDecompress); if (!reply->d_func()->autoDecompress) { reply->d_func()->totalProgress += fragment.size(); - if (emitSignals(reply)) { + if (shouldEmitSignals(reply)) { emit reply->readyRead(); // make sure that the reply is valid if (channels[i].reply != reply) @@ -673,7 +673,7 @@ void QHttpNetworkConnectionPrivate::allDone(QAbstractSocket *socket, QHttpNetwor expand(socket, reply, true); // ### if expand returns false, its an error #endif // while handling 401 & 407, we might reset the status code, so save this. - bool emitFinished = emitSignals(reply); + bool emitFinished = shouldEmitSignals(reply); handleStatus(socket, reply); // ### at this point there should be no more data on the socket // close if server requested @@ -828,7 +828,7 @@ bool QHttpNetworkConnectionPrivate::handleAuthenticateChallenge(QAbstractSocket if (priv->phase != QAuthenticatorPrivate::Done) { // send any pending requests copyCredentials(i, auth, isProxy); - QMetaObject::invokeMethod(q, "_q_restartPendingRequest", Qt::QueuedConnection); + QMetaObject::invokeMethod(q, "_q_restartAuthPendingRequests", Qt::QueuedConnection); } } // changing values in QAuthenticator will reset the 'phase' @@ -907,7 +907,7 @@ QHttpNetworkReply* QHttpNetworkConnectionPrivate::queueRequest(const QHttpNetwor return reply; } -void QHttpNetworkConnectionPrivate::unqueueRequest(QAbstractSocket *socket) +void QHttpNetworkConnectionPrivate::unqueueAndSendRequest(QAbstractSocket *socket) { Q_ASSERT(socket); @@ -1112,10 +1112,10 @@ void QHttpNetworkConnectionPrivate::_q_startNextRequest() if (!socket) { return; // this will be called after finishing current request. } - unqueueRequest(socket); + unqueueAndSendRequest(socket); } -void QHttpNetworkConnectionPrivate::_q_restartPendingRequest() +void QHttpNetworkConnectionPrivate::_q_restartAuthPendingRequests() { // send the request using the idle socket for (int i = 0 ; i < channelCount; ++i) { diff --git a/src/network/access/qhttpnetworkconnection_p.h b/src/network/access/qhttpnetworkconnection_p.h index 9b127dd..4603a55 100644 --- a/src/network/access/qhttpnetworkconnection_p.h +++ b/src/network/access/qhttpnetworkconnection_p.h @@ -140,7 +140,7 @@ private: Q_PRIVATE_SLOT(d_func(), void _q_readyRead()) Q_PRIVATE_SLOT(d_func(), void _q_disconnected()) Q_PRIVATE_SLOT(d_func(), void _q_startNextRequest()) - Q_PRIVATE_SLOT(d_func(), void _q_restartPendingRequest()) + Q_PRIVATE_SLOT(d_func(), void _q_restartAuthPendingRequests()) Q_PRIVATE_SLOT(d_func(), void _q_connected()) Q_PRIVATE_SLOT(d_func(), void _q_error(QAbstractSocket::SocketError)) #ifndef QT_NO_NETWORKPROXY @@ -189,7 +189,7 @@ public: bool isSocketReading(QAbstractSocket *socket) const; QHttpNetworkReply *queueRequest(const QHttpNetworkRequest &request); - void unqueueRequest(QAbstractSocket *socket); + void unqueueAndSendRequest(QAbstractSocket *socket); void prepareRequest(HttpMessagePair &request); bool sendRequest(QAbstractSocket *socket); void receiveReply(QAbstractSocket *socket, QHttpNetworkReply *reply); @@ -202,7 +202,7 @@ public: void _q_readyRead(); // pending data to read void _q_disconnected(); // disconnected from host void _q_startNextRequest(); // send the next request from the queue - void _q_restartPendingRequest(); // send the currently blocked request + void _q_restartAuthPendingRequests(); // send the currently blocked request void _q_connected(); // start sending request void _q_error(QAbstractSocket::SocketError); // error from socket #ifndef QT_NO_NETWORKPROXY @@ -261,7 +261,7 @@ public: bool handleAuthenticateChallenge(QAbstractSocket *socket, QHttpNetworkReply *reply, bool isProxy, bool &resend); void allDone(QAbstractSocket *socket, QHttpNetworkReply *reply); void handleStatus(QAbstractSocket *socket, QHttpNetworkReply *reply); - inline bool emitSignals(QHttpNetworkReply *reply); + inline bool shouldEmitSignals(QHttpNetworkReply *reply); inline bool expectContent(QHttpNetworkReply *reply); #ifndef QT_NO_OPENSSL @@ -283,9 +283,6 @@ public: QT_END_NAMESPACE -//Q_DECLARE_METATYPE(QHttpNetworkRequest) -//Q_DECLARE_METATYPE(QHttpNetworkReply) - #endif // QT_NO_HTTP #endif -- cgit v0.12 From 61569e83107e30deb671f37f29ca71989410d8ff Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Morten=20S=C3=B8rvig?= Date: Thu, 11 Jun 2009 13:44:00 +0200 Subject: Make configure pass the -sdk option on to the configure tests. This makes sure that we only detect and use libraries that are actually in the SDK. Task-number: 109757 Reviewed-by: Richard Moe Gustavsen --- config.tests/unix/compile.test | 5 ++++ configure | 60 +++++++++++++++++++++++------------------- 2 files changed, 38 insertions(+), 27 deletions(-) diff --git a/config.tests/unix/compile.test b/config.tests/unix/compile.test index ff51c91..a854bd1 100755 --- a/config.tests/unix/compile.test +++ b/config.tests/unix/compile.test @@ -28,6 +28,11 @@ while [ "$#" -gt 0 ]; do MAC_ARCH_LFLAGS="$MAC_ARCH_LFLAGS -arch $2" shift ;; + -sdk) + LFLAGS="$LFLAGS -Wl,-syslibroot,$2" + CXXFLAGS="$CXXFLAGS -isysroot $2" + shift + ;; -F*|-m*|-x*) LFLAGS="$LFLAGS $PARAM" CXXFLAGS="$CXXFLAGS $PARAM" diff --git a/configure b/configure index 58ab08c..0a8b61a 100755 --- a/configure +++ b/configure @@ -668,7 +668,7 @@ CFG_INOTIFY=auto CFG_RPATH=yes CFG_FRAMEWORK=auto CFG_MAC_ARCHS= -MAC_ARCHS_COMMANDLINE= +MAC_CONFIG_TEST_COMMANDLINE= # used to make the configure tests run with the correct arch's and SDK settings CFG_MAC_DWARF2=auto CFG_MAC_XARCH=auto CFG_MAC_CARBON=yes @@ -2718,14 +2718,20 @@ if [ "$PLATFORM_MAC" = "yes" ]; then # These are synonymous values # CFG_MAC_ARCHS requires x86 while GCC requires i386 CFG_MAC_ARCHS="$CFG_MAC_ARCHS x86" - MAC_ARCHS_COMMANDLINE="$MAC_ARCHS_COMMANDLINE -arch i386" + MAC_CONFIG_TEST_COMMANDLINE="$MAC_CONFIG_TEST_COMMANDLINE -arch i386" else CFG_MAC_ARCHS="$CFG_MAC_ARCHS $i" - MAC_ARCHS_COMMANDLINE="$MAC_ARCHS_COMMANDLINE -arch $i" + MAC_CONFIG_TEST_COMMANDLINE="$MAC_CONFIG_TEST_COMMANDLINE -arch $i" fi done fi +# pass on $CFG_SDK to the configure tests. +if [ '!' -z "$CFG_SDK" ]; then + MAC_CONFIG_TEST_COMMANDLINE="-sdk $CFG_SDK" + echo "tests command line: $MAC_CONFIG_TEST_COMMANDLINE" +fi + # find the default framework value if [ "$PLATFORM_MAC" = "yes" ] && [ "$PLATFORM" != "macx-xlc" ]; then if [ "$CFG_FRAMEWORK" = "auto" ]; then @@ -4263,7 +4269,7 @@ if [ "$CFG_ZLIB" = "no" ]; then ZLIB_FORCED=yes fi if [ "$CFG_ZLIB" = "auto" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/zlib "zlib" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/zlib "zlib" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_ZLIB=system else CFG_ZLIB=yes @@ -4280,7 +4286,7 @@ if [ "$CFG_JPEG" = "auto" ]; then fi # detect jpeg if [ "$CFG_LIBJPEG" = "auto" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/libjpeg "libjpeg" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/libjpeg "libjpeg" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_LIBJPEG=system else CFG_LIBJPEG=qt @@ -4307,7 +4313,7 @@ fi # detect tiff if [ "$CFG_LIBTIFF" = "auto" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/libtiff "libtiff" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/libtiff "libtiff" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_LIBTIFF=system else CFG_LIBTIFF=qt @@ -4324,7 +4330,7 @@ if [ "$CFG_MNG" = "auto" ]; then fi # detect mng if [ "$CFG_LIBMNG" = "auto" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/libmng "libmng" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/libmng "libmng" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_LIBMNG=system else CFG_LIBMNG=qt @@ -4333,7 +4339,7 @@ fi # detect png if [ "$CFG_LIBPNG" = "auto" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/libpng "libpng" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/libpng "libpng" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_LIBPNG=system else CFG_LIBPNG=qt @@ -4372,13 +4378,13 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do QT_CFLAGS_MYSQL="" fi else - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/mysql_r "MySQL (thread-safe)" $QT_LFLAGS_MYSQL_R $L_FLAGS $QT_CFLAGS_MYSQL $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/mysql_r "MySQL (thread-safe)" $QT_LFLAGS_MYSQL_R $L_FLAGS $QT_CFLAGS_MYSQL $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then QMakeVar add CONFIG use_libmysqlclient_r if [ "$CFG_SQL_mysql" = "auto" ]; then CFG_SQL_mysql=plugin fi QT_LFLAGS_MYSQL="$QT_LFLAGS_MYSQL_R" - elif "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/mysql "MySQL (thread-unsafe)" $QT_LFLAGS_MYSQL $L_FLAGS $QT_CFLAGS_MYSQL $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + elif "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/mysql "MySQL (thread-unsafe)" $QT_LFLAGS_MYSQL $L_FLAGS $QT_CFLAGS_MYSQL $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_mysql" = "auto" ]; then CFG_SQL_mysql=plugin fi @@ -4407,7 +4413,7 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do fi [ -z "$QT_CFLAGS_PSQL" ] || QT_CFLAGS_PSQL="-I$QT_CFLAGS_PSQL" [ -z "$QT_LFLAGS_PSQL" ] || QT_LFLAGS_PSQL="-L$QT_LFLAGS_PSQL" - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/psql "PostgreSQL" $QT_LFLAGS_PSQL $L_FLAGS $QT_CFLAGS_PSQL $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/psql "PostgreSQL" $QT_LFLAGS_PSQL $L_FLAGS $QT_CFLAGS_PSQL $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_psql" = "auto" ]; then CFG_SQL_psql=plugin fi @@ -4428,12 +4434,12 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do ;; odbc) if [ "$CFG_SQL_odbc" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/odbc "ODBC" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/odbc "ODBC" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_odbc" = "auto" ]; then CFG_SQL_odbc=plugin fi else - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/iodbc "iODBC" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/iodbc "iODBC" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then QT_LFLAGS_ODBC="-liodbc" if [ "$CFG_SQL_odbc" = "auto" ]; then CFG_SQL_odbc=plugin @@ -4454,7 +4460,7 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do ;; oci) if [ "$CFG_SQL_oci" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/oci "OCI" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/oci "OCI" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_oci" = "auto" ]; then CFG_SQL_oci=plugin fi @@ -4473,7 +4479,7 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do ;; tds) if [ "$CFG_SQL_tds" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/tds "TDS" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/tds "TDS" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_tds" = "auto" ]; then CFG_SQL_tds=plugin fi @@ -4492,7 +4498,7 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do ;; db2) if [ "$CFG_SQL_db2" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/db2 "DB2" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/db2 "DB2" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_db2" = "auto" ]; then CFG_SQL_db2=plugin fi @@ -4511,7 +4517,7 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do ;; ibase) if [ "$CFG_SQL_ibase" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/ibase "InterBase" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/ibase "InterBase" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_ibase" = "auto" ]; then CFG_SQL_ibase=plugin fi @@ -4530,7 +4536,7 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do ;; sqlite2) if [ "$CFG_SQL_sqlite2" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/sqlite2 "SQLite2" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/sqlite2 "SQLite2" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_sqlite2" = "auto" ]; then CFG_SQL_sqlite2=plugin fi @@ -4555,7 +4561,7 @@ for _SQLDR in $CFG_SQL_AVAILABLE; do QT_CFLAGS_SQLITE=`$PKG_CONFIG --cflags sqlite3 2>/dev/null` QT_LFLAGS_SQLITE=`$PKG_CONFIG --libs sqlite3 2>/dev/null` fi - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/sqlite "SQLite" $QT_LFLAGS_SQLITE $L_FLAGS $QT_CFLAGS_SQLITE $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/sqlite "SQLite" $QT_LFLAGS_SQLITE $L_FLAGS $QT_CFLAGS_SQLITE $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_SQL_sqlite" = "auto" ]; then CFG_SQL_sqlite=plugin fi @@ -4592,7 +4598,7 @@ done # auto-detect NIS support if [ "$CFG_NIS" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/nis "NIS" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/nis "NIS" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_NIS=yes else if [ "$CFG_NIS" = "yes" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then @@ -4609,7 +4615,7 @@ fi # auto-detect CUPS support if [ "$CFG_CUPS" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/cups "Cups" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/cups "Cups" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_CUPS=yes else if [ "$CFG_CUPS" = "yes" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then @@ -4628,9 +4634,9 @@ fi if [ "$CFG_ICONV" != "no" ]; then if [ "$PLATFORM_QWS" = "yes" ]; then CFG_ICONV=no - elif "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" "$OPT_VERBOSE" "$relpath" "$outpath" "config.tests/unix/iconv" "POSIX iconv" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + elif "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" "$OPT_VERBOSE" "$relpath" "$outpath" "config.tests/unix/iconv" "POSIX iconv" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_ICONV=yes - elif "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" "$OPT_VERBOSE" "$relpath" "$outpath" "config.tests/unix/gnu-libiconv" "GNU libiconv" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + elif "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" "$OPT_VERBOSE" "$relpath" "$outpath" "config.tests/unix/gnu-libiconv" "GNU libiconv" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_ICONV=gnu else if [ "$CFG_ICONV" = "yes" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then @@ -4651,7 +4657,7 @@ if [ "$CFG_DBUS" != "no" ]; then QT_CFLAGS_DBUS=`$PKG_CONFIG --cflags dbus-1 2>/dev/null` QT_LIBS_DBUS=`$PKG_CONFIG --libs dbus-1 2>/dev/null` fi - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/dbus "D-Bus" $L_FLAGS $I_FLAGS $l_FLAGS $QT_CFLAGS_DBUS $QT_LIBS_DBUS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/dbus "D-Bus" $L_FLAGS $I_FLAGS $l_FLAGS $QT_CFLAGS_DBUS $QT_LIBS_DBUS $MAC_CONFIG_TEST_COMMANDLINE; then [ "$CFG_DBUS" = "auto" ] && CFG_DBUS=yes QMakeVar set QT_CFLAGS_DBUS "$QT_CFLAGS_DBUS" QMakeVar set QT_LIBS_DBUS "$QT_LIBS_DBUS" @@ -5228,7 +5234,7 @@ fi # QWS [ "x$CFG_EMBEDDED" != "xno" ] && CFG_LIBFREETYPE="$CFG_QWS_FREETYPE" [ "x$PLATFORM_MAC" = "xyes" ] && CFG_LIBFREETYPE=no if [ "$CFG_LIBFREETYPE" = "auto" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/freetype "FreeType" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/freetype "FreeType" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_LIBFREETYPE=system else CFG_LIBFREETYPE=yes @@ -5345,7 +5351,7 @@ fi # find if the platform supports IPv6 if [ "$CFG_IPV6" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/ipv6 "IPv6" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/ipv6 "IPv6" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then CFG_IPV6=yes else if [ "$CFG_IPV6" = "yes" ] && [ "$CFG_CONFIGURE_EXIT_ON_ERROR" = "yes" ]; then @@ -5476,7 +5482,7 @@ fi # detect OpenSSL if [ "$CFG_OPENSSL" != "no" ]; then - if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/openssl "OpenSSL" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_ARCHS_COMMANDLINE; then + if "$unixtests/compile.test" "$XQMAKESPEC" "$QMAKE_CONFIG" $OPT_VERBOSE "$relpath" "$outpath" config.tests/unix/openssl "OpenSSL" $L_FLAGS $I_FLAGS $l_FLAGS $MAC_CONFIG_TEST_COMMANDLINE; then if [ "$CFG_OPENSSL" = "auto" ]; then CFG_OPENSSL=yes fi -- cgit v0.12 From d91a4e137556854f2d9c9a3fea5f480acd0e62c2 Mon Sep 17 00:00:00 2001 From: Markus Goetz Date: Thu, 11 Jun 2009 12:24:43 +0200 Subject: QHttpNetworkConnection: Removed an unnecessary/dead check --- src/network/access/qhttpnetworkconnection.cpp | 25 +++++++++++-------------- src/network/access/qhttpnetworkreply.cpp | 2 +- src/network/access/qhttpnetworkreply_p.h | 1 - 3 files changed, 12 insertions(+), 16 deletions(-) diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp index 741a9a5..abaa7fb 100644 --- a/src/network/access/qhttpnetworkconnection.cpp +++ b/src/network/access/qhttpnetworkconnection.cpp @@ -918,13 +918,12 @@ void QHttpNetworkConnectionPrivate::unqueueAndSendRequest(QAbstractSocket *socke HttpMessagePair &messagePair = highPriorityQueue[j]; if (!messagePair.second->d_func()->requestIsPrepared) prepareRequest(messagePair); - if (!messagePair.second->d_func()->requestIsBuffering) { - channels[i].request = messagePair.first; - channels[i].reply = messagePair.second; - sendRequest(socket); - highPriorityQueue.removeAt(j); - return; - } + + channels[i].request = messagePair.first; + channels[i].reply = messagePair.second; + sendRequest(socket); + highPriorityQueue.removeAt(j); + return; } } @@ -933,13 +932,11 @@ void QHttpNetworkConnectionPrivate::unqueueAndSendRequest(QAbstractSocket *socke HttpMessagePair &messagePair = lowPriorityQueue[j]; if (!messagePair.second->d_func()->requestIsPrepared) prepareRequest(messagePair); - if (!messagePair.second->d_func()->requestIsBuffering) { - channels[i].request = messagePair.first; - channels[i].reply = messagePair.second; - sendRequest(socket); - lowPriorityQueue.removeAt(j); - return; - } + channels[i].request = messagePair.first; + channels[i].reply = messagePair.second; + sendRequest(socket); + lowPriorityQueue.removeAt(j); + return; } } } diff --git a/src/network/access/qhttpnetworkreply.cpp b/src/network/access/qhttpnetworkreply.cpp index 310994c..88b1a44 100644 --- a/src/network/access/qhttpnetworkreply.cpp +++ b/src/network/access/qhttpnetworkreply.cpp @@ -187,7 +187,7 @@ QHttpNetworkReplyPrivate::QHttpNetworkReplyPrivate(const QUrl &newUrl) : QHttpNetworkHeaderPrivate(newUrl), state(NothingDoneState), statusCode(100), majorVersion(0), minorVersion(0), bodyLength(0), contentRead(0), totalProgress(0), currentChunkSize(0), currentChunkRead(0), connection(0), initInflate(false), - autoDecompress(false), requestIsBuffering(false), requestIsPrepared(false) + autoDecompress(false), requestIsPrepared(false) { } diff --git a/src/network/access/qhttpnetworkreply_p.h b/src/network/access/qhttpnetworkreply_p.h index cc5cce8..eff1da3 100644 --- a/src/network/access/qhttpnetworkreply_p.h +++ b/src/network/access/qhttpnetworkreply_p.h @@ -206,7 +206,6 @@ public: QByteArray responseData; // uncompressed body QByteArray compressedData; // compressed body (temporary) - bool requestIsBuffering; bool requestIsPrepared; }; -- cgit v0.12 From 5f31403e74c4eaf89a213ce3514fe380d221298b Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Thu, 11 Jun 2009 13:58:42 +0200 Subject: doc: Fixed several qdoc warnings. --- src/corelib/tools/qcontiguouscache.cpp | 7 ------- src/corelib/tools/qstringbuilder.cpp | 10 +++++----- src/gui/painting/qdrawutil.cpp | 4 ++-- tools/qdoc3/test/qt-cpp-ignore.qdocconf | 3 ++- tools/qdoc3/test/qt-inc.qdocconf | 3 ++- 5 files changed, 11 insertions(+), 16 deletions(-) diff --git a/src/corelib/tools/qcontiguouscache.cpp b/src/corelib/tools/qcontiguouscache.cpp index 996ac18..fc75cc0 100644 --- a/src/corelib/tools/qcontiguouscache.cpp +++ b/src/corelib/tools/qcontiguouscache.cpp @@ -429,11 +429,4 @@ MyRecord record(int row) const \sa normalizeIndexes(), append(), prepend() */ -/*! \fn void QContiguousCache::dump() const - - \internal - - Sends information about the cache's internal structure to qDebug() -*/ - QT_END_NAMESPACE diff --git a/src/corelib/tools/qstringbuilder.cpp b/src/corelib/tools/qstringbuilder.cpp index 740deb4..366a07b 100644 --- a/src/corelib/tools/qstringbuilder.cpp +++ b/src/corelib/tools/qstringbuilder.cpp @@ -64,17 +64,17 @@ \sa QStringBuilder, QLatin1String, QString, QStringRef */ -/*! \fn QLatin1Literal::QLatin1Literal(const char(&string)[N]) - - Constructs a new literal from the given \a string. -*/ - /*! \fn int QLatin1Literal::size() const Returns the number of characters in the literal \e{excluding} the trailing NULL char. */ +/*! \fn QLatin1Literal::QLatin1Literal(const char(&string)[N]) + + Constructs a new literal from the given \a string. +*/ + /*! \fn char *QLatin1Literal::data() const Returns a pointer to the first character of the string literal. diff --git a/src/gui/painting/qdrawutil.cpp b/src/gui/painting/qdrawutil.cpp index 230d30b..4020593 100644 --- a/src/gui/painting/qdrawutil.cpp +++ b/src/gui/painting/qdrawutil.cpp @@ -1039,7 +1039,7 @@ void qDrawItem(QPainter *p, Qt::GUIStyle gs, #endif /*! - \struct QMargins + \class QMargins \since 4.6 Holds the borders used to split a pixmap into nine segments in order to @@ -1050,7 +1050,7 @@ void qDrawItem(QPainter *p, Qt::GUIStyle gs, */ /*! - \struct QTileRules + \class QTileRules \since 4.6 Holds the rules used to draw a pixmap or image split into nine segments, diff --git a/tools/qdoc3/test/qt-cpp-ignore.qdocconf b/tools/qdoc3/test/qt-cpp-ignore.qdocconf index 107c692..cfb3afd 100644 --- a/tools/qdoc3/test/qt-cpp-ignore.qdocconf +++ b/tools/qdoc3/test/qt-cpp-ignore.qdocconf @@ -65,7 +65,8 @@ Cpp.ignoretokens = QAXFACTORY_EXPORT \ QT_BEGIN_INCLUDE_NAMESPACE \ QT_END_NAMESPACE \ QT_END_INCLUDE_NAMESPACE \ - PHONON_EXPORT + PHONON_EXPORT \ + Q_GADGET Cpp.ignoredirectives = Q_DECLARE_HANDLE \ Q_DECLARE_INTERFACE \ Q_DECLARE_METATYPE \ diff --git a/tools/qdoc3/test/qt-inc.qdocconf b/tools/qdoc3/test/qt-inc.qdocconf index d6cb0e6..01b07b3 100644 --- a/tools/qdoc3/test/qt-inc.qdocconf +++ b/tools/qdoc3/test/qt-inc.qdocconf @@ -99,7 +99,8 @@ Cpp.ignoretokens = QAXFACTORY_EXPORT \ Q_TESTLIB_EXPORT \ Q_TYPENAME \ Q_XML_EXPORT \ - QDBUS_EXPORT + QDBUS_EXPORT \ + Q_GADGET Cpp.ignoredirectives = Q_DECLARE_HANDLE \ Q_DECLARE_INTERFACE \ Q_DECLARE_METATYPE \ -- cgit v0.12 From dc802d17d998b62546de0a9725535202d7cbf9e4 Mon Sep 17 00:00:00 2001 From: Thomas Zander Date: Thu, 11 Jun 2009 13:12:30 +0200 Subject: Makes the ODF writer use one text:tab tag for each tab, per ODF spec. We used tab-ref to place multiple tabs compressed into one tag just like text:s does, but thats not what the spec says. We now don't sum up tabs anymore but just simply write out one "" tag per tab. Task: 249110 --- src/gui/text/qtextodfwriter.cpp | 51 +++++++++++------------- tests/auto/qtextodfwriter/tst_qtextodfwriter.cpp | 2 +- 2 files changed, 24 insertions(+), 29 deletions(-) diff --git a/src/gui/text/qtextodfwriter.cpp b/src/gui/text/qtextodfwriter.cpp index 75e89d2..bc8ac5b 100644 --- a/src/gui/text/qtextodfwriter.cpp +++ b/src/gui/text/qtextodfwriter.cpp @@ -295,28 +295,13 @@ void QTextOdfWriter::writeBlock(QXmlStreamWriter &writer, const QTextBlock &bloc writer.writeAttribute(textNS, QString::fromLatin1("style-name"), QString::fromLatin1("c%1") .arg(frag.fragment().charFormatIndex())); bool escapeNextSpace = true; - int precedingSpaces = 0, precedingTabs = 0; + int precedingSpaces = 0; int exportedIndex = 0; for (int i=0; i <= fragmentText.count(); ++i) { - bool isTab = false, isSpace = false; - if (i < fragmentText.count()) { + bool isSpace = false; QChar character = fragmentText[i]; - isTab = character.unicode() == '\t'; isSpace = character.unicode() == ' '; - if (character.unicode() == 0x2028) { // soft-return - writer.writeCharacters(fragmentText.mid(exportedIndex, i)); - writer.writeEmptyElement(textNS, QString::fromLatin1("line-break")); - exportedIndex = i+1; - continue; - } - if (isSpace) { - ++precedingSpaces; - escapeNextSpace = true; - } - else if (isTab) { - precedingTabs++; - } - } + // find more than one space. -> if (!isSpace && escapeNextSpace && precedingSpaces > 1) { const bool startParag = exportedIndex == 0 && i == precedingSpaces; @@ -329,17 +314,27 @@ void QTextOdfWriter::writeBlock(QXmlStreamWriter &writer, const QTextBlock &bloc precedingSpaces = 0; exportedIndex = i; } - // find tabs. -> or - if (!isTab && precedingTabs) { - writer.writeCharacters(fragmentText.mid(exportedIndex, i - precedingTabs - exportedIndex)); - writer.writeEmptyElement(textNS, QString::fromLatin1("tab")); - if (precedingTabs > 1) - writer.writeAttribute(textNS, QString::fromLatin1("tab-ref"), QString::number(precedingTabs)); - precedingTabs = 0; - exportedIndex = i; + + if (i < fragmentText.count()) { + if (character.unicode() == 0x2028) { // soft-return + //if (exportedIndex < i) + writer.writeCharacters(fragmentText.mid(exportedIndex, i - exportedIndex)); + writer.writeEmptyElement(textNS, QString::fromLatin1("line-break")); + exportedIndex = i+1; + continue; + } else if (character.unicode() == '\t') { // Tab + //if (exportedIndex < i) + writer.writeCharacters(fragmentText.mid(exportedIndex, i - exportedIndex)); + writer.writeEmptyElement(textNS, QString::fromLatin1("tab")); + exportedIndex = i+1; + precedingSpaces = 0; + } else if (isSpace) { + ++precedingSpaces; + escapeNextSpace = true; + } else if (!isSpace) { + precedingSpaces = 0; + } } - if (!isSpace && !isTab) - precedingSpaces = 0; } writer.writeCharacters(fragmentText.mid(exportedIndex)); diff --git a/tests/auto/qtextodfwriter/tst_qtextodfwriter.cpp b/tests/auto/qtextodfwriter/tst_qtextodfwriter.cpp index f92e30f..f8c7cdf 100644 --- a/tests/auto/qtextodfwriter/tst_qtextodfwriter.cpp +++ b/tests/auto/qtextodfwriter/tst_qtextodfwriter.cpp @@ -133,7 +133,7 @@ void tst_QTextOdfWriter::testWriteParagraph_data() QTest::newRow("tab") << "word\ttab x" << "wordtab x"; QTest::newRow("tab2") << "word\t\ttab\tx" << - "wordtabx"; + "wordtabx"; QTest::newRow("misc") << "foobar word\ttab x" << "foobar wordtab x"; QTest::newRow("misc2") << "\t \tFoo" << -- cgit v0.12 From 26f55ab3ebbb7d1aa7a218cc3373224acc482c56 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Thu, 11 Jun 2009 15:21:44 +0200 Subject: doc: Fixed several qdoc warnings. --- src/gui/graphicsview/qgraphicsitem.cpp | 9 ++++++--- src/gui/painting/qpainterpath.cpp | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 0390a83..43cbca1 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -3064,7 +3064,7 @@ QPointF QGraphicsItem::transformOrigin() const /*! \since 4.6 - Sets the origin for transformation in item coordinate + Sets the \a origin for transformation in item coordinate \sa transformOrigin(), {Transformations} */ @@ -3079,11 +3079,14 @@ void QGraphicsItem::setTransformOrigin(const QPointF &origin) } /*! - \fn inline void setTransformOrigin(qreal x, qreal y) + \fn void QGraphicsItem::setTransformOrigin(qreal x, qreal y) \since 4.6 \overload + Sets the origin for the transformation to the point + composed of \a x and \a y. + \sa setTransformOrigin(), {Transformations} */ @@ -6483,7 +6486,7 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent */ /*! - \property QGraphicsObject:y + \property QGraphicsObject::y \brief the y position of the item Describes the items y position. diff --git a/src/gui/painting/qpainterpath.cpp b/src/gui/painting/qpainterpath.cpp index e1bb317..2f3a0cb 100644 --- a/src/gui/painting/qpainterpath.cpp +++ b/src/gui/painting/qpainterpath.cpp @@ -2049,7 +2049,7 @@ QPainterPath QPainterPath::translated(qreal dx, qreal dy) const } /*! - \fn void QPainterPath::translated(const QPointF &offset) + \fn QPainterPath QPainterPath::translated(const QPointF &offset) const; \overload \since 4.6 -- cgit v0.12 From f0a4a37a5182660580fd361110d3fd51463221d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Thu, 11 Jun 2009 14:25:40 +0200 Subject: Fixed clipping bugs due to not accounting for the redirection offset. Also, updateInvMatrix() can be greatly simplified as updateMatrix() is always called whenever anything related to the state matrix changes, so we can assume that it's up-to-date. Reviewed-by: bnilsen --- src/gui/painting/qpainter.cpp | 29 +++++++++-------------------- 1 file changed, 9 insertions(+), 20 deletions(-) diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index 0ece498..528c575 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -414,7 +414,7 @@ void QPainterPrivate::draw_helper(const QPainterPath &originalPath, DrawOperatio bool old_txinv = txinv; QTransform old_invMatrix = invMatrix; txinv = true; - invMatrix = state->redirectionMatrix; + invMatrix = state->redirectionMatrix.inverted(); QPainterPath clipPath = q->clipPath(); QRectF r = clipPath.boundingRect().intersected(absPathRect); absPathRect = r.toAlignedRect(); @@ -653,18 +653,7 @@ void QPainterPrivate::updateInvMatrix() { Q_ASSERT(txinv == false); txinv = true; // creating inverted matrix - QTransform m; - - if (state->VxF) - m = viewTransform(); - - if (state->WxF) { - if (state->VxF) - m = state->worldMatrix * m; - else - m = state->worldMatrix; - } - invMatrix = m.inverted(); // invert matrix + invMatrix = state->matrix.inverted(); } void QPainterPrivate::updateEmulationSpecifier(QPainterState *s) @@ -2569,7 +2558,7 @@ void QPainter::setClipRect(const QRectF &rect, Qt::ClipOperation op) QVectorPath vp(pts, 4, 0, QVectorPath::RectangleHint); d->state->clipEnabled = true; d->extended->clip(vp, op); - d->state->clipInfo << QPainterClipInfo(rect, op, combinedTransform()); + d->state->clipInfo << QPainterClipInfo(rect, op, d->state->matrix); d->state->clipOperation = op; return; } @@ -2612,7 +2601,7 @@ void QPainter::setClipRect(const QRect &rect, Qt::ClipOperation op) if (d->extended) { d->state->clipEnabled = true; d->extended->clip(rect, op); - d->state->clipInfo << QPainterClipInfo(rect, op, combinedTransform()); + d->state->clipInfo << QPainterClipInfo(rect, op, d->state->matrix); d->state->clipOperation = op; return; } @@ -2624,7 +2613,7 @@ void QPainter::setClipRect(const QRect &rect, Qt::ClipOperation op) d->state->clipOperation = op; if (op == Qt::NoClip || op == Qt::ReplaceClip) d->state->clipInfo.clear(); - d->state->clipInfo << QPainterClipInfo(rect, op, combinedTransform()); + d->state->clipInfo << QPainterClipInfo(rect, op, d->state->matrix); d->state->clipEnabled = true; d->state->dirtyFlags |= QPaintEngine::DirtyClipRegion | QPaintEngine::DirtyClipEnabled; d->updateState(d->state); @@ -2665,7 +2654,7 @@ void QPainter::setClipRegion(const QRegion &r, Qt::ClipOperation op) if (d->extended) { d->state->clipEnabled = true; d->extended->clip(r, op); - d->state->clipInfo << QPainterClipInfo(r, op, combinedTransform()); + d->state->clipInfo << QPainterClipInfo(r, op, d->state->matrix); d->state->clipOperation = op; return; } @@ -2677,7 +2666,7 @@ void QPainter::setClipRegion(const QRegion &r, Qt::ClipOperation op) d->state->clipOperation = op; if (op == Qt::NoClip || op == Qt::ReplaceClip) d->state->clipInfo.clear(); - d->state->clipInfo << QPainterClipInfo(r, op, combinedTransform()); + d->state->clipInfo << QPainterClipInfo(r, op, d->state->matrix); d->state->clipEnabled = true; d->state->dirtyFlags |= QPaintEngine::DirtyClipRegion | QPaintEngine::DirtyClipEnabled; d->updateState(d->state); @@ -3062,7 +3051,7 @@ void QPainter::setClipPath(const QPainterPath &path, Qt::ClipOperation op) if (d->extended) { d->state->clipEnabled = true; d->extended->clip(path, op); - d->state->clipInfo << QPainterClipInfo(path, op, combinedTransform()); + d->state->clipInfo << QPainterClipInfo(path, op, d->state->matrix); d->state->clipOperation = op; return; } @@ -3076,7 +3065,7 @@ void QPainter::setClipPath(const QPainterPath &path, Qt::ClipOperation op) d->state->clipOperation = op; if (op == Qt::NoClip || op == Qt::ReplaceClip) d->state->clipInfo.clear(); - d->state->clipInfo << QPainterClipInfo(path, op, combinedTransform()); + d->state->clipInfo << QPainterClipInfo(path, op, d->state->matrix); d->state->clipEnabled = true; d->state->dirtyFlags |= QPaintEngine::DirtyClipPath | QPaintEngine::DirtyClipEnabled; d->updateState(d->state); -- cgit v0.12 From 0f60b6e05a707630e02655c60ae60884262a4b8e Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 11 Jun 2009 10:51:54 +0200 Subject: remove q->layout() and q->parentWidget() code where unnecessary --- src/corelib/io/qfile.cpp | 6 +- src/corelib/statemachine/qabstractstate.cpp | 3 +- src/corelib/statemachine/qabstracttransition.cpp | 6 +- src/gui/dialogs/qmessagebox.cpp | 14 ++--- src/gui/itemviews/qtreewidget.cpp | 10 ++-- src/gui/kernel/qapplication_win.cpp | 10 ++-- src/gui/kernel/qwidget.cpp | 8 +-- src/gui/widgets/qdockwidget.cpp | 75 ++++++++++++------------ src/gui/widgets/qmdiarea.cpp | 2 +- src/gui/widgets/qmdisubwindow.cpp | 12 ++-- src/gui/widgets/qmdisubwindow_p.h | 2 +- src/gui/widgets/qpushbutton.cpp | 2 +- src/gui/widgets/qspinbox.cpp | 13 ++-- src/gui/widgets/qsplitter.cpp | 2 +- src/gui/widgets/qtoolbar.cpp | 8 +-- src/gui/widgets/qtoolbutton.cpp | 4 +- 16 files changed, 84 insertions(+), 93 deletions(-) diff --git a/src/corelib/io/qfile.cpp b/src/corelib/io/qfile.cpp index 4deaddb..bfb1aae 100644 --- a/src/corelib/io/qfile.cpp +++ b/src/corelib/io/qfile.cpp @@ -154,17 +154,15 @@ QFilePrivate::setError(QFile::FileError err) void QFilePrivate::setError(QFile::FileError err, const QString &errStr) { - Q_Q(QFile); error = err; - q->setErrorString(errStr); + errorString = errStr; } void QFilePrivate::setError(QFile::FileError err, int errNum) { - Q_Q(QFile); error = err; - q->setErrorString(qt_error_string(errNum)); + errorString = qt_error_string(errNum); } //************* QFile diff --git a/src/corelib/statemachine/qabstractstate.cpp b/src/corelib/statemachine/qabstractstate.cpp index b9a50a2..973057b 100644 --- a/src/corelib/statemachine/qabstractstate.cpp +++ b/src/corelib/statemachine/qabstractstate.cpp @@ -89,8 +89,7 @@ QAbstractStatePrivate *QAbstractStatePrivate::get(QAbstractState *q) QStateMachine *QAbstractStatePrivate::machine() const { - Q_Q(const QAbstractState); - QObject *par = q->parent(); + QObject *par = parent; while (par != 0) { if (QStateMachine *mach = qobject_cast(par)) return mach; diff --git a/src/corelib/statemachine/qabstracttransition.cpp b/src/corelib/statemachine/qabstracttransition.cpp index f582b8c..c1b553c 100644 --- a/src/corelib/statemachine/qabstracttransition.cpp +++ b/src/corelib/statemachine/qabstracttransition.cpp @@ -113,8 +113,7 @@ QAbstractTransitionPrivate *QAbstractTransitionPrivate::get(QAbstractTransition QStateMachine *QAbstractTransitionPrivate::machine() const { - Q_Q(const QAbstractTransition); - QObject *par = q->parent(); + QObject *par = parent; while (par != 0) { if (QStateMachine *mach = qobject_cast(par)) return mach; @@ -137,8 +136,7 @@ void QAbstractTransitionPrivate::callOnTransition(QEvent *e) QState *QAbstractTransitionPrivate::sourceState() const { - Q_Q(const QAbstractTransition); - return qobject_cast(q->parent()); + return qobject_cast(parent); } /*! diff --git a/src/gui/dialogs/qmessagebox.cpp b/src/gui/dialogs/qmessagebox.cpp index 648cda8..c526c7d 100644 --- a/src/gui/dialogs/qmessagebox.cpp +++ b/src/gui/dialogs/qmessagebox.cpp @@ -258,10 +258,8 @@ void QMessageBoxPrivate::init(const QString &title, const QString &text) int QMessageBoxPrivate::layoutMinimumWidth() { - Q_Q(QMessageBox); - - q->layout()->activate(); - return q->layout()->totalMinimumSize().width(); + layout->activate(); + return layout->totalMinimumSize().width(); } void QMessageBoxPrivate::updateSize() @@ -339,10 +337,10 @@ void QMessageBoxPrivate::updateSize() if (windowTitleWidth > width) width = windowTitleWidth; - q->layout()->activate(); - int height = (q->layout()->hasHeightForWidth()) - ? q->layout()->totalHeightForWidth(width) - : q->layout()->totalMinimumSize().height(); + layout->activate(); + int height = (layout->hasHeightForWidth()) + ? layout->totalHeightForWidth(width) + : layout->totalMinimumSize().height(); q->setFixedSize(width, height); QCoreApplication::removePostedEvents(q, QEvent::LayoutRequest); } diff --git a/src/gui/itemviews/qtreewidget.cpp b/src/gui/itemviews/qtreewidget.cpp index 5604f8d..24713c4 100644 --- a/src/gui/itemviews/qtreewidget.cpp +++ b/src/gui/itemviews/qtreewidget.cpp @@ -2280,10 +2280,9 @@ void QTreeWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex ¤t, void QTreeWidgetPrivate::_q_sort() { - Q_Q(QTreeWidget); if (sortingEnabled) { - int column = q->header()->sortIndicatorSection(); - Qt::SortOrder order = q->header()->sortIndicatorOrder(); + int column = header->sortIndicatorSection(); + Qt::SortOrder order = header->sortIndicatorOrder(); model()->sort(column, order); } } @@ -2311,12 +2310,11 @@ void QTreeWidgetPrivate::_q_selectionChanged(const QItemSelection &selected, con void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { - Q_Q(QTreeWidget); if (sortingEnabled && topLeft.isValid() && bottomRight.isValid() && !model()->sortPendingTimer.isActive()) { - int column = q->header()->sortIndicatorSection(); + int column = header->sortIndicatorSection(); if (column >= topLeft.column() && column <= bottomRight.column()) { - Qt::SortOrder order = q->header()->sortIndicatorOrder(); + Qt::SortOrder order = header->sortIndicatorOrder(); model()->ensureSorted(column, order, topLeft.row(), bottomRight.row(), topLeft.parent()); } diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index b21eb36..8d77c4c 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -2748,9 +2748,9 @@ void QApplicationPrivate::openPopup(QWidget *popup) if (popup->focusWidget()) { popup->focusWidget()->setFocus(Qt::PopupFocusReason); } else if (QApplicationPrivate::popupWidgets->count() == 1) { // this was the first popup - if (QWidget *fw = q_func()->focusWidget()) { + if (QWidget *fw = QApplication::focusWidget()) { QFocusEvent e(QEvent::FocusOut, Qt::PopupFocusReason); - q_func()->sendEvent(fw, &e); + QApplication::sendEvent(fw, &e); } } } @@ -2777,13 +2777,13 @@ void QApplicationPrivate::closePopup(QWidget *popup) if (!qt_nograb()) // grabbing not disabled releaseAutoCapture(); QWidget *fw = QApplicationPrivate::active_window ? QApplicationPrivate::active_window->focusWidget() - : q_func()->focusWidget(); + : QApplication::focusWidget(); if (fw) { - if (fw != q_func()->focusWidget()) { + if (fw != QApplication::focusWidget()) { fw->setFocus(Qt::PopupFocusReason); } else { QFocusEvent e(QEvent::FocusIn, Qt::PopupFocusReason); - q_func()->sendEvent(fw, &e); + QApplication::sendEvent(fw, &e); } } } else { diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index 61d8f20..230b8f6 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -7268,10 +7268,10 @@ QSize QWidgetPrivate::adjustedSize() const if (q->isWindow()) { Qt::Orientations exp; - if (QLayout *l = q->layout()) { - if (l->hasHeightForWidth()) - s.setHeight(l->totalHeightForWidth(s.width())); - exp = l->expandingDirections(); + if (layout) { + if (layout->hasHeightForWidth()) + s.setHeight(layout->totalHeightForWidth(s.width())); + exp = layout->expandingDirections(); } else { if (q->sizePolicy().hasHeightForWidth()) diff --git a/src/gui/widgets/qdockwidget.cpp b/src/gui/widgets/qdockwidget.cpp index 6a0c879..30f9a87 100644 --- a/src/gui/widgets/qdockwidget.cpp +++ b/src/gui/widgets/qdockwidget.cpp @@ -69,6 +69,9 @@ extern QString qt_setWindowTitle_helperHelper(const QString&, const QWidget*); / extern QHash *qt_app_fonts_hash(); // qapplication.cpp +static inline bool hasFeature(const QDockWidgetPrivate *priv, QDockWidget::DockWidgetFeature feature) +{ return (priv->features & feature) == feature; } + static inline bool hasFeature(const QDockWidget *dockwidget, QDockWidget::DockWidgetFeature feature) { return (dockwidget->features() & feature) == feature; } @@ -647,25 +650,25 @@ void QDockWidgetPrivate::_q_toggleView(bool b) void QDockWidgetPrivate::updateButtons() { Q_Q(QDockWidget); - QDockWidgetLayout *layout = qobject_cast(q->layout()); + QDockWidgetLayout *dwLayout = qobject_cast(layout); QStyleOptionDockWidget opt; q->initStyleOption(&opt); - bool customTitleBar = layout->widgetForRole(QDockWidgetLayout::TitleBar) != 0; - bool nativeDeco = layout->nativeWindowDeco(); + bool customTitleBar = dwLayout->widgetForRole(QDockWidgetLayout::TitleBar) != 0; + bool nativeDeco = dwLayout->nativeWindowDeco(); bool hideButtons = nativeDeco || customTitleBar; - bool canClose = hasFeature(q, QDockWidget::DockWidgetClosable); - bool canFloat = hasFeature(q, QDockWidget::DockWidgetFloatable); + bool canClose = hasFeature(this, QDockWidget::DockWidgetClosable); + bool canFloat = hasFeature(this, QDockWidget::DockWidgetFloatable); QAbstractButton *button - = qobject_cast(layout->widgetForRole(QDockWidgetLayout::FloatButton)); + = qobject_cast(dwLayout->widgetForRole(QDockWidgetLayout::FloatButton)); button->setIcon(q->style()->standardIcon(QStyle::SP_TitleBarNormalButton, &opt, q)); button->setVisible(canFloat && !hideButtons); button - = qobject_cast (layout->widgetForRole(QDockWidgetLayout::CloseButton)); + = qobject_cast (dwLayout->widgetForRole(QDockWidgetLayout::CloseButton)); button->setIcon(q->style()->standardIcon(QStyle::SP_TitleBarCloseButton, &opt, q)); button->setVisible(canClose && !hideButtons); @@ -688,7 +691,7 @@ void QDockWidgetPrivate::initDrag(const QPoint &pos, bool nca) if (state != 0) return; - QMainWindow *win = qobject_cast(q->parentWidget()); + QMainWindow *win = qobject_cast(parent); Q_ASSERT(win != 0); QMainWindowLayout *layout = qobject_cast(win->layout()); Q_ASSERT(layout != 0); @@ -741,15 +744,15 @@ void QDockWidgetPrivate::endDrag(bool abort) q->releaseMouse(); if (state->dragging) { - QMainWindowLayout *layout = + QMainWindowLayout *mwLayout = qobject_cast(q->parentWidget()->layout()); - Q_ASSERT(layout != 0); + Q_ASSERT(mwLayout != 0); - if (abort || !layout->plug(state->widgetItem)) { - if (hasFeature(q, QDockWidget::DockWidgetFloatable)) { + if (abort || !mwLayout->plug(state->widgetItem)) { + if (hasFeature(this, QDockWidget::DockWidgetFloatable)) { if (state->ownWidgetItem) delete state->widgetItem; - layout->restore(); + mwLayout->restore(); #ifdef Q_WS_X11 // get rid of the X11BypassWindowManager window flag and activate the resizer Qt::WindowFlags flags = q->windowFlags(); @@ -759,14 +762,14 @@ void QDockWidgetPrivate::endDrag(bool abort) q->show(); #else QDockWidgetLayout *myLayout - = qobject_cast(q->layout()); + = qobject_cast(layout); resizer->setActive(QWidgetResizeHandler::Resize, myLayout->widgetForRole(QDockWidgetLayout::TitleBar) != 0); #endif undockedGeometry = q->geometry(); q->activateWindow(); } else { - layout->revert(state->widgetItem); + mwLayout->revert(state->widgetItem); } } } @@ -778,7 +781,7 @@ bool QDockWidgetPrivate::isAnimating() const { Q_Q(const QDockWidget); - QMainWindow *mainWin = qobject_cast(q->parentWidget()); + QMainWindow *mainWin = qobject_cast(parent); if (mainWin == 0) return false; @@ -795,18 +798,18 @@ bool QDockWidgetPrivate::mousePressEvent(QMouseEvent *event) #if !defined(QT_NO_MAINWINDOW) Q_Q(QDockWidget); - QDockWidgetLayout *layout - = qobject_cast(q->layout()); + QDockWidgetLayout *dwLayout + = qobject_cast(layout); - if (!layout->nativeWindowDeco()) { - QRect titleArea = layout->titleArea(); + if (!dwLayout->nativeWindowDeco()) { + QRect titleArea = dwLayout->titleArea(); if (event->button() != Qt::LeftButton || !titleArea.contains(event->pos()) || // check if the tool window is movable... do nothing if it // is not (but allow moving if the window is floating) - (!hasFeature(q, QDockWidget::DockWidgetMovable) && !q->isFloating()) || - qobject_cast(q->parentWidget()) == 0 || + (!hasFeature(this, QDockWidget::DockWidgetMovable) && !q->isFloating()) || + qobject_cast(parent) == 0 || isAnimating() || state != 0) { return false; } @@ -814,7 +817,7 @@ bool QDockWidgetPrivate::mousePressEvent(QMouseEvent *event) initDrag(event->pos(), false); if (state) - state->ctrlDrag = hasFeature(q, QDockWidget::DockWidgetFloatable) && event->modifiers() & Qt::ControlModifier; + state->ctrlDrag = hasFeature(this, QDockWidget::DockWidgetFloatable) && event->modifiers() & Qt::ControlModifier; return true; } @@ -825,15 +828,13 @@ bool QDockWidgetPrivate::mousePressEvent(QMouseEvent *event) bool QDockWidgetPrivate::mouseDoubleClickEvent(QMouseEvent *event) { - Q_Q(QDockWidget); + QDockWidgetLayout *dwLayout = qobject_cast(layout); - QDockWidgetLayout *layout = qobject_cast(q->layout()); - - if (!layout->nativeWindowDeco()) { - QRect titleArea = layout->titleArea(); + if (!dwLayout->nativeWindowDeco()) { + QRect titleArea = dwLayout->titleArea(); if (event->button() == Qt::LeftButton && titleArea.contains(event->pos()) && - hasFeature(q, QDockWidget::DockWidgetFloatable)) { + hasFeature(this, QDockWidget::DockWidgetFloatable)) { _q_toggleTopLevel(); return true; } @@ -851,7 +852,7 @@ bool QDockWidgetPrivate::mouseMoveEvent(QMouseEvent *event) return ret; QDockWidgetLayout *dwlayout - = qobject_cast(q->layout()); + = qobject_cast(layout); QMainWindowLayout *mwlayout = qobject_cast(q->parentWidget()->layout()); if (!dwlayout->nativeWindowDeco()) { @@ -924,7 +925,7 @@ void QDockWidgetPrivate::nonClientAreaMouseEvent(QMouseEvent *event) break; if (state != 0) break; - if (qobject_cast(q->parentWidget()) == 0) + if (qobject_cast(parent) == 0) break; if (isAnimating()) break; @@ -997,9 +998,9 @@ void QDockWidgetPrivate::unplug(const QRect &rect) Q_Q(QDockWidget); QRect r = rect; r.moveTopLeft(q->mapToGlobal(QPoint(0, 0))); - QDockWidgetLayout *layout = qobject_cast(q->layout()); - if (layout->nativeWindowDeco(true)) - r.adjust(0, layout->titleHeight(), 0, 0); + QDockWidgetLayout *dwLayout = qobject_cast(layout); + if (dwLayout->nativeWindowDeco(true)) + r.adjust(0, dwLayout->titleHeight(), 0, 0); setWindowState(true, true, r); } @@ -1020,12 +1021,12 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect Qt::WindowFlags flags = floating ? Qt::Tool : Qt::Widget; - QDockWidgetLayout *layout = qobject_cast(q->layout()); - const bool nativeDeco = layout->nativeWindowDeco(floating); + QDockWidgetLayout *dwLayout = qobject_cast(layout); + const bool nativeDeco = dwLayout->nativeWindowDeco(floating); if (nativeDeco) { flags |= Qt::CustomizeWindowHint | Qt::WindowTitleHint; - if (hasFeature(q, QDockWidget::DockWidgetClosable)) + if (hasFeature(this, QDockWidget::DockWidgetClosable)) flags |= Qt::WindowCloseButtonHint; } else { flags |= Qt::FramelessWindowHint; diff --git a/src/gui/widgets/qmdiarea.cpp b/src/gui/widgets/qmdiarea.cpp index 0235c04..efaa2d3 100644 --- a/src/gui/widgets/qmdiarea.cpp +++ b/src/gui/widgets/qmdiarea.cpp @@ -1212,7 +1212,7 @@ void QMdiAreaPrivate::internalRaise(QMdiSubWindow *mdiChild) const QMdiSubWindow *stackUnderChild = 0; if (!windowStaysOnTop(mdiChild)) { - foreach (QObject *object, q_func()->viewport()->children()) { + foreach (QObject *object, viewport->children()) { QMdiSubWindow *child = qobject_cast(object); if (!child || !childWindows.contains(child)) continue; diff --git a/src/gui/widgets/qmdisubwindow.cpp b/src/gui/widgets/qmdisubwindow.cpp index b366c28..e5cc6b6 100644 --- a/src/gui/widgets/qmdisubwindow.cpp +++ b/src/gui/widgets/qmdisubwindow.cpp @@ -1006,7 +1006,7 @@ void QMdiSubWindowPrivate::removeBaseWidget() Q_Q(QMdiSubWindow); baseWidget->removeEventFilter(q); - if (QLayout *layout = q->layout()) + if (layout) layout->removeWidget(baseWidget); if (baseWidget->windowTitle() == q->windowTitle()) { ignoreWindowTitleChange = true; @@ -1102,7 +1102,7 @@ void QMdiSubWindowPrivate::updateCursor() void QMdiSubWindowPrivate::updateDirtyRegions() { // No update necessary - if (!q_func()->parent()) + if (!parent) return; foreach (Operation operation, operationMap.keys()) @@ -2180,17 +2180,17 @@ void QMdiSubWindowPrivate::setSizeGrip(QSizeGrip *newSizeGrip) if (!newSizeGrip || sizeGrip || q->windowFlags() & Qt::FramelessWindowHint) return; - if (q->layout() && q->layout()->indexOf(newSizeGrip) != -1) + if (layout && layout->indexOf(newSizeGrip) != -1) return; newSizeGrip->setFixedSize(newSizeGrip->sizeHint()); - bool putSizeGripInLayout = q->layout() ? true : false; + bool putSizeGripInLayout = layout ? true : false; #if defined(Q_WS_MAC) && !defined(QT_NO_STYLE_MAC) if (qobject_cast(q->style())) putSizeGripInLayout = false; #endif if (putSizeGripInLayout) { - q->layout()->addWidget(newSizeGrip); - q->layout()->setAlignment(newSizeGrip, Qt::AlignBottom | Qt::AlignRight); + layout->addWidget(newSizeGrip); + layout->setAlignment(newSizeGrip, Qt::AlignBottom | Qt::AlignRight); } else { newSizeGrip->setParent(q); newSizeGrip->move(q->isLeftToRight() ? q->width() - newSizeGrip->width() : 0, diff --git a/src/gui/widgets/qmdisubwindow_p.h b/src/gui/widgets/qmdisubwindow_p.h index 394f11c..d706546 100644 --- a/src/gui/widgets/qmdisubwindow_p.h +++ b/src/gui/widgets/qmdisubwindow_p.h @@ -308,7 +308,7 @@ public: inline void setNewGeometry(QRect *geometry) { Q_Q(QMdiSubWindow); - Q_ASSERT(q->parent()); + Q_ASSERT(parent); geometry->setSize(geometry->size().expandedTo(internalMinimumSize)); #ifndef QT_NO_RUBBERBAND if (isInRubberBandMode) diff --git a/src/gui/widgets/qpushbutton.cpp b/src/gui/widgets/qpushbutton.cpp index ca58f87..5001001 100644 --- a/src/gui/widgets/qpushbutton.cpp +++ b/src/gui/widgets/qpushbutton.cpp @@ -576,7 +576,7 @@ void QPushButtonPrivate::_q_popupPressed() menu->setNoReplayFor(q); bool horizontal = true; #if !defined(QT_NO_TOOLBAR) - QToolBar *tb = qobject_cast(q->parentWidget()); + QToolBar *tb = qobject_cast(parent); if (tb && tb->orientation() == Qt::Vertical) horizontal = false; #endif diff --git a/src/gui/widgets/qspinbox.cpp b/src/gui/widgets/qspinbox.cpp index f12946c..a9b9a84 100644 --- a/src/gui/widgets/qspinbox.cpp +++ b/src/gui/widgets/qspinbox.cpp @@ -983,7 +983,7 @@ QVariant QSpinBoxPrivate::valueFromText(const QString &text) const bool QSpinBoxPrivate::isIntermediateValue(const QString &str) const { - const int num = q_func()->locale().toInt(str, 0, 10); + const int num = locale.toInt(str, 0, 10); const int min = minimum.toInt(); const int max = maximum.toInt(); @@ -1053,13 +1053,13 @@ QVariant QSpinBoxPrivate::validateAndInterpret(QString &input, int &pos, } else { bool ok = false; bool removedThousand = false; - num = q_func()->locale().toInt(copy, &ok, 10); + num = locale.toInt(copy, &ok, 10); if (!ok && copy.contains(thousand) && (max >= 1000 || min <= -1000)) { const int s = copy.size(); copy.remove(thousand); pos = qMax(0, pos - (s - copy.size())); removedThousand = true; - num = q_func()->locale().toInt(copy, &ok, 10); + num = locale.toInt(copy, &ok, 10); } QSBDEBUG() << __FILE__ << __LINE__<< "num is set to" << num; if (!ok) { @@ -1346,9 +1346,8 @@ QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos, { bool ok = false; - QLocale loc(q_func()->locale()); - num = loc.toDouble(copy, &ok); - QSBDEBUG() << __FILE__ << __LINE__ << loc << copy << num << ok; + num = locale.toDouble(copy, &ok); + QSBDEBUG() << __FILE__ << __LINE__ << locale << copy << num << ok; bool notAcceptable = false; if (!ok) { @@ -1373,7 +1372,7 @@ QVariant QDoubleSpinBoxPrivate::validateAndInterpret(QString &input, int &pos, pos = qMax(0, pos - (s - copy.size())); - num = loc.toDouble(copy, &ok); + num = locale.toDouble(copy, &ok); QSBDEBUG() << thousand << num << copy << ok; if (!ok) { diff --git a/src/gui/widgets/qsplitter.cpp b/src/gui/widgets/qsplitter.cpp index 400d78a..24a8b6c 100644 --- a/src/gui/widgets/qsplitter.cpp +++ b/src/gui/widgets/qsplitter.cpp @@ -397,7 +397,7 @@ void QSplitterPrivate::recalc(bool update) } if (empty) { - if (qobject_cast(q->parentWidget())) { + if (qobject_cast(parent)) { // nested splitters; be nice maxl = maxt = 0; } else { diff --git a/src/gui/widgets/qtoolbar.cpp b/src/gui/widgets/qtoolbar.cpp index d765794..20f2c23 100644 --- a/src/gui/widgets/qtoolbar.cpp +++ b/src/gui/widgets/qtoolbar.cpp @@ -198,7 +198,7 @@ void QToolBarPrivate::initDrag(const QPoint &pos) if (state != 0) return; - QMainWindow *win = qobject_cast(q->parentWidget()); + QMainWindow *win = qobject_cast(parent); Q_ASSERT(win != 0); QMainWindowLayout *layout = qobject_cast(win->layout()); Q_ASSERT(layout != 0); @@ -224,7 +224,7 @@ void QToolBarPrivate::startDrag(bool moving) if ((moving && state->moving) || state->dragging) return; - QMainWindow *win = qobject_cast(q->parentWidget()); + QMainWindow *win = qobject_cast(parent); Q_ASSERT(win != 0); QMainWindowLayout *layout = qobject_cast(win->layout()); Q_ASSERT(layout != 0); @@ -283,7 +283,7 @@ bool QToolBarPrivate::mousePressEvent(QMouseEvent *event) // drag between toolbar contents to move the window. Make this work by // implementing the standard mouse-dragging code and then call // window->move() in mouseMoveEvent below. - if (QMainWindow *mainWindow = qobject_cast(q->parentWidget())) { + if (QMainWindow *mainWindow = qobject_cast(parent)) { if (mainWindow->toolBarArea(q) == Qt::TopToolBarArea && mainWindow->unifiedTitleAndToolBarOnMac() && q->childAt(event->pos()) == 0) { @@ -337,7 +337,7 @@ bool QToolBarPrivate::mouseMoveEvent(QMouseEvent *event) return false; } - QMainWindow *win = qobject_cast(q->parentWidget()); + QMainWindow *win = qobject_cast(parent); if (win == 0) return true; diff --git a/src/gui/widgets/qtoolbutton.cpp b/src/gui/widgets/qtoolbutton.cpp index 20b84ef..7d41d1e 100644 --- a/src/gui/widgets/qtoolbutton.cpp +++ b/src/gui/widgets/qtoolbutton.cpp @@ -278,7 +278,7 @@ void QToolButtonPrivate::init() #endif defaultAction = 0; #ifndef QT_NO_TOOLBAR - if (qobject_cast(q->parentWidget())) + if (qobject_cast(parent)) autoRaise = true; else #endif @@ -890,7 +890,7 @@ void QToolButtonPrivate::popupTimerDone() q->setAutoRepeat(false); bool horizontal = true; #if !defined(QT_NO_TOOLBAR) - QToolBar *tb = qobject_cast(q->parentWidget()); + QToolBar *tb = qobject_cast(parent); if (tb && tb->orientation() == Qt::Vertical) horizontal = false; #endif -- cgit v0.12 From 3f7a7c20c8493f62e090e703acfd581a4e3c4d2e Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 11 Jun 2009 11:56:54 +0200 Subject: refactor of private getters for the mode i item widget classes --- src/gui/itemviews/qlistwidget.cpp | 92 +++++++++++++-------------- src/gui/itemviews/qlistwidget_p.h | 2 +- src/gui/itemviews/qtablewidget.cpp | 118 +++++++++++++++++------------------ src/gui/itemviews/qtablewidget_p.h | 2 +- src/gui/itemviews/qtreeview.cpp | 2 +- src/gui/itemviews/qtreewidget.cpp | 87 +++++++++++++------------- src/gui/itemviews/qtreewidget_p.h | 7 +-- src/gui/text/qtextdocumentlayout.cpp | 10 ++- 8 files changed, 158 insertions(+), 162 deletions(-) diff --git a/src/gui/itemviews/qlistwidget.cpp b/src/gui/itemviews/qlistwidget.cpp index 504908f..51861b3 100644 --- a/src/gui/itemviews/qlistwidget.cpp +++ b/src/gui/itemviews/qlistwidget.cpp @@ -1020,51 +1020,51 @@ void QListWidgetPrivate::setup() QObject::connect(q, SIGNAL(activated(QModelIndex)), q, SLOT(_q_emitItemActivated(QModelIndex))); QObject::connect(q, SIGNAL(entered(QModelIndex)), q, SLOT(_q_emitItemEntered(QModelIndex))); - QObject::connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), + QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), q, SLOT(_q_emitItemChanged(QModelIndex))); QObject::connect(q->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), q, SLOT(_q_emitCurrentItemChanged(QModelIndex,QModelIndex))); QObject::connect(q->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SIGNAL(itemSelectionChanged())); - QObject::connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), + QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), q, SLOT(_q_dataChanged(QModelIndex,QModelIndex))); - QObject::connect(model(), SIGNAL(columnsRemoved(QModelIndex,int,int)), q, SLOT(_q_sort())); + QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)), q, SLOT(_q_sort())); } void QListWidgetPrivate::_q_emitItemPressed(const QModelIndex &index) { Q_Q(QListWidget); - emit q->itemPressed(model()->at(index.row())); + emit q->itemPressed(listModel()->at(index.row())); } void QListWidgetPrivate::_q_emitItemClicked(const QModelIndex &index) { Q_Q(QListWidget); - emit q->itemClicked(model()->at(index.row())); + emit q->itemClicked(listModel()->at(index.row())); } void QListWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index) { Q_Q(QListWidget); - emit q->itemDoubleClicked(model()->at(index.row())); + emit q->itemDoubleClicked(listModel()->at(index.row())); } void QListWidgetPrivate::_q_emitItemActivated(const QModelIndex &index) { Q_Q(QListWidget); - emit q->itemActivated(model()->at(index.row())); + emit q->itemActivated(listModel()->at(index.row())); } void QListWidgetPrivate::_q_emitItemEntered(const QModelIndex &index) { Q_Q(QListWidget); - emit q->itemEntered(model()->at(index.row())); + emit q->itemEntered(listModel()->at(index.row())); } void QListWidgetPrivate::_q_emitItemChanged(const QModelIndex &index) { Q_Q(QListWidget); - emit q->itemChanged(model()->at(index.row())); + emit q->itemChanged(listModel()->at(index.row())); } void QListWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex ¤t, @@ -1072,8 +1072,8 @@ void QListWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex ¤t, { Q_Q(QListWidget); QPersistentModelIndex persistentCurrent = current; - QListWidgetItem *currentItem = model()->at(persistentCurrent.row()); - emit q->currentItemChanged(currentItem, model()->at(previous.row())); + QListWidgetItem *currentItem = listModel()->at(persistentCurrent.row()); + emit q->currentItemChanged(currentItem, listModel()->at(previous.row())); //persistentCurrent is invalid if something changed the model in response //to the currentItemChanged signal emission and the item was removed @@ -1088,14 +1088,14 @@ void QListWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex ¤t, void QListWidgetPrivate::_q_sort() { if (sortingEnabled) - model()->sort(0, sortOrder); + model->sort(0, sortOrder); } void QListWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { if (sortingEnabled && topLeft.isValid() && bottomRight.isValid()) - model()->ensureSorted(topLeft.column(), sortOrder, + listModel()->ensureSorted(topLeft.column(), sortOrder, topLeft.row(), bottomRight.row()); } @@ -1308,9 +1308,9 @@ QListWidget::~QListWidget() QListWidgetItem *QListWidget::item(int row) const { Q_D(const QListWidget); - if (row < 0 || row >= d->model()->rowCount()) + if (row < 0 || row >= d->model->rowCount()) return 0; - return d->model()->at(row); + return d->listModel()->at(row); } /*! @@ -1322,7 +1322,7 @@ QListWidgetItem *QListWidget::item(int row) const int QListWidget::row(const QListWidgetItem *item) const { Q_D(const QListWidget); - return d->model()->index(const_cast(item)).row(); + return d->listModel()->index(const_cast(item)).row(); } @@ -1336,7 +1336,7 @@ void QListWidget::insertItem(int row, QListWidgetItem *item) { Q_D(QListWidget); if (item && !item->view) - d->model()->insert(row, item); + d->listModel()->insert(row, item); } /*! @@ -1349,7 +1349,7 @@ void QListWidget::insertItem(int row, QListWidgetItem *item) void QListWidget::insertItem(int row, const QString &label) { Q_D(QListWidget); - d->model()->insert(row, new QListWidgetItem(label)); + d->listModel()->insert(row, new QListWidgetItem(label)); } /*! @@ -1362,7 +1362,7 @@ void QListWidget::insertItem(int row, const QString &label) void QListWidget::insertItems(int row, const QStringList &labels) { Q_D(QListWidget); - d->model()->insert(row, labels); + d->listModel()->insert(row, labels); } /*! @@ -1378,9 +1378,9 @@ void QListWidget::insertItems(int row, const QStringList &labels) QListWidgetItem *QListWidget::takeItem(int row) { Q_D(QListWidget); - if (row < 0 || row >= d->model()->rowCount()) + if (row < 0 || row >= d->model->rowCount()) return 0; - return d->model()->take(row); + return d->listModel()->take(row); } /*! @@ -1391,7 +1391,7 @@ QListWidgetItem *QListWidget::takeItem(int row) int QListWidget::count() const { Q_D(const QListWidget); - return d->model()->rowCount(); + return d->model->rowCount(); } /*! @@ -1400,7 +1400,7 @@ int QListWidget::count() const QListWidgetItem *QListWidget::currentItem() const { Q_D(const QListWidget); - return d->model()->at(currentIndex().row()); + return d->listModel()->at(currentIndex().row()); } @@ -1438,7 +1438,7 @@ int QListWidget::currentRow() const void QListWidget::setCurrentRow(int row) { Q_D(QListWidget); - QModelIndex index = d->model()->index(row); + QModelIndex index = d->listModel()->index(row); if (d->selectionMode == SingleSelection) selectionModel()->setCurrentIndex(index, QItemSelectionModel::ClearAndSelect); else if (d->selectionMode == NoSelection) @@ -1455,7 +1455,7 @@ void QListWidget::setCurrentRow(int row) void QListWidget::setCurrentRow(int row, QItemSelectionModel::SelectionFlags command) { Q_D(QListWidget); - d->selectionModel->setCurrentIndex(d->model()->index(row), command); + d->selectionModel->setCurrentIndex(d->listModel()->index(row), command); } /*! @@ -1464,7 +1464,7 @@ void QListWidget::setCurrentRow(int row, QItemSelectionModel::SelectionFlags com QListWidgetItem *QListWidget::itemAt(const QPoint &p) const { Q_D(const QListWidget); - return d->model()->at(indexAt(p).row()); + return d->listModel()->at(indexAt(p).row()); } @@ -1482,7 +1482,7 @@ QListWidgetItem *QListWidget::itemAt(const QPoint &p) const QRect QListWidget::visualItemRect(const QListWidgetItem *item) const { Q_D(const QListWidget); - QModelIndex index = d->model()->index(const_cast(item)); + QModelIndex index = d->listModel()->index(const_cast(item)); return visualRect(index); } @@ -1493,7 +1493,7 @@ void QListWidget::sortItems(Qt::SortOrder order) { Q_D(QListWidget); d->sortOrder = order; - d->model()->sort(0, order); + d->listModel()->sort(0, order); } /*! @@ -1532,7 +1532,7 @@ Qt::SortOrder QListWidget::sortOrder() const void QListWidget::editItem(QListWidgetItem *item) { Q_D(QListWidget); - edit(d->model()->index(item)); + edit(d->listModel()->index(item)); } /*! @@ -1543,7 +1543,7 @@ void QListWidget::editItem(QListWidgetItem *item) void QListWidget::openPersistentEditor(QListWidgetItem *item) { Q_D(QListWidget); - QModelIndex index = d->model()->index(item); + QModelIndex index = d->listModel()->index(item); QAbstractItemView::openPersistentEditor(index); } @@ -1555,7 +1555,7 @@ void QListWidget::openPersistentEditor(QListWidgetItem *item) void QListWidget::closePersistentEditor(QListWidgetItem *item) { Q_D(QListWidget); - QModelIndex index = d->model()->index(item); + QModelIndex index = d->listModel()->index(item); QAbstractItemView::closePersistentEditor(index); } @@ -1567,7 +1567,7 @@ void QListWidget::closePersistentEditor(QListWidgetItem *item) QWidget *QListWidget::itemWidget(QListWidgetItem *item) const { Q_D(const QListWidget); - QModelIndex index = d->model()->index(item); + QModelIndex index = d->listModel()->index(item); return QAbstractItemView::indexWidget(index); } @@ -1585,7 +1585,7 @@ QWidget *QListWidget::itemWidget(QListWidgetItem *item) const void QListWidget::setItemWidget(QListWidgetItem *item, QWidget *widget) { Q_D(QListWidget); - QModelIndex index = d->model()->index(item); + QModelIndex index = d->listModel()->index(item); QAbstractItemView::setIndexWidget(index, widget); } @@ -1599,7 +1599,7 @@ void QListWidget::setItemWidget(QListWidgetItem *item, QWidget *widget) bool QListWidget::isItemSelected(const QListWidgetItem *item) const { Q_D(const QListWidget); - QModelIndex index = d->model()->index(const_cast(item)); + QModelIndex index = d->listModel()->index(const_cast(item)); return selectionModel()->isSelected(index); } @@ -1614,7 +1614,7 @@ bool QListWidget::isItemSelected(const QListWidgetItem *item) const void QListWidget::setItemSelected(const QListWidgetItem *item, bool select) { Q_D(QListWidget); - QModelIndex index = d->model()->index(const_cast(item)); + QModelIndex index = d->listModel()->index(const_cast(item)); if (d->selectionMode == SingleSelection) { selectionModel()->select(index, select @@ -1638,7 +1638,7 @@ QList QListWidget::selectedItems() const QModelIndexList indexes = selectionModel()->selectedIndexes(); QList items; for (int i = 0; i < indexes.count(); ++i) - items.append(d->model()->at(indexes.at(i).row())); + items.append(d->listModel()->at(indexes.at(i).row())); return items; } @@ -1649,11 +1649,11 @@ QList QListWidget::selectedItems() const QList QListWidget::findItems(const QString &text, Qt::MatchFlags flags) const { Q_D(const QListWidget); - QModelIndexList indexes = d->model()->match(model()->index(0, 0, QModelIndex()), + QModelIndexList indexes = d->listModel()->match(model()->index(0, 0, QModelIndex()), Qt::DisplayRole, text, -1, flags); QList items; for (int i = 0; i < indexes.size(); ++i) - items.append(d->model()->at(indexes.at(i).row())); + items.append(d->listModel()->at(indexes.at(i).row())); return items; } @@ -1690,7 +1690,7 @@ void QListWidget::setItemHidden(const QListWidgetItem *item, bool hide) void QListWidget::scrollToItem(const QListWidgetItem *item, QAbstractItemView::ScrollHint hint) { Q_D(QListWidget); - QModelIndex index = d->model()->index(const_cast(item)); + QModelIndex index = d->listModel()->index(const_cast(item)); QListView::scrollTo(index, hint); } @@ -1703,7 +1703,7 @@ void QListWidget::clear() { Q_D(QListWidget); selectionModel()->clear(); - d->model()->clear(); + d->listModel()->clear(); } /*! @@ -1714,7 +1714,7 @@ void QListWidget::clear() */ QStringList QListWidget::mimeTypes() const { - return d_func()->model()->QAbstractListModel::mimeTypes(); + return d_func()->listModel()->QAbstractListModel::mimeTypes(); } /*! @@ -1727,7 +1727,7 @@ QStringList QListWidget::mimeTypes() const */ QMimeData *QListWidget::mimeData(const QList) const { - return d_func()->model()->internalMimeData(); + return d_func()->listModel()->internalMimeData(); } #ifndef QT_NO_DRAGANDDROP @@ -1750,7 +1750,7 @@ bool QListWidget::dropMimeData(int index, const QMimeData *data, Qt::DropAction row = -1; column = -1; } - return d_func()->model()->QAbstractListModel::dropMimeData(data, action , row, column, idx); + return d_func()->listModel()->QAbstractListModel::dropMimeData(data, action , row, column, idx); } /*! \reimp */ @@ -1809,7 +1809,7 @@ void QListWidget::dropEvent(QDropEvent *event) { Qt::DropActions QListWidget::supportedDropActions() const { Q_D(const QListWidget); - return d->model()->QAbstractListModel::supportedDropActions() | Qt::MoveAction; + return d->listModel()->QAbstractListModel::supportedDropActions() | Qt::MoveAction; } #endif // QT_NO_DRAGANDDROP @@ -1833,7 +1833,7 @@ QList QListWidget::items(const QMimeData *data) const QModelIndex QListWidget::indexFromItem(QListWidgetItem *item) const { Q_D(const QListWidget); - return d->model()->index(item); + return d->listModel()->index(item); } /*! @@ -1844,7 +1844,7 @@ QListWidgetItem *QListWidget::itemFromIndex(const QModelIndex &index) const { Q_D(const QListWidget); if (d->isIndexValid(index)) - return d->model()->at(index.row()); + return d->listModel()->at(index.row()); return 0; } diff --git a/src/gui/itemviews/qlistwidget_p.h b/src/gui/itemviews/qlistwidget_p.h index 8556047..6887d9d 100644 --- a/src/gui/itemviews/qlistwidget_p.h +++ b/src/gui/itemviews/qlistwidget_p.h @@ -143,7 +143,7 @@ class QListWidgetPrivate : public QListViewPrivate Q_DECLARE_PUBLIC(QListWidget) public: QListWidgetPrivate() : QListViewPrivate(), sortOrder(Qt::AscendingOrder), sortingEnabled(false) {} - inline QListModel *model() const { return qobject_cast(q_func()->model()); } + inline QListModel *listModel() const { return qobject_cast(model); } void setup(); void _q_emitItemPressed(const QModelIndex &index); void _q_emitItemClicked(const QModelIndex &index); diff --git a/src/gui/itemviews/qtablewidget.cpp b/src/gui/itemviews/qtablewidget.cpp index 072e435..6645376 100644 --- a/src/gui/itemviews/qtablewidget.cpp +++ b/src/gui/itemviews/qtablewidget.cpp @@ -1570,7 +1570,7 @@ void QTableWidgetPrivate::setup() QObject::connect(q, SIGNAL(activated(QModelIndex)), q, SLOT(_q_emitItemActivated(QModelIndex))); QObject::connect(q, SIGNAL(entered(QModelIndex)), q, SLOT(_q_emitItemEntered(QModelIndex))); // model signals - QObject::connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), + QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), q, SLOT(_q_emitItemChanged(QModelIndex))); // selection signals QObject::connect(q->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), @@ -1578,15 +1578,15 @@ void QTableWidgetPrivate::setup() QObject::connect(q->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), q, SIGNAL(itemSelectionChanged())); // sorting - QObject::connect(model(), SIGNAL(dataChanged(QModelIndex,QModelIndex)), + QObject::connect(model, SIGNAL(dataChanged(QModelIndex,QModelIndex)), q, SLOT(_q_dataChanged(QModelIndex,QModelIndex))); - QObject::connect(model(), SIGNAL(columnsRemoved(QModelIndex,int,int)), q, SLOT(_q_sort())); + QObject::connect(model, SIGNAL(columnsRemoved(QModelIndex,int,int)), q, SLOT(_q_sort())); } void QTableWidgetPrivate::_q_emitItemPressed(const QModelIndex &index) { Q_Q(QTableWidget); - if (QTableWidgetItem *item = model()->item(index)) + if (QTableWidgetItem *item = tableModel()->item(index)) emit q->itemPressed(item); emit q->cellPressed(index.row(), index.column()); } @@ -1594,7 +1594,7 @@ void QTableWidgetPrivate::_q_emitItemPressed(const QModelIndex &index) void QTableWidgetPrivate::_q_emitItemClicked(const QModelIndex &index) { Q_Q(QTableWidget); - if (QTableWidgetItem *item = model()->item(index)) + if (QTableWidgetItem *item = tableModel()->item(index)) emit q->itemClicked(item); emit q->cellClicked(index.row(), index.column()); } @@ -1602,7 +1602,7 @@ void QTableWidgetPrivate::_q_emitItemClicked(const QModelIndex &index) void QTableWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index) { Q_Q(QTableWidget); - if (QTableWidgetItem *item = model()->item(index)) + if (QTableWidgetItem *item = tableModel()->item(index)) emit q->itemDoubleClicked(item); emit q->cellDoubleClicked(index.row(), index.column()); } @@ -1610,7 +1610,7 @@ void QTableWidgetPrivate::_q_emitItemDoubleClicked(const QModelIndex &index) void QTableWidgetPrivate::_q_emitItemActivated(const QModelIndex &index) { Q_Q(QTableWidget); - if (QTableWidgetItem *item = model()->item(index)) + if (QTableWidgetItem *item = tableModel()->item(index)) emit q->itemActivated(item); emit q->cellActivated(index.row(), index.column()); } @@ -1618,7 +1618,7 @@ void QTableWidgetPrivate::_q_emitItemActivated(const QModelIndex &index) void QTableWidgetPrivate::_q_emitItemEntered(const QModelIndex &index) { Q_Q(QTableWidget); - if (QTableWidgetItem *item = model()->item(index)) + if (QTableWidgetItem *item = tableModel()->item(index)) emit q->itemEntered(item); emit q->cellEntered(index.row(), index.column()); } @@ -1626,7 +1626,7 @@ void QTableWidgetPrivate::_q_emitItemEntered(const QModelIndex &index) void QTableWidgetPrivate::_q_emitItemChanged(const QModelIndex &index) { Q_Q(QTableWidget); - if (QTableWidgetItem *item = model()->item(index)) + if (QTableWidgetItem *item = tableModel()->item(index)) emit q->itemChanged(item); emit q->cellChanged(index.row(), index.column()); } @@ -1635,8 +1635,8 @@ void QTableWidgetPrivate::_q_emitCurrentItemChanged(const QModelIndex ¤t, const QModelIndex &previous) { Q_Q(QTableWidget); - QTableWidgetItem *currentItem = model()->item(current); - QTableWidgetItem *previousItem = model()->item(previous); + QTableWidgetItem *currentItem = tableModel()->item(current); + QTableWidgetItem *previousItem = tableModel()->item(previous); if (currentItem || previousItem) emit q->currentItemChanged(currentItem, previousItem); emit q->currentCellChanged(current.row(), current.column(), previous.row(), previous.column()); @@ -1647,7 +1647,7 @@ void QTableWidgetPrivate::_q_sort() if (sortingEnabled) { int column = horizontalHeader->sortIndicatorSection(); Qt::SortOrder order = horizontalHeader->sortIndicatorOrder(); - model()->sort(column, order); + model->sort(column, order); } } @@ -1658,7 +1658,7 @@ void QTableWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, int column = horizontalHeader->sortIndicatorSection(); if (column >= topLeft.column() && column <= bottomRight.column()) { Qt::SortOrder order = horizontalHeader->sortIndicatorOrder(); - model()->ensureSorted(column, order, topLeft.row(), bottomRight.row()); + tableModel()->ensureSorted(column, order, topLeft.row(), bottomRight.row()); } } } @@ -1862,7 +1862,7 @@ QTableWidget::~QTableWidget() void QTableWidget::setRowCount(int rows) { Q_D(QTableWidget); - d->model()->setRowCount(rows); + d->tableModel()->setRowCount(rows); } /*! @@ -1872,7 +1872,7 @@ void QTableWidget::setRowCount(int rows) int QTableWidget::rowCount() const { Q_D(const QTableWidget); - return d->model()->rowCount(); + return d->model->rowCount(); } /*! @@ -1885,7 +1885,7 @@ int QTableWidget::rowCount() const void QTableWidget::setColumnCount(int columns) { Q_D(QTableWidget); - d->model()->setColumnCount(columns); + d->tableModel()->setColumnCount(columns); } /*! @@ -1895,7 +1895,7 @@ void QTableWidget::setColumnCount(int columns) int QTableWidget::columnCount() const { Q_D(const QTableWidget); - return d->model()->columnCount(); + return d->model->columnCount(); } /*! @@ -1904,7 +1904,7 @@ int QTableWidget::columnCount() const int QTableWidget::row(const QTableWidgetItem *item) const { Q_D(const QTableWidget); - return d->model()->index(item).row(); + return d->tableModel()->index(item).row(); } /*! @@ -1913,7 +1913,7 @@ int QTableWidget::row(const QTableWidgetItem *item) const int QTableWidget::column(const QTableWidgetItem *item) const { Q_D(const QTableWidget); - return d->model()->index(item).column(); + return d->tableModel()->index(item).column(); } @@ -1926,7 +1926,7 @@ int QTableWidget::column(const QTableWidgetItem *item) const QTableWidgetItem *QTableWidget::item(int row, int column) const { Q_D(const QTableWidget); - return d->model()->item(row, column); + return d->tableModel()->item(row, column); } /*! @@ -1955,7 +1955,7 @@ void QTableWidget::setItem(int row, int column, QTableWidgetItem *item) qWarning("QTableWidget: cannot insert an item that is already owned by another QTableWidget"); } else { item->view = this; - d->model()->setItem(row, column, item); + d->tableModel()->setItem(row, column, item); } } else { delete takeItem(row, column); @@ -1968,7 +1968,7 @@ void QTableWidget::setItem(int row, int column, QTableWidgetItem *item) QTableWidgetItem *QTableWidget::takeItem(int row, int column) { Q_D(QTableWidget); - QTableWidgetItem *item = d->model()->takeItem(row, column); + QTableWidgetItem *item = d->tableModel()->takeItem(row, column); if (item) item->view = 0; return item; @@ -1980,7 +1980,7 @@ QTableWidgetItem *QTableWidget::takeItem(int row, int column) QTableWidgetItem *QTableWidget::verticalHeaderItem(int row) const { Q_D(const QTableWidget); - return d->model()->verticalHeaderItem(row); + return d->tableModel()->verticalHeaderItem(row); } /*! @@ -1991,7 +1991,7 @@ void QTableWidget::setVerticalHeaderItem(int row, QTableWidgetItem *item) Q_D(QTableWidget); if (item) { item->view = this; - d->model()->setVerticalHeaderItem(row, item); + d->tableModel()->setVerticalHeaderItem(row, item); } else { delete takeVerticalHeaderItem(row); } @@ -2004,7 +2004,7 @@ void QTableWidget::setVerticalHeaderItem(int row, QTableWidgetItem *item) QTableWidgetItem *QTableWidget::takeVerticalHeaderItem(int row) { Q_D(QTableWidget); - QTableWidgetItem *itm = d->model()->takeVerticalHeaderItem(row); + QTableWidgetItem *itm = d->tableModel()->takeVerticalHeaderItem(row); if (itm) itm->view = 0; return itm; @@ -2017,7 +2017,7 @@ QTableWidgetItem *QTableWidget::takeVerticalHeaderItem(int row) QTableWidgetItem *QTableWidget::horizontalHeaderItem(int column) const { Q_D(const QTableWidget); - return d->model()->horizontalHeaderItem(column); + return d->tableModel()->horizontalHeaderItem(column); } /*! @@ -2028,7 +2028,7 @@ void QTableWidget::setHorizontalHeaderItem(int column, QTableWidgetItem *item) Q_D(QTableWidget); if (item) { item->view = this; - d->model()->setHorizontalHeaderItem(column, item); + d->tableModel()->setHorizontalHeaderItem(column, item); } else { delete takeHorizontalHeaderItem(column); } @@ -2041,7 +2041,7 @@ void QTableWidget::setHorizontalHeaderItem(int column, QTableWidgetItem *item) QTableWidgetItem *QTableWidget::takeHorizontalHeaderItem(int column) { Q_D(QTableWidget); - QTableWidgetItem *itm = d->model()->takeHorizontalHeaderItem(column); + QTableWidgetItem *itm = d->tableModel()->takeHorizontalHeaderItem(column); if (itm) itm->view = 0; return itm; @@ -2053,7 +2053,7 @@ QTableWidgetItem *QTableWidget::takeHorizontalHeaderItem(int column) void QTableWidget::setVerticalHeaderLabels(const QStringList &labels) { Q_D(QTableWidget); - QTableModel *model = d->model(); + QTableModel *model = d->tableModel(); QTableWidgetItem *item = 0; for (int i = 0; i < model->rowCount() && i < labels.count(); ++i) { item = model->verticalHeaderItem(i); @@ -2071,7 +2071,7 @@ void QTableWidget::setVerticalHeaderLabels(const QStringList &labels) void QTableWidget::setHorizontalHeaderLabels(const QStringList &labels) { Q_D(QTableWidget); - QTableModel *model = d->model(); + QTableModel *model = d->tableModel(); QTableWidgetItem *item = 0; for (int i = 0; i < model->columnCount() && i < labels.count(); ++i) { item = model->horizontalHeaderItem(i); @@ -2111,7 +2111,7 @@ int QTableWidget::currentColumn() const QTableWidgetItem *QTableWidget::currentItem() const { Q_D(const QTableWidget); - return d->model()->item(currentIndex()); + return d->tableModel()->item(currentIndex()); } /*! @@ -2125,7 +2125,7 @@ QTableWidgetItem *QTableWidget::currentItem() const void QTableWidget::setCurrentItem(QTableWidgetItem *item) { Q_D(QTableWidget); - setCurrentIndex(d->model()->index(item)); + setCurrentIndex(d->tableModel()->index(item)); } /*! @@ -2138,7 +2138,7 @@ void QTableWidget::setCurrentItem(QTableWidgetItem *item) void QTableWidget::setCurrentItem(QTableWidgetItem *item, QItemSelectionModel::SelectionFlags command) { Q_D(QTableWidget); - d->selectionModel->setCurrentIndex(d->model()->index(item), command); + d->selectionModel->setCurrentIndex(d->tableModel()->index(item), command); } /*! @@ -2177,7 +2177,7 @@ void QTableWidget::setCurrentCell(int row, int column, QItemSelectionModel::Sele void QTableWidget::sortItems(int column, Qt::SortOrder order) { Q_D(QTableWidget); - d->model()->sort(column, order); + d->model->sort(column, order); horizontalHeader()->setSortIndicator(column, order); } @@ -2206,7 +2206,7 @@ void QTableWidget::editItem(QTableWidgetItem *item) Q_D(QTableWidget); if (!item) return; - edit(d->model()->index(item)); + edit(d->tableModel()->index(item)); } /*! @@ -2219,7 +2219,7 @@ void QTableWidget::openPersistentEditor(QTableWidgetItem *item) Q_D(QTableWidget); if (!item) return; - QModelIndex index = d->model()->index(item); + QModelIndex index = d->tableModel()->index(item); QAbstractItemView::openPersistentEditor(index); } @@ -2233,7 +2233,7 @@ void QTableWidget::closePersistentEditor(QTableWidgetItem *item) Q_D(QTableWidget); if (!item) return; - QModelIndex index = d->model()->index(item); + QModelIndex index = d->tableModel()->index(item); QAbstractItemView::closePersistentEditor(index); } @@ -2283,7 +2283,7 @@ void QTableWidget::setCellWidget(int row, int column, QWidget *widget) bool QTableWidget::isItemSelected(const QTableWidgetItem *item) const { Q_D(const QTableWidget); - QModelIndex index = d->model()->index(item); + QModelIndex index = d->tableModel()->index(item); return selectionModel()->isSelected(index); } @@ -2297,7 +2297,7 @@ bool QTableWidget::isItemSelected(const QTableWidgetItem *item) const void QTableWidget::setItemSelected(const QTableWidgetItem *item, bool select) { Q_D(QTableWidget); - QModelIndex index = d->model()->index(item); + QModelIndex index = d->tableModel()->index(item); selectionModel()->select(index, select ? QItemSelectionModel::Select : QItemSelectionModel::Deselect); } @@ -2354,7 +2354,7 @@ QList QTableWidget::selectedItems() QModelIndex index = indexes.at(i); if (isIndexHidden(index)) continue; - QTableWidgetItem *item = d->model()->item(index); + QTableWidgetItem *item = d->tableModel()->item(index); if (item) items.append(item); } @@ -2370,11 +2370,11 @@ QList QTableWidget::findItems(const QString &text, Qt::MatchF Q_D(const QTableWidget); QModelIndexList indexes; for (int column = 0; column < columnCount(); ++column) - indexes += d->model()->match(model()->index(0, column, QModelIndex()), + indexes += d->model->match(model()->index(0, column, QModelIndex()), Qt::DisplayRole, text, -1, flags); QList items; for (int i = 0; i < indexes.size(); ++i) - items.append(d->model()->item(indexes.at(i))); + items.append(d->tableModel()->item(indexes.at(i))); return items; } @@ -2408,7 +2408,7 @@ int QTableWidget::visualColumn(int logicalColumn) const QTableWidgetItem *QTableWidget::itemAt(const QPoint &p) const { Q_D(const QTableWidget); - return d->model()->item(indexAt(p)); + return d->tableModel()->item(indexAt(p)); } /*! @@ -2419,7 +2419,7 @@ QRect QTableWidget::visualItemRect(const QTableWidgetItem *item) const Q_D(const QTableWidget); if (!item) return QRect(); - QModelIndex index = d->model()->index(const_cast(item)); + QModelIndex index = d->tableModel()->index(const_cast(item)); Q_ASSERT(index.isValid()); return visualRect(index); } @@ -2435,7 +2435,7 @@ void QTableWidget::scrollToItem(const QTableWidgetItem *item, QAbstractItemView: Q_D(QTableWidget); if (!item) return; - QModelIndex index = d->model()->index(const_cast(item)); + QModelIndex index = d->tableModel()->index(const_cast(item)); Q_ASSERT(index.isValid()); QTableView::scrollTo(index, hint); } @@ -2448,7 +2448,7 @@ void QTableWidget::scrollToItem(const QTableWidgetItem *item, QAbstractItemView: const QTableWidgetItem *QTableWidget::itemPrototype() const { Q_D(const QTableWidget); - return d->model()->itemPrototype(); + return d->tableModel()->itemPrototype(); } /*! @@ -2467,7 +2467,7 @@ const QTableWidgetItem *QTableWidget::itemPrototype() const void QTableWidget::setItemPrototype(const QTableWidgetItem *item) { Q_D(QTableWidget); - d->model()->setItemPrototype(item); + d->tableModel()->setItemPrototype(item); } /*! @@ -2476,7 +2476,7 @@ void QTableWidget::setItemPrototype(const QTableWidgetItem *item) void QTableWidget::insertRow(int row) { Q_D(QTableWidget); - d->model()->insertRows(row); + d->tableModel()->insertRows(row); } /*! @@ -2485,7 +2485,7 @@ void QTableWidget::insertRow(int row) void QTableWidget::insertColumn(int column) { Q_D(QTableWidget); - d->model()->insertColumns(column); + d->tableModel()->insertColumns(column); } /*! @@ -2494,7 +2494,7 @@ void QTableWidget::insertColumn(int column) void QTableWidget::removeRow(int row) { Q_D(QTableWidget); - d->model()->removeRows(row); + d->tableModel()->removeRows(row); } /*! @@ -2503,7 +2503,7 @@ void QTableWidget::removeRow(int row) void QTableWidget::removeColumn(int column) { Q_D(QTableWidget); - d->model()->removeColumns(column); + d->tableModel()->removeColumns(column); } /*! @@ -2516,7 +2516,7 @@ void QTableWidget::clear() { Q_D(QTableWidget); selectionModel()->clear(); - d->model()->clear(); + d->tableModel()->clear(); } /*! @@ -2530,7 +2530,7 @@ void QTableWidget::clearContents() { Q_D(QTableWidget); selectionModel()->clear(); - d->model()->clearContents(); + d->tableModel()->clearContents(); } /*! @@ -2541,7 +2541,7 @@ void QTableWidget::clearContents() */ QStringList QTableWidget::mimeTypes() const { - return d_func()->model()->QAbstractTableModel::mimeTypes(); + return d_func()->tableModel()->QAbstractTableModel::mimeTypes(); } /*! @@ -2554,7 +2554,7 @@ QStringList QTableWidget::mimeTypes() const */ QMimeData *QTableWidget::mimeData(const QList) const { - return d_func()->model()->internalMimeData(); + return d_func()->tableModel()->internalMimeData(); } /*! @@ -2576,7 +2576,7 @@ bool QTableWidget::dropMimeData(int row, int column, const QMimeData *data, Qt:: column = -1; } #endif - return d_func()->model()->QAbstractTableModel::dropMimeData(data, action , row, column, idx); + return d_func()->tableModel()->QAbstractTableModel::dropMimeData(data, action , row, column, idx); } /*! @@ -2586,7 +2586,7 @@ bool QTableWidget::dropMimeData(int row, int column, const QMimeData *data, Qt:: */ Qt::DropActions QTableWidget::supportedDropActions() const { - return d_func()->model()->QAbstractTableModel::supportedDropActions() | Qt::MoveAction; + return d_func()->tableModel()->QAbstractTableModel::supportedDropActions() | Qt::MoveAction; } /*! @@ -2610,7 +2610,7 @@ QList QTableWidget::items(const QMimeData *data) const QModelIndex QTableWidget::indexFromItem(QTableWidgetItem *item) const { Q_D(const QTableWidget); - return d->model()->index(item); + return d->tableModel()->index(item); } /*! @@ -2620,7 +2620,7 @@ QModelIndex QTableWidget::indexFromItem(QTableWidgetItem *item) const QTableWidgetItem *QTableWidget::itemFromIndex(const QModelIndex &index) const { Q_D(const QTableWidget); - return d->model()->item(index); + return d->tableModel()->item(index); } /*! diff --git a/src/gui/itemviews/qtablewidget_p.h b/src/gui/itemviews/qtablewidget_p.h index d8bfcc5..2acaf9b 100644 --- a/src/gui/itemviews/qtablewidget_p.h +++ b/src/gui/itemviews/qtablewidget_p.h @@ -189,7 +189,7 @@ class QTableWidgetPrivate : public QTableViewPrivate Q_DECLARE_PUBLIC(QTableWidget) public: QTableWidgetPrivate() : QTableViewPrivate() {} - inline QTableModel *model() const { return qobject_cast(q_func()->model()); } + inline QTableModel *tableModel() const { return qobject_cast(model); } void setup(); // view signals diff --git a/src/gui/itemviews/qtreeview.cpp b/src/gui/itemviews/qtreeview.cpp index 53fa170..ecbd683 100644 --- a/src/gui/itemviews/qtreeview.cpp +++ b/src/gui/itemviews/qtreeview.cpp @@ -3485,7 +3485,7 @@ void QTreeViewPrivate::updateScrollBars() int QTreeViewPrivate::itemDecorationAt(const QPoint &pos) const { - const_cast(q_func())->executeDelayedItemsLayout(); + executePostedLayout(); int x = pos.x(); int column = header->logicalIndexAt(x); if (column != 0) diff --git a/src/gui/itemviews/qtreewidget.cpp b/src/gui/itemviews/qtreewidget.cpp index 24713c4..2a6ac30 100644 --- a/src/gui/itemviews/qtreewidget.cpp +++ b/src/gui/itemviews/qtreewidget.cpp @@ -2283,7 +2283,7 @@ void QTreeWidgetPrivate::_q_sort() if (sortingEnabled) { int column = header->sortIndicatorSection(); Qt::SortOrder order = header->sortIndicatorOrder(); - model()->sort(column, order); + treeModel()->sort(column, order); } } @@ -2292,7 +2292,7 @@ void QTreeWidgetPrivate::_q_selectionChanged(const QItemSelection &selected, con Q_Q(QTreeWidget); QModelIndexList indices = selected.indexes(); int i; - QTreeModel *m = model(); + QTreeModel *m = treeModel(); for (i = 0; i < indices.count(); ++i) { QTreeWidgetItem *item = m->item(indices.at(i)); item->d->selected = true; @@ -2311,11 +2311,11 @@ void QTreeWidgetPrivate::_q_dataChanged(const QModelIndex &topLeft, const QModelIndex &bottomRight) { if (sortingEnabled && topLeft.isValid() && bottomRight.isValid() - && !model()->sortPendingTimer.isActive()) { + && !treeModel()->sortPendingTimer.isActive()) { int column = header->sortIndicatorSection(); if (column >= topLeft.column() && column <= bottomRight.column()) { Qt::SortOrder order = header->sortIndicatorOrder(); - model()->ensureSorted(column, order, topLeft.row(), + treeModel()->ensureSorted(column, order, topLeft.row(), bottomRight.row(), topLeft.parent()); } } @@ -2543,7 +2543,7 @@ QTreeWidget::~QTreeWidget() int QTreeWidget::columnCount() const { Q_D(const QTreeWidget); - return d->model()->columnCount(); + return d->model->columnCount(); } /* @@ -2555,7 +2555,7 @@ void QTreeWidget::setColumnCount(int columns) Q_D(QTreeWidget); if (columns < 0) return; - d->model()->setColumnCount(columns); + d->treeModel()->setColumnCount(columns); } /*! @@ -2572,7 +2572,7 @@ void QTreeWidget::setColumnCount(int columns) QTreeWidgetItem *QTreeWidget::invisibleRootItem() const { Q_D(const QTreeWidget); - return d->model()->rootItem; + return d->treeModel()->rootItem; } /*! @@ -2585,7 +2585,7 @@ QTreeWidgetItem *QTreeWidget::invisibleRootItem() const QTreeWidgetItem *QTreeWidget::topLevelItem(int index) const { Q_D(const QTreeWidget); - return d->model()->rootItem->child(index); + return d->treeModel()->rootItem->child(index); } /*! @@ -2600,7 +2600,7 @@ QTreeWidgetItem *QTreeWidget::topLevelItem(int index) const int QTreeWidget::topLevelItemCount() const { Q_D(const QTreeWidget); - return d->model()->rootItem->childCount(); + return d->treeModel()->rootItem->childCount(); } /*! @@ -2614,7 +2614,7 @@ int QTreeWidget::topLevelItemCount() const void QTreeWidget::insertTopLevelItem(int index, QTreeWidgetItem *item) { Q_D(QTreeWidget); - d->model()->rootItem->insertChild(index, item); + d->treeModel()->rootItem->insertChild(index, item); } /*! @@ -2639,7 +2639,7 @@ void QTreeWidget::addTopLevelItem(QTreeWidgetItem *item) QTreeWidgetItem *QTreeWidget::takeTopLevelItem(int index) { Q_D(QTreeWidget); - return d->model()->rootItem->takeChild(index); + return d->treeModel()->rootItem->takeChild(index); } /*! @@ -2648,8 +2648,8 @@ QTreeWidgetItem *QTreeWidget::takeTopLevelItem(int index) int QTreeWidget::indexOfTopLevelItem(QTreeWidgetItem *item) { Q_D(QTreeWidget); - d->model()->executePendingSort(); - return d->model()->rootItem->children.indexOf(item); + d->treeModel()->executePendingSort(); + return d->treeModel()->rootItem->children.indexOf(item); } /*! @@ -2661,8 +2661,8 @@ int QTreeWidget::indexOfTopLevelItem(QTreeWidgetItem *item) int QTreeWidget::indexOfTopLevelItem(QTreeWidgetItem *item) const { Q_D(const QTreeWidget); - d->model()->executePendingSort(); - return d->model()->rootItem->children.indexOf(item); + d->treeModel()->executePendingSort(); + return d->treeModel()->rootItem->children.indexOf(item); } /*! @@ -2677,7 +2677,7 @@ int QTreeWidget::indexOfTopLevelItem(QTreeWidgetItem *item) const void QTreeWidget::insertTopLevelItems(int index, const QList &items) { Q_D(QTreeWidget); - d->model()->rootItem->insertChildren(index, items); + d->treeModel()->rootItem->insertChildren(index, items); } /*! @@ -2699,7 +2699,7 @@ void QTreeWidget::addTopLevelItems(const QList &items) QTreeWidgetItem *QTreeWidget::headerItem() const { Q_D(const QTreeWidget); - return d->model()->headerItem; + return d->treeModel()->headerItem; } /*! @@ -2720,16 +2720,16 @@ void QTreeWidget::setHeaderItem(QTreeWidgetItem *item) int oldCount = columnCount(); if (oldCount < item->columnCount()) - d->model()->beginInsertColumns(QModelIndex(), oldCount, item->columnCount()); + d->treeModel()->beginInsertColumns(QModelIndex(), oldCount, item->columnCount()); else - d->model()->beginRemoveColumns(QModelIndex(), item->columnCount(), oldCount); - delete d->model()->headerItem; - d->model()->headerItem = item; + d->treeModel()->beginRemoveColumns(QModelIndex(), item->columnCount(), oldCount); + delete d->treeModel()->headerItem; + d->treeModel()->headerItem = item; if (oldCount < item->columnCount()) - d->model()->endInsertColumns(); + d->treeModel()->endInsertColumns(); else - d->model()->endRemoveColumns(); - d->model()->headerDataChanged(Qt::Horizontal, 0, oldCount); + d->treeModel()->endRemoveColumns(); + d->treeModel()->headerDataChanged(Qt::Horizontal, 0, oldCount); } @@ -2746,8 +2746,7 @@ void QTreeWidget::setHeaderLabels(const QStringList &labels) Q_D(QTreeWidget); if (columnCount() < labels.count()) setColumnCount(labels.count()); - QTreeModel *model = d->model(); - QTreeWidgetItem *item = model->headerItem; + QTreeWidgetItem *item = d->treeModel()->headerItem; for (int i = 0; i < labels.count(); ++i) item->setText(i, labels.at(i)); } @@ -2875,7 +2874,7 @@ void QTreeWidget::sortItems(int column, Qt::SortOrder order) { Q_D(QTreeWidget); header()->setSortIndicator(column, order); - d->model()->sort(column, order); + d->model->sort(column, order); } /*! @@ -3042,7 +3041,7 @@ QList QTreeWidget::selectedItems() const QList QTreeWidget::findItems(const QString &text, Qt::MatchFlags flags, int column) const { Q_D(const QTreeWidget); - QModelIndexList indexes = d->model()->match(model()->index(0, column, QModelIndex()), + QModelIndexList indexes = d->model->match(model()->index(0, column, QModelIndex()), Qt::DisplayRole, text, -1, flags); QList items; for (int i = 0; i < indexes.size(); ++i) @@ -3060,11 +3059,11 @@ QList QTreeWidget::findItems(const QString &text, Qt::MatchFla bool QTreeWidget::isItemHidden(const QTreeWidgetItem *item) const { Q_D(const QTreeWidget); - if (item == d->model()->headerItem) + if (item == d->treeModel()->headerItem) return header()->isHidden(); if (d->hiddenIndexes.isEmpty()) return false; - QTreeModel::SkipSorting skipSorting(d->model()); + QTreeModel::SkipSorting skipSorting(d->treeModel()); return d->isRowHidden(d->index(item)); } @@ -3080,7 +3079,7 @@ bool QTreeWidget::isItemHidden(const QTreeWidgetItem *item) const void QTreeWidget::setItemHidden(const QTreeWidgetItem *item, bool hide) { Q_D(QTreeWidget); - if (item == d->model()->headerItem) { + if (item == d->treeModel()->headerItem) { header()->setHidden(hide); } else { const QModelIndex index = d->index(item); @@ -3100,7 +3099,7 @@ void QTreeWidget::setItemHidden(const QTreeWidgetItem *item, bool hide) bool QTreeWidget::isItemExpanded(const QTreeWidgetItem *item) const { Q_D(const QTreeWidget); - QTreeModel::SkipSorting skipSorting(d->model()); + QTreeModel::SkipSorting skipSorting(d->treeModel()); return isExpanded(d->index(item)); } @@ -3117,7 +3116,7 @@ bool QTreeWidget::isItemExpanded(const QTreeWidgetItem *item) const void QTreeWidget::setItemExpanded(const QTreeWidgetItem *item, bool expand) { Q_D(QTreeWidget); - QTreeModel::SkipSorting skipSorting(d->model()); + QTreeModel::SkipSorting skipSorting(d->treeModel()); setExpanded(d->index(item), expand); } @@ -3132,7 +3131,7 @@ void QTreeWidget::setItemExpanded(const QTreeWidgetItem *item, bool expand) bool QTreeWidget::isFirstItemColumnSpanned(const QTreeWidgetItem *item) const { Q_D(const QTreeWidget); - if (item == d->model()->headerItem) + if (item == d->treeModel()->headerItem) return false; // We can't set the header items to spanning const QModelIndex index = d->index(item); return isFirstColumnSpanned(index.row(), index.parent()); @@ -3149,7 +3148,7 @@ bool QTreeWidget::isFirstItemColumnSpanned(const QTreeWidgetItem *item) const void QTreeWidget::setFirstItemColumnSpanned(const QTreeWidgetItem *item, bool span) { Q_D(QTreeWidget); - if (item == d->model()->headerItem) + if (item == d->treeModel()->headerItem) return; // We can't set header items to spanning const QModelIndex index = d->index(item); setFirstColumnSpanned(index.row(), index.parent(), span); @@ -3163,7 +3162,7 @@ void QTreeWidget::setFirstItemColumnSpanned(const QTreeWidgetItem *item, bool sp QTreeWidgetItem *QTreeWidget::itemAbove(const QTreeWidgetItem *item) const { Q_D(const QTreeWidget); - if (item == d->model()->headerItem) + if (item == d->treeModel()->headerItem) return 0; const QModelIndex index = d->index(item); const QModelIndex above = indexAbove(index); @@ -3178,7 +3177,7 @@ QTreeWidgetItem *QTreeWidget::itemAbove(const QTreeWidgetItem *item) const QTreeWidgetItem *QTreeWidget::itemBelow(const QTreeWidgetItem *item) const { Q_D(const QTreeWidget); - if (item == d->model()->headerItem) + if (item == d->treeModel()->headerItem) return 0; const QModelIndex index = d->index(item); const QModelIndex below = indexBelow(index); @@ -3218,7 +3217,7 @@ void QTreeWidget::scrollToItem(const QTreeWidgetItem *item, QAbstractItemView::S void QTreeWidget::expandItem(const QTreeWidgetItem *item) { Q_D(QTreeWidget); - QTreeModel::SkipSorting skipSorting(d->model()); + QTreeModel::SkipSorting skipSorting(d->treeModel()); expand(d->index(item)); } @@ -3231,7 +3230,7 @@ void QTreeWidget::expandItem(const QTreeWidgetItem *item) void QTreeWidget::collapseItem(const QTreeWidgetItem *item) { Q_D(QTreeWidget); - QTreeModel::SkipSorting skipSorting(d->model()); + QTreeModel::SkipSorting skipSorting(d->treeModel()); collapse(d->index(item)); } @@ -3248,7 +3247,7 @@ void QTreeWidget::clear() { Q_D(QTreeWidget); selectionModel()->clear(); - d->model()->clear(); + d->treeModel()->clear(); } /*! @@ -3273,7 +3272,7 @@ QStringList QTreeWidget::mimeTypes() const QMimeData *QTreeWidget::mimeData(const QList items) const { Q_D(const QTreeWidget); - if (d->model()->cachedIndexes.isEmpty()) { + if (d->treeModel()->cachedIndexes.isEmpty()) { QList indexes; for (int i = 0; i < items.count(); ++i) { QTreeWidgetItem *item = items.at(i); @@ -3281,9 +3280,9 @@ QMimeData *QTreeWidget::mimeData(const QList items) const indexes << indexFromItem(item, c); } } - return model()->QAbstractItemModel::mimeData(indexes); + return d->model->QAbstractItemModel::mimeData(indexes); } - return d->model()->internalMimeData(); + return d->treeModel()->internalMimeData(); } /*! @@ -3427,7 +3426,7 @@ bool QTreeWidget::event(QEvent *e) { Q_D(QTreeWidget); if (e->type() == QEvent::Polish) - d->model()->executePendingSort(); + d->treeModel()->executePendingSort(); return QTreeView::event(e); } diff --git a/src/gui/itemviews/qtreewidget_p.h b/src/gui/itemviews/qtreewidget_p.h index a089cf5..fb0ee11 100644 --- a/src/gui/itemviews/qtreewidget_p.h +++ b/src/gui/itemviews/qtreewidget_p.h @@ -219,12 +219,11 @@ class QTreeWidgetPrivate : public QTreeViewPrivate Q_DECLARE_PUBLIC(QTreeWidget) public: QTreeWidgetPrivate() : QTreeViewPrivate(), explicitSortColumn(-1) {} - inline QTreeModel *model() const - { return qobject_cast(q_func()->model()); } + inline QTreeModel *treeModel() const { return qobject_cast(model); } inline QModelIndex index(const QTreeWidgetItem *item, int column = 0) const - { return model()->index(item, column); } + { return treeModel()->index(item, column); } inline QTreeWidgetItem *item(const QModelIndex &index) const - { return model()->item(index); } + { return treeModel()->item(index); } void _q_emitItemPressed(const QModelIndex &index); void _q_emitItemClicked(const QModelIndex &index); void _q_emitItemDoubleClicked(const QModelIndex &index); diff --git a/src/gui/text/qtextdocumentlayout.cpp b/src/gui/text/qtextdocumentlayout.cpp index fa032e6..cf40ad8 100644 --- a/src/gui/text/qtextdocumentlayout.cpp +++ b/src/gui/text/qtextdocumentlayout.cpp @@ -3205,18 +3205,16 @@ bool QTextDocumentLayout::contentHasAlignment() const qreal QTextDocumentLayoutPrivate::scaleToDevice(qreal value) const { - QPaintDevice *dev = q_func()->paintDevice(); - if (!dev) + if (!paintDevice) return value; - return value * dev->logicalDpiY() / qreal(qt_defaultDpi()); + return value * paintDevice->logicalDpiY() / qreal(qt_defaultDpi()); } QFixed QTextDocumentLayoutPrivate::scaleToDevice(QFixed value) const { - QPaintDevice *dev = q_func()->paintDevice(); - if (!dev) + if (!paintDevice) return value; - return value * QFixed(dev->logicalDpiY()) / QFixed(qt_defaultDpi()); + return value * QFixed(paintDevice->logicalDpiY()) / QFixed(qt_defaultDpi()); } QT_END_NAMESPACE -- cgit v0.12 From 35e2a2978a2318ca025393a8f67d30746c8b78fc Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 11 Jun 2009 13:39:09 +0200 Subject: Removed qApp and replaced with QApplication:: for static member calls --- src/gui/accessible/qaccessible_win.cpp | 4 +- src/gui/accessible/qaccessibleobject.cpp | 14 ++--- src/gui/dialogs/qcolordialog.cpp | 2 +- src/gui/dialogs/qerrormessage.cpp | 2 +- src/gui/dialogs/qfiledialog_win.cpp | 6 +-- src/gui/dialogs/qfilesystemmodel.cpp | 2 +- src/gui/dialogs/qmessagebox.cpp | 10 ++-- src/gui/dialogs/qpagesetupdialog_win.cpp | 2 +- src/gui/dialogs/qprintdialog_win.cpp | 2 +- src/gui/dialogs/qprogressdialog.cpp | 2 +- src/gui/dialogs/qwizard.cpp | 2 +- src/gui/dialogs/qwizard_win.cpp | 4 +- src/gui/graphicsview/qgraphicsgridlayout.cpp | 2 +- src/gui/graphicsview/qgraphicslinearlayout.cpp | 2 +- src/gui/graphicsview/qgraphicsscene.cpp | 16 +++--- src/gui/image/qicon.cpp | 2 +- src/gui/inputmethod/qinputcontext.cpp | 4 +- src/gui/inputmethod/qwininputcontext_win.cpp | 4 +- src/gui/itemviews/qabstractitemview.cpp | 2 +- src/gui/itemviews/qcolumnview.cpp | 2 +- src/gui/kernel/qapplication.cpp | 36 ++++++------- src/gui/kernel/qapplication_win.cpp | 74 +++++++++++++------------- src/gui/kernel/qcursor.cpp | 2 +- src/gui/kernel/qdnd.cpp | 2 +- src/gui/kernel/qdnd_win.cpp | 2 +- src/gui/kernel/qshortcutmap.cpp | 6 +-- src/gui/kernel/qwidget.cpp | 24 ++++----- src/gui/kernel/qwidget_win.cpp | 6 +-- src/gui/painting/qbackingstore.cpp | 4 +- src/gui/styles/qcleanlooksstyle.cpp | 4 +- src/gui/styles/qcommonstyle.cpp | 6 +-- src/gui/styles/qstylesheetstyle.cpp | 8 +-- src/gui/styles/qwindowsvistastyle.cpp | 4 +- src/gui/styles/qwindowsxpstyle.cpp | 6 +-- src/gui/text/qfontdatabase.cpp | 36 ++++++------- src/gui/text/qtextcontrol.cpp | 2 +- src/gui/util/qsystemtrayicon_win.cpp | 2 +- src/gui/widgets/qabstractbutton.cpp | 2 +- src/gui/widgets/qeffects.cpp | 8 +-- src/gui/widgets/qmenu.cpp | 12 ++--- src/gui/widgets/qmenubar.cpp | 4 +- src/gui/widgets/qpushbutton.cpp | 4 +- src/gui/widgets/qtabwidget.cpp | 2 +- src/gui/widgets/qtextbrowser.cpp | 8 +-- src/gui/widgets/qtoolbar.cpp | 4 +- src/gui/widgets/qtoolbutton.cpp | 2 +- src/gui/widgets/qwidgetresizehandler.cpp | 2 +- 47 files changed, 178 insertions(+), 180 deletions(-) diff --git a/src/gui/accessible/qaccessible_win.cpp b/src/gui/accessible/qaccessible_win.cpp index f287874..6195451 100644 --- a/src/gui/accessible/qaccessible_win.cpp +++ b/src/gui/accessible/qaccessible_win.cpp @@ -270,9 +270,9 @@ void QAccessible::updateAccessibility(QObject *o, int who, Event reason) if (!w) { if (reason != QAccessible::ContextHelpStart && reason != QAccessible::ContextHelpEnd) - w = qApp->focusWidget(); + w = QApplication::focusWidget(); if (!w) { - w = qApp->activeWindow(); + w = QApplication::activeWindow(); if (!w) return; diff --git a/src/gui/accessible/qaccessibleobject.cpp b/src/gui/accessible/qaccessibleobject.cpp index 7df097b..0c710f0 100644 --- a/src/gui/accessible/qaccessibleobject.cpp +++ b/src/gui/accessible/qaccessibleobject.cpp @@ -212,7 +212,7 @@ QAccessibleApplication::QAccessibleApplication() static QWidgetList topLevelWidgets() { QWidgetList list; - const QWidgetList tlw(qApp->topLevelWidgets()); + const QWidgetList tlw(QApplication::topLevelWidgets()); for (int i = 0; i < tlw.count(); ++i) { QWidget *w = tlw.at(i); if (!(w->windowType() == Qt::Popup) && !(w->windowType() == Qt::Desktop)) @@ -308,7 +308,7 @@ int QAccessibleApplication::navigate(RelationFlag relation, int entry, } break; case FocusChild: - targetObject = qApp->activeWindow(); + targetObject = QApplication::activeWindow(); break; default: break; @@ -322,11 +322,11 @@ QString QAccessibleApplication::text(Text t, int) const { switch (t) { case Name: - if (qApp->activeWindow()) - return qApp->activeWindow()->windowTitle(); + if (QApplication::activeWindow()) + return QApplication::activeWindow()->windowTitle(); break; case Description: - return qApp->applicationFilePath(); + return QApplication::applicationFilePath(); default: break; } @@ -342,7 +342,7 @@ QAccessible::Role QAccessibleApplication::role(int) const /*! \reimp */ QAccessible::State QAccessibleApplication::state(int) const { - return qApp->activeWindow() ? Focused : Normal; + return QApplication::activeWindow() ? Focused : Normal; } /*! \reimp */ @@ -356,7 +356,7 @@ bool QAccessibleApplication::doAction(int action, int child, const QVariantList { if (action == 0 || action == 1) { QWidget *w = 0; - w = qApp->activeWindow(); + w = QApplication::activeWindow(); if (!w) w = topLevelWidgets().at(0); if (!w) diff --git a/src/gui/dialogs/qcolordialog.cpp b/src/gui/dialogs/qcolordialog.cpp index dc7e3cc..8299381 100644 --- a/src/gui/dialogs/qcolordialog.cpp +++ b/src/gui/dialogs/qcolordialog.cpp @@ -1375,7 +1375,7 @@ void QColorDialogPrivate::init(const QColor &initial) #else // small displays (e.g. PDAs) cannot fit the full color dialog, // so just use the color picker. - smallDisplay = (qApp->desktop()->width() < 480 || qApp->desktop()->height() < 350); + smallDisplay = (QApplication::desktop()->width() < 480 || QApplication::desktop()->height() < 350); const int lumSpace = topLay->spacing() / 2; #endif diff --git a/src/gui/dialogs/qerrormessage.cpp b/src/gui/dialogs/qerrormessage.cpp index ca39d31..d24d348 100644 --- a/src/gui/dialogs/qerrormessage.cpp +++ b/src/gui/dialogs/qerrormessage.cpp @@ -300,7 +300,7 @@ QErrorMessage * QErrorMessage::qtHandler() if (!qtMessageHandler) { qtMessageHandler = new QErrorMessage(0); qAddPostRoutine(deleteStaticcQErrorMessage); // clean up - qtMessageHandler->setWindowTitle(qApp->applicationName()); + qtMessageHandler->setWindowTitle(QApplication::applicationName()); qInstallMsgHandler(jump); } return qtMessageHandler; diff --git a/src/gui/dialogs/qfiledialog_win.cpp b/src/gui/dialogs/qfiledialog_win.cpp index 75a1820..4e818be 100644 --- a/src/gui/dialogs/qfiledialog_win.cpp +++ b/src/gui/dialogs/qfiledialog_win.cpp @@ -206,7 +206,7 @@ static OPENFILENAMEA *qt_win_make_OFNA(QWidget *parent, if (parent) parent = parent->window(); else - parent = qApp->activeWindow(); + parent = QApplication::activeWindow(); aTitle = title.toLocal8Bit(); aInitDir = QDir::toNativeSeparators(initialDirectory).toLocal8Bit(); @@ -279,7 +279,7 @@ static OPENFILENAME* qt_win_make_OFN(QWidget *parent, if (parent) parent = parent->window(); else - parent = qApp->activeWindow(); + parent = QApplication::activeWindow(); tInitDir = QDir::toNativeSeparators(initialDirectory); tFilters = filters; @@ -692,7 +692,7 @@ QString qt_win_get_existing_directory(const QFileDialogArgs &args) if (parent) parent = parent->window(); else - parent = qApp->activeWindow(); + parent = QApplication::activeWindow(); if (parent) parent->createWinId(); diff --git a/src/gui/dialogs/qfilesystemmodel.cpp b/src/gui/dialogs/qfilesystemmodel.cpp index 2c47116..603789e 100644 --- a/src/gui/dialogs/qfilesystemmodel.cpp +++ b/src/gui/dialogs/qfilesystemmodel.cpp @@ -1407,7 +1407,7 @@ void QFileSystemModel::setIconProvider(QFileIconProvider *provider) { Q_D(QFileSystemModel); d->fileInfoGatherer.setIconProvider(provider); - qApp->processEvents(); + QApplication::processEvents(); d->root.updateIcon(provider, QString()); } diff --git a/src/gui/dialogs/qmessagebox.cpp b/src/gui/dialogs/qmessagebox.cpp index c526c7d..1fefb67 100644 --- a/src/gui/dialogs/qmessagebox.cpp +++ b/src/gui/dialogs/qmessagebox.cpp @@ -332,7 +332,7 @@ void QMessageBoxPrivate::updateSize() label->setSizePolicy(policy); } - QFontMetrics fm(qApp->font("QWorkspaceTitleBar")); + QFontMetrics fm(QApplication::font("QWorkspaceTitleBar")); int windowTitleWidth = qMin(fm.width(q->windowTitle()) + 50, hardLimit); if (windowTitleWidth > width) width = windowTitleWidth; @@ -361,7 +361,7 @@ void QMessageBoxPrivate::hideSpecial() QPushButton *pb = list.at(i); QString text = pb->text(); text.remove(QChar::fromLatin1('&')); - if (text == qApp->translate("QMessageBox", "OK" )) + if (text == QApplication::translate("QMessageBox", "OK" )) pb->setFixedSize(0,0); } } @@ -1208,8 +1208,8 @@ bool QMessageBox::event(QEvent *e) case QEvent::HelpRequest: { QString bName = (e->type() == QEvent::OkRequest) - ? qApp->translate("QMessageBox", "OK") - : qApp->translate("QMessageBox", "Help"); + ? QApplication::translate("QMessageBox", "OK") + : QApplication::translate("QMessageBox", "Help"); QList list = qFindChildren(this); for (int i=0; iclipboard()->setText(textToCopy); + QApplication::clipboard()->setText(textToCopy); return; } #endif //QT_NO_SHORTCUT QT_NO_CLIPBOARD Q_OS_WIN diff --git a/src/gui/dialogs/qpagesetupdialog_win.cpp b/src/gui/dialogs/qpagesetupdialog_win.cpp index 4bb571c..2c74ed2 100644 --- a/src/gui/dialogs/qpagesetupdialog_win.cpp +++ b/src/gui/dialogs/qpagesetupdialog_win.cpp @@ -98,7 +98,7 @@ int QPageSetupDialog::exec() psd.hDevNames = tempDevNames; QWidget *parent = parentWidget(); - parent = parent ? parent->window() : qApp->activeWindow(); + parent = parent ? parent->window() : QApplication::activeWindow(); Q_ASSERT(!parent ||parent->testAttribute(Qt::WA_WState_Created)); psd.hwndOwner = parent ? parent->winId() : 0; diff --git a/src/gui/dialogs/qprintdialog_win.cpp b/src/gui/dialogs/qprintdialog_win.cpp index 936d1ed..2561227 100644 --- a/src/gui/dialogs/qprintdialog_win.cpp +++ b/src/gui/dialogs/qprintdialog_win.cpp @@ -225,7 +225,7 @@ int QPrintDialogPrivate::openWindowsPrintDialogModally() if (parent) parent = parent->window(); else - parent = qApp->activeWindow(); + parent = QApplication::activeWindow(); QWidget modal_widget; modal_widget.setAttribute(Qt::WA_NoChildEventsForParent, true); diff --git a/src/gui/dialogs/qprogressdialog.cpp b/src/gui/dialogs/qprogressdialog.cpp index 66a1285..b68a0a72 100644 --- a/src/gui/dialogs/qprogressdialog.cpp +++ b/src/gui/dialogs/qprogressdialog.cpp @@ -643,7 +643,7 @@ void QProgressDialog::setValue(int progress) if (d->shown_once) { if (isModal()) - qApp->processEvents(); + QApplication::processEvents(); } else { if (progress == 0) { d->starttime.start(); diff --git a/src/gui/dialogs/qwizard.cpp b/src/gui/dialogs/qwizard.cpp index b2ed983..7fc8a63 100644 --- a/src/gui/dialogs/qwizard.cpp +++ b/src/gui/dialogs/qwizard.cpp @@ -377,7 +377,7 @@ void QWizardHeader::setup(const QWizardLayoutInfo &info, const QString &title, /* There is no widthForHeight() function, so we simulate it with a loop. */ - int candidateSubTitleWidth = qMin(512, 2 * qApp->desktop()->width() / 3); + int candidateSubTitleWidth = qMin(512, 2 * QApplication::desktop()->width() / 3); int delta = candidateSubTitleWidth >> 1; while (delta > 0) { if (subTitleLabel->heightForWidth(candidateSubTitleWidth - delta) diff --git a/src/gui/dialogs/qwizard_win.cpp b/src/gui/dialogs/qwizard_win.cpp index 8aad4af..e0aaa19 100644 --- a/src/gui/dialogs/qwizard_win.cpp +++ b/src/gui/dialogs/qwizard_win.cpp @@ -279,7 +279,7 @@ QVistaHelper::VistaState QVistaHelper::vistaState() QColor QVistaHelper::basicWindowFrameColor() { DWORD rgb; - HANDLE hTheme = pOpenThemeData(qApp->desktop()->winId(), L"WINDOW"); + HANDLE hTheme = pOpenThemeData(QApplication::desktop()->winId(), L"WINDOW"); pGetThemeColor( hTheme, WIZ_WP_CAPTION, WIZ_CS_ACTIVE, wizard->isActiveWindow() ? WIZ_TMT_FILLCOLORHINT : WIZ_TMT_BORDERCOLORHINT, @@ -611,7 +611,7 @@ bool QVistaHelper::drawTitleText(QPainter *painter, const QString &text, const Q { bool value = false; if (vistaState() == VistaAero) { - HANDLE hTheme = pOpenThemeData(qApp->desktop()->winId(), L"WINDOW"); + HANDLE hTheme = pOpenThemeData(QApplication::desktop()->winId(), L"WINDOW"); if (!hTheme) return false; // Set up a memory DC and bitmap that we'll draw into HDC dcMem; diff --git a/src/gui/graphicsview/qgraphicsgridlayout.cpp b/src/gui/graphicsview/qgraphicsgridlayout.cpp index 1e21b54..36281f8 100644 --- a/src/gui/graphicsview/qgraphicsgridlayout.cpp +++ b/src/gui/graphicsview/qgraphicsgridlayout.cpp @@ -100,7 +100,7 @@ QLayoutStyleInfo QGraphicsGridLayoutPrivate::styleInfo() const if (!wid) wid = new QWidget; QGraphicsItem *item = parentItem(); - QStyle *style = (item && item->isWidget()) ? static_cast(item)->style() : qApp->style(); + QStyle *style = (item && item->isWidget()) ? static_cast(item)->style() : QApplication::style(); return QLayoutStyleInfo(style, wid); } diff --git a/src/gui/graphicsview/qgraphicslinearlayout.cpp b/src/gui/graphicsview/qgraphicslinearlayout.cpp index 6a2d456..2f32950 100644 --- a/src/gui/graphicsview/qgraphicslinearlayout.cpp +++ b/src/gui/graphicsview/qgraphicslinearlayout.cpp @@ -178,7 +178,7 @@ QLayoutStyleInfo QGraphicsLinearLayoutPrivate::styleInfo() const if (!wid) wid = new QWidget; QGraphicsItem *item = parentItem(); - QStyle *style = (item && item->isWidget()) ? static_cast(item)->style() : qApp->style(); + QStyle *style = (item && item->isWidget()) ? static_cast(item)->style() : QApplication::style(); return QLayoutStyleInfo(style, wid); } diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index e6c3503..1c48675 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -2161,7 +2161,7 @@ void QGraphicsScenePrivate::setFont_helper(const QFont &font) */ void QGraphicsScenePrivate::resolveFont() { - QFont naturalFont = qApp->font(); + QFont naturalFont = QApplication::font(); naturalFont.resolve(0); QFont resolvedFont = font.resolve(naturalFont); updateFont(resolvedFont); @@ -2217,7 +2217,7 @@ void QGraphicsScenePrivate::setPalette_helper(const QPalette &palette) */ void QGraphicsScenePrivate::resolvePalette() { - QPalette naturalPalette = qApp->palette(); + QPalette naturalPalette = QApplication::palette(); naturalPalette.resolve(0); QPalette resolvedPalette = palette.resolve(naturalPalette); updatePalette(resolvedPalette); @@ -3975,10 +3975,10 @@ bool QGraphicsScene::eventFilter(QObject *watched, QEvent *event) switch (event->type()) { case QEvent::ApplicationPaletteChange: - qApp->postEvent(this, new QEvent(QEvent::ApplicationPaletteChange)); + QApplication::postEvent(this, new QEvent(QEvent::ApplicationPaletteChange)); break; case QEvent::ApplicationFontChange: - qApp->postEvent(this, new QEvent(QEvent::ApplicationFontChange)); + QApplication::postEvent(this, new QEvent(QEvent::ApplicationFontChange)); break; default: break; @@ -4918,7 +4918,7 @@ void QGraphicsScenePrivate::drawItemHelper(QGraphicsItem *item, QPainter *painte bool allowPartialCacheExposure = !viewRect.contains(deviceRect); #else // Only if deviceRect is 20% taller or wider than the desktop. - QRect desktopRect = qApp->desktop()->availableGeometry(widget); + QRect desktopRect = QApplication::desktop()->availableGeometry(widget); bool allowPartialCacheExposure = (desktopRect.width() * 1.2 < deviceRect.width() || desktopRect.height() * 1.2 < deviceRect.height()); #endif @@ -5606,7 +5606,7 @@ QStyle *QGraphicsScene::style() const { Q_D(const QGraphicsScene); // ### This function, and the use of styles in general, is non-reentrant. - return d->style ? d->style : qApp->style(); + return d->style ? d->style : QApplication::style(); } /*! @@ -5683,7 +5683,7 @@ QFont QGraphicsScene::font() const void QGraphicsScene::setFont(const QFont &font) { Q_D(QGraphicsScene); - QFont naturalFont = qApp->font(); + QFont naturalFont = QApplication::font(); naturalFont.resolve(0); QFont resolvedFont = font.resolve(naturalFont); d->setFont_helper(resolvedFont); @@ -5720,7 +5720,7 @@ QPalette QGraphicsScene::palette() const void QGraphicsScene::setPalette(const QPalette &palette) { Q_D(QGraphicsScene); - QPalette naturalPalette = qApp->palette(); + QPalette naturalPalette = QApplication::palette(); naturalPalette.resolve(0); QPalette resolvedPalette = palette.resolve(naturalPalette); d->setPalette_helper(resolvedPalette); diff --git a/src/gui/image/qicon.cpp b/src/gui/image/qicon.cpp index f24aeff..7e262b1 100644 --- a/src/gui/image/qicon.cpp +++ b/src/gui/image/qicon.cpp @@ -304,7 +304,7 @@ QPixmap QPixmapIconEngine::pixmap(const QSize &size, QIcon::Mode mode, QIcon::St QString key = QLatin1String("$qt_icon_") + QString::number(pm.cacheKey()) + QString::number(pe->mode) - + QString::number(qApp->palette().cacheKey()) + + QString::number(QApplication::palette().cacheKey()) + QLatin1Char('_') + QString::number(actualSize.width()) + QLatin1Char('_') diff --git a/src/gui/inputmethod/qinputcontext.cpp b/src/gui/inputmethod/qinputcontext.cpp index f78b86a..8db326b 100644 --- a/src/gui/inputmethod/qinputcontext.cpp +++ b/src/gui/inputmethod/qinputcontext.cpp @@ -262,7 +262,7 @@ void QInputContext::sendEvent(const QInputMethodEvent &event) return; QInputMethodEvent e(event); - qApp->sendEvent(focus, &e); + QApplication::sendEvent(focus, &e); } @@ -408,7 +408,7 @@ QList QInputContext::actions() QTextFormat QInputContext::standardFormat(StandardFormat s) const { QWidget *focus = focusWidget(); - const QPalette &pal = focus ? focus->palette() : qApp->palette(); + const QPalette &pal = focus ? focus->palette() : QApplication::palette(); QTextCharFormat fmt; QColor bg; diff --git a/src/gui/inputmethod/qwininputcontext_win.cpp b/src/gui/inputmethod/qwininputcontext_win.cpp index dd966d5..b94c604 100644 --- a/src/gui/inputmethod/qwininputcontext_win.cpp +++ b/src/gui/inputmethod/qwininputcontext_win.cpp @@ -539,7 +539,7 @@ bool QWinInputContext::endComposition() } if (!fw) - fw = qApp->focusWidget(); + fw = QApplication::focusWidget(); if (fw) { QInputMethodEvent e; @@ -637,7 +637,7 @@ bool QWinInputContext::composition(LPARAM lParam) // bogus event return true; - QWidget *fw = qApp->focusWidget(); + QWidget *fw = QApplication::focusWidget(); if (fw) { Q_ASSERT(fw->testAttribute(Qt::WA_WState_Created)); HIMC imc = getContext(fw->effectiveWinId()); diff --git a/src/gui/itemviews/qabstractitemview.cpp b/src/gui/itemviews/qabstractitemview.cpp index 7890e1f..9effc70 100644 --- a/src/gui/itemviews/qabstractitemview.cpp +++ b/src/gui/itemviews/qabstractitemview.cpp @@ -3784,7 +3784,7 @@ void QAbstractItemViewPrivate::clearOrRemove() void QAbstractItemViewPrivate::checkPersistentEditorFocus() { Q_Q(QAbstractItemView); - if (QWidget *widget = qApp->focusWidget()) { + if (QWidget *widget = QApplication::focusWidget()) { if (persistent.contains(widget)) { //a persistent editor has gained the focus QModelIndex index = indexForEditor(widget); diff --git a/src/gui/itemviews/qcolumnview.cpp b/src/gui/itemviews/qcolumnview.cpp index 1f88f7c..16ae8e9 100644 --- a/src/gui/itemviews/qcolumnview.cpp +++ b/src/gui/itemviews/qcolumnview.cpp @@ -1116,7 +1116,7 @@ void QColumnViewDelegate::paint(QPainter *painter, // Draw > if (index.model()->hasChildren(index)) { const QWidget *view = opt.widget; - QStyle *style = view ? view->style() : qApp->style(); + QStyle *style = view ? view->style() : QApplication::style(); style->drawPrimitive(QStyle::PE_IndicatorColumnViewArrow, &opt, painter, view); } } diff --git a/src/gui/kernel/qapplication.cpp b/src/gui/kernel/qapplication.cpp index 4923d23..cbb1f45 100644 --- a/src/gui/kernel/qapplication.cpp +++ b/src/gui/kernel/qapplication.cpp @@ -491,8 +491,6 @@ QWidgetList * qt_modal_stack=0; // stack of modal widgets */ void QApplicationPrivate::process_cmdline() { - Q_Q(QApplication); - Q_UNUSED(q);// only static members being used. // process platform-indep command line if (!qt_is_gui_used || !argc) return; @@ -537,7 +535,7 @@ void QApplicationPrivate::process_cmdline() #endif } else if (qstrcmp(arg, "-reverse") == 0) { force_reverse = true; - q->setLayoutDirection(Qt::RightToLeft); + QApplication::setLayoutDirection(Qt::RightToLeft); } else if (qstrcmp(arg, "-widgetcount") == 0) { widgetCount = true; } else if (arg == "-graphicssystem" && i < argc-1) { @@ -2577,14 +2575,14 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave) { QEvent leaveEvent(QEvent::Leave); for (int i = 0; i < leaveList.size(); ++i) { w = leaveList.at(i); - if (!qApp->activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) { + if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) { #if defined(Q_WS_WIN) || defined(Q_WS_X11) if (leaveAfterRelease == w) leaveAfterRelease = 0; #endif QApplication::sendEvent(w, &leaveEvent); if (w->testAttribute(Qt::WA_Hover) && - (!qApp->activePopupWidget() || qApp->activePopupWidget() == w->window())) { + (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) { Q_ASSERT(instance()); QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1), w->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos)); qApp->d_func()->notify_helper(w, &he); @@ -2595,10 +2593,10 @@ void QApplicationPrivate::dispatchEnterLeave(QWidget* enter, QWidget* leave) { QEvent enterEvent(QEvent::Enter); for (int i = 0; i < enterList.size(); ++i) { w = enterList.at(i); - if (!qApp->activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) { + if (!QApplication::activeModalWidget() || QApplicationPrivate::tryModalHelper(w, 0)) { QApplication::sendEvent(w, &enterEvent); if (w->testAttribute(Qt::WA_Hover) && - (!qApp->activePopupWidget() || qApp->activePopupWidget() == w->window())) { + (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) { QHoverEvent he(QEvent::HoverEnter, w->mapFromGlobal(posEnter), QPoint(-1, -1)); qApp->d_func()->notify_helper(w, &he); } @@ -2672,7 +2670,7 @@ bool QApplicationPrivate::isBlockedByModal(QWidget *widget) widget = widget->window(); if (!modalState()) return false; - if (qApp->activePopupWidget() == widget) + if (QApplication::activePopupWidget() == widget) return false; for (int i = 0; i < qt_modal_stack->size(); ++i) { @@ -2761,7 +2759,7 @@ bool QApplicationPrivate::isBlockedByModal(QWidget *widget) void QApplicationPrivate::enterModal(QWidget *widget) { QSet blocked; - QList windows = qApp->topLevelWidgets(); + QList windows = QApplication::topLevelWidgets(); for (int i = 0; i < windows.count(); ++i) { QWidget *window = windows.at(i); if (window->windowType() != Qt::Tool && isBlockedByModal(window)) @@ -2770,7 +2768,7 @@ void QApplicationPrivate::enterModal(QWidget *widget) enterModal_sys(widget); - windows = qApp->topLevelWidgets(); + windows = QApplication::topLevelWidgets(); QEvent e(QEvent::WindowBlocked); for (int i = 0; i < windows.count(); ++i) { QWidget *window = windows.at(i); @@ -2784,7 +2782,7 @@ void QApplicationPrivate::enterModal(QWidget *widget) void QApplicationPrivate::leaveModal(QWidget *widget) { QSet blocked; - QList windows = qApp->topLevelWidgets(); + QList windows = QApplication::topLevelWidgets(); for (int i = 0; i < windows.count(); ++i) { QWidget *window = windows.at(i); if (window->windowType() != Qt::Tool && isBlockedByModal(window)) @@ -2793,7 +2791,7 @@ void QApplicationPrivate::leaveModal(QWidget *widget) leaveModal_sys(widget); - windows = qApp->topLevelWidgets(); + windows = QApplication::topLevelWidgets(); QEvent e(QEvent::WindowUnblocked); for (int i = 0; i < windows.count(); ++i) { QWidget *window = windows.at(i); @@ -2816,7 +2814,7 @@ bool QApplicationPrivate::tryModalHelper(QWidget *widget, QWidget **rettop) *rettop = top; // the active popup widget always gets the input event - if (qApp->activePopupWidget()) + if (QApplication::activePopupWidget()) return true; #if defined(Q_WS_MAC) && defined(QT_MAC_USE_COCOA) @@ -2882,7 +2880,7 @@ bool QApplicationPrivate::sendMouseEvent(QWidget *receiver, QMouseEvent *event, QPointer receiverGuard = receiver; QPointer nativeGuard = nativeWidget; QPointer alienGuard = alienWidget; - QPointer activePopupWidget = qApp->activePopupWidget(); + QPointer activePopupWidget = QApplication::activePopupWidget(); const bool graphicsWidget = nativeWidget->testAttribute(Qt::WA_DontShowOnScreen); @@ -3779,7 +3777,7 @@ bool QApplication::notify(QObject *receiver, QEvent *e) QPoint diff = relpos - w->mapFromGlobal(d->hoverGlobalPos); while (w) { if (w->testAttribute(Qt::WA_Hover) && - (!qApp->activePopupWidget() || qApp->activePopupWidget() == w->window())) { + (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == w->window())) { QHoverEvent he(QEvent::HoverMove, relpos, relpos - diff); d->notify_helper(w, &he); } @@ -4038,7 +4036,7 @@ bool QApplicationPrivate::notify_helper(QObject *receiver, QEvent * e) #if !defined(Q_WS_WINCE) || (defined(GWES_ICONCURS) && !defined(QT_NO_CURSOR)) // toggle HasMouse widget state on enter and leave if ((e->type() == QEvent::Enter || e->type() == QEvent::DragEnter) && - (!qApp->activePopupWidget() || qApp->activePopupWidget() == widget->window())) + (!QApplication::activePopupWidget() || QApplication::activePopupWidget() == widget->window())) widget->setAttribute(Qt::WA_UnderMouse, true); else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave) widget->setAttribute(Qt::WA_UnderMouse, false); @@ -4568,9 +4566,9 @@ void QSessionManager::requestPhase2() \oldcode app.setWinStyleHighlightColor(color); \newcode - QPalette palette(qApp->palette()); + QPalette palette(QApplication::palette()); palette.setColor(QPalette::Highlight, color); - qApp->setPalette(palette); + QApplication::setPalette(palette); \endcode */ @@ -4589,7 +4587,7 @@ void QSessionManager::requestPhase2() /*! \fn const QColor &QApplication::winStyleHighlightColor() - Use qApp->palette().color(QPalette::Active, QPalette::Highlight) instead. + Use QApplication::palette().color(QPalette::Active, QPalette::Highlight) instead. */ /*! diff --git a/src/gui/kernel/qapplication_win.cpp b/src/gui/kernel/qapplication_win.cpp index 8d77c4c..f449141 100644 --- a/src/gui/kernel/qapplication_win.cpp +++ b/src/gui/kernel/qapplication_win.cpp @@ -1526,13 +1526,13 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam int index = QApplication::staticMetaObject.indexOfSignal("aboutToQuit()"); qApp->qt_metacall(QMetaObject::InvokeMetaMethod, index,0); // since the process will be killed immediately quit() has no real effect - qApp->quit(); + QApplication::quit(); } RETURN(0); } case WM_DISPLAYCHANGE: - if (qApp->type() == QApplication::Tty) + if (QApplication::type() == QApplication::Tty) break; if (qt_desktopWidget) { qt_desktopWidget->move(GetSystemMetrics(76), GetSystemMetrics(77)); @@ -1558,7 +1558,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam } #endif // ignore spurious XP message when user logs in again after locking - if (qApp->type() == QApplication::Tty) + if (QApplication::type() == QApplication::Tty) break; if (QApplication::desktopSettingsAware() && wParam != SPI_SETWORKAREA) { widget = (QETWidget*)QWidget::find(hwnd); @@ -1581,7 +1581,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam if (wParam == SPI_SETFONTSMOOTHINGTYPE) { qt_win_read_cleartype_settings(); - foreach (QWidget *w, qApp->topLevelWidgets()) { + foreach (QWidget *w, QApplication::topLevelWidgets()) { if (!w->isVisible()) continue; ((QETWidget *) w)->forceUpdate(); @@ -1590,7 +1590,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam break; case WM_SYSCOLORCHANGE: - if (qApp->type() == QApplication::Tty) + if (QApplication::type() == QApplication::Tty) break; if (QApplication::desktopSettingsAware()) { widget = (QETWidget*)QWidget::find(hwnd); @@ -1642,7 +1642,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam RETURN(res); if (qt_is_translatable_mouse_event(message)) { - if (qApp->activePopupWidget() != 0) { // in popup mode + if (QApplication::activePopupWidget() != 0) { // in popup mode POINT curPos = msg.pt; QWidget* w = QApplication::widgetAt(curPos.x, curPos.y); if (w) @@ -1652,9 +1652,9 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam if (!qt_tabletChokeMouse) { result = widget->translateMouseEvent(msg); // mouse event #if defined(Q_WS_WINCE) && !defined(QT_NO_CONTEXTMENU) - if (message == WM_LBUTTONDOWN && widget != qApp->activePopupWidget()) { + if (message == WM_LBUTTONDOWN && widget != QApplication::activePopupWidget()) { QWidget* alienWidget = widget; - if ((alienWidget != qApp->activePopupWidget()) && (alienWidget->contextMenuPolicy() != Qt::PreventContextMenu)) { + if ((alienWidget != QApplication::activePopupWidget()) && (alienWidget->contextMenuPolicy() != Qt::PreventContextMenu)) { QPoint pos(GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam)); QPoint globalPos(msg.pt.x, msg.pt.y); // In case we are using Alien, then the widget to @@ -1673,8 +1673,8 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam shrg.dwFlags = SHRG_RETURNCMD | SHRG_NOANIMATION; resolveAygLibs(); if (ptrRecognizeGesture && (ptrRecognizeGesture(&shrg) == GN_CONTEXTMENU)) { - if (qApp->activePopupWidget()) - qApp->activePopupWidget()->close(); + if (QApplication::activePopupWidget()) + QApplication::activePopupWidget()->close(); QContextMenuEvent e(QContextMenuEvent::Mouse, pos, globalPos); result = qt_sendSpontaneousEvent(alienWidget, &e); } @@ -1752,7 +1752,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam widget = (QETWidget*)QApplication::activePopupWidget()->focusWidget() ? (QETWidget*)QApplication::activePopupWidget()->focusWidget() : (QETWidget*)QApplication::activePopupWidget(); - else if (qApp->focusWidget()) + else if (QApplication::focusWidget()) widget = (QETWidget*)QApplication::focusWidget(); else if (!widget || widget->internalWinId() == GetFocus()) // We faked the message to go to exactly that widget. widget = (QETWidget*)widget->window(); @@ -1875,8 +1875,8 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam QWidget *g = QWidget::keyboardGrabber(); if (g) widget = (QETWidget*)g; - else if (qApp->focusWidget()) - widget = (QETWidget*)qApp->focusWidget(); + else if (QApplication::focusWidget()) + widget = (QETWidget*)QApplication::focusWidget(); else widget = (QETWidget*)widget->window(); if (widget->isEnabled()) { @@ -1991,7 +1991,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam } case WM_SETTINGCHANGE: - if ( qApp->type() == QApplication::Tty ) + if ( QApplication::type() == QApplication::Tty ) break; if (!msg.wParam) { @@ -2004,7 +2004,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam } } else if (msg.wParam == SPI_SETICONTITLELOGFONT) { - if (qApp->desktopSettingsAware()) { + if (QApplication::desktopSettingsAware()) { widget = (QETWidget*)QWidget::find(hwnd); if (widget && !widget->parentWidget()) { qt_set_windows_font_resources(); @@ -2047,7 +2047,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam break; case WM_ACTIVATE: - if ( qApp->type() == QApplication::Tty ) + if ( QApplication::type() == QApplication::Tty ) break; if (ptrWTOverlap && ptrWTEnable) { @@ -2276,12 +2276,12 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam QWidget *fw = QWidget::keyboardGrabber(); if (!fw) { - if (qApp->activePopupWidget()) - fw = (qApp->activePopupWidget()->focusWidget() - ? qApp->activePopupWidget()->focusWidget() - : qApp->activePopupWidget()); - else if (qApp->focusWidget()) - fw = qApp->focusWidget(); + if (QApplication::activePopupWidget()) + fw = (QApplication::activePopupWidget()->focusWidget() + ? QApplication::activePopupWidget()->focusWidget() + : QApplication::activePopupWidget()); + else if (QApplication::focusWidget()) + fw = QApplication::focusWidget(); else if (widget) fw = widget->window(); } @@ -2298,7 +2298,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam case WM_IME_STARTCOMPOSITION: case WM_IME_ENDCOMPOSITION: case WM_IME_COMPOSITION: { - QWidget *fw = qApp->focusWidget(); + QWidget *fw = QApplication::focusWidget(); QWinInputContext *im = fw ? qobject_cast(fw->inputContext()) : 0; if (fw && im) { if(message == WM_IME_STARTCOMPOSITION) @@ -2331,7 +2331,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam case WM_GETOBJECT: { // Ignoring all requests while starting up - if (qApp->startingUp() || qApp->closingDown() || (DWORD)lParam != OBJID_CLIENT) { + if (QApplication::startingUp() || QApplication::closingDown() || (DWORD)lParam != OBJID_CLIENT) { result = false; break; } @@ -2431,7 +2431,7 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam case WM_KILLFOCUS: if (!QWidget::find((HWND)wParam)) { // we don't get focus, so unset it now if (!widget->hasFocus()) // work around Windows bug after minimizing/restoring - widget = (QETWidget*)qApp->focusWidget(); + widget = (QETWidget*)QApplication::focusWidget(); HWND focus = ::GetFocus(); //if there is a current widget and the new widget belongs to the same toplevel window //or if the current widget was embedded into non-qt window (i.e. we won't get WM_ACTIVATEAPP) @@ -2450,16 +2450,16 @@ LRESULT CALLBACK QtWndProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam } break; case WM_THEMECHANGED: - if ((widget->windowType() == Qt::Desktop) || !qApp || qApp->closingDown() - || qApp->type() == QApplication::Tty) + if ((widget->windowType() == Qt::Desktop) || !qApp || QApplication::closingDown() + || QApplication::type() == QApplication::Tty) break; if (widget->testAttribute(Qt::WA_WState_Polished)) - qApp->style()->unpolish(widget); + QApplication::style()->unpolish(widget); if (widget->testAttribute(Qt::WA_WState_Polished)) - qApp->style()->polish(widget); - widget->repolishStyle(*qApp->style()); + QApplication::style()->polish(widget); + widget->repolishStyle(*QApplication::style()); if (widget->isVisible()) widget->update(); break; @@ -3047,7 +3047,7 @@ bool QETWidget::translateMouseEvent(const MSG &msg) HWND id = effectiveWinId(); QWidget *mouseGrabber = QWidget::mouseGrabber(); - QWidget *activePopupWidget = qApp->activePopupWidget(); + QWidget *activePopupWidget = QApplication::activePopupWidget(); if (mouseGrabber) { if (!activePopupWidget || (activePopupWidget == this && !rect().contains(widgetPos))) id = mouseGrabber->effectiveWinId(); @@ -3140,7 +3140,7 @@ bool QETWidget::translateMouseEvent(const MSG &msg) return false; replayPopupMouseEvent = false; - QWidget* activePopupWidget = qApp->activePopupWidget(); + QWidget* activePopupWidget = QApplication::activePopupWidget(); QWidget *target = activePopupWidget; const QPoint globalPos(gpos.x, gpos.y); @@ -3198,7 +3198,7 @@ bool QETWidget::translateMouseEvent(const MSG &msg) } if (type == QEvent::MouseButtonPress - && qApp->activePopupWidget() != activePopupWidget + && QApplication::activePopupWidget() != activePopupWidget && replayPopupMouseEvent) { // the popup dissappeared. Replay the event QWidget* w = QApplication::widgetAt(gpos.x, gpos.y); @@ -3215,7 +3215,7 @@ bool QETWidget::translateMouseEvent(const MSG &msg) winPostMessage(hwndTarget, msg.message, msg.wParam, lParam); } } else if (type == QEvent::MouseButtonRelease && button == Qt::RightButton - && qApp->activePopupWidget() == activePopupWidget) { + && QApplication::activePopupWidget() == activePopupWidget) { // popup still alive and received right-button-release #if !defined(QT_NO_CONTEXTMENU) QContextMenuEvent e2(QContextMenuEvent::Mouse, pos, globalPos, @@ -3325,7 +3325,7 @@ bool QETWidget::translateWheelEvent(const MSG &msg) // send the event to the widget or its ancestors { - QWidget* popup = qApp->activePopupWidget(); + QWidget* popup = QApplication::activePopupWidget(); if (popup && w->window() != popup) popup->close(); #ifndef QT_NO_WHEELEVENT @@ -3341,8 +3341,8 @@ bool QETWidget::translateWheelEvent(const MSG &msg) } // send the event to the widget that has the focus or its ancestors, if different - if (w != qApp->focusWidget() && (w = qApp->focusWidget())) { - QWidget* popup = qApp->activePopupWidget(); + if (w != QApplication::focusWidget() && (w = QApplication::focusWidget())) { + QWidget* popup = QApplication::activePopupWidget(); if (popup && w->window() != popup) popup->close(); #ifndef QT_NO_WHEELEVENT diff --git a/src/gui/kernel/qcursor.cpp b/src/gui/kernel/qcursor.cpp index 598f4ba..4ffa8fd 100644 --- a/src/gui/kernel/qcursor.cpp +++ b/src/gui/kernel/qcursor.cpp @@ -403,7 +403,7 @@ void QCursorData::initialize() QCursor::QCursor() { if (!QCursorData::initialized) { - if (qApp->startingUp()) { + if (QApplication::startingUp()) { d = 0; return; } diff --git a/src/gui/kernel/qdnd.cpp b/src/gui/kernel/qdnd.cpp index a5092a0..e83a2ae 100644 --- a/src/gui/kernel/qdnd.cpp +++ b/src/gui/kernel/qdnd.cpp @@ -368,7 +368,7 @@ QDragManager::~QDragManager() QDragManager *QDragManager::self() { - if (!instance && qApp && !qApp->closingDown()) + if (!instance && !QApplication::closingDown()) instance = new QDragManager; return instance; } diff --git a/src/gui/kernel/qdnd_win.cpp b/src/gui/kernel/qdnd_win.cpp index 8bf5c84..b8c65e8 100644 --- a/src/gui/kernel/qdnd_win.cpp +++ b/src/gui/kernel/qdnd_win.cpp @@ -549,7 +549,7 @@ QOleDropSource::QueryContinueDrag(BOOL fEscapePressed, DWORD grfKeyState) return ResultFromScode(DRAGDROP_S_DROP); } #endif - qApp->processEvents(); + QApplication::processEvents(); return NOERROR; } } diff --git a/src/gui/kernel/qshortcutmap.cpp b/src/gui/kernel/qshortcutmap.cpp index 3c2fcdd..735fe0f 100644 --- a/src/gui/kernel/qshortcutmap.cpp +++ b/src/gui/kernel/qshortcutmap.cpp @@ -628,13 +628,13 @@ QKeySequence::SequenceMatch QShortcutMap::matches(const QKeySequence &seq1, bool QShortcutMap::correctContext(const QShortcutEntry &item) const { Q_ASSERT_X(item.owner, "QShortcutMap", "Shortcut has no owner. Illegal map state!"); - QWidget *active_window = qApp->activeWindow(); + QWidget *active_window = QApplication::activeWindow(); // popups do not become the active window, // so we fake it here to get the correct context // for the shortcut system. - if (qApp->activePopupWidget()) - active_window = qApp->activePopupWidget(); + if (QApplication::activePopupWidget()) + active_window = QApplication::activePopupWidget(); if (!active_window) return false; diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index 230b8f6..7b0bf1e 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -1052,7 +1052,7 @@ void QWidgetPrivate::adjustFlags(Qt::WindowFlags &flags, QWidget *w) void QWidgetPrivate::init(QWidget *parentWidget, Qt::WindowFlags f) { Q_Q(QWidget); - if (qApp->type() == QApplication::Tty) + if (QApplication::type() == QApplication::Tty) qFatal("QWidget: Cannot create a QWidget when no GUI is being used"); Q_ASSERT(uncreatedWidgets); @@ -1345,7 +1345,7 @@ QWidget::~QWidget() #ifdef QT3_SUPPORT if (QApplicationPrivate::main_widget == this) { // reset main widget QApplicationPrivate::main_widget = 0; - qApp->quit(); + QApplication::quit(); } #endif @@ -2034,8 +2034,8 @@ void QWidgetPrivate::deactivateWidgetCleanup() { Q_Q(QWidget); // If this was the active application window, reset it - if (qApp->activeWindow() == q) - qApp->setActiveWindow(0); + if (QApplication::activeWindow() == q) + QApplication::setActiveWindow(0); // If the is the active mouse press widget, reset it if (q == qt_button_down) qt_button_down = 0; @@ -2236,7 +2236,7 @@ QStyle *QWidget::style() const if (d->extra && d->extra->style) return d->extra->style; - return qApp->style(); + return QApplication::style(); } /*! @@ -5372,7 +5372,7 @@ QIcon QWidget::windowIcon() const return *d->extra->topextra->icon; w = w->parentWidget(); } - return qApp->windowIcon(); + return QApplication::windowIcon(); } void QWidgetPrivate::setWindowIcon_helper() @@ -5894,7 +5894,7 @@ QWidget *QWidget::previousInFocusChain() const bool QWidget::isActiveWindow() const { QWidget *tlw = window(); - if(tlw == qApp->activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup))) + if(tlw == QApplication::activeWindow() || (isVisible() && (tlw->windowType() == Qt::Popup))) return true; #ifndef QT_NO_GRAPHICSVIEW @@ -5915,7 +5915,7 @@ bool QWidget::isActiveWindow() const !tlw->isModal() && (!tlw->parentWidget() || tlw->parentWidget()->isActiveWindow())) return true; - QWidget *w = qApp->activeWindow(); + QWidget *w = QApplication::activeWindow(); while(w && tlw->windowType() == Qt::Tool && !w->isModal() && w->parentWidget()) { w = w->parentWidget()->window(); @@ -7085,7 +7085,7 @@ bool QWidgetPrivate::close_helper(CloseMode mode) #ifdef QT3_SUPPORT if (isMain) - qApp->quit(); + QApplication::quit(); #endif // Attempt to close the application only if this widget has the // WA_QuitOnClose flag set set and has a non-visible parent @@ -7784,7 +7784,7 @@ bool QWidget::event(QEvent *event) QList childList = d->children; for (int i = 0; i < childList.size(); ++i) { QObject *o = childList.at(i); - if (o != qApp->activeModalWidget()) { + if (o != QApplication::activeModalWidget()) { if (qobject_cast(o) && static_cast(o)->isWindow()) { // do not forward the event to child windows, // QApplication does this for us @@ -8007,9 +8007,9 @@ void QWidget::mousePressEvent(QMouseEvent *event) if ((windowType() == Qt::Popup)) { event->accept(); QWidget* w; - while ((w = qApp->activePopupWidget()) && w != this){ + while ((w = QApplication::activePopupWidget()) && w != this){ w->close(); - if (qApp->activePopupWidget() == w) // widget does not want to dissappear + if (QApplication::activePopupWidget() == w) // widget does not want to dissappear w->hide(); // hide at least } if (!rect().contains(event->pos())){ diff --git a/src/gui/kernel/qwidget_win.cpp b/src/gui/kernel/qwidget_win.cpp index ea79329..6ad2548 100644 --- a/src/gui/kernel/qwidget_win.cpp +++ b/src/gui/kernel/qwidget_win.cpp @@ -1036,7 +1036,7 @@ void QWidget::setWindowState(Qt::WindowStates newstate) if (isVisible()) style |= WS_VISIBLE; SetWindowLongA(internalWinId(), GWL_STYLE, style); - QRect r = qApp->desktop()->screenGeometry(this); + QRect r = QApplication::desktop()->screenGeometry(this); UINT swpf = SWP_FRAMECHANGED; if (newstate & Qt::WindowActive) swpf |= SWP_NOACTIVATE; @@ -1977,8 +1977,8 @@ public: // in QOnScreenRasterPaintEngine() : QRasterPaintEngine(new QImage(qt_primary_surface_bits, - qApp->desktop()->width(), - qApp->desktop()->height(), + QApplication::desktop()->width(), + QApplication::desktop()->height(), qt_primary_surface_stride, qt_primary_surface_format)) { diff --git a/src/gui/painting/qbackingstore.cpp b/src/gui/painting/qbackingstore.cpp index 0a3a8dd..25dab4c 100644 --- a/src/gui/painting/qbackingstore.cpp +++ b/src/gui/painting/qbackingstore.cpp @@ -758,7 +758,7 @@ void QWidgetBackingStore::paintWindowDecoration() engine->setSystemClip(decorationRegion.translated(tlwOffset)); QPainter painter(windowSurface->paintDevice()); - painter.setFont(qApp->font()); + painter.setFont(QApplication::font()); painter.translate(tlwOffset); const int numDirty = managerPrivate->dirtyRegions.size(); @@ -1347,7 +1347,7 @@ void QWidgetBackingStore::flush(QWidget *widget, QWindowSurface *surface) static inline bool discardInvalidateBufferRequest(QWidget *widget, QTLWExtra *tlwExtra) { Q_ASSERT(widget); - if (qApp && qApp->closingDown()) + if (QApplication::closingDown()) return true; if (!tlwExtra || tlwExtra->inTopLevelResize || !tlwExtra->backingStore) diff --git a/src/gui/styles/qcleanlooksstyle.cpp b/src/gui/styles/qcleanlooksstyle.cpp index 805cd05..aff0af3 100644 --- a/src/gui/styles/qcleanlooksstyle.cpp +++ b/src/gui/styles/qcleanlooksstyle.cpp @@ -4419,7 +4419,7 @@ QIcon QCleanlooksStyle::standardIconImplementation(StandardPixmap standardIcon, { #ifdef Q_WS_X11 Q_D(const QCleanlooksStyle); - if (!qApp->desktopSettingsAware()) + if (!QApplication::desktopSettingsAware()) return QWindowsStyle::standardIconImplementation(standardIcon, option, widget); QIcon icon; QPixmap pixmap; @@ -4588,7 +4588,7 @@ QPixmap QCleanlooksStyle::standardPixmap(StandardPixmap standardPixmap, const QS #ifdef Q_WS_X11 Q_D(const QCleanlooksStyle); QPixmap pixmap; - if (!qApp->desktopSettingsAware()) + if (!QApplication::desktopSettingsAware()) return QWindowsStyle::standardPixmap(standardPixmap, opt, widget); d->lookupIconTheme(); #ifndef QT_NO_IMAGEFORMAT_XPM diff --git a/src/gui/styles/qcommonstyle.cpp b/src/gui/styles/qcommonstyle.cpp index 1285598..74eacf6 100644 --- a/src/gui/styles/qcommonstyle.cpp +++ b/src/gui/styles/qcommonstyle.cpp @@ -3130,7 +3130,7 @@ QRect QCommonStyle::subElementRect(SubElement sr, const QStyleOption *opt, if (dw->isFloating()) icon = dw->windowIcon(); if (!icon.isNull() - && icon.cacheKey() != qApp->windowIcon().cacheKey()) { + && icon.cacheKey() != QApplication::windowIcon().cacheKey()) { QSize sz = icon.actualSize(QSize(r.height(), r.height())); if (verticalTitleBar) sz.transpose(); @@ -5309,7 +5309,7 @@ QPixmap QCommonStyle::standardPixmap(StandardPixmap sp, const QStyleOption *opti #ifdef Q_WS_X11 Q_D(const QCommonStyle); QPixmap pixmap; - if (qApp->desktopSettingsAware()) { + if (QApplication::desktopSettingsAware()) { d->lookupIconTheme(); switch (sp) { case SP_DirHomeIcon: @@ -5730,7 +5730,7 @@ QIcon QCommonStyle::standardIconImplementation(StandardPixmap standardIcon, cons QIcon icon; #ifdef Q_WS_X11 Q_D(const QCommonStyle); - if (qApp->desktopSettingsAware()) { + if (QApplication::desktopSettingsAware()) { d->lookupIconTheme(); QPixmap pixmap; switch (standardIcon) { diff --git a/src/gui/styles/qstylesheetstyle.cpp b/src/gui/styles/qstylesheetstyle.cpp index fe0e53c..1bbe70e 100644 --- a/src/gui/styles/qstylesheetstyle.cpp +++ b/src/gui/styles/qstylesheetstyle.cpp @@ -867,7 +867,7 @@ static QStyle::StandardPixmap subControlIcon(int pe) QRenderRule::QRenderRule(const QVector &declarations, const QWidget *widget) : features(0), hasFont(false), pal(0), b(0), bg(0), bd(0), ou(0), geo(0), p(0), img(0), clipset(0) { - QPalette palette = qApp->palette(); // ###: ideally widget's palette + QPalette palette = QApplication::palette(); // ###: ideally widget's palette ValueExtractor v(declarations, palette); features = v.extractStyleFeatures(); @@ -2584,7 +2584,7 @@ static void updateWidgets(const QList& widgets) continue; widget->style()->polish(widget); QEvent event(QEvent::StyleChange); - qApp->sendEvent(widget, &event); + QApplication::sendEvent(widget, &event); widget->update(); widget->updateGeometry(); } @@ -2630,9 +2630,9 @@ QStyle *QStyleSheetStyle::baseStyle() const { if (base) return base; - if (QStyleSheetStyle *me = qobject_cast(qApp->style())) + if (QStyleSheetStyle *me = qobject_cast(QApplication::style())) return me->base; - return qApp->style(); + return QApplication::style(); } void QStyleSheetStyle::widgetDestroyed(QObject *o) diff --git a/src/gui/styles/qwindowsvistastyle.cpp b/src/gui/styles/qwindowsvistastyle.cpp index 013ca1e..9ea9a03 100644 --- a/src/gui/styles/qwindowsvistastyle.cpp +++ b/src/gui/styles/qwindowsvistastyle.cpp @@ -1436,7 +1436,7 @@ void QWindowsVistaStyle::drawControl(ControlElement element, const QStyleOption if (isFloating) { titleRect.adjust(0, -fw, 0, 0); - if (widget != 0 && widget->windowIcon().cacheKey() != qApp->windowIcon().cacheKey()) + if (widget != 0 && widget->windowIcon().cacheKey() != QApplication::windowIcon().cacheKey()) titleRect.adjust(titleRect.height() + mw, 0, 0, 0); } else { titleRect.adjust(mw, 0, 0, 0); @@ -2435,7 +2435,7 @@ void QWindowsVistaStyle::unpolish(QWidget *widget) else if (QTreeView *tree = qobject_cast (widget)) { tree->viewport()->setAttribute(Qt::WA_Hover, false); } else if (qobject_cast(widget)) { - QFont font = qApp->font("QCommandLinkButton"); + QFont font = QApplication::font("QCommandLinkButton"); QFont widgetFont = widget->font(); widgetFont.setFamily(font.family()); //Only family set by polish widget->setFont(widgetFont); diff --git a/src/gui/styles/qwindowsxpstyle.cpp b/src/gui/styles/qwindowsxpstyle.cpp index 3dac9f5..b5dfdbd 100644 --- a/src/gui/styles/qwindowsxpstyle.cpp +++ b/src/gui/styles/qwindowsxpstyle.cpp @@ -261,7 +261,7 @@ void QWindowsXPStylePrivate::cleanup(bool force) use_xp = false; cleanupHandleMap(); if (limboWidget) { - if (qApp->closingDown()) + if (QApplication::closingDown()) delete limboWidget; else limboWidget->deleteLater(); @@ -2275,7 +2275,7 @@ void QWindowsXPStyle::drawControl(ControlElement element, const QStyleOption *op if (isFloating) { titleRect.adjust(0, -fw, 0, 0); - if (widget != 0 && widget->windowIcon().cacheKey() != qApp->windowIcon().cacheKey()) + if (widget != 0 && widget->windowIcon().cacheKey() != QApplication::windowIcon().cacheKey()) titleRect.adjust(titleRect.height() + mw, 0, 0, 0); } else { titleRect.adjust(mw, 0, 0, 0); @@ -2322,7 +2322,7 @@ void QWindowsXPStyle::drawControl(ControlElement element, const QStyleOption *op // Figure out maximal button space on title bar QIcon ico = widget->windowIcon(); - bool hasIcon = (ico.cacheKey() != qApp->windowIcon().cacheKey()); + bool hasIcon = (ico.cacheKey() != QApplication::windowIcon().cacheKey()); if (hasIcon) { QPixmap pxIco = ico.pixmap(titleHeight); if (!verticalTitleBar && QApplication::layoutDirection() == Qt::RightToLeft) diff --git a/src/gui/text/qfontdatabase.cpp b/src/gui/text/qfontdatabase.cpp index 9c3c4a4..e9f067a 100644 --- a/src/gui/text/qfontdatabase.cpp +++ b/src/gui/text/qfontdatabase.cpp @@ -87,34 +87,34 @@ static int getFontWeight(const QString &weightString) // Test in decreasing order of commonness if (s == QLatin1String("medium") || s == QLatin1String("normal") - || s.compare(qApp->translate("QFontDatabase", "Normal"), Qt::CaseInsensitive) == 0) + || s.compare(QApplication::translate("QFontDatabase", "Normal"), Qt::CaseInsensitive) == 0) return QFont::Normal; if (s == QLatin1String("bold") - || s.compare(qApp->translate("QFontDatabase", "Bold"), Qt::CaseInsensitive) == 0) + || s.compare(QApplication::translate("QFontDatabase", "Bold"), Qt::CaseInsensitive) == 0) return QFont::Bold; if (s == QLatin1String("demibold") || s == QLatin1String("demi bold") - || s.compare(qApp->translate("QFontDatabase", "Demi Bold"), Qt::CaseInsensitive) == 0) + || s.compare(QApplication::translate("QFontDatabase", "Demi Bold"), Qt::CaseInsensitive) == 0) return QFont::DemiBold; if (s == QLatin1String("black") - || s.compare(qApp->translate("QFontDatabase", "Black"), Qt::CaseInsensitive) == 0) + || s.compare(QApplication::translate("QFontDatabase", "Black"), Qt::CaseInsensitive) == 0) return QFont::Black; if (s == QLatin1String("light")) return QFont::Light; if (s.contains(QLatin1String("bold")) - || s.contains(qApp->translate("QFontDatabase", "Bold"), Qt::CaseInsensitive)) { + || s.contains(QApplication::translate("QFontDatabase", "Bold"), Qt::CaseInsensitive)) { if (s.contains(QLatin1String("demi")) - || s.compare(qApp->translate("QFontDatabase", "Demi"), Qt::CaseInsensitive) == 0) + || s.compare(QApplication::translate("QFontDatabase", "Demi"), Qt::CaseInsensitive) == 0) return (int) QFont::DemiBold; return (int) QFont::Bold; } if (s.contains(QLatin1String("light")) - || s.compare(qApp->translate("QFontDatabase", "Light"), Qt::CaseInsensitive) == 0) + || s.compare(QApplication::translate("QFontDatabase", "Light"), Qt::CaseInsensitive) == 0) return (int) QFont::Light; if (s.contains(QLatin1String("black")) - || s.compare(qApp->translate("QFontDatabase", "Black"), Qt::CaseInsensitive) == 0) + || s.compare(QApplication::translate("QFontDatabase", "Black"), Qt::CaseInsensitive) == 0) return (int) QFont::Black; return (int) QFont::Normal; @@ -251,10 +251,10 @@ QtFontStyle::Key::Key(const QString &styleString) weight = getFontWeight(styleString); if (styleString.contains(QLatin1String("Italic")) - || styleString.contains(qApp->translate("QFontDatabase", "Italic"))) + || styleString.contains(QApplication::translate("QFontDatabase", "Italic"))) style = QFont::StyleItalic; else if (styleString.contains(QLatin1String("Oblique")) - || styleString.contains(qApp->translate("QFontDatabase", "Oblique"))) + || styleString.contains(QApplication::translate("QFontDatabase", "Oblique"))) style = QFont::StyleOblique; } @@ -1249,21 +1249,21 @@ static QString styleStringHelper(int weight, QFont::Style style) { QString result; if (weight >= QFont::Black) - result = qApp->translate("QFontDatabase", "Black"); + result = QApplication::translate("QFontDatabase", "Black"); else if (weight >= QFont::Bold) - result = qApp->translate("QFontDatabase", "Bold"); + result = QApplication::translate("QFontDatabase", "Bold"); else if (weight >= QFont::DemiBold) - result = qApp->translate("QFontDatabase", "Demi Bold"); + result = QApplication::translate("QFontDatabase", "Demi Bold"); else if (weight < QFont::Normal) - result = qApp->translate("QFontDatabase", "Light"); + result = QApplication::translate("QFontDatabase", "Light"); if (style == QFont::StyleItalic) - result += QLatin1Char(' ') + qApp->translate("QFontDatabase", "Italic"); + result += QLatin1Char(' ') + QApplication::translate("QFontDatabase", "Italic"); else if (style == QFont::StyleOblique) - result += QLatin1Char(' ') + qApp->translate("QFontDatabase", "Oblique"); + result += QLatin1Char(' ') + QApplication::translate("QFontDatabase", "Oblique"); if (result.isEmpty()) - result = qApp->translate("QFontDatabase", "Normal"); + result = QApplication::translate("QFontDatabase", "Normal"); return result.simplified(); } @@ -2067,7 +2067,7 @@ QString QFontDatabase::writingSystemName(WritingSystem writingSystem) Q_ASSERT_X(false, "QFontDatabase::writingSystemName", "invalid 'writingSystem' parameter"); break; } - return qApp ? qApp->translate("QFontDatabase", name) : QString::fromLatin1(name); + return QApplication::translate("QFontDatabase", name); } diff --git a/src/gui/text/qtextcontrol.cpp b/src/gui/text/qtextcontrol.cpp index 780891b..8573fc9 100644 --- a/src/gui/text/qtextcontrol.cpp +++ b/src/gui/text/qtextcontrol.cpp @@ -1712,7 +1712,7 @@ void QTextControlPrivate::mouseDoubleClickEvent(QEvent *e, Qt::MouseButton butto selectedWordOnDoubleClick = cursor; trippleClickPoint = pos; - trippleClickTimer.start(qApp->doubleClickInterval(), q); + trippleClickTimer.start(QApplication::doubleClickInterval(), q); if (doEmit) { selectionChanged(); #ifndef QT_NO_CLIPBOARD diff --git a/src/gui/util/qsystemtrayicon_win.cpp b/src/gui/util/qsystemtrayicon_win.cpp index c46c929..f79f135 100644 --- a/src/gui/util/qsystemtrayicon_win.cpp +++ b/src/gui/util/qsystemtrayicon_win.cpp @@ -518,7 +518,7 @@ void QSystemTrayIconPrivate::install_sys() QRect QSystemTrayIconSys::findTrayGeometry() { //Use lower right corner as fallback - QPoint brCorner = qApp->desktop()->screenGeometry().bottomRight(); + QPoint brCorner = QApplication::desktop()->screenGeometry().bottomRight(); QRect ret(brCorner.x() - 10, brCorner.y() - 10, 10, 10); #if defined(Q_OS_WINCE) HWND trayHandle = FindWindowW(L"Shell_TrayWnd", NULL); diff --git a/src/gui/widgets/qabstractbutton.cpp b/src/gui/widgets/qabstractbutton.cpp index f28288e..6337b5c 100644 --- a/src/gui/widgets/qabstractbutton.cpp +++ b/src/gui/widgets/qabstractbutton.cpp @@ -379,7 +379,7 @@ void QAbstractButtonPrivate::moveFocus(int key) #else bool exclusive = autoExclusive; #endif - QWidget *f = qApp->focusWidget(); + QWidget *f = QApplication::focusWidget(); QAbstractButton *fb = qobject_cast(f); if (!fb || !buttonList.contains(fb)) return; diff --git a/src/gui/widgets/qeffects.cpp b/src/gui/widgets/qeffects.cpp index 140953d..19cdf89 100644 --- a/src/gui/widgets/qeffects.cpp +++ b/src/gui/widgets/qeffects.cpp @@ -588,8 +588,8 @@ void qScrollEffect(QWidget* w, QEffects::DirFlags orient, int time) if (!w) return; - qApp->sendPostedEvents(w, QEvent::Move); - qApp->sendPostedEvents(w, QEvent::Resize); + QApplication::sendPostedEvents(w, QEvent::Move); + QApplication::sendPostedEvents(w, QEvent::Resize); Qt::WindowFlags flags = Qt::ToolTip; // those can be popups - they would steal the focus, but are disabled @@ -610,8 +610,8 @@ void qFadeEffect(QWidget* w, int time) if (!w) return; - qApp->sendPostedEvents(w, QEvent::Move); - qApp->sendPostedEvents(w, QEvent::Resize); + QApplication::sendPostedEvents(w, QEvent::Move); + QApplication::sendPostedEvents(w, QEvent::Resize); Qt::WindowFlags flags = Qt::ToolTip; diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp index 711f1f4..7baea94 100644 --- a/src/gui/widgets/qmenu.cpp +++ b/src/gui/widgets/qmenu.cpp @@ -1048,7 +1048,7 @@ void QMenuPrivate::activateAction(QAction *action, QAction::ActionEvent action_e if (q->testAttribute(Qt::WA_DontShowOnScreen)) { hideUpToMenuBar(); } else { - for(QWidget *widget = qApp->activePopupWidget(); widget; ) { + for(QWidget *widget = QApplication::activePopupWidget(); widget; ) { if (QMenu *qmenu = qobject_cast(widget)) { if(qmenu == q) hideUpToMenuBar(); @@ -1843,7 +1843,7 @@ void QMenu::popup(const QPoint &p, QAction *atAction) if (adjustToDesktop) { //handle popup falling "off screen" - if (qApp->layoutDirection() == Qt::RightToLeft) { + if (QApplication::layoutDirection() == Qt::RightToLeft) { if(snapToMouse) //position flowing left from the mouse pos.setX(mouse.x()-size.width()); @@ -1881,9 +1881,9 @@ void QMenu::popup(const QPoint &p, QAction *atAction) } setGeometry(QRect(pos, size)); #ifndef QT_NO_EFFECTS - int hGuess = qApp->layoutDirection() == Qt::RightToLeft ? QEffects::LeftScroll : QEffects::RightScroll; + int hGuess = QApplication::layoutDirection() == Qt::RightToLeft ? QEffects::LeftScroll : QEffects::RightScroll; int vGuess = QEffects::DownScroll; - if (qApp->layoutDirection() == Qt::RightToLeft) { + if (QApplication::layoutDirection() == Qt::RightToLeft) { if ((snapToMouse && (pos.x() + size.width()/2 > mouse.x())) || (qobject_cast(d->causedPopup.widget) && pos.x() + size.width()/2 > d->causedPopup.widget->x())) hGuess = QEffects::RightScroll; @@ -2575,7 +2575,7 @@ void QMenu::keyPressEvent(QKeyEvent *e) { d->hideMenu(this); #ifndef QT_NO_MENUBAR - if (QMenuBar *mb = qobject_cast(qApp->focusWidget())) { + if (QMenuBar *mb = qobject_cast(QApplication::focusWidget())) { mb->d_func()->setKeyboardMode(false); } #endif @@ -2719,7 +2719,7 @@ void QMenu::keyPressEvent(QKeyEvent *e) #ifdef Q_OS_WIN32 if (key_consumed && (e->key() == Qt::Key_Control || e->key() == Qt::Key_Shift || e->key() == Qt::Key_Meta)) - qApp->beep(); + QApplication::beep(); #endif // Q_OS_WIN32 } if (key_consumed) diff --git a/src/gui/widgets/qmenubar.cpp b/src/gui/widgets/qmenubar.cpp index fc7e901..51e38e6 100644 --- a/src/gui/widgets/qmenubar.cpp +++ b/src/gui/widgets/qmenubar.cpp @@ -284,7 +284,7 @@ void QMenuBarPrivate::setKeyboardMode(bool b) } keyboardState = b; if(b) { - QWidget *fw = qApp->focusWidget(); + QWidget *fw = QApplication::focusWidget(); if (fw != q) keyboardFocusWidget = fw; if(!currentAction && !actionList.isEmpty()) @@ -294,7 +294,7 @@ void QMenuBarPrivate::setKeyboardMode(bool b) if(!popupState) setCurrentAction(0); if(keyboardFocusWidget) { - if (qApp->focusWidget() == q) + if (QApplication::focusWidget() == q) keyboardFocusWidget->setFocus(Qt::MenuBarFocusReason); keyboardFocusWidget = 0; } diff --git a/src/gui/widgets/qpushbutton.cpp b/src/gui/widgets/qpushbutton.cpp index 5001001..b526f02 100644 --- a/src/gui/widgets/qpushbutton.cpp +++ b/src/gui/widgets/qpushbutton.cpp @@ -589,7 +589,7 @@ void QPushButtonPrivate::_q_popupPressed() int x = globalPos.x(); int y = globalPos.y(); if (horizontal) { - if (globalPos.y() + rect.height() + menuSize.height() <= qApp->desktop()->height()) { + if (globalPos.y() + rect.height() + menuSize.height() <= QApplication::desktop()->height()) { y += rect.height(); } else { y -= menuSize.height(); @@ -597,7 +597,7 @@ void QPushButtonPrivate::_q_popupPressed() if (q->layoutDirection() == Qt::RightToLeft) x += rect.width() - menuSize.width(); } else { - if (globalPos.x() + rect.width() + menu->sizeHint().width() <= qApp->desktop()->width()) + if (globalPos.x() + rect.width() + menu->sizeHint().width() <= QApplication::desktop()->width()) x += rect.width(); else x -= menuSize.width(); diff --git a/src/gui/widgets/qtabwidget.cpp b/src/gui/widgets/qtabwidget.cpp index 43b2f54..c97154c 100644 --- a/src/gui/widgets/qtabwidget.cpp +++ b/src/gui/widgets/qtabwidget.cpp @@ -1057,7 +1057,7 @@ void QTabWidget::keyPressEvent(QKeyEvent *e) break; } } - if (!qApp->focusWidget()) + if (!QApplication::focusWidget()) d->tabs->setFocus(); } else { e->ignore(); diff --git a/src/gui/widgets/qtextbrowser.cpp b/src/gui/widgets/qtextbrowser.cpp index a1f4d34..d849184 100644 --- a/src/gui/widgets/qtextbrowser.cpp +++ b/src/gui/widgets/qtextbrowser.cpp @@ -263,7 +263,7 @@ void QTextBrowserPrivate::setSource(const QUrl &url) Q_Q(QTextBrowser); #ifndef QT_NO_CURSOR if (q->isVisible()) - qApp->setOverrideCursor(Qt::WaitCursor); + QApplication::setOverrideCursor(Qt::WaitCursor); #endif textOrSourceChanged = true; @@ -295,9 +295,9 @@ void QTextBrowserPrivate::setSource(const QUrl &url) if (q->isVisible()) { QString firstTag = txt.left(txt.indexOf(QLatin1Char('>')) + 1); - if (firstTag.left(3) == QLatin1String("restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); #endif #ifndef QT_NO_WHATSTHIS QWhatsThis::showText(QCursor::pos(), txt, q); @@ -342,7 +342,7 @@ void QTextBrowserPrivate::setSource(const QUrl &url) #ifndef QT_NO_CURSOR if (q->isVisible()) - qApp->restoreOverrideCursor(); + QApplication::restoreOverrideCursor(); #endif emit q->sourceChanged(url); } diff --git a/src/gui/widgets/qtoolbar.cpp b/src/gui/widgets/qtoolbar.cpp index 20f2c23..7787a66 100644 --- a/src/gui/widgets/qtoolbar.cpp +++ b/src/gui/widgets/qtoolbar.cpp @@ -1181,7 +1181,7 @@ bool QToolBar::event(QEvent *event) if (!d->layout->expanded) break; - QWidget *w = qApp->activePopupWidget(); + QWidget *w = QApplication::activePopupWidget(); if (waitForPopup(this, w)) { d->waitForPopupTimer->start(); break; @@ -1201,7 +1201,7 @@ void QToolBarPrivate::_q_waitForPopup() { Q_Q(QToolBar); - QWidget *w = qApp->activePopupWidget(); + QWidget *w = QApplication::activePopupWidget(); if (!waitForPopup(q, w)) { waitForPopupTimer->stop(); if (!q->underMouse()) diff --git a/src/gui/widgets/qtoolbutton.cpp b/src/gui/widgets/qtoolbutton.cpp index 7d41d1e..0eb6364 100644 --- a/src/gui/widgets/qtoolbutton.cpp +++ b/src/gui/widgets/qtoolbutton.cpp @@ -895,7 +895,7 @@ void QToolButtonPrivate::popupTimerDone() horizontal = false; #endif QPoint p; - QRect screen = qApp->desktop()->availableGeometry(q); + QRect screen = QApplication::desktop()->availableGeometry(q); QSize sh = ((QToolButton*)(QMenu*)actualMenu)->receivers(SIGNAL(aboutToShow()))? QSize() : actualMenu->sizeHint(); QRect rect = q->rect(); if (horizontal) { diff --git a/src/gui/widgets/qwidgetresizehandler.cpp b/src/gui/widgets/qwidgetresizehandler.cpp index 9171244..0e5b28a 100644 --- a/src/gui/widgets/qwidgetresizehandler.cpp +++ b/src/gui/widgets/qwidgetresizehandler.cpp @@ -258,7 +258,7 @@ void QWidgetResizeHandler::mouseMoveEvent(QMouseEvent *e) #ifdef Q_WS_X11 // Workaround for window managers which refuse to move a tool window partially offscreen. - QRect desktop = qApp->desktop()->availableGeometry(widget); + QRect desktop = QApplication::desktop()->availableGeometry(widget); pp.rx() = qMax(pp.x(), desktop.left()); pp.ry() = qMax(pp.y(), desktop.top()); p.rx() = qMin(p.x(), desktop.right()); -- cgit v0.12 From a208e75bcdeb4fe39e82d0f86cc2cd72980f40a4 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 11 Jun 2009 13:47:31 +0200 Subject: small change in a string, using startsWith --- src/gui/styles/qstylefactory.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/styles/qstylefactory.cpp b/src/gui/styles/qstylefactory.cpp index 70717db..376aa0f 100644 --- a/src/gui/styles/qstylefactory.cpp +++ b/src/gui/styles/qstylefactory.cpp @@ -170,7 +170,7 @@ QStyle *QStyleFactory::create(const QString& key) else #endif #ifndef QT_NO_STYLE_MAC - if (style.left(9) == QLatin1String("macintosh")) { + if (style.startsWith(QLatin1String("macintosh"))) { ret = new QMacStyle; # ifdef Q_WS_MAC if (style == QLatin1String("macintosh")) -- cgit v0.12 From e3d6bd3fc41b09c2eb7c56789d7dc5e26722a3b9 Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Thu, 11 Jun 2009 16:05:28 +0200 Subject: Fixed ToolBar layout so that when a toolbar is resized to its sizeHint we get a "sticky" effect --- src/gui/widgets/qtoolbararealayout.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/gui/widgets/qtoolbararealayout.cpp b/src/gui/widgets/qtoolbararealayout.cpp index 240d059..b1b743e 100644 --- a/src/gui/widgets/qtoolbararealayout.cpp +++ b/src/gui/widgets/qtoolbararealayout.cpp @@ -440,9 +440,10 @@ void QToolBarAreaLayoutInfo::moveToolBar(QToolBar *toolbar, int pos) //we check if the previous is near its size hint //in which case we try to stick to it - if (qAbs(pick(o, previous.sizeHint()) - (previous.size + extra)) < QApplication::startDragDistance()) { - //we stick to the default space - extra = 0; + const int diff = pick(o, previous.sizeHint()) - (previous.size + extra); + if (qAbs(diff) < QApplication::startDragDistance()) { + //we stick to the default place and size + extra += diff; } //update for the current item -- cgit v0.12 From aa2adb8d0072eccb549692d56168b8fde33f7b4f Mon Sep 17 00:00:00 2001 From: Benjamin Poulain Date: Thu, 11 Jun 2009 16:27:29 +0200 Subject: Sort QDir with qSort instead of qStableSort The commit 3e7fc907e5cc1937fb98bf4581cee960fe3d4e7a have changed the behavior of sorting of QDir. This revert to the old behavior with qSort instead of qStableSort. Reviewed-by: Alexis --- src/corelib/io/qdir.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp index 302d9b5..b6900bc 100644 --- a/src/corelib/io/qdir.cpp +++ b/src/corelib/io/qdir.cpp @@ -289,7 +289,7 @@ inline void QDirPrivate::sortFileList(QDir::SortFlags sort, QFileInfoList &l, QDirSortItem *si = new QDirSortItem[n]; for (int i = 0; i < n; ++i) si[i].item = l.at(i); - qStableSort(si, si + n, QDirSortItemComparator(sort)); + qSort(si, si+n, QDirSortItemComparator(sort)); // put them back in the list(s) if(infos) { for (int i = 0; i < n; ++i) @@ -1316,7 +1316,6 @@ QStringList QDir::entryList(Filters filters, SortFlags sort) const \sa entryList(), setNameFilters(), setSorting(), setFilter(), isReadable(), exists() */ - QFileInfoList QDir::entryInfoList(Filters filters, SortFlags sort) const { Q_D(const QDir); -- cgit v0.12 From fa5f3a4464f8265692c2ff50bd03b9b24b6ad912 Mon Sep 17 00:00:00 2001 From: Benjamin Poulain Date: Thu, 11 Jun 2009 17:27:23 +0200 Subject: Use the original order if two files are equivalent for the sort of QDir Set back the sort order of QDir::entryList() and entryInfoList(). This complement the change of aa2adb8d0072eccb549692d56168b8fde33f7b4f Reviewed-by: Olivier --- src/corelib/io/qdir.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/corelib/io/qdir.cpp b/src/corelib/io/qdir.cpp index b6900bc..8aadf34 100644 --- a/src/corelib/io/qdir.cpp +++ b/src/corelib/io/qdir.cpp @@ -263,7 +263,8 @@ bool QDirSortItemComparator::operator()(const QDirSortItem &n1, const QDirSortIt ? f1->filename_cache.localeAwareCompare(f2->filename_cache) : f1->filename_cache.compare(f2->filename_cache); } - + if (r == 0) // Enforce an order - the order the items appear in the array + r = (&n1) - (&n2); if (qt_cmp_si_sort_flags & QDir::Reversed) return r > 0; return r < 0; -- cgit v0.12 From 17f573ed026f0790cc305a407e69bb1e9a424e41 Mon Sep 17 00:00:00 2001 From: David Boddie Date: Thu, 11 Jun 2009 17:59:28 +0200 Subject: Doc: Added information about QDBUS_DEBUG to the D-Bus documentation. Task-number: 253715 Reviewed-by: Trust Me --- doc/src/introtodbus.qdoc | 19 ++++++++++++++++++- doc/src/snippets/code/doc_src_introtodbus.qdoc | 5 +++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/doc/src/introtodbus.qdoc b/doc/src/introtodbus.qdoc index 71c65d5..1edc6eb 100644 --- a/doc/src/introtodbus.qdoc +++ b/doc/src/introtodbus.qdoc @@ -198,7 +198,24 @@ \row \o Interface \o Plugin identifier \o Dot-separated \endtable - \section2 Further Reading + \section1 Debugging + + When developing applications that use D-Bus, it is sometimes useful to be able + to see information about the messages that are sent and received across the + bus by each application. + + This feature can be enabled on a per-application basis by setting the + \c QDBUS_DEBUG environment variable before running each application. + For example, we can enable debugging only for the car in the + \l{Remote Controlled Car Example} by running the controller and the + car in the following way: + + \snippet doc/src/snippets/code/doc_src_introtodbus.qdoc QDBUS_DEBUG + + Information about the messages will be written to the console the application + was launched from. + + \section1 Further Reading The following documents contain information about Qt's D-Bus integration features, and provide details about the mechanisms used to send and receive diff --git a/doc/src/snippets/code/doc_src_introtodbus.qdoc b/doc/src/snippets/code/doc_src_introtodbus.qdoc index bedfe7f..97b14e9 100644 --- a/doc/src/snippets/code/doc_src_introtodbus.qdoc +++ b/doc/src/snippets/code/doc_src_introtodbus.qdoc @@ -1,3 +1,8 @@ //! [0] org.freedesktop.DBus //! [0] + +//! [QDBUS_DEBUG] +examples/dbus/remotecontrolledcar/controller/controller & +QDBUS_DEBUG=1 examples/dbus/remotecontrolledcar/car/car & +//! [QDBUS_DEBUG] -- cgit v0.12 From a1786a441e9101500ae2c28a5226372ba0c7b4a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 11 Jun 2009 16:24:40 +0200 Subject: QGraphicsView: Replace update() with updateAll(). We have some nice cut-offs when there's a full update pending, but we don't know about it if we call update() directly on the viewport. Instead call QGraphicsViewPrivate::updateAll() which has the same effect, except that it also sets a flag telling us a full update is pending. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsview.cpp | 34 +++++++++++++--------------------- src/gui/graphicsview/qgraphicsview_p.h | 8 +++++++- 2 files changed, 20 insertions(+), 22 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index de7b9f4..4a32ee5 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -442,7 +442,7 @@ void QGraphicsViewPrivate::recalculateContentSize() // scroll instead. if (oldLeftIndent != leftIndent || oldTopIndent != topIndent) { dirtyScroll = true; - viewport->update(); + updateAll(); } else if (q->isRightToLeft() && !leftIndent) { // In reverse mode, the horizontal scroll always changes after the content // size has changed, as the scroll is calculated by summing the min and @@ -823,14 +823,6 @@ void QGraphicsViewPrivate::processPendingUpdates() dirtyRegion = QRegion(); } -void QGraphicsViewPrivate::updateAll() -{ - viewport->update(); - fullUpdatePending = true; - dirtyBoundingRect = QRect(); - dirtyRegion = QRegion(); -} - void QGraphicsViewPrivate::updateRegion(const QRegion &r) { if (r.isEmpty() || fullUpdatePending) @@ -1084,7 +1076,7 @@ void QGraphicsView::setRenderHints(QPainter::RenderHints hints) if (hints == d->renderHints) return; d->renderHints = hints; - viewport()->update(); + d->updateAll(); } /*! @@ -1102,7 +1094,7 @@ void QGraphicsView::setRenderHint(QPainter::RenderHint hint, bool enabled) else d->renderHints &= ~hint; if (oldHints != d->renderHints) - viewport()->update(); + d->updateAll(); } /*! @@ -1389,7 +1381,7 @@ void QGraphicsView::resetCachedContent() if (d->cacheMode & CacheBackground) { // Background caching is enabled. d->mustResizeBackgroundPixmap = true; - viewport()->update(); + d->updateAll(); } else if (d->mustResizeBackgroundPixmap) { // Background caching is disabled. // Cleanup, free some resources. @@ -1478,7 +1470,7 @@ void QGraphicsView::setScene(QGraphicsScene *scene) return; // Always update the viewport when the scene changes. - viewport()->update(); + d->updateAll(); // Remove the previously assigned scene. if (d->scene) { @@ -2434,7 +2426,7 @@ void QGraphicsView::setBackgroundBrush(const QBrush &brush) { Q_D(QGraphicsView); d->backgroundBrush = brush; - viewport()->update(); + d->updateAll(); if (d->cacheMode & CacheBackground) { // Invalidate the background pixmap @@ -2464,7 +2456,7 @@ void QGraphicsView::setForegroundBrush(const QBrush &brush) { Q_D(QGraphicsView); d->foregroundBrush = brush; - viewport()->update(); + d->updateAll(); } /*! @@ -3062,7 +3054,7 @@ void QGraphicsView::mouseMoveEvent(QMouseEvent *event) if (d->viewportUpdateMode != FullViewportUpdate) viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect)); else - viewport()->update(); + d->updateAll(); } // Stop rubber banding if the user has let go of all buttons (even @@ -3084,7 +3076,7 @@ void QGraphicsView::mouseMoveEvent(QMouseEvent *event) if (d->viewportUpdateMode != FullViewportUpdate) viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect)); else - viewport()->update(); + d->updateAll(); } // Set the new selection area QPainterPath selectionArea; @@ -3127,7 +3119,7 @@ void QGraphicsView::mouseReleaseEvent(QMouseEvent *event) if (d->viewportUpdateMode != FullViewportUpdate) viewport()->update(d->rubberBandRegion(viewport(), d->rubberBandRect)); else - viewport()->update(); + d->updateAll(); } d->rubberBanding = false; d->rubberBandRect = QRect(); @@ -3395,10 +3387,10 @@ void QGraphicsView::scrollContentsBy(int dx, int dy) #endif viewport()->scroll(dx, dy); } else { - viewport()->update(); + d->updateAll(); } } else { - viewport()->update(); + d->updateAll(); } } @@ -3611,7 +3603,7 @@ void QGraphicsView::setTransform(const QTransform &matrix, bool combine ) d->transforming = false; // Any matrix operation requires a full update. - viewport()->update(); + d->updateAll(); } /*! diff --git a/src/gui/graphicsview/qgraphicsview_p.h b/src/gui/graphicsview/qgraphicsview_p.h index 814e476..00f3035 100644 --- a/src/gui/graphicsview/qgraphicsview_p.h +++ b/src/gui/graphicsview/qgraphicsview_p.h @@ -163,7 +163,13 @@ public: QRegion dirtyRegion; QRect dirtyBoundingRect; void processPendingUpdates(); - void updateAll(); + inline void updateAll() + { + viewport->update(); + fullUpdatePending = true; + dirtyBoundingRect = QRect(); + dirtyRegion = QRegion(); + } void updateRect(const QRect &rect); void updateRegion(const QRegion ®ion); bool updateSceneSlotReimplementedChecked; -- cgit v0.12 From 5918d108579d53e9c41ee674379a8c60124e9838 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Thu, 11 Jun 2009 17:29:46 +0200 Subject: Painting artifacts in QGraphicsView. Problem appears in the chip demo when clicking an item while scrolling the view using the mouse wheel. The problem was that we didn't translate the the item's old painted view rect. There was also a problem when enabling the DontAdjustForAntialiasing flag, causing an item to not redraw its edges. We have to adjust the rectangle by (-1, -1, 1, 1) since QRect() and QRectF() behaves differently. Auto-test (made by Andreas) included. Reviewed-by: Andreas --- src/gui/graphicsview/qgraphicsscene.cpp | 8 +++- src/gui/graphicsview/qgraphicsview.cpp | 21 +++++---- src/gui/graphicsview/qgraphicsview_p.h | 1 + tests/auto/qgraphicsview/tst_qgraphicsview.cpp | 63 ++++++++++++++++++++++++++ 4 files changed, 83 insertions(+), 10 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 1c48675..55d8a1d 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5269,7 +5269,9 @@ void QGraphicsScenePrivate::markDirty(QGraphicsItem *item, const QRectF &rect, b for (int i = 0; i < views.size(); ++i) { QGraphicsViewPrivate *viewPrivate = views.at(i)->d_func(); - viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + QRect rect = item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport); + rect.translate(viewPrivate->dirtyScrollOffset); + viewPrivate->updateRect(rect); } return; } @@ -5350,7 +5352,9 @@ void QGraphicsScenePrivate::processDirtyItemsRecursive(QGraphicsItem *item, bool if (item->d_ptr->paintedViewBoundingRectsNeedRepaint) { wasDirtyParentViewBoundingRects = true; - viewPrivate->updateRect(item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport)); + QRect rect = item->d_ptr->paintedViewBoundingRects.value(viewPrivate->viewport); + rect.translate(viewPrivate->dirtyScrollOffset); + viewPrivate->updateRect(rect); } if (!item->d_ptr->dirty) diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index 4a32ee5..a72aa5a 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -812,7 +812,7 @@ void QGraphicsViewPrivate::processPendingUpdates() if (viewportUpdateMode == QGraphicsView::BoundingRectViewportUpdate) { if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) - viewport->update(dirtyBoundingRect); + viewport->update(dirtyBoundingRect.adjusted(-1, -1, 1, 1)); else viewport->update(dirtyBoundingRect.adjusted(-2, -2, 2, 2)); } else { @@ -843,14 +843,16 @@ void QGraphicsViewPrivate::updateRegion(const QRegion &r) break; case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE case QGraphicsView::MinimalViewportUpdate: - if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) { - dirtyRegion += r; - } else { - const QVector &rects = r.rects(); - for (int i = 0; i < rects.size(); ++i) + { + const QVector &rects = r.rects(); + for (int i = 0; i < rects.size(); ++i) { + if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) + dirtyRegion += rects.at(i).adjusted(-1, -1, 1, 1); + else dirtyRegion += rects.at(i).adjusted(-2, -2, 2, 2); } break; + } case QGraphicsView::NoViewportUpdate: // Unreachable break; @@ -878,7 +880,7 @@ void QGraphicsViewPrivate::updateRect(const QRect &r) case QGraphicsView::SmartViewportUpdate: // ### DEPRECATE case QGraphicsView::MinimalViewportUpdate: if (optimizationFlags & QGraphicsView::DontAdjustForAntialiasing) - dirtyRegion += r; + dirtyRegion += r.adjusted(-1, -1, 1, 1); else dirtyRegion += r.adjusted(-2, -2, 2, 2); break; @@ -2678,6 +2680,7 @@ bool QGraphicsView::viewportEvent(QEvent *event) case QEvent::Paint: // Reset full update d->fullUpdatePending = false; + d->dirtyScrollOffset = QPoint(); if (d->scene) { // Check if this view reimplements the updateScene slot; if it // does, we can't do direct update delivery and have to fall back @@ -3375,7 +3378,6 @@ void QGraphicsView::scrollContentsBy(int dx, int dy) if (d->viewportUpdateMode != QGraphicsView::NoViewportUpdate) { if (d->viewportUpdateMode != QGraphicsView::FullViewportUpdate) { - d->dirtyRegion.translate(dx, dy); if (d->accelerateScrolling) { #ifndef QT_NO_RUBBERBAND // Update new and old rubberband regions @@ -3385,6 +3387,9 @@ void QGraphicsView::scrollContentsBy(int dx, int dy) viewport()->update(rubberBandRegion); } #endif + d->dirtyScrollOffset.rx() += dx; + d->dirtyScrollOffset.ry() += dy; + d->dirtyRegion.translate(dx, dy); viewport()->scroll(dx, dy); } else { d->updateAll(); diff --git a/src/gui/graphicsview/qgraphicsview_p.h b/src/gui/graphicsview/qgraphicsview_p.h index 00f3035..a6f0d04 100644 --- a/src/gui/graphicsview/qgraphicsview_p.h +++ b/src/gui/graphicsview/qgraphicsview_p.h @@ -94,6 +94,7 @@ public: QPoint mousePressScreenPoint; QPointF lastMouseMoveScenePoint; QPoint lastMouseMoveScreenPoint; + QPoint dirtyScrollOffset; Qt::MouseButton mousePressButton; QTransform matrix; bool identityMatrix; diff --git a/tests/auto/qgraphicsview/tst_qgraphicsview.cpp b/tests/auto/qgraphicsview/tst_qgraphicsview.cpp index 5167682..06b4a78 100644 --- a/tests/auto/qgraphicsview/tst_qgraphicsview.cpp +++ b/tests/auto/qgraphicsview/tst_qgraphicsview.cpp @@ -188,6 +188,8 @@ private slots: void embeddedViews(); void scrollAfterResize_data(); void scrollAfterResize(); + void moveItemWhileScrolling_data(); + void moveItemWhileScrolling(); void centerOnDirtyItem(); void mouseTracking(); void mouseTracking2(); @@ -3045,6 +3047,67 @@ void tst_QGraphicsView::scrollAfterResize() QCOMPARE(view.viewportTransform(), x3); } +void tst_QGraphicsView::moveItemWhileScrolling_data() +{ + QTest::addColumn("adjustForAntialiasing"); + + QTest::newRow("no adjust") << false; + QTest::newRow("adjust") << true; +} + +void tst_QGraphicsView::moveItemWhileScrolling() +{ + QFETCH(bool, adjustForAntialiasing); + + class MoveItemScrollView : public QGraphicsView + { + public: + MoveItemScrollView() + { + setScene(new QGraphicsScene(0, 0, 1000, 1000)); + rect = scene()->addRect(0, 0, 10, 10); + rect->setPos(50, 50); + } + QRegion lastPaintedRegion; + QGraphicsItem *rect; + protected: + void paintEvent(QPaintEvent *event) + { + lastPaintedRegion = event->region(); + QGraphicsView::paintEvent(event); + } + }; + + MoveItemScrollView view; + view.setFrameStyle(0); + view.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + view.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + view.setResizeAnchor(QGraphicsView::NoAnchor); + view.setTransformationAnchor(QGraphicsView::NoAnchor); + if (!adjustForAntialiasing) + view.setOptimizationFlag(QGraphicsView::DontAdjustForAntialiasing); + view.show(); + view.resize(200, 200); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&view); +#endif + QTest::qWait(100); + + view.lastPaintedRegion = QRegion(); + view.horizontalScrollBar()->setValue(view.horizontalScrollBar()->value() + 10); + view.rect->moveBy(0, 10); + QTest::qWait(100); + + QRegion expectedRegion; + expectedRegion += QRect(0, 0, 200, 200); + expectedRegion -= QRect(0, 0, 190, 200); + int a = adjustForAntialiasing ? 2 : 1; + expectedRegion += QRect(40, 50, 10, 10).adjusted(-a, -a, a, a); + expectedRegion += QRect(40, 60, 10, 10).adjusted(-a, -a, a, a); + + QCOMPARE(view.lastPaintedRegion, expectedRegion); +} + void tst_QGraphicsView::centerOnDirtyItem() { QGraphicsView view; -- cgit v0.12 From 021ce0ba93168dcaf1744fc2da8faf4e2f4ba683 Mon Sep 17 00:00:00 2001 From: Olivier Goffart Date: Thu, 11 Jun 2009 18:22:54 +0200 Subject: Compile the qsettins autotest As suggested in merge request 641 --- src/corelib/io/qsettings_p.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/io/qsettings_p.h b/src/corelib/io/qsettings_p.h index 93d07e0..565aeb6 100644 --- a/src/corelib/io/qsettings_p.h +++ b/src/corelib/io/qsettings_p.h @@ -146,7 +146,7 @@ inline QString QSettingsGroup::toString() const return result; } -class QConfFile +class Q_AUTOTEST_EXPORT QConfFile { public: ParsedSettingsMap mergedKeyMap() const; -- cgit v0.12 From 3c4239a9ced4945e9b016a755180fac2f6b3a5ab Mon Sep 17 00:00:00 2001 From: David Boddie Date: Thu, 11 Jun 2009 18:46:57 +0200 Subject: Doc: Make it easier to find supported platform information from the installation page. Reviewed-by: Trust Me --- doc/src/installation.qdoc | 3 +++ 1 file changed, 3 insertions(+) diff --git a/doc/src/installation.qdoc b/doc/src/installation.qdoc index bc310c9..49ab45a 100644 --- a/doc/src/installation.qdoc +++ b/doc/src/installation.qdoc @@ -508,6 +508,9 @@ in the \l{Qt for Windows CE Requirements} document. This page describes the specific requirements of libraries and components on which Qt depends. For information about installing Qt, see the \l{Installation} page. + For information about the platforms that Qt supports, see the \l{Supported Platforms} + page. + \section1 OpenSSL (version 0.9.7 or later) Support for \l{SSL}{Secure Sockets Layer (SSL)} communication is provided by the -- cgit v0.12 From a2baabcfcb60a7a0e5d3926ad6938983e50dfefc Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Wed, 10 Jun 2009 22:13:57 +0200 Subject: Use the old codec if there is one available when reading data in qtextstream. Reviewed-by: trustme --- src/corelib/io/qtextstream.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/io/qtextstream.cpp b/src/corelib/io/qtextstream.cpp index 7c925f1..75c682a 100644 --- a/src/corelib/io/qtextstream.cpp +++ b/src/corelib/io/qtextstream.cpp @@ -561,7 +561,7 @@ bool QTextStreamPrivate::fillReadBuffer(qint64 maxBytes) if (!codec || autoDetectUnicode) { autoDetectUnicode = false; - codec = QTextCodec::codecForUtfText(QByteArray::fromRawData(buf, bytesRead), 0); + codec = QTextCodec::codecForUtfText(QByteArray::fromRawData(buf, bytesRead), codec); if (!codec) { codec = QTextCodec::codecForLocale(); writeConverterState.flags |= QTextCodec::IgnoreHeader; -- cgit v0.12 From 52392292c8fa096e3b0bb692dedce66924ab3305 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Wed, 10 Jun 2009 22:15:00 +0200 Subject: Skip the byte order mark when converting the utf16 and utf32 data MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When reading one character at a time (as QTextStream::pos does) the byte order mark could be ignored. This happens only with UTF-16 BE/LE and UTF-32 BE/LE codecs. This fixes the qtextstream autotest. Author: Olivier Goffart Author: João Abecasis --- src/corelib/codecs/qutfcodec.cpp | 4 ++-- tests/auto/qtextstream/tst_qtextstream.cpp | 14 +++++++++++++- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/src/corelib/codecs/qutfcodec.cpp b/src/corelib/codecs/qutfcodec.cpp index d9defe1..6611315 100644 --- a/src/corelib/codecs/qutfcodec.cpp +++ b/src/corelib/codecs/qutfcodec.cpp @@ -387,7 +387,7 @@ QString QUtf16Codec::convertToUnicode(const char *chars, int len, ConverterState result.truncate(qch - result.unicode()); if (state) { - if (endian != Detect) + if (headerdone) state->flags |= IgnoreHeader; state->state_data[Endian] = endian; if (half) { @@ -569,7 +569,7 @@ QString QUtf32Codec::convertToUnicode(const char *chars, int len, ConverterState result.truncate(qch - result.unicode()); if (state) { - if (endian != Detect) + if (headerdone) state->flags |= IgnoreHeader; state->state_data[Endian] = endian; state->remainingChars = num; diff --git a/tests/auto/qtextstream/tst_qtextstream.cpp b/tests/auto/qtextstream/tst_qtextstream.cpp index 358b4b6..cf495d5 100644 --- a/tests/auto/qtextstream/tst_qtextstream.cpp +++ b/tests/auto/qtextstream/tst_qtextstream.cpp @@ -552,8 +552,8 @@ void tst_QTextStream::generateLineData(bool for_QString) QTest::newRow("threelines/crlf/crlf/crlf") << QByteArray("ole\r\ndole\r\ndoffen\r\n") << (QStringList() << "ole" << "dole" << "doffen"); QTest::newRow("threelines/crlf/crlf/nothing") << QByteArray("ole\r\ndole\r\ndoffen") << (QStringList() << "ole" << "dole" << "doffen"); - // utf-16 if (!for_QString) { + // utf-16 // one line QTest::newRow("utf16-BE/nothing") << QByteArray("\xfe\xff" @@ -593,6 +593,18 @@ void tst_QTextStream::generateLineData(bool for_QString) "\xe5\x00\x67\x00\x65\x00\x0a\x00" "\xe5\x00\x67\x00\x65\x00\x0a\x00", 26) << (QStringList() << "\345ge" << "\345ge" << "\345ge"); + + // utf-32 + QTest::newRow("utf32-BE/twolines") + << QByteArray("\x00\x00\xfe\xff" + "\x00\x00\x00\xe5\x00\x00\x00\x67\x00\x00\x00\x65\x00\x00\x00\x0a" + "\x00\x00\x00\xe5\x00\x00\x00\x67\x00\x00\x00\x65\x00\x00\x00\x0a", 36) + << (QStringList() << "\345ge" << "\345ge"); + QTest::newRow("utf32-LE/twolines") + << QByteArray("\xff\xfe\x00\x00" + "\xe5\x00\x00\x00\x67\x00\x00\x00\x65\x00\x00\x00\x0a\x00\x00\x00" + "\xe5\x00\x00\x00\x67\x00\x00\x00\x65\x00\x00\x00\x0a\x00\x00\x00", 36) + << (QStringList() << "\345ge" << "\345ge"); } // partials -- cgit v0.12 From f6aa5d8cfbec4f4ffacf20a94a1653c1a8ee2134 Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Thu, 11 Jun 2009 14:59:23 +0200 Subject: UTF-8 text codec should be able to convert data when fed one by one byte. When the input data is fed to utf-8 by one byte it couldn't parse the BOM correctly. So we wait until the BOM is composed into a code point and check it afterwards. Reviewed-by: Olivier Goffart --- src/corelib/codecs/qutfcodec.cpp | 11 +++++- tests/auto/qtextcodec/tst_qtextcodec.cpp | 60 ++++++++++++++++++++++++++++++ tests/auto/qtextstream/tst_qtextstream.cpp | 7 ++++ 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/src/corelib/codecs/qutfcodec.cpp b/src/corelib/codecs/qutfcodec.cpp index 6611315..27c0572 100644 --- a/src/corelib/codecs/qutfcodec.cpp +++ b/src/corelib/codecs/qutfcodec.cpp @@ -184,7 +184,10 @@ void QUtf8Codec::convertToUnicode(QString *target, const char *chars, int len, C uc = (uc << 6) | (ch & 0x3f); need--; if (!need) { - if (uc > 0xffff && uc < 0x110000) { + // utf-8 bom composes into 0xfeff code point + if (!headerdone && uc == 0xfeff) { + // dont do anything, just skip the BOM + } else if (uc > 0xffff && uc < 0x110000) { // surrogate pair uc -= 0x10000; unsigned short high = uc/0x400 + 0xd800; @@ -206,6 +209,7 @@ void QUtf8Codec::convertToUnicode(QString *target, const char *chars, int len, C } else { *qch++ = uc; } + headerdone = true; } } else { // error @@ -213,15 +217,18 @@ void QUtf8Codec::convertToUnicode(QString *target, const char *chars, int len, C *qch++ = replacement; ++invalid; need = 0; + headerdone = true; } } else { if (ch < 128) { *qch++ = QLatin1Char(ch); + headerdone = true; } else if ((ch & 0xe0) == 0xc0) { uc = ch & 0x1f; need = 1; error = i; min_uc = 0x80; + headerdone = true; } else if ((ch & 0xf0) == 0xe0) { uc = ch & 0x0f; need = 2; @@ -232,10 +239,12 @@ void QUtf8Codec::convertToUnicode(QString *target, const char *chars, int len, C need = 3; error = i; min_uc = 0x10000; + headerdone = true; } else { // error *qch++ = replacement; ++invalid; + headerdone = true; } } } diff --git a/tests/auto/qtextcodec/tst_qtextcodec.cpp b/tests/auto/qtextcodec/tst_qtextcodec.cpp index 97c409b..88dbaf7 100644 --- a/tests/auto/qtextcodec/tst_qtextcodec.cpp +++ b/tests/auto/qtextcodec/tst_qtextcodec.cpp @@ -74,6 +74,9 @@ private slots: void utf8Codec_data(); void utf8Codec(); + void utf8bom_data(); + void utf8bom(); + void utfHeaders_data(); void utfHeaders(); @@ -1513,6 +1516,63 @@ void tst_QTextCodec::utf8Codec() QCOMPARE(str, res); } +void tst_QTextCodec::utf8bom_data() +{ + QTest::addColumn("data"); + QTest::addColumn("result"); + + QTest::newRow("nobom") + << QByteArray("\302\240", 2) + << QString("\240"); + + { + static const ushort data[] = { 0x201d }; + QTest::newRow("nobom 2") + << QByteArray("\342\200\235", 3) + << QString::fromUtf16(data, sizeof(data)/sizeof(short)); + } + + { + static const ushort data[] = { 0xf000 }; + QTest::newRow("bom1") + << QByteArray("\357\200\200", 3) + << QString::fromUtf16(data, sizeof(data)/sizeof(short)); + } + + { + static const ushort data[] = { 0xfec0 }; + QTest::newRow("bom2") + << QByteArray("\357\273\200", 3) + << QString::fromUtf16(data, sizeof(data)/sizeof(short)); + } + + { + QTest::newRow("normal-bom") + << QByteArray("\357\273\277a", 4) + << QString("a"); + } + + { + static const ushort data[] = { 0x61, 0xfeff, 0x62 }; + QTest::newRow("middle-bom") + << QByteArray("a\357\273\277b", 5) + << QString::fromUtf16(data, sizeof(data)/sizeof(short)); + } +} + +void tst_QTextCodec::utf8bom() +{ + QFETCH(QByteArray, data); + QFETCH(QString, result); + + QTextCodec *const codec = QTextCodec::codecForMib(106); // UTF-8 + Q_ASSERT(codec); + + QCOMPARE(codec->toUnicode(data.constData(), data.length(), 0), result); + + QTextCodec::ConverterState state; + QCOMPARE(codec->toUnicode(data.constData(), data.length(), &state), result); +} void tst_QTextCodec::utfHeaders_data() { diff --git a/tests/auto/qtextstream/tst_qtextstream.cpp b/tests/auto/qtextstream/tst_qtextstream.cpp index cf495d5..9573957 100644 --- a/tests/auto/qtextstream/tst_qtextstream.cpp +++ b/tests/auto/qtextstream/tst_qtextstream.cpp @@ -553,6 +553,13 @@ void tst_QTextStream::generateLineData(bool for_QString) QTest::newRow("threelines/crlf/crlf/nothing") << QByteArray("ole\r\ndole\r\ndoffen") << (QStringList() << "ole" << "dole" << "doffen"); if (!for_QString) { + // utf-8 + QTest::newRow("utf8/twolines") + << QByteArray("\xef\xbb\xbf" + "\x66\x67\x65\x0a" + "\x66\x67\x65\x0a", 11) + << (QStringList() << "fge" << "fge"); + // utf-16 // one line QTest::newRow("utf16-BE/nothing") -- cgit v0.12 From 66f34c40dbc52b76434db4ccac6c43101bd57e1e Mon Sep 17 00:00:00 2001 From: Denis Dzyubenko Date: Thu, 11 Jun 2009 21:00:49 +0200 Subject: Fixed qtextcodec autotest so it can be run from a build directory. Reviewed-by: trustme --- tests/auto/qtextcodec/test/test.pro | 6 +++--- tests/auto/qtextcodec/tst_qtextcodec.cpp | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/auto/qtextcodec/test/test.pro b/tests/auto/qtextcodec/test/test.pro index e52bb7a..9c07e76 100644 --- a/tests/auto/qtextcodec/test/test.pro +++ b/tests/auto/qtextcodec/test/test.pro @@ -6,7 +6,7 @@ wince*: { addFiles.path = . DEPLOYMENT += addFiles DEPLOYMENT_PLUGIN += qcncodecs qjpcodecs qkrcodecs qtwcodecs + DEFINES += SRCDIR=\\\"\\\" +} else { + DEFINES += SRCDIR=\\\"$$PWD/../\\\" } - - - diff --git a/tests/auto/qtextcodec/tst_qtextcodec.cpp b/tests/auto/qtextcodec/tst_qtextcodec.cpp index 88dbaf7..1802c3e 100644 --- a/tests/auto/qtextcodec/tst_qtextcodec.cpp +++ b/tests/auto/qtextcodec/tst_qtextcodec.cpp @@ -95,8 +95,8 @@ void tst_QTextCodec::toUnicode_data() QTest::addColumn("fileName"); QTest::addColumn("codecName"); - QTest::newRow( "korean-eucKR" ) << "korean.txt" << "eucKR"; - QTest::newRow( "UTF-8" ) << "utf8.txt" << "UTF-8"; + QTest::newRow( "korean-eucKR" ) << SRCDIR "korean.txt" << "eucKR"; + QTest::newRow( "UTF-8" ) << SRCDIR "utf8.txt" << "UTF-8"; } void tst_QTextCodec::toUnicode() @@ -237,7 +237,7 @@ void tst_QTextCodec::fromUnicode() void tst_QTextCodec::toUnicode_codecForHtml() { - QFile file(QString("QT4-crashtest.txt")); + QFile file(QString(SRCDIR "QT4-crashtest.txt")); QVERIFY(file.open(QFile::ReadOnly)); QByteArray data = file.readAll(); -- cgit v0.12 From 344279da7e1cfbc4a28fd46931301d08ed9ef7d8 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 12 Jun 2009 09:07:09 +1000 Subject: Revert "Getting kinetic compiling again on MacOS." This reverts commit f10791eb1c45b090f60a2c2ecca3cc5fd237278e. --- src/gui/painting/qpaintengineex.cpp | 83 +++++++++++++++++++++++++++++++++++-- src/gui/painting/qpaintengineex_p.h | 34 ++++++++------- src/gui/painting/qpainter.cpp | 71 ++++++++++++++----------------- src/gui/painting/qpainter.h | 1 + src/gui/painting/qpainter_p.h | 6 +-- 5 files changed, 134 insertions(+), 61 deletions(-) diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index 8eaad60..d2671c8 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -105,7 +105,7 @@ QDebug Q_GUI_EXPORT &operator<<(QDebug &s, const QVectorPath &path) vectorPathBounds.x2 - vectorPathBounds.x1, vectorPathBounds.y2 - vectorPathBounds.y1); s << "QVectorPath(size:" << path.elementCount() << " hints:" << hex << path.hints() - << rf << ")"; + << rf << ')'; return s; } #endif @@ -138,6 +138,75 @@ QPaintEngineExPrivate::~QPaintEngineExPrivate() } +void QPaintEngineExPrivate::replayClipOperations() +{ + Q_Q(QPaintEngineEx); + + QPainter *p = q->painter(); + if (!p || !p->d_ptr) + return; + + QPainterPrivate *pp = p->d_ptr; + QList clipInfo = pp->state->clipInfo; + + QTransform transform = q->state()->matrix; + + const QTransform &redirection = q->state()->redirectionMatrix; + + for (int i = 0; i < clipInfo.size(); ++i) { + const QPainterClipInfo &info = clipInfo.at(i); + + QTransform combined = info.matrix * redirection; + + if (combined != q->state()->matrix) { + q->state()->matrix = combined; + q->transformChanged(); + } + + switch (info.clipType) { + case QPainterClipInfo::RegionClip: + q->clip(info.region, info.operation); + break; + case QPainterClipInfo::PathClip: + q->clip(info.path, info.operation); + break; + case QPainterClipInfo::RectClip: + q->clip(info.rect, info.operation); + break; + case QPainterClipInfo::RectFClip: { + qreal right = info.rectf.x() + info.rectf.width(); + qreal bottom = info.rectf.y() + info.rectf.height(); + qreal pts[] = { info.rectf.x(), info.rectf.y(), + right, info.rectf.y(), + right, bottom, + info.rectf.x(), bottom }; + QVectorPath vp(pts, 4, 0, QVectorPath::RectangleHint); + q->clip(vp, info.operation); + break; + } + } + } + + if (transform != q->state()->matrix) { + q->state()->matrix = transform; + q->transformChanged(); + } +} + + +bool QPaintEngineExPrivate::hasClipOperations() const +{ + Q_Q(const QPaintEngineEx); + + QPainter *p = q->painter(); + if (!p || !p->d_ptr) + return false; + + QPainterPrivate *pp = p->d_ptr; + QList clipInfo = pp->state->clipInfo; + + return !clipInfo.isEmpty(); +} /******************************************************************************* * @@ -244,13 +313,18 @@ static void qpaintengineex_cubicTo(qreal c1x, qreal c1y, qreal c2x, qreal c2y, q ((StrokeHandler *) data)->types.add(QPainterPath::CurveToDataElement); } +QPaintEngineEx::QPaintEngineEx() + : QPaintEngine(*new QPaintEngineExPrivate, AllFeatures) +{ + extended = true; +} + QPaintEngineEx::QPaintEngineEx(QPaintEngineExPrivate &data) : QPaintEngine(data, AllFeatures) { extended = true; } - QPainterState *QPaintEngineEx::createState(QPainterState *orig) const { if (!orig) @@ -483,6 +557,9 @@ void QPaintEngineEx::clip(const QRect &r, Qt::ClipOperation op) void QPaintEngineEx::clip(const QRegion ®ion, Qt::ClipOperation op) { + if (region.numRects() == 1) + clip(region.boundingRect(), op); + QVector rects = region.rects(); if (rects.size() <= 32) { qreal pts[2*32*4]; @@ -778,7 +855,7 @@ void QPaintEngineEx::drawTiledPixmap(const QRectF &r, const QPixmap &pixmap, con { QBrush brush(state()->pen.color(), pixmap); QTransform xform; - xform.translate(-s.x(), -s.y()); + xform.translate(r.x() - s.x(), r.y() - s.y()); brush.setTransform(xform); qreal pts[] = { r.x(), r.y(), diff --git a/src/gui/painting/qpaintengineex_p.h b/src/gui/painting/qpaintengineex_p.h index 593726c..3f64260 100644 --- a/src/gui/painting/qpaintengineex_p.h +++ b/src/gui/painting/qpaintengineex_p.h @@ -139,27 +139,13 @@ public: QDebug Q_GUI_EXPORT &operator<<(QDebug &, const QVectorPath &path); #endif -class Q_GUI_EXPORT QPaintEngineExPrivate : public QPaintEnginePrivate -{ -public: - QPaintEngineExPrivate(); - ~QPaintEngineExPrivate(); - - QStroker stroker; - QDashStroker dasher; - StrokeHandler *strokeHandler; - QStrokerOps *activeStroker; - QPen strokerPen; -}; - class QPixmapFilter; class Q_GUI_EXPORT QPaintEngineEx : public QPaintEngine { Q_DECLARE_PRIVATE(QPaintEngineEx) public: - inline QPaintEngineEx() - : QPaintEngine(*new QPaintEngineExPrivate, AllFeatures) { extended = true; } + QPaintEngineEx(); virtual QPainterState *createState(QPainterState *orig) const; @@ -216,12 +202,30 @@ public: inline QPainterState *state() { return static_cast(QPaintEngine::state); } inline const QPainterState *state() const { return static_cast(QPaintEngine::state); } + virtual void sync() {} + virtual QPixmapFilter *createPixmapFilter(int /*type*/) const { return 0; } protected: QPaintEngineEx(QPaintEngineExPrivate &data); }; +class Q_GUI_EXPORT QPaintEngineExPrivate : public QPaintEnginePrivate +{ + Q_DECLARE_PUBLIC(QPaintEngineEx) +public: + QPaintEngineExPrivate(); + ~QPaintEngineExPrivate(); + + void replayClipOperations(); + bool hasClipOperations() const; + + QStroker stroker; + QDashStroker dasher; + StrokeHandler *strokeHandler; + QStrokerOps *activeStroker; + QPen strokerPen; +}; inline uint QVectorPath::polygonFlags(QPaintEngine::PolygonDrawMode mode) { switch (mode) { diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index cc48d24..0ece498 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -281,10 +281,14 @@ bool QPainterPrivate::attachPainterPrivate(QPainter *q, QPaintDevice *pdev) q->d_ptr->state->wh = q->d_ptr->state->vh = widget->height(); // Update matrix. - if (q->d_ptr->state->WxF) - q->d_ptr->state->worldMatrix.translate(-offset.x(), -offset.y()); - else - q->d_ptr->state->redirection_offset = offset; + if (q->d_ptr->state->WxF) { + q->d_ptr->state->redirectionMatrix *= q->d_ptr->state->worldMatrix; + q->d_ptr->state->redirectionMatrix.translate(-offset.x(), -offset.y()); + q->d_ptr->state->worldMatrix = QTransform(); + q->d_ptr->state->WxF = false; + } else { + q->d_ptr->state->redirectionMatrix = QTransform::fromTranslate(-offset.x(), -offset.y()); + } q->d_ptr->updateMatrix(); QPaintEnginePrivate *enginePrivate = q->d_ptr->engine->d_func(); @@ -410,7 +414,7 @@ void QPainterPrivate::draw_helper(const QPainterPath &originalPath, DrawOperatio bool old_txinv = txinv; QTransform old_invMatrix = invMatrix; txinv = true; - invMatrix = QTransform().translate(-state->redirection_offset.x(), -state->redirection_offset.y()); + invMatrix = state->redirectionMatrix; QPainterPath clipPath = q->clipPath(); QRectF r = clipPath.boundingRect().intersected(absPathRect); absPathRect = r.toAlignedRect(); @@ -634,20 +638,7 @@ void QPainterPrivate::updateMatrix() state->matrix *= viewTransform(); txinv = false; // no inverted matrix - if (!state->redirection_offset.isNull()) { - // We want to translate in dev space so we do the adding of the redirection - // offset manually. - if (state->matrix.isAffine()) { - state->matrix = QTransform(state->matrix.m11(), state->matrix.m12(), - state->matrix.m21(), state->matrix.m22(), - state->matrix.dx()-state->redirection_offset.x(), - state->matrix.dy()-state->redirection_offset.y()); - } else { - QTransform temp; - temp.translate(-state->redirection_offset.x(), -state->redirection_offset.y()); - state->matrix *= temp; - } - } + state->matrix *= state->redirectionMatrix; if (extended) extended->transformChanged(); else @@ -1572,10 +1563,8 @@ void QPainter::restore() // replay the list of clip states, for (int i=0; istate->clipInfo.size(); ++i) { const QPainterClipInfo &info = d->state->clipInfo.at(i); - tmp->matrix.setMatrix(info.matrix.m11(), info.matrix.m12(), info.matrix.m13(), - info.matrix.m21(), info.matrix.m22(), info.matrix.m23(), - info.matrix.dx() - d->state->redirection_offset.x(), - info.matrix.dy() - d->state->redirection_offset.y(), info.matrix.m33()); + tmp->matrix = info.matrix; + tmp->matrix *= d->state->redirectionMatrix; tmp->clipOperation = info.operation; if (info.clipType == QPainterClipInfo::RectClip) { tmp->dirtyFlags = QPaintEngine::DirtyClipRegion | QPaintEngine::DirtyTransform; @@ -1689,7 +1678,7 @@ bool QPainter::begin(QPaintDevice *pd) d->state->painter = this; d->states.push_back(d->state); - d->state->redirection_offset = redirectionOffset; + d->state->redirectionMatrix.translate(-redirectionOffset.x(), -redirectionOffset.y()); d->state->brushOrigin = QPointF(); if (!d->engine) { @@ -1723,7 +1712,8 @@ bool QPainter::begin(QPaintDevice *pd) // Adjust offset for alien widgets painting outside the paint event. if (!inPaintEvent && paintOutsidePaintEvent && !widget->internalWinId() && widget->testAttribute(Qt::WA_WState_Created)) { - d->state->redirection_offset -= widget->mapTo(widget->nativeParentWidget(), QPoint()); + const QPoint offset = widget->mapTo(widget->nativeParentWidget(), QPoint()); + d->state->redirectionMatrix.translate(offset.x(), offset.y()); } break; } @@ -1805,11 +1795,12 @@ bool QPainter::begin(QPaintDevice *pd) d->state->wh = d->state->vh = pd->metric(QPaintDevice::PdmHeight); } - d->state->redirection_offset += d->engine->coordinateOffset(); + const QPoint coordinateOffset = d->engine->coordinateOffset(); + d->state->redirectionMatrix.translate(-coordinateOffset.x(), -coordinateOffset.y()); Q_ASSERT(d->engine->isActive()); - if (!d->state->redirection_offset.isNull()) + if (!d->state->redirectionMatrix.isIdentity()) d->updateMatrix(); Q_ASSERT(d->engine->isActive()); @@ -6082,22 +6073,22 @@ void QPainter::drawTextItem(const QPointF &p, const QTextItem &_ti) const QTransform &m = d->state->matrix; if (d->state->matrix.type() < QTransform::TxShear) { bool isPlain90DegreeRotation = - (qFuzzyCompare(m.m11() + 1, qreal(1)) - && qFuzzyCompare(m.m12(), qreal(1)) - && qFuzzyCompare(m.m21(), qreal(-1)) - && qFuzzyCompare(m.m22() + 1, qreal(1)) + (qFuzzyIsNull(m.m11()) + && qFuzzyIsNull(m.m12() - qreal(1)) + && qFuzzyIsNull(m.m21() + qreal(1)) + && qFuzzyIsNull(m.m22()) ) || - (qFuzzyCompare(m.m11(), qreal(-1)) - && qFuzzyCompare(m.m12() + 1, qreal(1)) - && qFuzzyCompare(m.m21() + 1, qreal(1)) - && qFuzzyCompare(m.m22(), qreal(-1)) + (qFuzzyIsNull(m.m11() + qreal(1)) + && qFuzzyIsNull(m.m12()) + && qFuzzyIsNull(m.m21()) + && qFuzzyIsNull(m.m22() + qreal(1)) ) || - (qFuzzyCompare(m.m11() + 1, qreal(1)) - && qFuzzyCompare(m.m12(), qreal(-1)) - && qFuzzyCompare(m.m21(), qreal(1)) - && qFuzzyCompare(m.m22() + 1, qreal(1)) + (qFuzzyIsNull(m.m11()) + && qFuzzyIsNull(m.m12() + qreal(1)) + && qFuzzyIsNull(m.m21() - qreal(1)) + && qFuzzyIsNull(m.m22()) ) ; aa = !isPlain90DegreeRotation; @@ -7704,7 +7695,7 @@ QPainterState::QPainterState(const QPainterState *s) clipRegion(s->clipRegion), clipPath(s->clipPath), clipOperation(s->clipOperation), renderHints(s->renderHints), clipInfo(s->clipInfo), - worldMatrix(s->worldMatrix), matrix(s->matrix), redirection_offset(s->redirection_offset), + worldMatrix(s->worldMatrix), matrix(s->matrix), redirectionMatrix(s->redirectionMatrix), wx(s->wx), wy(s->wy), ww(s->ww), wh(s->wh), vx(s->vx), vy(s->vy), vw(s->vw), vh(s->vh), opacity(s->opacity), WxF(s->WxF), VxF(s->VxF), diff --git a/src/gui/painting/qpainter.h b/src/gui/painting/qpainter.h index f3df7a3..78cd713 100644 --- a/src/gui/painting/qpainter.h +++ b/src/gui/painting/qpainter.h @@ -507,6 +507,7 @@ private: friend class QFontEngineXLFD; friend class QWSManager; friend class QPaintEngine; + friend class QPaintEngineExPrivate; friend class QOpenGLPaintEngine; friend class QX11PaintEngine; friend class QX11PaintEnginePrivate; diff --git a/src/gui/painting/qpainter_p.h b/src/gui/painting/qpainter_p.h index 258b25a..8d4e6c5 100644 --- a/src/gui/painting/qpainter_p.h +++ b/src/gui/painting/qpainter_p.h @@ -92,8 +92,8 @@ inline Qt::PenJoinStyle qpen_joinStyle(const QPen &p) { return data_ptr(p)->join // QBrush inline functions... inline QBrush::DataPtr &data_ptr(const QBrush &p) { return const_cast(p).data_ptr(); } inline bool qbrush_fast_equals(const QBrush &a, const QBrush &b) { return data_ptr(a) == data_ptr(b); } -inline Qt::BrushStyle qbrush_style(const QBrush &b) { return data_ptr(b)->style; }; -inline const QColor &qbrush_color(const QBrush &b) { return data_ptr(b)->color; }; +inline Qt::BrushStyle qbrush_style(const QBrush &b) { return data_ptr(b)->style; } +inline const QColor &qbrush_color(const QBrush &b) { return data_ptr(b)->color; } inline bool qbrush_has_transform(const QBrush &b) { return data_ptr(b)->transform.type() > QTransform::TxNone; } class QPainterClipInfo @@ -158,7 +158,7 @@ public: QList clipInfo; // ### Make me smaller and faster to copy around... QTransform worldMatrix; // World transformation matrix, not window and viewport QTransform matrix; // Complete transformation matrix, - QPoint redirection_offset; + QTransform redirectionMatrix; int wx, wy, ww, wh; // window rectangle int vx, vy, vw, vh; // viewport rectangle qreal opacity; -- cgit v0.12 From 74c18979b927ba3dd82ed3f5ca362428c61c2675 Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Fri, 12 Jun 2009 09:46:39 +1000 Subject: More explicit QUrl <-> QString conversion. --- src/declarative/extra/qmlsqlconnection.cpp | 2 +- src/declarative/fx/qfxanimatedimageitem.cpp | 2 +- src/declarative/fx/qfxanimatedimageitem.h | 2 +- src/declarative/fx/qfxhighlightfilter.cpp | 7 +++---- src/declarative/fx/qfxitem.cpp | 6 +++--- src/declarative/fx/qfxwebview.cpp | 2 +- src/declarative/qml/qmlbindablevalue.cpp | 2 +- src/declarative/qml/qmlcompiler.cpp | 2 +- src/declarative/qml/qmlcompositetypemanager.cpp | 4 ++-- src/declarative/qml/qmlengine.cpp | 2 +- src/declarative/util/qmlscript.cpp | 10 +++++----- 11 files changed, 20 insertions(+), 21 deletions(-) diff --git a/src/declarative/extra/qmlsqlconnection.cpp b/src/declarative/extra/qmlsqlconnection.cpp index b65fe35..a329f3c 100644 --- a/src/declarative/extra/qmlsqlconnection.cpp +++ b/src/declarative/extra/qmlsqlconnection.cpp @@ -415,7 +415,7 @@ QSqlDatabase QmlSqlConnection::database() const qmlContext(this)) { // SQLITE uses files for databases, hence use relative pathing // if possible. - QUrl url = qmlContext(this)->resolvedUrl(d->databaseName); + QUrl url = qmlContext(this)->resolvedUrl(QUrl(d->databaseName)); if (url.isRelative() || url.scheme() == QLatin1String("file")) db.setDatabaseName(url.toLocalFile()); else diff --git a/src/declarative/fx/qfxanimatedimageitem.cpp b/src/declarative/fx/qfxanimatedimageitem.cpp index 604481c..d22959a 100644 --- a/src/declarative/fx/qfxanimatedimageitem.cpp +++ b/src/declarative/fx/qfxanimatedimageitem.cpp @@ -152,7 +152,7 @@ int QFxAnimatedImageItem::frameCount() const return d->_movie->frameCount(); } -void QFxAnimatedImageItem::setSource(const QString &url) +void QFxAnimatedImageItem::setSource(const QUrl &url) { Q_D(QFxAnimatedImageItem); if (url == d->url) diff --git a/src/declarative/fx/qfxanimatedimageitem.h b/src/declarative/fx/qfxanimatedimageitem.h index a0d14c4..5d115d7 100644 --- a/src/declarative/fx/qfxanimatedimageitem.h +++ b/src/declarative/fx/qfxanimatedimageitem.h @@ -73,7 +73,7 @@ public: int frameCount() const; // Extends QFxImage's src property*/ - virtual void setSource(const QString&); + virtual void setSource(const QUrl&); Q_SIGNALS: void playingChanged(); diff --git a/src/declarative/fx/qfxhighlightfilter.cpp b/src/declarative/fx/qfxhighlightfilter.cpp index 3d5f413..2c6fb0a 100644 --- a/src/declarative/fx/qfxhighlightfilter.cpp +++ b/src/declarative/fx/qfxhighlightfilter.cpp @@ -58,7 +58,6 @@ public: QFxHighlightFilterPrivate() : xOffset(0), yOffset(0), tiled(false) {} - QString source; QUrl url; int xOffset; int yOffset; @@ -130,7 +129,7 @@ QFxHighlightFilter::~QFxHighlightFilter() */ QUrl QFxHighlightFilter::source() const { - return d->source; + return d->url; } void QFxHighlightFilter::imageLoaded() @@ -140,7 +139,7 @@ void QFxHighlightFilter::imageLoaded() if (!img.isNull()) d->tex.setImage(img.toImage()); #endif - emit sourceChanged(d->source); + emit sourceChanged(d->url); update(); } @@ -158,7 +157,7 @@ void QFxHighlightFilter::setSource(const QUrl &f) if (!f.isEmpty()) QFxPixmap::get(qmlEngine(this), d->url, this, SLOT(imageLoaded())); else - emit sourceChanged(d->source); + emit sourceChanged(d->url); } /*! diff --git a/src/declarative/fx/qfxitem.cpp b/src/declarative/fx/qfxitem.cpp index 648b0fb..079d691 100644 --- a/src/declarative/fx/qfxitem.cpp +++ b/src/declarative/fx/qfxitem.cpp @@ -901,11 +901,11 @@ void QFxItem::qmlLoaded() QFxItem *qmlChild = qobject_cast(obj); if (qmlChild) { qmlChild->setItemParent(this); - d->_qmlChildren.insert(d->_qml, qmlChild); + d->_qmlChildren.insert(d->_qml.toString(), qmlChild); d->qmlItem = qmlChild; } else { delete qmlChild; - d->_qml = QString(); + d->_qml = QUrl(); } delete d->_qmlcomp; d->_qmlcomp = 0; @@ -1962,7 +1962,7 @@ void QFxItem::newChild(const QString &type) { Q_D(QFxItem); - QUrl url = qmlContext(this)->resolvedUri(type); + QUrl url = qmlContext(this)->resolvedUri(QUrl(type)); if (url.isEmpty()) return; diff --git a/src/declarative/fx/qfxwebview.cpp b/src/declarative/fx/qfxwebview.cpp index d15502b..dc7f60e 100644 --- a/src/declarative/fx/qfxwebview.cpp +++ b/src/declarative/fx/qfxwebview.cpp @@ -1065,7 +1065,7 @@ QFxWebView *QFxWebPage::view() QObject *QFxWebPage::createPlugin(const QString &, const QUrl &url, const QStringList ¶mNames, const QStringList ¶mValues) { - QUrl comp = qmlContext(view())->resolvedUri(url.toString()); + QUrl comp = qmlContext(view())->resolvedUri(url); return new QWidget_Dummy_Plugin(comp,view(),paramNames,paramValues); } diff --git a/src/declarative/qml/qmlbindablevalue.cpp b/src/declarative/qml/qmlbindablevalue.cpp index e1b6961..f2cfcf8 100644 --- a/src/declarative/qml/qmlbindablevalue.cpp +++ b/src/declarative/qml/qmlbindablevalue.cpp @@ -136,7 +136,7 @@ void QmlBindableValue::update() QVariant value = this->value(); if (d->property.propertyType() == QVariant::Url && value.canConvert(QVariant::String) && !value.isNull()) - value.setValue(context()->resolvedUrl(value.toString())); + value.setValue(context()->resolvedUrl(QUrl(value.toString()))); d->property.write(value); } diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 3123254..41cbc19 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -281,7 +281,7 @@ bool QmlCompiler::compileStoreInstruction(QmlInstruction &instr, case QVariant::Url: { instr.type = QmlInstruction::StoreUrl; - QUrl u = output->url.resolved(string); + QUrl u = output->url.resolved(QUrl(string)); instr.storeUrl.propertyIndex = prop.propertyIndex(); instr.storeUrl.value = output->indexForString(u.toString()); } diff --git a/src/declarative/qml/qmlcompositetypemanager.cpp b/src/declarative/qml/qmlcompositetypemanager.cpp index a5e302c..9950b48 100644 --- a/src/declarative/qml/qmlcompositetypemanager.cpp +++ b/src/declarative/qml/qmlcompositetypemanager.cpp @@ -109,7 +109,7 @@ QmlCompositeTypeData::toCompiledComponent(QmlEngine *engine) status = Error; errors = compiler.errors(); for(int ii = 0; ii < errors.count(); ++ii) - errors[ii].setUrl(url); + errors[ii].setUrl(compiledComponent->url); compiledComponent->release(); compiledComponent = 0; } @@ -336,7 +336,7 @@ void QmlCompositeTypeManager::compile(QmlCompositeTypeData *unit) unit->status = QmlCompositeTypeData::Error; { QmlError error; - error.setUrl(unit->url); + error.setUrl(QUrl(unit->url)); error.setDescription(tr("Type %1 unavailable").arg(QLatin1String(type))); unit->errors << error; } diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index 2c1d324..23ab744 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -1128,7 +1128,7 @@ QVariant QmlExpression::value() for (int i = context()->d_func()->scopeChain.size() - 1; i > -1; --i) { scriptEngine->currentContext()->pushScope(context()->d_func()->scopeChain.at(i)); } - QScriptValue svalue = scriptEngine->evaluate(expression(), d->fileName, d->line); + QScriptValue svalue = scriptEngine->evaluate(expression(), d->fileName.toString(), d->line); if (scriptEngine->hasUncaughtException()) { if (scriptEngine->uncaughtException().isError()){ QScriptValue exception = scriptEngine->uncaughtException(); diff --git a/src/declarative/util/qmlscript.cpp b/src/declarative/util/qmlscript.cpp index e422f37..ab095b1 100644 --- a/src/declarative/util/qmlscript.cpp +++ b/src/declarative/util/qmlscript.cpp @@ -66,7 +66,7 @@ class QmlScriptPrivate : public QObjectPrivate public: QmlScriptPrivate() : reply(0) {} - void addScriptToEngine(const QString &, const QString &fileName=QString()); + void addScriptToEngine(const QString &, const QString &source=QString()); QString script; QNetworkReply *reply; @@ -156,7 +156,7 @@ void QmlScript::setSource(const QUrl &source) QFile file(d->url.toLocalFile()); file.open(QIODevice::ReadOnly); QByteArray ba = file.readAll(); - d->addScriptToEngine(QString::fromUtf8(ba), d->url); + d->addScriptToEngine(QString::fromUtf8(ba), file.fileName()); } else #endif { @@ -173,13 +173,13 @@ void QmlScript::replyFinished() Q_D(QmlScript); if (!d->reply->error()) { QByteArray ba = d->reply->readAll(); - d->addScriptToEngine(QString::fromUtf8(ba), d->url); + d->addScriptToEngine(QString::fromUtf8(ba), d->url.toString()); } d->reply->deleteLater(); d->reply = 0; } -void QmlScriptPrivate::addScriptToEngine(const QString &script, const QString &fileName) +void QmlScriptPrivate::addScriptToEngine(const QString &script, const QString &source) { #ifdef Q_ENABLE_PERFORMANCE_LOG QFxPerfTimer pt; @@ -202,7 +202,7 @@ void QmlScriptPrivate::addScriptToEngine(const QString &script, const QString &f currentContext->setActivationObject(context->d_func()->scopeChain.at(0)); - QScriptValue val = scriptEngine->evaluate(script, fileName); + QScriptValue val = scriptEngine->evaluate(script, source); if (scriptEngine->hasUncaughtException()) { if (scriptEngine->uncaughtException().isError()){ QScriptValue exception = scriptEngine->uncaughtException(); -- cgit v0.12 From 35521a8dac1cd10fe0e2bba9eb4df1b2a97320ef Mon Sep 17 00:00:00 2001 From: Warwick Allison Date: Fri, 12 Jun 2009 09:49:35 +1000 Subject: Help people find poor uses of QString -> QUrl conversion. Since a file name looks just like a relative URL, bugs can easily creep in if QString can be assigned directly to a QUrl rather than, for example, with an explicity "file:" scheme, or via QUrl::resolved(QUrl(...)). --- src/corelib/io/qurl.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/corelib/io/qurl.h b/src/corelib/io/qurl.h index e9c4a8d..276872b 100644 --- a/src/corelib/io/qurl.h +++ b/src/corelib/io/qurl.h @@ -81,12 +81,17 @@ public: Q_DECLARE_FLAGS(FormattingOptions, FormattingOption) QUrl(); +#ifdef Q_EXPLICIT_URL_QSTRING_CONVERSION + explicit +#endif QUrl(const QString &url); QUrl(const QString &url, ParsingMode mode); // ### Qt 5: merge the two constructors, with mode = TolerantMode QUrl(const QUrl ©); QUrl &operator =(const QUrl ©); +#ifndef Q_EXPLICIT_URL_QSTRING_CONVERSION QUrl &operator =(const QString &url); +#endif ~QUrl(); void setUrl(const QString &url); @@ -235,7 +240,9 @@ public: { url = QString::fromLatin1(QUrl::toPercentEncoding(url).constData()); } +#ifndef Q_EXPLICIT_URL_QSTRING_CONVERSION inline QT3_SUPPORT operator QString() const { return toString(); } +#endif inline QT3_SUPPORT bool cdUp() { *this = resolved(QUrl(QLatin1String(".."))); -- cgit v0.12 From e0d86a3b3da044c565a34f3a66335e3e977e1d63 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 12 Jun 2009 10:56:38 +1000 Subject: Behavior fixes. You can now write x: Behavior { NumericAnimation { duration: 500 } }, rather than having to specify the target and property for the animation explicitly. Also other minor fixes. --- examples/declarative/behaviours/test.qml | 15 ++++----------- src/declarative/util/qmlanimation.cpp | 26 ++++++++++++++++++++++++-- src/declarative/util/qmlanimation.h | 7 ++++--- src/declarative/util/qmlbehaviour.cpp | 32 +++++++++++++++++++------------- src/declarative/util/qmlbehaviour.h | 6 ++---- 5 files changed, 53 insertions(+), 33 deletions(-) diff --git a/examples/declarative/behaviours/test.qml b/examples/declarative/behaviours/test.qml index bb7109e..e6a50cd 100644 --- a/examples/declarative/behaviours/test.qml +++ b/examples/declarative/behaviours/test.qml @@ -54,7 +54,7 @@ Rect { width: 100 height: 100 id: bluerect - x: Behaviour { + x: Behavior { SequentialAnimation { NumericAnimation { target: bluerect @@ -73,13 +73,9 @@ Rect { duration: 250 } } - NumericAnimation { - target: bluerect - property: "x" - duration: 500 - } + NumericAnimation { duration: 500 } } - parent: Behaviour { + parent: Behavior { SequentialAnimation { NumericAnimation { target: bluerect @@ -87,10 +83,7 @@ Rect { to: 0 duration: 150 } - SetPropertyAction { - target: bluerect - property: "parent" - } + SetPropertyAction {} NumericAnimation { target: bluerect properties: "opacity" diff --git a/src/declarative/util/qmlanimation.cpp b/src/declarative/util/qmlanimation.cpp index d4aea81..7df249e 100644 --- a/src/declarative/util/qmlanimation.cpp +++ b/src/declarative/util/qmlanimation.cpp @@ -1168,12 +1168,17 @@ void QmlSetPropertyAction::transition(QmlStateActions &actions, } }; - QStringList props = d->properties.split(QLatin1Char(',')); + QStringList props = d->properties.isEmpty() ? QStringList() : d->properties.split(QLatin1Char(',')); for (int ii = 0; ii < props.count(); ++ii) props[ii] = props.at(ii).trimmed(); if (!d->propertyName.isEmpty() && !props.contains(d->propertyName)) props.append(d->propertyName); + if (d->userProperty.isValid() && props.isEmpty() && !target()) { + props.append(d->userProperty.value.name()); + d->target = d->userProperty.value.object(); + } + QmlSetPropertyAnimationAction *data = new QmlSetPropertyAnimationAction; QSet objs; @@ -1649,12 +1654,17 @@ void QmlNumericAnimation::transition(QmlStateActions &actions, } }; - QStringList props = d->properties.split(QLatin1Char(',')); + QStringList props = d->properties.isEmpty() ? QStringList() : d->properties.split(QLatin1Char(',')); for (int ii = 0; ii < props.count(); ++ii) props[ii] = props.at(ii).trimmed(); if (!d->propertyName.isEmpty() && !props.contains(d->propertyName)) props.append(d->propertyName); + if (d->userProperty.isValid() && props.isEmpty() && !target()) { + props.append(d->userProperty.value.name()); + d->target = d->userProperty.value.object(); + } + NTransitionData *data = new NTransitionData; QSet objs; @@ -1785,6 +1795,12 @@ void QmlSequentialAnimation::transition(QmlStateActions &actions, inc = -1; from = d->animations.count() - 1; } + + //### needed for Behavior + if (d->userProperty.isValid() && d->propertyName.isEmpty() && !target()) { + for (int i = 0; i < d->animations.count(); ++i) + d->animations.at(i)->setTarget(d->userProperty); + } //XXX removing and readding isn't ideal; we do it to get around the problem mentioned below. for (int i = d->ag->animationCount()-1; i >= 0; --i) @@ -1870,6 +1886,12 @@ void QmlParallelAnimation::transition(QmlStateActions &actions, { Q_D(QmlAnimationGroup); + //### needed for Behavior + if (d->userProperty.isValid() && d->propertyName.isEmpty() && !target()) { + for (int i = 0; i < d->animations.count(); ++i) + d->animations.at(i)->setTarget(d->userProperty); + } + for (int ii = 0; ii < d->animations.count(); ++ii) { d->animations.at(ii)->transition(actions, modified, direction); } diff --git a/src/declarative/util/qmlanimation.h b/src/declarative/util/qmlanimation.h index 8b9ecc2..5ab9dda 100644 --- a/src/declarative/util/qmlanimation.h +++ b/src/declarative/util/qmlanimation.h @@ -91,6 +91,8 @@ public: QString property() const; void setProperty(const QString &); + virtual void setTarget(const QmlMetaProperty &); + void classBegin(); void componentComplete(); @@ -109,7 +111,6 @@ public Q_SLOTS: void complete(); protected: - virtual void setTarget(const QmlMetaProperty &); QmlAbstractAnimation(QmlAbstractAnimationPrivate &dd, QObject *parent); public: @@ -446,8 +447,8 @@ Q_SIGNALS: }; QML_DECLARE_TYPE(QmlVariantAnimation) -#endif // QMLANIMATION_H - QT_END_NAMESPACE QT_END_HEADER + +#endif // QMLANIMATION_H diff --git a/src/declarative/util/qmlbehaviour.cpp b/src/declarative/util/qmlbehaviour.cpp index 077f666..3617541 100644 --- a/src/declarative/util/qmlbehaviour.cpp +++ b/src/declarative/util/qmlbehaviour.cpp @@ -44,11 +44,11 @@ #include "qmltransition.h" #include "qmlbehaviour.h" #include - +#include QT_BEGIN_NAMESPACE -QML_DEFINE_TYPE(QmlBehaviour,Behaviour) +QML_DEFINE_TYPE(QmlBehaviour,Behavior) class QmlBehaviourData : public QObject { @@ -92,18 +92,21 @@ public: { QmlConcreteList::append(a); _parent->group->addAnimation(a->qtAnimation()); + if (_parent->property.isValid()) { + a->setTarget(_parent->property); + } } virtual void clear() { QmlConcreteList::clear(); } //### private: QmlBehaviourPrivate *_parent; }; AnimationList operations; - QSequentialAnimationGroup *group; + QParallelAnimationGroup *group; }; /*! - \qmlclass Behaviour QmlBehaviour - \brief The Behaviour element allows you to specify a default animation for a property change. + \qmlclass Behavior QmlBehaviour + \brief The Behavior element allows you to specify a default animation for a property change. In example below, the rect will use a bounce easing curve over 200 millisecond for any changes to its y property: \code @@ -111,7 +114,7 @@ public: width: 20; height: 20 color: "#00ff00" y: 200 //initial value - y: Behaviour { + y: Behavior { NumericAnimation { easing: "easeOutBounce(amplitude:100)" duration: 200 @@ -126,14 +129,14 @@ QmlBehaviour::QmlBehaviour(QObject *parent) { Q_D(QmlBehaviour); d->valueData = new QmlBehaviourData(this); - d->group = new QSequentialAnimationGroup(this); + d->group = new QParallelAnimationGroup(this); } /*! - \qmlproperty QVariant Behaviour::fromValue - This property holds a selector specifying a starting value for the behaviour + \qmlproperty QVariant Behavior::fromValue + This property holds a selector specifying a starting value for the behavior - If you only want the behaviour to apply when the change starts at a + If you only want the behavior to apply when the change starts at a specific value you can specify fromValue. This selector is used in conjunction with the toValue selector. */ @@ -151,10 +154,10 @@ void QmlBehaviour::setFromValue(const QVariant &v) } /*! - \qmlproperty QVariant Behaviour::toValue - This property holds a selector specifying a ending value for the behaviour + \qmlproperty QVariant Behavior::toValue + This property holds a selector specifying a ending value for the behavior - If you only want the behaviour to apply when the change ends at a + If you only want the behavior to apply when the change ends at a specific value you can specify toValue. This selector is used in conjunction with the fromValue selector. */ @@ -230,6 +233,9 @@ void QmlBehaviour::setTarget(const QmlMetaProperty &property) d->property = property; d->currentValue = property.read(); d->property.connectNotifier(this, SLOT(propertyValueChanged())); + for (int ii = 0; ii < d->operations.count(); ++ii) { + d->operations.at(ii)->setTarget(property); + } } void QmlBehaviour::classBegin() diff --git a/src/declarative/util/qmlbehaviour.h b/src/declarative/util/qmlbehaviour.h index aef53a3..7cc83b2 100644 --- a/src/declarative/util/qmlbehaviour.h +++ b/src/declarative/util/qmlbehaviour.h @@ -88,10 +88,8 @@ private Q_SLOTS: }; QML_DECLARE_TYPE(QmlBehaviour) - -#endif // QMLBEHAVIOUR_H - - QT_END_NAMESPACE QT_END_HEADER + +#endif // QMLBEHAVIOUR_H -- cgit v0.12 From d3f42ead5e9de12dd1f733461ccb1a1298f6966f Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 12 Jun 2009 10:59:01 +1000 Subject: Fixup headers. --- src/declarative/util/qmlbind.h | 2 ++ src/declarative/util/qmlconnection.h | 6 +++--- src/declarative/util/qmldatetimeformatter.h | 3 +-- src/declarative/util/qmlfollow.h | 8 +++----- src/declarative/util/qmlfont.h | 4 ++-- src/declarative/util/qmllistaccessor.h | 4 ++-- src/declarative/util/qmlopenmetaobject.h | 3 ++- src/declarative/util/qmlpackage.h | 7 +++---- src/declarative/util/qmlstategroup.h | 7 +++---- 9 files changed, 21 insertions(+), 23 deletions(-) diff --git a/src/declarative/util/qmlbind.h b/src/declarative/util/qmlbind.h index 706e202..b7b77f2 100644 --- a/src/declarative/util/qmlbind.h +++ b/src/declarative/util/qmlbind.h @@ -51,6 +51,7 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Declarative) + class QmlBindPrivate; class Q_DECLARATIVE_EXPORT QmlBind : public QObject { @@ -86,4 +87,5 @@ QML_DECLARE_TYPE(QmlBind) QT_END_NAMESPACE QT_END_HEADER + #endif diff --git a/src/declarative/util/qmlconnection.h b/src/declarative/util/qmlconnection.h index 57a406b..4350123 100644 --- a/src/declarative/util/qmlconnection.h +++ b/src/declarative/util/qmlconnection.h @@ -51,6 +51,7 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Declarative) + class QmlBoundSignal; class QmlContext; class QmlConnectionPrivate; @@ -83,9 +84,8 @@ private: }; QML_DECLARE_TYPE(QmlConnection) -#endif - - QT_END_NAMESPACE QT_END_HEADER + +#endif diff --git a/src/declarative/util/qmldatetimeformatter.h b/src/declarative/util/qmldatetimeformatter.h index 5d11dab..84b27e3 100644 --- a/src/declarative/util/qmldatetimeformatter.h +++ b/src/declarative/util/qmldatetimeformatter.h @@ -45,7 +45,6 @@ #include #include - QT_BEGIN_HEADER QT_BEGIN_NAMESPACE @@ -109,8 +108,8 @@ private: QML_DECLARE_TYPE(QmlDateTimeFormatter) - QT_END_NAMESPACE QT_END_HEADER + #endif diff --git a/src/declarative/util/qmlfollow.h b/src/declarative/util/qmlfollow.h index d210592..72d6df5 100644 --- a/src/declarative/util/qmlfollow.h +++ b/src/declarative/util/qmlfollow.h @@ -45,12 +45,12 @@ #include #include - QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Declarative) + class QmlFollowPrivate; class Q_DECLARATIVE_EXPORT QmlFollow : public QmlPropertyValueSource, public QmlParserStatus @@ -94,10 +94,8 @@ Q_SIGNALS: QML_DECLARE_TYPE(QmlFollow) - -#endif // QFXFOLLOW_H - - QT_END_NAMESPACE QT_END_HEADER + +#endif // QFXFOLLOW_H diff --git a/src/declarative/util/qmlfont.h b/src/declarative/util/qmlfont.h index 1fee6cb..c4c86e2 100644 --- a/src/declarative/util/qmlfont.h +++ b/src/declarative/util/qmlfont.h @@ -45,12 +45,12 @@ #include #include - QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Declarative) + class QmlFontPrivate; class Q_DECLARATIVE_EXPORT QmlFont : public QObject { @@ -85,8 +85,8 @@ Q_SIGNALS: }; QML_DECLARE_TYPE(QmlFont) - QT_END_NAMESPACE QT_END_HEADER + #endif // QMLFONT_H diff --git a/src/declarative/util/qmllistaccessor.h b/src/declarative/util/qmllistaccessor.h index dd766b2..27a77a0 100644 --- a/src/declarative/util/qmllistaccessor.h +++ b/src/declarative/util/qmllistaccessor.h @@ -75,8 +75,8 @@ private: QVariant d; }; -#endif // QMLLISTACCESSOR_H - QT_END_NAMESPACE QT_END_HEADER + +#endif // QMLLISTACCESSOR_H diff --git a/src/declarative/util/qmlopenmetaobject.h b/src/declarative/util/qmlopenmetaobject.h index 239276d..f65660d 100644 --- a/src/declarative/util/qmlopenmetaobject.h +++ b/src/declarative/util/qmlopenmetaobject.h @@ -51,6 +51,7 @@ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Declarative) + class QmlOpenMetaObjectPrivate; class QMetaPropertyBuilder; class Q_DECLARATIVE_EXPORT QmlOpenMetaObject : public QAbstractDynamicMetaObject @@ -82,8 +83,8 @@ private: QmlOpenMetaObjectPrivate *d; }; - QT_END_NAMESPACE QT_END_HEADER + #endif // QMLOPENMETAOBJECT_H diff --git a/src/declarative/util/qmlpackage.h b/src/declarative/util/qmlpackage.h index cc77b6c..9f1d94f 100644 --- a/src/declarative/util/qmlpackage.h +++ b/src/declarative/util/qmlpackage.h @@ -44,12 +44,12 @@ #include - QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Declarative) + /***************************************************************************** ***************************************************************************** XXX Experimental @@ -79,9 +79,8 @@ public: }; QML_DECLARE_TYPE(QmlPackage) -#endif // QMLPACKAGE_H - - QT_END_NAMESPACE QT_END_HEADER + +#endif // QMLPACKAGE_H diff --git a/src/declarative/util/qmlstategroup.h b/src/declarative/util/qmlstategroup.h index ac1d917..3953e58 100644 --- a/src/declarative/util/qmlstategroup.h +++ b/src/declarative/util/qmlstategroup.h @@ -44,12 +44,12 @@ #include - QT_BEGIN_HEADER QT_BEGIN_NAMESPACE QT_MODULE(Declarative) + class QmlStateGroupPrivate; class QmlStateGroup : public QObject, public QmlParserStatus { @@ -87,9 +87,8 @@ private: }; QML_DECLARE_TYPE(QmlStateGroup) -#endif // QMLSTATEGROUP_H - - QT_END_NAMESPACE QT_END_HEADER + +#endif // QMLSTATEGROUP_H -- cgit v0.12 From d0baa9b8dc9ed191903447032f1cf6afe9a2463e Mon Sep 17 00:00:00 2001 From: Martin Jones Date: Fri, 12 Jun 2009 11:21:14 +1000 Subject: Set qreal to float for Symbian. Make sure we match the logic in qglobal.h. --- src/corelib/kernel/qmetatype.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/corelib/kernel/qmetatype.h b/src/corelib/kernel/qmetatype.h index 22214a4..687a070 100644 --- a/src/corelib/kernel/qmetatype.h +++ b/src/corelib/kernel/qmetatype.h @@ -89,7 +89,7 @@ public: // This logic must match the one in qglobal.h #if defined(QT_COORD_TYPE) QReal = 0, -#elif defined(QT_NO_FPU) || defined(QT_ARCH_ARM) || defined(QT_ARCH_WINDOWSCE) +#elif defined(QT_NO_FPU) || defined(QT_ARCH_ARM) || defined(QT_ARCH_WINDOWSCE) || defined(QT_ARCH_SYMBIAN) QReal = Float, #else QReal = Double, -- cgit v0.12 From 815df4da786a778517b1fac8435cc052d791ce92 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 12 Jun 2009 15:17:09 +1000 Subject: Speed up XmlListModel. --- src/declarative/extra/qmlxmllistmodel.cpp | 29 ++++++++++++++++++++++------- 1 file changed, 22 insertions(+), 7 deletions(-) diff --git a/src/declarative/extra/qmlxmllistmodel.cpp b/src/declarative/extra/qmlxmllistmodel.cpp index 62ede80..b10f5fd 100644 --- a/src/declarative/extra/qmlxmllistmodel.cpp +++ b/src/declarative/extra/qmlxmllistmodel.cpp @@ -202,11 +202,10 @@ void QmlXmlQuery::doQueryJob() QXmlItem item(result.next()); if (item.isAtomicValue()) count = item.toAtomicValue().toInt(); - prefix += QLatin1String("[%1]/"); } //qDebug() << count; - m_prefix = namespaces + prefix; + m_prefix = namespaces + prefix + QLatin1String("/"); m_data = xml; if (count > 0) m_size = count; @@ -222,8 +221,24 @@ void QmlXmlQuery::doSubQueryJob() QXmlQuery subquery; subquery.bindVariable(QLatin1String("inputDocument"), &b); - //XXX should we use an array of objects or something else rather than a table? - for (int j = 0; j < m_size; ++j) { + //### we might be able to condense even further (query for everything in one go) + for (int i = 0; i < m_roleObjects->size(); ++i) { + XmlListModelRole *role = m_roleObjects->at(i); + subquery.setQuery(m_prefix + QLatin1String("(let $v := ") + role->query() + QLatin1String(" return if ($v) then ") + role->query() + QLatin1String(" else \"\")")); + QXmlResultItems output3; + subquery.evaluateTo(&output3); + QXmlItem item(output3.next()); + QList resultList; + while (!item.isNull()) { + resultList << item.toAtomicValue(); + item = output3.next(); + } + m_modelData << resultList; + b.seek(0); + } + + //XXX this method is much slower, but would work better for incremental loading + /*for (int j = 0; j < m_size; ++j) { QList resultList; for (int i = 0; i < m_roleObjects->size(); ++i) { XmlListModelRole *role = m_roleObjects->at(i); @@ -248,7 +263,7 @@ void QmlXmlQuery::doSubQueryJob() b.seek(0); } m_modelData << resultList; - } + }*/ } @@ -362,7 +377,7 @@ QHash QmlXmlListModel::data(int index, const QList &roles) co for (int i = 0; i < roles.size(); ++i) { int role = roles.at(i); int roleIndex = d->roles.indexOf(role); - rv.insert(role, d->data.at(index).at(roleIndex)); + rv.insert(role, d->data.at(roleIndex).at(index)); } return rv; } @@ -462,8 +477,8 @@ void QmlXmlListModel::reload() d->queryId = -1; //clear existing data + int count = d->size; d->size = 0; - int count = d->data.count(); d->data.clear(); if (count > 0) emit itemsRemoved(0, count); -- cgit v0.12 From 87dff0ac19fc8af4c30fd7959723fbdb60eb3bdf Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 12 Jun 2009 15:35:27 +1000 Subject: Some XmlListModel cleanup. --- demos/declarative/flickr/flickr.qml | 2 +- demos/declarative/flickr/flickr2.qml | 2 +- examples/declarative/xmldata/daringfireball.qml | 1 - examples/declarative/xmldata/yahoonews.qml | 1 - src/declarative/extra/qmlxmllistmodel.cpp | 4 ++-- src/declarative/extra/qmlxmllistmodel.h | 12 +----------- 6 files changed, 5 insertions(+), 17 deletions(-) diff --git a/demos/declarative/flickr/flickr.qml b/demos/declarative/flickr/flickr.qml index da77d93..83448ee 100644 --- a/demos/declarative/flickr/flickr.qml +++ b/demos/declarative/flickr/flickr.qml @@ -16,7 +16,7 @@ Item { Role { name: "title"; query: "title/string()" } Role { name: "imagePath"; query: "media:thumbnail/@url/string()" } Role { name: "url"; query: "media:content/@url/string()" } - Role { name: "description"; query: "description/string()"; isCData: true } + Role { name: "description"; query: "description/string()" } Role { name: "tags"; query: "media:category/string()" } Role { name: "photoWidth"; query: "media:content/@width/string()" } Role { name: "photoHeight"; query: "media:content/@height/string()" } diff --git a/demos/declarative/flickr/flickr2.qml b/demos/declarative/flickr/flickr2.qml index 52f8675..79f7a32 100644 --- a/demos/declarative/flickr/flickr2.qml +++ b/demos/declarative/flickr/flickr2.qml @@ -18,7 +18,7 @@ Item { Role { name: "title"; query: "title/string()" } Role { name: "imagePath"; query: "media:thumbnail/@url/string()" } Role { name: "url"; query: "media:content/@url/string()" } - Role { name: "description"; query: "description/string()"; isCData: true } + Role { name: "description"; query: "description/string()" } Role { name: "tags"; query: "media:category/string()" } Role { name: "photoWidth"; query: "media:content/@width/string()" } Role { name: "photoHeight"; query: "media:content/@height/string()" } diff --git a/examples/declarative/xmldata/daringfireball.qml b/examples/declarative/xmldata/daringfireball.qml index 3877adf..b14dfbf 100644 --- a/examples/declarative/xmldata/daringfireball.qml +++ b/examples/declarative/xmldata/daringfireball.qml @@ -19,7 +19,6 @@ Rect { Role { name: "content" query: "content/string()" - isCData: true } }, Component { diff --git a/examples/declarative/xmldata/yahoonews.qml b/examples/declarative/xmldata/yahoonews.qml index 206c85f..b465ef1 100644 --- a/examples/declarative/xmldata/yahoonews.qml +++ b/examples/declarative/xmldata/yahoonews.qml @@ -21,7 +21,6 @@ Rect { Role { name: "description" query: "description/string()" - isCData: true } }, Component { diff --git a/src/declarative/extra/qmlxmllistmodel.cpp b/src/declarative/extra/qmlxmllistmodel.cpp index b10f5fd..51905fa 100644 --- a/src/declarative/extra/qmlxmllistmodel.cpp +++ b/src/declarative/extra/qmlxmllistmodel.cpp @@ -230,7 +230,7 @@ void QmlXmlQuery::doSubQueryJob() QXmlItem item(output3.next()); QList resultList; while (!item.isNull()) { - resultList << item.toAtomicValue(); + resultList << item.toAtomicValue(); //### we used to trim strings item = output3.next(); } m_modelData << resultList; @@ -346,7 +346,7 @@ void QmlXmlRoleList::insert(int i, XmlListModelRole *role) query: "doc($src)/rss/channel/item" Role { name: "title"; query: "title/string()" } Role { name: "link"; query: "link/string()" } - Role { name: "description"; query: "description/string()"; isCData: true } + Role { name: "description"; query: "description/string()" } } \endqml \note The model is currently static, so the above is really just a snapshot of an RSS feed. diff --git a/src/declarative/extra/qmlxmllistmodel.h b/src/declarative/extra/qmlxmllistmodel.h index bdbba47..c6aae4a 100644 --- a/src/declarative/extra/qmlxmllistmodel.h +++ b/src/declarative/extra/qmlxmllistmodel.h @@ -57,11 +57,9 @@ class Q_DECLARATIVE_EXPORT XmlListModelRole : public QObject Q_OBJECT Q_PROPERTY(QString name READ name WRITE setName) Q_PROPERTY(QString query READ query WRITE setQuery) - Q_PROPERTY(bool isCData READ isCData WRITE setIsCData) - Q_PROPERTY(bool isStringList READ isStringList WRITE setIsStringList) public: - XmlListModelRole() : m_isList(false), m_isCData(false) {} + XmlListModelRole() {} ~XmlListModelRole() {} QString name() const { return m_name; } @@ -70,17 +68,9 @@ public: QString query() const { return m_query; } void setQuery(const QString &query) { m_query = query; } - bool isStringList() const { return m_isList; } - void setIsStringList(bool b) { m_isList = b; } - - bool isCData() const { return m_isCData; } - void setIsCData(bool b) { m_isCData = b; } - private: QString m_name; QString m_query; - bool m_isList; - bool m_isCData; }; QML_DECLARE_TYPE(XmlListModelRole) -- cgit v0.12 From 79f58df5b28dca88a4359ea9a76325e1a4a7f4e5 Mon Sep 17 00:00:00 2001 From: Michael Brasser Date: Fri, 12 Jun 2009 15:56:33 +1000 Subject: Use standard cursor control for TextEdit. --- src/declarative/fx/qfxtextedit.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/declarative/fx/qfxtextedit.cpp b/src/declarative/fx/qfxtextedit.cpp index 5492aaa..5f2f36c 100644 --- a/src/declarative/fx/qfxtextedit.cpp +++ b/src/declarative/fx/qfxtextedit.cpp @@ -682,7 +682,9 @@ void QFxTextEdit::keyPressEvent(QKeyEvent *event) if (event->isAccepted()) return; - QTextCursor c = textCursor(); + //### this causes non-standard cursor behavior in some cases. + // is it still needed? + /*QTextCursor c = textCursor(); QTextCursor::MoveOperation op = QTextCursor::NoMove; if (event == QKeySequence::MoveToNextChar) { op = QTextCursor::Right; @@ -700,7 +702,7 @@ void QFxTextEdit::keyPressEvent(QKeyEvent *event) if (op != QTextCursor::NoMove && !c.movePosition(op)) event->ignore(); - else + else*/ d->control->processEvent(event, QPointF(0, 0)); } -- cgit v0.12 From f86dcade8716a0aee841ba05740887598633de17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 12 Jun 2009 10:24:34 +0200 Subject: Fixed clipping bug due to applying redirection offset twice. After change f0a4a37a5182660580fd361110d3fd51463221d8 the clip info stack already contains the redirection offset, so we don't need to apply it again. Reviewed-by: bnilsen --- src/gui/painting/qpainter.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/gui/painting/qpainter.cpp b/src/gui/painting/qpainter.cpp index 528c575..1094206 100644 --- a/src/gui/painting/qpainter.cpp +++ b/src/gui/painting/qpainter.cpp @@ -414,7 +414,7 @@ void QPainterPrivate::draw_helper(const QPainterPath &originalPath, DrawOperatio bool old_txinv = txinv; QTransform old_invMatrix = invMatrix; txinv = true; - invMatrix = state->redirectionMatrix.inverted(); + invMatrix = QTransform(); QPainterPath clipPath = q->clipPath(); QRectF r = clipPath.boundingRect().intersected(absPathRect); absPathRect = r.toAlignedRect(); -- cgit v0.12 From fd0ef21c295c316ccfebc833c011ed7a9fb5b3fc Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Fri, 12 Jun 2009 12:48:53 +0200 Subject: refactor some code removed qstrdup and used QByteArray to its full extent --- src/corelib/codecs/qtextcodec.cpp | 57 ++++++++++++++++++--------------------- 1 file changed, 26 insertions(+), 31 deletions(-) diff --git a/src/corelib/codecs/qtextcodec.cpp b/src/corelib/codecs/qtextcodec.cpp index 51ca43e..050c997 100644 --- a/src/corelib/codecs/qtextcodec.cpp +++ b/src/corelib/codecs/qtextcodec.cpp @@ -448,10 +448,10 @@ static const char * const tis_620locales[] = { // static const char * const tcvnlocales[] = { // "vi", "vi_VN", 0 }; -static bool try_locale_list(const char * const locale[], const char * lang) +static bool try_locale_list(const char * const locale[], const QByteArray &lang) { int i; - for(i=0; locale[i] && *locale[i] && strcmp(locale[i], lang); i++) + for(i=0; locale[i] && lang != locale[i]; i++) ; return locale[i] != 0; } @@ -503,13 +503,12 @@ static QTextCodec * ru_RU_hack(const char * i) { #endif #if !defined(Q_OS_WIN32) && !defined(Q_OS_WINCE) -static QTextCodec *checkForCodec(const char *name) { +static QTextCodec *checkForCodec(const QByteArray &name) { QTextCodec *c = QTextCodec::codecForName(name); if (!c) { - const char *at = strchr(name, '@'); - if (at) { - QByteArray n(name, at - name); - c = QTextCodec::codecForName(n.data()); + const int index = name.indexOf('@'); + if (index != -1) { + c = QTextCodec::codecForName(name.left(index)); } } return c; @@ -550,21 +549,19 @@ static void setupLocaleMapper() // definitely knows it, but since we cannot fully trust it, get ready // to fall back to environment variables. #if !defined(QT_NO_SETLOCALE) - char * ctype = qstrdup(setlocale(LC_CTYPE, 0)); + const QByteArray ctype = setlocale(LC_CTYPE, 0); #else - char * ctype = qstrdup(""); + const QByteArray ctype; #endif // Get the first nonempty value from $LC_ALL, $LC_CTYPE, and $LANG // environment variables. - char * lang = qstrdup(qgetenv("LC_ALL").constData()); - if (!lang || lang[0] == 0 || strcmp(lang, "C") == 0) { - if (lang) delete [] lang; - lang = qstrdup(qgetenv("LC_CTYPE").constData()); + QByteArray lang = qgetenv("LC_ALL"); + if (lang.isEmpty() || lang == "C") { + lang = qgetenv("LC_CTYPE"); } - if (!lang || lang[0] == 0 || strcmp(lang, "C") == 0) { - if (lang) delete [] lang; - lang = qstrdup(qgetenv("LANG").constData()); + if (lang.isEmpty() || lang == "C") { + lang = qgetenv("LANG"); } // Now try these in order: @@ -577,35 +574,35 @@ static void setupLocaleMapper() // 7. guess locale from lang // 1. CODESET from ctype if it contains a .CODESET part (e.g. en_US.ISO8859-15) - char * codeset = ctype ? strchr(ctype, '.') : 0; - if (codeset && *codeset == '.') - localeMapper = checkForCodec(codeset + 1); + int indexOfDot = ctype.indexOf('.'); + if (indexOfDot != -1) + localeMapper = checkForCodec( ctype.mid(indexOfDot + 1) ); // 2. CODESET from lang if it contains a .CODESET part - codeset = lang ? strchr(lang, '.') : 0; - if (!localeMapper && codeset && *codeset == '.') - localeMapper = checkForCodec(codeset + 1); + if (!localeMapper) { + indexOfDot = lang.indexOf('.'); + if (indexOfDot != -1) + localeMapper = checkForCodec( lang.mid(indexOfDot + 1) ); + } // 3. ctype (maybe the locale is named "ISO-8859-1" or something) - if (!localeMapper && ctype && *ctype != 0 && strcmp (ctype, "C") != 0) + if (!localeMapper && !ctype.isEmpty() && ctype != "C") localeMapper = checkForCodec(ctype); // 4. locale (ditto) - if (!localeMapper && lang && *lang != 0) + if (!localeMapper && !lang.isEmpty()) localeMapper = checkForCodec(lang); // 5. "@euro" - if ((!localeMapper && ctype && strstr(ctype, "@euro")) || (lang && strstr(lang, "@euro"))) + if ((!localeMapper && ctype.contains("@euro")) || lang.contains("@euro")) localeMapper = checkForCodec("ISO 8859-15"); // 6. guess locale from ctype unless ctype is "C" // 7. guess locale from lang - char * try_by_name = ctype; - if (ctype && *ctype != 0 && strcmp (ctype, "C") != 0) - try_by_name = lang; + const QByteArray &try_by_name = (!ctype.isEmpty() && ctype != "C") ? lang : ctype; // Now do the guessing. - if (lang && *lang && !localeMapper && try_by_name && *try_by_name) { + if (!lang.isEmpty() && !localeMapper && !try_by_name.isEmpty()) { if (try_locale_list(iso8859_15locales, lang)) localeMapper = QTextCodec::codecForName("ISO 8859-15"); else if (try_locale_list(iso8859_2locales, lang)) @@ -638,8 +635,6 @@ static void setupLocaleMapper() localeMapper = ru_RU_hack(lang); } - delete [] ctype; - delete [] lang; } // If everything failed, we default to 8859-1 -- cgit v0.12 From 814667587e6ab9dda754647f08fec969ed8434aa Mon Sep 17 00:00:00 2001 From: Prasanth Ullattil Date: Thu, 11 Jun 2009 15:59:33 +0200 Subject: Allow a maximum of 6 simultaneous HTTP connections to a server. Even though the standard mandates a maximum of 2 connections, most new browsers support atleast 6 connections. So we are also bumping the limit. Task-number: 251144 Reviewed-by: Markus Goetz Reviewed-by: Peter Hartmann --- src/network/access/qhttpnetworkconnection.cpp | 37 ++++++++++++++------------ src/network/access/qhttpnetworkconnection_p.h | 2 +- tests/auto/qnetworkreply/tst_qnetworkreply.cpp | 31 +++++++++++++++++++++ 3 files changed, 52 insertions(+), 18 deletions(-) diff --git a/src/network/access/qhttpnetworkconnection.cpp b/src/network/access/qhttpnetworkconnection.cpp index abaa7fb..b40b4c8 100644 --- a/src/network/access/qhttpnetworkconnection.cpp +++ b/src/network/access/qhttpnetworkconnection.cpp @@ -64,7 +64,7 @@ QT_BEGIN_NAMESPACE -const int QHttpNetworkConnectionPrivate::channelCount = 2; +const int QHttpNetworkConnectionPrivate::channelCount = 6; QHttpNetworkConnectionPrivate::QHttpNetworkConnectionPrivate(const QString &hostName, quint16 port, bool encrypt) : hostName(hostName), port(port), encrypt(encrypt), @@ -74,6 +74,7 @@ QHttpNetworkConnectionPrivate::QHttpNetworkConnectionPrivate(const QString &host #endif { + channels = new Channel[channelCount]; } QHttpNetworkConnectionPrivate::~QHttpNetworkConnectionPrivate() @@ -82,6 +83,7 @@ QHttpNetworkConnectionPrivate::~QHttpNetworkConnectionPrivate() channels[i].socket->close(); delete channels[i].socket; } + delete []channels; } void QHttpNetworkConnectionPrivate::connectSignals(QAbstractSocket *socket) @@ -1090,25 +1092,26 @@ void QHttpNetworkConnectionPrivate::_q_disconnected() void QHttpNetworkConnectionPrivate::_q_startNextRequest() { - // send the current request again - if (channels[0].resendCurrent || channels[1].resendCurrent) { - int i = channels[0].resendCurrent ? 0:1; - QAbstractSocket *socket = channels[i].socket; - channels[i].resendCurrent = false; - channels[i].state = IdleState; - if (channels[i].reply) - sendRequest(socket); - return; + //resend the necessary ones. + for (int i = 0; i < channelCount; ++i) { + if (channels[i].resendCurrent) { + channels[i].resendCurrent = false; + channels[i].state = IdleState; + if (channels[i].reply) + sendRequest(channels[i].socket); + } } - // send the request using the idle socket - QAbstractSocket *socket = channels[0].socket; - if (isSocketBusy(socket)) { - socket = (isSocketBusy(channels[1].socket) ? 0 :channels[1].socket); + QAbstractSocket *socket = 0; + for (int i = 0; i < channelCount; ++i) { + QAbstractSocket *chSocket = channels[i].socket; + // send the request using the idle socket + if (!isSocketBusy(chSocket)) { + socket = chSocket; + break; + } } - - if (!socket) { + if (!socket) return; // this will be called after finishing current request. - } unqueueAndSendRequest(socket); } diff --git a/src/network/access/qhttpnetworkconnection_p.h b/src/network/access/qhttpnetworkconnection_p.h index 4603a55..b5f3593 100644 --- a/src/network/access/qhttpnetworkconnection_p.h +++ b/src/network/access/qhttpnetworkconnection_p.h @@ -250,7 +250,7 @@ public: {} }; static const int channelCount; - Channel channels[2]; // maximum of 2 socket connections to the server + Channel *channels; // parallel connections to the server bool pendingAuthSignal; // there is an incomplete authentication signal bool pendingProxyAuthSignal; // there is an incomplete proxy authentication signal diff --git a/tests/auto/qnetworkreply/tst_qnetworkreply.cpp b/tests/auto/qnetworkreply/tst_qnetworkreply.cpp index 43b4ea9..a93d0b6 100644 --- a/tests/auto/qnetworkreply/tst_qnetworkreply.cpp +++ b/tests/auto/qnetworkreply/tst_qnetworkreply.cpp @@ -243,6 +243,8 @@ private Q_SLOTS: void proxyChange(); void authorizationError_data(); void authorizationError(); + + void httpConnectionCount(); }; QT_BEGIN_NAMESPACE @@ -3665,5 +3667,34 @@ void tst_QNetworkReply::authorizationError() QCOMPARE(QString(reply->readAll()), httpBody); } +void tst_QNetworkReply::httpConnectionCount() +{ + QTcpServer server; + QVERIFY(server.listen()); + QCoreApplication::instance()->processEvents(); + + for (int i = 0; i < 10; i++) { + QNetworkRequest request (QUrl("http://127.0.0.1:" + QString::number(server.serverPort()) + "/" + QString::number(i))); + QNetworkReply* reply = manager.get(request); + reply->setParent(this); + } + + int pendingConnectionCount = 0; + QTime time; + time.start(); + + while(pendingConnectionCount != 6) { + QCoreApplication::instance()->processEvents(); + while (server.nextPendingConnection()) + pendingConnectionCount++; + + // at max. wait 10 sec + if (time.elapsed() > 10000) + break; + } + + QCOMPARE(pendingConnectionCount, 6); +} + QTEST_MAIN(tst_QNetworkReply) #include "tst_qnetworkreply.moc" -- cgit v0.12 From 9bbd0bed3afc44ece34119a9c563726b0e6298a8 Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Fri, 12 Jun 2009 12:20:55 +0200 Subject: doc: Fixed several qdoc warnings. --- doc/src/qnamespace.qdoc | 11 ++- src/gui/graphicsview/qgraphicsitem.cpp | 122 ++++++++++++++++++------------- src/gui/graphicsview/qgraphicsview.cpp | 2 + src/gui/graphicsview/qgraphicswidget.cpp | 35 ++++++++- src/gui/kernel/qwidget.cpp | 4 +- 5 files changed, 116 insertions(+), 58 deletions(-) diff --git a/doc/src/qnamespace.qdoc b/doc/src/qnamespace.qdoc index 069541f..7772958 100644 --- a/doc/src/qnamespace.qdoc +++ b/doc/src/qnamespace.qdoc @@ -2674,11 +2674,14 @@ \enum Qt::TileRule \since 4.6 - This enum describes how to repeat or stretch the parts of an image when drawing. + This enum describes how to repeat or stretch the parts of an image + when drawing. \value Stretch Scale the image to fit to the available area. - \value Repeat Tile the image until there is no more space. May crop the last image. - \value Round Like Repeat, but scales the images down to ensure that the last image is not cropped. - \sa QPixmapBorders, qDrawBorderPixmap() + \value Repeat Tile the image until there is no more space. May crop + the last image. + + \value Round Like Repeat, but scales the images down to ensure that + the last image is not cropped. */ diff --git a/src/gui/graphicsview/qgraphicsitem.cpp b/src/gui/graphicsview/qgraphicsitem.cpp index 43cbca1..e4f2a75 100644 --- a/src/gui/graphicsview/qgraphicsitem.cpp +++ b/src/gui/graphicsview/qgraphicsitem.cpp @@ -91,30 +91,33 @@ \snippet doc/src/snippets/code/src_gui_graphicsview_qgraphicsitem.cpp 0 - The boundingRect() function has many different purposes. QGraphicsScene - bases its item index on boundingRect(), and QGraphicsView uses it both for - culling invisible items, and for determining the area that needs to be - recomposed when drawing overlapping items. In addition, QGraphicsItem's - collision detection mechanisms use boundingRect() to provide an efficient - cut-off. The fine grained collision algorithm in collidesWithItem() is based - on calling shape(), which returns an accurate outline of the item's shape - as a QPainterPath. - - QGraphicsScene expects all items boundingRect() and shape() to remain - unchanged unless it is notified. If you want to change an item's geometry - in any way, you must first call prepareGeometryChange() to allow - QGraphicsScene to update its bookkeeping. + The boundingRect() function has many different purposes. + QGraphicsScene bases its item index on boundingRect(), and + QGraphicsView uses it both for culling invisible items, and for + determining the area that needs to be recomposed when drawing + overlapping items. In addition, QGraphicsItem's collision + detection mechanisms use boundingRect() to provide an efficient + cut-off. The fine grained collision algorithm in + collidesWithItem() is based on calling shape(), which returns an + accurate outline of the item's shape as a QPainterPath. + + QGraphicsScene expects all items boundingRect() and shape() to + remain unchanged unless it is notified. If you want to change an + item's geometry in any way, you must first call + prepareGeometryChange() to allow QGraphicsScene to update its + bookkeeping. Collision detection can be done in two ways: \list 1 - \o Reimplement shape() to return an accurate shape for your item, and rely - on the default implementation of collidesWithItem() to do shape-shape - intersection. This can be rather expensive if the shapes are complex. + \o Reimplement shape() to return an accurate shape for your item, + and rely on the default implementation of collidesWithItem() to do + shape-shape intersection. This can be rather expensive if the + shapes are complex. - \o Reimplement collidesWithItem() to provide your own custom item and shape - collision algorithm. + \o Reimplement collidesWithItem() to provide your own custom item + and shape collision algorithm. \endlist @@ -136,24 +139,28 @@ position, pos(). To change the item's transformation, you can pass a transformation matrix to setTransform() - Item transformations accumulate from parent to child, so if both a parent and child - item are rotated 90 degrees, the child's total transformation will be 180 degrees. - Similarly, if the item's parent is scaled to 2x its original size, its - children will also be twice as large. An item's transformation does not - affect its own local geometry; all geometry functions (e.g., contains(), + Item transformations accumulate from parent to child, so if both a + parent and child item are rotated 90 degrees, the child's total + transformation will be 180 degrees. Similarly, if the item's + parent is scaled to 2x its original size, its children will also + be twice as large. An item's transformation does not affect its + own local geometry; all geometry functions (e.g., contains(), update(), and all the mapping functions) still operate in local coordinates. For convenience, QGraphicsItem provides the functions - sceneTransform(), which returns the item's total transformation matrix - (including its position and all parents' positions and transformations), - and scenePos(), which returns its position in scene coordinates. To reset - an item's matrix, call resetTransform(). + sceneTransform(), which returns the item's total transformation + matrix (including its position and all parents' positions and + transformations), and scenePos(), which returns its position in + scene coordinates. To reset an item's matrix, call + resetTransform(). - Another way to apply transformation to an item is to use the , or set the - different transformation properties (transformOrigin, x/y/zRotation, x/yScale, - horizontal/verticalShear). Those properties come in addition to the base transformation + Another way to apply transformation to an item is to use the , or + set the different transformation properties (transformOrigin, + x/y/zRotation, x/yScale, horizontal/verticalShear). Those + properties come in addition to the base transformation - The order you set the transformation properties does not affect the resulting transformation - The resulting transformation is always computed in the following order + The order you set the transformation properties does not affect + the resulting transformation The resulting transformation is + always computed in the following order \code [Origin] [Base] [RotateX] [RotateY] [RotateZ] [Shear] [Scale] [-Origin] @@ -2538,8 +2545,8 @@ QPointF QGraphicsItem::pos() const \sa y() */ -/* - Set's the x coordinate of the item's position. Equivalent to +/*! + Set's the \a x coordinate of the item's position. Equivalent to calling setPos(x, y()). \sa x(), setPos() @@ -2557,8 +2564,8 @@ void QGraphicsItem::setX(qreal x) \sa x() */ -/* - Set's the y coordinate of the item's position. Equivalent to +/*! + Set's the \a y coordinate of the item's position. Equivalent to calling setPos(x(), y). \sa x(), setPos() @@ -2743,7 +2750,8 @@ QTransform QGraphicsItem::transform() const The default is 0 - \warning The value doesn't take in account any rotation set with the setTransform() method. + \warning The value doesn't take in account any rotation set with + the setTransform() method. \sa setXRotation(), {Transformations} */ @@ -3048,7 +3056,7 @@ void QGraphicsItem::setShear(qreal sh, qreal sv) /*! \since 4.6 - Returns the origin point using for transformation in item coordinate. + Returns the origin point used for transformation in item coordinate. The default is QPointF(0,0). @@ -6440,15 +6448,21 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent \property QGraphicsObject::parent \brief the parent of the item - \sa QGraphicsItem::setParentItem, QGraphicsItem::parentObject + \sa QGraphicsItem::setParentItem(), QGraphicsItem::parentObject() */ +/*! + \property QGraphicsObject::id + \brief the id of of the item + + \sa QGraphicsItem::opacity(), QGraphicsItem::setOpacity() +*/ /*! \property QGraphicsObject::opacity \brief the opacity of the item - \sa QGraphicsItem::setOpacity, QGraphicsItem::opacity + \sa QGraphicsItem::setOpacity(), QGraphicsItem::opacity() */ /*! @@ -6456,7 +6470,13 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent This signal gets emitted whenever the opacity of the item changes - \sa opacity + \sa QGraphicsItem::opacity() +*/ + +/*! + \fn QGraphicsObject::parentChanged() + + This signal gets emitted whenever the parent of the item changes */ /*! @@ -6465,7 +6485,7 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent Describes the items position. - \sa QGraphicsItem::setPos, QGraphicsItem::pos, positionChanged + \sa QGraphicsItem::setPos(), QGraphicsItem::pos() */ /*! @@ -6474,7 +6494,7 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent Describes the items x position. - \sa QGraphicsItem::setX, setPos, xChanged + \sa QGraphicsItem::setX(), setPos(), xChanged() */ /*! @@ -6482,7 +6502,7 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent This signal gets emitted whenever the x position of the item changes - \sa pos + \sa pos() */ /*! @@ -6491,15 +6511,15 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent Describes the items y position. - \sa QGraphicsItem::setY, setPos, yChanged + \sa QGraphicsItem::setY(), setPos(), yChanged() */ /*! \fn QGraphicsObject::yChanged() - This signal gets emitted whenever the y position of the item changes + This signal gets emitted whenever the y position of the item changes. - \sa pos + \sa pos() */ /*! @@ -6508,15 +6528,15 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent Describes the items z value. - \sa QGraphicsItem::setZValue, zValue, zChanged + \sa QGraphicsItem::setZValue(), zValue(), zChanged() */ /*! \fn QGraphicsObject::zChanged() - This signal gets emitted whenever the z value of the item changes + This signal gets emitted whenever the z value of the item changes. - \sa pos + \sa pos() */ @@ -6536,7 +6556,7 @@ QGraphicsObject::QGraphicsObject(QGraphicsItemPrivate &dd, QGraphicsItem *parent This signal gets emitted whenever the item get's enabled or disabled. - \sa enabled + \sa isEnabled() */ /*! diff --git a/src/gui/graphicsview/qgraphicsview.cpp b/src/gui/graphicsview/qgraphicsview.cpp index a72aa5a..c94c1d7 100644 --- a/src/gui/graphicsview/qgraphicsview.cpp +++ b/src/gui/graphicsview/qgraphicsview.cpp @@ -217,6 +217,8 @@ static const int QGRAPHICSVIEW_PREALLOC_STYLE_OPTIONS = 503; // largest prime < minimizing the areas that require redrawing, which improves performance. A common side effect is that items that do draw with antialiasing can leave painting traces behind on the scene as they are moved. + + \omitvalue IndirectPainting */ /*! diff --git a/src/gui/graphicsview/qgraphicswidget.cpp b/src/gui/graphicsview/qgraphicswidget.cpp index 419277d..78bd062 100644 --- a/src/gui/graphicsview/qgraphicswidget.cpp +++ b/src/gui/graphicsview/qgraphicswidget.cpp @@ -1658,7 +1658,8 @@ bool QGraphicsWidget::isActiveWindow() const This property is only used for windows. - By default, if no title has been set, this property contains an empty string. + By default, if no title has been set, this property contains an + empty string. */ void QGraphicsWidget::setWindowTitle(const QString &title) { @@ -1721,6 +1722,38 @@ QGraphicsWidget *QGraphicsWidget::focusWidget() const return d->focusChild; } +/*! \property QGraphicsWidget::horizontalShear + \brief This property holds the horizontal shear value for the item. + */ + +/*! \property QGraphicsWidget::transformOrigin + \brief This property holds the origin point used for transformations + in item coordinates. + */ + +/*! \property QGraphicsWidget::verticalShear + \brief This property holds the vertical shear value for the item. + */ + +/*! \property QGraphicsWidget::xRotation + \brief This property holds the value for rotation around the x axis. + */ + +/*! \property QGraphicsWidget::xScale + \brief This property holds the scale factor for the x axis. + */ + +/*! \property QGraphicsWidget::yRotation + \brief This property holds the value for rotation around the y axis. + */ + +/*! \property QGraphicsWidget::yScale + \brief This property holds the scale factor for the y axis. + */ + +/*! \property QGraphicsWidget::zRotation + \brief This property holds the value for rotation around the z axis. + */ #ifndef QT_NO_SHORTCUT /*! diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index 7b0bf1e..d5fdd93 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -5857,7 +5857,7 @@ QWidget *QWidget::focusWidget() const /*! Returns the next widget in this widget's focus chain. - \sa previousInFocusChain + \sa previousInFocusChain() */ QWidget *QWidget::nextInFocusChain() const { @@ -5867,7 +5867,7 @@ QWidget *QWidget::nextInFocusChain() const /*! Returns the previous widget in this widget's focus chain. - \sa nextInFocusChain + \sa nextInFocusChain() \since 4.6 */ -- cgit v0.12 From 957063e915281af895529a239fee3dd52e5f0b5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 12 Jun 2009 12:26:55 +0200 Subject: Fixed clipping bugs in GL 2 paint engine. Similar to what was done in f86dcade8716a0aee841ba05740887598633de17, we shouldn't multiply by the redirectionMatrix in replayClipOperations() as the clip info matrices already contain the redirectionMatrix. Reviewed-by: bnilsen --- src/gui/painting/qpaintengineex.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/gui/painting/qpaintengineex.cpp b/src/gui/painting/qpaintengineex.cpp index 67a3fa9..222e29f 100644 --- a/src/gui/painting/qpaintengineex.cpp +++ b/src/gui/painting/qpaintengineex.cpp @@ -149,15 +149,11 @@ void QPaintEngineExPrivate::replayClipOperations() QTransform transform = q->state()->matrix; - const QTransform &redirection = q->state()->redirectionMatrix; - for (int i = 0; i < clipInfo.size(); ++i) { const QPainterClipInfo &info = clipInfo.at(i); - QTransform combined = info.matrix * redirection; - - if (combined != q->state()->matrix) { - q->state()->matrix = combined; + if (info.matrix != q->state()->matrix) { + q->state()->matrix = info.matrix; q->transformChanged(); } -- cgit v0.12 From 426be37acb7b7fb0bbd58ff8ec18dac8ae650375 Mon Sep 17 00:00:00 2001 From: mae Date: Fri, 12 Jun 2009 12:40:35 +0200 Subject: Make repeated calls to QToolTip::hideText() still hide the text Previously the 300 msec hide timer was restarted every time hideText() was called. Reviewed-by: Thorbjorn Lindeijer --- src/gui/kernel/qtooltip.cpp | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/src/gui/kernel/qtooltip.cpp b/src/gui/kernel/qtooltip.cpp index 15a3dd2..2f97e7b 100644 --- a/src/gui/kernel/qtooltip.cpp +++ b/src/gui/kernel/qtooltip.cpp @@ -126,14 +126,15 @@ public: bool eventFilter(QObject *, QEvent *); - QBasicTimer hideTimer; + QBasicTimer hideTimer, expireTimer; + bool fadingOut; void reuseTip(const QString &text); void hideTip(); void hideTipImmediately(); void setTipRect(QWidget *w, const QRect &r); - void restartHideTimer(); + void restartExpireTimer(); bool tipChanged(const QPoint &pos, const QString &text, QObject *o); void placeTip(const QPoint &pos, QWidget *w); @@ -190,16 +191,17 @@ QTipLabel::QTipLabel(const QString &text, QWidget *w) reuseTip(text); } -void QTipLabel::restartHideTimer() +void QTipLabel::restartExpireTimer() { int time = 10000 + 40 * qMax(0, text().length()-100); - hideTimer.start(time, this); + expireTimer.start(time, this); + hideTimer.stop(); } void QTipLabel::reuseTip(const QString &text) { #ifndef QT_NO_STYLE_STYLESHEET - if (styleSheetParent) { + if (styleSheetParent){ disconnect(styleSheetParent, SIGNAL(destroyed()), QTipLabel::instance, SLOT(styleSheetParentDestroyed())); styleSheetParent = 0; @@ -213,7 +215,7 @@ void QTipLabel::reuseTip(const QString &text) if (fm.descent() == 2 && fm.ascent() >= 11) ++extra.rheight(); resize(sizeHint() + extra); - restartHideTimer(); + restartExpireTimer(); } void QTipLabel::paintEvent(QPaintEvent *ev) @@ -257,7 +259,8 @@ QTipLabel::~QTipLabel() void QTipLabel::hideTip() { - hideTimer.start(300, this); + if (!hideTimer.isActive()) + hideTimer.start(300, this); } void QTipLabel::hideTipImmediately() @@ -278,8 +281,10 @@ void QTipLabel::setTipRect(QWidget *w, const QRect &r) void QTipLabel::timerEvent(QTimerEvent *e) { - if (e->timerId() == hideTimer.timerId()){ + if (e->timerId() == hideTimer.timerId() + || e->timerId() == expireTimer.timerId()){ hideTimer.stop(); + expireTimer.stop(); #if defined(Q_WS_MAC) && !defined(QT_NO_EFFECTS) if (QApplication::isEffectEnabled(Qt::UI_FadeTooltip)){ // Fade out tip on mac (makes it invisible). -- cgit v0.12 From 6a408b6c6d00a76c74a4d612d85996d7ad3f03ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Samuel=20R=C3=B8dal?= Date: Fri, 12 Jun 2009 12:54:18 +0200 Subject: Fixed bug where QTransform::type() failed to compute the correct type. Since QTransform::type() now uses a switch based on m_dirty, we can't treat m_dirty as a bit mask anymore. Reviewed-by: Ariya --- src/gui/painting/qtransform.cpp | 15 ++++++++++----- tests/auto/qtransform/tst_qtransform.cpp | 7 +++++++ 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/gui/painting/qtransform.cpp b/src/gui/painting/qtransform.cpp index c00012a..16d60f8 100644 --- a/src/gui/painting/qtransform.cpp +++ b/src/gui/painting/qtransform.cpp @@ -420,7 +420,8 @@ QTransform &QTransform::translate(qreal dx, qreal dy) affine._dy += dy*affine._m22 + dx*affine._m12; break; } - m_dirty |= TxTranslate; + if (m_dirty < TxTranslate) + m_dirty = TxTranslate; return *this; } @@ -472,7 +473,8 @@ QTransform & QTransform::scale(qreal sx, qreal sy) affine._m22 *= sy; break; } - m_dirty |= TxScale; + if (m_dirty < TxScale) + m_dirty = TxScale; return *this; } @@ -529,7 +531,8 @@ QTransform & QTransform::shear(qreal sh, qreal sv) break; } } - m_dirty |= TxShear; + if (m_dirty < TxShear) + m_dirty = TxShear; return *this; } @@ -605,7 +608,8 @@ QTransform & QTransform::rotate(qreal a, Qt::Axis axis) break; } } - m_dirty |= TxRotate; + if (m_dirty < TxRotate) + m_dirty = TxRotate; } else { QTransform result; if (axis == Qt::YAxis) { @@ -677,7 +681,8 @@ QTransform & QTransform::rotateRadians(qreal a, Qt::Axis axis) break; } } - m_dirty |= TxRotate; + if (m_dirty < TxRotate) + m_dirty = TxRotate; } else { QTransform result; if (axis == Qt::YAxis) { diff --git a/tests/auto/qtransform/tst_qtransform.cpp b/tests/auto/qtransform/tst_qtransform.cpp index 74c405e..3b13a41 100644 --- a/tests/auto/qtransform/tst_qtransform.cpp +++ b/tests/auto/qtransform/tst_qtransform.cpp @@ -603,6 +603,13 @@ void tst_QTransform::types() 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f); QCOMPARE(m3.type(), QTransform::TxProject); + + QTransform m4; + m4.scale(5, 5); + m4.translate(4, 2); + m4.rotate(45); + + QCOMPARE(m4.type(), QTransform::TxRotate); } -- cgit v0.12 From 643e58248a22e54134c99d2ba70371f7f57b4040 Mon Sep 17 00:00:00 2001 From: Kent Hansen Date: Fri, 12 Jun 2009 13:03:59 +0200 Subject: add streaming ops for scriptdebugger object deltas Needed for remote debugging. --- .../debugging/qscriptdebuggerobjectsnapshotdelta_p.h | 5 +++++ .../debugging/qscriptdebuggervalueproperty.cpp | 17 +++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/src/scripttools/debugging/qscriptdebuggerobjectsnapshotdelta_p.h b/src/scripttools/debugging/qscriptdebuggerobjectsnapshotdelta_p.h index e3ec541..546ed7f 100644 --- a/src/scripttools/debugging/qscriptdebuggerobjectsnapshotdelta_p.h +++ b/src/scripttools/debugging/qscriptdebuggerobjectsnapshotdelta_p.h @@ -60,6 +60,8 @@ QT_BEGIN_NAMESPACE +class QDataStream; + class Q_AUTOTEST_EXPORT QScriptDebuggerObjectSnapshotDelta { public: @@ -68,6 +70,9 @@ public: QScriptDebuggerValuePropertyList addedProperties; }; +Q_AUTOTEST_EXPORT QDataStream &operator<<(QDataStream &, const QScriptDebuggerObjectSnapshotDelta &); +Q_AUTOTEST_EXPORT QDataStream &operator>>(QDataStream &, QScriptDebuggerObjectSnapshotDelta &); + QT_END_NAMESPACE #endif diff --git a/src/scripttools/debugging/qscriptdebuggervalueproperty.cpp b/src/scripttools/debugging/qscriptdebuggervalueproperty.cpp index 723e304..51133bc 100644 --- a/src/scripttools/debugging/qscriptdebuggervalueproperty.cpp +++ b/src/scripttools/debugging/qscriptdebuggervalueproperty.cpp @@ -41,6 +41,7 @@ #include "qscriptdebuggervalueproperty_p.h" #include "qscriptdebuggervalue_p.h" +#include "qscriptdebuggerobjectsnapshotdelta_p.h" #include #include @@ -225,4 +226,20 @@ QDataStream &operator>>(QDataStream &in, QScriptDebuggerValueProperty &property) return in; } +QDataStream &operator<<(QDataStream &out, const QScriptDebuggerObjectSnapshotDelta &delta) +{ + out << delta.removedProperties; + out << delta.changedProperties; + out << delta.addedProperties; + return out; +} + +QDataStream &operator>>(QDataStream &in, QScriptDebuggerObjectSnapshotDelta &delta) +{ + in >> delta.removedProperties; + in >> delta.changedProperties; + in >> delta.addedProperties; + return in; +} + QT_END_NAMESPACE -- cgit v0.12 From d86ec1c4bec373090d85835f1bec44b025fa2fbc Mon Sep 17 00:00:00 2001 From: Martin Smith Date: Fri, 12 Jun 2009 13:44:43 +0200 Subject: doc: Fixed several qdoc warnings. --- src/gui/painting/qdrawutil.cpp | 37 ++++++++++++++++++++++++++++++++----- 1 file changed, 32 insertions(+), 5 deletions(-) diff --git a/src/gui/painting/qdrawutil.cpp b/src/gui/painting/qdrawutil.cpp index 4020593..29b922d 100644 --- a/src/gui/painting/qdrawutil.cpp +++ b/src/gui/painting/qdrawutil.cpp @@ -1046,9 +1046,19 @@ void qDrawItem(QPainter *p, Qt::GUIStyle gs, draw it, similar to \l{http://www.w3.org/TR/css3-background/} {CSS3 border-images}. - \sa qDrawBorderPixmap, Qt::TileRule, QTileRules + \sa Qt::TileRule, QTileRules */ +/*! \fn QMargins::QMargins(int margin) + Constructs a QMargins with the top, left, bottom, and + right margins set to \a margin. +*/ + +/*! \fn QMargins::QMargins(int topMargin, int leftMargin, int bottomMargin, int rightMargin) + Constructs a QMargins with the given \a topMargin, \a leftMargin, + \a bottomMargin, and \a rightMargin. + */ + /*! \class QTileRules \since 4.6 @@ -1056,20 +1066,37 @@ void qDrawItem(QPainter *p, Qt::GUIStyle gs, Holds the rules used to draw a pixmap or image split into nine segments, similar to \l{http://www.w3.org/TR/css3-background/}{CSS3 border-images}. - \sa qDrawBorderPixmap, Qt::TileRule, QMargins + \sa Qt::TileRule, QMargins */ +/*! \fn QTileRules::QTileRules(Qt::TileRule horizontalRule, Qt::TileRule verticalRule) + Constructs a QTileRules with the given \a horizontalRule and + \a verticalRule. + */ + +/*! \fn QTileRules::QTileRules(Qt::TileRule rule) + Constructs a QTileRules with the given \a rule used for both + the horizontal rule and the vertical rule. + */ + /*! - \fn qDrawBorderPixmap(QPainter *painter, const QRect &target, const QMargins &margins, const QPixmap &pixmap) + \fn void qDrawBorderPixmap(QPainter *painter, const QRect &target, const QMargins &margins, const QPixmap &pixmap) \since 4.6 + \relates QMargins Draws the given \a pixmap into the given \a target rectangle, using the given \a painter. The pixmap will be split into nine segments and drawn according to the \a margins structure. */ -static inline void qVerticalRepeat(QPainter *painter, const QRect &target, const QPixmap &pixmap, const QRect &source, - void (*drawPixmap)(QPainter*, const QRect&, const QPixmap&, const QRect&)) +static inline void qVerticalRepeat(QPainter *painter, + const QRect &target, + const QPixmap &pixmap, + const QRect &source, + void (*drawPixmap)(QPainter*, + const QRect&, + const QPixmap&, + const QRect&)) { const int x = target.x(); const int width = target.width(); -- cgit v0.12 From 8134541fc3229177ec7545fa0d3ea49eadc8f00c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bj=C3=B8rn=20Erik=20Nilsen?= Date: Fri, 12 Jun 2009 13:27:57 +0200 Subject: QGraphicsItems are repainted when outside the view's exposed region. The problem was that we used QRect::isEmpty() on the item's bounding rect intersected with the exposed region's bounding rect as a criteria for whether the item should be drawn or not. This does not work as expected with partial updates, where the boundingRect() of the exposed region easily can cover the entire viewport area. The item should *only* be drawn if its bounding rect intersects with the exposed region (and not the exposed region's bounding rect). Auto-test included. --- src/gui/graphicsview/qgraphicsscene.cpp | 11 +++++---- tests/auto/qgraphicsview/tst_qgraphicsview.cpp | 34 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/src/gui/graphicsview/qgraphicsscene.cpp b/src/gui/graphicsview/qgraphicsscene.cpp index 55d8a1d..673fd23 100644 --- a/src/gui/graphicsview/qgraphicsscene.cpp +++ b/src/gui/graphicsview/qgraphicsscene.cpp @@ -5074,8 +5074,8 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } // Calculate the full transform for this item. - QRect viewBoundingRect; bool wasDirtyParentSceneTransform = false; + bool dontDrawItem = true; QTransform transform; if (item) { if (item->d_ptr->itemIsUntransformable()) { @@ -5091,15 +5091,17 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * transform = item->d_ptr->sceneTransform; transform *= viewTransform; } - + QRectF brect = item->boundingRect(); // ### This does not take the clip into account. _q_adjustRect(&brect); - viewBoundingRect = transform.mapRect(brect).toRect(); + QRect viewBoundingRect = transform.mapRect(brect).toRect(); item->d_ptr->paintedViewBoundingRects.insert(widget, viewBoundingRect); viewBoundingRect.adjust(-1, -1, 1, 1); if (exposedRegion) - viewBoundingRect &= exposedRegion->boundingRect(); + dontDrawItem = !exposedRegion->intersects(viewBoundingRect); + else + dontDrawItem = viewBoundingRect.isEmpty(); } // Find and sort children. @@ -5154,7 +5156,6 @@ void QGraphicsScenePrivate::drawSubtreeRecursive(QGraphicsItem *item, QPainter * } bool childClip = (item && (item->d_ptr->flags & QGraphicsItem::ItemClipsChildrenToShape)); - bool dontDrawItem = !item || viewBoundingRect.isEmpty(); bool dontDrawChildren = item && dontDrawItem && childClip; childClip &= !dontDrawChildren && !children->isEmpty(); if (item && ((item->d_ptr->flags & QGraphicsItem::ItemHasNoContents) || invisibleButChildIgnoresParentOpacity)) diff --git a/tests/auto/qgraphicsview/tst_qgraphicsview.cpp b/tests/auto/qgraphicsview/tst_qgraphicsview.cpp index 06b4a78..78d09ba 100644 --- a/tests/auto/qgraphicsview/tst_qgraphicsview.cpp +++ b/tests/auto/qgraphicsview/tst_qgraphicsview.cpp @@ -194,6 +194,7 @@ private slots: void mouseTracking(); void mouseTracking2(); void render(); + void exposeRegion(); // task specific tests below me void task172231_untransformableItems(); @@ -3323,6 +3324,39 @@ void tst_QGraphicsView::render() QCOMPARE(r4->paints, 2); } +void tst_QGraphicsView::exposeRegion() +{ + RenderTester *item = new RenderTester(QRectF(0, 0, 20, 20)); + QGraphicsScene scene; + scene.addItem(item); + + CustomView view; + view.setScene(&scene); + view.show(); +#ifdef Q_WS_X11 + qt_x11_wait_for_window_manager(&view); +#endif + QTest::qWait(125); + + item->paints = 0; + view.lastUpdateRegions.clear(); + + // Update a small area in the viewport's topLeft() and bottomRight(). + // (the boundingRect() of this area covers the entire viewport). + QWidget *viewport = view.viewport(); + QRegion expectedExposeRegion = QRect(0, 0, 5, 5); + expectedExposeRegion += QRect(viewport->rect().bottomRight() - QPoint(5, 5), QSize(5, 5)); + viewport->update(expectedExposeRegion); + qApp->processEvents(); + + // Make sure it triggers correct repaint on the view. + QCOMPARE(view.lastUpdateRegions.size(), 1); + QCOMPARE(view.lastUpdateRegions.at(0), expectedExposeRegion); + + // Make sure the item didn't get any repaints. + QCOMPARE(item->paints, 0); +} + void tst_QGraphicsView::task253415_reconnectUpdateSceneOnSceneChanged() { QGraphicsView view; -- cgit v0.12 From f2b93868f48a3e2d6e462ca8a051ab47eefef49d Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Fri, 12 Jun 2009 13:56:30 +0200 Subject: QMenu, QMenuBar: small cleanup Removed calls to the widget getters because we have the members directly in the private class. --- src/gui/kernel/qshortcut.cpp | 1 - src/gui/widgets/qdockwidget.cpp | 2 +- src/gui/widgets/qmenu.cpp | 4 ++-- src/gui/widgets/qmenu_p.h | 2 +- src/gui/widgets/qmenubar.cpp | 18 +++++++----------- src/gui/widgets/qsizegrip.cpp | 2 +- src/gui/widgets/qtoolbutton.cpp | 4 +--- 7 files changed, 13 insertions(+), 20 deletions(-) diff --git a/src/gui/kernel/qshortcut.cpp b/src/gui/kernel/qshortcut.cpp index 50b6e59..bced833 100644 --- a/src/gui/kernel/qshortcut.cpp +++ b/src/gui/kernel/qshortcut.cpp @@ -163,7 +163,6 @@ public: void QShortcutPrivate::redoGrab(QShortcutMap &map) { Q_Q(QShortcut); - QWidget *parent = q->parentWidget(); if (!parent) { qWarning("QShortcut: No widget parent defined"); return; diff --git a/src/gui/widgets/qdockwidget.cpp b/src/gui/widgets/qdockwidget.cpp index 30f9a87..e20fedd 100644 --- a/src/gui/widgets/qdockwidget.cpp +++ b/src/gui/widgets/qdockwidget.cpp @@ -1053,7 +1053,7 @@ void QDockWidgetPrivate::setWindowState(bool floating, bool unplug, const QRect if (floating != wasFloating) { emit q->topLevelChanged(floating); - if (!floating && q->parentWidget()) { + if (!floating && parent) { QMainWindowLayout *mwlayout = qobject_cast(q->parentWidget()->layout()); if (mwlayout) emit q->dockLocationChanged(mwlayout->dockWidgetArea(q)); diff --git a/src/gui/widgets/qmenu.cpp b/src/gui/widgets/qmenu.cpp index 7baea94..aa601cb 100644 --- a/src/gui/widgets/qmenu.cpp +++ b/src/gui/widgets/qmenu.cpp @@ -205,7 +205,6 @@ void QMenuPrivate::calcActionRects(QMap &actionRects, QList items = filterActions(q->actions()); int max_column_width = 0, dh = popupGeometry(QApplication::desktop()->screenNumber(q)).height(), ncols = 1, @@ -218,6 +217,7 @@ void QMenuPrivate::calcActionRects(QMap &actionRects, QList items = filteredActions(); for(int i = 0; i < items.count(); i++) { QAction *action = items.at(i); if (widgetItems.value(action)) @@ -348,7 +348,7 @@ void QMenuPrivate::updateActions() itemsDirty = 0; } -QList QMenuPrivate::filterActions(const QList &actions) const +QList QMenuPrivate::filteredActions() const { QList visibleActions; int i = 0; diff --git a/src/gui/widgets/qmenu_p.h b/src/gui/widgets/qmenu_p.h index f08283d..1dfe701 100644 --- a/src/gui/widgets/qmenu_p.h +++ b/src/gui/widgets/qmenu_p.h @@ -161,7 +161,7 @@ public: void calcActionRects(QMap &actionRects, QList &actionList) const; void updateActions(); QRect popupGeometry(int screen=-1) const; - QList filterActions(const QList &actions) const; + QList filteredActions() const; uint ncols : 4; //4 bits is probably plenty uint collapsibleSeparators : 1; diff --git a/src/gui/widgets/qmenubar.cpp b/src/gui/widgets/qmenubar.cpp index 51e38e6..68a0233 100644 --- a/src/gui/widgets/qmenubar.cpp +++ b/src/gui/widgets/qmenubar.cpp @@ -116,11 +116,9 @@ QSize QMenuBarExtension::sizeHint() const */ QAction *QMenuBarPrivate::actionAt(QPoint p) const { - Q_Q(const QMenuBar); - QList items = q->actions(); - for(int i = 0; i < items.size(); ++i) { - if(actionRect(items.at(i)).contains(p)) - return items.at(i); + for(int i = 0; i < actions.size(); ++i) { + if(actionRect(actions.at(i)).contains(p)) + return actions.at(i); } return 0; } @@ -259,9 +257,9 @@ void QMenuBarPrivate::updateGeometries() } q->updateGeometry(); #ifdef QT3_SUPPORT - if (q->parentWidget() != 0) { + if (parent) { QMenubarUpdatedEvent menubarUpdated(q); - QApplication::sendEvent(q->parentWidget(), &menubarUpdated); + QApplication::sendEvent(parent, &menubarUpdated); } #endif } @@ -413,15 +411,14 @@ void QMenuBarPrivate::calcActionRects(int max_width, int start, QMapstyle()->pixelMetric(QStyle::PM_MenuBarItemSpacing, 0, q); int max_item_height = 0, separator = -1, separator_start = 0, separator_len = 0; - QList items = q->actions(); //calculate size const QFontMetrics fm = q->fontMetrics(); const int hmargin = q->style()->pixelMetric(QStyle::PM_MenuBarHMargin, 0, q), vmargin = q->style()->pixelMetric(QStyle::PM_MenuBarVMargin, 0, q), icone = q->style()->pixelMetric(QStyle::PM_SmallIconSize, 0, q); - for(int i = 0; i < items.count(); i++) { - QAction *action = items.at(i); + for(int i = 0; i < actions.count(); i++) { + QAction *action = actions.at(i); if(!action->isVisible()) continue; @@ -534,7 +531,6 @@ void QMenuBarPrivate::_q_actionHovered() emit q->hovered(action); #ifndef QT_NO_ACCESSIBILITY if (QAccessible::isActive()) { - QList actions = q->actions(); int actionIndex = actions.indexOf(action); ++actionIndex; QAccessible::updateAccessibility(q, actionIndex, QAccessible::Focus); diff --git a/src/gui/widgets/qsizegrip.cpp b/src/gui/widgets/qsizegrip.cpp index 6458b15..244d34a 100644 --- a/src/gui/widgets/qsizegrip.cpp +++ b/src/gui/widgets/qsizegrip.cpp @@ -139,7 +139,7 @@ public: void QSizeGripPrivate::updateMacSizer(bool hide) const { Q_Q(const QSizeGrip); - if (QApplication::closingDown() || !q->parentWidget()) + if (QApplication::closingDown() || !parent) return; QWidget *topLevelWindow = qt_sizegrip_topLevelWidget(const_cast(q)); if(topLevelWindow && topLevelWindow->isWindow()) diff --git a/src/gui/widgets/qtoolbutton.cpp b/src/gui/widgets/qtoolbutton.cpp index 0eb6364..d26cf5b 100644 --- a/src/gui/widgets/qtoolbutton.cpp +++ b/src/gui/widgets/qtoolbutton.cpp @@ -104,10 +104,9 @@ public: #ifndef QT_NO_MENU bool QToolButtonPrivate::hasMenu() const { - Q_Q(const QToolButton); return ((defaultAction && defaultAction->menu()) || (menuAction && menuAction->menu()) - || q->actions().size() > (defaultAction ? 1 : 0)); + || actions.size() > (defaultAction ? 1 : 0)); } #endif @@ -882,7 +881,6 @@ void QToolButtonPrivate::popupTimerDone() } else { actualMenu = new QMenu(q); mustDeleteActualMenu = true; - QList actions = q->actions(); for(int i = 0; i < actions.size(); i++) actualMenu->addAction(actions.at(i)); } -- cgit v0.12 From 31b30cf6e95cf76d62d226b3253cc9ed2076b1a1 Mon Sep 17 00:00:00 2001 From: Alan Alpert Date: Mon, 15 Jun 2009 09:41:59 +1000 Subject: minor doc fixes --- src/declarative/qml/qmlengine.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index 73b9245..435019a 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -827,7 +827,7 @@ QmlEngine *QmlEngine::activeEngine() dynamically creates and returns objects when called from QtScript, and these objects are visual items in the QML tree. - \sa QmlEngine::newQObject() + \sa QScriptEngine::newQObject() */ QScriptValue QmlEngine::qmlScriptObject(QObject* object, QmlEngine* engine) { @@ -884,6 +884,7 @@ QScriptValue QmlEngine::qmlScriptObject(QObject* object, QmlEngine* engine) } \endcode + \sa QmlComponent::createObject() */ QScriptValue QmlEngine::createComponent(QScriptContext *ctxt, QScriptEngine *engine) { -- cgit v0.12 From 1312c0ca987b008d43558ff4cfa69b8dfd11616e Mon Sep 17 00:00:00 2001 From: Thierry Bastian Date: Mon, 15 Jun 2009 17:17:12 +0200 Subject: Fix a assert failure on windows When creating a file dialog, you need to show its parent prior to invoking that dialog. --- tools/qmlviewer/main.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tools/qmlviewer/main.cpp b/tools/qmlviewer/main.cpp index ed700a0..5c75656 100644 --- a/tools/qmlviewer/main.cpp +++ b/tools/qmlviewer/main.cpp @@ -154,11 +154,11 @@ int main(int argc, char ** argv) viewer.setDeviceKeys(true); viewer.setRecordDither(dither); viewer.setRecordArgs(recordargs); + viewer.show(); if (!fileName.isEmpty()) viewer.openQml(fileName); else viewer.open(); - viewer.show(); return app.exec(); } -- cgit v0.12 From 364524ddf8dddddcbe86917ce2c0271223b78ce6 Mon Sep 17 00:00:00 2001 From: Rhys Weatherley Date: Tue, 16 Jun 2009 10:46:21 +1000 Subject: Export QmlStateGroup so that it can be used by non-QFxItem DUI's --- src/declarative/util/qmlstategroup.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/declarative/util/qmlstategroup.h b/src/declarative/util/qmlstategroup.h index 3953e58..237b60e 100644 --- a/src/declarative/util/qmlstategroup.h +++ b/src/declarative/util/qmlstategroup.h @@ -51,7 +51,7 @@ QT_BEGIN_NAMESPACE QT_MODULE(Declarative) class QmlStateGroupPrivate; -class QmlStateGroup : public QObject, public QmlParserStatus +class Q_DECLARATIVE_EXPORT QmlStateGroup : public QObject, public QmlParserStatus { Q_OBJECT Q_INTERFACES(QmlParserStatus) -- cgit v0.12 From ce28ad22e2e8d7dadea55f89e9ef93f2528d1098 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 16 Jun 2009 12:26:39 +1000 Subject: Revert "Compilation fix on MSVC" This reverts commit 6d28410756ab29277807d2026b4cbd8e1c707714. --- src/declarative/qml/qmlprivate.h | 46 +++++++++++++++++++++++----- tests/auto/declarative/qmlparser/testtypes.h | 20 +++++++++--- 2 files changed, 54 insertions(+), 12 deletions(-) diff --git a/src/declarative/qml/qmlprivate.h b/src/declarative/qml/qmlprivate.h index 25e60e0..21a1164 100644 --- a/src/declarative/qml/qmlprivate.h +++ b/src/declarative/qml/qmlprivate.h @@ -123,13 +123,43 @@ namespace QmlPrivate } }; - template - struct has_qmlAttachedProperties + template + class has_attachedPropertiesMember + { + typedef int yes_type; + typedef char no_type; + template + struct Selector {}; + + template + static yes_type test(Selector*); + + template + static no_type test(...); + + public: + static bool const value = sizeof(test(0)) == sizeof(yes_type); + }; + + template + class has_attachedPropertiesMethod { - template struct type_check; - template static char check(type_check *); - template static int check(...); - static bool const value = sizeof(check(0)) == sizeof(char); + typedef int yes_type; + typedef char no_type; + + template + static yes_type check(ReturnType *(*)(QObject *)); + static no_type check(...); + + public: + static bool const value = sizeof(check(&T::qmlAttachedProperties)) == sizeof(yes_type); + }; + + template + class has_attachedPropertiesMethod + { + public: + static bool const value = false; }; template @@ -161,13 +191,13 @@ namespace QmlPrivate template inline QmlAttachedPropertiesFunc attachedPropertiesFunc() { - return AttachedPropertySelector::value >::func(); + return AttachedPropertySelector::value>::value>::func(); } template inline const QMetaObject *attachedPropertiesMetaObject() { - return AttachedPropertySelector::value >::metaObject(); + return AttachedPropertySelector::value>::value>::metaObject(); } struct MetaTypeIds { diff --git a/tests/auto/declarative/qmlparser/testtypes.h b/tests/auto/declarative/qmlparser/testtypes.h index e124631..ab67a4a 100644 --- a/tests/auto/declarative/qmlparser/testtypes.h +++ b/tests/auto/declarative/qmlparser/testtypes.h @@ -34,6 +34,20 @@ static QVariant myCustomVariantTypeConverter(const QString &data) return QVariant::fromValue(rv); } +class MyAttachedObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(int value READ value WRITE setValue) +public: + MyAttachedObject(QObject *parent) : QObject(parent), m_value(0) {} + + int value() const { return m_value; } + void setValue(int v) { m_value = v; } + +private: + int m_value; +}; + class MyQmlObject : public QObject, public MyInterface, public QmlParserStatus { Q_OBJECT @@ -66,10 +80,8 @@ public: MyInterface *interface() const { return m_interface; } void setInterface(MyInterface *iface) { m_interface = iface; } - static MyQmlObject *qmlAttachedProperties(QObject *other) { - MyQmlObject *rv = new MyQmlObject; - rv->setParent(other); - return rv; + static MyAttachedObject *qmlAttachedProperties(QObject *other) { + return new MyAttachedObject(other); } Q_CLASSINFO("DefaultMethod", "basicSlot()"); -- cgit v0.12 From a6b7a8a5fb49acc957599111be222769e6b34521 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 16 Jun 2009 13:10:45 +1000 Subject: Fix autotest crash --- src/declarative/qml/qmlvme.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index 58972ef..e65b206 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -94,9 +94,9 @@ struct ListInstance : list(l), type(t), qmlListInterface(0) {} */ ListInstance(QList *q, int t) - : type(t), qListInterface(q) {} + : type(t), qListInterface(q), qmlListInterface(0) {} ListInstance(QmlPrivate::ListInterface *q, int t) - : type(t), qmlListInterface(q) {} + : type(t), qListInterface(0), qmlListInterface(q) {} //QVariant list; int type; -- cgit v0.12 From c9fd96774ced98da4145259d132a2c305dd3e6a9 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 16 Jun 2009 13:21:33 +1000 Subject: Invalidate the cache if the script resets --- src/declarative/qml/qmlbasicscript.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/declarative/qml/qmlbasicscript.cpp b/src/declarative/qml/qmlbasicscript.cpp index dd6766e..a679532 100644 --- a/src/declarative/qml/qmlbasicscript.cpp +++ b/src/declarative/qml/qmlbasicscript.cpp @@ -828,7 +828,7 @@ QVariant QmlBasicScript::run(QmlContext *context, void *voidCache, CacheState *c if (instr.type == ScriptInstruction::Load) { - if (n.type == QmlBasicScriptNodeCache::Invalid) { + if (n.type == QmlBasicScriptNodeCache::Invalid || state == Reset) { context->engine()->d_func()->loadCache(n, QLatin1String(id), static_cast(context->d_ptr)); state = Incremental; } @@ -852,7 +852,7 @@ QVariant QmlBasicScript::run(QmlContext *context, void *voidCache, CacheState *c CacheState dummy; return run(context, voidCache, &dummy); } - } else if (n.type == QmlBasicScriptNodeCache::Invalid) { + } else if (n.type == QmlBasicScriptNodeCache::Invalid || state == Reset) { context->engine()->d_func()->fetchCache(n, QLatin1String(id), obj); guard(n); state = Incremental; -- cgit v0.12 From 1e5dd7d82d542527ca9e650f78a5e25b6a3ebc41 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 16 Jun 2009 14:32:04 +1000 Subject: Deferred properties mostly work. However, they still don't honour the presence of an id property. --- src/declarative/qml/qmlengine.cpp | 9 +++-- src/declarative/qml/qmlvme.cpp | 38 +++++++++++++++++----- src/declarative/qml/qmlvme_p.h | 4 ++- .../qmlbindengine/deferredProperties.txt | 5 +++ tests/auto/declarative/qmlbindengine/testtypes.cpp | 1 + tests/auto/declarative/qmlbindengine/testtypes.h | 25 ++++++++++++++ .../qmlbindengine/tst_qmlbindengine.cpp | 18 ++++++++++ 7 files changed, 88 insertions(+), 12 deletions(-) create mode 100644 tests/auto/declarative/qmlbindengine/deferredProperties.txt diff --git a/src/declarative/qml/qmlengine.cpp b/src/declarative/qml/qmlengine.cpp index a43b9b9..36b6424 100644 --- a/src/declarative/qml/qmlengine.cpp +++ b/src/declarative/qml/qmlengine.cpp @@ -71,7 +71,7 @@ #include #include "private/qmlmetaproperty_p.h" #include - +#include QT_BEGIN_NAMESPACE @@ -710,7 +710,12 @@ void qmlExecuteDeferred(QObject *object) { QmlInstanceDeclarativeData *data = QmlInstanceDeclarativeData::get(object); - if (data) { + if (data && data->deferredComponent) { + QmlVME vme; + vme.runDeferred(object); + + data->deferredComponent->release(); + data->deferredComponent = 0; } } diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index e65b206..ccf12b0 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -89,16 +89,11 @@ QmlVME::QmlVME() struct ListInstance { ListInstance() {} - /* - ListInstance(const QVariant &l, int t) - : list(l), type(t), qmlListInterface(0) {} - */ ListInstance(QList *q, int t) : type(t), qListInterface(q), qmlListInterface(0) {} ListInstance(QmlPrivate::ListInterface *q, int t) : type(t), qListInterface(0), qmlListInterface(q) {} - //QVariant list; int type; QList *qListInterface; QmlPrivate::ListInterface *qmlListInterface; @@ -106,6 +101,35 @@ struct ListInstance QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, int count) { + QStack stack; + + if (start == -1) start = 0; + if (count == -1) count = comp->bytecode.count(); + + return run(stack, ctxt, comp, start, count); +} + +void QmlVME::runDeferred(QObject *object) +{ + QmlInstanceDeclarativeData *data = QmlInstanceDeclarativeData::get(object); + + if (!data || !data->context || !data->deferredComponent) + return; + + QmlContext *ctxt = data->context; + ctxt->activate(); + QmlCompiledComponent *comp = data->deferredComponent; + int start = data->deferredIdx + 1; + int count = data->deferredComponent->bytecode.at(data->deferredIdx).defer.deferCount; + QStack stack; + stack.push(object); + + run(stack, ctxt, comp, start, count); + ctxt->deactivate(); +} + +QObject *QmlVME::run(QStack &stack, QmlContext *ctxt, QmlCompiledComponent *comp, int start, int count) +{ // XXX - All instances of QmlContext::activeContext() here should be // replaced with the use of ctxt. However, this cannot be done until // behaviours stop modifying the active context and expecting the @@ -126,7 +150,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in QmlEnginePrivate::SimpleList bindValues; QmlEnginePrivate::SimpleList parserStatus; - QStack stack; QStack qliststack; QStack pushedProperties; @@ -134,9 +157,6 @@ QObject *QmlVME::run(QmlContext *ctxt, QmlCompiledComponent *comp, int start, in vmeErrors.clear(); - if (start == -1) start = 0; - if (count == -1) count = comp->bytecode.count(); - for (int ii = start; !isError() && ii < (start + count); ++ii) { QmlInstruction &instr = comp->bytecode[ii]; diff --git a/src/declarative/qml/qmlvme_p.h b/src/declarative/qml/qmlvme_p.h index f2ed576..149c82c 100644 --- a/src/declarative/qml/qmlvme_p.h +++ b/src/declarative/qml/qmlvme_p.h @@ -58,12 +58,14 @@ class QmlVME public: QmlVME(); - QObject *run(QmlContext *, QmlCompiledComponent *, int start = -1, int end = -1); + QObject *run(QmlContext *, QmlCompiledComponent *, int start = -1, int count = -1); + void runDeferred(QObject *); bool isError() const; QList errors() const; private: + QObject *run(QStack &, QmlContext *, QmlCompiledComponent *, int start, int count); QList vmeErrors; }; diff --git a/tests/auto/declarative/qmlbindengine/deferredProperties.txt b/tests/auto/declarative/qmlbindengine/deferredProperties.txt new file mode 100644 index 0000000..41aa891 --- /dev/null +++ b/tests/auto/declarative/qmlbindengine/deferredProperties.txt @@ -0,0 +1,5 @@ +MyDeferredObject { + value: 10 + objectProperty: MyQmlObject {} + objectProperty2: MyQmlObject { id: blah } +} diff --git a/tests/auto/declarative/qmlbindengine/testtypes.cpp b/tests/auto/declarative/qmlbindengine/testtypes.cpp index 4bb0dc8..afac27b 100644 --- a/tests/auto/declarative/qmlbindengine/testtypes.cpp +++ b/tests/auto/declarative/qmlbindengine/testtypes.cpp @@ -1,4 +1,5 @@ #include "testtypes.h" QML_DEFINE_TYPE(MyQmlObject,MyQmlObject); +QML_DEFINE_TYPE(MyDeferredObject,MyDeferredObject); QML_DEFINE_TYPE(MyQmlContainer,MyQmlContainer); diff --git a/tests/auto/declarative/qmlbindengine/testtypes.h b/tests/auto/declarative/qmlbindengine/testtypes.h index 6a4bda6..1934fe0 100644 --- a/tests/auto/declarative/qmlbindengine/testtypes.h +++ b/tests/auto/declarative/qmlbindengine/testtypes.h @@ -122,6 +122,31 @@ public: int millipedeLegs() const { return 1000; } }; +class MyDeferredObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(int value READ value WRITE setValue) + Q_PROPERTY(QObject *objectProperty READ objectProperty WRITE setObjectProperty); + Q_PROPERTY(QObject *objectProperty2 READ objectProperty2 WRITE setObjectProperty2); + Q_CLASSINFO("DeferredPropertyNames", "value,objectProperty,objectProperty2"); + +public: + MyDeferredObject() : m_value(0), m_object(0), m_object2(0) {} + + int value() const { return m_value; } + void setValue(int v) { m_value = v; } + + QObject *objectProperty() const { return m_object; } + void setObjectProperty(QObject *obj) { m_object = obj; } + + QObject *objectProperty2() const { return m_object2; } + void setObjectProperty2(QObject *obj) { m_object2 = obj; } +private: + int m_value; + QObject *m_object; + QObject *m_object2; +}; +QML_DECLARE_TYPE(MyDeferredObject); #endif // TESTTYPES_H diff --git a/tests/auto/declarative/qmlbindengine/tst_qmlbindengine.cpp b/tests/auto/declarative/qmlbindengine/tst_qmlbindengine.cpp index a1efc5f..0ff66c4 100644 --- a/tests/auto/declarative/qmlbindengine/tst_qmlbindengine.cpp +++ b/tests/auto/declarative/qmlbindengine/tst_qmlbindengine.cpp @@ -36,6 +36,7 @@ private slots: void arrayExpressions(); void contextPropertiesTriggerReeval(); void objectPropertiesTriggerReeval(); + void deferredProperties(); private: QmlEngine engine; @@ -337,6 +338,23 @@ void tst_qmlbindengine::objectPropertiesTriggerReeval() } } +void tst_qmlbindengine::deferredProperties() +{ + QmlComponent component(&engine, TEST_FILE("deferredProperties.txt")); + MyDeferredObject *object = + qobject_cast(component.create()); + QVERIFY(object != 0); + QCOMPARE(object->value(), 0); + QVERIFY(object->objectProperty() == 0); + QVERIFY(object->objectProperty2() != 0); + qmlExecuteDeferred(object); + QCOMPARE(object->value(), 10); + QVERIFY(object->objectProperty() != 0); + MyQmlObject *qmlObject = + qobject_cast(object->objectProperty()); + QVERIFY(qmlObject != 0); +} + QTEST_MAIN(tst_qmlbindengine) #include "tst_qmlbindengine.moc" -- cgit v0.12 From 6bc2a137e2b9c508d86047576907956418d292aa Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 16 Jun 2009 15:02:51 +1000 Subject: Forward signals from extended objects This is necessary so that notify signals on properties defined in an extension object operate correctly. --- src/declarative/qml/qmlmetatype.cpp | 5 ++++- src/declarative/qml/qmlproxymetaobject.cpp | 28 ++++++++++++++++++++++++++-- src/declarative/qml/qmlproxymetaobject_p.h | 1 + 3 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/declarative/qml/qmlmetatype.cpp b/src/declarative/qml/qmlmetatype.cpp index 3e25ae0..8ce8571 100644 --- a/src/declarative/qml/qmlmetatype.cpp +++ b/src/declarative/qml/qmlmetatype.cpp @@ -214,9 +214,12 @@ void QmlTypePrivate::init() const mo = mo->d.superdata; } - for (int ii = 0; ii < m_metaObjects.count(); ++ii) + for (int ii = 0; ii < m_metaObjects.count(); ++ii) { m_metaObjects[ii].propertyOffset = m_metaObjects.at(ii).metaObject->propertyOffset(); + m_metaObjects[ii].methodOffset = + m_metaObjects.at(ii).metaObject->methodOffset(); + } // Calculate hash QByteArray hashData; diff --git a/src/declarative/qml/qmlproxymetaobject.cpp b/src/declarative/qml/qmlproxymetaobject.cpp index 686c6d7..06d8a50 100644 --- a/src/declarative/qml/qmlproxymetaobject.cpp +++ b/src/declarative/qml/qmlproxymetaobject.cpp @@ -78,6 +78,7 @@ QmlProxyMetaObject::~QmlProxyMetaObject() proxies = 0; } +#include int QmlProxyMetaObject::metaCall(QMetaObject::Call c, int id, void **a) { if ((c == QMetaObject::ReadProperty || @@ -93,8 +94,24 @@ int QmlProxyMetaObject::metaCall(QMetaObject::Call c, int id, void **a) sizeof(QObject *) * metaObjects->count()); } - if (!proxies[ii]) - proxies[ii] = data.createFunc(object); + if (!proxies[ii]) { + QObject *proxy = data.createFunc(object); + const QMetaObject *metaObject = proxy->metaObject(); + proxies[ii] = proxy; + + int localOffset = data.metaObject->methodOffset(); + int methodOffset = metaObject->methodOffset(); + int methods = metaObject->methodCount() - methodOffset; + + // ### - Can this be done more optimally? + for (int jj = 0; jj < methods; ++jj) { + QMetaMethod method = + metaObject->method(jj + methodOffset); + if (method.methodType() == QMetaMethod::Signal) + QMetaObject::connect(proxy, methodOffset + jj, + object, localOffset + jj); + } + } int proxyOffset = proxies[ii]->metaObject()->propertyOffset(); int proxyId = id - data.propertyOffset + proxyOffset; @@ -102,6 +119,13 @@ int QmlProxyMetaObject::metaCall(QMetaObject::Call c, int id, void **a) return proxies[ii]->qt_metacall(c, proxyId, a); } } + } else if (c == QMetaObject::InvokeMetaMethod && + id >= metaObjects->last().methodOffset) { + QMetaMethod m = object->metaObject()->method(id); + if (m.methodType() == QMetaMethod::Signal) { + QMetaObject::activate(object, id, a); + return -1; + } } if (parent) diff --git a/src/declarative/qml/qmlproxymetaobject_p.h b/src/declarative/qml/qmlproxymetaobject_p.h index 0ffa365..c0ce36e 100644 --- a/src/declarative/qml/qmlproxymetaobject_p.h +++ b/src/declarative/qml/qmlproxymetaobject_p.h @@ -61,6 +61,7 @@ public: QMetaObject *metaObject; CreateFunc createFunc; int propertyOffset; + int methodOffset; }; QmlProxyMetaObject(QObject *, QList *); -- cgit v0.12 From 27f14fcbf4eeec1b5f2255e1a0ebc74a221964a1 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 16 Jun 2009 15:26:08 +1000 Subject: Autotest for extension objects --- .../declarative/qmlbindengine/extensionObjects.txt | 8 +++++ tests/auto/declarative/qmlbindengine/testtypes.cpp | 36 ++++++++++++++++++++++ tests/auto/declarative/qmlbindengine/testtypes.h | 30 ++++++++++++++++++ .../qmlbindengine/tst_qmlbindengine.cpp | 16 ++++++++++ 4 files changed, 90 insertions(+) create mode 100644 tests/auto/declarative/qmlbindengine/extensionObjects.txt diff --git a/tests/auto/declarative/qmlbindengine/extensionObjects.txt b/tests/auto/declarative/qmlbindengine/extensionObjects.txt new file mode 100644 index 0000000..4c33de4 --- /dev/null +++ b/tests/auto/declarative/qmlbindengine/extensionObjects.txt @@ -0,0 +1,8 @@ +MyExtendedObject +{ + baseProperty: baseExtendedProperty + baseExtendedProperty: 13 + + coreProperty: extendedProperty + extendedProperty: 9 +} diff --git a/tests/auto/declarative/qmlbindengine/testtypes.cpp b/tests/auto/declarative/qmlbindengine/testtypes.cpp index afac27b..2f83f58 100644 --- a/tests/auto/declarative/qmlbindengine/testtypes.cpp +++ b/tests/auto/declarative/qmlbindengine/testtypes.cpp @@ -1,5 +1,41 @@ #include "testtypes.h" +class BaseExtensionObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(int baseExtendedProperty READ extendedProperty WRITE setExtendedProperty NOTIFY extendedPropertyChanged); +public: + BaseExtensionObject(QObject *parent) : QObject(parent), m_value(0) {} + + int extendedProperty() const { return m_value; } + void setExtendedProperty(int v) { m_value = v; emit extendedPropertyChanged(); } + +signals: + void extendedPropertyChanged(); +private: + int m_value; +}; + +class ExtensionObject : public QObject +{ + Q_OBJECT + Q_PROPERTY(int extendedProperty READ extendedProperty WRITE setExtendedProperty NOTIFY extendedPropertyChanged); +public: + ExtensionObject(QObject *parent) : QObject(parent), m_value(0) {} + + int extendedProperty() const { return m_value; } + void setExtendedProperty(int v) { m_value = v; emit extendedPropertyChanged(); } + +signals: + void extendedPropertyChanged(); +private: + int m_value; +}; + QML_DEFINE_TYPE(MyQmlObject,MyQmlObject); QML_DEFINE_TYPE(MyDeferredObject,MyDeferredObject); QML_DEFINE_TYPE(MyQmlContainer,MyQmlContainer); +QML_DEFINE_EXTENDED_TYPE(MyBaseExtendedObject,MyBaseExtendedObject,BaseExtensionObject); +QML_DEFINE_EXTENDED_TYPE(MyExtendedObject,MyExtendedObject,ExtensionObject); + +#include "testtypes.moc" diff --git a/tests/auto/declarative/qmlbindengine/testtypes.h b/tests/auto/declarative/qmlbindengine/testtypes.h index 1934fe0..df31f7a 100644 --- a/tests/auto/declarative/qmlbindengine/testtypes.h +++ b/tests/auto/declarative/qmlbindengine/testtypes.h @@ -148,5 +148,35 @@ private: }; QML_DECLARE_TYPE(MyDeferredObject); +class MyBaseExtendedObject : public QObject +{ +Q_OBJECT +Q_PROPERTY(int baseProperty READ baseProperty WRITE setBaseProperty); +public: + MyBaseExtendedObject() : m_value(0) {} + + int baseProperty() const { return m_value; } + void setBaseProperty(int v) { m_value = v; } + +private: + int m_value; +}; +QML_DECLARE_TYPE(MyBaseExtendedObject); + +class MyExtendedObject : public MyBaseExtendedObject +{ +Q_OBJECT +Q_PROPERTY(int coreProperty READ coreProperty WRITE setCoreProperty); +public: + MyExtendedObject() : m_value(0) {} + + int coreProperty() const { return m_value; } + void setCoreProperty(int v) { m_value = v; } + +private: + int m_value; +}; +QML_DECLARE_TYPE(MyExtendedObject); + #endif // TESTTYPES_H diff --git a/tests/auto/declarative/qmlbindengine/tst_qmlbindengine.cpp b/tests/auto/declarative/qmlbindengine/tst_qmlbindengine.cpp index 0ff66c4..8d3c0b4 100644 --- a/tests/auto/declarative/qmlbindengine/tst_qmlbindengine.cpp +++ b/tests/auto/declarative/qmlbindengine/tst_qmlbindengine.cpp @@ -37,6 +37,7 @@ private slots: void contextPropertiesTriggerReeval(); void objectPropertiesTriggerReeval(); void deferredProperties(); + void extensionObjects(); private: QmlEngine engine; @@ -355,6 +356,21 @@ void tst_qmlbindengine::deferredProperties() QVERIFY(qmlObject != 0); } +void tst_qmlbindengine::extensionObjects() +{ + QmlComponent component(&engine, TEST_FILE("extensionObjects.txt")); + MyExtendedObject *object = + qobject_cast(component.create()); + QVERIFY(object != 0); + QCOMPARE(object->baseProperty(), 13); + QCOMPARE(object->coreProperty(), 9); + + object->setProperty("extendedProperty", QVariant(11)); + object->setProperty("baseExtendedProperty", QVariant(92)); + QCOMPARE(object->coreProperty(), 11); + QCOMPARE(object->baseProperty(), 92); +} + QTEST_MAIN(tst_qmlbindengine) #include "tst_qmlbindengine.moc" -- cgit v0.12 From 2f3aca28242fb4849f62b7391460ba66361f29d7 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 16 Jun 2009 15:47:42 +1000 Subject: Use system configuration for proxy settings --- tools/qmlviewer/qmlviewer.cpp | 18 ++++++++++++++++++ tools/qmlviewer/qmlviewer.h | 2 ++ 2 files changed, 20 insertions(+) diff --git a/tools/qmlviewer/qmlviewer.cpp b/tools/qmlviewer/qmlviewer.cpp index 75a8f1c..af543c9 100644 --- a/tools/qmlviewer/qmlviewer.cpp +++ b/tools/qmlviewer/qmlviewer.cpp @@ -39,6 +39,7 @@ #include #include #include +#include class PreviewDeviceSkin : public DeviceSkin { @@ -153,6 +154,8 @@ QmlViewer::QmlViewer(QFxTestEngine::TestMode testMode, const QString &testDir, Q if (mb) layout->addWidget(mb); layout->addWidget(canvas); + + setupProxy(); } QMenuBar *QmlViewer::menuBar() const @@ -677,6 +680,21 @@ void QmlViewer::setDeviceKeys(bool on) devicemode = on; } +void QmlViewer::setupProxy() +{ + class SystemProxyFactory : public QNetworkProxyFactory + { + public: + virtual QList queryProxy(const QNetworkProxyQuery &query) + { + return QNetworkProxyFactory::systemProxyForQuery(query); + } + }; + + QNetworkAccessManager * nam = canvas->engine()->networkAccessManager(); + nam->setProxyFactory(new SystemProxyFactory); +} + void QmlViewer::setCacheEnabled(bool on) { QNetworkAccessManager * nam = canvas->engine()->networkAccessManager(); diff --git a/tools/qmlviewer/qmlviewer.h b/tools/qmlviewer/qmlviewer.h index 45ec446..9de47a8 100644 --- a/tools/qmlviewer/qmlviewer.h +++ b/tools/qmlviewer/qmlviewer.h @@ -68,6 +68,8 @@ private slots: void setScaleView(); private: + void setupProxy(); + QString currentFileName; PreviewDeviceSkin *skin; QSize skinscreensize; -- cgit v0.12 From dc7d82434debd9b660dbdd963f88071a41b21897 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Tue, 16 Jun 2009 16:08:36 +1000 Subject: Make the default rect color white --- src/declarative/fx/qfxrect.cpp | 2 ++ src/declarative/fx/qfxrect_p.h | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/declarative/fx/qfxrect.cpp b/src/declarative/fx/qfxrect.cpp index f55357f..fd8d9ca 100644 --- a/src/declarative/fx/qfxrect.cpp +++ b/src/declarative/fx/qfxrect.cpp @@ -391,6 +391,8 @@ void QFxRect::dump(int depth) // steelblue rect using SVG color name Rect { color: "steelblue" } \endqml + + The default color is white. */ /*! diff --git a/src/declarative/fx/qfxrect_p.h b/src/declarative/fx/qfxrect_p.h index f662fac..23bb944 100644 --- a/src/declarative/fx/qfxrect_p.h +++ b/src/declarative/fx/qfxrect_p.h @@ -72,7 +72,7 @@ public: #if defined(QFX_RENDER_OPENGL) rectTexture(0), #endif //QFX_RENDER_OPENGL - gradient(0), pen(0), radius(0) + color(Qt::white), gradient(0), pen(0), radius(0) { } -- cgit v0.12 From 7e6f67dd9a177c56fdf190b9657294d73776863f Mon Sep 17 00:00:00 2001 From: Erik Verbruggen Date: Tue, 16 Jun 2009 15:39:01 +0200 Subject: Fixed range calculation for UiQualifiedId in the visitor for UiScriptBinding. --- src/declarative/qml/qmlscriptparser.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/declarative/qml/qmlscriptparser.cpp b/src/declarative/qml/qmlscriptparser.cpp index 6c2e3e0..fb7492d 100644 --- a/src/declarative/qml/qmlscriptparser.cpp +++ b/src/declarative/qml/qmlscriptparser.cpp @@ -628,6 +628,8 @@ bool ProcessAST::visit(AST::UiScriptBinding *node) node->statement); } + prop->location.range.length = prop->location.range.offset + prop->location.range.length - node->qualifiedId->identifierToken.offset; + prop->location.range.offset = node->qualifiedId->identifierToken.offset; Value *v = new Value; v->value = primitive; v->location = location(node->statement->firstSourceLocation(), -- cgit v0.12 From 59629ac728f2fdbc3047554d715e2f908b1844c4 Mon Sep 17 00:00:00 2001 From: Thomas Hartmann Date: Tue, 16 Jun 2009 15:43:46 +0200 Subject: Fixing qml for QWidget support (crash) QWidget deletes its children in its own constructor so we have to cleanup before explicitly Reviewed-by: Aaron Kennedy --- src/gui/kernel/qwidget.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/gui/kernel/qwidget.cpp b/src/gui/kernel/qwidget.cpp index d5fdd93..74703bf 100644 --- a/src/gui/kernel/qwidget.cpp +++ b/src/gui/kernel/qwidget.cpp @@ -1372,6 +1372,12 @@ QWidget::~QWidget() // set all QPointers for this object to zero QObjectPrivate::clearGuards(this); + if(d->declarativeData) { + QDeclarativeData *dd = d->declarativeData; + d->declarativeData = 0; + dd->destroyed(this); + } + if (!d->children.isEmpty()) d->deleteChildren(); -- cgit v0.12 From 6f4779a7ac3dcfca23124f20bba6ab650e4a8a04 Mon Sep 17 00:00:00 2001 From: Thomas Hartmann Date: Tue, 16 Jun 2009 15:45:33 +0200 Subject: Fixing QWidget support Reviewed-by: Kai Koehne --- src/declarative/qml/qmlvme.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index ccf12b0..be09190 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -193,7 +193,17 @@ QObject *QmlVME::run(QStack &stack, QmlContext *ctxt, QmlCompiledComp } if (!stack.isEmpty()) { QObject *parent = stack.top(); - o->setParent(parent); + if (o->isWidgetType()) { + QWidget *widget = static_cast(o); + if (parent->isWidgetType()) { + QWidget *parentWidget = static_cast(parent); + widget->setParent(parentWidget); + } else { + // TODO: parent might be a layout + } + } else { + o->setParent(parent); + } } stack.push(o); } -- cgit v0.12 From 146171c3a393b18a0345d36461c2f276d39b980f Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 17 Jun 2009 10:45:11 +1000 Subject: Respect string converters in binding assignments --- src/declarative/qml/qmlbindablevalue.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/declarative/qml/qmlbindablevalue.cpp b/src/declarative/qml/qmlbindablevalue.cpp index f2cfcf8..d1835cf 100644 --- a/src/declarative/qml/qmlbindablevalue.cpp +++ b/src/declarative/qml/qmlbindablevalue.cpp @@ -134,6 +134,13 @@ void QmlBindableValue::update() } else { QVariant value = this->value(); + if ((uint)d->property.propertyType() >= QVariant::UserType && + value.type() == QVariant::String) { + QmlMetaType::StringConverter con = QmlMetaType::customStringConverter(d->property.propertyType()); + if (con) + value = con(value.toString()); + } + if (d->property.propertyType() == QVariant::Url && value.canConvert(QVariant::String) && !value.isNull()) value.setValue(context()->resolvedUrl(QUrl(value.toString()))); -- cgit v0.12 From 4b29e52cad8d719d382110349e29c127db45036a Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 17 Jun 2009 15:00:46 +1000 Subject: VC2008 Compile --- src/declarative/qml/qmlprivate.h | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/declarative/qml/qmlprivate.h b/src/declarative/qml/qmlprivate.h index 21a1164..ed1304a 100644 --- a/src/declarative/qml/qmlprivate.h +++ b/src/declarative/qml/qmlprivate.h @@ -123,6 +123,19 @@ namespace QmlPrivate } }; +#if defined(Q_CC_MSVC) + template + class has_attachedPropertiesMember + { + public: + __if_exists(T::qmlAttachedProperties) { + static bool const value = true; + } + __if_not_exists(T::qmlAttachedProperties) { + static bool const value = false; + } + }; +#else template class has_attachedPropertiesMember { @@ -140,6 +153,7 @@ namespace QmlPrivate public: static bool const value = sizeof(test(0)) == sizeof(yes_type); }; +#endif template class has_attachedPropertiesMethod -- cgit v0.12 From 00d6d725ed0c3eb7d2bc0d0187e66c0ee55ef4a7 Mon Sep 17 00:00:00 2001 From: Aaron Kennedy Date: Wed, 17 Jun 2009 15:44:46 +1000 Subject: Don't defer properties if an id has been set --- src/declarative/qml/qmlcompiler.cpp | 12 ++++++++---- src/declarative/qml/qmlvme.cpp | 16 +++++++++------- 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/src/declarative/qml/qmlcompiler.cpp b/src/declarative/qml/qmlcompiler.cpp index 5b81721..8297ac4 100644 --- a/src/declarative/qml/qmlcompiler.cpp +++ b/src/declarative/qml/qmlcompiler.cpp @@ -687,20 +687,24 @@ bool QmlCompiler::compileObject(Object *obj, const BindingContext &ctxt) output->indexForByteArray(customData); } - // Build the deferred block (### Need to check for presence of "id") + // Build the deferred block if (!deferredProps.isEmpty()) { QmlInstruction defer; defer.type = QmlInstruction::Defer; defer.line = 0; + defer.defer.deferCount = 0; int deferIdx = output->bytecode.count(); output->bytecode << defer; + // ### This is lame, we should check if individual properties have + // ids defined within them + int idCount = compileState.ids.count(); foreach (Property *prop, deferredProps) { COMPILE_CHECK(compileProperty(prop, obj, objCtxt)); } - - output->bytecode[deferIdx].defer.deferCount = - output->bytecode.count() - deferIdx - 1; + if (idCount == compileState.ids.count()) + output->bytecode[deferIdx].defer.deferCount = + output->bytecode.count() - deferIdx - 1; } // If the type support the QmlParserStatusInterface we need to invoke diff --git a/src/declarative/qml/qmlvme.cpp b/src/declarative/qml/qmlvme.cpp index be09190..a3ee4e5 100644 --- a/src/declarative/qml/qmlvme.cpp +++ b/src/declarative/qml/qmlvme.cpp @@ -778,13 +778,15 @@ QObject *QmlVME::run(QStack &stack, QmlContext *ctxt, QmlCompiledComp case QmlInstruction::Defer: { - QObject *target = stack.top(); - QmlInstanceDeclarativeData *data = - QmlInstanceDeclarativeData::get(target, true); - comp->addref(); - data->deferredComponent = comp; - data->deferredIdx = ii; - ii += instr.defer.deferCount; + if (instr.defer.deferCount) { + QObject *target = stack.top(); + QmlInstanceDeclarativeData *data = + QmlInstanceDeclarativeData::get(target, true); + comp->addref(); + data->deferredComponent = comp; + data->deferredIdx = ii; + ii += instr.defer.deferCount; + } } break; -- cgit v0.12
    • + Getting Started + General + Developer Resources
      + API Reference + Core Features + Key Technologies
      + Add-ons & Services + Tools + Licenses & Credits